@makaio/framework 1.0.0-dev-1783940945655 → 1.0.0-dev-1783975608971

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 (142) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/{account-identity-BYfeWLe-.mjs → account-identity-CP4DC0DL.mjs} +1 -1
  3. package/dist/{adapter-nl_xz9dz.mjs → adapter-B9vVBwli.mjs} +1 -1
  4. package/dist/adapter-subsystem/index.d.mts +10 -0
  5. package/dist/adapter-subsystem/index.mjs +1 -1
  6. package/dist/adapters/node.mjs +1 -1
  7. package/dist/authority-state-bootstrap-CEuKScnL.mjs +1 -0
  8. package/dist/bus/index.d.mts +31 -31
  9. package/dist/bus/index.mjs +1 -1
  10. package/dist/{canonical-model-CVRCW9h7.mjs → canonical-model-C31NaBJs.mjs} +1 -1
  11. package/dist/{client-BkpLM8Fx.mjs → client-CzPCSeyE.mjs} +1 -1
  12. package/dist/clients/index.d.mts +5 -5
  13. package/dist/contracts/adapter/index.d.mts +1 -1
  14. package/dist/contracts/adapter/index.mjs +1 -1
  15. package/dist/contracts/canonical-model/index.d.mts +1 -1
  16. package/dist/contracts/canonical-model/index.mjs +1 -1
  17. package/dist/contracts/client/index.d.mts +1 -1
  18. package/dist/contracts/client/index.mjs +1 -1
  19. package/dist/contracts/extension/index.d.mts +2 -2
  20. package/dist/contracts/extension/index.mjs +1 -1
  21. package/dist/contracts/facet/index.d.mts +1 -1
  22. package/dist/contracts/harness/index.d.mts +1 -1
  23. package/dist/contracts/index.d.mts +221 -153
  24. package/dist/contracts/index.mjs +1 -1
  25. package/dist/contracts/materialization/index.d.mts +1 -1
  26. package/dist/contracts/native-session-supervisor/index.d.mts +2 -2
  27. package/dist/contracts/native-session-supervisor/index.mjs +1 -1
  28. package/dist/contracts/session/index.d.mts +3 -3
  29. package/dist/contracts/session/index.mjs +1 -1
  30. package/dist/contracts/shared/index.d.mts +1 -1
  31. package/dist/contracts/variant/index.d.mts +1 -1
  32. package/dist/contracts/workflow/index.d.mts +3 -3
  33. package/dist/contracts/workflow/index.mjs +1 -1
  34. package/dist/{detached-extension-handle-CTaQoolf.mjs → detached-extension-handle-vDK194QV.mjs} +1 -1
  35. package/dist/drizzle/0026_m_mrgvi7fq.sql +16 -0
  36. package/dist/drizzle/0027_m_mrgw0uzg.sql +1 -0
  37. package/dist/drizzle/0028_m_mrgx04i1.sql +1 -0
  38. package/dist/drizzle/0029_terminal-authority.sql +1 -0
  39. package/dist/drizzle/meta/_journal.json +28 -0
  40. package/dist/{extension-D4iKUUMG.mjs → extension-Cgg45Xk1.mjs} +1 -1
  41. package/dist/git/index.mjs +8 -8
  42. package/dist/{index-D5IEq4_E.d.mts → index-BH145jWk.d.mts} +9 -7
  43. package/dist/{index-BcejR1Jc.d.mts → index-BORQLrT7.d.mts} +1 -1
  44. package/dist/{index-CB2XTzvd.d.mts → index-Bbr5LEUc.d.mts} +1 -1
  45. package/dist/{index-5s_dN3cg2.d.mts → index-BmsPH78f2.d.mts} +33 -5
  46. package/dist/{index-BtL7ONuM.d.mts → index-C6LZOiDv.d.mts} +149 -1
  47. package/dist/{index-DlUPWOh4.d.mts → index-CCX4veeR.d.mts} +2859 -692
  48. package/dist/{index-DxatNFz7.d.mts → index-CMTNBuo6.d.mts} +16 -16
  49. package/dist/{index-CVs0Qxks.d.mts → index-CSxfU0tB.d.mts} +4 -4
  50. package/dist/{index-Cw3cjGAT.d.mts → index-ChSwb11f.d.mts} +7 -7
  51. package/dist/{index-Lp0T_V1W.d.mts → index-CidZvQ-c.d.mts} +3 -3
  52. package/dist/{index-p6dWV52m.d.mts → index-Cq6rXKae.d.mts} +379 -379
  53. package/dist/{index-DNc1yLQs.d.mts → index-DHGW7dFf.d.mts} +8 -8
  54. package/dist/{index-C9Q1E8Y-.d.mts → index-DMQlLz2W.d.mts} +34 -34
  55. package/dist/{index-iJP-l15K.d.mts → index-DXBiCH2y.d.mts} +27 -1
  56. package/dist/{index-CW6-0k3Z.d.mts → index-DlAfs3RD.d.mts} +105 -105
  57. package/dist/{index-sCOlgPyj.d.mts → index-DpZbaS7y.d.mts} +388 -388
  58. package/dist/{index-Do7Wgio_2.d.mts → index-MTvmxwiu2.d.mts} +1 -1
  59. package/dist/{index-BsEvzFey.d.mts → index-kqxUXYe7.d.mts} +6 -6
  60. package/dist/kernel/extension/index.d.mts +1 -1
  61. package/dist/kernel/index.d.mts +2 -2
  62. package/dist/kernel/observability/index.d.mts +1 -1
  63. package/dist/{lib-DymjnkAP.mjs → lib-DktBDEoY.mjs} +1 -1
  64. package/dist/{load-extensions-BtUrq2_t.mjs → load-extensions-nqL5WAKj.mjs} +1 -1
  65. package/dist/mcp-http-server/index.d.mts +27 -90
  66. package/dist/mcp-http-server/index.mjs +1 -1
  67. package/dist/{namespace-CfgtqUWS.d.mts → namespace-BoA6u44C.d.mts} +156 -156
  68. package/dist/{namespace-D3SQQgxa2.d.mts → namespace-CukqFYHf2.d.mts} +1 -1
  69. package/dist/{namespace-CQBSXm1U.d.mts → namespace-TLkZRkcU.d.mts} +20 -20
  70. package/dist/{namespace-CpyL93kW.d.mts → namespace-dgNmx9g3.d.mts} +27 -27
  71. package/dist/{namespace-CGgOLxiW2.d.mts → namespace-rO-C2Dgu2.d.mts} +2 -2
  72. package/dist/{native-session-supervisor-CdtVGWA9.mjs → native-session-supervisor-Bgz-Q1WH.mjs} +1 -1
  73. package/dist/package-BYpWkSuQ.mjs +1 -0
  74. package/dist/package-CsFFT9iR.mjs +7 -0
  75. package/dist/{package-CdBiknf3.d.mts → package-DG9GSY8M.d.mts} +52 -1
  76. package/dist/package.json +1 -1
  77. package/dist/{profile-D2m94ZYD.mjs → profile-BRi6K6am.mjs} +1 -1
  78. package/dist/rules/index.mjs +1 -1
  79. package/dist/runtime-node/extension-validation.mjs +1 -1
  80. package/dist/runtime-node/index.d.mts +4 -89
  81. package/dist/runtime-node/index.mjs +24 -24
  82. package/dist/runtime-node/makaio-config.mjs +1 -1
  83. package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
  84. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  85. package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
  86. package/dist/{schema-BnTOFCdU.d.mts → schema-CxN7d_MU.d.mts} +1 -1
  87. package/dist/{schemas--uwN5dfK2.d.mts → schemas-CIO03KSD2.d.mts} +11 -11
  88. package/dist/{schemas-n9Ff6_RX.mjs → schemas-DyJHJ8Pm.mjs} +1 -1
  89. package/dist/{schemas-C17AifUQ.d.mts → schemas-OaBqeEUT.d.mts} +156 -156
  90. package/dist/schemas-th_nuC5t.mjs +1 -0
  91. package/dist/semver-D3Y7uMEb.mjs +1 -0
  92. package/dist/service-base/index.d.mts +4 -3
  93. package/dist/service-base/index.mjs +1 -1
  94. package/dist/services/agent-runtime/index.d.mts +2 -2
  95. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  96. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  97. package/dist/services/execution-target/index.d.mts +1 -1
  98. package/dist/services/filesystem/namespace.d.mts +6 -6
  99. package/dist/services/filesystem/schemas.d.mts +3 -3
  100. package/dist/services/harness/index.d.mts +3 -3
  101. package/dist/services/index.d.mts +100 -100
  102. package/dist/services/index.mjs +1 -1
  103. package/dist/services/session/index.d.mts +5 -5
  104. package/dist/services/session/messages/namespace.d.mts +1 -1
  105. package/dist/services/session/session-events/namespace.d.mts +1 -1
  106. package/dist/services/session/storage/namespace.d.mts +1 -1
  107. package/dist/services/session/storage/schema.d.mts +1 -1
  108. package/dist/services/settings/namespace.d.mts +8 -8
  109. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  110. package/dist/services/subagent/index.d.mts +2 -2
  111. package/dist/services/subagent/index.mjs +1 -1
  112. package/dist/services/subagent-template/index.d.mts +2 -2
  113. package/dist/services/subagent-template/namespace.d.mts +1 -1
  114. package/dist/services/subagent-template/schemas.d.mts +1 -1
  115. package/dist/services/tools/index.mjs +1 -1
  116. package/dist/{session-lRd8HZNZ.mjs → session-BxWogVkD.mjs} +1 -1
  117. package/dist/storage/drizzle/index.d.mts +8 -1
  118. package/dist/storage/drizzle/index.mjs +1 -1
  119. package/dist/tools/index.d.mts +1 -1
  120. package/dist/{tools-C8vqn1KY.mjs → tools-PC_L6g2m.mjs} +1 -1
  121. package/dist/{transition-Bfe8VVc1.d.mts → transition-CwUIm1hJ.d.mts} +8 -0
  122. package/dist/{types-q95p55BF.d.mts → types-DQsYUZwa.d.mts} +578 -267
  123. package/dist/ui-components/index.d.mts +4 -4
  124. package/dist/{version-C1-VD-XL.mjs → version-BbWrAPld.mjs} +1 -1
  125. package/dist/workflow-DFJYGjq_.mjs +1 -0
  126. package/dist/workflow-engine/index.d.mts +670 -67
  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/dist/workflow-worker-BEFjCccX.mjs +1 -0
  132. package/package.json +10 -9
  133. package/dist/loop-gate-handlers-0a3dIY8O.mjs +0 -1
  134. package/dist/package-0gVhAVkO.mjs +0 -7
  135. package/dist/package-BwvGaKwn.mjs +0 -1
  136. package/dist/schemas-D6lj9NMg.mjs +0 -1
  137. package/dist/semver-BccS1s9R.mjs +0 -1
  138. package/dist/workflow-CvVAZ89A.mjs +0 -1
  139. package/dist/workflow-worker-CudfEstp.mjs +0 -1
  140. /package/dist/{await-trigger-D623tvig.mjs → await-trigger-DP-fTQc4.mjs} +0 -0
  141. /package/dist/{descriptor-to-package-D5SWf6TL.mjs → descriptor-to-package-Rs-OjOQU.mjs} +0 -0
  142. /package/dist/{esm-oHhRYTEn.mjs → esm-C_WW4-pP.mjs} +0 -0
