@makaio/framework 1.0.0-dev-1783940945655 → 1.0.0-dev-1783973359164
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.makaio-build.json +2 -2
- package/dist/adapter-subsystem/index.d.mts +10 -0
- package/dist/adapter-subsystem/index.mjs +1 -1
- package/dist/authority-state-bootstrap-CEuKScnL.mjs +1 -0
- package/dist/bus/index.d.mts +31 -31
- package/dist/bus/index.mjs +1 -1
- package/dist/{canonical-model-CVRCW9h7.mjs → canonical-model-C31NaBJs.mjs} +1 -1
- package/dist/clients/index.d.mts +5 -5
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/canonical-model/index.mjs +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +228 -160
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/native-session-supervisor/index.d.mts +2 -2
- package/dist/contracts/session/index.d.mts +3 -3
- package/dist/contracts/shared/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/workflow/index.d.mts +3 -3
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/{detached-extension-handle-CTaQoolf.mjs → detached-extension-handle-vDK194QV.mjs} +1 -1
- package/dist/drizzle/0026_m_mrgvi7fq.sql +16 -0
- package/dist/drizzle/0027_m_mrgw0uzg.sql +1 -0
- package/dist/drizzle/0028_m_mrgx04i1.sql +1 -0
- package/dist/drizzle/0029_terminal-authority.sql +1 -0
- package/dist/drizzle/meta/_journal.json +28 -0
- package/dist/{index-Do7Wgio_2.d.mts → index-BDr2Ba122.d.mts} +1 -1
- package/dist/{index-p6dWV52m.d.mts → index-BKZAAWo2.d.mts} +330 -330
- package/dist/{index-CB2XTzvd.d.mts → index-Bbr5LEUc.d.mts} +1 -1
- package/dist/{index-5s_dN3cg2.d.mts → index-BmsPH78f2.d.mts} +33 -5
- package/dist/{index-BsEvzFey.d.mts → index-ButbwvVY.d.mts} +6 -6
- package/dist/{index-D5IEq4_E.d.mts → index-C2C1qH1Y.d.mts} +6 -4
- package/dist/{index-BtL7ONuM.d.mts → index-C6LZOiDv.d.mts} +149 -1
- package/dist/{index-DxatNFz7.d.mts → index-COC9jCdc.d.mts} +12 -12
- package/dist/{index-BcejR1Jc.d.mts → index-CtjLeK1F.d.mts} +1 -1
- package/dist/{index-Cw3cjGAT.d.mts → index-Cx8jGKOs.d.mts} +11 -11
- package/dist/{index-DNc1yLQs.d.mts → index-DHGW7dFf.d.mts} +8 -8
- package/dist/{index-DlUPWOh4.d.mts → index-DNkR5yTY.d.mts} +2876 -709
- package/dist/{index-iJP-l15K.d.mts → index-DXBiCH2y.d.mts} +27 -1
- package/dist/{index-CW6-0k3Z.d.mts → index-DlAfs3RD.d.mts} +105 -105
- package/dist/{index-sCOlgPyj.d.mts → index-DpZbaS7y.d.mts} +388 -388
- package/dist/{index-C9Q1E8Y-.d.mts → index-x2gFj3BK.d.mts} +38 -38
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{load-extensions-BtUrq2_t.mjs → load-extensions-nqL5WAKj.mjs} +1 -1
- package/dist/mcp-http-server/index.d.mts +27 -90
- package/dist/mcp-http-server/index.mjs +1 -1
- package/dist/{namespace-CQBSXm1U.d.mts → namespace-B0uZIZYT.d.mts} +20 -20
- package/dist/{namespace-CfgtqUWS.d.mts → namespace-BoA6u44C.d.mts} +156 -156
- package/dist/{namespace-CpyL93kW.d.mts → namespace-CCZXyxSe.d.mts} +9 -9
- package/dist/{namespace-D3SQQgxa2.d.mts → namespace-CukqFYHf2.d.mts} +1 -1
- package/dist/{namespace-CGgOLxiW2.d.mts → namespace-rO-C2Dgu2.d.mts} +2 -2
- package/dist/package-BYpWkSuQ.mjs +1 -0
- package/dist/package-CsFFT9iR.mjs +7 -0
- package/dist/{package-CdBiknf3.d.mts → package-DG9GSY8M.d.mts} +52 -1
- package/dist/package.json +1 -1
- package/dist/rules/index.mjs +1 -1
- package/dist/runtime-node/extension-validation.mjs +1 -1
- package/dist/runtime-node/index.d.mts +4 -89
- package/dist/runtime-node/index.mjs +24 -24
- package/dist/runtime-node/makaio-config.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
- package/dist/runtime-node/workflow-worker/index.mjs +1 -1
- package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
- package/dist/{schema-BnTOFCdU.d.mts → schema-aOwmHxaF.d.mts} +1 -1
- package/dist/{schemas--uwN5dfK2.d.mts → schemas-CoJCTFod2.d.mts} +19 -19
- package/dist/{schemas-C17AifUQ.d.mts → schemas-OaBqeEUT.d.mts} +156 -156
- package/dist/schemas-th_nuC5t.mjs +1 -0
- package/dist/service-base/index.d.mts +4 -3
- package/dist/service-base/index.mjs +1 -1
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/context-rules/index.d.mts +3 -3
- package/dist/services/execution-target/index.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/index.d.mts +104 -104
- package/dist/services/index.mjs +1 -1
- package/dist/services/session/index.d.mts +5 -5
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/session/storage/namespace.d.mts +1 -1
- package/dist/services/session/storage/schema.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +16 -16
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/subagent/index.d.mts +2 -2
- package/dist/services/subagent/index.mjs +1 -1
- package/dist/services/subagent-template/index.d.mts +2 -2
- package/dist/services/subagent-template/namespace.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/services/tools/index.mjs +1 -1
- package/dist/{session-lineage-BLw8iWAj.d.mts → session-lineage-YShrn77v.d.mts} +1 -1
- package/dist/storage/drizzle/index.d.mts +8 -1
- package/dist/storage/drizzle/index.mjs +1 -1
- package/dist/tools/index.d.mts +1 -1
- package/dist/{tools-C8vqn1KY.mjs → tools-PC_L6g2m.mjs} +1 -1
- package/dist/{transition-Bfe8VVc1.d.mts → transition-CwUIm1hJ.d.mts} +8 -0
- package/dist/{types-q95p55BF.d.mts → types-BaDYigzD.d.mts} +567 -256
- package/dist/workflow-DFJYGjq_.mjs +1 -0
- package/dist/workflow-engine/index.d.mts +690 -87
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
- package/dist/workflow-worker-BEFjCccX.mjs +1 -0
- package/package.json +9 -8
- package/dist/loop-gate-handlers-0a3dIY8O.mjs +0 -1
- package/dist/package-0gVhAVkO.mjs +0 -7
- package/dist/package-BwvGaKwn.mjs +0 -1
- package/dist/schemas-D6lj9NMg.mjs +0 -1
- package/dist/workflow-CvVAZ89A.mjs +0 -1
- package/dist/workflow-worker-CudfEstp.mjs +0 -1
- /package/dist/{await-trigger-D623tvig.mjs → await-trigger-DP-fTQc4.mjs} +0 -0
- /package/dist/{descriptor-to-package-D5SWf6TL.mjs → descriptor-to-package-Rs-OjOQU.mjs} +0 -0
- /package/dist/{esm-oHhRYTEn.mjs → esm-C_WW4-pP.mjs} +0 -0
|
@@ -0,0 +1 @@
|
|
|
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),toolObservations:[],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)}recordToolObservation(e,t){let n=[...this.subagents.values()].find(t=>t.childSessionId===e);n!==void 0&&(n.toolObservations.push(t),n.lastActivityAt=Date.now())}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,toolObservations:[...t.toolObservations]};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,...e.executionOwnerId!==void 0&&{executionOwnerId:e.executionOwnerId},...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,toolObservations:[...i.toolObservations]};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,toolObservations:e.toolObservations}))};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()};function F(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}var I=class extends Error{code;constructor(e){super(`Subagent failure finalization failed (${e}).`),this.code=e,this.name=`SubagentFailureFinalizationError`}},L=class extends m{machineId;delegationAllowSet;requestHandlerPriority;executionOwnerId;manager;pendingChildSessionClose=new Set;spawningExecutions=new Set;constructor(e=n,t=a,r,i=new Set,o=0,s=crypto.randomUUID()){super(e),this.machineId=r,this.delegationAllowSet=i,this.requestHandlerPriority=o,this.executionOwnerId=s,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=>{e.payload.executionOwnerId!==void 0&&e.payload.executionOwnerId!==this.executionOwnerId||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.registerHandler(i.tool.completed,e=>{e.payload.sessionId===void 0||e.payload.success===void 0||this.manager.recordToolObservation(e.payload.sessionId,{toolName:e.payload.toolName,outcome:e.payload.success?`success`:`failure`,...e.payload.success===!0&&e.payload.artifactResult!==void 0?{artifact:e.payload.artifactResult}:{}})}),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,executionOwnerId:this.executionOwnerId};this.registerHandler(d.getStatus,t=>{let n=T(e,t.payload);t.setResult(n)},{priority:this.requestHandlerPriority}),this.registerHandler(d.spawn,async t=>{if(!this.isRemoteDelegationAllowed(t))return;let n=await E(e,s.parse(t.payload));t.setResult(n)},{priority:this.requestHandlerPriority}),this.registerHandler(d.await,async t=>{let n=await D(e,t.payload);t.setResult(n)},{priority:this.requestHandlerPriority}),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)},{priority:this.requestHandlerPriority}),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(),this.spawningExecutions.clear()}async handleSpawned(e){let{subagentId:t,parentSessionId:n,task:r,spawningToolCallId:i}=e,a=this.manager.get(t);if(!(a&&a.status!==`spawning`)&&!this.spawningExecutions.has(t)){this.spawningExecutions.add(t);try{return await this.executeSpawned(e,n,r,i)}finally{this.spawningExecutions.delete(t)}}}async executeSpawned(e,n,r,i){let{subagentId:a}=e,o=c.parse({...e.config,task:r}),s=o.adapterName?.trim();if(!s)return this.failSpawn(a,n,`adapter_start`,`Subagent spawn requires a non-empty adapterName`);this.manager.get(a)||this.manager.track({subagentId:a,parentSessionId:n,config:o,depth:e.depth??1});let l,u;try{u=await this.buildExecutionTargetResolutionParams(n,o.executionTargetId);let e=await this.bus.requestOptional(t.resolve,u),r;if(e.handled)r=e.data.executionTarget;else if(u.executionTargetId!=null)throw Error(`Execution target resolver unavailable for explicit target '${u.executionTargetId}'`);else r=P;if(r.type!==`local`)return this.failSpawn(a,n,`adapter_start`,`Execution target type '${r.type}' is not yet supported for subagents`);l=u.executionTargetId??void 0}catch(e){return this.failSpawn(a,n,`adapter_start`,e)}let d;try{d=await this.createChildSessionForSpawn(a,n,o,l,u,i)}catch(e){return this.failSpawn(a,n,`session_create`,e)}let f=this.manager.get(a);if(!(f&&this.isTerminalSubagentStatus(f.status)))try{await this.startAdapterForSubagent(s,o,d,r,u.targetWorkingDirectory)}catch(e){return this.failSpawn(a,n,`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,i.targetWorkingDirectory,a));return this.manager.setChildSessionId(e,s),this.pendingChildSessionClose.has(e)&&await this.closeChildSession(e),s}async startAdapterForSubagent(e,t,n,i,a){let{adapterId:o}=await this.bus.request(h.resolveId,{adapterName:e,...this.machineId!==void 0&&{machineId:this.machineId}}),s=t.providerContext;if(s?.state===`resolved`&&t.providerConfigId!==void 0&&t.providerConfigId!==s.providerConfigId)throw Error(`Subagent providerConfigId "${t.providerConfigId}" does not match its resolved provider context "${s.providerConfigId}".`);if(s?.state===`unresolved`&&t.providerConfigId!==void 0)throw new g(`provider-context-unresolved`,e,t.providerConfigId);let c=s??(t.providerConfigId?await _(this.bus,{adapterName:e,providerConfigId:t.providerConfigId}):void 0),l=F({adapterConfig:t.adapterConfig,cwd:a,allowedTools:t.tools,disallowedTools:t.disallowedTools,allowedDirectories:t.allowedDirectories}),u=await this.bus.request(r.startAgent,{adapterId:o,role:`lead`,...c!==void 0&&{providerContext:c},sessionId:n,initialMessage:i,model:t.model,reasoningEffort:t.reasoningEffort,systemPrompt:t.systemPrompt,responseSchema:t.responseSchema,...l,...t.harnessId!==void 0&&{harnessId:t.harnessId}});if(!u||u.success!==!0)throw Error(u?.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 I(`child-session-close-failed`)),o.status===`rejected`&&s.push(new I(`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{...r.executionTargetId!==void 0&&{executionTargetId:r.executionTargetId},...r.targetWorkingDirectory!==void 0&&{targetWorkingDirectory:r.targetWorkingDirectory}}}buildChildSessionCreatePayload(e,t,n,r,i){return{branchKind:`subagent`,parentSessionId:e,contextInheritance:t.contextMode===`fork`?`parent-history`:`none`,...n!==void 0&&{executionTargetId:n},...r!==void 0&&{targetWorkingDirectory:r},...i!==void 0&&{spawningToolCallId:i}}}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 I(`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 R=p(`subagent-service`);function z(e=0){return{name:R.name,displayName:`Subagent Service`,version:`0.1.0`,critical:!0,surface:`headless`,dependencies:[f(`session`)],create:t=>new L(t.bus,a,t.machineId,new Set,e)}}const B=z();export{L as a,I as i,z as n,C as o,B as r,y as s,R as t};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{$ as e,A as t,B 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 m,P as ee,Q 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 ue,_ as h,a as de,b as fe,c as pe,d as me,et as he,f as ge,g as _e,h as ve,i as ye,it as g,j as be,k as xe,m as Se,n as Ce,nt as we,p as Te,q as Ee,r as De,rt as Oe,s as ke,tt as Ae,u as je,v as Me,w as Ne,x as Pe,y as Fe,z as Ie}from"./authority-state-bootstrap-CEuKScnL.mjs";import{matchesFilter as Le,matchesSubscription as Re}from"@makaio/framework/bus";import{ArtifactSubjects as ze,EXECUTION_LIST_DEFAULT_LIMIT as Be,EXECUTION_LIST_MAX_LIMIT as _,EXECUTION_LIST_MIN_LIMIT as v,EXTERNAL_EXECUTION_ID_PREFIX as Ve,ExecutionHintsSchema as He,ExecutionsByArtifactRefsQuerySchema as Ue,JsonPatchOperationSchema as We,JsonValueSchema as Ge,SessionSubjects as Ke,WORKFLOW_CANCELLED_REASON as qe,WorkLogFrameEntrySchema as Je,WorkflowError as y,WorkflowErrorCode as Ye,WorkflowNamespace as Xe,WorkflowStepTypeSchema as Ze,WorkflowSubjects as b,createWorkflowCancelSubject as Qe,createWorkflowFinalizerNamespace as $e,dep as et,extensionToken as tt,serializeArtifactRef as nt}from"@makaio/framework/contracts";import{BaseService as rt}from"@makaio/framework/service-base";import{defineDialectSchema as it,executeTransaction as x,getDatabaseDialect as at,registerDrizzleHandlers as ot,resolveSchema as S,serializeDatabaseOperation 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 st,gte as ct,isNotNull as lt,isNull as k,lt as ut,lte as dt,notInArray as ft,or as pt,sql as A,sum as j}from"drizzle-orm";import{compile as mt}from"@makaio/framework/expression";import*as ht from"node:os";import{SessionToken as gt}from"@makaio/framework/services";const _t=t.postgres,vt=n.postgres,yt=f.postgres,bt=s.postgres,xt=u.postgres,St=ee.postgres,Ct=se.postgres,wt=he.postgres,Tt=ce.postgres,Et=l.postgres,Dt=te.postgres,Ot=c.postgres,kt=ne.postgres,At=we.postgres,M=it({workflowDefinitions:xe,workflowExecutions:Ie,workflowExecutionFrames:be,workflowGateInstances:oe,workflowStepSpans:o,workflowExecutionLinks:p,workflowRunContexts:ae,worklogSummaries:e,worklogFrameEntries:le,worklogArtifactWrites:Ee,worklogGateEvents:ue,workflowExecutionState:a,workflowExecutionStateEvents:d,workflowFinalizations:Ae},{workflowDefinitions:_t,workflowExecutions:vt,workflowExecutionFrames:yt,workflowGateInstances:bt,workflowStepSpans:xt,workflowExecutionLinks:St,workflowRunContexts:Ct,worklogSummaries:wt,worklogFrameEntries:Tt,worklogArtifactWrites:Et,worklogGateEvents:Dt,workflowExecutionState:Ot,workflowExecutionStateEvents:kt,workflowFinalizations:At});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 P(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 jt(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 F(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:P(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,successFinalizerId:e.successFinalizerId??void 0,executionHints:e.executionHints??void 0}}function Mt(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,successFinalizerId:e.successFinalizerId??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Nt(e,t){let{workflowDefinitions:n}=S(t,M),r=st(n),i=e.on(m.get,async e=>{let r=await t.select().from(n).where(O(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?F(r[0]):null})}),a=e.on(m.set,async i=>{let a=i.payload.workflow,o=Date.now(),s=Mt(a,o),c=await C(t,async()=>{let e=await t.insert(n).values(s).onConflictDoNothing({target:n.id}).returning();if(e.length>0)return{kind:`created`,row:e[0]};let[i]=await t.update(n).set({name:s.name,root:s.root,updatedAt:o,createdAt:A`COALESCE(${r.createdAt}, ${o})`,description:s.description===null?A`${r.description}`:s.description,inputSchema:s.inputSchema===null?A`${r.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?A`${r.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?A`${r.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?A`${r.artifact}`:s.artifact,triggers:s.triggers===null?A`${r.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?A`${r.canvasLayout}`:s.canvasLayout,source:s.source===null?A`${r.source}`:s.source,successFinalizerId:s.successFinalizerId,executionHints:s.executionHints===null?A`${r.executionHints}`:s.executionHints,...N(a.scope)}).where(O(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});c&&await e.emit(c.kind===`created`?g.definition.created:g.definition.updated,F(c.row)),i.setResult({id:a.id})}),o=e.on(m.delete,async r=>{let i=(await C(t,()=>t.delete(n).where(O(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(g.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),s=e.on(m.list,async e=>{let r=e.payload,i=r.scope?jt(n,r.scope):[],a=i.length>0?await t.select().from(n).where(w(...i)):await t.select().from(n);e.setResult({workflows:a.map(F)})});return()=>{i(),a(),o(),s()}}function Pt(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 Ft(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 It(e,t){let{workflowExecutionFrames:n}=S(t,M),r=e.on(m.setFrame,async e=>{let{executionId:r,frame:i}=e.payload,a=Ft(r,i);await C(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(m.getFrame,async e=>{let r=await t.select().from(n).where(O(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?Pt(r[0]):null})}),a=e.on(m.listFrames,async e=>{let r=await t.select().from(n).where(O(n.executionId,e.payload.executionId)).orderBy(T(n.startedAt),T(n.frameId));e.setResult({frames:r.map(Pt)})});return()=>{r(),i(),a()}}function Lt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function I(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 L(e){return{id:Lt(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 Rt(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??Be;if(!Number.isInteger(i)||i<v||i>_)throw Error(`Gate instance list limit must be an integer between ${v} and ${_}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[O(r.executionId,e)],...t===void 0?[]:[O(r.status,t)]]}}function zt(e,t){let{workflowExecutions:n,workflowGateInstances:r}=S(t,M),i=e.on(m.setGateInstance,async e=>{let n=e.payload.gate,i=L(n);await C(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),a=e.on(m.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=L(n),a=await C(t,()=>t.update(r).set(i).where(w(O(r.id,i.id),O(r.status,`waiting`))).returning({id:r.id}));e.setResult({accepted:a.length===1})}),o=e.on(m.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload,o=[O(r.executionId,n),O(r.nodeId,i)];a!==void 0&&o.push(O(r.frameId,a));let s=await t.select().from(r).where(w(...o)).limit(1);e.setResult({gate:s[0]?I(s[0]):null})}),s=e.on(m.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Rt(n,i,a,r),c=await t.select().from(r).where(w(...s)).orderBy(D(r.createdAt),D(r.id)).limit(o);e.setResult({gates:c.map(I)})}),c=e.on(m.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,O(r.executionId,n.id)).where(w(O(r.status,`waiting`),O(n.status,`paused`),lt(r.timeoutMs)));e.setResult({gates:i.map(e=>I(e.gate))})});return()=>{i(),a(),o(),s(),c()}}function Bt(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 Vt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Ht(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=S(t,M),i=e.on(m.setSpan,async e=>{let{span:r}=e.payload;await C(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),a=e.on(m.listSpans,async e=>{let r=await t.select().from(n).where(O(n.executionId,e.payload.executionId)).orderBy(T(n.startedAt),T(n.stepId),T(n.frameId));e.setResult({spans:r.map(Bt)})}),o=e.on(m.setExecutionLink,async e=>{let{link:n}=e.payload;await C(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),s=e.on(m.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:i}=e.payload;if(n===void 0&&i===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[O(r.sourceExecutionId,n)],...i===void 0?[]:[O(r.targetExecutionId,i)]],o=t.select().from(r).where(w(...a));e.setResult({links:(await o).map(Vt)})});return()=>{i(),a(),o(),s()}}function R(e,t){return t===null?at(e)===`postgres`?A`'null'::jsonb`:A`'null'`:t}function Ut(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 Wt(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 Gt(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Wt(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:P(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`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority}}}function Kt(e){let t=Ut(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,terminalAuthority:e.terminalAuthority??null}}async function qt(e,t,n){let r=Kt(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Jt(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=S(t,M),a=e.on(m.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await x(t,async e=>{if(await qt(e,a,n),o===void 0)return;let s=Date.now(),c=R(t,o);await e.insert(r).values({executionId:a.executionId,sequence:0,value:c,updatedAt:s}).onConflictDoNothing(),await e.insert(i).values({executionId:a.executionId,sequence:0,patch:[],value:c,createdAt:s}).onConflictDoNothing()}),e.setResult({executionId:a.executionId})}),o=e.on(m.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(O(n.executionId,r)),a=i[0]?Gt(i[0]):null;e.setResult({runContext:a})});return()=>{a(),o()}}async function Yt(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=S(e,M),a=Date.now(),o=R(e,n);await x(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 Xt(e,t){let{workflowExecutionState:n}=S(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 Zt(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=S(e,M),a=Date.now(),o=R(e,t.nextValue);return x(e,async e=>{let s=(await e.select().from(n).where(O(n.executionId,t.executionId)).limit(1))[0];if(!s)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let c=s.sequence+1,l=i(s.value,t.nextValue);if((await e.update(n).set({sequence:c,value:o,updatedAt:a}).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(s.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:c,patch:l,value:o,createdAt:a}),{executionId:t.executionId,sequence:c,patch:l,value:t.nextValue}})}function Qt(e,t){let n=e.on(m.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await Yt(t,n,r),e.setResult({})}),r=e.on(m.getState,async e=>{let{executionId:n}=e.payload,r=await Xt(t,n);e.setResult({state:r})}),i=e.on(m.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Zt(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function $t(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 en(e,t){let{worklogSummaries:n}=S(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function tn(e,t){let{worklogSummaries:n}=S(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:nn(t),setWhere:ft(n.status,[`completed`,`failed`,`cancelled`])})}function nn(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 z(e,t){let{worklogSummaries:n}=S(e,M),r=await e.select().from(n).where(O(n.executionId,t)).limit(1);return r[0]?$t(r[0]):null}async function rn(e,t={}){let{worklogSummaries:n}=S(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($t),total:u[0]?.count??0}}async function an(e,t){let{worklogFrameEntries:n}=S(e,M);await e.insert(n).values(t).onConflictDoNothing()}async function on(e,t){let{worklogFrameEntries:n}=S(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:ft(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function B(e,t){let{worklogFrameEntries:n}=S(e,M);return(await e.select().from(n).where(O(n.frameId,t)).limit(1))[0]??null}async function sn(e,t){let n=await B(e,t);return n===null?null:Je.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 cn(e,t){let{worklogArtifactWrites:n}=S(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function ln(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function V(e,t){let{worklogGateEvents:n}=S(e,M);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function un(e,t){let{worklogGateEvents:n}=S(e,M);return(await e.select().from(n).where(O(n.id,t)).limit(1))[0]??null}function dn(e,t,n){return`${e}:${t}:${n}`}async function fn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(O(t.executionId,n)).returning();return r}async function pn(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 mn(e){return e.hasMeasurements}async function hn(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 gn(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 _n(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=S(e,M);if(at(e)===`sqlite`){await gn(e,n,r,t);return}await x(e,async e=>{if(await fn(e,n,t)===void 0)return;let i=await pn(e,r,t);mn(i)&&await hn(e,n,t,i)})}async function vn(e,t={}){let{worklogSummaries:n}=S(e,M),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[O(n.workflowId,r)],...i===void 0?[]:[ct(n.startedAt,i)],...a===void 0?[]:[dt(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,finalizing:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function yn(e,t,n,r,i){let a=await B(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(ze.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(g.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const bn=new Set([`completed`,`failed`,`cancelled`]);function xn(e){return bn.has(e)}async function Sn(e,t){return await en(e,{executionId:t.executionId,workflowId:t.workflowId,workflowName:null,status:`running`,startedAt:t.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),!0}async function Cn(e,t){let n=t.completedAt??Date.now(),r=await z(e,t.executionId);return r!==null&&xn(r.status)?!1:(await tn(e,{executionId:t.executionId,workflowId:r?.workflowId??t.executionId,workflowName:r?.workflowName??null,status:`completed`,startedAt:r?.startedAt??n-t.totalDuration,completedAt:n,durationMs:t.totalDuration,totalInputTokens:r?.totalInputTokens??null,totalOutputTokens:r?.totalOutputTokens??null,totalEstimatedCost:r?.totalEstimatedCost??null,error:null,failedNodeId:null}),!0)}async function wn(e,t,n,r,i,a){let o=await z(e,t);if(o!==null&&xn(o.status))return!1;let s=o?.startedAt??a;return await tn(e,{executionId:t,workflowId:o?.workflowId??t,workflowName:o?.workflowName??null,status:n,startedAt:s,completedAt:a,durationMs:a-s,totalInputTokens:o?.totalInputTokens??null,totalOutputTokens:o?.totalOutputTokens??null,totalEstimatedCost:o?.totalEstimatedCost??null,error:r,failedNodeId:i}),!0}function Tn(e,t){return[e.on(g.execution.started,async n=>{let{executionId:r}=n.payload;await H(`execution.started[${r}]`,async()=>{await C(t,()=>Sn(t,n.payload))&&await U(e,r)})}),e.on(g.execution.completed,async n=>{let{executionId:r}=n.payload;await H(`execution.completed[${r}]`,async()=>{await C(t,()=>Cn(t,n.payload))&&await U(e,r)})}),e.on(g.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await H(`execution.failed[${r}]`,async()=>{await C(t,()=>wn(t,r,`failed`,i,a??null,o))&&await U(e,r)})}),e.on(g.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await H(`execution.cancelled[${r}]`,async()=>{await C(t,()=>wn(t,r,`cancelled`,null,null,i))&&await U(e,r)})})]}const En=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function Dn(e){return En.has(e)}function On(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 kn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await B(t,r);c!==null&&Dn(c.status)||(await on(t,{frameId:r,executionId:n,...On(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await _n(t,n),await U(e,n))}async function An(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await B(t,r);l!==null&&Dn(l.status)||(await on(t,{frameId:r,executionId:n,...On(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await U(e,n))}function jn(e,t){return[e.on(g.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 an(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(g.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await H(`frame.completed[${i}]`,()=>kn(e,t,r,i,a,o,s))}),e.on(g.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await H(`frame.failed[${i}]`,()=>An(e,t,r,i,a,o,s,c))})]}const Mn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function Nn(e,t){return[e.on(g.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await H(`gate.suspended[${i}]`,async()=>{await V(t,{id:dn(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(g.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await H(`gate.resumed[${i}]`,async()=>{let n=dn(r,a,i),s=await un(t,n),c=Date.now();await V(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(g.gate.resolved,async n=>Pn(n.payload,e,t)),e.on(g.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 yn(e,t,i,a,o);if(n===null)return;let s=Date.now();await cn(t,{id:ln(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 Pn(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=dn(r,a,i),c=await un(n,s),l=Date.now();await V(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Mn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await U(t,r)})}function Fn(e,t){let n=[...Tn(e,t),...jn(e,t),...Nn(e,t),e.on(g.worklog.get,async e=>{let{executionId:n}=e.payload,r=await z(t,n);e.setResult({summary:r})}),e.on(g.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await sn(t,n);e.setResult({frame:r})}),e.on(g.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await rn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(g.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await vn(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 In(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 Ln(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 Rn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function zn(e,t,n,r,i){let a=Ln(r,i);if(n.externalSettlementFingerprint!==null){Rn(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(Vn(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Rn(c.externalSettlementFingerprint,a,r.executionId)}function Bn(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 Vn(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 Hn(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 Un(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 Wn(e,t){return In({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function Gn(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 Kn(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 qn(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 Jn(e,t,n,r){if(!t.id.startsWith(Ve))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}=S(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 x(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`);Gn(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):Kn(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(In(n))}else qn(i,n)}})}async function Yn(e,t,n,r,i){if(r.frame!==void 0){let n=await Hn(e,t,r);return n!==void 0&&Bn(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=Ze.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 Xn(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await fn(e,a,n.id),c=await Yn(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=Wn(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await pn(e,o,n.id),d=mn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...Un(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:nn(p)}),d&&await hn(e,a,n.id,u)}async function Zn(e,t){if(!t.executionId.startsWith(Ve))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}=S(e,M);return x(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=Ln(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),Vn(r,t,o),await zn(e,n,r,t,o)}}else Vn(a,t,o),await zn(e,n,a,t,o);return await Xn(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function Qn(e,t,n){let r=e.on(m.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await Jn(t,i,a,n),await U(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(m.settleExternalExecution,async n=>{let r=await Zn(t,n.payload);await U(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function G(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function $n(e,t){return e.state===`claimed`&&e.executionId===t.executionId&&e.workflowId===t.workflowId&&e.finalizerId===t.finalizerId&&e.transitionKey===t.transitionKey&&e.claimToken===t.claimToken&&e.intent.status===t.intent.status&&e.intent.completedAt===t.intent.completedAt&&e.intent.error===t.intent.error&&e.intent.reason===t.intent.reason}function er(e,t){if(e.executionId!==t.executionId||e.workflowId!==t.workflowId||e.finalizerId!==t.finalizerId||e.transitionKey!==t.transitionKey||e.claimToken!==t.claimToken)throw Error(`workflow finalization publication claim does not match durable transition ${t.executionId}`)}async function tr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=S(e,M);return x(e,async e=>{let i=await e.select().from(r).where(O(r.executionId,t.executionId)).limit(1);return i[0]?$n(i[0],t):(await e.update(n).set({status:`finalizing`}).where(w(O(n.id,t.executionId),O(n.workflowId,t.workflowId),O(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function nr(e){return{status:e.status,completedAt:e.completedAt,error:e.status===`failed`?e.error??`Workflow finalization failed`:null,reason:e.status===`cancelled`?e.reason??null:null}}async function rr(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=S(e,M);return x(e,async e=>{let o=(await e.select().from(a).where(O(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(nr(o.intent)).where(w(O(i.id,t),O(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(w(O(a.executionId,t),O(a.claimToken,n),O(a.state,`claimed`))),!0)})}async function ir(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=S(e,M);return x(e,async e=>{let s=(await e.select().from(o).where(O(o.executionId,t)).limit(1))[0];return!s||s.claimToken!==n||s.state===`acknowledged`?!1:s.state===`failed`?!0:(await e.update(a).set({status:`failed`,error:r,reason:null,completedAt:i}).where(w(O(a.id,t),O(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(w(O(o.executionId,t),O(o.claimToken,n),O(o.state,`claimed`))),!0)})}async function ar(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=S(t,M),a=(await t.select().from(i).where(O(i.executionId,n.executionId)).limit(1))[0];if(!a||(er(a,n),a.state===`claimed`||a.publishedAt!==null))return;let o=(await t.select({startedAt:r.startedAt,status:r.status,error:r.error,reason:r.reason,completedAt:r.completedAt}).from(r).where(O(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(g.execution.completed,{executionId:a.executionId,workflowId:a.workflowId,totalDuration:o.completedAt-o.startedAt,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`failed`)await e.emit(g.execution.failed,{executionId:a.executionId,workflowId:a.workflowId,error:o.error??`Workflow finalization failed`,completedAt:o.completedAt,transitionKey:a.transitionKey});else if(o.status===`cancelled`)await e.emit(g.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await C(t,()=>t.update(i).set({publishedAt:Date.now()}).where(w(O(i.executionId,a.executionId),k(i.publishedAt))))}}function or(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>ar(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function sr(e,t){let n=or(e,t),r=e.on(m.claimFinalization,async e=>{e.setResult({claimed:await tr(t,e.payload.claim)})}),i=e.on(m.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=S(t,M),r=await t.select().from(n).where(w(O(n.finalizerId,e.payload.finalizerId),O(n.state,`claimed`)));e.setResult({claims:r.map(G)})}),a=e.on(m.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=S(t,M),r=await t.select().from(n).where(w(pt(O(n.state,`acknowledged`),O(n.state,`failed`)),O(n.finalizerId,e.payload.finalizerId),k(n.publishedAt)));e.setResult({claims:r.map(G)})}),o=e.on(m.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),s=e.on(m.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await rr(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=S(t,M),c=await t.select().from(s).where(O(s.executionId,r)).limit(1);c[0]&&await n(G(c[0]))}),c=e.on(m.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await ir(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=S(t,M),l=await t.select().from(c).where(O(c.executionId,r)).limit(1);l[0]&&await n(G(l[0]))});return()=>{r(),i(),a(),o(),s(),c()}}function cr(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:P(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 lr(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(...jt(a,t)),r){let e=pt(ut(a.startedAt,r.startedAt),w(O(a.startedAt,r.startedAt),ut(a.id,r.id)));e&&o.push(e)}return o}async function ur(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}=S(e,M),u=K(t);await x(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 qt(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=R(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 dr(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}=S(e,M),a=K(t),o=L(n);await x(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 fr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=S(e,M);return x(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=>({...I(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=L(t);await e.update(a).set(n).where(O(a.id,n.id))}return{cancelled:!0,gates:o}})}async function pr(e,t,n,r,i,a){let{workflowExecutions:o}=S(e,M);return x(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 mr(e,t){let{workflowExecutions:n}=S(t,M),r=e.on(m.getExecution,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(O(n.id,r));e.setResult({execution:i[0]?cr(i[0]):null})}),i=e.on(m.setExecution,async e=>{let r=e.payload.execution,i=K(r);await C(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),a=e.on(m.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await ur(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),o=e.on(m.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await dr(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),s=e.on(m.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await pr(t,n,r,i,a,o);e.setResult({success:s})}),c=e.on(m.pauseRunningExecution,async e=>{let{workflowExecutions:n}=S(t,M),r=await C(t,()=>t.update(n).set({status:`paused`}).where(w(O(n.id,e.payload.executionId),O(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),l=e.on(m.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await fr(t,n,r,i))});return()=>{r(),i(),a(),o(),s(),c(),l()}}function hr(e,t){let{workflowExecutions:n}=S(t,M),r=e.on(m.listExecutions,async e=>{let{workflowId:r,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(r===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=lr(r,i,a,s,c,n),u=o??Be;if(!Number.isInteger(u)||u<v||u>_)throw Error(`Execution list limit must be an integer between ${v} and ${_}.`);let d=await t.select().from(n).where(w(...l)).orderBy(D(n.startedAt),D(n.id)).limit(u);e.setResult({executions:d.map(cr)})}),i=e.on(m.listExecutionsByArtifactRefs,async e=>{let r=Ue.safeParse(e.payload);if(!r.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${r.error.message}`);let{refs:i,limitPerRef:a}=r.data,o={};for(let e of i){let r=await t.select().from(n).where(w(O(n.artifactKind,e.kind),O(n.artifactId,e.id))).orderBy(D(n.startedAt),D(n.id)).limit(a);r.length>0&&(o[nt(e)]=r.map(cr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function gr(e,t){let n=Nt(e,t),r=mr(e,t),i=hr(e,t),a=It(e,t),o=zt(e,t),s=Ht(e,t),c=Jt(e,t),l=Qt(e,t),u=Fn(e,t),d=Qn(e,t,K),f=sr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function _r(e){return e.startsWith(Ve)}function vr(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function yr(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 br(e,t){let{runContext:n}=await e.request(m.getRunContext,{executionId:t});if(n===null)throw Error(`Run context not found for execution: ${t}`);if(n.definitionSnapshot!==void 0)return n.definitionSnapshot;let{workflow:r}=await e.request(m.get,{id:n.workflowId});return r??void 0}function xr(e){return[e.on(g.getDefinition,async t=>{let n=await e.request(m.get,{id:t.payload.id});t.setResult(n)}),e.on(g.setDefinition,async t=>{let n=await e.request(m.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(g.deleteDefinition,async t=>{let n=await e.request(m.delete,{id:t.payload.id});t.setResult(n)}),e.on(g.listDefinitions,async t=>{let n=await e.request(m.list,t.payload);t.setResult(n)}),e.on(g.getExecution,async t=>{let n=await e.request(m.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(g.listExecutions,async t=>{let n=await e.request(m.listExecutions,t.payload);t.setResult(n)}),e.on(g.listExecutionsByArtifactRefs,async t=>{let n=await e.request(m.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(g.listSpans,async t=>{let n=await e.request(m.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(g.listFrames,async t=>{let n=await e.request(m.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(g.listGateInstances,async t=>{let n=await e.request(m.listGateInstances,t.payload);t.setResult(n)}),e.on(g.setExecutionLink,async t=>{let n=await e.request(m.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(g.listExecutionLinks,async t=>{let n=await e.request(m.listExecutionLinks,t.payload);t.setResult(n)}),e.on(g.getRunContext,async t=>{let{executionId:n}=t.payload;if(!q(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(m.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...Sr(e)]}function Sr(e){return[e.on(g.registerExternalExecution,async t=>{let n=Oe.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:a}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let o=n.executionId??re(`wfx-ext`);if(!_r(o))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let s=n.startedAt??Date.now(),c={id:o,workflowId:r,status:`running`,inputs:a===void 0?{}:a,startedAt:s,scope:i??{type:`global`},...vr(n)},l=Cr(o,s,n.frame),u=await e.request(m.setExternalExecutionStart,{execution:c,...l===void 0?{}:{frame:l}});t.setResult(u)}),e.on(g.completeExternalExecution,async t=>{let n=Oe.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!q(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!_r(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let a=wr(n),o=await e.request(m.settleExternalExecution,{executionId:r,status:i,...yr(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...a===void 0?{}:{frame:a}});t.setResult({success:o.success})})]}function Cr(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 wr(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 Tr(e){return[e.on(g.state.get,async t=>{let{executionId:n}=t.payload;if(!q(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(m.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(g.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:a}=t.payload;if(!q(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let o=await br(e,n);o!==void 0&&Ne(o,a,`next`),We.array().parse(i);let s=await e.request(m.patchState,{executionId:n,expectedSequence:r,nextValue:a});e.emit(g.state.updated,{executionId:s.executionId,sequence:s.sequence,patch:s.patch,value:s.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:s.executionId,sequence:s.sequence,value:s.value})})]}function Er(e,t){return[e.on(g.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}async function Dr(e,t){let{runContext:n}=await e.bus.request(m.getRunContext,{executionId:t});if(n===null)throw new y(Ye.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function Or(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function kr(e,t){let n=await Dr(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:Or(t.mode,t.reason)}]};return t.mode===`snapshot`?await Nr(e,n,l):jr(n)?await Pr(e,n,l):await je(e,n.workflowId,l)}function Ar(e,t){return jr(e)?t.id:e.workflowId}function jr(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function Mr(e){let t=e.definitionSnapshot;if(t===void 0)throw new y(Ye.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Nr(e,t,n){let r=Mr(t);return ge(e,Ar(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 Pr(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`)return me(e,t.source.path,n);let r=Mr(t);return ge(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 Fr=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(m.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:n}=await this.bus.request(m.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function Ir(e){if(e!==void 0)return Lr(e)?e:{}}function Lr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Rr(e){if(e!==void 0)return Ge.parse(e)}function zr(e){if(e!==void 0)return He.parse(e)}function Br(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${ht.homedir()}/.makaio`,os:_e(process.platform),arch:process.arch}}function Vr(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:Br(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Hr(e){return e?.status===`paused`}function Ur(e){return e?.status===`waiting`}async function Wr(e,t,n,r,i,a,o){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(m.restorePausedGateResumeState,{execution:i,gate:a})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${o}' after resume launch failure:`,e)}}async function Gr(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(m.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Kr(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function qr(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(m.getGateInstance,t);return Ur(n)?n:null}let{gates:n}=await e.request(m.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}var Jr=class extends rt{static storage={drizzle:gr};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;successFinalizers=new Map;durableLifecycleTransitions=new Map;lifecyclePublications=new Map;publishingLifecycleExecutions=new Set;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...ie,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new Fr(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=$e(e);this.bus.registerNamespace(t);let r={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,r);try{await Pe(this.buildFinalizerDeps())}catch(t){throw this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e),t}let i=!1;return()=>{i||(i=!0,this.successFinalizers.get(e)===r&&this.successFinalizers.delete(e))}}async acceptAuthorityRunnerResult(e,t){if(t.status===`paused`)throw Error(`authority runner result must be terminal`);if(t.executionId!==e)throw Error(`authority runner result execution identity mismatch`);let{execution:n}=await this.bus.request(m.getExecution,{executionId:e});if(!n)throw Error(`Authority runner execution not found: ${e}`);if(n.workflowId!==t.workflowId)throw Error(`authority runner result workflow identity mismatch`);let r;if(n.status===`finalizing`){let{workflow:n}=await this.loadAuthorityRunnerContext(e,t.workflowId);r=await this.registerAuthorityResultFinalizer(n)}let i=await this.resolveAuthorityRunnerReplay(n,t).finally(()=>r?.());if(i!==void 0)return{accepted:!0,status:i};if(n.status!==`running`)throw Error(`Authority runner execution is ${n.status}`);let{runContext:a,workflow:o}=await this.loadAuthorityRunnerContext(e,t.workflowId),s=await this.registerAuthorityResultFinalizer(o),c=this.activeExecutions.get(e),l=!1;if(!c)this.activeExecutions.set(e,{execution:n,workflow:o,runContext:a,runtimeHandlers:new Map,runtimeLoopGates:new Map}),l=!0;else if(c.execution.workflowId!==t.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await ve({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},t)}finally{l&&this.activeExecutions.delete(e),s?.()}let u=await this.bus.request(m.getExecution,{executionId:e});if(!u.execution||!fe(u.execution.status,t.status))throw Error(`Authority runner result did not settle compatibly with ${t.status}`);return{accepted:!0,status:u.execution.status}}async resolveAuthorityRunnerReplay(e,t){if(e.status===`finalizing`){if(t.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await Pe(this.buildFinalizerDeps());let n=await this.bus.request(m.getExecution,{executionId:e.id});if(!n.execution)throw Error(`Authority runner success finalization execution is missing`);if(!fe(n.execution.status,t.status))throw Error(`authority runner result conflicts with terminal execution`);return n.execution.status}if(!(e.status!==`completed`&&e.status!==`failed`&&e.status!==`cancelled`)){if(!fe(e.status,t.status))throw Error(`authority runner result conflicts with terminal execution`);return e.status}}async loadAuthorityRunnerContext(e,t){let{runContext:n}=await this.bus.request(m.getRunContext,{executionId:e});if(!n)throw Error(`Authority runner run context not found: ${e}`);if(n.executionId!==e||n.workflowId!==t)throw Error(`authority runner run context identity mismatch`);if(n.terminalAuthority!==`authority`)throw Error(`authority runner result requires terminalAuthority=authority`);let r=n.definitionSnapshot??(await this.bus.request(m.get,{id:n.workflowId})).workflow;if(!r||r.id!==t)throw Error(`authority runner workflow definition is unavailable or mismatched`);return{runContext:n,workflow:r}}registerAuthorityResultFinalizer(e){return!e.successFinalizerId||this.successFinalizers.has(e.successFinalizerId)?Promise.resolve(void 0):this.registerSuccessFinalizer(e.successFinalizerId)}async onInit(){this.registerExecutionHandlers(),this.addCleanup(Ce(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)}));for(let e of xr(this.bus))this.addCleanup(e);for(let e of Tr(this.bus))this.addCleanup(e);for(let e of Er(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()),await Promise.allSettled(this.durableLifecycleTransitions.values()),await Promise.allSettled(this.lifecyclePublications.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs,successFinalizers:this.successFinalizers,resolveSuccessFinalizerId:e=>this.activeExecutions.get(e)?.workflow.successFinalizerId,durableLifecycleTransitions:this.durableLifecycleTransitions,lifecyclePublications:this.lifecyclePublications,publishingLifecycleExecutions:this.publishingLifecycleExecutions}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>Br(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Ke.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=>Vr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(g.acceptAuthorityRunnerResult,async e=>{if(!e.origin.local)throw Error(`authority runner result acceptance is local-authority only`);let{executionId:t,result:n}=e.payload;e.setResult(await this.acceptAuthorityRunnerResult(t,n))}),this.registerHandler(g.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 je(this.buildStartDeps(),t,{input:Rr(n),config:Ir(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:zr(c),scopeOverride:s});e.setResult({executionId:l})}catch(e){if(e instanceof y)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(g.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 kr(this.buildStartDeps(),{executionId:t,mode:n,input:Rr(r),config:Ir(i),parentSessionId:a,triggerPayload:o,artifactRef:s,executionHints:zr(l),scopeOverride:c,reason:u});e.setResult({executionId:d})}catch(e){if(e instanceof y)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(g.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 me(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(g.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(Qe(`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??qe);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(g.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(g.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(g.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(m.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Kr(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let n=new AbortController;this.workflowAbortControllers.set(e,n);try{let r;try{let i=await ke({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new pe(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,n.signal,void 0,i,{context:t.runContext.context,env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});De(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();r=await ye(t.workflow.root,a,o)}catch(r){if(n.signal.aborted||t.execution.status===`cancelled`){await h(this.buildFinalizerDeps(),e,qe);return}let i=r instanceof Error?r.message:String(r);await Me(this.buildFinalizerDeps(),t.execution,e,i);return}let i=this.buildFinalizerDeps();r.status===`cancelled`||n.signal.aborted||t.execution.status===`cancelled`?await h(i,e,qe):r.status===`failed`?await Me(i,t.execution,e,r.error):r.status===`paused`?(t.execution.status=`paused`,await this.bus.request(m.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await Fe(i,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:n,frameId:r,resumeData:i,reason:a}=e,{execution:o}=await this.bus.request(m.getExecution,{executionId:t});if(!Hr(o))return!1;let s=await qr(this.bus,{executionId:t,nodeId:n,frameId:r});if(s===null||!de(n,s.schema,i).valid)return!1;let{runContext:c}=await this.bus.request(m.getRunContext,{executionId:t});if(c===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Gr(this.bus,c);let{accepted:l}=await this.bus.request(m.resolveWaitingGateInstance,{gate:{...s,status:e.action===`reject`?`rejected`:`resumed`,resumeData:i,...a===void 0?{}:{reason:a},resolvedAt:Date.now()}});if(!l)return!1;try{await this.resumePausedExecution(o.id)}catch(e){throw await Wr(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,o,s,n),e}return this.gateTimeoutScheduler.clear(t,n,s.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(m.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let n=t.definitionSnapshot??(await this.bus.request(m.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:r}=await this.bus.request(m.getExecution,{executionId:e});if(r===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(r.status!==`paused`)return!1;await Gr(this.bus,t),await this.bus.request(m.setExecution,{execution:{...r,status:`running`}}),this.activeExecutions.set(e,{execution:{...r,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let i=Se(t,n,{resume:!0}),a=Te(this.buildStartDeps(),i).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,a),!0}};function Yr(e,t){try{return mt(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function Xr(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 Zr(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Qr=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(b.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(b.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(b.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(m.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`?Yr(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(Xr(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=Zr(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(Re(e,r.subject)&&!(r.filter&&!Le(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(b.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(ei(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=$r(e.tz,n),i=new Date(n.getTime()-r),a=$r(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=$r(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 $r(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 ei(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 ti=32,Y=31|ti,ni=[1,2,4,8,16],ri=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]|ti;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|ni[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},ii=[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&&ni[a-1]&r)return!0;if(r&ti){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>ii[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():ii[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 ai(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 oi(e){return Q(e)}function si(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var ci=30*1e3,$=[],li=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=ai(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 ri(`* * * * *`)},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 ri(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&&oi(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>ci&&(t=ci),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&si(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 ui(e,t){return`${e}:${t}`}function di(e){return e??`UTC`}var fi=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(b.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(b.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(b.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(m.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=ui(e.id,n);this.stopJob(i);try{let t=di(r.timezone),a=new li(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(b.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)})}},pi=class extends rt{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new Jr(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Qr(e),this.cronTriggerEvaluator=new fi(e)}get executor(){return this.workflowExecutor}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}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 mi=tt(`makaio.workflow-engine`);function hi(e){return{name:mi.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[et(gt.name)],critical:!0,namespaces:[Xe,r],storage:{registerHandlers:ot(gr)},create:t=>new pi(t.bus,e)}}const gi=hi();export{Jr as a,Yt as c,pi as i,Zt as l,hi as n,gr as o,gi as r,Xt as s,mi as t};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { IMakaioBus } from "@makaio/framework/bus";
|
|
2
2
|
import * as _$_makaio_contracts0 from "@makaio/framework/contracts";
|
|
3
|
-
import { IWorkflowRunner, IWorkflowTriggerTypeRegistry, LoopGateHandler, MakaioNodeExtension, StationHandler, StepRunnerBusAuth, StepRunnerPlatformDefaults, WorkflowDefinition } from "@makaio/framework/contracts";
|
|
3
|
+
import { IWorkflowRunner, IWorkflowTriggerTypeRegistry, LoopGateHandler, MakaioNodeExtension, StationHandler, StepRunnerBusAuth, StepRunnerPlatformDefaults, WorkflowDefinition, WorkflowExecution, WorkflowRunResult } from "@makaio/framework/contracts";
|
|
4
4
|
import { BaseService } from "@makaio/framework/service-base";
|
|
5
5
|
import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
|
|
6
6
|
|
|
@@ -79,6 +79,10 @@ declare class WorkflowExecutor extends BaseService {
|
|
|
79
79
|
* Keyed by execution ID; only populated when a {@link IWorkflowRunner} is used.
|
|
80
80
|
*/
|
|
81
81
|
private readonly workflowAbortControllers;
|
|
82
|
+
private readonly successFinalizers;
|
|
83
|
+
private readonly durableLifecycleTransitions;
|
|
84
|
+
private readonly lifecyclePublications;
|
|
85
|
+
private readonly publishingLifecycleExecutions;
|
|
82
86
|
private readonly workflowRunner?;
|
|
83
87
|
private triggerTypeRegistry?;
|
|
84
88
|
/**
|
|
@@ -101,6 +105,36 @@ declare class WorkflowExecutor extends BaseService {
|
|
|
101
105
|
* @returns The trigger type registry, or `undefined` if not yet set.
|
|
102
106
|
*/
|
|
103
107
|
getTriggerTypeRegistry(): IWorkflowTriggerTypeRegistry | undefined;
|
|
108
|
+
/**
|
|
109
|
+
* Register one named finalizer eligible for compiled workflow success transitions.
|
|
110
|
+
*
|
|
111
|
+
* A workflow selects this registration through its immutable
|
|
112
|
+
* `successFinalizerId` definition field. Disposing the returned registration
|
|
113
|
+
* leaves already-claimed work recoverable only when the same ID is registered
|
|
114
|
+
* again on a later executor instance.
|
|
115
|
+
* @param finalizerId - Stable finalizer identity used by the durable claim.
|
|
116
|
+
* @returns Idempotent cleanup after any recoverable claims have been drained.
|
|
117
|
+
* @throws When another active registration already owns `finalizerId`.
|
|
118
|
+
*/
|
|
119
|
+
registerSuccessFinalizer(finalizerId: string): Promise<() => void>;
|
|
120
|
+
/**
|
|
121
|
+
* Accept a terminal result from an authority-dispatched runner that was not
|
|
122
|
+
* launched through this executor's in-memory task registry.
|
|
123
|
+
*
|
|
124
|
+
* Durable execution and run-context rows remain the source of truth. The
|
|
125
|
+
* executor temporarily adopts a missing active entry and delegates to the
|
|
126
|
+
* same runner-result finalization path used by executor-owned tasks.
|
|
127
|
+
* @param executionId - Durable authority-owned execution identity.
|
|
128
|
+
* @param result - Correlated terminal runner result.
|
|
129
|
+
* @returns The durable status after acceptance, including pending success finalization.
|
|
130
|
+
*/
|
|
131
|
+
acceptAuthorityRunnerResult(executionId: string, result: WorkflowRunResult): Promise<{
|
|
132
|
+
accepted: boolean;
|
|
133
|
+
status: WorkflowExecution['status'];
|
|
134
|
+
}>;
|
|
135
|
+
private resolveAuthorityRunnerReplay;
|
|
136
|
+
private loadAuthorityRunnerContext;
|
|
137
|
+
private registerAuthorityResultFinalizer;
|
|
104
138
|
/**
|
|
105
139
|
* Register all bus handlers via BaseService lifecycle.
|
|
106
140
|
* Called once by `init()` — idempotency is handled by BaseService.
|
|
@@ -324,6 +358,23 @@ declare class WorkflowEngineService extends BaseService {
|
|
|
324
358
|
* @returns Workflow executor instance.
|
|
325
359
|
*/
|
|
326
360
|
get executor(): WorkflowExecutor;
|
|
361
|
+
/**
|
|
362
|
+
* Register a named workflow success finalizer with the owned executor.
|
|
363
|
+
*
|
|
364
|
+
* Compiled workflow definitions opt into this registration through their
|
|
365
|
+
* immutable `successFinalizerId`; registration alone never changes ordinary
|
|
366
|
+
* workflow completion behavior.
|
|
367
|
+
* @param finalizerId - Stable lifecycle-finalizer identity.
|
|
368
|
+
* @returns Idempotent cleanup that unregisters this exact registration.
|
|
369
|
+
*/
|
|
370
|
+
registerSuccessFinalizer(finalizerId: string): Promise<() => void>;
|
|
371
|
+
/**
|
|
372
|
+
* Accept a terminal result for a durable authority-owned runner execution.
|
|
373
|
+
* @param executionId - Durable authority-owned execution identity.
|
|
374
|
+
* @param result - Correlated terminal result returned by the runner.
|
|
375
|
+
* @returns The current durable status after acceptance.
|
|
376
|
+
*/
|
|
377
|
+
acceptAuthorityRunnerResult(executionId: string, result: Parameters<WorkflowExecutor['acceptAuthorityRunnerResult']>[1]): ReturnType<WorkflowExecutor['acceptAuthorityRunnerResult']>;
|
|
327
378
|
/**
|
|
328
379
|
* Cron evaluator owned by this package service.
|
|
329
380
|
* @returns Cron trigger evaluator instance.
|
package/dist/package.json
CHANGED
package/dist/rules/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../esm-
|
|
1
|
+
import{t as e}from"../esm-C_WW4-pP.mjs";import{ConditionSchema as t,ExpressionConditionSchema as n,FieldConditionSchema as r,FieldOperatorSchema as i,JsonObjectSchema as a,JsonValueSchema as o,RuleSchema as s,RuleSetOptionsSchema as c,ScalarValueSchema as l}from"./schemas.mjs";import{compile as u}from"@makaio/framework/expression";const d=new Map,f=new Map;function p(e,t){if(`$and`in e){for(let n of e.$and)if(!p(n,t))return!1;return!0}if(`$or`in e){for(let n of e.$or)if(p(n,t))return!0;return!1}return`$not`in e?!p(e.$not,t):`$expr`in e?!!_(e.$expr).evalSync(t):h(g(t,e.field),e.operator)}function m(e,t,n={}){let{includeDisabled:r=!1}=n,i=[];for(let n of e)!r&&!n.enabled||p(n.condition,t)&&i.push(n);return i}function h(e,t){if(typeof t!=`object`||!t)return e===t;if(`$eq`in t)return e===t.$eq;if(`$ne`in t)return e!==t.$ne;if(`$in`in t)return t.$in.includes(e);if(`$nin`in t)return!t.$nin.includes(e);if(`$exists`in t){let n=e!==void 0;return t.$exists?n:!n}return`$startsWith`in t?typeof e==`string`&&e.startsWith(t.$startsWith):`$endsWith`in t?typeof e==`string`&&e.endsWith(t.$endsWith):`$glob`in t?typeof e==`string`&&v(t.$glob).match(e):!1}function g(e,t){if(e==null)return;let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}function _(e){return y(d,e,()=>u(e))}function v(t){return y(f,t,()=>new e(t))}function y(e,t,n){let r=e.get(t);if(r!==void 0)return e.delete(t),e.set(t,r),r;let i=n();if(e.set(t,i),e.size>256){let t=e.keys().next().value;t!==void 0&&e.delete(t)}return i}export{t as ConditionSchema,n as ExpressionConditionSchema,r as FieldConditionSchema,i as FieldOperatorSchema,a as JsonObjectSchema,o as JsonValueSchema,s as RuleSchema,c as RuleSetOptionsSchema,l as ScalarValueSchema,p as evaluate,m as evaluateRules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,c as t,n,o as r,r as i}from"../load-extensions-
|
|
1
|
+
import{a as e,c as t,n,o as r,r as i}from"../load-extensions-nqL5WAKj.mjs";export{n as entrypointStem,i as isCliContributionLike,e as isMakaioExtensionLike,r as isWithinDirectory,t as resolveConventionEntrypoint};
|
|
@@ -2,7 +2,7 @@ import { RuntimeSubjects } from "./bus/runtime/namespace.mjs";
|
|
|
2
2
|
import { NodeClientBinaryStrategyDependencyOptions, createNodeClientBinaryStrategyDependencies } from "./client-binary-strategy-dependencies.mjs";
|
|
3
3
|
import { a as FilesystemDescriptorDiscovery, n as ExplicitDescriptorDiscovery, o as FilesystemDescriptorDiscoveryOptions, r as ExtensionDiscovery, s as MergedDescriptorDiscovery, t as DiscoveredExtension } from "../extension-discovery-APMf1Tes.mjs";
|
|
4
4
|
import { a as isMakaioExtensionLike, c as resolveConventionEntrypoint, i as isCliContributionLike, n as LoadExtensionsOptions, o as isWithinDirectory, r as entrypointStem, s as loadExtensions, t as DescriptorSourcePackageGroup } from "../load-extensions-_EnedkUp.mjs";
|
|
5
|
-
import { A as
|
|
5
|
+
import { $ as HonoRouteGraph, A as TransportReadyInfo, B as HostCapabilityDeclaration, C as ThinWorkflowPiscinaRunnerOptions, D as CoreBootOptions, E as BootMakaioRuntimeOptions, F as resolveWorkflowWorkerEntry, G as FrameworkModuleResolver, H as selectFrameworkCorePackages, I as DatabaseBootOptions, J as resolveFrameworkSpecifier, K as NodeFrameworkModuleResolver, L as InitializeNodeDatabaseOptions, M as WorkflowRunnerBootOptions, N as WorkflowWorkerEntryMode, O as MakaioRuntime, P as WorkflowWorkerEntryResolverOptions, Q as HttpRouteContribution, R as InitializeNodeDatabaseResult, T as BootCoordinatorSetupContext, U as ShutdownStep, V as normalizeNodeHostCapabilities, W as BridgeBrowserOptions, X as createHttpRouteGraphBuilder, Y as HttpRouteGraphBuilder, Z as HttpContributionPhase, a as IsolatedWorkflowRuntime, at as PreparedAdapterRuntime, b as ThinWorkflowPiscinaRunner, c as WorkflowRuntimeContributionLoader, d as InProcessWorkflowRunnerOptions, et as HonoRouteGraphOptions, i as CreateIsolatedWorkflowRuntimeOptions, it as PrepareAdapterRuntimeInput, j as UpstreamTelemetryBootOptions, k as ServerTransportProvider, l as createIsolatedWorkflowRuntime, nt as ActivateAdapterRuntimeIdentityInput, o as IsolatedWorkflowRuntimeContext, ot as activateAdapterRuntimeIdentity, q as NoopFrameworkModuleResolver, rt as ActivatedAdapterRuntimeIdentity, s as WorkflowRuntimeAuthorityConnector, st as prepareAdapterRuntime, tt as createHonoRouteGraph, u as InProcessWorkflowRunner, w as WorkflowRunResult, x as IWorkflowRunner, z as initializeNodeDatabase } from "../index-C6LZOiDv.mjs";
|
|
6
6
|
import { ConfiguredRuntimeOptions, LoadMakaioConfigOptions, LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MakaioConfig, ParseMakaioConfigOptions, ParsedMakaioConfig, WorkflowRunnerConfig, buildConfiguredRuntimeOptions, createMakaioConfigDiscovery, defineMakaioConfig, loadMakaioConfig, parseMakaioConfig, resolveMakaioConfigPath, resolveMakaioHome, shouldIncludeExtension } from "./makaio-config.mjs";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { IConfigStorage } from "@makaio/framework/core";
|
|
@@ -11,9 +11,9 @@ import { Config, EntityUIConfig, ProtocolId } from "@makaio/framework/contracts"
|
|
|
11
11
|
import { DispatchingAuth } from "@makaio/framework/node/transports";
|
|
12
12
|
import { MakaioDatabase, StorageDialect as StorageDialect$1 } from "@makaio/framework/storage/drizzle";
|
|
13
13
|
import { CredentialRef } from "@makaio/framework/contracts/config";
|
|
14
|
-
import {
|
|
14
|
+
import { KernelMakaioExtension, TransportProvider } from "@makaio/framework/kernel";
|
|
15
15
|
import { IModelRegistryCache, ModelRegistry } from "@makaio/framework/services/model-registry";
|
|
16
|
-
import { AdapterInstance,
|
|
16
|
+
import { AdapterInstance, LoadedAdapter } from "@makaio/framework/adapter-subsystem";
|
|
17
17
|
import { MachineKeyStatus, MachineKeyValidation, PersistedMachineIdentity, loadOrCreateMachineIdentity, machineKeysExist, validateMachineKeys } from "@makaio/framework/node/machine-identity";
|
|
18
18
|
import { TransportAuth as TransportAuth$1 } from "@makaio/framework/node/bus-server";
|
|
19
19
|
import { ConfigProvider } from "@makaio/framework/providers";
|
|
@@ -53,91 +53,6 @@ declare function registerRuntimeHandlers(bus: IMakaioBus, getLoadedAdapters: ()
|
|
|
53
53
|
uiConfig?: EntityUIConfig;
|
|
54
54
|
} | undefined): () => void;
|
|
55
55
|
//#endregion
|
|
56
|
-
//#region runtimes/node/src/compose-adapter-runtime.d.ts
|
|
57
|
-
/**
|
|
58
|
-
* Composition seam for booting a local adapter runtime.
|
|
59
|
-
*
|
|
60
|
-
* Encapsulates the proven host sequence for making `adapter.*` execution
|
|
61
|
-
* subjects locally owned, so every adapter-capable runtime composes it the
|
|
62
|
-
* same way instead of reinventing it. There are two phases because the kernel
|
|
63
|
-
* lifecycle requires it:
|
|
64
|
-
*
|
|
65
|
-
* 1. {@link prepareAdapterRuntime} — call **before** `coordinator.startAll()`:
|
|
66
|
-
* builds the adapter-subsystem package (add it to the coordinator load set)
|
|
67
|
-
* and registers the adapter contribution processor so adapter contributions
|
|
68
|
-
* are awaited during activation.
|
|
69
|
-
* 2. {@link activateAdapterRuntimeIdentity} — call **after** `coordinator.startAll()`:
|
|
70
|
-
* registers the adapter-runtime identity handlers and the adapter-name
|
|
71
|
-
* resolver, which resolve `adapterName` to the deterministic adapter id that
|
|
72
|
-
* live `AIAdapter` instances filter `AdapterSubjects.startAgent` on.
|
|
73
|
-
*
|
|
74
|
-
* The locality invariant this seam upholds: the `currentMachineId` passed to
|
|
75
|
-
* {@link activateAdapterRuntimeIdentity} MUST be the same machine id the
|
|
76
|
-
* coordinator injects as `extensionContextBase.machineId` (and therefore the
|
|
77
|
-
* id `AdapterSubsystemService` and `SubagentService` derive adapter ids from).
|
|
78
|
-
* If they diverge, `AdapterRuntimeSubjects.resolveId` yields an id no local
|
|
79
|
-
* adapter listens on and `startAgent` silently falls through to the transport.
|
|
80
|
-
*/
|
|
81
|
-
/** Input for {@link prepareAdapterRuntime} (the pre-`startAll` phase). */
|
|
82
|
-
interface PrepareAdapterRuntimeInput {
|
|
83
|
-
/** Coordinator that loads the adapter-subsystem package and owns activation. */
|
|
84
|
-
readonly coordinator: ExtensionCoordinator;
|
|
85
|
-
/** Persistence seam for adapter/provider configuration. */
|
|
86
|
-
readonly configRepository: IAdapterConfigRepository;
|
|
87
|
-
/** Platform defaults (cwd/env) supplied to adapter instances. */
|
|
88
|
-
readonly platformDefaults: PlatformDefaults;
|
|
89
|
-
/** Trusted non-serializable auth preparer forwarded to every loaded adapter. */
|
|
90
|
-
readonly prepareAuthRuntime?: unknown;
|
|
91
|
-
}
|
|
92
|
-
/** Result of {@link prepareAdapterRuntime}. */
|
|
93
|
-
interface PreparedAdapterRuntime {
|
|
94
|
-
/**
|
|
95
|
-
* The adapter-subsystem package. The caller MUST add this to the array passed
|
|
96
|
-
* to `coordinator.load(...)`; its `create` reads `ctx.machineId`, so adapter
|
|
97
|
-
* ids derive from the coordinator's machine id.
|
|
98
|
-
*/
|
|
99
|
-
readonly adapterSubsystemPackage: ReturnType<typeof createAdapterSubsystemPackage>;
|
|
100
|
-
}
|
|
101
|
-
/** Input for {@link activateAdapterRuntimeIdentity} (the post-`startAll` phase). */
|
|
102
|
-
interface ActivateAdapterRuntimeIdentityInput {
|
|
103
|
-
/** Bus the identity handlers and name resolver are registered on. */
|
|
104
|
-
readonly bus: IMakaioBus;
|
|
105
|
-
/**
|
|
106
|
-
* The runtime's machine id. MUST equal the coordinator's
|
|
107
|
-
* `extensionContextBase.machineId` (see the locality invariant above).
|
|
108
|
-
*/
|
|
109
|
-
readonly currentMachineId: string;
|
|
110
|
-
/**
|
|
111
|
-
* Optional override for enumerating known adapter names. Defaults to querying
|
|
112
|
-
* `AdapterSubsystemSubjects.listAdapterConfigs` on the bus, matching the host.
|
|
113
|
-
*/
|
|
114
|
-
readonly listKnownAdapterNames?: () => Promise<Iterable<string>>;
|
|
115
|
-
}
|
|
116
|
-
/** Result of {@link activateAdapterRuntimeIdentity}. */
|
|
117
|
-
interface ActivatedAdapterRuntimeIdentity {
|
|
118
|
-
/** Tear down the identity handlers and the adapter-name resolver. */
|
|
119
|
-
readonly cleanup: () => void;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Build the adapter-subsystem package and register its contribution processor.
|
|
123
|
-
*
|
|
124
|
-
* Call before `coordinator.startAll()`. Registering the contribution processor
|
|
125
|
-
* only stores it for use during activation, so it is order-independent relative
|
|
126
|
-
* to `coordinator.load(...)` as long as it happens before `startAll()`.
|
|
127
|
-
* @param input - Coordinator, config repository, and platform defaults.
|
|
128
|
-
* @returns The adapter-subsystem package to add to the coordinator load set.
|
|
129
|
-
*/
|
|
130
|
-
declare function prepareAdapterRuntime(input: PrepareAdapterRuntimeInput): PreparedAdapterRuntime;
|
|
131
|
-
/**
|
|
132
|
-
* Register the adapter-runtime identity handlers and adapter-name resolver.
|
|
133
|
-
*
|
|
134
|
-
* Call after `coordinator.startAll()` so that `CapabilityService` and the
|
|
135
|
-
* adapter subsystem have registered their handlers.
|
|
136
|
-
* @param input - Bus, the runtime machine id, and an optional name enumerator.
|
|
137
|
-
* @returns A cleanup that tears both registrations down.
|
|
138
|
-
*/
|
|
139
|
-
declare function activateAdapterRuntimeIdentity(input: ActivateAdapterRuntimeIdentityInput): ActivatedAdapterRuntimeIdentity;
|
|
140
|
-
//#endregion
|
|
141
56
|
//#region runtimes/node/src/db-migrations.d.ts
|
|
142
57
|
/** Options for applying framework central migrations. */
|
|
143
58
|
interface RunMigrationsOptions {
|
|
@@ -756,4 +671,4 @@ declare function findWorkspaceRoot(startDir: string): string;
|
|
|
756
671
|
*/
|
|
757
672
|
declare function findWorkspaceRootInfo(startDir: string): WorkspaceRootInfo;
|
|
758
673
|
//#endregion
|
|
759
|
-
export { type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, type ConfiguredRuntimeOptions, type CoreBootOptions, type CredentialProvider, type DatabaseBootOptions, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, MergedDescriptorDiscovery, type NodeClientBinaryStrategyDependencyOptions, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createMakaioConfigDiscovery, createNodeClientBinaryStrategyDependencies, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, getRuntimeDatabase, initializeNodeDatabase, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, registerRuntimeHandlers, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runMigrations, runRuntimeHandlerCleanups, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };
|
|
674
|
+
export { type ActivateAdapterRuntimeIdentityInput, type ActivatedAdapterRuntimeIdentity, type AttachedUpstreamTelemetry, type BootCoordinatorSetupContext, type BootMakaioRuntimeOptions, type BridgeBrowserOptions, type BundledMigrationsProbes, type BusServerTransportOptions, BusServerTransportProvider, type ConfiguredRuntimeOptions, type CoreBootOptions, type CreateIsolatedWorkflowRuntimeOptions, type CredentialProvider, type DatabaseBootOptions, type DescriptorSourcePackageGroup, type DiscoveredExtension, ExplicitDescriptorDiscovery, type ExtensionDiscovery, FileConfigStorage, FileRegistryCache, FilesystemDescriptorDiscovery, type FilesystemDescriptorDiscoveryOptions, type FrameworkModuleResolver, type HonoRouteGraph, type HonoRouteGraphOptions, type HttpContributionPhase, type HttpRouteContribution, type HttpRouteGraphBuilder, type IWorkflowRunner, InProcessWorkflowRunner, type InProcessWorkflowRunnerOptions, type InitializeNodeDatabaseOptions, type InitializeNodeDatabaseResult, type IsolatedWorkflowRuntime, type IsolatedWorkflowRuntimeContext, type LoadExtensionsOptions, type LoadMakaioConfigOptions, type LoadedMakaioConfig, MAKAIO_CONFIG_FILE_ENV, MAKAIO_HOME_ENV, MAKAIO_UPSTREAM_SECRET_ENV, MAKAIO_UPSTREAM_URL_ENV, type MachineKeyStatus, type MachineKeyValidation, type MakaioConfig, type MakaioRuntime, MergedDescriptorDiscovery, type NodeClientBinaryStrategyDependencyOptions, NodeCredentialProvider, NodeFrameworkModuleResolver, type NodeRuntimeOptions, NoopFrameworkModuleResolver, type ParseMakaioConfigOptions, type ParsedMakaioConfig, type PersistedMachineIdentity, type PrepareAdapterRuntimeInput, type PreparedAdapterRuntime, type ResolveUpstreamTelemetryBootOptionsFromEnvOptions, RuntimeSubjects, type ServerTransportProvider, StoredCredentialProvider, ThinWorkflowPiscinaRunner, type ThinWorkflowPiscinaRunnerOptions, type TransportReadyInfo, type UpstreamTelemetryBootOptions, type UpstreamTelemetryEnv, type UpstreamTelemetryTransportConfig, type WorkflowRunResult, type WorkflowRunnerBootOptions, type WorkflowRunnerConfig, type WorkflowRuntimeAuthorityConnector, type WorkflowRuntimeContributionLoader, type WorkflowWorkerEntryMode, type WorkflowWorkerEntryResolverOptions, type WorkspaceRootInfo, WorkspaceRootNotFoundError, activateAdapterRuntimeIdentity, attachUpstreamTelemetry, bootMakaioRuntime, bootMakaioRuntimeCore, bridgeExtensionBrowserEntries, buildConfiguredRuntimeOptions, buildExtensionBrowserRollupInputName, buildExtensionBrowserRuntimeEntrypoint, buildNodeRuntimeOptions, createHonoRouteGraph, createHttpRouteGraphBuilder, createIsolatedWorkflowRuntime, createMakaioConfigDiscovery, createNodeClientBinaryStrategyDependencies, createUpstreamTelemetryTransport, defineMakaioConfig, entrypointStem, findWorkspaceRoot, findWorkspaceRootInfo, getRuntimeDatabase, initializeNodeDatabase, isCliContributionLike, isMakaioExtensionLike, isMissingOptionalRuntimePackage, isWithinDirectory, loadExtensions, loadMakaioConfig, loadOrCreateMachineIdentity, machineKeysExist, normalizeNodeHostCapabilities, parseMakaioConfig, prepareAdapterRuntime, readFrameworkVersion, registerAdapterNameResolver, registerRuntimeHandlers, resolveBundledMigrationsDir, resolveConventionEntrypoint, resolveFrameworkSpecifier, resolveListeningPort, resolveMakaioConfigPath, resolveMakaioHome, resolveStaticModelRegistryPath, resolveUpstreamTelemetryBootOptionsFromEnv, resolveWorkflowWorkerEntry, runMigrations, runRuntimeHandlerCleanups, selectFrameworkCorePackages, shouldIncludeExtension, tryImport, validateMachineKeys, waitForServerListening };
|