@@ -1,7 +0,0 @@
1
- import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as ee,P as te,R as ne,S as re,T as ie,U as ae,V as oe,W as se,X as ce,Y as le,Z as m,_ as ue,a as de,b as fe,c as pe,d as me,f as he,g as ge,h as _e,j as ve,k as ye,l as be,m as h,n as xe,o as Se,p as Ce,q as we,r as Te,t as Ee,u as De,w as Oe,x as ke,y as Ae,z as je}from"./loop-gate-handlers-0a3dIY8O.mjs";import{matchesFilter as Me,matchesSubscription as Ne}from"@makaio/framework/bus";import{ArtifactSubjects as Pe,EXECUTION_LIST_DEFAULT_LIMIT as Fe,EXECUTION_LIST_MAX_LIMIT as g,EXECUTION_LIST_MIN_LIMIT as _,EXTERNAL_EXECUTION_ID_PREFIX as v,ExecutionHintsSchema as Ie,ExecutionsByArtifactRefsQuerySchema as Le,JsonPatchOperationSchema as Re,JsonValueSchema as ze,SessionSubjects as Be,WORKFLOW_CANCELLED_REASON as y,WorkLogFrameEntrySchema as Ve,WorkflowError as b,WorkflowErrorCode as He,WorkflowNamespace as Ue,WorkflowStepTypeSchema as We,WorkflowSubjects as x,createWorkflowCancelSubject as Ge,dep as Ke,extensionToken as qe,serializeArtifactRef as Je}from"@makaio/framework/contracts";import{BaseService as Ye}from"@makaio/framework/service-base";import{defineDialectSchema as Xe,executeTransaction as S,getDatabaseDialect as Ze,registerDrizzleHandlers as Qe,resolveSchema as C}from"@makaio/framework/storage/drizzle";import{and as w,asc as T,count as E,desc as D,eq as O,getTableColumns as $e,gte as et,isNotNull as tt,isNull as k,lt as nt,lte as rt,notInArray as it,or as at,sql as A,sum as j}from"drizzle-orm";import{compile as ot}from"@makaio/framework/expression";import*as st from"node:os";import{SessionToken as ct}from"@makaio/framework/services";const lt=ie.postgres,ut=a.postgres,dt=r.postgres,ft=d.postgres,pt=oe.postgres,mt=ye.postgres,ht=je.postgres,gt=le.postgres,_t=o.postgres,vt=ae.postgres,yt=we.postgres,bt=ve.postgres,xt=p.postgres,M=Xe({workflowDefinitions:Oe,workflowExecutions:te,workflowExecutionFrames:i,workflowGateInstances:c,workflowStepSpans:t,workflowExecutionLinks:ee,workflowRunContexts:ne,worklogSummaries:l,worklogFrameEntries:se,worklogArtifactWrites:s,worklogGateEvents:u,workflowExecutionState:e,workflowExecutionStateEvents:f},{workflowDefinitions:lt,workflowExecutions:ut,workflowExecutionFrames:dt,workflowGateInstances:ft,workflowStepSpans:pt,workflowExecutionLinks:mt,workflowRunContexts:ht,worklogSummaries:gt,worklogFrameEntries:_t,worklogArtifactWrites:vt,worklogGateEvents:yt,workflowExecutionState:bt,workflowExecutionStateEvents:xt});function N(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 St(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 Ct(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=N(t);return[O(e.scopeType,n),O(e.scopeKind,r),O(e.scopeId,i)]}function P(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:St(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function wt(e,t){let n=N(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Tt(e,t){let{workflowDefinitions:r}=C(t,M),i=$e(r),a=e.on(n.get,async e=>{let n=await t.select().from(r).where(O(r.id,e.payload.id)).limit(1);e.setResult({workflow:n[0]?P(n[0]):null})}),o=e.on(n.set,async n=>{let a=n.payload.workflow,o=Date.now(),s=wt(a,o),c=await t.insert(r).values(s).onConflictDoNothing({target:r.id}).returning();if(c.length>0){await e.emit(m.definition.created,P(c[0])),n.setResult({id:a.id});return}let[l]=await t.update(r).set({name:s.name,root:s.root,updatedAt:o,createdAt:A`COALESCE(${i.createdAt}, ${o})`,description:s.description===null?A`${i.description}`:s.description,inputSchema:s.inputSchema===null?A`${i.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?A`${i.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?A`${i.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?A`${i.artifact}`:s.artifact,triggers:s.triggers===null?A`${i.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?A`${i.canvasLayout}`:s.canvasLayout,source:s.source===null?A`${i.source}`:s.source,executionHints:s.executionHints===null?A`${i.executionHints}`:s.executionHints,...N(a.scope)}).where(O(r.id,a.id)).returning();l&&await e.emit(m.definition.updated,P(l)),n.setResult({id:a.id})}),s=e.on(n.delete,async n=>{let i=(await t.delete(r).where(O(r.id,n.payload.id)).returning()).length>0;i&&await e.emit(m.definition.deleted,{id:n.payload.id}),n.setResult({deleted:i})}),c=e.on(n.list,async e=>{let n=e.payload,i=n.scope?Ct(r,n.scope):[],a=i.length>0?await t.select().from(r).where(w(...i)):await t.select().from(r);e.setResult({workflows:a.map(P)})});return()=>{a(),o(),s(),c()}}function Et(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 Dt(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 Ot(e,t){let{workflowExecutionFrames:r}=C(t,M),i=e.on(n.setFrame,async e=>{let{executionId:n,frame:i}=e.payload,a=Dt(n,i);await t.insert(r).values(a).onConflictDoUpdate({target:r.frameId,set:a}),e.setResult({frameId:i.frameId})}),a=e.on(n.getFrame,async e=>{let n=await t.select().from(r).where(O(r.frameId,e.payload.frameId)).limit(1);e.setResult({frame:n[0]?Et(n[0]):null})}),o=e.on(n.listFrames,async e=>{let n=await t.select().from(r).where(O(r.executionId,e.payload.executionId)).orderBy(T(r.startedAt),T(r.frameId));e.setResult({frames:n.map(Et)})});return()=>{i(),a(),o()}}function kt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function F(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 I(e){return{id:kt(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 At(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??Fe;if(!Number.isInteger(i)||i<_||i>g)throw Error(`Gate instance list limit must be an integer between ${_} and ${g}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[O(r.executionId,e)],...t===void 0?[]:[O(r.status,t)]]}}function jt(e,t){let{workflowExecutions:r,workflowGateInstances:i}=C(t,M),a=e.on(n.setGateInstance,async e=>{let n=e.payload.gate,r=I(n);await t.insert(i).values(r).onConflictDoUpdate({target:i.id,set:r}),e.setResult({id:r.id})}),o=e.on(n.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,r=I(n),a=await t.update(i).set(r).where(w(O(i.id,r.id),O(i.status,`waiting`))).returning({id:i.id});e.setResult({accepted:a.length===1})}),s=e.on(n.getGateInstance,async e=>{let{executionId:n,nodeId:r,frameId:a}=e.payload,o=[O(i.executionId,n),O(i.nodeId,r)];a!==void 0&&o.push(O(i.frameId,a));let s=await t.select().from(i).where(w(...o)).limit(1);e.setResult({gate:s[0]?F(s[0]):null})}),c=e.on(n.listGateInstances,async e=>{let{executionId:n,status:r,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=At(n,r,a,i),c=await t.select().from(i).where(w(...s)).orderBy(D(i.createdAt),D(i.id)).limit(o);e.setResult({gates:c.map(F)})}),l=e.on(n.listPausedGateTimeouts,async e=>{let n=await t.select({gate:i}).from(i).innerJoin(r,O(i.executionId,r.id)).where(w(O(i.status,`waiting`),O(r.status,`paused`),tt(i.timeoutMs)));e.setResult({gates:n.map(e=>F(e.gate))})});return()=>{a(),o(),s(),c(),l()}}function Mt(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 Nt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Pt(e,t){let{workflowStepSpans:r,workflowExecutionLinks:i}=C(t,M),a=e.on(n.setSpan,async e=>{let{span:n}=e.payload;await t.insert(r).values(n).onConflictDoUpdate({target:[r.executionId,r.frameId],set:n}),e.setResult({id:`${n.executionId}:${n.frameId}`})}),o=e.on(n.listSpans,async e=>{let n=await t.select().from(r).where(O(r.executionId,e.payload.executionId)).orderBy(T(r.startedAt),T(r.stepId),T(r.frameId));e.setResult({spans:n.map(Mt)})}),s=e.on(n.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(i).values(n).onConflictDoUpdate({target:[i.sourceExecutionId,i.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(n.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:r}=e.payload;if(n===void 0&&r===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[O(i.sourceExecutionId,n)],...r===void 0?[]:[O(i.targetExecutionId,r)]],o=t.select().from(i).where(w(...a));e.setResult({links:(await o).map(Nt)})});return()=>{a(),o(),s(),c()}}function Ft(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 It(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 Lt(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:It(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:St(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 Rt(e){let t=Ft(e.source),n=N(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 zt(e,t,n){let r=Rt(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Bt(e,t){let{workflowRunContexts:r}=C(t,M),i=e.on(n.setRunContext,async e=>{let n=e.payload.runContext;await zt(t,n,r),e.setResult({executionId:n.executionId})}),a=e.on(n.getRunContext,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(O(r.executionId,n)),a=i[0]?Lt(i[0]):null;e.setResult({runContext:a})});return()=>{i(),a()}}function L(e,t){return t===null?Ze(e)===`postgres`?A`'null'::jsonb`:A`'null'`:t}async function Vt(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=C(e,M),a=Date.now(),o=L(e,n);await S(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Ht(e,t){let{workflowExecutionState:n}=C(e,M),r=(await e.select().from(n).where(O(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Ut(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=C(e,M),i=Date.now(),a=L(e,t.nextValue);return S(e,async e=>{let o=(await e.select().from(n).where(O(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=ke(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(w(O(n.executionId,t.executionId),O(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function Wt(e,t){let r=e.on(n.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await Vt(t,n,r),e.setResult({})}),i=e.on(n.getState,async e=>{let{executionId:n}=e.payload,r=await Ht(t,n);e.setResult({state:r})}),a=e.on(n.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Ut(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{r(),i(),a()}}function Gt(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 Kt(e,t){let{worklogSummaries:n}=C(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function qt(e,t){let{worklogSummaries:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:Jt(t),setWhere:it(n.status,[`completed`,`failed`,`cancelled`])})}function Jt(e){return{workflowId:e.workflowId,workflowName:e.workflowName,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,error:e.error,failedNodeId:e.failedNodeId}}async function R(e,t){let{worklogSummaries:n}=C(e,M),r=await e.select().from(n).where(O(n.executionId,t)).limit(1);return r[0]?Gt(r[0]):null}async function Yt(e,t={}){let{worklogSummaries:n}=C(e,M),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[O(n.workflowId,r)],...i===void 0?[]:[O(n.status,i)]],c=s.length>0?w(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(D(n.startedAt)).limit(a).offset(o),e.select({count:E()}).from(n).where(c)]);return{items:l.map(Gt),total:u[0]?.count??0}}async function Xt(e,t){let{worklogFrameEntries:n}=C(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function Zt(e,t){let{worklogFrameEntries:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:it(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function z(e,t){let{worklogFrameEntries:n}=C(e,M);return(await e.select().from(n).where(O(n.frameId,t)).limit(1))[0]??null}async function Qt(e,t){let n=await z(e,t);return n===null?null:Ve.parse({executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??void 0,branchKey:n.branchKey??void 0,startedAt:n.startedAt??void 0,completedAt:n.completedAt??void 0,durationMs:n.durationMs??void 0,inputTokens:n.inputTokens??void 0,outputTokens:n.outputTokens??void 0,estimatedCost:n.estimatedCost??void 0,error:n.error??void 0})}async function $t(e,t){let{worklogArtifactWrites:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function en(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function B(e,t){let{worklogGateEvents:n}=C(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function tn(e,t){let{worklogGateEvents:n}=C(e,M);return(await e.select().from(n).where(O(n.id,t)).limit(1))[0]??null}function V(e,t,n){return`${e}:${t}:${n}`}async function nn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(O(t.executionId,n)).returning();return r}async function rn(e,t,n){let[r]=await e.select({totalInputTokens:j(t.inputTokens),totalOutputTokens:j(t.outputTokens),totalEstimatedCost:j(t.estimatedCost),measuredInputTokens:E(t.inputTokens),measuredOutputTokens:E(t.outputTokens),measuredCosts:E(t.estimatedCost)}).from(t).where(O(t.executionId,n));return{totalInputTokens:Number(r?.totalInputTokens??0),totalOutputTokens:Number(r?.totalOutputTokens??0),totalEstimatedCost:Number(r?.totalEstimatedCost??0),hasMeasurements:Number(r?.measuredInputTokens??0)>0||Number(r?.measuredOutputTokens??0)>0||Number(r?.measuredCosts??0)>0}}function an(e){return e.hasMeasurements}async function on(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(O(t.executionId,n))}async function sn(e,t,n,r){let i=A`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=A`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=A`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=A`exists(
2
- select 1 from ${n}
3
- where ${n.executionId} = ${r}
4
- and (${n.inputTokens} is not null
5
- or ${n.outputTokens} is not null
6
- or ${n.estimatedCost} is not null)
7
- )`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(w(O(t.executionId,r),s))}async function cn(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=C(e,M);if(Ze(e)===`sqlite`){await sn(e,n,r,t);return}await S(e,async e=>{if(await nn(e,n,t)===void 0)return;let i=await rn(e,r,t);an(i)&&await on(e,n,t,i)})}async function ln(e,t={}){let{worklogSummaries:n}=C(e,M),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[O(n.workflowId,r)],...i===void 0?[]:[et(n.startedAt,i)],...a===void 0?[]:[rt(n.startedAt,a)]],s=o.length>0?w(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:E()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:j(n.durationMs),totalInputTokens:j(n.totalInputTokens),totalOutputTokens:j(n.totalOutputTokens),totalEstimatedCost:j(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 un(e,t,n,r,i){let a=await z(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 H(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function U(e,t){try{await e.emit(m.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const dn=new Set([`completed`,`failed`,`cancelled`]);function fn(e){return dn.has(e)}async function pn(e,t,n){await Kt(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 U(e,n.executionId)}async function mn(e,t,n){let r=n.completedAt??Date.now(),i=await R(t,n.executionId);i!==null&&fn(i.status)||(await qt(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 U(e,n.executionId))}async function hn(e,t,n,r,i,a,o){let s=await R(t,n);if(s!==null&&fn(s.status))return;let c=s?.startedAt??o;await qt(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 U(e,n)}function gn(e,t){return[e.on(m.execution.started,async n=>{let{executionId:r}=n.payload;await H(`execution.started[${r}]`,()=>pn(e,t,n.payload))}),e.on(m.execution.completed,async n=>{let{executionId:r}=n.payload;await H(`execution.completed[${r}]`,()=>mn(e,t,n.payload))}),e.on(m.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await H(`execution.failed[${r}]`,()=>hn(e,t,r,`failed`,i,a??null,o))}),e.on(m.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await H(`execution.cancelled[${r}]`,()=>hn(e,t,r,`cancelled`,null,null,i))})]}const _n=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function vn(e){return _n.has(e)}function yn(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 bn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await z(t,r);c!==null&&vn(c.status)||(await Zt(t,{frameId:r,executionId:n,...yn(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await cn(t,n),await U(e,n))}async function xn(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await z(t,r);l!==null&&vn(l.status)||(await Zt(t,{frameId:r,executionId:n,...yn(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await U(e,n))}function Sn(e,t){return[e.on(m.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await H(`frame.started[${i}]`,async()=>{await Xt(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 U(e,r)})}),e.on(m.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await H(`frame.completed[${i}]`,()=>bn(e,t,r,i,a,o,s))}),e.on(m.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await H(`frame.failed[${i}]`,()=>xn(e,t,r,i,a,o,s,c))})]}const Cn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function wn(e,t){return[e.on(m.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await H(`gate.suspended[${i}]`,async()=>{await B(t,{id:V(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await U(e,r)})}),e.on(m.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await H(`gate.resumed[${i}]`,async()=>{let n=V(r,a,i),s=await tn(t,n),c=Date.now();await B(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await U(e,r)})}),e.on(m.gate.resolved,async n=>Tn(n.payload,e,t)),e.on(m.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await H(`artifact.updated[${r}:${i}]`,async()=>{let n=await un(e,t,i,a,o);if(n===null)return;let s=Date.now();await $t(t,{id:en(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await U(e,r)})})]}async function Tn(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await H(`gate.resolved[${i}]`,async()=>{let s=V(r,a,i),c=await tn(n,s),l=Date.now();await B(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Cn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await U(t,r)})}function En(e,t){let n=[...gn(e,t),...Sn(e,t),...wn(e,t),e.on(m.worklog.get,async e=>{let{executionId:n}=e.payload,r=await R(t,n);e.setResult({summary:r})}),e.on(m.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await Qt(t,n);e.setResult({frame:r})}),e.on(m.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Yt(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(m.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await ln(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function W(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>W(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&W(n[e],r[e]))}function Dn(e){return{executionId:e.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,status:e.status,attempt:e.attempt,iteration:e.iteration??null,branchKey:e.branchKey??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,durationMs:e.durationMs??null,inputTokens:e.inputTokens??null,outputTokens:e.outputTokens??null,estimatedCost:e.estimatedCost??null,error:e.error??null}}function On(e,t){let n=e.frame;if(n!==void 0){let r=e.status===`failed`?e.error??null:null;if(n.executionId!==e.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);if(n.status!==e.status)throw Error(`settleExternalExecution requires frame.status to match status`);if(n.completedAt!==t)throw Error(`settleExternalExecution requires frame.completedAt to match completedAt`);if(n.durationMs!==t-n.startedAt)throw Error(`settleExternalExecution requires frame.durationMs to match its timestamps`);if((n.error??null)!==r)throw Error(`settleExternalExecution requires frame.error to match terminal error metadata`)}return JSON.stringify({version:1,status:e.status,completedAt:t,error:e.status===`failed`?e.error??null:null,reason:e.status===`cancelled`?e.reason??null:null,frame:n===void 0?null:{executionId:n.executionId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path,status:n.status,attempt:n.attempt,iteration:n.iteration??null,branchKey:n.branchKey??null,startedAt:n.startedAt,completedAt:n.completedAt,durationMs:n.durationMs,error:n.status===`failed`?n.error??null:null}})}function kn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function An(e,t,n,r,i){let a=On(r,i);if(n.externalSettlementFingerprint!==null){kn(n.externalSettlementFingerprint,a,r.executionId);return}if(r.frame!==void 0)throw Error(`settleExternalExecution: frame presence conflicts with the legacy frame-less settlement for execution "${r.executionId}"`);let o=r.status===`failed`?r.error??null:null,s=r.status===`cancelled`?r.reason??null:null;if((await e.update(t).set({externalSettlementFingerprint:a}).where(w(O(t.id,r.executionId),k(t.externalSettlementFingerprint),O(t.status,r.status),O(t.completedAt,i),o===null?k(t.error):O(t.error,o),s===null?k(t.reason):O(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(O(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(G(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);kn(c.externalSettlementFingerprint,a,r.executionId)}function jn(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!W(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function G(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function Mn(e,t,n){let r=await e.select().from(t).where(O(t.executionId,n.executionId)),i=r.find(e=>e.frameId===n.frame.frameId);if(i!==void 0)return i;if(r.length>0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" conflicts with the registered frame identity`);let[a]=await e.select().from(t).where(O(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function Nn(e,t,n,r){let i=Math.min(e.startedAt,r);return{executionId:e.id,workflowId:e.workflowId,workflowName:t?.workflowName??null,status:n.status,startedAt:i,completedAt:r,durationMs:r-i,totalInputTokens:t?.totalInputTokens??null,totalOutputTokens:t?.totalOutputTokens??null,totalEstimatedCost:t?.totalEstimatedCost??null,error:n.status===`failed`?n.error??null:null,failedNodeId:n.status===`failed`?n.frame?.nodeId??t?.failedNodeId??null:null}}function Pn(e,t){return Dn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Fn(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&W(e.inputs,t.inputs)&&W(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function In(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function Ln(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!W(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function Rn(e,t,n,r){if(!t.id.startsWith(v))throw Error(`setExternalExecutionStart: execution "${t.id}" is not an external execution ID`);if(n!==void 0&&n.executionId!==t.id)throw Error(`setExternalExecutionStart requires frame.executionId to match execution.id`);let{workflowExecutions:i,worklogSummaries:a,worklogFrameEntries:o}=C(e,M),s={...r(t),externalRegistrationFrameId:n?.frameId??null},c={executionId:t.id,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt,completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null};await S(e,async e=>{let r=(await e.insert(i).values(s).onConflictDoNothing().returning({id:i.id})).length===0;if(r){let[n]=await e.select().from(i).where(O(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);Fn(n,s)}let[l]=await e.select().from(a).where(O(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):In(l,c),n!==void 0){let[i]=await e.select().from(o).where(O(o.frameId,n.frameId)).limit(1);if(i===void 0){if(r)throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);await e.insert(o).values(Dn(n))}else Ln(i,n)}})}async function zn(e,t,n,r,i){if(r.frame!==void 0){let n=await Mn(e,t,r);return n!==void 0&&jn(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(O(t.frameId,n.externalRegistrationFrameId)).limit(1);if(a===void 0||a.executionId!==n.id)throw Error(`settleExternalExecution: registered frame "${n.externalRegistrationFrameId}" is unavailable for execution "${n.id}"`);if(a.startedAt===null)throw Error(`settleExternalExecution: registered frame "${a.frameId}" has no start timestamp`);if(i<a.startedAt)throw Error(`settleExternalExecution: completedAt must not precede the registered frame start timestamp`);let o=We.parse(a.nodeType);return{frame:{executionId:a.executionId,frameId:a.frameId,nodeId:a.nodeId,nodeType:o,path:a.path,status:r.status,attempt:a.attempt,...a.iteration===null?{}:{iteration:a.iteration},...a.branchKey===null?{}:{branchKey:a.branchKey},startedAt:a.startedAt,completedAt:i,durationMs:i-a.startedAt,...r.status===`failed`&&r.error!==void 0?{error:r.error}:{}},existing:a}}async function Bn(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await nn(e,a,n.id),c=await zn(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Pn(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await rn(e,o,n.id),d=an(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Nn(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:Jt(p)}),d&&await on(e,a,n.id,u)}async function Vn(e,t){if(!t.executionId.startsWith(v))throw Error(`settleExternalExecution: execution "${t.executionId}" is engine-owned and must use the engine finalizer`);if(t.frame!==void 0&&t.frame.executionId!==t.executionId)throw Error(`settleExternalExecution requires frame.executionId to match executionId`);let{workflowExecutions:n,worklogSummaries:r,worklogFrameEntries:i}=C(e,M);return S(e,async e=>{let[a]=await e.select().from(n).where(O(n.id,t.executionId)).limit(1);if(a===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" was not registered`);let o=t.completedAt??a.completedAt??Date.now();if(a.status===`running`){let r=On(t,o);if((await e.update(n).set({status:t.status,completedAt:o,error:t.status===`failed`?t.error??null:null,reason:t.status===`cancelled`?t.reason??null:null,externalSettlementFingerprint:r}).where(w(O(n.id,t.executionId),O(n.status,`running`),k(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(O(n.id,t.executionId)).limit(1);if(r===void 0)throw Error(`settleExternalExecution: execution "${t.executionId}" disappeared`);t.completedAt===void 0&&r.completedAt!==null&&(o=r.completedAt),G(r,t,o),await An(e,n,r,t,o)}}else G(a,t,o),await An(e,n,a,t,o);return await Bn(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function Hn(e,t,r){let i=e.on(n.setExternalExecutionStart,async n=>{let i=n.payload.execution,a=n.payload.frame;await Rn(t,i,a,r),await U(e,i.id),n.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),a=e.on(n.settleExternalExecution,async n=>{let r=await Vn(t,n.payload);await U(e,n.payload.executionId),n.setResult({success:r})});return()=>{i(),a()}}function Un(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:St(e)}}function K(e){let t=N(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 Wn(e,t,n,r,i,a){let o=[...e?[O(a.workflowId,e)]:[],...n?[O(a.status,n)]:[],...i===void 0?[]:[O(a.artifactKind,i.kind),O(a.artifactId,i.id)]];if(t&&o.push(...Ct(a,t)),r){let e=at(nt(a.startedAt,r.startedAt),w(O(a.startedAt,r.startedAt),nt(a.id,r.id)));e&&o.push(e)}return o}async function Gn(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=C(e,M),u=K(t);await S(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(O(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await zt(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=L(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function Kn(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}=C(e,M),a=K(t),o=I(n);await S(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 qn(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=C(e,M);return S(e,async e=>{if((await e.select().from(i).where(O(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(w(O(a.executionId,t),O(a.status,`waiting`)))).map(e=>({...F(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(O(i.id,t));for(let t of o){let n=I(t);await e.update(a).set(n).where(O(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Jn(e,t,n,r,i,a){let{workflowExecutions:o}=C(e,M);return S(e,async e=>{if((await e.select({id:o.id}).from(o).where(O(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(O(o.id,t)),!0})}function Yn(e,t){let{workflowExecutions:r}=C(t,M),i=e.on(n.getExecution,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(O(r.id,n));e.setResult({execution:i[0]?Un(i[0]):null})}),a=e.on(n.setExecution,async e=>{let n=e.payload.execution,i=K(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:n.id})}),o=e.on(n.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await Gn(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(n.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Kn(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(n.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Jn(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(n.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await qn(t,n,r,i))});return()=>{i(),a(),o(),s(),c(),l()}}function Xn(e,t){let{workflowExecutions:r}=C(t,M),i=e.on(n.listExecutions,async e=>{let{workflowId:n,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(n===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=Wn(n,i,a,s,c,r),u=o??Fe;if(!Number.isInteger(u)||u<_||u>g)throw Error(`Execution list limit must be an integer between ${_} and ${g}.`);let d=await t.select().from(r).where(w(...l)).orderBy(D(r.startedAt),D(r.id)).limit(u);e.setResult({executions:d.map(Un)})}),a=e.on(n.listExecutionsByArtifactRefs,async e=>{let n=Le.safeParse(e.payload);if(!n.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${n.error.message}`);let{refs:i,limitPerRef:a}=n.data,o={};for(let e of i){let n=await t.select().from(r).where(w(O(r.artifactKind,e.kind),O(r.artifactId,e.id))).orderBy(D(r.startedAt),D(r.id)).limit(a);n.length>0&&(o[Je(e)]=n.map(Un))}e.setResult({executionsByRef:o})});return()=>{i(),a()}}function Zn(e,t){let n=Tt(e,t),r=Yn(e,t),i=Xn(e,t),a=Ot(e,t),o=jt(e,t),s=Pt(e,t),c=Bt(e,t),l=Wt(e,t),u=En(e,t),d=Hn(e,t,K);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d()}}function Qn(e){return e.startsWith(v)}function $n(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function er(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}function q(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}async function tr(e,t){let{runContext:r}=await e.request(n.getRunContext,{executionId:t});if(r===null)throw Error(`Run context not found for execution: ${t}`);if(r.definitionSnapshot!==void 0)return r.definitionSnapshot;let{workflow:i}=await e.request(n.get,{id:r.workflowId});return i??void 0}function nr(e){return[e.on(m.getDefinition,async t=>{let r=await e.request(n.get,{id:t.payload.id});t.setResult(r)}),e.on(m.setDefinition,async t=>{let r=await e.request(n.set,{workflow:t.payload.workflow});t.setResult(r)}),e.on(m.deleteDefinition,async t=>{let r=await e.request(n.delete,{id:t.payload.id});t.setResult(r)}),e.on(m.listDefinitions,async t=>{let r=await e.request(n.list,t.payload);t.setResult(r)}),e.on(m.getExecution,async t=>{let r=await e.request(n.getExecution,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listExecutions,async t=>{let r=await e.request(n.listExecutions,t.payload);t.setResult(r)}),e.on(m.listExecutionsByArtifactRefs,async t=>{let r=await e.request(n.listExecutionsByArtifactRefs,t.payload);t.setResult(r)}),e.on(m.listSpans,async t=>{let r=await e.request(n.listSpans,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listFrames,async t=>{let r=await e.request(n.listFrames,{executionId:t.payload.executionId});t.setResult(r)}),e.on(m.listGateInstances,async t=>{let r=await e.request(n.listGateInstances,t.payload);t.setResult(r)}),e.on(m.setExecutionLink,async t=>{let r=await e.request(n.setExecutionLink,{link:t.payload.link});t.setResult(r)}),e.on(m.listExecutionLinks,async t=>{let r=await e.request(n.listExecutionLinks,t.payload);t.setResult(r)}),e.on(m.getRunContext,async t=>{let{executionId:r}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${r}`);let{runContext:i}=await e.request(n.getRunContext,{executionId:r});if(!i)throw Error(`Run context not found for execution: ${r}`);t.setResult(i)}),...rr(e)]}function rr(e){return[e.on(m.registerExternalExecution,async t=>{let r=ce.registerExternalExecution.request.parse(t.payload),{name:i,scope:a,input:o}=r;if(r.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let s=r.executionId??ue(`wfx-ext`);if(!Qn(s))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let c=r.startedAt??Date.now(),l={id:s,workflowId:i,status:`running`,inputs:o===void 0?{}:o,startedAt:c,scope:a??{type:`global`},...$n(r)},u=ir(s,c,r.frame),d=await e.request(n.setExternalExecutionStart,{execution:l,...u===void 0?{}:{frame:u}});t.setResult(d)}),e.on(m.completeExternalExecution,async t=>{let r=ce.completeExternalExecution.request.parse(t.payload),{executionId:i,status:a}=r;if(!q(t,i))throw Error(`Unauthorized: caller is not permitted to settle execution: ${i}`);if(!Qn(i))throw Error(`completeExternalExecution: execution "${i}" is engine-owned and must be completed through the engine finalizer, not this API`);let o=ar(r),s=await e.request(n.settleExternalExecution,{executionId:i,status:a,...er(r),...r.completedAt===void 0?{}:{completedAt:r.completedAt},...o===void 0?{}:{frame:o}});t.setResult({success:s.success})})]}function ir(e,t,n){if(n===void 0)return;let r=n.frameId??`${e}:${n.nodeId}`;return{executionId:e,frameId:r,nodeId:n.nodeId,nodeType:n.nodeType,path:n.path??[r],status:`running`,attempt:n.attempt,...n.iteration===void 0?{}:{iteration:n.iteration},...n.branchKey===void 0?{}:{branchKey:n.branchKey},startedAt:n.startedAt??t}}function ar(e){if(e.frame===void 0)return;if(e.completedAt===void 0)throw Error(`completedAt is required when frame metadata is supplied`);let t=e.completedAt-e.frame.startedAt;if(t<0)throw Error(`completedAt must not precede frame.startedAt`);if(e.frame.durationMs!==void 0&&e.frame.durationMs!==t)throw Error(`frame.durationMs must equal completedAt - frame.startedAt`);return{executionId:e.executionId,frameId:e.frame.frameId,nodeId:e.frame.nodeId,nodeType:e.frame.nodeType,path:e.frame.path,status:e.status,attempt:e.frame.attempt,...e.frame.iteration===void 0?{}:{iteration:e.frame.iteration},...e.frame.branchKey===void 0?{}:{branchKey:e.frame.branchKey},startedAt:e.frame.startedAt,completedAt:e.completedAt,durationMs:t,...e.status===`failed`&&e.error!==void 0?{error:e.error}:{}}}function or(e){return[e.on(m.state.get,async t=>{let{executionId:r}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${r}`);let{state:i}=await e.request(n.getState,{executionId:r});if(i===null)throw Error(`no workflow state for execution ${r}`);t.setResult(i)}),e.on(m.state.patch,async t=>{let{executionId:r,expectedSequence:i,patch:a,nextValue:o}=t.payload;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${r}`);if(i===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=await tr(e,r);s!==void 0&&Ae(s,o,`next`),Re.array().parse(a);let c=await e.request(n.patchState,{executionId:r,expectedSequence:i,nextValue:o});e.emit(m.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}function sr(e,t){return[e.on(m.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}async function cr(e,t){let{runContext:r}=await e.bus.request(n.getRunContext,{executionId:t});if(r===null)throw new b(He.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return r}function lr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function ur(e,t){let n=await cr(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.executionHints??(t.mode===`snapshot`?n.executionHints:void 0),c=t.scopeOverride??n.scope,l={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,executionHints:s,scopeOverride:c,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:lr(t.mode,t.reason)}]};return t.mode===`snapshot`?await mr(e,n,l):fr(n)?await hr(e,n,l):await pe(e,n.workflowId,l)}function dr(e,t){return fr(e)?t.id:e.workflowId}function fr(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function pr(e){let t=e.definitionSnapshot;if(t===void 0)throw new b(He.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function mr(e,t,n){let r=pr(t);return De(e,dr(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}async function hr(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`)return be(e,t.source.path,n);let r=pr(t);return De(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}var gr=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(n.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:r}=await this.bus.request(n.getExecution,{executionId:e.executionId});return r?.status===`running`?`retry`:r?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function _r(e){if(e!==void 0)return vr(e)?e:{}}function vr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function yr(e){if(e!==void 0)return ze.parse(e)}function br(e){if(e!==void 0)return Ie.parse(e)}function xr(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${st.homedir()}/.makaio`,os:Ce(process.platform),arch:process.arch}}function Sr(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:xr(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Cr(e){return e?.status===`paused`}function wr(e){return e?.status===`waiting`}async function Tr(e,t,r,i,a,o,s){t.delete(a.id),r.delete(a.id),i.delete(a.id);try{await e.request(n.restorePausedGateResumeState,{execution:a,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function Er(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:r}=await e.request(n.listFrames,{executionId:t.executionId});if(r.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Dr(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Or(e,t){if(t.frameId!==void 0){let{gate:r}=await e.request(n.getGateInstance,t);return wr(r)?r:null}let{gates:r}=await e.request(n.listGateInstances,{executionId:t.executionId}),i=r.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return i.length===1?i[0]:null}var kr=class extends Ye{static storage={drizzle:Zn};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={...fe,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new gr(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of nr(this.bus))this.addCleanup(e);for(let e of or(this.bus))this.addCleanup(e);for(let e of sr(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=>xr(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Be.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${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=>Sr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(m.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload;try{let l=await pe(this.buildStartDeps(),t,{input:yr(n),config:_r(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:br(c),scopeOverride:s});e.setResult({executionId:l})}catch(e){if(e instanceof b)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(m.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,executionHints:l,reason:u}=e.payload;try{let d=await ur(this.buildStartDeps(),{executionId:t,mode:n,input:yr(r),config:_r(i),parentSessionId:a,triggerPayload:o,artifactRef:s,executionHints:br(l),scopeOverride:c,reason:u});e.setResult({executionId:d})}catch(e){if(e instanceof b)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(m.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 be(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(m.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(Ge(`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??y);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(m.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(m.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(m.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(n.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Dr(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let n=await de({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Se(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,r.signal,void 0,n,{context:t.runContext.context,env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});Ee(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();i=await xe(t.workflow.root,a,o)}catch(n){if(r.signal.aborted||t.execution.status===`cancelled`){await h(this.buildFinalizerDeps(),e,y);return}let i=n instanceof Error?n.message:String(n);await _e(this.buildFinalizerDeps(),t.execution,e,i);return}let a=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||t.execution.status===`cancelled`?await h(a,e,y):i.status===`failed`?await _e(a,t.execution,e,i.error):i.status===`paused`?(t.execution.status=`paused`,await this.bus.request(n.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await ge(a,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:r,frameId:i,resumeData:a,reason:o}=e,{execution:s}=await this.bus.request(n.getExecution,{executionId:t});if(!Cr(s))return!1;let c=await Or(this.bus,{executionId:t,nodeId:r,frameId:i});if(c===null||!Te(r,c.schema,a).valid)return!1;let{runContext:l}=await this.bus.request(n.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Er(this.bus,l);let{accepted:u}=await this.bus.request(n.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:a,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Tr(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,r),e}return this.gateTimeoutScheduler.clear(t,r,c.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(n.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let r=t.definitionSnapshot??(await this.bus.request(n.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(n.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await Er(this.bus,t),await this.bus.request(n.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:r,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let a=he(t,r,{resume:!0}),o=me(this.buildStartDeps(),a).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,o),!0}};function Ar(e,t){try{return ot(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function jr(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 Mr(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Nr=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(x.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(x.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(x.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(n.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`?Ar(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(jr(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=Mr(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(Ne(e,r.subject)&&!(r.filter&&!Me(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(x.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function J(e,t,n,r,i,a,o,s){return J.fromTZ(J.tp(e,t,n,r,i,a,o),s)}J.fromTZISO=(e,t,n)=>J.fromTZ(Fr(e,t),n),J.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=Pr(e.tz,n),i=new Date(n.getTime()-r),a=Pr(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=Pr(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},J.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}},J.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function Pr(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 Fr(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(`+`)?J.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):J.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}J.minitz=J;var Ir=32,Y=31|Ir,Lr=[1,2,4,8,16],Rr=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]|Ir;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|Lr[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},zr=[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&&Lr[a-1]&r)return!0;if(r&Ir){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=J.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>zr[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=J.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(J.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():zr[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)):J.fromTZ(J.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Br(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 Vr(e){return Q(e)}function Hr(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var Ur=30*1e3,$=[],Wr=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=Br(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 Rr(`* * * * *`)},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 Rr(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&&Vr(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>Ur&&(t=Ur),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&Hr(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 Gr(e,t){return`${e}:${t}`}function Kr(e){return e??`UTC`}var qr=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(x.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(x.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(x.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(n.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=Gr(e.id,n);this.stopJob(i);try{let t=Kr(r.timezone),a=new Wr(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(x.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)})}},Jr=class extends Ye{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new kr(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Nr(e),this.cronTriggerEvaluator=new qr(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 Yr=qe(`makaio.workflow-engine`);function Xr(e){return{name:Yr.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[Ke(ct.name)],critical:!0,namespaces:[Ue,re],storage:{registerHandlers:Qe(Zn)},create:t=>new Jr(t.bus,e)}}const Zr=Xr();export{kr as a,Vt as c,Jr as i,Ut as l,Xr as n,Zn as o,Zr as r,Ht as s,Yr as t};
@@ -1 +0,0 @@
1
- import{SessionStorageSubjects as e}from"./services/session/storage/namespace.mjs";import{ExecutionTargetSubjects as t}from"./services/execution-target/namespace.mjs";import{MakaioBus as n}from"@makaio/framework/bus";import{AdapterSubjects as r,AgentSubjects as i,DEFAULT_CONSTRAINTS as a,SessionSubjects as o,SpawnSubagentRpcRequestSchema as s,SubagentConfigSchema as c,SubagentError as l,SubagentErrorCode as u,SubagentSubjects as d,dep as f,extensionToken as p}from"@makaio/framework/contracts";import{BaseService as m}from"@makaio/framework/service-base";import{AdapterRuntimeSubjects as h}from"@makaio/framework/services/adapter-runtime";import{RuntimeProviderContextResolutionError as g,resolveRuntimeProviderContext as _}from"@makaio/framework/services/provider-context";function v(e,t){return`${e}:${t}`}function y(e,t){return e?.authenticated!==!0||!e.id?!1:e.kind===`workflow-execution`?!0:t.size===0?!1:t.has(v(e.kind,e.id))}var b=class{maxSize;items=[];constructor(e=50){this.maxSize=e}push(e){this.items.push(e),this.items.length>this.maxSize&&this.items.shift()}toArray(){return[...this.items]}get length(){return this.items.length}clear(){this.items=[]}};const x=[`completed`,`failed`,`cancelled`];function S(e){return x.includes(e)}var C=class{constraints;subagents=new Map;awaiters=new Map;constructor(e){this.constraints=e}track(e){let t=Date.now(),n={subagentId:e.subagentId,parentSessionId:e.parentSessionId,childSessionId:void 0,status:`spawning`,config:e.config,depth:e.depth,progressUpdates:new b(50),startTime:t,lastActivityAt:t};return this.subagents.set(e.subagentId,n),n}setChildSessionId(e,t){let n=this.subagents.get(e);n&&(n.childSessionId=t,n.lastActivityAt=Date.now(),n.status===`spawning`&&(n.status=`running`))}get(e){return this.subagents.get(e)}getAllNonTerminal(){let e=[];for(let t of this.subagents.values())S(t.status)||e.push(t);return e}countActiveBySession(e){let t=0;for(let n of this.subagents.values())n.parentSessionId===e&&!S(n.status)&&t++;return t}countTotalActive(){let e=0;for(let t of this.subagents.values())S(t.status)||e++;return e}updateStatus(e,t){let n=this.subagents.get(e);if(!n)return;let r=Date.now();n.status=t,n.lastActivityAt=r,S(t)&&(n.endTime=r)}addProgress(e,t){let n=this.subagents.get(e);n&&(n.progressUpdates.push(t),n.lastActivityAt=Date.now())}setPendingRequest(e,t){let n=this.subagents.get(e);if(!n)throw new l(u.NOT_FOUND,`Subagent ${e} not found`);if(n.pendingRequest)throw new l(u.REQUEST_PENDING,`Cannot call request_input while another request is pending`);n.pendingRequest=t,n.status=`waiting_input`,n.lastActivityAt=Date.now()}resolvePendingRequest(e,t){let n=this.subagents.get(e);n?.pendingRequest&&(n.pendingRequest.resolver(t),n.pendingRequest=void 0,n.lastActivityAt=Date.now(),n.status===`waiting_input`&&(n.status=`running`))}markCompleted(e,t,n,r){let i=this.subagents.get(e);if(!i)throw new l(u.NOT_FOUND,`Subagent ${e} not found`);if(S(i.status))throw new l(u.ALREADY_TERMINAL,`Subagent already in terminal state: ${i.status}`);let a=Date.now();i.status=`completed`,i.result=t,i.summary=n,i.completionSource=r,i.endTime=a,i.lastActivityAt=a,this.resolveAwaiters(e)}markFailed(e,t){let n=this.subagents.get(e);if(!n||S(n.status))return;let r=Date.now();n.status=`failed`,n.error=t,n.endTime=r,n.lastActivityAt=r,this.resolveAwaiters(e)}markCancelled(e){let t=this.subagents.get(e);if(!t||S(t.status))return!1;let n=Date.now();return t.status=`cancelled`,t.endTime=n,t.lastActivityAt=n,t.pendingRequest&&=(t.pendingRequest.resolver(null),void 0),this.resolveAwaiters(e),!0}addAwaiter(e,t){let n=this.awaiters.get(e)??[];n.push(t),this.awaiters.set(e,n)}removeAwaiter(e,t){let n=this.awaiters.get(e);if(!n)return!1;let r=n.indexOf(t);return r===-1?!1:(n.splice(r,1),n.length===0&&this.awaiters.delete(e),!0)}resolveAwaiters(e){let t=this.subagents.get(e),n=this.awaiters.get(e);if(!n||!t)return;let r={status:t.status,result:t.result,error:t.error,completionSource:t.completionSource};for(let e of n)e(r);this.awaiters.delete(e)}cleanup(){let e=Date.now(),t=0;for(let[n,r]of this.subagents)S(r.status)&&r.endTime&&e-r.endTime>this.constraints.stateRetentionMs&&(this.subagents.delete(n),t++);return t}sweepHung(e){if(e<=0)return 0;let t=Date.now(),n=0;for(let r of this.subagents.values())S(r.status)||r.status!==`waiting_input`&&r.status!==`hung`&&t-r.lastActivityAt>=e&&(r.status=`hung`,r.lastActivityAt=t,n++);return n}};async function w(e,t,n){let r=n?.trim();if(r)return r;let{session:i}=await e.request(o.get,{sessionId:t});return(i?.agents.find(e=>e.agentId===i.leadAgentId)??i?.agents[0])?.adapterName?.trim()}function T(e,t){let n=e.manager.get(t.subagentId);if(!n)throw Error(`Subagent not found: ${t.subagentId}`);return{status:n.status,childSessionId:n.childSessionId,pendingRequest:n.pendingRequest?{messageId:n.pendingRequest.messageId,question:n.pendingRequest.question,context:n.pendingRequest.context}:void 0,progress:n.progressUpdates.toArray(),result:n.result,summary:n.summary,error:n.error}}async function E(e,t){let{parentSessionId:n,config:r,depth:i,spawningToolCallId:a}=t,{constraints:o}=e.manager,s=Math.min(r.maxDepth??o.maxDepth,o.maxDepth);if(i>s)throw new l(u.DEPTH_EXCEEDED,`Maximum subagent depth (${s}) exceeded`);if(e.manager.countActiveBySession(n)>=o.maxConcurrentPerSession)throw new l(u.SESSION_LIMIT,`Maximum concurrent subagents per session (${o.maxConcurrentPerSession}) reached`);if(e.manager.countTotalActive()>=o.maxTotalActive)throw new l(u.GLOBAL_LIMIT,`Maximum total active subagents (${o.maxTotalActive}) reached`);let c=await w(e.bus,n,r.adapterName);if(!c)throw new l(u.ADAPTER_NOT_ALLOWED,`adapterName is required for subagent spawn when parent session has no inheritable adapter`);if(o.allowedAdapters.length>0&&!o.allowedAdapters.includes(c))throw new l(u.ADAPTER_NOT_ALLOWED,`Adapter '${c}' is not allowed`);if(r.model&&o.allowedModels.length>0&&!o.allowedModels.includes(r.model))throw new l(u.MODEL_NOT_ALLOWED,`Model '${r.model}' is not allowed`);let f={...r,adapterName:c},p=crypto.randomUUID();return e.manager.track({subagentId:p,parentSessionId:n,config:f,depth:i}),await e.bus.emit(d.spawned,{subagentId:p,parentSessionId:n,task:f.task,config:f,depth:i,...a!==void 0&&{spawningToolCallId:a}}),{subagentId:p,status:`spawning`}}async function D(e,t){let{subagentId:n,timeoutMs:r}=t,i=e.manager.get(n);if(!i)throw Error(`Subagent not found: ${n}`);if([`completed`,`failed`,`cancelled`].includes(i.status))return{status:i.status,result:i.result,error:i.error,completionSource:i.completionSource};if(i.status===`waiting_input`&&i.pendingRequest)return{status:`waiting_input`,pendingRequest:{messageId:i.pendingRequest.messageId,question:i.pendingRequest.question,context:i.pendingRequest.context}};let a=r??e.manager.constraints.defaultAwaitTimeoutMs;return new Promise(t=>{let r=!1,i,o=e=>{r||(r=!0,i&&clearTimeout(i),t({status:e.status,result:e.result,error:e.error,pendingRequest:e.pendingRequest,completionSource:e.completionSource}))};e.manager.addAwaiter(n,o),a>0&&(i=setTimeout(()=>{r||(r=!0,e.manager.removeAwaiter(n,o),t({status:`timeout`}))},a))})}async function O(e,t){let{subagentId:n,content:r,inResponseTo:i}=t,a=e.manager.get(n);if(!a)throw Error(`Subagent not found: ${n}`);let o=!1;return i&&a.pendingRequest?.messageId===i&&(e.manager.resolvePendingRequest(n,r),o=!0),await e.bus.emit(d.toChild,{subagentId:n,messageId:crypto.randomUUID(),content:r,inResponseTo:i}),{sent:!0,resolvedPending:o}}async function k(e,t){let{subagentId:n,reason:r}=t,i=e.manager.markCancelled(n);return i&&await e.bus.emit(d.cancelled,{subagentId:n,reason:r??`Killed by parent`}),{killed:i}}async function A(e,t){let{subagentId:n,update:r,percentComplete:i}=t;if(!e.manager.get(n))throw Error(`Subagent not found: ${n}`);let a=i===void 0?r:`[${i}%] ${r}`;return e.manager.addProgress(n,a),await e.bus.emit(d.toParent,{subagentId:n,messageId:crypto.randomUUID(),type:`progress`,content:a}),{reported:!0}}async function j(e,t){let{subagentId:n,question:r,context:i,timeoutMs:a}=t;if(!e.manager.get(n))throw Error(`Subagent not found: ${n}`);let o=crypto.randomUUID(),s=a??e.manager.constraints.defaultRequestTimeoutMs;return await e.bus.emit(d.toParent,{subagentId:n,messageId:o,type:`request_input`,content:r,context:i}),new Promise(t=>{let a=!1,c;e.manager.setPendingRequest(n,{messageId:o,question:r,context:i,resolver:e=>{a||(a=!0,c&&clearTimeout(c),t(e===null?{responded:!1,timedOut:!0}:{responded:!0,response:e,timedOut:!1}))}}),s>0&&(c=setTimeout(()=>{a||e.manager.resolvePendingRequest(n,null)},s))})}async function M(e,t){let{subagentId:n,result:r,summary:i}=t;return e.manager.markCompleted(n,r,i,`tool`),await e.bus.emit(d.completed,{subagentId:n,success:!0,result:i?`${i}\n\n${r}`:r}),{completed:!0}}function N(e,t){let{parentSessionId:n}=t;return{subagents:e.manager.getAllNonTerminal().filter(e=>e.parentSessionId===n).map(e=>({subagentId:e.subagentId,task:e.config.task,status:e.status}))}}const P={id:`system:local`,name:`Local`,description:`Default local process execution`,type:`local`,scope:`default`,enabled:!0,createdAt:Date.now(),updatedAt:Date.now()};var F=class extends Error{code;constructor(e){super(`Subagent failure finalization failed (${e}).`),this.code=e,this.name=`SubagentFailureFinalizationError`}},I=class extends m{machineId;delegationAllowSet;manager;pendingChildSessionClose=new Set;constructor(e=n,t=a,r,i=new Set){super(e),this.machineId=r,this.delegationAllowSet=i,this.manager=new C(t)}grantDelegation(e,t){this.delegationAllowSet.add(`${e}:${t}`)}revokeDelegation(e,t){this.delegationAllowSet.delete(`${e}:${t}`)}onInit(){this.registerHandler(d.spawned,async e=>{this.handleSpawned(e.payload).catch(e=>{console.error(`[SubagentService] handleSpawned error:`,e)})}),this.registerHandler(d.execute,async e=>{if(!this.isRemoteDelegationAllowed(e))return;let t=await this.handleExecute(e.payload);e.setResult(t)}),this.registerHandler(d.toChild,async e=>{await this.handleToChild(e.payload)}),this.registerHandler(d.completed,async e=>{await this.handleCompleted(e.payload.subagentId)}),this.registerHandler(d.cancelled,async e=>{await this.handleCancelled(e.payload.subagentId)}),this.registerHandler(r.session.closed,e=>{this.handleAdapterSessionClosed(e.payload.sessionId)}),this.registerHandler(i.complete,async e=>{await this.handleAgentComplete(e.payload)}),this.registerRpcHandlers(),this.wirePeriodicSweep()}wirePeriodicSweep(){let{inactivityTimeoutMs:e,sweepIntervalMs:t}=this.manager.constraints;if(t<=0)return;let n=setInterval(()=>{let t=this.manager.sweepHung(e);t>0&&console.warn(`[SubagentService] Swept ${t} hung subagent(s) due to inactivity`),this.manager.cleanup()},t);this.addCleanup(()=>clearInterval(n))}registerRpcHandlers(){let e={manager:this.manager,bus:this.bus};this.registerHandler(d.getStatus,t=>{let n=T(e,t.payload);t.setResult(n)}),this.registerHandler(d.spawn,async t=>{if(!this.isRemoteDelegationAllowed(t))return;let n=await E(e,s.parse(t.payload));t.setResult(n)}),this.registerHandler(d.await,async t=>{let n=await D(e,t.payload);t.setResult(n)}),this.registerHandler(d.send,async t=>{let n=await O(e,t.payload);t.setResult(n)}),this.registerHandler(d.kill,async t=>{let n=await k(e,t.payload);t.setResult(n)}),this.registerHandler(d.reportProgress,async t=>{let n=await A(e,t.payload);t.setResult(n)}),this.registerHandler(d.requestInput,async t=>{let n=await j(e,t.payload);t.setResult(n)}),this.registerHandler(d.completeTask,async t=>{let n=await M(e,t.payload);t.setResult(n)}),this.registerHandler(d.listBySession,t=>{let n=N(e,t.payload);t.setResult(n)})}onDestroy(){this.pendingChildSessionClose.clear()}async handleSpawned(e){let{subagentId:n,parentSessionId:r,task:i,spawningToolCallId:a}=e,o=c.parse({...e.config,task:i}),s=o.adapterName?.trim();if(!s)return this.failSpawn(n,r,`adapter_start`,`Subagent spawn requires a non-empty adapterName`);this.manager.get(n)||this.manager.track({subagentId:n,parentSessionId:r,config:o,depth:e.depth??1});let l,u;try{u=await this.buildExecutionTargetResolutionParams(r,o.executionTargetId);let e=await this.bus.requestOptional(t.resolve,u),i;if(e.handled)i=e.data.executionTarget;else if(u.executionTargetId!=null)throw Error(`Execution target resolver unavailable for explicit target '${u.executionTargetId}'`);else i=P;if(i.type!==`local`)return this.failSpawn(n,r,`adapter_start`,`Execution target type '${i.type}' is not yet supported for subagents`);l=u.executionTargetId??void 0}catch(e){return this.failSpawn(n,r,`adapter_start`,e)}let d;try{d=await this.createChildSessionForSpawn(n,r,o,l,u,a)}catch(e){return this.failSpawn(n,r,`session_create`,e)}let f=this.manager.get(n);if(!(f&&this.isTerminalSubagentStatus(f.status)))try{await this.startAdapterForSubagent(s,o,d,i)}catch(e){return this.failSpawn(n,r,`adapter_start`,e)}}async createChildSessionForSpawn(e,t,n,r,i,a){let{sessionId:s}=await this.bus.request(o.create,this.buildChildSessionCreatePayload(t,n,r,a));return this.manager.setChildSessionId(e,s),this.pendingChildSessionClose.has(e)&&await this.closeChildSession(e),s}async startAdapterForSubagent(e,t,n,i){let{adapterId:a}=await this.bus.request(h.resolveId,{adapterName:e,...this.machineId!==void 0&&{machineId:this.machineId}}),o=t.providerContext;if(o?.state===`resolved`&&t.providerConfigId!==void 0&&t.providerConfigId!==o.providerConfigId)throw Error(`Subagent providerConfigId "${t.providerConfigId}" does not match its resolved provider context "${o.providerConfigId}".`);if(o?.state===`unresolved`&&t.providerConfigId!==void 0)throw new g(`provider-context-unresolved`,e,t.providerConfigId);let s=o??(t.providerConfigId?await _(this.bus,{adapterName:e,providerConfigId:t.providerConfigId}):void 0),c=await this.bus.request(r.startAgent,{adapterId:a,role:`lead`,...s!==void 0&&{providerContext:s},sessionId:n,initialMessage:i,model:t.model,reasoningEffort:t.reasoningEffort,systemPrompt:t.systemPrompt,responseSchema:t.responseSchema,allowedTools:t.tools,disallowedTools:t.disallowedTools,allowedDirectories:t.allowedDirectories,...t.harnessId!==void 0&&{harnessId:t.harnessId}});if(!c||c.success!==!0)throw Error(c?.message??`Adapter start failed`)}async failSpawn(e,t,n,r){let i=r instanceof Error?r:Error(String(r));this.manager.markFailed(e,i.message);let[a,o]=await Promise.allSettled([this.manager.get(e)?.childSessionId===void 0?Promise.resolve():this.requestChildSessionClose(e),this.emitExecutionFailed(e,t,n,i)]),s=[];if(a.status===`rejected`&&s.push(new F(`child-session-close-failed`)),o.status===`rejected`&&s.push(new F(`failure-publication-failed`)),s.length>0)throw AggregateError([i,...s],`Subagent spawn failed and failure finalization also failed.`);return i.message}async buildExecutionTargetResolutionParams(t,n){if(n!==void 0)return{executionTargetId:n};let{session:r}=await this.bus.request(e.get,{sessionId:t});if(!r)throw Error(`Parent session not found: ${t}`);return{executionTargetId:r.executionTargetId}}buildChildSessionCreatePayload(e,t,n,r){return{branchKind:`subagent`,parentSessionId:e,contextInheritance:t.contextMode===`fork`?`parent-history`:`none`,...n!==void 0&&{executionTargetId:n},...r!==void 0&&{spawningToolCallId:r}}}async handleExecute(e){let t=c.parse({...e.config,task:e.task});this.manager.track({subagentId:e.subagentId,parentSessionId:e.parentSessionId,config:t,depth:e.depth});let n=await this.handleSpawned({subagentId:e.subagentId,parentSessionId:e.parentSessionId,task:e.task,config:t,depth:e.depth});return n?{success:!1,error:n}:{success:!0}}async handleToChild(e){let{subagentId:t,content:n}=e,r=this.manager.get(t);if(!r){console.warn(`[SubagentService] No subagent found: ${t}`);return}if(!r.childSessionId){console.warn(`[SubagentService] No child session for subagent: ${t}`);return}try{await this.bus.request(o.sendMessage,{sessionId:r.childSessionId,message:n,source:`system`})}catch(e){console.error(`[SubagentService] Failed to route message to child session:`,e)}}async handleCompleted(e){await this.closeChildSession(e)}async handleCancelled(e){await this.closeChildSession(e)}async closeChildSession(e){try{await this.requestChildSessionClose(e)}catch{console.error(`[SubagentService] Failed to close child session for subagent ${e}:`,new F(`child-session-close-failed`))}}async requestChildSessionClose(e){let t=this.manager.get(e);if(t){if(!t.childSessionId){this.pendingChildSessionClose.add(e);return}this.pendingChildSessionClose.delete(e),await this.bus.request(o.close,{sessionId:t.childSessionId})}}isTerminalSubagentStatus(e){return e===`completed`||e===`failed`||e===`cancelled`}handleAdapterSessionClosed(e){for(let t of this.manager.getAllNonTerminal())if(t.childSessionId===e){console.warn(`[SubagentService] Adapter session closed for subagent ${t.subagentId}: ${e}`),this.manager.markFailed(t.subagentId,`adapter-session-closed`);return}}async handleAgentComplete(e){let{sessionId:t,outcome:n,message:r,error:i}=e;if(t)for(let e of this.manager.getAllNonTerminal()){if(e.childSessionId!==t)continue;if((e.config.completion??`tool`)!==`turn`||e.status===`waiting_input`)return;let a=n??`completed`;if(a===`completed`){try{this.manager.markCompleted(e.subagentId,r??``,void 0,`turn`)}catch{return}await this.bus.emit(d.completed,{subagentId:e.subagentId,success:!0,result:r??``})}else if(a===`error`){let t=i??`agent turn error`;this.manager.markFailed(e.subagentId,t),await this.bus.emit(d.completed,{subagentId:e.subagentId,success:!1,error:t})}return}}isRemoteDelegationAllowed(e){return e.origin.local||y(e.transport?.peer,this.delegationAllowSet)}async emitExecutionFailed(e,t,n,r){let i=r instanceof Error?r.message:String(r);await this.bus.emit(d.executionFailed,{subagentId:e,parentSessionId:t,phase:n,error:i})}};const L=p(`subagent-service`),R={name:L.name,displayName:`Subagent Service`,version:`0.1.0`,critical:!0,surface:`headless`,dependencies:[f(`session`)],create:e=>new I(e.bus,a,e.machineId)};export{C as a,I as i,R as n,y as o,F as r,L as t};
@@ -1 +0,0 @@
1
- import{a as e}from"./visibility-Cb62p9bv.mjs";import"./model-uE5IyUFJ.mjs";import{p as t}from"./shared-RP_KARKF.mjs";import{t as n}from"./provider-context-DOsjOjiR.mjs";import{z as r}from"zod";const i=r.enum([`fork`,`fresh`]),a=r.enum([`spawning`,`running`,`waiting_input`,`hung`,`completed`,`failed`,`cancelled`]),o=r.enum([`tool`,`turn`]),s=r.object({task:r.string(),adapterName:r.string().optional(),providerConfigId:r.string().optional(),providerContext:n.optional(),harnessId:r.string().optional(),model:r.string().optional(),reasoningEffort:e.optional(),contextMode:i.default(`fork`),tools:r.array(r.string()).optional(),disallowedTools:r.array(r.string()).optional(),allowedDirectories:r.array(r.string()).optional(),systemPrompt:r.string().optional(),maxDepth:r.number().optional(),responseSchema:t.optional(),executionTargetId:r.string().optional(),completion:o.optional()}),c=r.object({maxDepth:r.number().default(3),maxConcurrentPerSession:r.number().default(10),maxTotalActive:r.number().default(50),defaultRequestTimeoutMs:r.number().default(6e4),defaultAwaitTimeoutMs:r.number().default(3e5),stateRetentionMs:r.number().default(1800*1e3),inactivityTimeoutMs:r.number().int().nonnegative().default(0),sweepIntervalMs:r.number().int().nonnegative().default(6e4),allowedAdapters:r.array(r.string()).default([]),allowedModels:r.array(r.string()).default([])}).parse({}),l=r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number()}),u=r.object({messageId:r.string(),question:r.string(),context:r.string().optional()}),d=r.object({subagentId:r.string(),parentSessionId:r.string(),task:r.string(),config:s,depth:r.number()}),f=r.object({success:r.boolean(),agentId:r.string().optional(),error:r.string().optional()}),p=r.object({subagentId:r.string(),parentSessionId:r.string(),error:r.string(),phase:r.enum([`session_create`,`adapter_start`,`agent_start`])}),m=r.object({parentSessionId:r.string(),config:s,depth:r.number(),spawningToolCallId:r.string().optional()}),h=r.object({subagentId:r.string(),status:r.literal(`spawning`)}),g=r.object({subagentId:r.string(),timeoutMs:r.number().optional()}),_=r.object({status:r.enum([`completed`,`failed`,`waiting_input`,`timeout`,`cancelled`]),result:r.string().optional(),error:r.string().optional(),pendingRequest:u.optional(),completionSource:o.optional()}),v=r.object({subagentId:r.string(),content:r.string(),inResponseTo:r.string().optional()}),y=r.object({sent:r.boolean(),resolvedPending:r.boolean()}),b=r.object({subagentId:r.string(),reason:r.string().optional()}),x=r.object({killed:r.boolean()}),S=r.object({subagentId:r.string(),update:r.string(),percentComplete:r.number().optional()}),C=r.object({reported:r.boolean()}),w=r.object({subagentId:r.string(),question:r.string(),context:r.string().optional(),timeoutMs:r.number().optional()}),T=r.object({responded:r.boolean(),response:r.string().optional(),timedOut:r.boolean()}),E=r.object({subagentId:r.string(),result:r.string(),summary:r.string().optional()}),D=r.object({completed:r.boolean()}),O=r.object({subagentId:r.string(),task:r.string(),status:a}),k=r.object({parentSessionId:r.string()}),A=r.object({subagents:r.array(O)});export{s as C,l as E,h as S,a as T,w as _,o as a,y as b,d as c,x as d,k as f,C as g,S as h,D as i,f as l,u as m,_ as n,i as o,A as p,E as r,c as s,g as t,b as u,T as v,p as w,m as x,v as y};
@@ -1 +0,0 @@
1
- import{t as e}from"./chunk-DTipWd-i.mjs";var t=e(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),n=e(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),r=e(((e,r)=>{let{MAX_SAFE_COMPONENT_LENGTH:i,MAX_SAFE_BUILD_LENGTH:a,MAX_LENGTH:o}=t(),s=n();e=r.exports={};let c=e.re=[],l=e.safeRe=[],u=e.src=[],d=e.safeSrc=[],f=e.t={},p=0,m=`[a-zA-Z0-9-]`,h=[[`\\s`,1],[`\\d`,o],[m,a]],g=e=>{for(let[t,n]of h)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},_=(e,t,n)=>{let r=g(t),i=p++;s(e,i,t),f[e]=i,u[i]=t,d[i]=r,c[i]=new RegExp(t,n?`g`:void 0),l[i]=new RegExp(r,n?`g`:void 0)};_(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),_(`NUMERICIDENTIFIERLOOSE`,`\\d+`),_(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${m}*`),_(`MAINVERSION`,`(${u[f.NUMERICIDENTIFIER]})\\.(${u[f.NUMERICIDENTIFIER]})\\.(${u[f.NUMERICIDENTIFIER]})`),_(`MAINVERSIONLOOSE`,`(${u[f.NUMERICIDENTIFIERLOOSE]})\\.(${u[f.NUMERICIDENTIFIERLOOSE]})\\.(${u[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASEIDENTIFIER`,`(?:${u[f.NONNUMERICIDENTIFIER]}|${u[f.NUMERICIDENTIFIER]})`),_(`PRERELEASEIDENTIFIERLOOSE`,`(?:${u[f.NONNUMERICIDENTIFIER]}|${u[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASE`,`(?:-(${u[f.PRERELEASEIDENTIFIER]}(?:\\.${u[f.PRERELEASEIDENTIFIER]})*))`),_(`PRERELEASELOOSE`,`(?:-?(${u[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[f.PRERELEASEIDENTIFIERLOOSE]})*))`),_(`BUILDIDENTIFIER`,`${m}+`),_(`BUILD`,`(?:\\+(${u[f.BUILDIDENTIFIER]}(?:\\.${u[f.BUILDIDENTIFIER]})*))`),_(`FULLPLAIN`,`v?${u[f.MAINVERSION]}${u[f.PRERELEASE]}?${u[f.BUILD]}?`),_(`FULL`,`^${u[f.FULLPLAIN]}$`),_(`LOOSEPLAIN`,`[v=\\s]*${u[f.MAINVERSIONLOOSE]}${u[f.PRERELEASELOOSE]}?${u[f.BUILD]}?`),_(`LOOSE`,`^${u[f.LOOSEPLAIN]}$`),_(`GTLT`,`((?:<|>)?=?)`),_(`XRANGEIDENTIFIERLOOSE`,`${u[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),_(`XRANGEIDENTIFIER`,`${u[f.NUMERICIDENTIFIER]}|x|X|\\*`),_(`XRANGEPLAIN`,`[v=\\s]*(${u[f.XRANGEIDENTIFIER]})(?:\\.(${u[f.XRANGEIDENTIFIER]})(?:\\.(${u[f.XRANGEIDENTIFIER]})(?:${u[f.PRERELEASE]})?${u[f.BUILD]}?)?)?`),_(`XRANGEPLAINLOOSE`,`[v=\\s]*(${u[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[f.XRANGEIDENTIFIERLOOSE]})(?:${u[f.PRERELEASELOOSE]})?${u[f.BUILD]}?)?)?`),_(`XRANGE`,`^${u[f.GTLT]}\\s*${u[f.XRANGEPLAIN]}$`),_(`XRANGELOOSE`,`^${u[f.GTLT]}\\s*${u[f.XRANGEPLAINLOOSE]}$`),_(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${i}})(?:\\.(\\d{1,${i}}))?(?:\\.(\\d{1,${i}}))?`),_(`COERCE`,`${u[f.COERCEPLAIN]}(?:$|[^\\d])`),_(`COERCEFULL`,u[f.COERCEPLAIN]+`(?:${u[f.PRERELEASE]})?(?:${u[f.BUILD]})?(?:$|[^\\d])`),_(`COERCERTL`,u[f.COERCE],!0),_(`COERCERTLFULL`,u[f.COERCEFULL],!0),_(`LONETILDE`,`(?:~>?)`),_(`TILDETRIM`,`(\\s*)${u[f.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,_(`TILDE`,`^${u[f.LONETILDE]}${u[f.XRANGEPLAIN]}$`),_(`TILDELOOSE`,`^${u[f.LONETILDE]}${u[f.XRANGEPLAINLOOSE]}$`),_(`LONECARET`,`(?:\\^)`),_(`CARETTRIM`,`(\\s*)${u[f.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,_(`CARET`,`^${u[f.LONECARET]}${u[f.XRANGEPLAIN]}$`),_(`CARETLOOSE`,`^${u[f.LONECARET]}${u[f.XRANGEPLAINLOOSE]}$`),_(`COMPARATORLOOSE`,`^${u[f.GTLT]}\\s*(${u[f.LOOSEPLAIN]})$|^$`),_(`COMPARATOR`,`^${u[f.GTLT]}\\s*(${u[f.FULLPLAIN]})$|^$`),_(`COMPARATORTRIM`,`(\\s*)${u[f.GTLT]}\\s*(${u[f.LOOSEPLAIN]}|${u[f.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,_(`HYPHENRANGE`,`^\\s*(${u[f.XRANGEPLAIN]})\\s+-\\s+(${u[f.XRANGEPLAIN]})\\s*$`),_(`HYPHENRANGELOOSE`,`^\\s*(${u[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[f.XRANGEPLAINLOOSE]})\\s*$`),_(`STAR`,`(<|>)?=?\\s*\\*`),_(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),_(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),i=e(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),a=e(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),o=e(((e,o)=>{let s=n(),{MAX_LENGTH:c,MAX_SAFE_INTEGER:l}=t(),{safeRe:u,t:d}=r(),f=i(),{compareIdentifiers:p}=a();o.exports=class e{constructor(t,n){if(n=f(n),t instanceof e){if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>c)throw TypeError(`version is longer than ${c} characters`);s(`SemVer`,t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let r=t.trim().match(n.loose?u[d.LOOSE]:u[d.FULL]);if(!r)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>l||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>l||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>l||this.patch<0)throw TypeError(`Invalid patch version`);r[4]?this.prerelease=r[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<l)return t}return e}):this.prerelease=[],this.build=r[5]?r[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(s(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{let e=this.prerelease[n],r=t.prerelease[n];if(s(`prerelease compare`,n,e,r),e===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;if(e===r)continue;return p(e,r)}while(++n)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let n=0;do{let e=this.build[n],r=t.build[n];if(s(`build compare`,n,e,r),e===void 0&&r===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;if(e===r)continue;return p(e,r)}while(++n)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?u[d.PRERELEASELOOSE]:u[d.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),p(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),s=e(((e,t)=>{let n=o();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),c=e(((e,t)=>{let n=s();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),l=e(((e,t)=>{let n=s();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),u=e(((e,t)=>{let n=o();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),d=e(((e,t)=>{let n=s();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),f=e(((e,t)=>{let n=o();t.exports=(e,t)=>new n(e,t).major})),p=e(((e,t)=>{let n=o();t.exports=(e,t)=>new n(e,t).minor})),m=e(((e,t)=>{let n=o();t.exports=(e,t)=>new n(e,t).patch})),h=e(((e,t)=>{let n=s();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),g=e(((e,t)=>{let n=o();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),_=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(t,e,r)})),v=e(((e,t)=>{let n=g();t.exports=(e,t)=>n(e,t,!0)})),y=e(((e,t)=>{let n=o();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),b=e(((e,t)=>{let n=y();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),x=e(((e,t)=>{let n=y();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),S=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)>0})),C=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)<0})),w=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)===0})),T=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)!==0})),E=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)>=0})),D=e(((e,t)=>{let n=g();t.exports=(e,t,r)=>n(e,t,r)<=0})),O=e(((e,t)=>{let n=w(),r=T(),i=S(),a=E(),o=C(),s=D();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),k=e(((e,t)=>{let n=o(),i=s(),{safeRe:a,t:c}=r();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?a[c.COERCEFULL]:a[c.COERCE]);else{let n=t.includePrerelease?a[c.COERCERTLFULL]:a[c.COERCERTL],i;for(;(i=n.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||i.index+i[0].length!==r.index+r[0].length)&&(r=i),n.lastIndex=i.index+i[1].length+i[2].length;n.lastIndex=-1}if(r===null)return null;let o=r[2];return i(`${o}.${r[3]||`0`}.${r[4]||`0`}${t.includePrerelease&&r[5]?`-${r[5]}`:``}${t.includePrerelease&&r[6]?`+${r[6]}`:``}`,t)}})),A=e(((e,n)=>{let r=s(),i=t(),a=o(),c=(e,t,n)=>{if(!i.RELEASE_TYPES.includes(t))return null;let r=l(e,n);return r&&u(r,t)},l=(e,t)=>r(e instanceof a?e.version:e,t),u=(e,t)=>{if(d(t))return e.version;switch(e.prerelease=[],t){case`major`:e.minor=0,e.patch=0;break;case`minor`:e.patch=0;break}return e.format()},d=e=>e.startsWith(`pre`);n.exports=c})),j=e(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),M=e(((e,a)=>{let s=/\s+/g;a.exports=class e{constructor(t,n){if(n=l(n),t instanceof e)return t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease?t:new e(t.raw,n);if(t instanceof u)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=t.trim().replace(s,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!b(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&x(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&v)|(this.options.loose&&y))+`:`+e,n=c.get(t);if(n)return n;let r=this.options.loose,i=r?p[m.HYPHENRANGELOOSE]:p[m.HYPHENRANGE];e=e.replace(i,F(this.options.includePrerelease)),d(`hyphen replace`,e),e=e.replace(p[m.COMPARATORTRIM],h),d(`comparator trim`,e),e=e.replace(p[m.TILDETRIM],g),d(`tilde trim`,e),e=e.replace(p[m.CARETTRIM],_),d(`caret trim`,e);let a=e.split(` `).map(e=>C(e,this.options)).join(` `).split(/\s+/).map(e=>P(e,this.options));r&&(a=a.filter(e=>(d(`loose invalid filter`,e,this.options),!!e.match(p[m.COMPARATORLOOSE])))),d(`range list`,a);let o=new Map,s=a.map(e=>new u(e,this.options));for(let e of s){if(b(e))return[e];o.set(e.value,e)}o.size>1&&o.has(``)&&o.delete(``);let l=[...o.values()];return c.set(t,l),l}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>S(e,n)&&t.set.some(t=>S(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new f(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(I(this.set[t],e,this.options))return!0;return!1}};let c=new(j()),l=i(),u=N(),d=n(),f=o(),{safeRe:p,t:m,comparatorTrimReplace:h,tildeTrimReplace:g,caretTrimReplace:_}=r(),{FLAG_INCLUDE_PRERELEASE:v,FLAG_LOOSE:y}=t(),b=e=>e.value===`<0.0.0-0`,x=e=>e.value===``,S=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},C=(e,t)=>(e=e.replace(p[m.BUILD],``),d(`comp`,e,t),e=D(e,t),d(`caret`,e),e=T(e,t),d(`tildes`,e),e=k(e,t),d(`xrange`,e),e=M(e,t),d(`stars`,e),e),w=e=>!e||e.toLowerCase()===`x`||e===`*`,T=(e,t)=>e.trim().split(/\s+/).map(e=>E(e,t)).join(` `),E=(e,t)=>{let n=t.loose?p[m.TILDELOOSE]:p[m.TILDE];return e.replace(n,(t,n,r,i,a)=>{d(`tilde`,e,t,n,r,i,a);let o;return w(n)?o=``:w(r)?o=`>=${n}.0.0 <${+n+1}.0.0-0`:w(i)?o=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(d(`replaceTilde pr`,a),o=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):o=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,d(`tilde return`,o),o})},D=(e,t)=>e.trim().split(/\s+/).map(e=>O(e,t)).join(` `),O=(e,t)=>{d(`caret`,e,t);let n=t.loose?p[m.CARETLOOSE]:p[m.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,o)=>{d(`caret`,e,t,n,i,a,o);let s;return w(n)?s=``:w(i)?s=`>=${n}.0.0${r} <${+n+1}.0.0-0`:w(a)?s=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:o?(d(`replaceCaret pr`,o),s=n===`0`?i===`0`?`>=${n}.${i}.${a}-${o} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${o} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${o} <${+n+1}.0.0-0`):(d(`no pr`),s=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),d(`caret return`,s),s})},k=(e,t)=>(d(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>A(e,t)).join(` `)),A=(e,t)=>{e=e.trim();let n=t.loose?p[m.XRANGELOOSE]:p[m.XRANGE];return e.replace(n,(n,r,i,a,o,s)=>{d(`xRange`,e,n,r,i,a,o,s);let c=w(i),l=c||w(a),u=l||w(o),f=u;return r===`=`&&f&&(r=``),s=t.includePrerelease?`-0`:``,c?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(l&&(a=0),o=0,r===`>`?(r=`>=`,l?(i=+i+1,a=0,o=0):(a=+a+1,o=0)):r===`<=`&&(r=`<`,l?i=+i+1:a=+a+1),r===`<`&&(s=`-0`),n=`${r+i}.${a}.${o}${s}`):l?n=`>=${i}.0.0${s} <${+i+1}.0.0-0`:u&&(n=`>=${i}.${a}.0${s} <${i}.${+a+1}.0-0`),d(`xRange return`,n),n})},M=(e,t)=>(d(`replaceStars`,e,t),e.trim().replace(p[m.STAR],``)),P=(e,t)=>(d(`replaceGTE0`,e,t),e.trim().replace(p[t.includePrerelease?m.GTE0PRE:m.GTE0],``)),F=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=w(r)?``:w(i)?`>=${r}.0.0${e?`-0`:``}`:w(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=w(l)?``:w(u)?`<${+l+1}.0.0-0`:w(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),I=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(d(e[n].semver),e[n].semver!==u.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),N=e(((e,t)=>{let a=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return a}constructor(t,n){if(n=s(n),t instanceof e){if(t.loose===!!n.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),d(`comparator`,t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===a?this.value=``:this.value=this.operator+this.semver.version,d(`comp`,this)}parse(e){let t=this.options.loose?c[l.COMPARATORLOOSE]:c[l.COMPARATOR],n=e.match(t);if(!n)throw TypeError(`Invalid comparator: ${e}`);this.operator=n[1]===void 0?``:n[1],this.operator===`=`&&(this.operator=``),n[2]?this.semver=new f(n[2],this.options.loose):this.semver=a}toString(){return this.value}test(e){if(d(`Comparator.test`,e,this.options.loose),this.semver===a||e===a)return!0;if(typeof e==`string`)try{e=new f(e,this.options)}catch{return!1}return u(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new p(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new p(this.value,n).test(t.semver):(n=s(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||u(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||u(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let s=i(),{safeRe:c,t:l}=r(),u=O(),d=n(),f=o(),p=M()})),P=e(((e,t)=>{let n=M();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),F=e(((e,t)=>{let n=M();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),I=e(((e,t)=>{let n=o(),r=M();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),L=e(((e,t)=>{let n=o(),r=M();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),R=e(((e,t)=>{let n=o(),r=M(),i=S();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),z=e(((e,t)=>{let n=M();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),B=e(((e,t)=>{let n=o(),r=N(),{ANY:i}=r,a=M(),s=P(),c=S(),l=C(),u=D(),d=E();t.exports=(e,t,o,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(o){case`>`:p=c,m=u,h=l,g=`>`,_=`>=`;break;case`<`:p=l,m=d,h=c,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(s(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),V=e(((e,t)=>{let n=B();t.exports=(e,t,r)=>n(e,t,`>`,r)})),H=e(((e,t)=>{let n=B();t.exports=(e,t,r)=>n(e,t,`<`,r)})),U=e(((e,t)=>{let n=M();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),W=e(((e,t)=>{let n=P(),r=g();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),G=e(((e,t)=>{let n=M(),r=N(),{ANY:i}=r,a=P(),o=g(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),K=e(((e,n)=>{let i=r(),j=t(),K=o(),q=a();n.exports={parse:s(),valid:c(),clean:l(),inc:u(),diff:d(),major:f(),minor:p(),patch:m(),prerelease:h(),compare:g(),rcompare:_(),compareLoose:v(),compareBuild:y(),sort:b(),rsort:x(),gt:S(),lt:C(),eq:w(),neq:T(),gte:E(),lte:D(),cmp:O(),coerce:k(),truncate:A(),Comparator:N(),Range:M(),satisfies:P(),toComparators:F(),maxSatisfying:I(),minSatisfying:L(),minVersion:R(),validRange:z(),outside:B(),gtr:V(),ltr:H(),intersects:U(),simplifyRange:W(),subset:G(),SemVer:K,re:i.re,src:i.src,tokens:i.t,SEMVER_SPEC_VERSION:j.SEMVER_SPEC_VERSION,RELEASE_TYPES:j.RELEASE_TYPES,compareIdentifiers:q.compareIdentifiers,rcompareIdentifiers:q.rcompareIdentifiers}}));export{K as t};
@@ -1 +0,0 @@
1
- import{C as e,g as t,w as n}from"./artifact-CGjnoyCC.mjs";import{i as r,r as i,t as a}from"./json-value-DmU8ibo_.mjs";import{a as o}from"./visibility-Cb62p9bv.mjs";import"./model-uE5IyUFJ.mjs";import{t as s}from"./provider-context-DOsjOjiR.mjs";import{a as c,o as l}from"./schemas-D6lj9NMg.mjs";import{z as u}from"zod";import{createBusNamespace as d,getFullSubjectForSubjectDefinition as f,observability as p}from"@makaio/framework/core";const m=u.enum([`wait-in-process`,`exit-and-redispatch`,`exit-and-resume`]),ee=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`path`),path:u.string().min(1)}).strict(),u.object({kind:u.literal(`source`),filename:u.string().min(1),source:u.string()}).strict()]),h=u.object({source:ee.optional(),requirements:u.object({isolation:u.enum([`local`,`container`,`remote`]).optional(),capabilities:u.array(u.string()).optional()}).catchall(r).optional(),providers:u.record(u.string(),r).optional()}).catchall(r),g=u.object({kind:u.string().min(1),id:u.string().min(1)});function te(e){return`${re(e.kind)}:${re(e.id)}`}function ne(e){let t=ie(e);if(t<1)throw Error(`Invalid artifact ref key: ${e}`);let n=ae(e.slice(t+1));if(n.length===0)throw Error(`Invalid artifact ref key (empty id): ${e}`);return{kind:ae(e.slice(0,t)),id:n}}function re(e){return e.replace(/\\/g,`\\\\`).replace(/:/g,`\\:`)}function ie(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(t){t=!1;continue}if(r===`\\`){t=!0;continue}if(r===`:`)return n}return-1}function ae(e){let t=``,n=!1;for(let r of e){if(n){if(r!==`\\`&&r!==`:`)throw Error(`Invalid artifact ref key component: ${e}`);t+=r,n=!1;continue}if(r===`\\`){n=!0;continue}t+=r}if(n)throw Error(`Invalid artifact ref key component: ${e}`);return t}const _=u.union([u.string(),u.number(),u.boolean(),u.null()]),oe=u.union([_,u.object({$in:u.array(_)}).strict(),u.object({$ne:_}).strict(),u.object({$exists:u.boolean()}).strict(),u.object({$startsWith:u.string()}).strict(),u.object({$endsWith:u.string()}).strict()]),se=u.record(u.string(),oe),ce=u.object({type:u.literal(`bus-event`),subject:u.string(),filter:se.optional(),filterExpression:u.string().optional()}),v=u.object({type:u.literal(`extension`),extensionType:u.string().regex(/^[a-z0-9-]+:[a-z0-9._-]+$/),config:a.optional()}),y=u.discriminatedUnion(`type`,[u.object({type:u.literal(`manual`)}),u.object({type:u.literal(`cron`),schedule:u.string(),timezone:u.string().optional()}),u.object({type:u.literal(`webhook`),event:u.string(),branch:u.string().optional(),repo:u.string().optional()}),v,ce]),b=u.discriminatedUnion(`type`,[u.object({type:u.literal(`global`)}).strict(),u.object({type:u.literal(`workspace`),id:u.string().min(1)}).strict(),u.object({type:u.literal(`session`),id:u.string().min(1)}).strict(),u.object({type:u.literal(`external`),kind:u.string().min(1),id:u.string().min(1)}).strict()]),x=u.string().min(1),S=u.object({kind:u.string().min(1),schemaVersion:u.string().min(1),scope:n,resolve:u.string().min(1).optional(),create:u.string().min(1).optional(),statusPath:u.string().min(1).optional()}),le=u.object({kind:u.string().min(1),schemaVersion:u.string().min(1),scope:n,dataExpression:u.string().optional()}),ue=u.object({file:u.string().min(1),line:u.number().int().positive().optional(),column:u.number().int().positive().optional()}),C=u.enum([`station`,`delegate-agent`,`delegate-role`,`parallel`,`gate`,`iterate`,`iterate-chain`,`loop`,`sequence`]),de=u.enum([`all-settled`,`fail-fast`]),w=u.object({id:u.string().min(1),when:x.optional(),skip:x.optional(),writes:u.array(le).optional()}),T=u.lazy(()=>u.discriminatedUnion(`type`,[D,fe,pe,me,he,ge,_e,ye,E])),E=w.extend({type:u.literal(`sequence`),nodes:u.lazy(()=>u.array(T))}),D=w.extend({type:u.literal(`station`),prompt:u.string().min(1),role:u.string().min(1).optional(),outputSchema:i.optional(),timeoutMs:u.number().int().positive().optional(),completion:c.optional()}),fe=w.extend({type:u.literal(`delegate-agent`),agentId:u.string().min(1),inputExpression:u.string().optional(),outputSchema:i.optional()}),pe=w.extend({type:u.literal(`delegate-role`),role:u.string().min(1),prompt:u.string().min(1),outputSchema:i.optional(),timeoutMs:u.number().int().positive().optional(),completion:c.optional()}),me=w.extend({type:u.literal(`parallel`),mode:de.optional(),branches:u.record(u.string().min(1),u.lazy(()=>E))}),he=w.extend({type:u.literal(`gate`),prompt:u.string().min(1),title:u.string().optional(),autoAction:u.enum([`approve`,`reject`]),timeoutMs:u.number().int().positive().nullable(),resumeSchema:i.optional()}),ge=w.extend({type:u.literal(`iterate`),collection:u.string().min(1),body:u.lazy(()=>E),concurrency:u.number().int().nonnegative().optional()}),_e=w.extend({type:u.literal(`iterate-chain`),collection:u.string().min(1),body:u.lazy(()=>E)}),ve=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`pass`)}).strict(),u.object({kind:u.literal(`loop`)}).strict(),u.object({kind:u.literal(`escalate`),reason:u.string().min(1)}).strict()]),ye=w.extend({type:u.literal(`loop`),maxRounds:u.number().int().positive(),body:u.lazy(()=>E),gate:u.object({handler:u.string().min(1),input:u.string().min(1).optional(),config:r.optional(),escalation:u.object({title:u.string().optional(),prompt:u.string().min(1),resumeSchema:i.optional(),autoAction:u.enum([`approve`,`reject`]).default(`reject`),timeoutMs:u.number().int().positive().nullable().default(null)}).strict().optional()}).strict()}),be=u.object({factoryId:u.string().min(1),preview:u.array(u.lazy(()=>T)).optional(),sourceLocation:ue.optional()}),xe=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`editor`)}).strict(),u.object({kind:u.literal(`extension`),extension:u.string().min(1),externalId:u.string().min(1).optional(),syncedAt:u.string().datetime().optional(),metadata:a.default({})}).strict()]),Se=u.object({schema:i,initial:r.optional()}),O=u.object({id:u.string().min(1),name:u.string().optional(),description:u.string().optional(),inputSchema:i.optional(),configSchema:i.optional(),outputSchema:i.optional(),state:Se.optional(),artifact:S.optional(),root:E,triggers:u.array(y).optional(),scope:b.default({type:`global`}),canvasLayout:u.record(u.string(),r).optional(),source:xe.optional(),executionHints:h.optional()}),k=u.enum([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]),A=u.object({id:u.string(),workflowId:u.string(),coordinatorSessionId:u.string().optional(),status:k,inputs:r,config:a.optional(),startedAt:u.number(),completedAt:u.number().optional(),error:u.string().optional(),reason:u.string().optional(),triggerPayload:a.optional(),scope:b,artifactRef:g.optional()}),j=u.object({frameId:u.string(),nodeId:u.string(),nodeType:C,path:u.array(u.string()),parentFrameId:u.string().optional(),status:u.enum([`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]),attempt:u.number().int().nonnegative().default(0),iteration:u.number().int().nonnegative().optional(),branchKey:u.string().optional(),output:r.optional(),error:u.string().optional(),startedAt:u.number().optional(),completedAt:u.number().optional()}),M=u.enum([`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]),N=u.object({executionId:u.string(),nodeId:u.string(),frameId:u.string(),schema:i,prompt:u.string().optional(),status:M,autoAction:u.enum([`approve`,`reject`]),timeoutMs:u.number().int().positive().nullable(),resumeData:r.optional(),reason:u.string().optional(),createdAt:u.number(),resolvedAt:u.number().optional()}),P=u.object({adapterName:u.string().min(1),model:u.string().optional(),reasoningEffort:o.optional(),harnessId:u.string().optional(),systemPrompt:u.string().optional(),contextMode:l.optional(),providerContext:s.optional(),completion:c.optional()}),Ce=P,we=u.object({scope:b.optional()}),Te=u.object({startedAt:u.number(),id:u.string()}),Ee=1,De=500,Oe=50,ke=u.object({workflowId:u.string().min(1).optional(),scope:b.optional(),status:k.optional(),artifactRef:g.optional(),limit:u.number().int().min(1).max(500).default(50),cursor:Te.optional()}).refine(e=>e.workflowId!==void 0||e.scope!==void 0||e.artifactRef!==void 0,{message:`Either workflowId, scope, or artifactRef is required.`}),Ae=200,je=100,Me=10,Ne=u.object({refs:u.array(g).min(1).max(200),limitPerRef:u.number().int().min(1).max(100).default(10)}),Pe=u.object({executionId:u.string().min(1).optional(),status:M.optional(),limit:u.number().int().min(1).max(500).default(50)}).refine(e=>e.executionId!==void 0||e.status!==void 0,{message:`Either executionId or status is required.`}),F=u.enum([`station`,`delegate-agent`,`delegate-role`,`gate`]),Fe=u.enum([`station`]),Ie=u.object({input:u.number().int().nonnegative(),output:u.number().int().nonnegative(),cached:u.number().int().nonnegative().optional()}),Le=u.object({duration:u.number().nonnegative(),tokenUsage:Ie.optional(),estimatedCost:u.number().nonnegative().optional(),toolCalls:u.number().int().nonnegative().optional()}),Re=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`none`)}).strict(),u.object({kind:u.literal(`hmac`),secret:u.string().min(1)}).strict()]),ze=u.object({cwd:u.string().min(1),env:u.record(u.string(),u.string()).optional()}),Be=u.object({executionId:u.string().min(1),stepId:u.string().min(1),reason:u.string().optional()});function Ve(e){let t=e.indexOf(`.`);if(t<=0||t===e.length-1)throw Error(`Invalid step cancel subject: ${e}`);return{subject:e.slice(t+1),$meta:{namespace:e.slice(0,t),isRequest:!1,payload:{},local:!1,channel:!1}}}const He=u.object({executionId:u.string().min(1),reason:u.string().optional()});function Ue(e){let t=e.indexOf(`.`);if(t<=0||t===e.length-1)throw Error(`Invalid workflow cancel subject: ${e}`);return{subject:e.slice(t+1),$meta:{namespace:e.slice(0,t),isRequest:!1,payload:{},local:!1,channel:!1}}}const We=u.object({stepId:u.string().min(1),executionId:u.string().min(1),workflowId:u.string().min(1),coordinatorSessionId:u.string().min(1),stepType:Fe,stepDefinition:D,resolvedInputs:a,busUrl:u.string().optional(),busAuth:Re.default({kind:`none`}),platformDefaults:ze,cancelSubject:u.string().min(1)}).superRefine((e,t)=>{e.stepType!==e.stepDefinition.type&&t.addIssue({code:`custom`,path:[`stepDefinition`,`type`],message:`stepDefinition.type must match stepType (${e.stepType})`})}),Ge=`Workflow cancelled`,Ke=u.object({status:u.enum([`completed`,`failed`]),output:r.optional(),error:u.string().optional(),telemetry:Le}),qe=u.enum([`running`,`completed`,`failed`,`skipped`]),I=u.object({executionId:u.string().min(1),frameId:u.string().min(1),stepId:u.string().min(1),stepType:F,status:qe,startedAt:u.number().optional(),completedAt:u.number().optional(),durationMs:u.number().nonnegative().optional(),inputTokens:u.number().int().nonnegative().optional(),outputTokens:u.number().int().nonnegative().optional(),estimatedCost:u.number().nonnegative().optional(),toolCallCount:u.number().int().nonnegative().optional(),input:u.string().optional(),output:u.string().optional()}),Je=u.enum([`triggered-by`,`feedback-loop`,`rerun-of`]),L=u.object({sourceExecutionId:u.string().min(1),targetExecutionId:u.string().min(1),linkType:Je,metadata:u.record(u.string(),u.unknown()).optional()}),Ye=u.object({sourceExecutionId:u.string().min(1).optional(),targetExecutionId:u.string().min(1).optional()}).refine(e=>e.sourceExecutionId!==void 0||e.targetExecutionId!==void 0,{message:`Either sourceExecutionId or targetExecutionId is required.`}),Xe={RUN_CONTEXT_NOT_FOUND:`WORKFLOW_RUN_CONTEXT_NOT_FOUND`,SNAPSHOT_UNAVAILABLE:`WORKFLOW_SNAPSHOT_UNAVAILABLE`,SOURCE_MISMATCH:`WORKFLOW_SOURCE_MISMATCH`,NOT_EXECUTABLE:`WORKFLOW_NOT_EXECUTABLE`,HANDLER_UNAVAILABLE:`WORKFLOW_HANDLER_UNAVAILABLE`};var Ze=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`WorkflowError`}};const R=u.string().refine(e=>e===``||e.startsWith(`/`),{message:`JSON Patch paths must be empty or start with "/".`}),Qe=u.object({op:u.enum([`add`,`replace`,`test`]),path:R,value:r}).strict(),$e=u.object({op:u.literal(`remove`),path:R}).strict(),et=u.object({op:u.enum([`move`,`copy`]),path:R,from:R}).strict(),z=u.discriminatedUnion(`op`,[Qe,$e,et]),tt=u.object({type:u.literal(`artifact-query`),query:t,select:u.enum([`latest`,`all`]),optional:u.boolean().optional()}),nt=u.object({type:u.literal(`bus-request`),subject:u.string().min(1),payload:u.record(u.string(),u.unknown()).optional(),optional:u.boolean().optional()}),rt=u.discriminatedUnion(`type`,[tt,nt]),it=u.object({type:u.literal(`artifact`),kind:u.string().min(1),schemaVersion:u.string().min(1),scope:n,metadata:u.record(u.string(),u.unknown()).optional()}),at=u.object({type:u.literal(`bus-event`),subject:u.string().min(1),payload:u.record(u.string(),u.unknown()).optional()}),ot=u.discriminatedUnion(`type`,[it,at]),st=u.object({content:u.string(),metadata:u.record(u.string(),u.unknown()).optional()}),ct=u.object({sources:u.record(u.string(),st)}),lt=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`none`)}).strict(),u.object({kind:u.literal(`hmac`),secret:u.string().min(1)}).strict()]),B=u.discriminatedUnion(`kind`,[u.object({kind:u.literal(`path`),path:u.string().min(1)}).strict(),u.object({kind:u.literal(`source`),filename:u.string().min(1),source:u.string()}).strict(),u.object({kind:u.literal(`definition`),workflowId:u.string().min(1)}).strict()]),ut=u.object({source:B,definition:O.optional(),executionId:u.string().min(1),workflowId:u.string().min(1),triggerPayload:a.default({}),inputs:r.default({}),config:a.optional(),artifactRef:g.optional(),scope:b.default({type:`global`}),busUrl:u.string().optional(),busAuth:lt.default({kind:`none`}),context:u.object({repoPath:u.string().min(1),makaioHome:u.string().min(1),os:u.enum([`darwin`,`linux`,`win32`]),arch:u.string().min(1),worktree:u.string().optional()}),env:u.record(u.string(),u.string()).default({}),coordinatorSessionId:u.string().min(1),executionHints:h.optional(),cancelSubject:u.string().min(1),suspensionStrategy:m.default(`wait-in-process`)}),V=u.object({executionId:u.string().min(1),workflowId:u.string().min(1)}),dt=u.discriminatedUnion(`status`,[V.extend({status:u.literal(`completed`),artifact:e.optional()}).strict(),V.extend({status:u.literal(`failed`),error:u.string().min(1)}).strict(),V.extend({status:u.literal(`cancelled`),reason:u.string().min(1).optional()}).strict(),V.extend({status:u.literal(`paused`),pausedAtGateId:u.string().min(1),pausedAtFrameId:u.string().min(1)}).strict()]),ft=u.object({name:u.string().min(1),importPath:u.string().min(1)}),pt=u.object({packages:u.array(ft).default([])}),mt=u.object({executionId:u.string().min(1),workflowId:u.string().min(1),source:B,definitionSnapshot:O.optional(),workerManifest:pt.default({packages:[]}),inputs:r.default({}),config:a.optional(),scope:b.default({type:`global`}),triggerPayload:a.default({}),artifactRef:g.optional(),coordinatorSessionId:u.string().min(1),executionHints:h.optional(),dispatchMetadata:a.optional(),cancelSubject:u.string().min(1),context:u.object({repoPath:u.string().min(1),makaioHome:u.string().min(1),os:u.enum([`darwin`,`linux`,`win32`]),arch:u.string().min(1),worktree:u.string().optional()}),env:u.record(u.string(),u.string()).default({}),createdAt:u.number(),suspensionStrategy:m.default(`wait-in-process`)}).superRefine((e,t)=>{e.source.kind===`definition`&&e.definitionSnapshot===void 0&&t.addIssue({code:u.ZodIssueCode.custom,path:[`definitionSnapshot`],message:`definitionSnapshot is required when source.kind is "definition"`})}),H=u.object({executionId:u.string().min(1),workflowId:u.string().min(1),workflowName:u.string().optional(),status:u.enum([`pending`,`running`,`paused`,`completed`,`failed`,`cancelled`]),startedAt:u.number(),completedAt:u.number().optional(),durationMs:u.number().nonnegative().optional(),totalInputTokens:u.number().int().nonnegative().optional(),totalOutputTokens:u.number().int().nonnegative().optional(),totalEstimatedCost:u.number().nonnegative().optional(),error:u.string().optional(),failedNodeId:u.string().optional()}),ht=u.object({executionId:u.string().min(1),frameId:u.string().min(1),nodeId:u.string().min(1),nodeType:C,path:u.array(u.string()),status:u.enum([`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]),attempt:u.number().int().nonnegative(),iteration:u.number().int().nonnegative().optional(),branchKey:u.string().optional(),startedAt:u.number().optional(),completedAt:u.number().optional(),durationMs:u.number().nonnegative().optional(),inputTokens:u.number().int().nonnegative().optional(),outputTokens:u.number().int().nonnegative().optional(),estimatedCost:u.number().nonnegative().optional(),error:u.string().optional()}),gt=u.object({executionId:u.string().min(1),frameId:u.string().min(1),nodeId:u.string().min(1),artifact:S,revision:u.string().min(1).optional(),writtenAt:u.number()}),_t=u.object({executionId:u.string().min(1),nodeId:u.string().min(1),frameId:u.string().min(1),status:u.enum([`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]),prompt:u.string().optional(),openedAt:u.number(),resolvedAt:u.number().optional(),resumeData:r.optional()}),vt=u.object({executionId:u.string().min(1),inputTokens:u.number().int().nonnegative(),outputTokens:u.number().int().nonnegative(),cachedTokens:u.number().int().nonnegative().optional(),estimatedCost:u.number().nonnegative(),byModel:u.record(u.string(),u.object({inputTokens:u.number().int().nonnegative(),outputTokens:u.number().int().nonnegative(),estimatedCost:u.number().nonnegative()})).optional()}),yt=u.object({total:u.number().int().nonnegative(),byStatus:u.object({pending:u.number().int().nonnegative(),running:u.number().int().nonnegative(),paused:u.number().int().nonnegative(),completed:u.number().int().nonnegative(),failed:u.number().int().nonnegative(),cancelled:u.number().int().nonnegative()}),totalDurationMs:u.number().nonnegative(),totalInputTokens:u.number().int().nonnegative(),totalOutputTokens:u.number().int().nonnegative(),totalEstimatedCost:u.number().nonnegative()}),bt=u.object({executionId:u.string().min(1),frameId:u.string().min(1),factoryId:u.string().min(1),materializedNodeIds:u.array(u.string().min(1)),factoryInput:i.optional(),materializedAt:u.number()}),xt=`wfx-ext-`,St=u.object({frameId:u.string().min(1).optional(),nodeId:u.string().min(1),nodeType:F,path:u.array(u.string().min(1)).optional(),attempt:u.number().int().nonnegative().default(0),iteration:u.number().int().nonnegative().optional(),branchKey:u.string().min(1).optional(),startedAt:u.number().int().nonnegative().optional()}).strict(),Ct=u.object({frameId:u.string().min(1),nodeId:u.string().min(1),nodeType:F,path:u.array(u.string().min(1)),attempt:u.number().int().nonnegative().default(0),iteration:u.number().int().nonnegative().optional(),branchKey:u.string().min(1).optional(),startedAt:u.number().int().nonnegative(),durationMs:u.number().int().nonnegative().optional()}).strict(),wt=u.object({executionId:u.string().startsWith(xt,{message:`executionId must use the wfx-ext- prefix`}).optional(),name:u.string().min(1),startedAt:u.number().int().nonnegative().optional(),scope:b.optional(),artifactRef:g.optional(),input:r.optional(),triggerPayload:a.optional(),frame:St.optional()}).superRefine((e,t)=>{e.executionId!==void 0&&e.startedAt===void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`startedAt is required when executionId is supplied`,path:[`startedAt`]})}),Tt=u.object({executionId:u.string().min(1),status:u.enum([`completed`,`failed`,`cancelled`]),error:u.string().min(1).optional(),reason:u.string().min(1).optional(),completedAt:u.number().nonnegative().overwrite(e=>Math.trunc(e)).optional(),frame:Ct.optional()}).superRefine((e,t)=>{if(e.status===`failed`&&e.error===void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`status 'failed' requires a non-empty 'error' message`,path:[`error`]}),e.status===`cancelled`&&e.reason===void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`status 'cancelled' requires a non-empty 'reason' string`,path:[`reason`]}),e.status===`completed`&&e.error!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`status 'completed' must not carry an 'error'`,path:[`error`]}),e.status===`completed`&&e.reason!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`status 'completed' must not carry a 'reason'`,path:[`reason`]}),e.frame!==void 0&&e.completedAt===void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:`completedAt is required when frame metadata is supplied`,path:[`completedAt`]}),e.frame!==void 0&&e.completedAt!==void 0){let n=e.completedAt-e.frame.startedAt;n<0&&t.addIssue({code:u.ZodIssueCode.custom,message:`completedAt must not precede frame.startedAt`,path:[`completedAt`]}),e.frame.durationMs!==void 0&&e.frame.durationMs!==n&&t.addIssue({code:u.ZodIssueCode.custom,message:`frame.durationMs must equal completedAt - frame.startedAt`,path:[`frame`,`durationMs`]})}}),Et=u.object({message:u.string().min(1),details:u.string().min(1).optional(),kind:u.string().min(1).optional(),metadata:r.optional()}).strict(),U=u.object({executionId:u.string(),stepId:u.string(),stepType:u.enum([`station`,`delegate-agent`,`delegate-role`,`gate`])}),W=U.extend({stepType:u.literal(`gate`)}),Dt=u.discriminatedUnion(`source`,[W.extend({frameId:u.string(),action:u.enum([`approve`,`reject`]),source:u.literal(`user`),reason:u.string().optional()}),W.extend({frameId:u.string(),action:u.enum([`approve`,`reject`]),source:u.literal(`timeout`)}),W.extend({frameId:u.string(),source:u.literal(`cancelled`)})]),Ot=W.extend({workflowId:u.string(),workflowName:u.string(),title:u.string(),message:u.string(),autoAction:u.enum([`approve`,`reject`]),timeoutMs:u.number().nullable(),openedAt:u.number()}),kt={getDefinition:{request:u.object({id:u.string()}),response:u.object({workflow:O.nullable()})},setDefinition:{request:u.object({workflow:O}),response:u.object({id:u.string()})},deleteDefinition:{request:u.object({id:u.string()}),response:u.object({deleted:u.boolean()})},listDefinitions:{request:we,response:u.object({workflows:u.array(O)})},"definition.created":O,"definition.updated":O,"definition.deleted":u.object({id:u.string()}),start:{request:u.object({workflowId:u.string(),input:r.optional(),config:r.optional(),artifactRef:g.optional(),scope:b.optional(),executionHints:h.optional(),parentSessionId:u.string().optional(),triggerPayload:a.optional()}),response:u.object({executionId:u.string()})},rerun:{request:u.object({executionId:u.string().min(1),mode:u.enum([`snapshot`,`current`]),input:r.optional(),config:r.optional(),artifactRef:g.optional(),scope:b.optional(),executionHints:h.optional(),parentSessionId:u.string().optional(),triggerPayload:a.optional(),reason:u.string().min(1).optional()}),response:u.object({executionId:u.string()})},cancel:{request:u.object({executionId:u.string(),reason:u.string().optional()}),response:u.object({cancelled:u.boolean()})},getExecution:{request:u.object({executionId:u.string()}),response:u.object({execution:A.nullable()})},listExecutions:{request:ke,response:u.object({executions:u.array(A)})},listExecutionsByArtifactRefs:{request:Ne,response:u.object({executionsByRef:u.record(u.string(),u.array(A))})},listSpans:{request:u.object({executionId:u.string()}),response:u.object({spans:u.array(I)})},listGateInstances:{request:Pe,response:u.object({gates:u.array(N)})},setExecutionLink:{request:u.object({link:L}),response:u.object({id:u.string()})},listExecutionLinks:{request:Ye,response:u.object({links:u.array(L)})},listFrames:{request:u.object({executionId:u.string().min(1)}),response:u.object({frames:u.array(j)})},listTriggerTypes:{request:u.object({}),response:u.object({triggerTypes:u.array(u.object({type:u.string(),displayName:u.string(),icon:u.string(),category:u.string(),description:u.string().optional(),configJsonSchema:i,outputJsonSchema:i,source:u.string()}))})},runFile:{request:u.object({filePath:u.string().min(1),triggerPayload:a.optional(),scope:b.optional()}),response:u.object({executionId:u.string()})},registerExternalExecution:{request:wt,response:u.object({executionId:u.string(),frameId:u.string().optional()})},completeExternalExecution:{request:Tt,response:u.object({success:u.boolean()})},resolveRole:{request:u.object({roleId:u.string().min(1)}),response:P},resolveAgent:{request:u.object({agentId:u.string().min(1)}),response:Ce},getRunContext:{request:u.object({executionId:u.string().min(1)}),response:mt},"execution.started":u.object({executionId:u.string(),workflowId:u.string(),coordinatorSessionId:u.string().optional(),startedAt:u.number().nonnegative().optional(),artifactRef:g.optional()}),"execution.completed":u.object({executionId:u.string(),workflowId:u.string(),totalDuration:u.number(),completedAt:u.number().nonnegative().optional()}),"execution.failed":u.object({executionId:u.string(),workflowId:u.string(),error:u.string(),failedStepId:u.string().optional(),completedAt:u.number().nonnegative().optional()}),"execution.cancelled":u.object({executionId:u.string(),workflowId:u.string(),reason:u.string().optional(),completedAt:u.number().nonnegative().optional()}),"execution.progress":u.object({executionId:u.string().min(1),workflowId:u.string().min(1),frameId:u.string().min(1),nodeId:u.string().min(1),progress:Et,emittedAt:u.number().int().nonnegative()}),"execution.paused":p.schema(u.object({executionId:u.string(),workflowId:u.string(),pausedAtGateId:u.string().min(1),pausedAtFrameId:u.string().min(1)}),{traceAll:!0}),"step.beforeStart":U,"step.started":U.extend({sessionId:u.string().optional(),subagentId:u.string().optional()}),"step.completed":U.extend({result:r.optional(),duration:u.number()}),"step.failed":U.extend({error:u.string()}),"step.skipped":U.extend({reason:u.string().optional(),condition:u.string().optional()}),"gate.requested":Ot,"gate.awaitApproval":{request:Ot,response:u.object({action:u.enum([`approve`,`reject`]),source:u.enum([`user`,`timeout`]),reason:u.string().optional()})},"gate.respond":{request:u.object({executionId:u.string(),gateId:u.string(),action:u.enum([`approve`,`reject`]),frameId:u.string().optional(),resumeData:r,reason:u.string().optional()}),response:u.object({accepted:u.boolean()})},"gate.resolved":Dt,"frame.started":u.object({executionId:u.string(),frameId:u.string(),nodeId:u.string(),nodeType:C,path:u.array(u.string()),parentFrameId:u.string().optional(),startedAt:u.number().nonnegative().optional()}),"frame.completed":u.object({executionId:u.string(),frameId:u.string(),nodeId:u.string(),output:r.optional(),duration:u.number().nonnegative().optional(),completedAt:u.number().nonnegative().optional()}),"frame.failed":u.object({executionId:u.string(),frameId:u.string(),nodeId:u.string(),error:u.string(),duration:u.number().nonnegative().optional(),completedAt:u.number().nonnegative().optional()}),"frame.sessionLinked":u.object({executionId:p.attribute(u.string(),`makaio.execution.id`),frameId:p.attribute(u.string(),`makaio.frame.id`),sessionId:p.attribute(u.string(),`makaio.session.id`)}).strict(),"gate.suspended":u.object({executionId:u.string(),frameId:u.string(),nodeId:u.string(),schema:i,prompt:u.string().optional(),title:u.string().optional(),autoAction:u.enum([`approve`,`reject`]),timeoutMs:u.number().nullable(),openedAt:u.number()}),"gate.resumed":u.object({executionId:u.string(),frameId:u.string(),nodeId:u.string(),resumeData:r}),"dynamic.materialized":u.object({executionId:u.string(),frameId:u.string(),factoryId:u.string().min(1),materializedNodes:u.number().int().nonnegative()}),"artifact.updated":u.object({executionId:u.string(),frameId:u.string(),artifactRef:u.object({kind:u.string().min(1),id:u.string().min(1)}),paths:u.array(u.string()),operation:u.string().min(1),revision:u.string().min(1).optional()}),"worklog.get":{request:u.object({executionId:u.string().min(1)}),response:u.object({summary:H.nullable()})},"worklog.frame.get":{request:u.object({frameId:u.string().min(1)}),response:u.object({frame:ht.nullable()})},"worklog.list":{request:u.object({workflowId:u.string().min(1).optional(),status:k.optional(),limit:u.number().int().positive().optional(),offset:u.number().int().nonnegative().optional()}),response:u.object({items:u.array(H),total:u.number().int().nonnegative()})},"worklog.stats":{request:u.object({workflowId:u.string().min(1).optional(),since:u.number().int().nonnegative().optional(),until:u.number().int().nonnegative().optional()}),response:u.object({stats:yt})},"worklog.changed":u.object({executionId:u.string().min(1)}),"state.get":{request:u.object({executionId:u.string().min(1)}),response:u.object({executionId:u.string().min(1),sequence:u.number().int().nonnegative(),value:r})},"state.patch":{request:u.object({executionId:u.string().min(1),expectedSequence:u.number().int().nonnegative(),patch:u.array(z),nextValue:r}),response:u.object({executionId:u.string().min(1),sequence:u.number().int().positive(),value:r})},"state.updated":u.object({executionId:u.string().min(1),sequence:u.number().int().positive(),patch:u.array(z),value:r,updatedAt:u.number().int().positive()})},At=d(`workflow`,kt),jt=At.subjects;function Mt(e,t){G(e,t,void 0,0,[],`root`,void 0,void 0)}function G(e,t,n,r,i,a,o,s){let c={parent:n,depth:r,ancestors:i,relationship:a,...o!==void 0&&{index:o},...s!==void 0&&{branchKey:s}};if(t.enter?.(e,c)===!1)return;let l=[...i,e.id],u=r+1;switch(e.type){case`sequence`:{let n=e;for(let r=0;r<n.nodes.length;r++)G(n.nodes[r],t,e,u,l,`sequence-child`,r,void 0);break}case`parallel`:{let n=e;for(let[r,i]of Object.entries(n.branches))G(i,t,e,u,l,`parallel-branch`,void 0,r);break}case`iterate`:G(e.body,t,e,u,l,`iterate-body`,void 0,void 0);break;case`iterate-chain`:G(e.body,t,e,u,l,`iterate-chain-body`,void 0,void 0);break;case`loop`:G(e.body,t,e,u,l,`loop-body`,void 0,void 0);break}t.leave?.(e,c)}function Nt(e){switch(e){case`station`:case`delegate-agent`:case`delegate-role`:case`gate`:return`leaf`;case`parallel`:case`iterate`:case`iterate-chain`:case`loop`:return`control`;case`sequence`:return`structural`}}function Pt(e,t,n){return e===`parallel-branch`&&t!==void 0?[{kind:`branch`,key:t}]:e===`sequence-child`&&n!==void 0?[{kind:`index`,value:n}]:e===`iterate-body`||e===`iterate-chain-body`||e===`loop-body`?[{kind:`body`}]:[]}function Ft(e){return e.replace(/\\/g,`\\\\`).replace(/\//g,`\\/`)}function It(e){return e.map(e=>{switch(e.kind){case`node`:return`n:${Ft(e.id)}`;case`branch`:return`b:${Ft(e.key)}`;case`index`:return`i:${e.value}`;case`body`:return`body`}}).join(`/`)}function Lt(e){let t=[],n=[],r=new Map,i=[],a=[],o=[];return Mt(e.root,{enter(e,s){let c=Pt(s.relationship,s.branchKey,s.index),l={kind:`node`,id:e.id};i.push(...c,l),o.push(c.length+1);let u=[...i],d=It(u),f=a.at(-1);if(t.push({key:d,nodeId:e.id,type:e.type,role:Nt(e.type),path:u,parentKey:f,...s.branchKey!==void 0&&{branchKey:s.branchKey}}),f!==void 0&&s.parent!==void 0)switch(s.parent.type){case`sequence`:{n.push({sourceKey:f,targetKey:d,kind:`contains`});let e=r.get(f);e!==void 0&&n.push({sourceKey:e,targetKey:d,kind:`sequence`}),r.set(f,d);break}case`parallel`:n.push({sourceKey:f,targetKey:d,kind:`branch`});break;case`iterate`:case`iterate-chain`:case`loop`:n.push({sourceKey:f,targetKey:d,kind:`body`});break;default:n.push({sourceKey:f,targetKey:d,kind:`contains`});break}a.push(d)},leave(){let e=o.pop()??0;i.splice(i.length-e,e),a.pop()}}),{nodes:t,edges:n}}function K(e){return q(e.body.nodes,e.id)}function q(e,t){for(let n of e){if(n.type===`loop`)return`Nested loop '${n.id}' found inside loop '${t}' — V1 does not support nested loops`;if(n.type===`sequence`){let e=q(n.nodes,t);if(e)return e}if(n.type===`parallel`)for(let e of Object.values(n.branches)){let n=q(e.nodes,t);if(n)return n}if(n.type===`iterate`||n.type===`iterate-chain`){let e=n.body,r=q(e.nodes,t);if(r)return r}}}const J=new WeakMap,Rt=new WeakMap;function Y(e){let{$schema:t,...n}=u.toJSONSchema(e);return n}function X(e,t,n){let r=J.get(e);if(r!==void 0&&t.set(e.id,r),e.type===`sequence`)for(let r of e.nodes)X(r,t,n);else if(e.type===`parallel`)for(let r of Object.values(e.branches))X(r,t,n);else if(e.type===`iterate`)X(e.body,t,n);else if(e.type===`iterate-chain`)X(e.body,t,n);else if(e.type===`loop`){if(n!==void 0){let t=Rt.get(e);t!==void 0&&n.set(e.gate.handler,t)}X(e.body,t,n)}}function zt(e,t,n){let r={id:e,type:`station`,prompt:e,...n?.when!==void 0&&{when:n.when},...n?.skip!==void 0&&{skip:n.skip}};return J.set(r,t),r}function Bt(e,t,n){return{id:e,type:`delegate-agent`,agentId:t.agentId,...t.inputExpression!==void 0&&{inputExpression:t.inputExpression},...t.outputSchema!==void 0&&{outputSchema:t.outputSchema},...n?.when!==void 0&&{when:n.when},...n?.skip!==void 0&&{skip:n.skip}}}function Vt(e,t,n){return{id:e,type:`delegate-role`,role:t,prompt:n?.prompt??e,...n?.when!==void 0&&{when:n.when},...n?.skip!==void 0&&{skip:n.skip},...n?.outputSchema!==void 0&&{outputSchema:n.outputSchema},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.completion!==void 0&&{completion:n.completion}}}function Ht(e,t){return{id:e,type:`gate`,prompt:t.prompt,autoAction:t.autoAction,timeoutMs:t.timeoutMs,...t.title!==void 0&&{title:t.title},...t.resume!==void 0&&{resumeSchema:Y(t.resume)}}}function Ut(e,t,n){let r=`${e}__item`,i={id:r,type:`station`,prompt:r},a={id:e,type:`iterate`,collection:n.collection,body:{id:`${e}__body`,type:`sequence`,nodes:[i]},...n.concurrency!==void 0&&{concurrency:n.concurrency},...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}};return J.set(i,t),a}function Wt(e,t,n){return{id:e,type:`iterate-chain`,collection:n.collection,body:{id:`${e}__body`,type:`sequence`,nodes:t},...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}}}function Gt(e,t,n){let r={id:e,type:`loop`,maxRounds:n.maxRounds,body:{id:`${e}__body`,type:`sequence`,nodes:t},gate:Kt(n),...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}},i=K(r);if(i!==void 0)throw Error(i);return Rt.set(r,n.gate.evaluate),r}function Kt(e){let t=e.gate.escalation;return{handler:e.gate.handler,...e.gate.input!==void 0&&{input:e.gate.input},...e.gate.config!==void 0&&{config:e.gate.config},...t!==void 0&&{escalation:{prompt:t.prompt,autoAction:t.autoAction??`reject`,timeoutMs:t.timeoutMs??null,...t.title!==void 0&&{title:t.title},...t.resumeSchema!==void 0&&{resumeSchema:t.resumeSchema}}}}}function qt(e){return{type:`bus-event`,subject:f(e.subject),...e.filter!==void 0&&{filter:e.filter},...e.filterExpression!==void 0&&{filterExpression:e.filterExpression}}}function Jt(){return{type:`manual`}}function Yt(e){return{type:`cron`,schedule:e.schedule,...e.timezone!==void 0&&{timezone:e.timezone}}}function Xt(e){return{type:`webhook`,event:e.event,...e.branch!==void 0&&{branch:e.branch},...e.repo!==void 0&&{repo:e.repo}}}function Zt(e){return{type:`extension`,extensionType:e.extensionType,...e.config!==void 0&&{config:e.config}}}function Z(e,t){if(e.has(t))throw Error(`Duplicate step ID: ${t}`);e.add(t)}function Q(e,t){if(Z(e,t.id),t.type===`sequence`)for(let n of t.nodes)Q(e,n);else if(t.type===`parallel`)for(let n of Object.values(t.branches))Q(e,n);else (t.type===`iterate`||t.type===`iterate-chain`||t.type===`loop`)&&Q(e,t.body)}function Qt(e,t,n,r,i){let a={};return t.forEach((t,o)=>{if(t.id.length===0)throw Error(`parallel branch at index ${o} has an empty ID`);let s=t.id,c=`${e}__${s}`;Q(n,t),Z(n,c),X(t,r,i),a[s]={id:c,type:`sequence`,nodes:[t]}}),a}function $t(e,t,n,r,i){let a=`${e}__body`,o=`${e}__item`;Z(r,a),Z(r,o),i.set(o,t);let s={id:o,type:`station`,prompt:o};return{id:e,type:`iterate`,collection:n.collection,body:{id:a,type:`sequence`,nodes:[s]},...n.concurrency!==void 0&&{concurrency:n.concurrency},...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}}}function en(e,t,n){return t.resume!==void 0&&(n[e]=t.resume),{id:e,type:`gate`,prompt:t.prompt,autoAction:t.autoAction,timeoutMs:t.timeoutMs,...t.title!==void 0&&{title:t.title},...t.resume!==void 0&&{resumeSchema:Y(t.resume)}}}function tn(e,t,n,r,i,a){let o=`${e}__body`;Z(r,o);for(let e of t)Q(r,e),X(e,i,a);return{id:e,type:`iterate-chain`,collection:n.collection,body:{id:o,type:`sequence`,nodes:t},...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}}}function nn(e,t,n,r,i,a){let o=`${e}__body`;Z(r,o);for(let e of t)Q(r,e),X(e,i,a);let s={id:e,type:`loop`,maxRounds:n.maxRounds,body:{id:o,type:`sequence`,nodes:t},gate:Kt(n),...n.when!==void 0&&{when:n.when},...n.skip!==void 0&&{skip:n.skip}},c=K(s);if(c!==void 0)throw Error(c);return a.set(n.gate.handler,n.gate.evaluate),s}function rn(e,t){e.input=n=>(t.zodSchemas.input=n,t.definition.inputSchema=Y(n),e),e.config=n=>(t.zodSchemas.config=n,t.definition.configSchema=Y(n),e),e.output=n=>(t.zodSchemas.output=n,t.definition.outputSchema=Y(n),e),e.artifact=n=>(n.schema!==void 0&&(t.zodSchemas.artifact=n.schema),t.definition.artifact={kind:n.kind,schemaVersion:n.schemaVersion,scope:n.scope,...n.resolve!==void 0&&{resolve:n.resolve},...n.create!==void 0&&{create:n.create},...n.statusPath!==void 0&&{statusPath:n.statusPath}},e),e.state=e=>(t.definition.state={schema:e.schema,...e.initial!==void 0&&{initial:e.initial}},$(t))}function an(e,t){let{rootNodes:n,runtimeHandlers:r,runtimeLoopGates:i,registeredIds:a,zodGates:o}=t;e.station=(t,i,o)=>(Z(a,t),n.push({id:t,type:`station`,prompt:t,...o?.when!==void 0&&{when:o.when},...o?.skip!==void 0&&{skip:o.skip}}),r.set(t,i),e),e.delegateToAgent=(t,r,i)=>{Z(a,t);let o={id:t,type:`delegate-agent`,agentId:r.agentId,...r.inputExpression!==void 0&&{inputExpression:r.inputExpression},...r.outputSchema!==void 0&&{outputSchema:r.outputSchema},...i?.when!==void 0&&{when:i.when},...i?.skip!==void 0&&{skip:i.skip}};return n.push(o),e},e.delegateToRole=(t,r,i)=>(Z(a,t),n.push({id:t,type:`delegate-role`,role:r,prompt:i?.prompt??t,...i?.when!==void 0&&{when:i.when},...i?.skip!==void 0&&{skip:i.skip},...i?.outputSchema!==void 0&&{outputSchema:i.outputSchema},...i?.timeoutMs!==void 0&&{timeoutMs:i.timeoutMs},...i?.completion!==void 0&&{completion:i.completion}}),e),e.parallel=(t,o,s)=>(Z(a,t),n.push({id:t,type:`parallel`,mode:o.mode??`all-settled`,branches:Qt(t,s,a,r,i),...o.when!==void 0&&{when:o.when},...o.skip!==void 0&&{skip:o.skip}}),e),e.gate=(t,r)=>(Z(a,t),n.push(en(t,r,o)),e),e.iterate=(t,i,o)=>(Z(a,t),n.push($t(t,i,o,a,r)),e),e.iterateChain=(t,o,s)=>(Z(a,t),n.push(tn(t,o,s,a,r,i)),e),e.loop=(t,o,s)=>(Z(a,t),n.push(nn(t,o,s,a,r,i)),e),e.addNode=e=>on(e,a,r,i,n)}function on(e,t,n,r,i){Q(t,e),X(e,n,r),i.push(e)}function $(e){let t={id:e.definition.id,definition:e.definition,runtimeHandlers:e.runtimeHandlers,runtimeFactories:e.runtimeFactories,runtimeLoopGates:e.runtimeLoopGates,source:void 0,get zodSchemas(){return e.zodSchemas},addTrigger(t){return e.triggers.push(t),$(e)}};return rn(t,e),an(t,e),t}function sn(e,t){let n=[],r=new Map,i=new Map,a=new Set,o={},s={gates:o},c=new Map,l=t?.triggers?[...t.triggers]:[];return $({rootNodes:n,runtimeHandlers:r,runtimeFactories:c,runtimeLoopGates:i,registeredIds:a,zodGates:o,zodSchemas:s,definition:{id:e,...t?.name!==void 0&&{name:t.name},...t?.description!==void 0&&{description:t.description},root:{id:`${e}__root`,type:`sequence`,nodes:n},triggers:l,scope:{type:`global`}},triggers:l})}function cn(e){if(e.workflows.length===0)throw Error(`defineWorkflowBundle: workflows must not be empty`);return{workflows:Object.freeze([...e.workflows])}}const ln=u.enum([`artifact.created`,`artifact.revised`,`artifact.status.changed`]),un=u.record(u.string(),r),dn=u.object({type:u.string().min(1),input:u.record(u.string(),r).optional(),executionHints:h.optional()}),fn=u.object({id:u.string().min(1),description:u.string().optional(),on:ln,when:un.optional(),action:dn,enabled:u.boolean().default(!0)});export{st as $,w as $t,St as A,k as At,pt as B,fe as Bt,At as C,je as Ct,Tt as D,Ee as Dt,jt as E,De as Et,ht as F,S as Ft,B as G,j as Gt,dt as H,be as Ht,_t as I,le as It,at as J,M as Jt,it as K,N as Kt,yt as L,x as Lt,gt as M,v as Mt,bt as N,Pe as Nt,xt as O,Te as Ot,H as P,ve as Pt,rt as Q,ye as Qt,vt as R,xe as Rt,Mt as S,Me as St,kt as T,Oe as Tt,lt as U,A as Ut,ft as V,pe as Vt,ut as W,b as Wt,ct as X,ge as Xt,nt as Y,_e as Yt,ot as Z,we as Zt,Gt as _,Fe as _t,cn as a,P as an,Je as at,K as b,Ue as bt,Yt as c,Se as cn,Be as ct,Xt as d,g as dn,Re as dt,T as en,z as et,Bt as f,ne as fn,ze as ft,Wt as g,m as gn,He as gt,Ut as h,ee as hn,Ge as ht,fn as i,Ce as in,L as it,wt as j,Ne as jt,Ct as k,ke as kt,Zt as l,D as ln,We as lt,Ht as m,h as mn,Ie as mt,un as n,de as nn,Xe as nt,sn as o,E as on,I as ot,Vt as p,te as pn,Le as pt,tt as q,he as qt,ln as r,me as rn,Ye as rt,qt as s,ue as sn,qe as st,dn as t,C as tn,Ze as tt,Jt as u,y as un,Ke as ut,zt as v,F as vt,Et as w,Ae as wt,Lt as x,ce as xt,Y as y,Ve as yt,mt as z,O as zt};
@@ -1 +0,0 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{n as r,o as i,t as a}from"./await-trigger-D623tvig.mjs";import{basename as o,join as s}from"node:path";import{WorkerNodeCapabilitiesSchema as c,WorkerNodeSubjects as l,WorkflowWorkerConfigSchema as u}from"@makaio/framework/contracts";import{runWorkflowOrchestrator as d}from"@makaio/framework/workflow-engine/workflow-orchestrator";var f=n(((e,t)=>{t.exports={name:`piscina`,version:`5.2.0`,description:`A fast, efficient Node.js Worker Thread Pool implementation`,main:`./dist/main.js`,types:`./dist/index.d.ts`,exports:{types:`./dist/index.d.ts`,import:`./dist/esm-wrapper.mjs`,require:`./dist/main.js`},engines:{node:`>=20.x`},scripts:{build:`tsc && gen-esm-wrapper . dist/esm-wrapper.mjs`,lint:`eslint`,test:`node scripts/run-tests.js`,"test:jest":`jest --config test/jest/jest.config.js`,"test:ci":`npm run lint && npm run build && npm run test:coverage && npm run test:jest`,"test:coverage":`node scripts/run-tests.js --coverage`,prepack:`npm run build`,benchmark:`node --allow-natives-syntax benchmark/index.js --scope all`,"benchmark:ci":`node --allow-natives-syntax benchmark/index.js --scope all --reporter json | jq '.[] | .name, .opsSec'`,"benchmark:simple":`node --allow-natives-syntax benchmark/index.js --scope simple:all`,"benchmark:simple:default":`node --allow-natives-syntax benchmark/index.js --scope simple`,"benchmark:simple:async":`node --allow-natives-syntax benchmark/index.js --scope simple:async`,"benchmark:startup":`node --allow-natives-syntax benchmark/index.js --scope startup`,"benchmark:queue":`node --allow-natives-syntax benchmark/index.js --scope queue`},repository:{type:`git`,url:`git+https://github.com/piscinajs/piscina.git`},keywords:[`fast`,`worker threads`,`thread pool`,`wade wilson`],author:`James M Snell <jasnell@gmail.com>`,contributors:[`Anna Henningsen <anna@addaleax.net>`,`Matteo Collina <matteo.collina@gmail.com>`,`Carlos Fuentes <me@metcoder.dev>`],license:`MIT`,devDependencies:{"@types/jest":`^30.0.0`,"@types/node":`^22.4.1`,"abort-controller":`^3.0.0`,"bench-node":`^0.7.0`,"concat-stream":`^2.0.0`,eslint:`^9.16.0`,"gen-esm-wrapper":`^1.1.1`,glob:`^13.0.1`,jest:`^30.2.0`,neostandard:`^0.13.0`,"ts-jest":`^29.4.6`,tsx:`^4.20.3`,typescript:`5.8.3`},optionalDependencies:{"@napi-rs/nice":`^1.0.4`},bugs:{url:`https://github.com/piscinajs/piscina/issues`},homepage:`https://github.com/piscinajs/piscina#readme`,directories:{example:`examples`,test:`test`}}})),p=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.kFieldCount=e.kResponseCountField=e.kRequestCountField=e.kQueueOptions=e.kValue=e.kTransferable=e.kWorkerData=e.kMovable=void 0,e.kMovable=Symbol(`Piscina.kMovable`),e.kWorkerData=Symbol(`Piscina.kWorkerData`),e.kTransferable=Symbol.for(`Piscina.transferable`),e.kValue=Symbol.for(`Piscina.valueOf`),e.kQueueOptions=Symbol.for(`Piscina.queueOptions`),e.kRequestCountField=0,e.kResponseCountField=1,e.kFieldCount=2})),m=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AbortError=void 0,e.onabort=t,e.AbortError=class extends Error{constructor(e){super(`The task has been aborted`,{cause:e})}get name(){return`AbortError`}};function t(e,t){return`addEventListener`in e?(e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t)):(e.once(`abort`,t),()=>e.removeListener(`abort`,t))}})),h=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.commonState=t.READY=void 0,t.isTransferable=a,t.isMovable=o,t.markMovable=s,t.maybeFileURLToPath=c,t.getAvailableParallelism=l,t.promiseResolvers=u;let n=e(`node:url`),r=e(`node:os`),i=p();t.READY=`_WORKER_READY`;function a(e){return typeof e==`object`&&!!e&&i.kTransferable in e&&i.kValue in e}function o(e){return a(e)&&e[i.kMovable]===!0}function s(e){Object.defineProperty(e,i.kMovable,{enumerable:!1,configurable:!0,writable:!0,value:!0})}t.commonState={isWorkerThread:!1,workerData:void 0};function c(e){return e.startsWith(`file:`)?(0,n.fileURLToPath)(new n.URL(e)):e}function l(){return(0,r.availableParallelism)()}function u(){if(Promise.withResolvers!=null)return Promise.withResolvers();let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}})),g=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ArrayTaskQueue=void 0;let r=n(e(`node:assert`));t.ArrayTaskQueue=class{constructor(){this.tasks=[]}get size(){return this.tasks.length}shift(){return this.tasks.shift()??null}push(e){this.tasks.push(e)}remove(e){let t=this.tasks.indexOf(e);r.default.notStrictEqual(t,-1),this.tasks.splice(t,1)}}})),_=n((t=>{var n=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},r=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},i=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a;Object.defineProperty(t,`__esModule`,{value:!0}),t.FixedQueue=void 0;let o=i(e(`node:assert`)),s=2048,c=s-1;var l=class{constructor(){this.bottom=0,this.top=0,this.list=Array(s),this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&c)===this.bottom}push(e){this.list[this.top]=e,this.top=this.top+1&c}shift(){let e=this.list[this.bottom];return e===void 0?null:(this.list[this.bottom]=void 0,this.bottom=this.bottom+1&c,e)}remove(e){let t=this.list.indexOf(e);o.default.notStrictEqual(t,-1);let n=t;for(;;){let e=n+1&c;if(this.list[n]=this.list[e],this.list[n]===void 0)break;if(e===t){this.list[n]=void 0;break}n=e}this.top=this.top-1&c}};t.FixedQueue=class{constructor(){a.set(this,0),this.head=this.tail=new l}isEmpty(){return this.head.isEmpty()}push(e){var t;this.head.isFull()&&(this.head=this.head.next=new l),this.head.push(e),r(this,a,(t=n(this,a,`f`),t++,t),`f`)}shift(){var e;let t=this.tail,i=t.shift();return i!==null&&r(this,a,(e=n(this,a,`f`),e--,e),`f`),t.isEmpty()&&t.next!==null&&(this.tail=t.next,t.next=null),i}remove(e){var t;let i=null,o=this.tail;for(;;){if(o.list.includes(e)){o.remove(e),r(this,a,(t=n(this,a,`f`),t--,t),`f`);break}if(o.next===null)break;i=o,o=o.next}o.isEmpty()&&(i===null?o.next!==null&&(this.tail=o.next):o.next===null?this.head=i:i.next=o.next)}get size(){return n(this,a,`f`)}},a=new WeakMap})),v=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.TaskInfo=t.FixedQueue=t.ArrayTaskQueue=void 0,t.isTaskQueue=l;let n=e(`node:perf_hooks`),r=e(`node:async_hooks`),i=m(),a=h(),o=p();var s=g();Object.defineProperty(t,`ArrayTaskQueue`,{enumerable:!0,get:function(){return s.ArrayTaskQueue}});var c=_();Object.defineProperty(t,`FixedQueue`,{enumerable:!0,get:function(){return c.FixedQueue}});function l(e){return typeof e==`object`&&!!e&&`size`in e&&typeof e.shift==`function`&&typeof e.remove==`function`&&typeof e.push==`function`}let u=0;t.TaskInfo=class extends r.AsyncResource{constructor({task:e,transferList:t,filename:r,name:i,abortSignal:s,triggerAsyncId:c},l){super(`Piscina.Task`,{requireManualDestroy:!0,triggerAsyncId:c}),this.workerInfo=null,this.aborted=!1,this._abortListener=()=>{this.aborted=!0},this._abortCleaner=null,this.callback=l,this.task=e,this.transferList=t,(0,a.isMovable)(e)&&(this.transferList??=[],this.transferList=this.transferList.concat(e[o.kTransferable]),this.task=e[o.kValue]),this.filename=r,this.name=i,this.taskId=u++,this.abortSignal=s,this.created=n.performance.now(),this.started=0}onAbort(e){this._abortListener=()=>{this.aborted=!0,e()}}setAbortListener(e){this._abortCleaner=(0,i.onabort)(e,this._abortListener)}releaseTask(){let e=this.task;return this.task=null,e}onResponse(e){}done(e,t){var n;this.runInAsyncScope(this.callback,null,e,t),this.emitDestroy(),(n=this._abortCleaner)==null||n.call(this)}get[o.kQueueOptions](){return this.task?.[o.kQueueOptions]??null}get interface(){return{taskId:this.taskId,filename:this.filename,name:this.name,created:this.created,isAbortable:this.abortSignal!==null,[o.kQueueOptions]:this[o.kQueueOptions]}}}})),y=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Errors=void 0,e.Errors={ThreadTermination:()=>Error(`Terminating worker thread`),FilenameNotProvided:()=>Error(`filename must be provided to run() or in options object`),TaskQueueAtLimit:()=>Error(`Task queue is at limit`),NoTaskQueueAvailable:()=>Error(`No task queue available and all Workers are busy`),CloseTimeout:()=>Error(`Close operation timed out`)}})),b=n((t=>{var n=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},r=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},i,a;Object.defineProperty(t,`__esModule`,{value:!0}),t.PiscinaHistogramHandler=void 0;let o=e(`node:perf_hooks`);t.PiscinaHistogramHandler=class e{constructor(){i.set(this,void 0),a.set(this,void 0),n(this,i,(0,o.createHistogram)(),`f`),n(this,a,(0,o.createHistogram)(),`f`)}get runTimeSummary(){return e.createHistogramSummary(r(this,i,`f`))}get waitTimeSummary(){return e.createHistogramSummary(r(this,a,`f`))}get runTimeCount(){return r(this,i,`f`).count}recordRunTime(t){r(this,i,`f`).record(e.toHistogramIntegerNano(t))}recordWaitTime(t){r(this,a,`f`).record(e.toHistogramIntegerNano(t))}resetWaitTime(){r(this,a,`f`).reset()}resetRunTime(){r(this,i,`f`).reset()}static createHistogramSummary(e){let{mean:t,stddev:n,min:r,max:i}=e;return{average:t/1e3,mean:t/1e3,stddev:n/1e3,min:r/1e3,max:i/1e3,p0_001:e.percentile(.001)/1e3,p0_01:e.percentile(.01)/1e3,p0_1:e.percentile(.1)/1e3,p1:e.percentile(1)/1e3,p2_5:e.percentile(2.5)/1e3,p10:e.percentile(10)/1e3,p25:e.percentile(25)/1e3,p50:e.percentile(50)/1e3,p75:e.percentile(75)/1e3,p90:e.percentile(90)/1e3,p97_5:e.percentile(97.5)/1e3,p99:e.percentile(99)/1e3,p99_9:e.percentile(99.9)/1e3,p99_99:e.percentile(99.99)/1e3,p99_999:e.percentile(99.999)/1e3}}static toHistogramIntegerNano(e){return Math.max(1,Math.trunc(e*1e3))}},i=new WeakMap,a=new WeakMap})),x=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.AsynchronouslyCreatedResourcePool=t.AsynchronouslyCreatedResource=void 0;let r=n(e(`node:assert`));t.AsynchronouslyCreatedResource=class{constructor(){this.onreadyListeners=[],this.ondestroyListeners=[]}markAsReady(){let e=this.onreadyListeners;(0,r.default)(e!=null),this.onreadyListeners=null;for(let t of e)t()}isReady(){return this.onreadyListeners==null}onReady(e){if(this.onreadyListeners==null){e();return}this.onreadyListeners.push(e)}onDestroy(e){this.ondestroyListeners!=null&&this.ondestroyListeners.push(e)}markAsDestroyed(){let e=this.ondestroyListeners;(0,r.default)(e!=null),this.ondestroyListeners=null;for(let t of e)t()}isDestroyed(){return this.ondestroyListeners==null}},t.AsynchronouslyCreatedResourcePool=class{constructor(e){this.pendingItems=new Set,this.readyItems=new Set,this.maximumUsage=e,this.onAvailableListeners=[],this.onTaskDoneListeners=[]}add(e){this.pendingItems.add(e),e.onReady(()=>{this.pendingItems.has(e)&&(this.pendingItems.delete(e),this.readyItems.add(e),this.maybeAvailable(e))})}delete(e){this.pendingItems.delete(e),this.readyItems.delete(e)}*[Symbol.iterator](){yield*this.pendingItems,yield*this.readyItems}get size(){return this.pendingItems.size+this.readyItems.size}maybeAvailable(e){if(e.currentUsage()<this.maximumUsage)for(let t of this.onAvailableListeners)t(e)}onAvailable(e){this.onAvailableListeners.push(e)}taskDone(e){for(let t=0;t<this.onTaskDoneListeners.length;t++)this.onTaskDoneListeners[t](e)}onTaskDone(e){this.onTaskDoneListeners.push(e)}getCurrentUsage(){let e=0;for(let t of this.readyItems){let n=t.currentUsage();Number.isFinite(n)&&(e+=n)}return e}}})),S=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LeastBusyBalancer=t;function t(e){let{maximumUsage:t}=e;return(e,n)=>{let r=null,i=t;for(let t of n){if(t.currentUsage===0){r=t;break}t.isRunningAbortableTask||e.isAbortable===!1&&t.currentUsage<i&&(r=t,i=t.currentUsage)}return r}}})),C=n((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__exportStar||function(e,t){for(var r in e)r!==`default`&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)},i=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,`__esModule`,{value:!0}),t.AsynchronouslyCreatedResourcePool=t.WorkerInfo=void 0;let a=e(`node:worker_threads`),o=e(`node:perf_hooks`),s=i(e(`node:assert`)),c=y(),l=p(),u=b(),d=x();Object.defineProperty(t,`AsynchronouslyCreatedResourcePool`,{enumerable:!0,get:function(){return d.AsynchronouslyCreatedResourcePool}}),r(S(),t),t.WorkerInfo=class extends d.AsynchronouslyCreatedResource{constructor({worker:e,port:t,enableHistogram:n},r){super(),this.idleTimeout=null,this.lastSeenResponseCount=0,this.terminating=!1,this.destroyed=!1;let{filename:i,...s}=e;this.worker=new a.Worker(i,s),this.port=t,this.onMessage=r,this.port.on(`message`,this._handleResponse.bind(this)),this.taskInfos=new Map,this.sharedBuffer=new Int32Array(new SharedArrayBuffer(l.kFieldCount*Int32Array.BYTES_PER_ELEMENT)),this.histogram=n?(0,o.createHistogram)():null}get id(){return this.worker.threadId}onWorkerMessage(e){this.worker.on(`message`,e)}onWorkerError(e){this.worker.on(`error`,e)}onWorkerExit(e){this.worker.on(`exit`,e)}onPortClose(e){this.port.on(`close`,e)}init(e,t){return this.worker.postMessage(e,t),this}workerRef(){return this.worker.ref(),this}workerUnref(){return this.worker.unref(),this}destroy(){if(!(this.terminating||this.destroyed)){this.terminating=!0,this.clearIdleTimeout(),this.worker.terminate(),this.port.close();for(let e of this.taskInfos.values())e.done(c.Errors.ThreadTermination());this.taskInfos.clear(),this.terminating=!1,this.destroyed=!0,this.markAsDestroyed()}}setIdleTimeout(e,t,...n){this.idleTimeout=setTimeout(e,t,...n).unref()}clearIdleTimeout(){this.idleTimeout!=null&&(clearTimeout(this.idleTimeout),this.idleTimeout=null)}ref(){return this.port.ref(),this}unref(){return this.port.unref(),this}_handleResponse(e){var t;(t=this.histogram)==null||t.record(u.PiscinaHistogramHandler.toHistogramIntegerNano(e?.time)),this.onMessage(e),this.taskInfos.size===0&&this.unref()}postTask(e){(0,s.default)(!this.taskInfos.has(e.taskId)),(0,s.default)(!this.terminating&&!this.destroyed);let t={task:e.releaseTask(),taskId:e.taskId,filename:e.filename,name:e.name,histogramEnabled:this.histogram==null?0:1};try{this.port.postMessage(t,e.transferList),queueMicrotask(()=>this.clearIdleTimeout()),e.workerInfo=this,this.taskInfos.set(e.taskId,e),this.ref(),Atomics.add(this.sharedBuffer,l.kRequestCountField,1),Atomics.notify(this.sharedBuffer,l.kRequestCountField,1)}catch(t){e.done(t)}}processPendingMessages(){if(this.destroyed)return;let e=Atomics.load(this.sharedBuffer,l.kResponseCountField);if(e!==this.lastSeenResponseCount){this.lastSeenResponseCount=e;let t;for(;(t=(0,a.receiveMessageOnPort)(this.port))!=null;)this._handleResponse(t.message)}}isRunningAbortableTask(){if(this.taskInfos.size!==1)return!1;let[[,e]]=this.taskInfos;return e.abortSignal!=null}currentUsage(){return this.isRunningAbortableTask()?1/0:this.taskInfos.size}popTask(e){let t=this.taskInfos.get(e)??null;return t!=null&&this.taskInfos.delete(e),t}get interface(){let e=this;return{get id(){return e.worker.threadId},get currentUsage(){return e.currentUsage()},get isRunningAbortableTask(){return e.isRunningAbortableTask()},get histogram(){return e.histogram==null?null:u.PiscinaHistogramHandler.createHistogramSummary(e.histogram)},get terminating(){return e.terminating},get destroyed(){return e.destroyed},[l.kWorkerData]:e}}}})),w=n((t=>{var n=t&&t.__classPrivateFieldSet||function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},r=t&&t.__classPrivateFieldGet||function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},i,a,o,s;Object.defineProperty(t,`__esModule`,{value:!0}),t.workerData=t.isWorkerThread=t.move=t.ArrayTaskQueue=t.FixedQueue=t.version=t.queueOptionsSymbol=t.valueSymbol=t.transferableSymbol=t.Piscina=void 0;let c=e(`node:worker_threads`),l=e(`node:events`),u=e(`node:path`),d=e(`node:util`),g=e(`node:perf_hooks`),_=e(`node:timers/promises`),x=f();Object.defineProperty(t,`version`,{enumerable:!0,get:function(){return x.version}});let S=p();Object.defineProperty(t,`queueOptionsSymbol`,{enumerable:!0,get:function(){return S.kQueueOptions}}),Object.defineProperty(t,`transferableSymbol`,{enumerable:!0,get:function(){return S.kTransferable}}),Object.defineProperty(t,`valueSymbol`,{enumerable:!0,get:function(){return S.kValue}});let w=v();Object.defineProperty(t,`ArrayTaskQueue`,{enumerable:!0,get:function(){return w.ArrayTaskQueue}}),Object.defineProperty(t,`FixedQueue`,{enumerable:!0,get:function(){return w.FixedQueue}});let T=C(),E=m(),D=b(),O=y(),k=h(),A=(0,k.getAvailableParallelism)(),j={filename:null,name:`default`,minThreads:Math.max(Math.floor(A/2),1),maxThreads:A*1.5,idleTimeout:0,maxQueue:1/0,concurrentTasksPerWorker:1,atomics:`sync`,taskQueue:new w.ArrayTaskQueue,niceIncrement:0,trackUnmanagedFds:!0,closeTimeout:3e4,recordTiming:!0,workerHistogram:!1},M={transferList:void 0,filename:null,signal:null,name:null},N={force:!1};var P=class{constructor(e){i.set(this,void 0),n(this,i,e,`f`)}get[(i=new WeakMap,S.kTransferable)](){return r(this,i,`f`)}get[S.kValue](){return r(this,i,`f`)}},F=class{constructor(e){a.set(this,void 0),n(this,a,e,`f`)}get[(a=new WeakMap,S.kTransferable)](){return r(this,a,`f`).buffer}get[S.kValue](){return r(this,a,`f`)}},I=class{constructor(e,t){this.skipQueue=[],this.completed=0,this.histogram=null,this.start=g.performance.now(),this.inProcessPendingMessages=!1,this.startingUp=!1,this.closingUp=!1,this.workerFailsDuringBootstrap=!1,this.destroying=!1,this.publicInterface=e,this.taskQueue=t.taskQueue??new w.FixedQueue;let n=t.filename?(0,k.maybeFileURLToPath)(t.filename):null;this.options={...j,...t,filename:n,maxQueue:0},this.options.recordTiming&&(this.histogram=new D.PiscinaHistogramHandler),t.maxThreads!==void 0&&this.options.minThreads>=t.maxThreads&&(this.options.minThreads=t.maxThreads),t.minThreads!==void 0&&this.options.maxThreads<=t.minThreads&&(this.options.maxThreads=t.minThreads),t.maxQueue===`auto`?this.options.maxQueue=this.options.maxThreads**2:this.options.maxQueue=t.maxQueue??j.maxQueue,this.balancer=this.options.loadBalancer??(0,T.LeastBusyBalancer)({maximumUsage:this.options.concurrentTasksPerWorker}),this.workers=new T.AsynchronouslyCreatedResourcePool(this.options.concurrentTasksPerWorker),this.workers.onTaskDone(this._onWorkerTaskDone.bind(this)),this.maxCapacity=this.options.maxThreads*this.options.concurrentTasksPerWorker,this.startingUp=!0,this._ensureMinimumWorkers(),this.startingUp=!1,this._needsDrain=!1}_ensureMinimumWorkers(){if(!(this.closingUp||this.destroying))for(;this.workers.size<this.options.minThreads;)this._addNewWorker()}_addNewWorker(){if(this.closingUp===!0)return;let{port1:e,port2:t}=new c.MessageChannel,n=new T.WorkerInfo({worker:{filename:(0,u.resolve)(__dirname,`worker.js`),env:this.options.env,argv:this.options.argv,execArgv:this.options.execArgv,resourceLimits:this.options.resourceLimits,workerData:this.options.workerData,trackUnmanagedFds:this.options.trackUnmanagedFds},port:e,enableHistogram:this.options.workerHistogram},i.bind(this)),r={filename:this.options.filename,name:this.options.name,port:t,sharedBuffer:n.sharedBuffer,atomics:this.options.atomics,niceIncrement:this.options.niceIncrement};n.onDestroy(()=>{this.publicInterface.emit(`workerDestroy`,n.interface)}),n.onWorkerMessage(s.bind(this)),n.onWorkerError(l.bind(this)),n.onWorkerExit(f.bind(this)),n.onPortClose(()=>{n.workerRef()}),this.startingUp===!0?(n.markAsReady(),queueMicrotask(()=>{this.publicInterface.emit(`workerCreate`,n.interface),this._onWorkerReady(n)})):n.onReady(()=>{this.publicInterface.emit(`workerCreate`,n.interface),this._onWorkerReady(n)}),n.init(r,[t]).workerUnref(),this.workers.add(n);function i(e){let{taskId:t,result:r}=e,i=n.popTask(t);if(this.workers.taskDone(n),i==null){let t=Error(`Unexpected message from Worker: ${(0,d.inspect)(e)}`);this.publicInterface.emit(`error`,t)}else i.done(e.error,r);this._processPendingMessages()}function a(){n.currentUsage()===0&&n.unref(),n.isReady()===!1&&n.markAsReady()}function o(e){this.publicInterface.emit(`message`,e)}function s(e){e instanceof Object&&k.READY in e||typeof e==`object`&&e&&k.READY in e?a():o.call(this,e)}function l(e){this._onError(n,e,!1)}function f(e){if(this.destroying===!1){let t=Error(`worker exited with code: ${e}`);this._onError(n,t,!0)}}}_onError(e,t,n){let r=[...e.taskInfos.values()];if(e.taskInfos.clear(),this._removeWorker(e),e.isReady()&&!this.workerFailsDuringBootstrap?this._ensureMinimumWorkers():this.workerFailsDuringBootstrap=!0,r.length>0)for(let e of r)e.done(t,null);else n||this.publicInterface.emit(`error`,t)}_processPendingMessages(){if(!(this.inProcessPendingMessages||this.options.atomics===`disabled`)){this.inProcessPendingMessages=!0;try{for(let e of this.workers)e.processPendingMessages()}finally{this.inProcessPendingMessages=!1}}}_removeWorker(e){e.destroy(),this.workers.delete(e)}_removeTaskFromQueue(e){this.taskQueue.remove(e);let t=this.skipQueue.indexOf(e);t!==-1&&this.skipQueue.splice(t,1)}_onWorkerReady(e){this._onWorkerAvailable(e)}_onWorkerTaskDone(e){this._onWorkerAvailable(e)}_onWorkerAvailable(e){let t=null;for(;this.taskQueue.size>0||this.skipQueue.length>0;){let e=this.skipQueue.shift()||this.taskQueue.shift();if(t??=[...this.workers].map(e=>e.interface),!this._distributeTask(e,t))if(this.workers.size<this.options.maxThreads){this._addNewWorker();continue}else break}this.options.idleTimeout!==1/0&&e.currentUsage()===0&&this.workers.size>this.options.minThreads&&e.setIdleTimeout(()=>{e.currentUsage()===0&&this.workers.size>this.options.minThreads&&this._removeWorker(e)},this.options.idleTimeout)}_distributeTask(e,t){var n;if(e.aborted)return!0;let r=this.balancer(e.interface,t);if(r!=null&&r[S.kWorkerData]!=null){let t=g.performance.now();return(n=this.histogram)==null||n.recordWaitTime(t-e.created),e.started=t,r[S.kWorkerData].postTask(e),queueMicrotask(()=>this._maybeDrain()),!0}return e.abortSignal==null?this.taskQueue.push(e):this.skipQueue.push(e),!1}runTask(e,t){let{filename:n,name:r}=t,{transferList:i=[]}=t;if(n??=this.options.filename,r??=this.options.name,typeof n!=`string`)return Promise.reject(O.Errors.FilenameNotProvided());n=(0,k.maybeFileURLToPath)(n);let a;if(this.closingUp||this.destroying){let e=new AbortController;e.abort(`queue is being terminated`),a=e.signal}else a=t.signal??null;let{promise:o,resolve:s,reject:c}=(0,k.promiseResolvers)(),l=new w.TaskInfo({task:e,transferList:i,filename:n,name:r,abortSignal:a,triggerAsyncId:this.publicInterface.asyncResource.asyncId()},(e,t)=>{var n;this.completed++,l.started&&((n=this.histogram)==null||n.recordRunTime(g.performance.now()-l.started)),e===null?s(t):c(e),queueMicrotask(this._maybeDrain.bind(this))});if(a!=null){if(a.aborted)return c(new E.AbortError(a.reason)),o;l.onAbort(()=>{c(new E.AbortError(a.reason)),l.workerInfo==null?this._removeTaskFromQueue(l):(this._removeWorker(l.workerInfo),this._ensureMinimumWorkers())}),l.setAbortListener(a)}if(this.taskQueue.size>0){let e=this.options.maxQueue+this.pendingCapacity();return this.taskQueue.size>=e?this.options.maxQueue===0?c(O.Errors.NoTaskQueueAvailable()):c(O.Errors.TaskQueueAtLimit()):(this.taskQueue.push(l),this.workers.size<this.options.maxThreads&&this._addNewWorker()),queueMicrotask(this._maybeDrain.bind(this)),o}let u=[...this.workers.readyItems].map(e=>e.interface);return this._distributeTask(l,u)||(this.workers.size<this.options.maxThreads&&this._addNewWorker(),this.options.maxQueue<=0&&this.pendingCapacity()===0&&c(O.Errors.NoTaskQueueAvailable())),queueMicrotask(this._maybeDrain.bind(this)),o}pendingCapacity(){return this.workers.pendingItems.size*this.options.concurrentTasksPerWorker}_maybeDrain(){let{maxCapacity:e}=this,t=this.workers.getCurrentUsage();e===t?(this._needsDrain=!0,queueMicrotask(()=>this.publicInterface.emit(`needsDrain`))):e>t&&this._needsDrain&&(this._needsDrain=!1,queueMicrotask(()=>this.publicInterface.emit(`drain`)))}async destroy(){for(this.destroying=!0;this.skipQueue.length>0;)this.skipQueue.shift().done(Error(`Terminating worker thread`));for(;this.taskQueue.size>0;)this.taskQueue.shift().done(Error(`Terminating worker thread`));let e=[];for(;this.workers.size>0;){let[t]=this.workers;e.push((0,l.once)(t.worker,`exit`)),this._removeWorker(t)}await Promise.allSettled(e),this.destroying=!1}async close(e){if(this.closingUp=!0,e.force){let e=this.skipQueue.length;for(let t=0;t<e;t++){let e=this.skipQueue.shift();e.workerInfo===null?e.done(new E.AbortError(`pool is closed`)):this.skipQueue.push(e)}let t=this.taskQueue.size;for(let e=0;e<t;e++){let e=this.taskQueue.shift();e.workerInfo===null?e.done(new E.AbortError(`pool is closed`)):this.taskQueue.push(e)}}let t=()=>new Promise(e=>{let t=this.workers.size;if(t===0){e();return}let n=0,r=r=>{r.taskInfos.size===0&&n++,t===n&&e()};this.workers.onTaskDone(r);for(let e of this.workers)r(e),this.workers.onTaskDone(r)}),n=async e=>{throw await(0,_.setTimeout)(e,null,{ref:!1}),O.Errors.CloseTimeout()};try{await Promise.race([t(),n(this.options.closeTimeout)])}catch(e){this.publicInterface.emit(`error`,e)}finally{await this.destroy(),this.publicInterface.emit(`close`),this.closingUp=!1}}},L=class e extends l.EventEmitterAsyncResource{constructor(e={}){let t={...e,"__proto__":null};if(super({...t,name:`Piscina`}),o.set(this,void 0),s.set(this,null),typeof t.filename!=`string`&&t.filename!=null)throw TypeError(`options.filename must be a string or null`);if(typeof t.name!=`string`&&t.name!=null)throw TypeError(`options.name must be a string or null`);if(t.minThreads!==void 0&&(typeof t.minThreads!=`number`||t.minThreads<0))throw TypeError(`options.minThreads must be a non-negative integer`);if(t.maxThreads!==void 0&&(typeof t.maxThreads!=`number`||t.maxThreads<1))throw TypeError(`options.maxThreads must be a positive integer`);if(t.minThreads!==void 0&&t.maxThreads!==void 0&&t.minThreads>t.maxThreads)throw RangeError(`options.minThreads and options.maxThreads must not conflict`);if(t.idleTimeout!==void 0&&(typeof t.idleTimeout!=`number`||t.idleTimeout<0))throw TypeError(`options.idleTimeout must be a non-negative integer`);if(t.maxQueue!==void 0&&t.maxQueue!==`auto`&&(typeof t.maxQueue!=`number`||t.maxQueue<0))throw TypeError(`options.maxQueue must be a non-negative integer`);if(t.concurrentTasksPerWorker!==void 0&&(typeof t.concurrentTasksPerWorker!=`number`||t.concurrentTasksPerWorker<1))throw TypeError(`options.concurrentTasksPerWorker must be a positive integer`);if(t.atomics!=null&&(typeof t.atomics!=`string`||![`sync`,`async`,`disabled`].includes(t.atomics)))throw TypeError(`options.atomics should be a value of sync, sync or disabled.`);if(t.resourceLimits!==void 0&&(typeof t.resourceLimits!=`object`||t.resourceLimits===null))throw TypeError(`options.resourceLimits must be an object`);if(t.taskQueue!==void 0&&!(0,w.isTaskQueue)(t.taskQueue))throw TypeError(`options.taskQueue must be a TaskQueue object`);if(t.niceIncrement!==void 0&&(typeof t.niceIncrement!=`number`||t.niceIncrement<0&&process.platform!==`win32`))throw TypeError(`options.niceIncrement must be a non-negative integer on Unix systems`);if(t.trackUnmanagedFds!==void 0&&typeof t.trackUnmanagedFds!=`boolean`)throw TypeError(`options.trackUnmanagedFds must be a boolean value`);if(t.closeTimeout!==void 0&&(typeof t.closeTimeout!=`number`||t.closeTimeout<0))throw TypeError(`options.closeTimeout must be a non-negative integer`);if(t.loadBalancer!==void 0&&(typeof t.loadBalancer!=`function`||t.loadBalancer.length<1))throw TypeError(`options.loadBalancer must be a function with at least two args`);if(t.workerHistogram!==void 0&&typeof t.workerHistogram!=`boolean`)throw TypeError(`options.workerHistogram must be a boolean`);n(this,o,new I(this,t),`f`)}run(e,t=M){if(typeof t!=`object`||!t)return Promise.reject(TypeError(`options must be an object`));let{transferList:n,signal:i}=t,a=Object.prototype.hasOwnProperty.call(t,`filename`)?t.filename:null,s=Object.prototype.hasOwnProperty.call(t,`name`)?t.name:null;return n!==void 0&&!Array.isArray(n)?Promise.reject(TypeError(`transferList argument must be an Array`)):a!=null&&typeof a!=`string`?Promise.reject(TypeError(`filename argument must be a string`)):s!=null&&typeof s!=`string`?Promise.reject(TypeError(`name argument must be a string`)):i!=null&&typeof i!=`object`?Promise.reject(TypeError(`signal argument must be an object`)):r(this,o,`f`).runTask(e,{transferList:n,filename:a,name:s,signal:i})}async close(e=N){if(typeof e!=`object`||!e)throw TypeError(`options must be an object`);let{force:t}=e;return t!==void 0&&typeof t!=`boolean`?Promise.reject(TypeError(`force argument must be a boolean`)):(t??=N.force,r(this,o,`f`).close({force:t}))}destroy(){return r(this,o,`f`).destroy()}[(o=new WeakMap,s=new WeakMap,Symbol.dispose)](){this.close()}[Symbol.asyncDispose](){return this.close()}get maxThreads(){return r(this,o,`f`).options.maxThreads}get minThreads(){return r(this,o,`f`).options.minThreads}get options(){return r(this,o,`f`).options}get threads(){let e=[];for(let t of r(this,o,`f`).workers)e.push(t.worker);return e}get idleThreads(){let e=0;for(let t of r(this,o,`f`).workers.readyItems)t.currentUsage()===0&&e++;return e}get queueSize(){let e=r(this,o,`f`);return Math.max(e.taskQueue.size+e.skipQueue.length-e.pendingCapacity(),0)}get completed(){return r(this,o,`f`).completed}get histogram(){if(r(this,s,`f`)==null){let e={get runTime(){return this.histogram?.runTimeSummary},get waitTime(){return this.histogram?.waitTimeSummary},resetRunTime(){var e;(e=this.histogram)==null||e.resetRunTime()},resetWaitTime(){var e;(e=this.histogram)==null||e.resetWaitTime()}};Object.defineProperty(e,`histogram`,{value:r(this,o,`f`).histogram,writable:!1,enumerable:!1,configurable:!1}),n(this,s,e,`f`)}return r(this,s,`f`)}get utilization(){if(r(this,o,`f`).histogram==null)return 0;let e=r(this,o,`f`).histogram.runTimeCount;if(e===0)return 0;let t=this.duration*r(this,o,`f`).options.maxThreads;return r(this,o,`f`).histogram.runTimeSummary.mean/1e3*e/t}get duration(){return g.performance.now()-r(this,o,`f`).start}get needsDrain(){return r(this,o,`f`)._needsDrain}static get isWorkerThread(){return k.commonState.isWorkerThread}static get workerData(){return k.commonState.workerData}static get version(){return x.version}static get Piscina(){return e}static get FixedQueue(){return w.FixedQueue}static get ArrayTaskQueue(){return w.ArrayTaskQueue}static move(e){return typeof e==`object`&&e&&typeof e!=`function`&&((0,k.isTransferable)(e)||(e=d.types.isArrayBufferView(e)?new F(e):new P(e)),(0,k.markMovable)(e)),e}static get transferableSymbol(){return S.kTransferable}static get valueSymbol(){return S.kValue}static get queueOptionsSymbol(){return S.kQueueOptions}};t.default=L,t.Piscina=L,t.move=L.move,t.isWorkerThread=L.isWorkerThread,t.workerData=L.workerData})),T=t(n(((e,t)=>{t.exports=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(w()).default}))(),1),E=T.default;T.default.ArrayTaskQueue,T.default.FixedQueue,T.default.Piscina,T.default.isWorkerThread,T.default.move,T.default.queueOptionsSymbol,T.default.transferableSymbol,T.default.valueSymbol,T.default.version,T.default.workerData;var D=class{pool;constructor(e){this.pool=new E({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t){return this.pool.run(e,{signal:t})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},O=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){return this.pool??=new D(this.options),this.pool.run({config:e,manifest:n??this.manifest},t)}runWithReadiness(e,t,n){this.pool??=new D(this.options);let r=this.pool,a,o=!1,s,c=new Promise((t,n)=>{s=n,a=r.onMessage(n=>{i(n)&&(n.executionId!==e.executionId||n.cancelSubject!==e.cancelSubject||(o=!0,a?.(),t(n)))})}),l=r.run({config:e,manifest:n??this.manifest},t);return l.then(()=>{o||(o=!0,a?.(),s(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{o||(o=!0,a?.(),s(e instanceof Error?e:Error(String(e))))}),{result:l,ready:c}}async dispose(){await this.pool?.dispose()}};function k(e){return e.mode===`source`?s(e.moduleDir,`workflow-worker`,`worker-entry.ts`):s(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}function A(e,t){let n=t.executionHints?.requirements?.capabilities??[];if(n.length===0)return e;let r=e?.customCapabilities??[];return{...e,customCapabilities:[...new Set([...r,...n])]}}var j=class{options;constructor(e){this.options=e}run(e,t,n,r){let i=n??this.options.manifest,a=A(this.options.requirements,e),o=r?.dispatchMetadata;return this.options.dispatch({config:e,...i!==void 0&&{manifest:i},...a!==void 0&&{requirements:a},...o!==void 0&&{metadata:o}},t)}},M=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let i=u.parse(e),o=await r(i);return d({config:await a(i,o,this.#e,t),loaded:o,bus:this.#e,signal:t})}};function N(){return{packages:[]}}function P(e){let t=o(e.runtimeModuleDir)===`src`?`source`:`dist`,n=F({moduleDir:e.runtimeModuleDir,defaultWorkerEntryMode:t,runner:e.workflowRunner,bus:e.bus});return{...n!==void 0&&{workflowRunner:n},executorConfig:{busUrl:e.busUrl,busAuth:{kind:`none`},platformDefaults:e.platformDefaults,makaioHome:e.makaioHome}}}function F(e){let{runner:t}=e;if(t)switch(t.mode){case void 0:case`in-process`:if(e.bus===void 0)throw Error(`InProcessWorkflowRunner requires a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'in-process'.`);return new M({bus:e.bus});case`worker-node`:{let n=e.bus,r=t.dispatch??(n===void 0?void 0:(e,t)=>n.request(l.dispatch,{config:e.config,manifest:e.manifest,requirements:e.requirements,metadata:e.metadata},{signal:t}));if(r===void 0)throw Error(`WorkerNodeRunner requires either a dispatch function or a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'worker-node'.`);return new j({dispatch:r,...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new O({workerEntry:t.workerEntry??k({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??N(),maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}function I(e){return e instanceof Error?e:Error(String(e??`WorkerNode wait aborted`))}function L(e){return typeof e.runWithReadiness==`function`}const R={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`};var z=class{options;environment=`piscina`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=c.parse({...R,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??R.suspensionStrategy})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e){let t=new AbortController,n=L(this.options.runner)?this.options.runner.runWithReadiness(e.workerConfig,t.signal,e.workerManifest):{result:this.options.runner.run(e.workerConfig,t.signal,e.workerManifest),ready:void 0},r=n.result,i=n.ready?.then(e=>({adapters:e.adapters}));return i?.catch(()=>void 0),r.catch(()=>void 0),{nodeId:e.nodeId,...i!==void 0&&{ready:i},waitForResult:async e=>{if(e.aborted)return t.abort(e.reason),Promise.reject(I(e.reason));let n,i=new Promise((e,t)=>{n=t}),a=()=>{t.abort(e.reason),n(I(e.reason))};e.addEventListener(`abort`,a,{once:!0});try{return await Promise.race([r,i])}finally{e.removeEventListener(`abort`,a)}},cancel:e=>(t.abort(e??`WorkerNode cancelled`),Promise.resolve()),terminate:()=>(t.abort(`WorkerNode terminated`),Promise.resolve())}}};export{j as a,M as i,F as n,k as o,P as r,O as s,z as t};
File without changes