@makaio/framework 1.0.0-dev-1788832451167 → 1.0.0-dev-1788897280508
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/{account-identity-B3vLwm9O.mjs → account-identity-DCBpVurJ.mjs} +1 -1
- package/dist/{adapter-Dz1fX5Wa.mjs → adapter-D6IpEDIo.mjs} +1 -1
- package/dist/adapters/config/index.d.mts +1 -1
- package/dist/adapters/config/index.mjs +1 -1
- package/dist/adapters/index.d.mts +2 -2
- package/dist/adapters/index.mjs +1 -1
- package/dist/adapters/node.d.mts +1 -1
- package/dist/adapters/node.mjs +1 -1
- package/dist/artifact-OnwP6uaD.mjs +1 -0
- package/dist/attempt-record-codec-CqKq0NIB.mjs +1 -0
- package/dist/{auth-C6tVtaOX.mjs → auth-CeH3w2fi.mjs} +1 -1
- package/dist/authority-state-bootstrap-rnsTk0u7.mjs +1 -0
- package/dist/{automation-trigger-ByjNlClm.mjs → automation-trigger-D_xKqEoV.mjs} +1 -1
- package/dist/bus/index.mjs +1 -1
- package/dist/{caller-owned-adapter-stub-C1M7FKrv.mjs → caller-owned-adapter-stub-egWCuKcE.mjs} +1 -1
- package/dist/{canonical-model-DXOvCaVg.mjs → canonical-model-DwuFQ02A.mjs} +1 -1
- package/dist/{capabilities-DEvmD9VJ.mjs → capabilities-DGqMG9M3.mjs} +1 -1
- package/dist/{client-BkznbdsO.mjs → client-CTqzLpVx.mjs} +1 -1
- package/dist/clients/index.d.mts +1 -1
- package/dist/clients/index.mjs +1 -1
- package/dist/clients/managed-install.d.mts +1 -1
- package/dist/clients/managed-install.mjs +1 -1
- package/dist/code-execution/worker-entry.d.mts +1 -1
- package/dist/code-execution/worker-entry.mjs +1 -1
- package/dist/{code-execution-Ckmn8OZu.mjs → code-execution-BMmUATcc.mjs} +1 -1
- package/dist/{code-execution-CweDSWco.mjs → code-execution-C2PgBdmE.mjs} +1 -1
- package/dist/{code-execution-DqkQjKa1.mjs → code-execution-Mo1jztUH.mjs} +1 -1
- package/dist/{compression-CtgeVLpP.mjs → compression-3DauETKU.mjs} +1 -1
- package/dist/{config-namespace-CjWvw8ij.mjs → config-namespace-MjFuIPyL.mjs} +1 -1
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +3 -3
- package/dist/contracts/artifact/index.mjs +1 -1
- package/dist/contracts/auth/index.d.mts +2 -2
- package/dist/contracts/auth/index.mjs +1 -1
- package/dist/contracts/automation-trigger/index.d.mts +3 -3
- package/dist/contracts/automation-trigger/index.mjs +1 -1
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/canonical-model/index.mjs +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/capabilities/index.mjs +1 -1
- package/dist/contracts/client/index.d.mts +2 -2
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/code-execution/index.d.mts +1 -1
- package/dist/contracts/code-execution/index.mjs +1 -1
- package/dist/contracts/common/index.d.mts +1 -1
- package/dist/contracts/config/index.d.mts +1 -1
- package/dist/contracts/config/index.mjs +1 -1
- package/dist/contracts/extension/index.d.mts +5 -5
- package/dist/contracts/extension/index.mjs +1 -1
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/facet/index.mjs +1 -1
- package/dist/contracts/harness/index.d.mts +1 -1
- package/dist/contracts/harness/index.mjs +1 -1
- package/dist/contracts/host/index.d.mts +1 -1
- package/dist/contracts/host/index.mjs +1 -1
- package/dist/contracts/index.d.mts +102 -102
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +2 -3
- package/dist/contracts/materialization/index.mjs +1 -1
- package/dist/contracts/model-registry/index.d.mts +1 -1
- package/dist/contracts/model-registry/index.mjs +1 -1
- package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
- package/dist/contracts/native-session-supervisor/index.mjs +1 -1
- package/dist/contracts/platform/index.d.mts +1 -1
- package/dist/contracts/platform/index.mjs +1 -1
- package/dist/contracts/provider/index.d.mts +2 -2
- package/dist/contracts/provider/index.mjs +1 -1
- package/dist/contracts/reaction/index.d.mts +1 -1
- package/dist/contracts/reaction/index.mjs +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/shared/index.d.mts +2 -2
- package/dist/contracts/shared/index.mjs +1 -1
- package/dist/contracts/skill/index.d.mts +1 -1
- package/dist/contracts/skill/index.mjs +1 -1
- package/dist/contracts/telemetry/index.d.mts +1 -1
- package/dist/contracts/telemetry/index.mjs +1 -1
- package/dist/contracts/timeout/index.d.mts +1 -1
- package/dist/contracts/timeout/index.mjs +1 -1
- package/dist/contracts/toast/index.mjs +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/variant/index.mjs +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/{contribution-Crm-mctl.d.mts → contribution-BoTMoHVB.d.mts} +2 -2
- package/dist/{definition-u_5rYQtc.d.mts → definition-BgY763Q4.d.mts} +1 -1
- package/dist/{definition-BH4QLGLI.mjs → definition-YGj42UeO.mjs} +1 -1
- package/dist/{detached-extension-handle-DAXKQT9c.mjs → detached-extension-handle-B9c_6Pcb.mjs} +1 -1
- package/dist/execution-attempt-owner-recovery-BNERIDH0.mjs +1 -0
- package/dist/{execution-attempt-repository-CgB7uiYD.d.mts → execution-attempt-repository-CtFZfBfp.d.mts} +111 -3
- package/dist/{execution-target-BcoF_oDB.mjs → execution-target-CqaBmnvX.mjs} +1 -1
- package/dist/{extension-Bfkr2DBs.mjs → extension-B51JzHJu.mjs} +1 -1
- package/dist/extension-C4lFc8-j.mjs +1 -0
- package/dist/{filesystem-service-CiUw0YN5.mjs → filesystem-service-DGqU-6x-.mjs} +1 -1
- package/dist/framework-packages-CZJDukan.mjs +1 -0
- package/dist/git/index.mjs +1 -1
- package/dist/{globby-QBDqstzq.mjs → globby-BT0rrriG.mjs} +1 -1
- package/dist/{handlers-BsHAFtye.mjs → handlers-CBbFzDHc.mjs} +1 -1
- package/dist/{harness-YQ2ewID9.mjs → harness-GNtHsoh4.mjs} +1 -1
- package/dist/{hook-responses-DcapjzLb.d.mts → hook-responses-BSCAdJ3i.d.mts} +1 -1
- package/dist/{index-QJW9g1mG.d.mts → index-BVRQOZbm.d.mts} +1 -1
- package/dist/{index-LryUXslm.d.mts → index-BZlmWCcW.d.mts} +3 -3
- package/dist/{index-rygpcDBV.d.mts → index-BZtasAZP.d.mts} +1 -1
- package/dist/{index-Bsr4rZl0.d.mts → index-BdbYIlDL.d.mts} +18 -18
- package/dist/{index-BxOFB25y.d.mts → index-BkY6zO7p.d.mts} +138 -115
- package/dist/{index-DZXpKlyB.d.mts → index-CDLHgV7v.d.mts} +14 -14
- package/dist/{index-CfJKwWJa.d.mts → index-CQtttPGm.d.mts} +1 -1
- package/dist/{index-BADuMxcP.d.mts → index-CYmQt2lF.d.mts} +100 -100
- package/dist/{index-J-kv32zv.d.mts → index-CYwbfa0_.d.mts} +2 -2
- package/dist/{index-DZnb56vt2.d.mts → index-C_OLvAr_.d.mts} +1 -1
- package/dist/{index-BvgLFm-U.d.mts → index-Cau0jTTM.d.mts} +1 -1
- package/dist/{index-BwccWakG.d.mts → index-D0DfEO45.d.mts} +1 -1
- package/dist/{index-COOM1j_L2.d.mts → index-DIYgFhTZ2.d.mts} +4 -4
- package/dist/{index-LOh6AEqx.d.mts → index-DJ0Muy2s.d.mts} +4 -4
- package/dist/{index-C1PfDEIV.d.mts → index-F6hV4tWI.d.mts} +35 -35
- package/dist/{index-CiKzWCW02.d.mts → index-LwOw7ZLk2.d.mts} +19 -19
- package/dist/{index-BakMNLkB.d.mts → index-PTp68NH1.d.mts} +92 -92
- package/dist/{index-vXmPEZ5O.d.mts → index-R2BZejEz.d.mts} +591 -726
- package/dist/{index-DIhkK4Y0.d.mts → index-RpG4EP3u.d.mts} +1 -1
- package/dist/{index-Bo3LRb2u.d.mts → index-dL0Oet1j.d.mts} +1 -1
- package/dist/{index-Cbv_3Xi12.d.mts → index-mylsCg6V2.d.mts} +1 -1
- package/dist/{index-BDzqNCXs.d.mts → index-nPpqnP7P.d.mts} +1 -1
- package/dist/kernel/cli/index.d.mts +2 -2
- package/dist/kernel/cli/index.mjs +1 -1
- package/dist/kernel/cli/register.d.mts +1 -1
- package/dist/kernel/cli/register.mjs +1 -1
- package/dist/kernel/cli/schemas.mjs +1 -1
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/extension/index.mjs +1 -1
- package/dist/kernel/index.d.mts +5 -5
- package/dist/kernel/index.mjs +1 -1
- package/dist/kernel/namespace/index.d.mts +1 -1
- package/dist/kernel/namespace/index.mjs +1 -1
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/kernel/observability/index.mjs +1 -1
- package/dist/kernel/providers/index.d.mts +1 -1
- package/dist/kernel/providers/index.mjs +1 -1
- package/dist/kernel/window/index.d.mts +1 -1
- package/dist/kernel/window/index.mjs +1 -1
- package/dist/kind-registration-BNhVCSaT.mjs +1 -0
- package/dist/{lib-271rPR7A.mjs → lib-B8Yv4IY-.mjs} +1 -1
- package/dist/{lib-RFpLjUda.mjs → lib-hwdGyO-m.mjs} +1 -1
- package/dist/{load-extensions-D9inWcDy.mjs → load-extensions-CNT2Nd9h.mjs} +1 -1
- package/dist/{load-extensions-CY8ELnCp.d.mts → load-extensions-D0yT_Kta.d.mts} +1 -1
- package/dist/materialization-Dx1z_MDj.mjs +1 -0
- package/dist/mcp-http-server/index.mjs +1 -1
- package/dist/model-B6t_-_sp.mjs +1 -0
- package/dist/{namespace-BymM0nl_.d.mts → namespace-C7wggVcn.d.mts} +9 -9
- package/dist/namespace-D4zmxaC4.mjs +1 -0
- package/dist/{namespace-DdqVQSyc.d.mts → namespace-Dh5fTXYt.d.mts} +2 -2
- package/dist/{namespace-DlrX8feY.d.mts → namespace-WeSQXdAL.d.mts} +45 -45
- package/dist/{namespace-BL7lHlmg.mjs → namespace-ZAIFBrIy.mjs} +1 -1
- package/dist/{native-session-supervisor-LKio8XZn.mjs → native-session-supervisor-BlGzmZrH.mjs} +1 -1
- package/dist/node/bus-server/index.d.mts +1 -1
- package/dist/node/bus-server/index.mjs +1 -1
- package/dist/node/bus-server/server-lifecycle.d.mts +1 -1
- package/dist/node/bus-server/server-lifecycle.mjs +1 -1
- package/dist/{orchestrator-shared-BGlN-m-V.mjs → orchestrator-shared-BKMtjTE9.mjs} +1 -1
- package/dist/{ownership-memory-handler-BpGdR_uG.mjs → ownership-memory-handler-BCu1EjFO.mjs} +1 -1
- package/dist/{package-DkpF17X_.d.mts → package-C9XYuN9J.d.mts} +20 -6
- package/dist/{package-CzKoZ1k0.mjs → package-D7c2HC-S.mjs} +2 -2
- package/dist/{package-JtjbO-Oi.mjs → package-buHQFmTH.mjs} +1 -1
- package/dist/package.json +1 -1
- package/dist/packages-BhhBcPgz.mjs +1 -0
- package/dist/{packages-Cx-BwSZr.d.mts → packages-DAqep89i.d.mts} +12 -39
- package/dist/{profile-N5qGUpF0.mjs → profile-DBDvy9uc.mjs} +1 -1
- package/dist/{provider-context-zTDSH2x9.mjs → provider-context-CSb0qX1c.mjs} +1 -1
- package/dist/{provider-context-CG42JlP9.mjs → provider-context-CTOrOW54.mjs} +1 -1
- package/dist/{reaction-D3TNwPK8.mjs → reaction-OQibmmDW.mjs} +1 -1
- package/dist/{resolved-sq8RXNDf.mjs → resolved-ONt3rOMh.mjs} +1 -1
- package/dist/rules/index.d.mts +1 -1
- package/dist/rules/index.mjs +1 -1
- package/dist/rules/schemas.d.mts +1 -1
- package/dist/runtime-bun/index.mjs +1 -1
- package/dist/runtime-node/code-execution/index.d.mts +2 -2
- package/dist/runtime-node/code-execution/index.mjs +1 -1
- package/dist/runtime-node/extension-discovery.d.mts +1 -1
- package/dist/runtime-node/extension-validation.d.mts +1 -1
- package/dist/runtime-node/extension-validation.mjs +1 -1
- package/dist/runtime-node/index.d.mts +6 -6
- package/dist/runtime-node/index.mjs +20 -20
- package/dist/runtime-node/makaio-config.d.mts +1 -1
- 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-Dq-7si8u.mjs → schema-B8jinlbH.mjs} +1 -1
- package/dist/{schema-C9PauHXt.d.mts → schema-wArHaxA9.d.mts} +2 -2
- package/dist/{schemas-QWDnauKX.mjs → schemas-BUK9I-Oz.mjs} +1 -1
- package/dist/{schemas-BDZFd3Wb.d.mts → schemas-BjNlwTDl.d.mts} +2 -2
- package/dist/{context-resolution-BrtoXnez.d.mts → schemas-C5FreSE0.d.mts} +133 -539
- package/dist/{schemas-_2Syo_01.mjs → schemas-CSDiTBsU.mjs} +1 -1
- package/dist/{schemas-BfO5jkrL.mjs → schemas-CbhvgFQs.mjs} +1 -1
- package/dist/schemas-hzbKeyyt.mjs +1 -0
- package/dist/{selection-DL3ric7K.mjs → selection-7SkHsmWs.mjs} +1 -1
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/index.mjs +1 -1
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- package/dist/services/adapter-subsystem/index.d.mts +3 -3
- package/dist/services/adapter-subsystem/index.mjs +1 -1
- package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
- package/dist/services/adapter-subsystem/namespace.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/automation-trigger/index.mjs +1 -1
- package/dist/services/capability/index.d.mts +2 -2
- package/dist/services/capability/index.mjs +1 -1
- package/dist/services/code-execution/index.d.mts +1 -1
- package/dist/services/code-execution/index.mjs +1 -1
- package/dist/services/codebase/index.d.mts +2 -2
- package/dist/services/codebase/namespace.d.mts +1 -1
- package/dist/services/codebase/schemas.d.mts +1 -1
- package/dist/services/compression/index.d.mts +2 -2
- package/dist/services/compression/namespace.d.mts +1 -1
- package/dist/services/compression/schemas.d.mts +1 -1
- package/dist/services/context-rules/index.d.mts +1 -1
- package/dist/services/context-rules/index.mjs +1 -1
- package/dist/services/execution-target/index.d.mts +3 -3
- package/dist/services/execution-target/index.mjs +1 -1
- package/dist/services/execution-target/namespace.d.mts +1 -1
- package/dist/services/execution-target/namespace.mjs +1 -1
- package/dist/services/execution-target/schemas.d.mts +1 -1
- package/dist/services/execution-target/schemas.mjs +1 -1
- package/dist/services/filesystem/index.d.mts +1 -1
- package/dist/services/filesystem/index.mjs +1 -1
- package/dist/services/git/namespace.mjs +1 -1
- package/dist/services/git/schemas.mjs +1 -1
- package/dist/services/harness/index.mjs +1 -1
- package/dist/services/index.d.mts +45 -66
- package/dist/services/index.mjs +1 -1
- package/dist/services/log-import/browser.d.mts +2 -2
- package/dist/services/log-import/index.d.mts +2 -2
- package/dist/services/log-import/log-import.d.mts +1 -1
- package/dist/services/log-import/log-import.mjs +1 -1
- package/dist/services/log-import/namespace.mjs +1 -1
- package/dist/services/log-import/schemas.mjs +1 -1
- package/dist/services/materialization/index.d.mts +13 -34
- package/dist/services/materialization/index.mjs +1 -1
- package/dist/services/model-registry/index.d.mts +1 -1
- package/dist/services/model-registry/index.mjs +1 -1
- package/dist/services/preferences/index.d.mts +2 -2
- package/dist/services/preferences/schemas.d.mts +1 -1
- package/dist/services/preferences/storage-namespace.d.mts +2 -2
- package/dist/services/provider-context/index.d.mts +1 -1
- package/dist/services/provider-context/index.mjs +1 -1
- package/dist/services/provider-runtime/index.mjs +1 -1
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/handlers/index.mjs +1 -1
- package/dist/services/session/index.d.mts +9 -9
- package/dist/services/session/index.mjs +1 -1
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/messages/namespace.mjs +1 -1
- package/dist/services/session/orchestrator-testing/index.d.mts +1 -1
- package/dist/services/session/orchestrator-testing/index.mjs +1 -1
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/session/session-events/namespace.mjs +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/session/testing/index.mjs +1 -1
- package/dist/services/session/testing/orchestrator-shared.d.mts +1 -1
- package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
- package/dist/services/session/turns/namespace.d.mts +1 -1
- package/dist/services/session/turns/namespace.mjs +1 -1
- package/dist/services/session-editor/index.d.mts +1 -1
- package/dist/services/session-editor/index.mjs +1 -1
- package/dist/services/settings/index.d.mts +3 -3
- package/dist/services/settings/index.mjs +1 -1
- package/dist/services/settings/namespace.mjs +1 -1
- package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
- package/dist/services/settings/storage/clients-namespace.mjs +1 -1
- package/dist/services/settings/storage/index.d.mts +3 -3
- package/dist/services/settings/storage/index.mjs +1 -1
- package/dist/services/settings/storage/providers-namespace.d.mts +1 -1
- package/dist/services/settings/storage/providers-namespace.mjs +1 -1
- package/dist/services/subagent/index.d.mts +1 -1
- 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/tool-approval/index.d.mts +1 -1
- package/dist/services/tool-approval/index.mjs +1 -1
- package/dist/services/tools/index.d.mts +1 -1
- package/dist/services/tools/index.mjs +1 -1
- package/dist/services/tray-menu/index.d.mts +3 -3
- package/dist/services/tray-menu/index.mjs +1 -1
- package/dist/services/tray-menu/namespace.d.mts +1 -1
- package/dist/services/tray-menu/schemas.d.mts +1 -1
- package/dist/services/turn/index.d.mts +1 -1
- package/dist/services/turn/namespace.d.mts +1 -1
- package/dist/services/workflow-transitions/index.d.mts +1 -1
- package/dist/services/workflow-transitions/index.mjs +1 -1
- package/dist/{session-CXOPk3yg.mjs → session-BDFNAcuY.mjs} +1 -1
- package/dist/{session-BOpTI79g.mjs → session-CQAuApxe.mjs} +1 -1
- package/dist/{shared-B9AWRm9A.mjs → shared-BYP7z9xy.mjs} +1 -1
- package/dist/{skill-DGNtc_ww.mjs → skill-1gU2q1KT.mjs} +1 -1
- package/dist/{src-DEgV239R.mjs → src-D4Gx0QHf.mjs} +1 -1
- package/dist/storage/drizzle/client.d.mts +1 -1
- package/dist/storage/drizzle/client.mjs +1 -1
- package/dist/storage/drizzle/index.d.mts +1 -1
- package/dist/storage/drizzle/index.mjs +1 -1
- package/dist/storage/handlers/drizzle/index.d.mts +1 -1
- package/dist/storage/handlers/drizzle/index.mjs +1 -1
- package/dist/storage/handlers/index.d.mts +1 -1
- package/dist/storage/handlers/index.mjs +1 -1
- package/dist/{tool-approval-service-BFDOFUGC.mjs → tool-approval-service-7mzJVMo_.mjs} +1 -1
- package/dist/{tools-DWKWX3eV.mjs → tools-Cyo6BuGM.mjs} +1 -1
- package/dist/{transition-DFA_ckdP.d.mts → transition-CwMPKBjz.d.mts} +2 -2
- package/dist/{types-p55qvq922.d.mts → types-BOF825V52.d.mts} +1 -1
- package/dist/{types-DkfDRSTr.d.mts → types-Dg_acP9p.d.mts} +36 -36
- package/dist/ui-kernel/index.d.mts +1 -1
- package/dist/ui-kernel/pages/schemas.d.mts +1 -1
- package/dist/{version-BYeVh1pI.mjs → version-3xWJDCeF.mjs} +1 -1
- package/dist/{view-builder-CYW_9n4A.d.mts → view-builder-D76L0Db8.d.mts} +209 -15
- package/dist/{visibility-DtDLRBdr.mjs → visibility-C5sLzqyS.mjs} +1 -1
- package/dist/{worker-B4nD_Erm.mjs → worker-9X0QNB1k.mjs} +1 -1
- package/dist/{worker-CLsRbzpk.mjs → worker-BwUhRg7i.mjs} +1 -1
- package/dist/workflow-B3MWrYhG.mjs +1 -0
- package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
- package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
- package/dist/workflow-engine/index.d.mts +52 -52
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/provider-operation.d.mts +1 -1
- package/dist/workflow-engine/testing/conformance.d.mts +1 -1
- package/dist/workflow-engine/testing/conformance.mjs +3 -1
- package/dist/workflow-engine/testing/index.d.mts +9 -6
- package/dist/workflow-engine/testing/index.mjs +1 -1
- package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
- package/dist/workflow-engine/testing/sqlite.mjs +63 -55
- package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
- package/dist/{workflow-transitions-c_VQbyV0.mjs → workflow-transitions-B7HtjuAn.mjs} +1 -1
- package/dist/workflow-worker-zYb2UguP.mjs +2 -0
- package/package.json +1 -1
- package/dist/artifact-ClvHqL3w.mjs +0 -1
- package/dist/attempt-record-codec-B32Whx75.mjs +0 -1
- package/dist/authority-state-bootstrap-7Cgb9TR2.mjs +0 -1
- package/dist/extension-Cz39YNXy.mjs +0 -1
- package/dist/framework-packages-BHgul8Kl.mjs +0 -1
- package/dist/materialization-B_LA9pfy.mjs +0 -1
- package/dist/model-DrzPt3ou.mjs +0 -1
- package/dist/namespace-sCPb79-7.mjs +0 -1
- package/dist/packages-Bp124-gx.mjs +0 -1
- package/dist/schemas-CNkUEbIr.mjs +0 -1
- package/dist/workflow-H8hsEikC.mjs +0 -1
- package/dist/workflow-worker-CmIkKnpF.mjs +0 -2
- /package/dist/{adapter-auth-runtime-DHHppU4f.mjs → adapter-auth-runtime-DGY1CDxj.mjs} +0 -0
- /package/dist/{adapter-binding-D68U_Hmh.d.mts → adapter-binding-fGIz-ss3.d.mts} +0 -0
- /package/dist/{ajv-krzJXh1X.mjs → ajv-DWgn_plp.mjs} +0 -0
- /package/dist/{attach-error-Cb3GbeKe.mjs → attach-error-B-vXQFLQ.mjs} +0 -0
- /package/dist/{attempt-fixtures-CnrnF5_4.mjs → attempt-fixtures-Dpfgqll0.mjs} +0 -0
- /package/dist/{base-orchestrator-DA95InJU.d.mts → base-orchestrator-BeLqYKJG.d.mts} +0 -0
- /package/dist/{bootstrap-start-client-DrvofWwi.mjs → bootstrap-start-client-BYoxrgMk.mjs} +0 -0
- /package/dist/{capability-j3NekkIu.mjs → capability-Bw4tsDQu.mjs} +0 -0
- /package/dist/{capability-service-s4ZYSEWc.d.mts → capability-service-BlYnun2M.d.mts} +0 -0
- /package/dist/{client-f5A-6La5.d.mts → client-CtOWHpFB.d.mts} +0 -0
- /package/dist/{client-binary-version-verifier-kd9LP9AQ.d.mts → client-binary-version-verifier-BwmToeS1.d.mts} +0 -0
- /package/dist/{client-binary-version-verifier-0lCKZOTg.mjs → client-binary-version-verifier-sv-Uv0lB.mjs} +0 -0
- /package/dist/{clients-namespace-q4PqU1cA.d.mts → clients-namespace-Bf73bcZh.d.mts} +0 -0
- /package/dist/{config-namespace-Cp71zTT0.d.mts → config-namespace-BbLLd4V0.d.mts} +0 -0
- /package/dist/{create-static-mount-CmQgA0jq.mjs → create-static-mount-BQnyEUH1.mjs} +0 -0
- /package/dist/{cross-spawn-CZygZJMH.mjs → cross-spawn-DPrJR9Nq.mjs} +0 -0
- /package/dist/{cursor-storage-bsc9lZKk.mjs → cursor-storage-iJ6vBOWd.mjs} +0 -0
- /package/dist/{definition-BHSzhrUf.d.mts → definition-aS9AM2ht.d.mts} +0 -0
- /package/dist/{definitions-CRpdnHYM.mjs → definitions-CYZTuMdL.mjs} +0 -0
- /package/dist/{descriptor-to-package-CcjdoWP4.mjs → descriptor-to-package-FBkLjHZo.mjs} +0 -0
- /package/dist/{drizzle-Bzc-OGVI.mjs → drizzle-CIf_jdYI.mjs} +0 -0
- /package/dist/{esm-i-S5TW72.mjs → esm-BH4Kmq3r.mjs} +0 -0
- /package/dist/{event-B8ELuk6k.mjs → event-m7_IdhOS.mjs} +0 -0
- /package/dist/{execution-attempt-repository-D0cCU7dI.mjs → execution-attempt-repository-D_qR7NyG.mjs} +0 -0
- /package/dist/{extension-context-BmU5XKjI.d.mts → extension-context-41A1ZUus.d.mts} +0 -0
- /package/dist/{extension-discovery-DnO7bINK.d.mts → extension-discovery-DNB1VVsV.d.mts} +0 -0
- /package/dist/{extension-namespace-QoTTwKPt.mjs → extension-namespace-twXNwE4R.mjs} +0 -0
- /package/dist/{extension-package-provenance-aYrZuS4W.mjs → extension-package-provenance-CTYdo0yF.mjs} +0 -0
- /package/dist/{facet-BnMh7Jyc.mjs → facet-Cly0VpTI.mjs} +0 -0
- /package/dist/{filesystem-service-BBArEDPL.d.mts → filesystem-service-DOrm4Llq.d.mts} +0 -0
- /package/dist/{handler-DF1fVDpf.mjs → handler-COkV00I9.mjs} +0 -0
- /package/dist/{host-B-_ntOMH.mjs → host-CiHn8Yog.mjs} +0 -0
- /package/dist/{identity-OjRlG6dZ.mjs → identity-BULrIHmo.mjs} +0 -0
- /package/dist/{index-xaBSwHxJ.d.mts → index-BB4EWIf3.d.mts} +0 -0
- /package/dist/{index-DYHxzwok2.d.mts → index-BBq5I7SB2.d.mts} +0 -0
- /package/dist/{index-NhW2h2wH2.d.mts → index-BJjdUzfw2.d.mts} +0 -0
- /package/dist/{index-CsFN2nv7.d.mts → index-BKvzOrbF.d.mts} +0 -0
- /package/dist/{index-D-JbTXIH.d.mts → index-BO8n7zAS.d.mts} +0 -0
- /package/dist/{index-Co1da7YK.d.mts → index-BbAqoQmv.d.mts} +0 -0
- /package/dist/{index-DSLTgc7h2.d.mts → index-BcTwLu9C2.d.mts} +0 -0
- /package/dist/{index-Dn_SGTgp.d.mts → index-Bg5iXHk5.d.mts} +0 -0
- /package/dist/{index-CPWBGotQ.d.mts → index-BiXqOfhl.d.mts} +0 -0
- /package/dist/{index-DSN2t48K.d.mts → index-BjaQsfAr.d.mts} +0 -0
- /package/dist/{index-mK-rgiit.d.mts → index-Bk865qJX.d.mts} +0 -0
- /package/dist/{index-CkpR5sIH.d.mts → index-Bq4PHWe9.d.mts} +0 -0
- /package/dist/{index-DW4SE_sH.d.mts → index-CUHWylh4.d.mts} +0 -0
- /package/dist/{index-CcrXttC02.d.mts → index-CavvxFdG2.d.mts} +0 -0
- /package/dist/{index-CDLf3Fka2.d.mts → index-Cb3NfGSV2.d.mts} +0 -0
- /package/dist/{index-Df1c_2PF.d.mts → index-Ce_l029J.d.mts} +0 -0
- /package/dist/{index-D94yE5Dr.d.mts → index-CgVdz5IV.d.mts} +0 -0
- /package/dist/{index-KAAnSRZt.d.mts → index-Ck5amD5_.d.mts} +0 -0
- /package/dist/{index-BB0HypzC.d.mts → index-ClJjlOox.d.mts} +0 -0
- /package/dist/{index-CGJgZGqN.d.mts → index-CoGo6HFE.d.mts} +0 -0
- /package/dist/{index-CrcfeFOo.d.mts → index-DR9-fFwc.d.mts} +0 -0
- /package/dist/{index-B-zl-O-Y.d.mts → index-Q29tcu5N.d.mts} +0 -0
- /package/dist/{index-DQD2-jcL.d.mts → index-VVJqONaI.d.mts} +0 -0
- /package/dist/{index-D6RMsZko.d.mts → index-gK54T8Am.d.mts} +0 -0
- /package/dist/{index-D_sMzTvv.d.mts → index-jW7MJ2_q.d.mts} +0 -0
- /package/dist/{index-CBixkF0n.d.mts → index-l5HeyxKn.d.mts} +0 -0
- /package/dist/{index-BDAfOYSw2.d.mts → index-oucWFlFP2.d.mts} +0 -0
- /package/dist/{index-Bf2MgOni.d.mts → index-z-YJG2cw.d.mts} +0 -0
- /package/dist/{index-C9xVZ-gt.d.mts → index-zvgQ8ErF.d.mts} +0 -0
- /package/dist/{json-value-pX6xnLGw.d.mts → json-value-C57MkQrB.d.mts} +0 -0
- /package/dist/{json-value-BBZ6uGwc.mjs → json-value-DM-EjTC1.mjs} +0 -0
- /package/dist/{jsonl-transport-DQIlRX_y.mjs → jsonl-transport-QQuABrN7.mjs} +0 -0
- /package/dist/{lib-6eNAiNK7.mjs → lib-Sx8gBJvV.mjs} +0 -0
- /package/dist/{model-registry-C9rFu3kV.mjs → model-registry-B7ThN_s3.mjs} +0 -0
- /package/dist/{model-registry-Cixxx2jv.mjs → model-registry-DNHDnyvs.mjs} +0 -0
- /package/dist/{modes-DwsJ3yVl.mjs → modes-CyG4sgs_.mjs} +0 -0
- /package/dist/{namespace-NXm_zvL1.mjs → namespace-BFlSY040.mjs} +0 -0
- /package/dist/{namespace-DiwqpB-c.mjs → namespace-BGgY903U.mjs} +0 -0
- /package/dist/{namespace-BMG3RCdr.d.mts → namespace-BY5-nA4j.d.mts} +0 -0
- /package/dist/{namespace-CVg_cpkh.d.mts → namespace-Bn-ryJn5.d.mts} +0 -0
- /package/dist/{namespace-Cs-cOyrn.d.mts → namespace-By3nEmBH.d.mts} +0 -0
- /package/dist/{namespace-Du0accdE.mjs → namespace-C9d0aoYT.mjs} +0 -0
- /package/dist/{namespace-Dw5H_KCF.d.mts → namespace-CPC1vbOu.d.mts} +0 -0
- /package/dist/{namespace-CPR2xem0.d.mts → namespace-Ca4sQ8X-.d.mts} +0 -0
- /package/dist/{namespace-BoyqQiW9.d.mts → namespace-D1qK-Ed3.d.mts} +0 -0
- /package/dist/{namespace-9ychTEk_.d.mts → namespace-DE3oGhaN.d.mts} +0 -0
- /package/dist/{namespace-DG0hjPcx.d.mts → namespace-DENdNdK0.d.mts} +0 -0
- /package/dist/{namespace-jVTsuZHX.mjs → namespace-DHrItZyM.mjs} +0 -0
- /package/dist/{namespace-DykqxEyX.d.mts → namespace-DInMixc8.d.mts} +0 -0
- /package/dist/{namespace-CQEYu8az.d.mts → namespace-DP0WWpTO.d.mts} +0 -0
- /package/dist/{namespace-BGDq7HmW.d.mts → namespace-DkAlBY9o.d.mts} +0 -0
- /package/dist/{namespace-BW3Bfu9h.mjs → namespace-QXCaZK3I.mjs} +0 -0
- /package/dist/{namespace-tjoxekmf.mjs → namespace-ZN49zpqw.mjs} +0 -0
- /package/dist/{orchestrator-shared-BzqqcY2z.d.mts → orchestrator-shared-2vuCvljs.d.mts} +0 -0
- /package/dist/{out-8bOYN6EF.mjs → out-Rz-t3WeC.mjs} +0 -0
- /package/dist/{ownership-recovery-guard-DyW5vGBr.mjs → ownership-recovery-guard-Ce9-C5Sa.mjs} +0 -0
- /package/dist/{package-DttKA9wN.mjs → package-DfjGt5oK.mjs} +0 -0
- /package/dist/{package-EGTn-Ng1.mjs → package-Tt2uoAFf.mjs} +0 -0
- /package/dist/{platform-CxyYPrkf.mjs → platform-C-fDsuEl.mjs} +0 -0
- /package/dist/{provider-operation-B2wQST6N.d.mts → provider-operation-BwrIrOeY.d.mts} +0 -0
- /package/dist/{providers-C-eekMxD.mjs → providers-DVlsnJaY.mjs} +0 -0
- /package/dist/{providers-namespace-DsKTnuO1.d.mts → providers-namespace-C56pGeTO.d.mts} +0 -0
- /package/dist/{quick-lru-CCEnf7y6.mjs → quick-lru-uXa2PNb5.mjs} +0 -0
- /package/dist/{registry-Dk12tAfv.mjs → registry-CZf8VGBh.mjs} +0 -0
- /package/dist/{schema-C0opCPww.mjs → schema-DIHGEQx3.mjs} +0 -0
- /package/dist/{schema-introspection-6-r_KEJQ.mjs → schema-introspection-CSnLZJpC.mjs} +0 -0
- /package/dist/{schemas-Dxvjq-Bi.d.mts → schemas-B0zhTfet.d.mts} +0 -0
- /package/dist/{schemas-ClGDFa44.d.mts → schemas-B2Q284-G.d.mts} +0 -0
- /package/dist/{schemas--LAbwXvw.d.mts → schemas-BJKx29Sp.d.mts} +0 -0
- /package/dist/{schemas-BivbWRkG.mjs → schemas-BKnJj2i-.mjs} +0 -0
- /package/dist/{schemas-DmULJ7Jk.d.mts → schemas-BMGJLkdK2.d.mts} +0 -0
- /package/dist/{schemas-B2UbGJpJ.d.mts → schemas-BSBb1KFq.d.mts} +0 -0
- /package/dist/{schemas-CeHU889f.mjs → schemas-BapfTRqp.mjs} +0 -0
- /package/dist/{schemas-Bk50UoMA.d.mts → schemas-BsZJHdvY.d.mts} +0 -0
- /package/dist/{schemas-CzGN0eqW.d.mts → schemas-CITR9cWN.d.mts} +0 -0
- /package/dist/{schemas-B8hKbBwI.mjs → schemas-CnFVygzI.mjs} +0 -0
- /package/dist/{schemas-scyC2tFF.mjs → schemas-DDCAGKRi.mjs} +0 -0
- /package/dist/{schemas-CBpjAhut.d.mts → schemas-DmE-a0kN.d.mts} +0 -0
- /package/dist/{schemas-Wqo3_F6-.d.mts → schemas-gfrOgGau.d.mts} +0 -0
- /package/dist/{schemas-CHRuwe18.d.mts → schemas-wPB7RnHB.d.mts} +0 -0
- /package/dist/{semver-BI7kTNsY.mjs → semver-D_D2mA48.mjs} +0 -0
- /package/dist/{server-lifecycle-B_OZnoe-.mjs → server-lifecycle-AvBVeCFR.mjs} +0 -0
- /package/dist/{server-lifecycle-WFZcCMwF.d.mts → server-lifecycle-CREtXADx.d.mts} +0 -0
- /package/dist/{session-lineage-C9kppcCa.d.mts → session-lineage-CRLvurB-.d.mts} +0 -0
- /package/dist/{shared-schemas-CQ6blrEW.mjs → shared-schemas-kUho6Kmw.mjs} +0 -0
- /package/dist/{src-DIyWekjW.mjs → src-DnLncoLg.mjs} +0 -0
- /package/dist/{storage-namespace-BZce8kkW.mjs → storage-namespace-CH4j0_Zs.mjs} +0 -0
- /package/dist/{storage-namespace-BWU-8rvj.d.mts → storage-namespace-JBh9nkKw.d.mts} +0 -0
- /package/dist/{storage-namespace-definition-Cca-zwXU.mjs → storage-namespace-definition-BJCbqVWz.mjs} +0 -0
- /package/dist/{storage-namespace-definition-B-8JKvzm.d.mts → storage-namespace-definition-C0mnpnC_.d.mts} +0 -0
- /package/dist/{supports-color-SV_FgSN2.mjs → supports-color-BBMFnbC4.mjs} +0 -0
- /package/dist/{telemetry-BqoC87F-.mjs → telemetry-CUkZrhW6.mjs} +0 -0
- /package/dist/{timeout-DVlN2Zhy.mjs → timeout-DeBYTGBR.mjs} +0 -0
- /package/dist/{tray-menu-service-eVVxgPLc.mjs → tray-menu-service-thAhpcPA.mjs} +0 -0
- /package/dist/{types-BnPJa-C_.d.mts → types-9ldZyQTb.d.mts} +0 -0
- /package/dist/{types-DQTCNM2i.d.mts → types-BMkn9jOe.d.mts} +0 -0
- /package/dist/{types-Cwza95hS.mjs → types-CjjNAiHa.mjs} +0 -0
- /package/dist/{types-DxHeL0pF.d.mts → types-DJuxNrac.d.mts} +0 -0
- /package/dist/{types-BFeWU3WM.d.mts → types-eCGV_g6P.d.mts} +0 -0
- /package/dist/{types-8rMNe3AS.d.mts → types-xXv0lUeU.d.mts} +0 -0
- /package/dist/{ui-config-B35GloSX.mjs → ui-config-9hlZAJOS.mjs} +0 -0
- /package/dist/{variant-Dwnge3J_.mjs → variant-73kFgYBK.mjs} +0 -0
- /package/dist/{window-registry-DQP5P2_0.d.mts → window-registry-CGaYVD7l.d.mts} +0 -0
- /package/dist/{window-registry-CKiMJjId.mjs → window-registry-CzAwaPKL.mjs} +0 -0
- /package/dist/{zod-json-schema-Dixc-B1T.mjs → zod-json-schema-B9TYYq3e.mjs} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{$ as e,A as t,B as n,D as r,G as i,H as a,I as o,J as s,K as c,L as l,M as u,N as d,O as f,P as p,Q as ee,R as te,U as ne,V as re,W as ie,X as ae,Y as oe,Z as se,_t as ce,a as le,at as ue,c as de,ct as fe,dt as pe,et as me,f as he,ft as ge,g as _e,gt as ve,h as ye,ht as be,i as xe,it as Se,j as Ce,k as m,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,st as Le,tt as Re,u as ze,ut as Be,v as Ve,vt as h,z as g}from"./authority-state-bootstrap-7Cgb9TR2.mjs";import{a as He}from"./execution-attempt-repository-D0cCU7dI.mjs";import{assertWorkflowTriggerPayload as Ue,compileWorkflowTriggerBindingFilter as We}from"./workflow-engine/workflow-trigger-binding-consumer.mjs";import{SerialLane as Ge}from"@makaio/framework/utils";import{ArtifactSubjects as Ke,AutomationTriggerSubjects as qe,CRON_AUTOMATION_TRIGGER_KIND as Je,EXECUTION_LIST_DEFAULT_LIMIT as Ye,EXECUTION_LIST_MAX_LIMIT as _,EXECUTION_LIST_MIN_LIMIT as v,EXTERNAL_EXECUTION_ID_PREFIX as y,ExecutionAttemptSchemas as b,ExecutionAttemptSubjects as x,ExecutionsByArtifactRefsQuerySchema as Xe,JsonPatchOperationSchema as Ze,JsonValueSchema as Qe,SessionSubjects as $e,WORKFLOW_CANCELLED_REASON as et,WorkLogFrameEntrySchema as tt,WorkerSubjects as nt,WorkflowAutomationTriggerBindingSchema as rt,WorkflowError as S,WorkflowErrorCode as it,WorkflowNamespace as at,WorkflowRunContextSchema as ot,WorkflowRunResultSchema as st,WorkflowStepTypeSchema as ct,WorkflowSubjects as C,createWorkflowCancelSubject as lt,createWorkflowDelegateResultFinalizerNamespace as ut,createWorkflowFinalizerNamespace as dt,dep as ft,extensionToken as pt,serializeArtifactRef as mt,walkWorkflowDefinition as ht}from"@makaio/framework/contracts";import{BaseService as gt}from"@makaio/framework/service-base";import{defineDialectSchema as _t,executeTransaction as w,getDatabaseDialect as vt,registerDrizzleHandlers as yt,resolveSchema as T,serializeDatabaseOperation as E}from"@makaio/framework/storage/drizzle";import{and as D,asc as O,count as k,desc as A,eq as j,getTableColumns as bt,gte as xt,isNotNull as St,isNull as M,lt as Ct,lte as wt,notInArray as Tt,or as Et,sql as N,sum as P}from"drizzle-orm";import{SessionToken as Dt}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as Ot}from"@makaio/framework/services/automation-trigger";const kt=ie.postgres,At=me.postgres,jt=c.postgres,Mt=ke.postgres,Nt=je.postgres,Pt=s.postgres,Ft=Se.postgres,It=De.postgres,Lt=Be.postgres,Rt=fe.postgres,zt=ge.postgres,Bt=ae.postgres,Vt=ee.postgres,Ht=ve.postgres,F=_t({workflowDefinitions:ne,workflowExecutions:e,workflowExecutionFrames:i,workflowGateInstances:Re,workflowStepSpans:ue,workflowExecutionLinks:Pe,workflowRunContexts:Ie,worklogSummaries:Ne,worklogFrameEntries:Te,worklogArtifactWrites:Le,worklogGateEvents:pe,workflowExecutionState:oe,workflowExecutionStateEvents:se,workflowFinalizations:be},{workflowDefinitions:kt,workflowExecutions:At,workflowExecutionFrames:jt,workflowGateInstances:Mt,workflowStepSpans:Nt,workflowExecutionLinks:Pt,workflowRunContexts:Ft,worklogSummaries:It,worklogFrameEntries:Lt,worklogArtifactWrites:Rt,worklogGateEvents:zt,workflowExecutionState:Bt,workflowExecutionStateEvents:Vt,workflowFinalizations:Ht});function I(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 L(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 Ut(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=I(t);return[j(e.scopeType,n),j(e.scopeKind,r),j(e.scopeId,i)]}function R(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:L(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executableSource:e.executableSource??void 0,requirements:e.requirements??void 0,successFinalizerId:e.successFinalizerId??void 0}}function Wt(e,t){let n=I(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executableSource:e.executableSource??null,requirements:e.requirements??null,successFinalizerId:e.successFinalizerId??null,createdAt:t,updatedAt:t,...n}}function Gt(e,t){let{workflowDefinitions:n}=T(t,F),r=bt(n),i=e.on(a.get,async e=>{let r=await t.select().from(n).where(j(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?R(r[0]):null})}),o=e.on(a.set,async i=>{let a=i.payload.workflow,o=Date.now(),s=Wt(a,o),c=await E(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:N`COALESCE(${r.createdAt}, ${o})`,description:s.description===null?N`${r.description}`:s.description,inputSchema:s.inputSchema===null?N`${r.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?N`${r.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?N`${r.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?N`${r.artifact}`:s.artifact,triggers:s.triggers===null?N`${r.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?N`${r.canvasLayout}`:s.canvasLayout,source:s.source===null?N`${r.source}`:s.source,executableSource:s.executableSource,requirements:s.requirements,successFinalizerId:s.successFinalizerId,...I(a.scope)}).where(j(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});c&&await e.emit(c.kind===`created`?h.definition.created:h.definition.updated,R(c.row)),i.setResult({id:a.id})}),s=e.on(a.delete,async r=>{let i=(await E(t,()=>t.delete(n).where(j(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(h.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),c=e.on(a.list,async e=>{let r=e.payload,i=r.scope?Ut(n,r.scope):[],a=i.length>0?await t.select().from(n).where(D(...i)):await t.select().from(n);e.setResult({workflows:a.map(R)})});return()=>{i(),o(),s(),c()}}function Kt(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 qt(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 Jt(e,t){let{workflowExecutionFrames:n}=T(t,F),r=e.on(a.setFrame,async e=>{let{executionId:r,frame:i}=e.payload;if(!g(e,r))throw Error(`Unauthorized: caller is not permitted to write frames for execution: ${r}`);let a=qt(r,i);await E(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(a.getFrame,async e=>{let r=await t.select().from(n).where(j(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?Kt(r[0]):null})}),o=e.on(a.listFrames,async e=>{if(!g(e,e.payload.executionId))throw Error(`Unauthorized: caller is not permitted to list frames for execution: ${e.payload.executionId}`);let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.frameId));e.setResult({frames:r.map(Kt)})});return()=>{r(),i(),o()}}function Yt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function z(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 B(e){return{id:Yt(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 Xt(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??Ye;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?[]:[j(r.executionId,e)],...t===void 0?[]:[j(r.status,t)]]}}function Zt(e,t){let{workflowExecutions:n,workflowGateInstances:r}=T(t,F),i=e.on(a.setGateInstance,async e=>{let n=e.payload.gate;if(!g(e,n.executionId))throw Error(`Unauthorized: caller is not permitted to write gates for execution: ${n.executionId}`);let i=B(n);await E(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),o=e.on(a.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=B(n),a=await E(t,()=>t.update(r).set(i).where(D(j(r.id,i.id),j(r.status,`waiting`))).returning({id:r.id}));e.setResult({accepted:a.length===1})}),s=e.on(a.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload;if(!g(e,n))throw Error(`Unauthorized: caller is not permitted to read gates for execution: ${n}`);let o=[j(r.executionId,n),j(r.nodeId,i)];a!==void 0&&o.push(j(r.frameId,a));let s=await t.select().from(r).where(D(...o)).limit(1);e.setResult({gate:s[0]?z(s[0]):null})}),c=e.on(a.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Xt(n,i,a,r),c=await t.select().from(r).where(D(...s)).orderBy(A(r.createdAt),A(r.id)).limit(o);e.setResult({gates:c.map(z)})}),l=e.on(a.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,j(r.executionId,n.id)).where(D(j(r.status,`waiting`),j(n.status,`paused`),St(r.timeoutMs)));e.setResult({gates:i.map(e=>z(e.gate))})});return()=>{i(),o(),s(),c(),l()}}function Qt(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 $t(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function en(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=T(t,F),i=e.on(a.setSpan,async e=>{let{span:r}=e.payload;if(!g(e,r.executionId))throw Error(`Unauthorized: caller is not permitted to write spans for execution: ${r.executionId}`);await E(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),o=e.on(a.listSpans,async e=>{let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.stepId),O(n.frameId));e.setResult({spans:r.map(Qt)})}),s=e.on(a.setExecutionLink,async e=>{let{link:n}=e.payload;await E(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(a.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?[]:[j(r.sourceExecutionId,n)],...i===void 0?[]:[j(r.targetExecutionId,i)]],o=t.select().from(r).where(D(...a));e.setResult({links:(await o).map($t)})});return()=>{i(),o(),s(),c()}}function V(e,t){return t===null?vt(e)===`postgres`?N`'null'::jsonb`:N`'null'`:t}function tn(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 nn(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 rn(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:nn(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:L(e),...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===null?{}:{materializationSpec:e.materializationSpec}}}function an(e){let t=tn(e.source),n=I(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,artifactRef:e.artifactRef??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??null,materializationSpec:e.materializationSpec??null}}async function on(e,t,n){let r=an(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function sn(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=T(t,F),o=e.on(a.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await w(t,async e=>{if(await on(e,a,n),o===void 0)return;let s=Date.now(),c=V(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})}),s=e.on(a.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(j(n.executionId,r)),a=i[0]?rn(i[0]):null;e.setResult({runContext:a})});return()=>{o(),s()}}async function cn(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=T(e,F),a=Date.now(),o=V(e,n);await w(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 ln(e,t){let{workflowExecutionState:n}=T(e,F),r=(await e.select().from(n).where(j(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function un(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=T(e,F),i=Date.now(),a=V(e,t.nextValue);return w(e,async e=>{let o=(await e.select().from(n).where(j(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=te(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(D(j(n.executionId,t.executionId),j(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function dn(e,t){let n=e.on(a.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await cn(t,n,r),e.setResult({})}),r=e.on(a.getState,async e=>{let{executionId:n}=e.payload,r=await ln(t,n);e.setResult({state:r})}),i=e.on(a.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await un(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function fn(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 pn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function mn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:hn(t),setWhere:Tt(n.status,[`completed`,`failed`,`cancelled`])})}function hn(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 H(e,t){let{worklogSummaries:n}=T(e,F),r=await e.select().from(n).where(j(n.executionId,t)).limit(1);return r[0]?fn(r[0]):null}async function gn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[j(n.status,i)]],c=s.length>0?D(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(A(n.startedAt)).limit(a).offset(o),e.select({count:k()}).from(n).where(c)]);return{items:l.map(fn),total:u[0]?.count??0}}async function _n(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function vn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:Tt(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function U(e,t){let{worklogFrameEntries:n}=T(e,F);return(await e.select().from(n).where(j(n.frameId,t)).limit(1))[0]??null}async function yn(e,t){let n=await U(e,t);return n===null?null:tt.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 bn(e,t){let{worklogArtifactWrites:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function xn(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function W(e,t){let{worklogGateEvents:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function Sn(e,t){let{worklogGateEvents:n}=T(e,F);return(await e.select().from(n).where(j(n.id,t)).limit(1))[0]??null}function G(e,t,n){return`${e}:${t}:${n}`}async function Cn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(j(t.executionId,n)).returning();return r}async function wn(e,t,n){let[r]=await e.select({totalInputTokens:P(t.inputTokens),totalOutputTokens:P(t.outputTokens),totalEstimatedCost:P(t.estimatedCost),measuredInputTokens:k(t.inputTokens),measuredOutputTokens:k(t.outputTokens),measuredCosts:k(t.estimatedCost)}).from(t).where(j(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 Tn(e){return e.hasMeasurements}async function En(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(j(t.executionId,n))}async function Dn(e,t,n,r){let i=N`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=N`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=N`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=N`exists(
|
|
1
|
+
import{$ as e,A as t,B as n,D as r,G as i,H as a,I as o,J as s,K as c,L as l,M as u,N as d,O as f,P as p,Q as ee,R as te,U as ne,V as re,W as ie,X as ae,Y as oe,Z as se,_t as ce,a as le,at as ue,c as de,ct as fe,dt as pe,et as me,f as he,ft as ge,g as _e,gt as ve,h as ye,ht as be,i as xe,it as Se,j as Ce,k as m,l as we,lt as Te,m as Ee,mt as De,n as Oe,nt as ke,o as Ae,ot as je,p as Me,pt as Ne,q as Pe,r as Fe,rt as Ie,st as Le,tt as Re,u as ze,ut as Be,v as Ve,vt as h,z as g}from"./authority-state-bootstrap-rnsTk0u7.mjs";import{a as He}from"./execution-attempt-repository-D_qR7NyG.mjs";import{assertWorkflowTriggerPayload as Ue,compileWorkflowTriggerBindingFilter as We}from"./workflow-engine/workflow-trigger-binding-consumer.mjs";import{a as Ge,r as Ke}from"./execution-attempt-owner-recovery-BNERIDH0.mjs";import{SerialLane as qe}from"@makaio/framework/utils";import{ArtifactSubjects as Je,AutomationTriggerSubjects as Ye,CRON_AUTOMATION_TRIGGER_KIND as Xe,EXECUTION_LIST_DEFAULT_LIMIT as Ze,EXECUTION_LIST_MAX_LIMIT as _,EXECUTION_LIST_MIN_LIMIT as v,EXTERNAL_EXECUTION_ID_PREFIX as y,ExecutionAttemptSchemas as b,ExecutionAttemptSubjects as x,ExecutionsByArtifactRefsQuerySchema as Qe,JsonPatchOperationSchema as $e,JsonValueSchema as et,SessionSubjects as tt,WORKFLOW_CANCELLED_REASON as nt,WorkLogFrameEntrySchema as rt,WorkerSubjects as it,WorkflowAutomationTriggerBindingSchema as at,WorkflowError as S,WorkflowErrorCode as ot,WorkflowNamespace as st,WorkflowRunContextSchema as ct,WorkflowRunResultSchema as lt,WorkflowStepTypeSchema as ut,WorkflowSubjects as C,createWorkflowCancelSubject as dt,createWorkflowDelegateResultFinalizerNamespace as ft,createWorkflowFinalizerNamespace as pt,dep as mt,extensionToken as ht,serializeArtifactRef as gt,walkWorkflowDefinition as _t}from"@makaio/framework/contracts";import{BaseService as vt}from"@makaio/framework/service-base";import{defineDialectSchema as yt,executeTransaction as w,getDatabaseDialect as bt,registerDrizzleHandlers as xt,resolveSchema as T,serializeDatabaseOperation as E}from"@makaio/framework/storage/drizzle";import{and as D,asc as O,count as k,desc as A,eq as j,getTableColumns as St,gte as Ct,isNotNull as wt,isNull as M,lt as Tt,lte as Et,notInArray as Dt,or as Ot,sql as N,sum as P}from"drizzle-orm";import{SessionToken as kt}from"@makaio/framework/services";import{AutomationTriggerBindingRuntimeToken as At}from"@makaio/framework/services/automation-trigger";const jt=ie.postgres,Mt=me.postgres,Nt=c.postgres,Pt=ke.postgres,Ft=je.postgres,It=s.postgres,Lt=Se.postgres,Rt=De.postgres,zt=Be.postgres,Bt=fe.postgres,Vt=ge.postgres,Ht=ae.postgres,Ut=ee.postgres,Wt=ve.postgres,F=yt({workflowDefinitions:ne,workflowExecutions:e,workflowExecutionFrames:i,workflowGateInstances:Re,workflowStepSpans:ue,workflowExecutionLinks:Pe,workflowRunContexts:Ie,worklogSummaries:Ne,worklogFrameEntries:Te,worklogArtifactWrites:Le,worklogGateEvents:pe,workflowExecutionState:oe,workflowExecutionStateEvents:se,workflowFinalizations:be},{workflowDefinitions:jt,workflowExecutions:Mt,workflowExecutionFrames:Nt,workflowGateInstances:Pt,workflowStepSpans:Ft,workflowExecutionLinks:It,workflowRunContexts:Lt,worklogSummaries:Rt,worklogFrameEntries:zt,worklogArtifactWrites:Bt,worklogGateEvents:Vt,workflowExecutionState:Ht,workflowExecutionStateEvents:Ut,workflowFinalizations:Wt});function I(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 L(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 Gt(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=I(t);return[j(e.scopeType,n),j(e.scopeKind,r),j(e.scopeId,i)]}function R(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:L(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executableSource:e.executableSource??void 0,requirements:e.requirements??void 0,successFinalizerId:e.successFinalizerId??void 0}}function Kt(e,t){let n=I(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executableSource:e.executableSource??null,requirements:e.requirements??null,successFinalizerId:e.successFinalizerId??null,createdAt:t,updatedAt:t,...n}}function qt(e,t){let{workflowDefinitions:n}=T(t,F),r=St(n),i=e.on(a.get,async e=>{let r=await t.select().from(n).where(j(n.id,e.payload.id)).limit(1);e.setResult({workflow:r[0]?R(r[0]):null})}),o=e.on(a.set,async i=>{let a=i.payload.workflow,o=Date.now(),s=Kt(a,o),c=await E(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:N`COALESCE(${r.createdAt}, ${o})`,description:s.description===null?N`${r.description}`:s.description,inputSchema:s.inputSchema===null?N`${r.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?N`${r.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?N`${r.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?N`${r.artifact}`:s.artifact,triggers:s.triggers===null?N`${r.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?N`${r.canvasLayout}`:s.canvasLayout,source:s.source===null?N`${r.source}`:s.source,executableSource:s.executableSource,requirements:s.requirements,successFinalizerId:s.successFinalizerId,...I(a.scope)}).where(j(n.id,a.id)).returning();return i?{kind:`updated`,row:i}:void 0});c&&await e.emit(c.kind===`created`?h.definition.created:h.definition.updated,R(c.row)),i.setResult({id:a.id})}),s=e.on(a.delete,async r=>{let i=(await E(t,()=>t.delete(n).where(j(n.id,r.payload.id)).returning())).length>0;i&&await e.emit(h.definition.deleted,{id:r.payload.id}),r.setResult({deleted:i})}),c=e.on(a.list,async e=>{let r=e.payload,i=r.scope?Gt(n,r.scope):[],a=i.length>0?await t.select().from(n).where(D(...i)):await t.select().from(n);e.setResult({workflows:a.map(R)})});return()=>{i(),o(),s(),c()}}function Jt(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 Yt(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 Xt(e,t){let{workflowExecutionFrames:n}=T(t,F),r=e.on(a.setFrame,async e=>{let{executionId:r,frame:i}=e.payload;if(!g(e,r))throw Error(`Unauthorized: caller is not permitted to write frames for execution: ${r}`);let a=Yt(r,i);await E(t,()=>t.insert(n).values(a).onConflictDoUpdate({target:n.frameId,set:a})),e.setResult({frameId:i.frameId})}),i=e.on(a.getFrame,async e=>{let r=await t.select().from(n).where(j(n.frameId,e.payload.frameId)).limit(1);e.setResult({frame:r[0]?Jt(r[0]):null})}),o=e.on(a.listFrames,async e=>{if(!g(e,e.payload.executionId))throw Error(`Unauthorized: caller is not permitted to list frames for execution: ${e.payload.executionId}`);let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.frameId));e.setResult({frames:r.map(Jt)})});return()=>{r(),i(),o()}}function Zt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function z(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 B(e){return{id:Zt(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 Qt(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??Ze;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?[]:[j(r.executionId,e)],...t===void 0?[]:[j(r.status,t)]]}}function $t(e,t){let{workflowExecutions:n,workflowGateInstances:r}=T(t,F),i=e.on(a.setGateInstance,async e=>{let n=e.payload.gate;if(!g(e,n.executionId))throw Error(`Unauthorized: caller is not permitted to write gates for execution: ${n.executionId}`);let i=B(n);await E(t,()=>t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i})),e.setResult({id:i.id})}),o=e.on(a.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,i=B(n),a=await E(t,()=>t.update(r).set(i).where(D(j(r.id,i.id),j(r.status,`waiting`))).returning({id:r.id}));e.setResult({accepted:a.length===1})}),s=e.on(a.getGateInstance,async e=>{let{executionId:n,nodeId:i,frameId:a}=e.payload;if(!g(e,n))throw Error(`Unauthorized: caller is not permitted to read gates for execution: ${n}`);let o=[j(r.executionId,n),j(r.nodeId,i)];a!==void 0&&o.push(j(r.frameId,a));let s=await t.select().from(r).where(D(...o)).limit(1);e.setResult({gate:s[0]?z(s[0]):null})}),c=e.on(a.listGateInstances,async e=>{let{executionId:n,status:i,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Qt(n,i,a,r),c=await t.select().from(r).where(D(...s)).orderBy(A(r.createdAt),A(r.id)).limit(o);e.setResult({gates:c.map(z)})}),l=e.on(a.listPausedGateTimeouts,async e=>{let i=await t.select({gate:r}).from(r).innerJoin(n,j(r.executionId,n.id)).where(D(j(r.status,`waiting`),j(n.status,`paused`),wt(r.timeoutMs)));e.setResult({gates:i.map(e=>z(e.gate))})});return()=>{i(),o(),s(),c(),l()}}function en(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function tn(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function nn(e,t){let{workflowStepSpans:n,workflowExecutionLinks:r}=T(t,F),i=e.on(a.setSpan,async e=>{let{span:r}=e.payload;if(!g(e,r.executionId))throw Error(`Unauthorized: caller is not permitted to write spans for execution: ${r.executionId}`);await E(t,()=>t.insert(n).values(r).onConflictDoUpdate({target:[n.executionId,n.frameId],set:r})),e.setResult({id:`${r.executionId}:${r.frameId}`})}),o=e.on(a.listSpans,async e=>{let r=await t.select().from(n).where(j(n.executionId,e.payload.executionId)).orderBy(O(n.startedAt),O(n.stepId),O(n.frameId));e.setResult({spans:r.map(en)})}),s=e.on(a.setExecutionLink,async e=>{let{link:n}=e.payload;await E(t,()=>t.insert(r).values(n).onConflictDoUpdate({target:[r.sourceExecutionId,r.targetExecutionId],set:n})),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(a.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?[]:[j(r.sourceExecutionId,n)],...i===void 0?[]:[j(r.targetExecutionId,i)]],o=t.select().from(r).where(D(...a));e.setResult({links:(await o).map(tn)})});return()=>{i(),o(),s(),c()}}function V(e,t){return t===null?bt(e)===`postgres`?N`'null'::jsonb`:N`'null'`:t}function rn(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 an(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function on(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:an(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:L(e),...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===null?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===null?{}:{materializationSpec:e.materializationSpec}}}function sn(e){let t=rn(e.source),n=I(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,artifactRef:e.artifactRef??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??null,materializationSpec:e.materializationSpec??null}}async function cn(e,t,n){let r=sn(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function ln(e,t){let{workflowRunContexts:n,workflowExecutionState:r,workflowExecutionStateEvents:i}=T(t,F),o=e.on(a.setRunContext,async e=>{let a=e.payload.runContext,o=e.payload.initialState;await w(t,async e=>{if(await cn(e,a,n),o===void 0)return;let s=Date.now(),c=V(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})}),s=e.on(a.getRunContext,async e=>{let{executionId:r}=e.payload,i=await t.select().from(n).where(j(n.executionId,r)),a=i[0]?on(i[0]):null;e.setResult({runContext:a})});return()=>{o(),s()}}async function un(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=T(e,F),a=Date.now(),o=V(e,n);await w(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 dn(e,t){let{workflowExecutionState:n}=T(e,F),r=(await e.select().from(n).where(j(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function fn(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=T(e,F),i=Date.now(),a=V(e,t.nextValue);return w(e,async e=>{let o=(await e.select().from(n).where(j(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=te(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(D(j(n.executionId,t.executionId),j(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function pn(e,t){let n=e.on(a.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await un(t,n,r),e.setResult({})}),r=e.on(a.getState,async e=>{let{executionId:n}=e.payload,r=await dn(t,n);e.setResult({state:r})}),i=e.on(a.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await fn(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{n(),r(),i()}}function mn(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 hn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function gn(e,t){let{worklogSummaries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:_n(t),setWhere:Dt(n.status,[`completed`,`failed`,`cancelled`])})}function _n(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 H(e,t){let{worklogSummaries:n}=T(e,F),r=await e.select().from(n).where(j(n.executionId,t)).limit(1);return r[0]?mn(r[0]):null}async function vn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[j(n.status,i)]],c=s.length>0?D(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(A(n.startedAt)).limit(a).offset(o),e.select({count:k()}).from(n).where(c)]);return{items:l.map(mn),total:u[0]?.count??0}}async function yn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoNothing()}async function bn(e,t){let{worklogFrameEntries:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t,setWhere:Dt(n.status,[`completed`,`failed`,`skipped`,`cancelled`])})}async function U(e,t){let{worklogFrameEntries:n}=T(e,F);return(await e.select().from(n).where(j(n.frameId,t)).limit(1))[0]??null}async function xn(e,t){let n=await U(e,t);return n===null?null:rt.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 Sn(e,t){let{worklogArtifactWrites:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function Cn(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function W(e,t){let{worklogGateEvents:n}=T(e,F);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function wn(e,t){let{worklogGateEvents:n}=T(e,F);return(await e.select().from(n).where(j(n.id,t)).limit(1))[0]??null}function G(e,t,n){return`${e}:${t}:${n}`}async function Tn(e,t,n){let[r]=await e.update(t).set({totalInputTokens:t.totalInputTokens}).where(j(t.executionId,n)).returning();return r}async function En(e,t,n){let[r]=await e.select({totalInputTokens:P(t.inputTokens),totalOutputTokens:P(t.outputTokens),totalEstimatedCost:P(t.estimatedCost),measuredInputTokens:k(t.inputTokens),measuredOutputTokens:k(t.outputTokens),measuredCosts:k(t.estimatedCost)}).from(t).where(j(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 Dn(e){return e.hasMeasurements}async function On(e,t,n,r){await e.update(t).set({totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost}).where(j(t.executionId,n))}async function kn(e,t,n,r){let i=N`coalesce((select sum(${n.inputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,a=N`coalesce((select sum(${n.outputTokens}) from ${n} where ${n.executionId} = ${r}), 0)`,o=N`coalesce((select sum(${n.estimatedCost}) from ${n} where ${n.executionId} = ${r}), 0)`,s=N`exists(
|
|
2
2
|
select 1 from ${n}
|
|
3
3
|
where ${n.executionId} = ${r}
|
|
4
4
|
and (${n.inputTokens} is not null
|
|
5
5
|
or ${n.outputTokens} is not null
|
|
6
6
|
or ${n.estimatedCost} is not null)
|
|
7
|
-
)`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(D(j(t.executionId,r),s))}async function On(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=T(e,F);if(vt(e)===`sqlite`){await Dn(e,n,r,t);return}await w(e,async e=>{if(await Cn(e,n,t)===void 0)return;let i=await wn(e,r,t);Tn(i)&&await En(e,n,t,i)})}async function kn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[xt(n.startedAt,i)],...a===void 0?[]:[wt(n.startedAt,a)]],s=o.length>0?D(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:k()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:P(n.durationMs),totalInputTokens:P(n.totalInputTokens),totalOutputTokens:P(n.totalOutputTokens),totalEstimatedCost:P(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 An(e,t,n,r,i){let a=await U(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(Ke.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function K(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function q(e,t){try{await e.emit(h.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const jn=new Set([`completed`,`failed`,`cancelled`]);function Mn(e){return jn.has(e)}async function Nn(e,t){return await pn(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 Pn(e,t){let n=t.completedAt??Date.now(),r=await H(e,t.executionId);return r!==null&&Mn(r.status)?!1:(await mn(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 Fn(e,t,n,r,i,a){let o=await H(e,t);if(o!==null&&Mn(o.status))return!1;let s=o?.startedAt??a;return await mn(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 In(e,t){return[e.on(h.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await E(t,()=>Nn(t,n.payload))&&await q(e,r)})}),e.on(h.execution.completed,async n=>{let{executionId:r}=n.payload;await K(`execution.completed[${r}]`,async()=>{await E(t,()=>Pn(t,n.payload))&&await q(e,r)})}),e.on(h.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await K(`execution.failed[${r}]`,async()=>{await E(t,()=>Fn(t,r,`failed`,i,a??null,o))&&await q(e,r)})}),e.on(h.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await K(`execution.cancelled[${r}]`,async()=>{await E(t,()=>Fn(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const Ln=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function Rn(e){return Ln.has(e)}function zn(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function Bn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await U(t,r);c!==null&&Rn(c.status)||(await vn(t,{frameId:r,executionId:n,...zn(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await On(t,n),await q(e,n))}async function Vn(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await U(t,r);l!==null&&Rn(l.status)||(await vn(t,{frameId:r,executionId:n,...zn(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function Hn(e,t){return[e.on(h.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await K(`frame.started[${i}]`,async()=>{await _n(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await q(e,r)})}),e.on(h.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await K(`frame.completed[${i}]`,()=>Bn(e,t,r,i,a,o,s))}),e.on(h.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await K(`frame.failed[${i}]`,()=>Vn(e,t,r,i,a,o,s,c))})]}const Un={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function Wn(e,t){return[e.on(h.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await K(`gate.suspended[${i}]`,async()=>{await W(t,{id:G(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await q(e,r)})}),e.on(h.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await K(`gate.resumed[${i}]`,async()=>{let n=G(r,a,i),s=await Sn(t,n),c=Date.now();await W(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await q(e,r)})}),e.on(h.gate.resolved,async n=>Gn(n.payload,e,t)),e.on(h.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await K(`artifact.updated[${r}:${i}]`,async()=>{let n=await An(e,t,i,a,o);if(n===null)return;let s=Date.now();await bn(t,{id:xn(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await q(e,r)})})]}async function Gn(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await K(`gate.resolved[${i}]`,async()=>{let s=G(r,a,i),c=await Sn(n,s),l=Date.now();await W(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Un[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function Kn(e,t){let n=[...In(e,t),...Hn(e,t),...Wn(e,t),e.on(h.worklog.get,async e=>{let{executionId:n}=e.payload,r=await H(t,n);e.setResult({summary:r})}),e.on(h.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await yn(t,n);e.setResult({frame:r})}),e.on(h.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await gn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(h.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await kn(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function J(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>J(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&J(n[e],r[e]))}function qn(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 Jn(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 Yn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function Xn(e,t,n,r,i){let a=Jn(r,i);if(n.externalSettlementFingerprint!==null){Yn(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(D(j(t.id,r.executionId),M(t.externalSettlementFingerprint),j(t.status,r.status),j(t.completedAt,i),o===null?M(t.error):j(t.error,o),s===null?M(t.reason):j(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(j(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(Y(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Yn(c.externalSettlementFingerprint,a,r.executionId)}function Zn(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function Y(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 Qn(e,t,n){let r=await e.select().from(t).where(j(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(j(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function $n(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 er(e,t){return qn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function tr(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&J(e.inputs,t.inputs)&&J(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function nr(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 rr(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function ir(e,t,n,r){if(!t.id.startsWith(y))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}=T(e,F),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 w(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(j(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);tr(n,s)}let[l]=await e.select().from(a).where(j(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):nr(l,c),n!==void 0){let[i]=await e.select().from(o).where(j(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(qn(n))}else rr(i,n)}})}async function ar(e,t,n,r,i){if(r.frame!==void 0){let n=await Qn(e,t,r);return n!==void 0&&Zn(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(j(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=ct.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 or(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await Cn(e,a,n.id),c=await ar(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=er(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await wn(e,o,n.id),d=Tn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...$n(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:hn(p)}),d&&await En(e,a,n.id,u)}async function sr(e,t){if(!t.executionId.startsWith(y))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}=T(e,F);return w(e,async e=>{let[a]=await e.select().from(n).where(j(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=Jn(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(D(j(n.id,t.executionId),j(n.status,`running`),M(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(j(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),Y(r,t,o),await Xn(e,n,r,t,o)}}else Y(a,t,o),await Xn(e,n,a,t,o);return await or(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function cr(e,t,n){let r=e.on(a.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await ir(t,i,a,n),await q(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(a.settleExternalExecution,async n=>{let r=await sr(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function X(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function lr(e,t){return e.state===`claimed`&&e.executionId===t.executionId&&e.workflowId===t.workflowId&&e.finalizerId===t.finalizerId&&e.transitionKey===t.transitionKey&&e.claimToken===t.claimToken&&e.intent.status===t.intent.status&&e.intent.completedAt===t.intent.completedAt&&e.intent.error===t.intent.error&&e.intent.reason===t.intent.reason}function ur(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 dr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=T(e,F);return w(e,async e=>{let i=await e.select().from(r).where(j(r.executionId,t.executionId)).limit(1);return i[0]?lr(i[0],t):(await e.update(n).set({status:`finalizing`}).where(D(j(n.id,t.executionId),j(n.workflowId,t.workflowId),j(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function fr(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 pr(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=T(e,F);return w(e,async e=>{let o=(await e.select().from(a).where(j(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(fr(o.intent)).where(D(j(i.id,t),j(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(D(j(a.executionId,t),j(a.claimToken,n),j(a.state,`claimed`))),!0)})}async function mr(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=T(e,F);return w(e,async e=>{let s=(await e.select().from(o).where(j(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(D(j(a.id,t),j(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(D(j(o.executionId,t),j(o.claimToken,n),j(o.state,`claimed`))),!0)})}async function hr(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=T(t,F),a=(await t.select().from(i).where(j(i.executionId,n.executionId)).limit(1))[0];if(!a||(ur(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(j(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(h.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(h.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(h.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await E(t,()=>t.update(i).set({publishedAt:Date.now()}).where(D(j(i.executionId,a.executionId),M(i.publishedAt))))}}function gr(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>hr(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function _r(e,t){let n=gr(e,t),r=e.on(a.claimFinalization,async e=>{e.setResult({claimed:await dr(t,e.payload.claim)})}),i=e.on(a.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(j(n.finalizerId,e.payload.finalizerId),j(n.state,`claimed`)));e.setResult({claims:r.map(X)})}),o=e.on(a.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(Et(j(n.state,`acknowledged`),j(n.state,`failed`)),j(n.finalizerId,e.payload.finalizerId),M(n.publishedAt)));e.setResult({claims:r.map(X)})}),s=e.on(a.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),c=e.on(a.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await pr(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=T(t,F),c=await t.select().from(s).where(j(s.executionId,r)).limit(1);c[0]&&await n(X(c[0]))}),l=e.on(a.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await mr(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=T(t,F),l=await t.select().from(c).where(j(c.executionId,r)).limit(1);l[0]&&await n(X(l[0]))});return()=>{r(),i(),o(),s(),c(),l()}}function vr(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:L(e)}}function Z(e){let t=I(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 yr(e,t,n,r,i,a){let o=[...e?[j(a.workflowId,e)]:[],...n?[j(a.status,n)]:[],...i===void 0?[]:[j(a.artifactKind,i.kind),j(a.artifactId,i.id)]];if(t&&o.push(...Ut(a,t)),r){let e=Et(Ct(a.startedAt,r.startedAt),D(j(a.startedAt,r.startedAt),Ct(a.id,r.id)));e&&o.push(e)}return o}async function br(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}=T(e,F),u=Z(t);await w(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(j(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await on(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=V(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 xr(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}=T(e,F),a=Z(t),o=B(n);await w(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 Sr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=T(e,F);return w(e,async e=>{if((await e.select().from(i).where(j(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(D(j(a.executionId,t),j(a.status,`waiting`)))).map(e=>({...z(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(j(i.id,t));for(let t of o){let n=B(t);await e.update(a).set(n).where(j(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Cr(e,t,n,r,i,a){let{workflowExecutions:o}=T(e,F);return w(e,async e=>{if((await e.select({id:o.id}).from(o).where(j(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(j(o.id,t)),!0})}function wr(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(a.getExecution,async e=>{let{executionId:r}=e.payload;if(!g(e,r))throw Error(`Unauthorized execution read: ${r}`);let i=await t.select().from(n).where(j(n.id,r));e.setResult({execution:i[0]?vr(i[0]):null})}),i=e.on(a.setExecution,async e=>{let r=e.payload.execution,i=Z(r);await E(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),o=e.on(a.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await br(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(a.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await xr(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(a.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Cr(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(a.pauseRunningExecution,async e=>{let{workflowExecutions:n}=T(t,F),r=await E(t,()=>t.update(n).set({status:`paused`}).where(D(j(n.id,e.payload.executionId),j(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),u=e.on(a.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await Sr(t,n,r,i))});return()=>{r(),i(),o(),s(),c(),l(),u()}}function Tr(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(a.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=yr(r,i,a,s,c,n),u=o??Ye;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(D(...l)).orderBy(A(n.startedAt),A(n.id)).limit(u);e.setResult({executions:d.map(vr)})}),i=e.on(a.listExecutionsByArtifactRefs,async e=>{let r=Xe.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(D(j(n.artifactKind,e.kind),j(n.artifactId,e.id))).orderBy(A(n.startedAt),A(n.id)).limit(a);r.length>0&&(o[mt(e)]=r.map(vr))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function Er(e,t){let n=Gt(e,t),r=wr(e,t),i=Tr(e,t),a=Jt(e,t),o=Zt(e,t),s=en(e,t),c=sn(e,t),l=dn(e,t),u=Kn(e,t),d=cr(e,t,Z),f=_r(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function Dr(e){return e.startsWith(y)}function Or(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function kr(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}async function Ar(e,t){let{runContext:n}=await e.request(a.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(a.get,{id:n.workflowId});return r??void 0}function jr(e){return[e.on(h.getDefinition,async t=>{let n=await e.request(a.get,{id:t.payload.id});t.setResult(n)}),e.on(h.setDefinition,async t=>{let n=await e.request(a.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(h.deleteDefinition,async t=>{let n=await e.request(a.delete,{id:t.payload.id});t.setResult(n)}),e.on(h.listDefinitions,async t=>{let n=await e.request(a.list,t.payload);t.setResult(n)}),e.on(h.getExecution,async t=>{let n=await e.request(a.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listExecutions,async t=>{let n=await e.request(a.listExecutions,t.payload);t.setResult(n)}),e.on(h.listExecutionsByArtifactRefs,async t=>{let n=await e.request(a.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(h.listSpans,async t=>{let n=await e.request(a.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listFrames,async t=>{let n=await e.request(a.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listGateInstances,async t=>{let n=await e.request(a.listGateInstances,t.payload);t.setResult(n)}),e.on(h.setExecutionLink,async t=>{let n=await e.request(a.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(h.listExecutionLinks,async t=>{let n=await e.request(a.listExecutionLinks,t.payload);t.setResult(n)}),e.on(h.getRunContext,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(a.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...Mr(e)]}function Mr(e){return[e.on(h.registerExternalExecution,async t=>{let n=ce.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:o}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let s=n.executionId??p(`wfx-ext`);if(!Dr(s))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let c=n.startedAt??Date.now(),l={id:s,workflowId:r,status:`running`,inputs:o===void 0?{}:o,startedAt:c,scope:i??{type:`global`},...Or(n)},u=Nr(s,c,n.frame),d=await e.request(a.setExternalExecutionStart,{execution:l,...u===void 0?{}:{frame:u}});t.setResult(d)}),e.on(h.completeExternalExecution,async t=>{let n=ce.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!g(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!Dr(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let o=Pr(n),s=await e.request(a.settleExternalExecution,{executionId:r,status:i,...kr(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...o===void 0?{}:{frame:o}});t.setResult({success:s.success})})]}function Nr(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 Pr(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 Fr(e){return[e.on(h.state.get,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(a.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(h.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:s}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let c=await Ar(e,n);c!==void 0&&o(c,s,`next`),Ze.array().parse(i);let l=await e.request(a.patchState,{executionId:n,expectedSequence:r,nextValue:s});e.emit(h.state.updated,{executionId:l.executionId,sequence:l.sequence,patch:l.patch,value:l.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:l.executionId,sequence:l.sequence,value:l.value})})]}async function Ir(e,t){let{runContext:n}=await e.bus.request(a.getRunContext,{executionId:t});if(n===null)throw new S(it.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function Lr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function Rr(e,t){let n=await Ir(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.scopeOverride??n.scope,c={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,scopeOverride:s,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:Lr(t.mode,t.reason)}]};return t.mode===`snapshot`?await Hr(e,n,c):Br(n)?await Ur(e,n,c):await he(e,n.workflowId,c)}function zr(e,t){return Br(e)?t.id:e.workflowId}function Br(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function Vr(e){let t=e.definitionSnapshot;if(t===void 0)throw new S(it.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Hr(e,t,n){let r=Vr(t);return Ee(e,zr(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}async function Ur(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`){let{materializationSpec:r}=t;if(r===void 0)throw Error(`Invalid persisted path-backed run context: materializationSpec is required`);return Me(e,t.source.path,{...n,materializationSpec:r})}let r=Vr(t);return Ee(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}var Wr=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(a.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(a.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function Gr(e){if(e!==void 0)return Kr(e)?e:{}}function Kr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qr(e){if(e!==void 0)return Qe.parse(e)}function Jr(e,t){return ot.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}function Yr(e){return e?.status===`paused`}function Xr(e){return e?.status===`waiting`}async function Zr(e,t,n,r,i,o,s){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(a.restorePausedGateResumeState,{execution:i,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function Qr(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(a.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function $r(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function ei(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(a.getGateInstance,t);return Xr(n)?n:null}let{gates:n}=await e.request(a.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}async function ti(e,t){let n=e.authority.canonicalizeOutcome(t.outcome),r=t.runtimeFence===void 0?void 0:{...t.runtimeFence};await e.validation?.validate(t.executionId,n.outcome);let i=await e.authority.commitOutcome(t.executionAttemptId,t.executionId,n,r);return(i.kind===`accepted`||i.kind===`duplicate`)&&(await e.convergence.converge({executionId:t.executionId,executionAttemptId:t.executionAttemptId,outcome:i.outcome,decision:i.kind}),e.authority.settleOutcome(t.executionAttemptId,{kind:i.kind,outcome:e.authority.decodeOutcome(i.text),text:i.text})),i.kind}function ni(e,t){let r=n(e);if(r===null)throw Error(`Attempt requests require an authenticated workflow-execution-attempt peer`);if(r.executionAttemptId!==t)throw Error(`Request executionAttemptId does not match authenticated peer identity`);return r}function ri(e,t){if(e===null||e.runtimeGeneration!==t.runtimeGeneration)return!1;if(t.outcome.kind===`cancelled`&&t.operationId===void 0)return e.activeOperationId===null;let n=t.outcome.kind===`technical-failure`?t.outcome.stage:t.outcome.kind===`cancelled`?e.activeOperationKind:`workload-invocation`;return n===`startup`?t.operationId===void 0&&e.activeOperationId===null:!(e.activeOperationId!==t.operationId||e.activeOperationGeneration!==t.runtimeGeneration||e.activeOperationKind!==n||n!==`workspace-preparation`&&n!==`workload-invocation`)}function ii(e,t){return e.on(x.instruction.get,async e=>{let n=b[`instruction.get`].request.parse(e.payload),r=ni(e,n.executionAttemptId),i=await t.getInstruction(r);if(i===null){e.setResult({decision:`refused`,refusalReason:`not-found`});return}if((await t.getAttemptControlState(r.executionAttemptId))?.runtimeGeneration!==n.runtimeGeneration){e.setResult({decision:`refused`,refusalReason:`stale-generation`});return}e.setResult({decision:`found`,instruction:i})})}function ai(e,t){let n=[ii(e,t.authority),e.on(x.operation.report,async e=>{let n=b[`operation.report`].request.parse(e.payload),r=ni(e,n.executionAttemptId),i=await t.authority.reportOperation({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind,binding:i.binding}):e.setResult({decision:`refused`,refusalReason:i.kind})}),e.on(x.outcome.submit,async e=>{let n=b[`outcome.submit`].request.parse(e.payload),r=ni(e,n.executionAttemptId),i=await t.authority.getInstruction(r);if(i===null)throw Error(`No instruction belongs to this authenticated Attempt`);if(!ri(await t.authority.getAttemptControlState(r.executionAttemptId),n)){e.setResult({decision:`fenced`});return}let a={runtimeGeneration:n.runtimeGeneration,operationId:n.operationId??null},o=await t.decodeOutcome({instruction:i,outcome:n.outcome});try{let n=await ti(t,{...r,outcome:o,runtimeFence:a});e.setResult({decision:n})}catch(t){if(!(t instanceof He))throw t;e.setResult({decision:`fenced`})}})];return()=>{for(let e of n)e()}}function oi(e,t){return e.origin.local?{executionAttemptId:t.executionAttemptId,executionId:t.executionId}:n(e)}async function si(e,t,n){if(n.pausedAtGateId===void 0||n.pausedAtFrameId===void 0)throw Error(`Paused outcome for '${t}' is missing gate identity`);let{paused:r}=await e.request(a.pauseRunningExecution,{executionId:t});if(!r){let{execution:n}=await e.request(a.getExecution,{executionId:t});if(n?.status!==`paused`)throw Error(`Failed to park execution '${t}': status is '${n?.status??`missing`}'`);return}await e.emit(h.execution.paused,{executionId:t,workflowId:n.workflowId,pausedAtGateId:n.pausedAtGateId,pausedAtFrameId:n.pausedAtFrameId})}var ci=class{bus;acceptTerminalResult;acceptTechnicalFailure;acceptCancellation;constructor(e,t,n,r){this.bus=e,this.acceptTerminalResult=t,this.acceptTechnicalFailure=n,this.acceptCancellation=r}async converge(e){if(`kind`in e.outcome){if(e.outcome.kind===`cancelled`){let t=await this.acceptCancellation(e.executionId,e.outcome);if(!t.accepted||t.status!==`cancelled`)throw Error(`Cancellation did not converge workflow execution '${e.executionId}'`);return}let t=await this.acceptTechnicalFailure(e.executionId,e.outcome);if(!t.accepted||t.status!==`failed`&&t.status!==`cancelled`)throw Error(`Technical failure did not converge workflow execution '${e.executionId}'`);return}if(e.outcome.status===`paused`){await si(this.bus,e.executionId,e.outcome);return}let t=await this.acceptTerminalResult(e.executionId,e.outcome);if(!t.accepted||!u(t.status,e.outcome.status))throw Error(`Workflow result did not converge execution '${e.executionId}'`)}};function li(e,t){return{authority:t.authority,decodeOutcome:Ve,convergence:new ci(e,t.acceptTerminalResult,t.acceptTechnicalFailure,t.acceptCancellation)}}function ui(e,t){let n=li(e,t),r=ai(e,n),i=e.on(nt.control.outcome.submit,async e=>{let r=oi(e,e.payload);if(r===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:i}=e.payload;if(!e.origin.local){if(e.payload.executionId!==r.executionId)throw Error(`Outcome payload executionId '${e.payload.executionId}' does not match authenticated peer claim '${r.executionId}'`);if(e.payload.executionAttemptId!==r.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${e.payload.executionAttemptId}' does not match authenticated peer identity '${r.executionAttemptId}'`)}if(i.executionId!==r.executionId)throw Error(`Nested result.executionId '${i.executionId}' does not match trusted identity '${r.executionId}'`);let a=st.parse(i),o=await t.authority.getInstruction(r);if(o===null)throw Error(`No instruction belongs to this workflow Attempt`);let s=await n.decodeOutcome({instruction:o,outcome:{kind:`workload-result`,result:a}}),c=await ti(n,{executionId:r.executionId,executionAttemptId:r.executionAttemptId,outcome:s});e.setResult({decision:di(c)})});return()=>{i(),r()}}function di(e){return e}function fi(e,t){return e.on(x.operation.admit,async e=>{let r=n(e);if(r===null)throw Error(`Operation admission requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i,operationKind:a,admissionKey:o,runtimeGeneration:s}=b[`operation.admit`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Admission payload executionAttemptId '${i}' does not match authenticated peer identity '${r.executionAttemptId}'`);if(a===`runtime-probe`)throw Error(`Operation admission does not accept 'runtime-probe' (executionAttemptId='${i}'): the bounded probe is admitted only by runtime registration`);let c=await t.authority.admitOperation({executionAttemptId:i,executionId:r.executionId,operationKind:a,admissionKey:o,runtimeGeneration:s});if(c.kind===`admitted`||c.kind===`duplicate`){await t.bus.emit(x.operation.admitted,{executionAttemptId:i,operationId:c.operationId,operationKind:a,runtimeGeneration:c.runtimeGeneration,admittedAt:c.admittedAt}),e.setResult({decision:c.kind,operationId:c.operationId});return}e.setResult({decision:`refused`,refusalReason:c.kind})})}const pi=1e4;function mi(e,t){let r=t.probeDeliveryTimeoutMs??1e4;return e.on(x.runtime.register,async e=>{let i=n(e);if(i===null)throw Error(`Runtime registration requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:a,runtimeIncarnationId:o}=b[`runtime.register`].request.parse(e.payload);if(a!==i.executionAttemptId)throw Error(`Registration payload executionAttemptId '${a}' does not match authenticated peer identity '${i.executionAttemptId}'`);let s=await t.authority.registerRuntime({executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o});if(s.kind===`duplicate`&&s.runtimeReadyAt!==null){await hi(t,a,s.runtimeGeneration),e.setResult({decision:`duplicate`,runtimeGeneration:s.runtimeGeneration});return}if(s.kind!==`registered`&&s.kind!==`duplicate`){e.setResult(vi(s.kind));return}let c=s.runtimeGeneration;if(await gi(t,r,{executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o,runtimeGeneration:c})===null){e.setResult(vi(`probe-failed`));return}await hi(t,a,c),e.setResult({decision:`ready`,runtimeGeneration:c})})}async function hi(e,t,n){let r=await e.authority.getAttemptControlState(t);r===null||r.runtimeGeneration!==n||r.runtimeReadyAt===null||await e.bus.emit(x.runtime.ready,{executionAttemptId:t,runtimeGeneration:n,acceptedAt:r.runtimeReadyAt})}async function gi(e,t,n){let{executionAttemptId:r,executionId:i,runtimeIncarnationId:a,runtimeGeneration:o}=n,s=await e.authority.admitOperation({executionAttemptId:r,executionId:i,operationKind:`runtime-probe`,admissionKey:`probe:${a}`,runtimeGeneration:o});if(s.kind!==`admitted`&&s.kind!==`duplicate`)return null;let c=s.operationId,l=()=>_i(e,{executionAttemptId:r,operationId:c,runtimeGeneration:o}),u;try{u=(await e.bus.request(x.operation.deliver,{executionAttemptId:r,runtimeIncarnationId:a,operationId:c,operationKind:`runtime-probe`,runtimeGeneration:o},{timeout:t})).receipt}catch{return await l(),null}if(u!==`completed`&&u!==`duplicate`)return await l(),null;let d=await e.authority.completeOperation({executionAttemptId:r,operationId:c,runtimeGeneration:o});if(d.kind!==`completed`&&d.kind!==`duplicate`)return null;let f=await e.authority.markRuntimeReady({executionAttemptId:r,executionId:i,runtimeGeneration:o,readyAt:new Date().toISOString()});return f.kind!==`ready`&&f.kind!==`duplicate`?null:{kind:f.kind,acceptedAt:f.acceptedAt}}async function _i(e,t){try{await e.authority.completeOperation(t)}catch{}}function vi(e){return{decision:`refused`,runtimeGeneration:0,refusalReason:e}}function yi(e,t,n){n(mi(e,{bus:e,authority:t})),n(fi(e,{bus:e,authority:t}))}function bi(e,t){let r=new AbortController,i=e.on(x.bootstrap.awaitStart,async e=>{let i=n(e);if(i===null)throw Error(`Bootstrap start requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:a}=b[`bootstrap.awaitStart`].request.parse(e.payload);if(a!==i.executionAttemptId)throw Error(`Bootstrap start executionAttemptId does not match authenticated peer identity`);let o=e.signal?AbortSignal.any([e.signal,r.signal]):r.signal;e.setResult(await t.awaitBootstrapStart({executionAttemptId:a,executionId:i.executionId},{signal:o,deadline:e.deadline??Date.now()+31e3}))});return()=>{r.signal.aborted||(r.abort(Error(`Bootstrap start handler shut down`)),i())}}function xi(e){return e.on(h.finalizeDelegateResult,async t=>{let n=t.payload;Si(t,n.executionId);let{execution:r}=await e.request(a.getExecution,{executionId:n.executionId});if(r===null||r.workflowId!==n.workflowId)throw Error(`delegate result finalization execution does not own the requested workflow`);let{runContext:i}=await e.request(a.getRunContext,{executionId:n.executionId});if(i===null||i.executionId!==n.executionId||i.workflowId!==n.workflowId)throw Error(`delegate result finalization run context does not own the requested workflow execution`);if(i.definitionSnapshot===void 0)throw Error(`delegate result finalization requires an Authority-owned definition snapshot`);Ci(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:o}=ut(n.finalizerId),s=await e.request(o.finalize,{executionId:n.executionId,workflowId:n.workflowId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,rawResult:n.rawResult,toolObservations:n.toolObservations,...n.economics===void 0?{}:{economics:n.economics}});t.setResult(s)})}function Si(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function Ci(e,t,n,r){let i=!1;if(ht(e.root,{enter(e){if(!(e.type!==`delegate-agent`&&e.type!==`delegate-role`||e.id!==t||e.type!==n))return e.resultFinalizerId===r&&(i=!0),!1}}),!i)throw Error(`delegate result finalizer is not selected by the requested durable delegate node`)}async function wi(e,n,r){let[{execution:i},{runContext:o}]=await Promise.all([e.bus.request(a.getExecution,{executionId:n}),e.bus.request(a.getRunContext,{executionId:n})]);if(!i)throw Error(`Authority execution not found: ${n}`);if(o?.executionId!==n||o.workflowId!==i.workflowId)throw Error(`authority technical failure run context identity mismatch`);if(o.terminalAuthority!==`authority`)throw Error(`authority technical failure requires terminalAuthority=authority`);if(i.status===`failed`||i.status===`cancelled`)return{accepted:!0,status:i.status};if(i.status!==`running`)throw Error(`Authority technical failure conflicts with execution status: ${i.status}`);await t(e,i,n,`${r.stage}: ${r.message}`);let s=await e.bus.request(a.getExecution,{executionId:n});if(s.execution?.status!==`failed`&&s.execution?.status!==`cancelled`)throw Error(`Authority technical failure did not settle as failed or cancelled`);return{accepted:!0,status:s.execution.status}}async function Ti(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(a.getExecution,{executionId:t}),e.bus.request(a.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority cancellation run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority cancellation requires terminalAuthority=authority`);if(r.status===`cancelled`)return{accepted:!0,status:`cancelled`};if(r.status!==`running`)throw Error(`Authority cancellation conflicts with execution status: ${r.status}`);if(await m(e,t,n.reason),(await e.bus.request(a.getExecution,{executionId:t})).execution?.status!==`cancelled`)throw Error(`Authority cancellation did not settle as cancelled`);return{accepted:!0,status:`cancelled`}}var Ei=class extends gt{workflowRunner;executionAttemptAuthority;static storage={drizzle:Er};config;stopBootstrapWaits;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;materializationSpecResolvers=new Set;constructor(e,t,n,r){super(e),this.workflowRunner=n,this.executionAttemptAuthority=r,this.config={...l,...t},this.gateTimeoutScheduler=new Wr(e,e=>this.resumePausedExecution(e))}registerWorkflowMaterializationSpecResolver(e){return this.materializationSpecResolvers.add(e),()=>this.materializationSpecResolvers.delete(e)}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=dt(e);this.bus.registerNamespace(t);let r={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,r);try{await d(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(a.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:o,workflow:s}=await this.loadAuthorityRunnerContext(e,t.workflowId),c=await this.registerAuthorityResultFinalizer(s),l=this.activeExecutions.get(e),d=!1;if(!l)this.activeExecutions.set(e,{execution:n,workflow:s,runContext:o,runtimeHandlers:new Map,runtimeLoopGates:new Map}),d=!0;else if(l.execution.workflowId!==t.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await f({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},t)}finally{d&&this.activeExecutions.delete(e),c?.()}let p=await this.bus.request(a.getExecution,{executionId:e});if(!p.execution||!u(p.execution.status,t.status))throw Error(`Authority runner result did not settle compatibly with ${t.status}`);return{accepted:!0,status:p.execution.status}}acceptAuthorityTechnicalFailure=(e,t)=>wi(this.buildFinalizerDeps(),e,t);acceptAuthorityCancellation=(e,t)=>Ti(this.buildFinalizerDeps(),e,t);async resolveAuthorityRunnerReplay(e,t){if(e.status===`finalizing`){if(t.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await d(this.buildFinalizerDeps());let n=await this.bus.request(a.getExecution,{executionId:e.id});if(!n.execution)throw Error(`Authority runner success finalization execution is missing`);if(!u(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(!u(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(a.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(a.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(Oe(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)})),this.addCleanup(xi(this.bus)),this.executionAttemptAuthority!==void 0&&(this.stopBootstrapWaits=bi(this.bus,this.executionAttemptAuthority),this.addCleanup(this.stopBootstrapWaits),this.addCleanup(ui(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t),acceptTechnicalFailure:this.acceptAuthorityTechnicalFailure,acceptCancellation:this.acceptAuthorityCancellation})),yi(this.bus,this.executionAttemptAuthority,e=>this.addCleanup(e))),jr(this.bus).forEach(e=>this.addCleanup(e)),Fr(this.bus).forEach(e=>this.addCleanup(e)),await this.rehydratePausedGateTimeouts()}async onDestroy(){this.stopBootstrapWaits?.();let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await m(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(),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request($e.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}resolveEphemeralPlatformFields(){return ze(this.config.platformDefaults.cwd,this.config.makaioHome)}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Jr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e),executionAttemptAuthority:this.executionAttemptAuthority,materializationSpecResolvers:this.materializationSpecResolvers}}registerExecutionHandlers(){this.registerHandler(h.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(h.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s}=e.payload;try{let c=await he(this.buildStartDeps(),t,{input:qr(n),config:Gr(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,scopeOverride:s});e.setResult({executionId:c})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(h.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,reason:l}=e.payload;try{let u=await Rr(this.buildStartDeps(),{executionId:t,mode:n,input:qr(r),config:Gr(i),parentSessionId:a,triggerPayload:o,artifactRef:s,scopeOverride:c,reason:l});e.setResult({executionId:u})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(h.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,materializationSpec:n,triggerPayload:r,triggerMode:i,scope:a}=e.payload;try{let o=await Me(this.buildStartDeps(),t,{...n===void 0?{}:{materializationSpec:n},triggerPayload:r,triggerMode:i,scopeOverride:a});e.setResult({executionId:o})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(h.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(lt(`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??et);let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(h.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(h.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(h.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(a.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule($r(t))}async runExecution(e){let n=this.activeExecutions.get(e);if(!n)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let t=await de({definition:n.workflow,execution:n.execution,runContext:n.runContext,bus:this.bus}),a=new we(e,n.workflow.id,n.workflow,n.execution,n.runtimeHandlers,this.bus,r.signal,void 0,t,{context:this.resolveEphemeralPlatformFields(),env:n.runContext.env},{runtimeLoopGates:n.runtimeLoopGates});Fe(n.workflow,n.runtimeLoopGates);let o=a.buildExpressionContext();i=await xe(n.workflow.root,a,o)}catch(i){if(r.signal.aborted||n.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,et);return}let a=i instanceof Error?i.message:String(i);await t(this.buildFinalizerDeps(),n.execution,e,a);return}let o=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||n.execution.status===`cancelled`?await m(o,e,et):i.status===`failed`?await t(o,n.execution,e,i.error):i.status===`paused`?(n.execution.status=`paused`,await this.bus.request(a.setExecution,{execution:n.execution}),this.activeExecutions.delete(e)):await Ce(o,n.execution,e,n.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:n,frameId:r,resumeData:i,reason:o}=e,{execution:s}=await this.bus.request(a.getExecution,{executionId:t});if(!Yr(s))return!1;let c=await ei(this.bus,{executionId:t,nodeId:n,frameId:r});if(c===null||!Ae(n,c.schema,i).valid)return!1;let{runContext:l}=await this.bus.request(a.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Qr(this.bus,l);let{accepted:u}=await this.bus.request(a.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:i,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Zr(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,n),e}return this.gateTimeoutScheduler.clear(t,n,c.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(a.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(a.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(a.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await Qr(this.bus,t);let o=r(t,n,{resume:!0}),s=_e(this.buildStartDeps(),o);await this.bus.request(a.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let c=ye(this.buildStartDeps(),o,s).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,c),!0}};const Q=`[WorkflowTriggerReconciler]`;function Di(e){return e.map(Oi)}function Oi(e){let t=rt.parse(e);return{binding:t,matches:We(t),subscription:void 0}}function ki(e,t,n){let r=e.triggers??[];try{return n===void 0?Di(r):r.map(e=>n.has(e.kind)?Oi(e):void 0)}catch(i){if(t){console.error(`${Q} keeping last-good triggers for workflow "${e.id}": its trigger bindings are invalid`,i);return}return r.map((t,r)=>{if(!(n!==void 0&&!n.has(t.kind)))try{return Oi(t)}catch(t){console.error(`${Q} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function Ai(e,t){return e.scope.type!==`global`||t.kind!==Je}async function ji(e,t,n,r){if(r!==void 0)for(let[i,a]of Array.from(r)){let o=e.triggers?.[i];if(o!==void 0&&n!==void 0&&!n.has(o.kind))continue;let s=t[i];s!==void 0&&Ai(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Q} detach failed for '${e.bindingKey}':`,t)}}var Mi=class{bus;resolveRuntime;consumers=new Map;cleanupFns=[];initialized=!1;initialization;lane=new Ge;pendingChanges=[];constructor(e,t){this.bus=e,this.resolveRuntime=t}async init(){if(this.initialized)return;if(this.initialization!==void 0)return this.initialization;let e=this.initialize();return this.initialization=e,e.then(()=>this.clearInitialization(e),()=>this.clearInitialization(e)),e}clearInitialization(e){this.initialization===e&&(this.initialization=void 0)}async initialize(){try{let e=({payload:e})=>{this.onSignal(`refresh of workflow "${e.id}"`,()=>this.refreshDefinition(e.id))};this.cleanupFns.push(this.bus.on(C.definition.created,e),this.bus.on(C.definition.updated,e),this.bus.on(C.definition.deleted,e),this.bus.on(qe.changed,e=>{this.scheduleRegistryReconcile(e.payload)})),await this.reconcileStored(`keep-last-good`),this.initialized=!0}catch(e){throw await this.teardown(),e}}async destroy(){await this.teardown(),this.initialized=!1}activeConsumerCount(){let e=0;for(let t of this.consumers.values())e+=t.size;return e}onSignal(e,t){t().catch(t=>{console.error(`${Q} ${e} failed:`,t)})}scheduleRegistryReconcile(e){let t=this.pendingChanges.length>0;this.pendingChanges.push(e),!t&&queueMicrotask(()=>{if(this.pendingChanges.length===0)return;let e=this.pendingChanges.splice(0),t=new Set(e.flatMap(({kinds:e})=>e)),n=e.map(({owner:e,revision:t})=>`${e}@${t}`).join(`, `);this.onSignal(`reconciliation after trigger registry changes (${n})`,()=>this.reconcileStored(`drop-unavailable`,t))})}async reconcileStored(e,t){await this.lane.run(async()=>{let{workflows:n}=await this.bus.request(a.list,{}),r=new Set(n.map(e=>e.id));for(let r of n){let n=r.triggers??[];t!==void 0&&!n.some(e=>t.has(e.kind))||await this.applyDefinitionWithinLane(r,e,t)}for(let e of Array.from(this.consumers.keys()))r.has(e)||await this.forgetWorkflowWithinLane(e)})}async refreshDefinition(e){await this.lane.run(async()=>{let{workflow:t}=await this.bus.request(a.get,{id:e});if(t===null){await this.forgetWorkflowWithinLane(e);return}await this.applyDefinitionWithinLane(t,`keep-last-good`)})}async applyDefinitionWithinLane(e,t,n){let r=ki(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await ji(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&Ai(e,t.binding)&&(n===void 0||n.has(t.binding.kind))))return;let a=this.resolveRuntime();if(a===void 0){r.length>0&&console.warn(`${Q} no automation trigger binding runtime is available; declarative triggers of workflow "${e.id}" stay inactive`);return}let o=this.consumers.get(e.id);o===void 0&&(o=new Map,this.consumers.set(e.id,o));for(let[i,s]of r.entries())s!==void 0&&Ai(e,s.binding)&&(n!==void 0&&!n.has(s.binding.kind)||await this.refreshConsumerWithinLane(a,e.id,i,s,o,t));o.size===0&&this.consumers.delete(e.id)}async refreshConsumerWithinLane(e,t,n,r,i,a){let o=i.get(n),s=this.createListener(t,n,r);try{let t=o?.subscription?.bindingKey,a=e.prepareBinding(r.binding);if(a===void 0)throw Error(`Automation trigger kind '${r.binding.kind}' is not registered`);if(!a.workflowCompatible)throw Error(`Automation trigger kind '${r.binding.kind}' does not emit an object-root payload`);(t===void 0||t!==a.bindingKey)&&i.set(n,r),r.subscription=await a.subscribe(s),i.set(n,r),await $(o?.subscription);return}catch(e){if(o===void 0?i.delete(n):i.set(n,o),a===`keep-last-good`){console.error(`${Q} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Q} dropping trigger ${n} of workflow "${t}": binding '${r.binding.kind}' is no longer available`,e),i.delete(n),await $(o?.subscription)}}async forgetWorkflowWithinLane(e){let t=this.consumers.get(e);if(t!==void 0){this.consumers.delete(e);for(let e of t.values())await $(e.subscription)}}createListener(e,t,n){let r=`trigger ${t} ('${n.binding.kind}') of workflow "${e}"`;return async i=>{if(this.consumers.get(e)?.get(t)!==n)return;let a;try{a=n.matches(i.payload)}catch(e){console.error(`${Q} filter evaluation failed for ${r}:`,e);return}if(a)try{await this.bus.request(C.start,{workflowId:e,triggerPayload:Ue(i.payload)})}catch(t){console.error(`${Q} failed to start workflow "${e}" from ${r}:`,t)}}}async teardown(){this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.pendingChanges.length=0,await this.lane.run(async()=>{for(let e of Array.from(this.consumers.keys()))await this.forgetWorkflowWithinLane(e)})}};const Ni=1e3;function Pi(e){if(e===null)return{status:`refused`,reason:`not-found`};if(e.settled)return{status:`refused`,reason:`resolved`};if(!e.active)return{status:`refused`,reason:`fenced`};if(e.allocationTerminated)return{status:`refused`,reason:`allocation-terminated`};if(e.operationStartGate===`closed`)return{status:`refused`,reason:`gate-closed`};let t=e.bootstrapDeadlineAt===null?NaN:Date.parse(e.bootstrapDeadlineAt);return!Number.isFinite(t)||t<=Date.now()?{status:`refused`,reason:`bootstrap-expired`}:{status:e.allocated?`permitted`:`pending`}}function Fi(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),t.aborted&&i(),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function Ii(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),n()},a=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),r(t.reason)},o=setTimeout(i,e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function Li(e,t){return setTimeout(()=>e.abort(Error(`Bootstrap start observation timed out`)),Math.max(0,t-Date.now()))}async function Ri(e,t,n){if(n.signal.throwIfAborted(),!Number.isFinite(n.deadline))throw Error(`Bootstrap start request requires a finite deadline`);let r=Math.min(Date.now()+3e4,n.deadline-Ni),i=new AbortController,a=AbortSignal.any([n.signal,i.signal]),o=Math.min(n.deadline,r+Ni),s=Li(i,o);try{for(;;){a.throwIfAborted();let n=await Fi(e.readBootstrapStartState(t),a);a.throwIfAborted();let c=Pi(n);if(c.status!==`pending`)return c;let l=Date.parse(n?.bootstrapDeadlineAt??``);clearTimeout(s),s=Li(i,Math.min(o,l+Ni));let u=Math.min(r,l)-Date.now();if(u<=0)return c;await Ii(Math.min(100,u),a)}}finally{clearTimeout(s)}}var zi=class{repository;bootstrapTimeoutMs;waiters=new Map;constructor(e,t){if(!Number.isSafeInteger(t?.bootstrapTimeoutMs)||t.bootstrapTimeoutMs<=0)throw Error(`ExecutionAttemptAuthority requires an explicit positive safe-integer bootstrapTimeoutMs`);this.repository=e,this.bootstrapTimeoutMs=t.bootstrapTimeoutMs}awaitBootstrapStart(e,t){return Ri(this.repository,e,t)}async createAttempt(e,t){let n=crypto.randomUUID(),r=await this.repository.createAttempt({executionAttemptId:n,executionId:e,instruction:t,bootstrapTimeoutMs:this.bootstrapTimeoutMs});return this.installWaiter(n),r}async getInstruction(e){return this.repository.getInstruction(e)}async reportOperation(e){return this.repository.reportOperation(e)}async beginProvisioning(e){return this.repository.beginProvisioning(e)}async getProviderOperation(e){return this.repository.getProviderOperation(e)}async renewProviderOperationClaim(e){return this.repository.renewProviderOperationClaim(e)}async takeOverProviderOperation(e){return this.repository.takeOverProviderOperation(e)}async handoffProviderOperation(e){return this.repository.handoffProviderOperation(e)}async recordProviderOperationUncertainty(e){return this.repository.recordProviderOperationUncertainty(e)}async recordAllocation(e){return this.repository.recordAllocation(e)}async recordProvisioningAbsent(e){let t=await this.repository.recordProvisioningAbsent(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' provisioning produced no allocation: ${e.evidence.source} reported '${e.evidence.summary}'`)),t}async recordProvisionerIncarnationLost(e){let t=await this.repository.recordProvisionerIncarnationLost(e);if(t.kind===`recorded`){let{evidence:t,provisionerIncarnationId:n}=e.proof;this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' lost the provisioner incarnation '${n}' its allocation was bound to: ${t.source} reported '${t.summary}'`))}return t}async recordAllocationTerminated(e){return this.repository.recordAllocationTerminated(e)}async registerRuntime(e){return this.repository.registerRuntime(e)}async admitOperation(e){return this.repository.admitOperation(e)}async completeOperation(e){return this.repository.completeOperation(e)}async markRuntimeReady(e){return this.repository.markRuntimeReady(e)}async getAttemptControlState(e){return this.repository.getAttemptControlState(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}canonicalizeOutcome(e){return this.repository.canonicalizeOutcome(e)}decodeOutcome(e){return this.repository.decodeOutcome(e)}async commitOutcome(e,t,n,r){let i=await this.repository.commitOutcome({executionAttemptId:e,executionId:t,result:n,...r===void 0?{}:{runtimeFence:r}});return(i.kind===`conflict`||i.kind===`fenced`)&&this.settleWaiterInternal(e,i),i}waitForOutcome(e){return this.waiters.get(e)?.promise}settleOutcome(e,t){this.settleWaiterInternal(e,t)}discardWaiter(e){this.waiters.delete(e)}rejectAndDiscardWaiter(e,t){this.rejectWaiterWith(e,()=>t)}rejectWaiterWith(e,t){let n=this.waiters.get(e);n!==void 0&&(n.promise.catch(()=>void 0),n.reject(t()),this.waiters.delete(e))}get supportsRecovery(){return this.repository.recovery!==void 0}async getAttemptWithAllocation(e){return this.requireRecovery(`getAttemptWithAllocation`).getAttemptWithAllocation(e)}async recordDiscoveredAllocation(e){return this.requireRecovery(`recordDiscoveredAllocation`).recordDiscoveredAllocation(e)}async evolveAllocationRef(e){let t=this.requireRecovery(`evolveAllocationRef`);if(e.currentRef.providerId!==e.nextRef.providerId)throw Error(`Provider identity mismatch in allocation ref evolution: currentRef.providerId '${e.currentRef.providerId}' !== nextRef.providerId '${e.nextRef.providerId}'. Provider identity must not change during correlation.`);return t.evolveAllocationRef(e)}async getRecoverableAttempts(e){return this.requireRecovery(`getRecoverableAttempts`).getRecoverableAttempts(e)}async recordInfrastructureFailure(e){let t=await this.repository.recordInfrastructureFailure(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' suffered infrastructure failure: the provider allocation terminated without an acknowledged outcome`)),t}async abandonPendingAttempt(e,t){let n=await this.repository.abandonPendingAttempt(e,t);return(n.kind===`abandoned`||n.kind===`already-abandoned`)&&this.waiters.delete(e),n}requireRecovery(e){let{recovery:t}=this.repository;if(t===void 0)throw Error(`Recovery operation '${e}' requires a repository that exposes recovery operations. The injected repository does not support recovery.`);return t}installWaiter(e){this.waiters.set(e,le())}settleWaiterInternal(e,t){let n=this.waiters.get(e);if(n){switch(t.kind){case`accepted`:case`duplicate`:n.resolve(t.outcome);break;case`conflict`:n.reject(Error(`Outcome conflict for attempt '${e}': a different outcome was already committed`));break;case`fenced`:n.reject(Error(`Attempt '${e}' has been fenced: it is no longer the active attempt for this execution`));break}this.waiters.delete(e)}}},Bi=class extends gt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e);let n=t?.executionAttemptAuthority;if(!n&&t?.executionAttemptRepository){let e=t.executionAttemptBootstrapTimeoutMs;if(e===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);n=new zi(t.executionAttemptRepository,{bootstrapTimeoutMs:e})}this.attemptAuthority=n,this.workflowExecutor=new Ei(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let r=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new Mi(e,()=>r?.())}get executor(){return this.workflowExecutor}get executionAttemptAuthority(){return this.attemptAuthority}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}get triggerReconciler(){return this.triggerReconcilerInstance}registerWorkflowMaterializationSpecResolver(e){return this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e)}registerWorkspaceRootResolver(e){return this.workspaceRootResolvers.add(e),()=>{this.workspaceRootResolvers.delete(e)}}async resolveWorkspaceRoot(e){for(let t of this.workspaceRootResolvers){let n=await t(e);if(n!==void 0)return n}}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.triggerReconcilerInstance.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.triggerReconcilerInstance.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const Vi=pt(`makaio.workflow-engine`);function Hi(e){return{name:Vi.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[ft(Dt.name),ft(Ot.name,void 0,!0)],critical:!0,namespaces:[at,re],storage:{registerHandlers:yt(Er)},create:t=>new Bi(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(Ot)})}}const Ui=Hi();export{un as _,zi as a,bi as c,fi as d,ai as f,cn as g,ln as h,Bi as i,pi as l,Er as m,Hi as n,Mi as o,ti as p,Ui as r,Ei as s,Vi as t,mi as u};
|
|
7
|
+
)`;await e.update(t).set({totalInputTokens:i,totalOutputTokens:a,totalEstimatedCost:o}).where(D(j(t.executionId,r),s))}async function An(e,t){let{worklogSummaries:n,worklogFrameEntries:r}=T(e,F);if(bt(e)===`sqlite`){await kn(e,n,r,t);return}await w(e,async e=>{if(await Tn(e,n,t)===void 0)return;let i=await En(e,r,t);Dn(i)&&await On(e,n,t,i)})}async function jn(e,t={}){let{worklogSummaries:n}=T(e,F),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[j(n.workflowId,r)],...i===void 0?[]:[Ct(n.startedAt,i)],...a===void 0?[]:[Et(n.startedAt,a)]],s=o.length>0?D(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:k()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:P(n.durationMs),totalInputTokens:P(n.totalInputTokens),totalOutputTokens:P(n.totalOutputTokens),totalEstimatedCost:P(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 Mn(e,t,n,r,i){let a=await U(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(Je.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function K(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function q(e,t){try{await e.emit(h.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}const Nn=new Set([`completed`,`failed`,`cancelled`]);function Pn(e){return Nn.has(e)}async function Fn(e,t){return await hn(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 In(e,t){let n=t.completedAt??Date.now(),r=await H(e,t.executionId);return r!==null&&Pn(r.status)?!1:(await gn(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 Ln(e,t,n,r,i,a){let o=await H(e,t);if(o!==null&&Pn(o.status))return!1;let s=o?.startedAt??a;return await gn(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 Rn(e,t){return[e.on(h.execution.started,async n=>{let{executionId:r}=n.payload;await K(`execution.started[${r}]`,async()=>{await E(t,()=>Fn(t,n.payload))&&await q(e,r)})}),e.on(h.execution.completed,async n=>{let{executionId:r}=n.payload;await K(`execution.completed[${r}]`,async()=>{await E(t,()=>In(t,n.payload))&&await q(e,r)})}),e.on(h.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await K(`execution.failed[${r}]`,async()=>{await E(t,()=>Ln(t,r,`failed`,i,a??null,o))&&await q(e,r)})}),e.on(h.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await K(`execution.cancelled[${r}]`,async()=>{await E(t,()=>Ln(t,r,`cancelled`,null,null,i))&&await q(e,r)})})]}const zn=new Set([`completed`,`failed`,`skipped`,`cancelled`]);function Bn(e){return zn.has(e)}function Vn(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 Hn(e,t,n,r,i,a,o){let s=o??Date.now(),c=await U(t,r);c!==null&&Bn(c.status)||(await bn(t,{frameId:r,executionId:n,...Vn(c,i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await An(t,n),await q(e,n))}async function Un(e,t,n,r,i,a,o,s){let c=s??Date.now(),l=await U(t,r);l!==null&&Bn(l.status)||(await bn(t,{frameId:r,executionId:n,...Vn(l,i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await q(e,n))}function Wn(e,t){return[e.on(h.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await K(`frame.started[${i}]`,async()=>{await yn(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await q(e,r)})}),e.on(h.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await K(`frame.completed[${i}]`,()=>Hn(e,t,r,i,a,o,s))}),e.on(h.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await K(`frame.failed[${i}]`,()=>Un(e,t,r,i,a,o,s,c))})]}const Gn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function Kn(e,t){return[e.on(h.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await K(`gate.suspended[${i}]`,async()=>{await W(t,{id:G(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await q(e,r)})}),e.on(h.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await K(`gate.resumed[${i}]`,async()=>{let n=G(r,a,i),s=await wn(t,n),c=Date.now();await W(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await q(e,r)})}),e.on(h.gate.resolved,async n=>qn(n.payload,e,t)),e.on(h.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await K(`artifact.updated[${r}:${i}]`,async()=>{let n=await Mn(e,t,i,a,o);if(n===null)return;let s=Date.now();await Sn(t,{id:Cn(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await q(e,r)})})]}async function qn(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await K(`gate.resolved[${i}]`,async()=>{let s=G(r,a,i),c=await wn(n,s),l=Date.now();await W(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:Gn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await q(t,r)})}function Jn(e,t){let n=[...Rn(e,t),...Wn(e,t),...Kn(e,t),e.on(h.worklog.get,async e=>{let{executionId:n}=e.payload,r=await H(t,n);e.setResult({summary:r})}),e.on(h.worklog.frame.get,async e=>{let{frameId:n}=e.payload,r=await xn(t,n);e.setResult({frame:r})}),e.on(h.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await vn(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(h.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await jn(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function J(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>J(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;let n=e,r=t,i=Object.keys(n).sort(),a=Object.keys(r).sort();return i.length===a.length&&i.every((e,t)=>e===a[t]&&J(n[e],r[e]))}function Yn(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 Xn(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 Zn(e,t,n){if(e!==t)throw Error(`settleExternalExecution: execution "${n}" conflicts with an existing terminal settlement fingerprint`)}async function Qn(e,t,n,r,i){let a=Xn(r,i);if(n.externalSettlementFingerprint!==null){Zn(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(D(j(t.id,r.executionId),M(t.externalSettlementFingerprint),j(t.status,r.status),j(t.completedAt,i),o===null?M(t.error):j(t.error,o),s===null?M(t.reason):j(t.reason,s))).returning({fingerprint:t.externalSettlementFingerprint})).length>0)return;let[c]=await e.select().from(t).where(j(t.id,r.executionId)).limit(1);if(c===void 0)throw Error(`settleExternalExecution: execution "${r.executionId}" disappeared`);if(Y(c,r,i),c.externalSettlementFingerprint===null)throw Error(`settleExternalExecution: failed to adopt terminal settlement fingerprint for execution "${r.executionId}"`);Zn(c.externalSettlementFingerprint,a,r.executionId)}function $n(e,t){if(e.executionId!==t.executionId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`settleExternalExecution: frame "${t.frameId}" conflicts with its registered metadata`)}function Y(e,t,n){let r=t.status===`failed`?t.error??null:null,i=t.status===`cancelled`?t.reason??null:null;if(e.status!==t.status||e.completedAt!==n||e.error!==r||e.reason!==i)throw e.status===t.status?Error(`settleExternalExecution: execution "${t.executionId}" conflicts with an existing terminal settlement`):Error(`settleExternalExecution: execution "${t.executionId}" cannot transition from status "${e.status}"`)}async function er(e,t,n){let r=await e.select().from(t).where(j(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(j(t.frameId,n.frame.frameId)).limit(1);if(a!==void 0)throw Error(`settleExternalExecution: frame "${n.frame.frameId}" belongs to another execution`)}function tr(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 nr(e,t){return Yn({...e,inputTokens:e.inputTokens??t?.inputTokens??void 0,outputTokens:e.outputTokens??t?.outputTokens??void 0,estimatedCost:e.estimatedCost??t?.estimatedCost??void 0})}function rr(e,t){if(e.externalRegistrationFrameId!==(t.externalRegistrationFrameId??null))throw Error(`setExternalExecutionStart: frame metadata conflicts for execution "${t.id}"`);if(!(e.id===t.id&&e.workflowId===t.workflowId&&e.coordinatorSessionId===t.coordinatorSessionId&&e.startedAt===t.startedAt&&e.scopeType===t.scopeType&&e.scopeKind===t.scopeKind&&e.scopeId===t.scopeId&&e.artifactKind===t.artifactKind&&e.artifactId===t.artifactId&&J(e.inputs,t.inputs)&&J(e.triggerPayload,t.triggerPayload)))throw Error(`setExternalExecutionStart: registration conflicts for execution "${t.id}"`)}function ir(e,t){if(e.workflowId!==t.workflowId||e.startedAt!==t.startedAt||e.executionId!==t.executionId)throw Error(`setExternalExecutionStart: WorkLog summary conflicts for execution "${t.executionId}"`)}function ar(e,t){if(e.executionId!==t.executionId||e.frameId!==t.frameId||e.nodeId!==t.nodeId||e.nodeType!==t.nodeType||!J(e.path,t.path)||e.attempt!==t.attempt||e.iteration!==(t.iteration??null)||e.branchKey!==(t.branchKey??null)||e.startedAt!==t.startedAt)throw Error(`setExternalExecutionStart: WorkLog frame conflicts for frame "${t.frameId}"`)}async function or(e,t,n,r){if(!t.id.startsWith(y))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}=T(e,F),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 w(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(j(i.id,t.id)).limit(1);if(n===void 0)throw Error(`setExternalExecutionStart: execution "${t.id}" disappeared`);rr(n,s)}let[l]=await e.select().from(a).where(j(a.executionId,t.id)).limit(1);if(l===void 0?await e.insert(a).values(c):ir(l,c),n!==void 0){let[i]=await e.select().from(o).where(j(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(Yn(n))}else ar(i,n)}})}async function sr(e,t,n,r,i){if(r.frame!==void 0){let n=await er(e,t,r);return n!==void 0&&$n(n,r.frame),{frame:r.frame,existing:n}}if(n.externalRegistrationFrameId===null)return;let[a]=await e.select().from(t).where(j(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=ut.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 cr(e,t,n,r,i){let{worklogSummaries:a,worklogFrameEntries:o}=t,s=await Tn(e,a,n.id),c=await sr(e,o,n,r,i),l=c===void 0?r:{...r,frame:c.frame};if(c!==void 0){let t=nr(c.frame,c.existing);await e.insert(o).values(t).onConflictDoUpdate({target:o.frameId,set:t})}let u=await En(e,o,n.id),d=Dn(u),f={totalInputTokens:u.totalInputTokens,totalOutputTokens:u.totalOutputTokens,totalEstimatedCost:u.totalEstimatedCost},p={...tr(n,s,l,i),...d?f:{}};await e.insert(a).values(p).onConflictDoUpdate({target:a.executionId,set:_n(p)}),d&&await On(e,a,n.id,u)}async function lr(e,t){if(!t.executionId.startsWith(y))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}=T(e,F);return w(e,async e=>{let[a]=await e.select().from(n).where(j(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=Xn(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(D(j(n.id,t.executionId),j(n.status,`running`),M(n.externalSettlementFingerprint))).returning({id:n.id})).length===0){let[r]=await e.select().from(n).where(j(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),Y(r,t,o),await Qn(e,n,r,t,o)}}else Y(a,t,o),await Qn(e,n,a,t,o);return await cr(e,{worklogSummaries:r,worklogFrameEntries:i},a,t,o),!0})}function ur(e,t,n){let r=e.on(a.setExternalExecutionStart,async r=>{let i=r.payload.execution,a=r.payload.frame;await or(t,i,a,n),await q(e,i.id),r.setResult({executionId:i.id,...a===void 0?{}:{frameId:a.frameId}})}),i=e.on(a.settleExternalExecution,async n=>{let r=await lr(t,n.payload);await q(e,n.payload.executionId),n.setResult({success:r})});return()=>{r(),i()}}function X(e){return{executionId:e.executionId,workflowId:e.workflowId,finalizerId:e.finalizerId,transitionKey:e.transitionKey,claimToken:e.claimToken,intent:e.intent,claimedAt:e.claimedAt}}function dr(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 fr(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 pr(e,t){let{workflowExecutions:n,workflowFinalizations:r}=T(e,F);return w(e,async e=>{let i=await e.select().from(r).where(j(r.executionId,t.executionId)).limit(1);return i[0]?dr(i[0],t):(await e.update(n).set({status:`finalizing`}).where(D(j(n.id,t.executionId),j(n.workflowId,t.workflowId),j(n.status,`running`))).returning({id:n.id})).length===0?!1:(await e.insert(r).values({...t,state:`claimed`}),!0)})}function mr(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 hr(e,t,n,r){let{workflowExecutions:i,workflowFinalizations:a}=T(e,F);return w(e,async e=>{let o=(await e.select().from(a).where(j(a.executionId,t)).limit(1))[0];return!o||o.claimToken!==n||o.state===`failed`?!1:o.state===`acknowledged`?!0:(await e.update(i).set(mr(o.intent)).where(D(j(i.id,t),j(i.status,`finalizing`))).returning({id:i.id})).length===0?!1:(await e.update(a).set({state:`acknowledged`,settledAt:r}).where(D(j(a.executionId,t),j(a.claimToken,n),j(a.state,`claimed`))),!0)})}async function gr(e,t,n,r,i){let{workflowExecutions:a,workflowFinalizations:o}=T(e,F);return w(e,async e=>{let s=(await e.select().from(o).where(j(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(D(j(a.id,t),j(a.status,`finalizing`))).returning({id:a.id})).length===0?!1:(await e.update(o).set({state:`failed`,failure:r,settledAt:i}).where(D(j(o.executionId,t),j(o.claimToken,n),j(o.state,`claimed`))),!0)})}async function _r(e,t,n){let{workflowExecutions:r,workflowFinalizations:i}=T(t,F),a=(await t.select().from(i).where(j(i.executionId,n.executionId)).limit(1))[0];if(!a||(fr(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(j(r.id,a.executionId)).limit(1))[0];if(!(!o||o.completedAt==null)){if(o.status===`completed`)await e.emit(h.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(h.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(h.execution.cancelled,{executionId:a.executionId,workflowId:a.workflowId,reason:o.reason??void 0,completedAt:o.completedAt,transitionKey:a.transitionKey});else return;await E(t,()=>t.update(i).set({publishedAt:Date.now()}).where(D(j(i.executionId,a.executionId),M(i.publishedAt))))}}function vr(e,t){let n=new Map;return async r=>{let i=(n.get(r.executionId)??Promise.resolve()).catch(()=>void 0).then(()=>_r(e,t,r));n.set(r.executionId,i);try{await i}finally{n.get(r.executionId)===i&&n.delete(r.executionId)}}}function yr(e,t){let n=vr(e,t),r=e.on(a.claimFinalization,async e=>{e.setResult({claimed:await pr(t,e.payload.claim)})}),i=e.on(a.listClaimedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(j(n.finalizerId,e.payload.finalizerId),j(n.state,`claimed`)));e.setResult({claims:r.map(X)})}),o=e.on(a.listUnpublishedFinalizations,async e=>{let{workflowFinalizations:n}=T(t,F),r=await t.select().from(n).where(D(Ot(j(n.state,`acknowledged`),j(n.state,`failed`)),j(n.finalizerId,e.payload.finalizerId),M(n.publishedAt)));e.setResult({claims:r.map(X)})}),s=e.on(a.publishFinalization,async e=>{await n(e.payload.claim),e.setResult({})}),c=e.on(a.acknowledgeFinalization,async e=>{let{executionId:r,claimToken:i,settledAt:a}=e.payload,o=await hr(t,r,i,a);if(e.setResult({acknowledged:o}),!o)return;let{workflowFinalizations:s}=T(t,F),c=await t.select().from(s).where(j(s.executionId,r)).limit(1);c[0]&&await n(X(c[0]))}),l=e.on(a.failFinalization,async e=>{let{executionId:r,claimToken:i,error:a,settledAt:o}=e.payload,s=await gr(t,r,i,a,o);if(e.setResult({failed:s}),!s)return;let{workflowFinalizations:c}=T(t,F),l=await t.select().from(c).where(j(c.executionId,r)).limit(1);l[0]&&await n(X(l[0]))});return()=>{r(),i(),o(),s(),c(),l()}}function br(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:L(e)}}function Z(e){let t=I(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 xr(e,t,n,r,i,a){let o=[...e?[j(a.workflowId,e)]:[],...n?[j(a.status,n)]:[],...i===void 0?[]:[j(a.artifactKind,i.kind),j(a.artifactId,i.id)]];if(t&&o.push(...Gt(a,t)),r){let e=Ot(Tt(a.startedAt,r.startedAt),D(j(a.startedAt,r.startedAt),Tt(a.id,r.id)));e&&o.push(e)}return o}async function Sr(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}=T(e,F),u=Z(t);await w(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(j(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await cn(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=V(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 Cr(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}=T(e,F),a=Z(t),o=B(n);await w(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 wr(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=T(e,F);return w(e,async e=>{if((await e.select().from(i).where(j(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(D(j(a.executionId,t),j(a.status,`waiting`)))).map(e=>({...z(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(j(i.id,t));for(let t of o){let n=B(t);await e.update(a).set(n).where(j(a.id,n.id))}return{cancelled:!0,gates:o}})}async function Tr(e,t,n,r,i,a){let{workflowExecutions:o}=T(e,F);return w(e,async e=>{if((await e.select({id:o.id}).from(o).where(j(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(j(o.id,t)),!0})}function Er(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(a.getExecution,async e=>{let{executionId:r}=e.payload;if(!g(e,r))throw Error(`Unauthorized execution read: ${r}`);let i=await t.select().from(n).where(j(n.id,r));e.setResult({execution:i[0]?br(i[0]):null})}),i=e.on(a.setExecution,async e=>{let r=e.payload.execution,i=Z(r);await E(t,()=>t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:i})),e.setResult({id:r.id})}),o=e.on(a.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await Sr(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(a.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await Cr(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(a.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await Tr(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(a.pauseRunningExecution,async e=>{let{workflowExecutions:n}=T(t,F),r=await E(t,()=>t.update(n).set({status:`paused`}).where(D(j(n.id,e.payload.executionId),j(n.status,`running`))).returning({id:n.id}));e.setResult({paused:r.length===1})}),u=e.on(a.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await wr(t,n,r,i))});return()=>{r(),i(),o(),s(),c(),l(),u()}}function Dr(e,t){let{workflowExecutions:n}=T(t,F),r=e.on(a.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=xr(r,i,a,s,c,n),u=o??Ze;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(D(...l)).orderBy(A(n.startedAt),A(n.id)).limit(u);e.setResult({executions:d.map(br)})}),i=e.on(a.listExecutionsByArtifactRefs,async e=>{let r=Qe.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(D(j(n.artifactKind,e.kind),j(n.artifactId,e.id))).orderBy(A(n.startedAt),A(n.id)).limit(a);r.length>0&&(o[gt(e)]=r.map(br))}e.setResult({executionsByRef:o})});return()=>{r(),i()}}function Or(e,t){let n=qt(e,t),r=Er(e,t),i=Dr(e,t),a=Xt(e,t),o=$t(e,t),s=nn(e,t),c=ln(e,t),l=pn(e,t),u=Jn(e,t),d=ur(e,t,Z),f=yr(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u(),d(),f()}}function kr(e){return e.startsWith(y)}function Ar(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function jr(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}async function Mr(e,t){let{runContext:n}=await e.request(a.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(a.get,{id:n.workflowId});return r??void 0}function Nr(e){return[e.on(h.getDefinition,async t=>{let n=await e.request(a.get,{id:t.payload.id});t.setResult(n)}),e.on(h.setDefinition,async t=>{let n=await e.request(a.set,{workflow:t.payload.workflow});t.setResult(n)}),e.on(h.deleteDefinition,async t=>{let n=await e.request(a.delete,{id:t.payload.id});t.setResult(n)}),e.on(h.listDefinitions,async t=>{let n=await e.request(a.list,t.payload);t.setResult(n)}),e.on(h.getExecution,async t=>{let n=await e.request(a.getExecution,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listExecutions,async t=>{let n=await e.request(a.listExecutions,t.payload);t.setResult(n)}),e.on(h.listExecutionsByArtifactRefs,async t=>{let n=await e.request(a.listExecutionsByArtifactRefs,t.payload);t.setResult(n)}),e.on(h.listSpans,async t=>{let n=await e.request(a.listSpans,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listFrames,async t=>{let n=await e.request(a.listFrames,{executionId:t.payload.executionId});t.setResult(n)}),e.on(h.listGateInstances,async t=>{let n=await e.request(a.listGateInstances,t.payload);t.setResult(n)}),e.on(h.setExecutionLink,async t=>{let n=await e.request(a.setExecutionLink,{link:t.payload.link});t.setResult(n)}),e.on(h.listExecutionLinks,async t=>{let n=await e.request(a.listExecutionLinks,t.payload);t.setResult(n)}),e.on(h.getRunContext,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${n}`);let{runContext:r}=await e.request(a.getRunContext,{executionId:n});if(!r)throw Error(`Run context not found for execution: ${n}`);t.setResult(r)}),...Pr(e)]}function Pr(e){return[e.on(h.registerExternalExecution,async t=>{let n=ce.registerExternalExecution.request.parse(t.payload),{name:r,scope:i,input:o}=n;if(n.executionId!==void 0&&!t.origin.local)throw Error(`registerExternalExecution: caller-supplied executionId is restricted to local callers`);let s=n.executionId??p(`wfx-ext`);if(!kr(s))throw Error(`registerExternalExecution: executionId must use the wfx-ext- prefix`);let c=n.startedAt??Date.now(),l={id:s,workflowId:r,status:`running`,inputs:o===void 0?{}:o,startedAt:c,scope:i??{type:`global`},...Ar(n)},u=Fr(s,c,n.frame),d=await e.request(a.setExternalExecutionStart,{execution:l,...u===void 0?{}:{frame:u}});t.setResult(d)}),e.on(h.completeExternalExecution,async t=>{let n=ce.completeExternalExecution.request.parse(t.payload),{executionId:r,status:i}=n;if(!g(t,r))throw Error(`Unauthorized: caller is not permitted to settle execution: ${r}`);if(!kr(r))throw Error(`completeExternalExecution: execution "${r}" is engine-owned and must be completed through the engine finalizer, not this API`);let o=Ir(n),s=await e.request(a.settleExternalExecution,{executionId:r,status:i,...jr(n),...n.completedAt===void 0?{}:{completedAt:n.completedAt},...o===void 0?{}:{frame:o}});t.setResult({success:s.success})})]}function Fr(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 Ir(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 Lr(e){return[e.on(h.state.get,async t=>{let{executionId:n}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${n}`);let{state:r}=await e.request(a.getState,{executionId:n});if(r===null)throw Error(`no workflow state for execution ${n}`);t.setResult(r)}),e.on(h.state.patch,async t=>{let{executionId:n,expectedSequence:r,patch:i,nextValue:s}=t.payload;if(!g(t,n))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${n}`);if(r===void 0)throw Error(`expectedSequence is required to patch workflow state`);let c=await Mr(e,n);c!==void 0&&o(c,s,`next`),$e.array().parse(i);let l=await e.request(a.patchState,{executionId:n,expectedSequence:r,nextValue:s});e.emit(h.state.updated,{executionId:l.executionId,sequence:l.sequence,patch:l.patch,value:l.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:l.executionId,sequence:l.sequence,value:l.value})})]}async function Rr(e,t){let{runContext:n}=await e.bus.request(a.getRunContext,{executionId:t});if(n===null)throw new S(ot.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return n}function zr(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function Br(e,t){let n=await Rr(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.scopeOverride??n.scope,c={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,scopeOverride:s,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:zr(t.mode,t.reason)}]};return t.mode===`snapshot`?await Wr(e,n,c):Hr(n)?await Gr(e,n,c):await he(e,n.workflowId,c)}function Vr(e,t){return Hr(e)?t.id:e.workflowId}function Hr(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function Ur(e){let t=e.definitionSnapshot;if(t===void 0)throw new S(ot.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Wr(e,t,n){let r=Ur(t);return Ee(e,Vr(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}async function Gr(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`){let{materializationSpec:r}=t;if(r===void 0)throw Error(`Invalid persisted path-backed run context: materializationSpec is required`);return Me(e,t.source.path,{...n,materializationSpec:r})}let r=Ur(t);return Ee(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks,...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}})}var Kr=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(a.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(a.getExecution,{executionId:e.executionId});return n?.status===`running`?`retry`:n?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function qr(e){if(e!==void 0)return Jr(e)?e:{}}function Jr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Yr(e){if(e!==void 0)return et.parse(e)}function Xr(e,t){return ct.parse({executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{contributionRefs:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,triggerMode:e.triggerMode??`immediate`,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`,...e.terminalAuthority===void 0?{}:{terminalAuthority:e.terminalAuthority},...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec}})}function Zr(e){return e?.status===`paused`}function Qr(e){return e?.status===`waiting`}async function $r(e,t,n,r,i,o,s){t.delete(i.id),n.delete(i.id),r.delete(i.id);try{await e.request(a.restorePausedGateResumeState,{execution:i,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function ei(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:n}=await e.request(a.listFrames,{executionId:t.executionId});if(n.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function ti(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function ni(e,t){if(t.frameId!==void 0){let{gate:n}=await e.request(a.getGateInstance,t);return Qr(n)?n:null}let{gates:n}=await e.request(a.listGateInstances,{executionId:t.executionId}),r=n.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return r.length===1?r[0]:null}async function ri(e,t){let n=e.authority.canonicalizeOutcome(t.outcome),r=t.runtimeFence===void 0?void 0:{...t.runtimeFence};await e.validation?.validate(t.executionId,n.outcome);let i=await e.authority.commitOutcome(t.executionAttemptId,t.executionId,n,r);return(i.kind===`accepted`||i.kind===`duplicate`)&&(await e.convergence.converge({executionId:t.executionId,executionAttemptId:t.executionAttemptId,outcome:i.outcome,decision:i.kind}),e.authority.settleOutcome(t.executionAttemptId,{kind:i.kind,outcome:e.authority.decodeOutcome(i.text),text:i.text})),i.kind}function ii(e,t){let r=n(e);if(r===null)throw Error(`Attempt requests require an authenticated workflow-execution-attempt peer`);if(r.executionAttemptId!==t)throw Error(`Request executionAttemptId does not match authenticated peer identity`);return r}function ai(e,t){if(e===null||e.runtimeGeneration!==t.runtimeGeneration)return!1;if(t.outcome.kind===`cancelled`&&t.operationId===void 0)return e.activeOperationId===null;let n=t.outcome.kind===`technical-failure`?t.outcome.stage:t.outcome.kind===`cancelled`?e.activeOperationKind:`workload-invocation`;return n===`startup`?t.operationId===void 0&&e.activeOperationId===null:!(e.activeOperationId!==t.operationId||e.activeOperationGeneration!==t.runtimeGeneration||e.activeOperationKind!==n||n!==`workspace-preparation`&&n!==`workload-invocation`)}function oi(e,t){return e.on(x.instruction.get,async e=>{let n=b[`instruction.get`].request.parse(e.payload),r=ii(e,n.executionAttemptId),i=await t.getInstruction(r);if(i===null){e.setResult({decision:`refused`,refusalReason:`not-found`});return}if((await t.getAttemptControlState(r.executionAttemptId))?.runtimeGeneration!==n.runtimeGeneration){e.setResult({decision:`refused`,refusalReason:`stale-generation`});return}e.setResult({decision:`found`,instruction:i})})}function si(e,t){let n=[oi(e,t.authority),e.on(x.operation.report,async e=>{let n=b[`operation.report`].request.parse(e.payload),r=ii(e,n.executionAttemptId),i=await t.authority.reportOperation({...n,executionId:r.executionId});i.kind===`accepted`||i.kind===`duplicate`?e.setResult({decision:i.kind,binding:i.binding}):e.setResult({decision:`refused`,refusalReason:i.kind})}),e.on(x.outcome.submit,async e=>{let n=b[`outcome.submit`].request.parse(e.payload),r=ii(e,n.executionAttemptId),i=await t.authority.getInstruction(r);if(i===null)throw Error(`No instruction belongs to this authenticated Attempt`);if(!ai(await t.authority.getAttemptControlState(r.executionAttemptId),n)){e.setResult({decision:`fenced`});return}let a={runtimeGeneration:n.runtimeGeneration,operationId:n.operationId??null},o=await t.decodeOutcome({instruction:i,outcome:n.outcome});try{let n=await ri(t,{...r,outcome:o,runtimeFence:a});e.setResult({decision:n})}catch(t){if(!(t instanceof He))throw t;e.setResult({decision:`fenced`})}})];return()=>{for(let e of n)e()}}function ci(e,t){return e.origin.local?{executionAttemptId:t.executionAttemptId,executionId:t.executionId}:n(e)}async function li(e,t,n){if(n.pausedAtGateId===void 0||n.pausedAtFrameId===void 0)throw Error(`Paused outcome for '${t}' is missing gate identity`);let{paused:r}=await e.request(a.pauseRunningExecution,{executionId:t});if(!r){let{execution:n}=await e.request(a.getExecution,{executionId:t});if(n?.status!==`paused`)throw Error(`Failed to park execution '${t}': status is '${n?.status??`missing`}'`);return}await e.emit(h.execution.paused,{executionId:t,workflowId:n.workflowId,pausedAtGateId:n.pausedAtGateId,pausedAtFrameId:n.pausedAtFrameId})}var ui=class{bus;acceptTerminalResult;acceptTechnicalFailure;acceptCancellation;constructor(e,t,n,r){this.bus=e,this.acceptTerminalResult=t,this.acceptTechnicalFailure=n,this.acceptCancellation=r}async converge(e){if(`kind`in e.outcome){if(e.outcome.kind===`cancelled`){let t=await this.acceptCancellation(e.executionId,e.outcome);if(!t.accepted||t.status!==`cancelled`)throw Error(`Cancellation did not converge workflow execution '${e.executionId}'`);return}let t=await this.acceptTechnicalFailure(e.executionId,e.outcome);if(!t.accepted||t.status!==`failed`&&t.status!==`cancelled`)throw Error(`Technical failure did not converge workflow execution '${e.executionId}'`);return}if(e.outcome.status===`paused`){await li(this.bus,e.executionId,e.outcome);return}let t=await this.acceptTerminalResult(e.executionId,e.outcome);if(!t.accepted||!u(t.status,e.outcome.status))throw Error(`Workflow result did not converge execution '${e.executionId}'`)}};function di(e,t){return{authority:t.authority,decodeOutcome:Ve,convergence:new ui(e,t.acceptTerminalResult,t.acceptTechnicalFailure,t.acceptCancellation)}}function fi(e,t){let n=di(e,t),r=si(e,n),i=e.on(it.control.outcome.submit,async e=>{let r=ci(e,e.payload);if(r===null)throw Error(`Outcome submission requires an authenticated workflow-execution-attempt peer`);let{result:i}=e.payload;if(!e.origin.local){if(e.payload.executionId!==r.executionId)throw Error(`Outcome payload executionId '${e.payload.executionId}' does not match authenticated peer claim '${r.executionId}'`);if(e.payload.executionAttemptId!==r.executionAttemptId)throw Error(`Outcome payload executionAttemptId '${e.payload.executionAttemptId}' does not match authenticated peer identity '${r.executionAttemptId}'`)}if(i.executionId!==r.executionId)throw Error(`Nested result.executionId '${i.executionId}' does not match trusted identity '${r.executionId}'`);let a=lt.parse(i),o=await t.authority.getInstruction(r);if(o===null)throw Error(`No instruction belongs to this workflow Attempt`);let s=await n.decodeOutcome({instruction:o,outcome:{kind:`workload-result`,result:a}}),c=await ri(n,{executionId:r.executionId,executionAttemptId:r.executionAttemptId,outcome:s});e.setResult({decision:pi(c)})});return()=>{i(),r()}}function pi(e){return e}function mi(e,t){return e.on(x.operation.admit,async e=>{let r=n(e);if(r===null)throw Error(`Operation admission requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:i,operationKind:a,admissionKey:o,runtimeGeneration:s}=b[`operation.admit`].request.parse(e.payload);if(i!==r.executionAttemptId)throw Error(`Admission payload executionAttemptId '${i}' does not match authenticated peer identity '${r.executionAttemptId}'`);if(a===`runtime-probe`)throw Error(`Operation admission does not accept 'runtime-probe' (executionAttemptId='${i}'): the bounded probe is admitted only by runtime registration`);let c=await t.authority.admitOperation({executionAttemptId:i,executionId:r.executionId,operationKind:a,admissionKey:o,runtimeGeneration:s});if(c.kind===`admitted`||c.kind===`duplicate`){await t.bus.emit(x.operation.admitted,{executionAttemptId:i,operationId:c.operationId,operationKind:a,runtimeGeneration:c.runtimeGeneration,admittedAt:c.admittedAt}),e.setResult({decision:c.kind,operationId:c.operationId});return}e.setResult({decision:`refused`,refusalReason:c.kind})})}const hi=1e4;function gi(e,t){let r=t.probeDeliveryTimeoutMs??1e4;return e.on(x.runtime.register,async e=>{let i=n(e);if(i===null)throw Error(`Runtime registration requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:a,runtimeIncarnationId:o}=b[`runtime.register`].request.parse(e.payload);if(a!==i.executionAttemptId)throw Error(`Registration payload executionAttemptId '${a}' does not match authenticated peer identity '${i.executionAttemptId}'`);let s=await t.authority.registerRuntime({executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o});if(s.kind===`duplicate`&&s.runtimeReadyAt!==null){await _i(t,a,s.runtimeGeneration),e.setResult({decision:`duplicate`,runtimeGeneration:s.runtimeGeneration});return}if(s.kind!==`registered`&&s.kind!==`duplicate`){e.setResult(bi(s.kind));return}let c=s.runtimeGeneration;if(await vi(t,r,{executionAttemptId:a,executionId:i.executionId,runtimeIncarnationId:o,runtimeGeneration:c})===null){e.setResult(bi(`probe-failed`));return}await _i(t,a,c),e.setResult({decision:`ready`,runtimeGeneration:c})})}async function _i(e,t,n){let r=await e.authority.getAttemptControlState(t);r===null||r.runtimeGeneration!==n||r.runtimeReadyAt===null||await e.bus.emit(x.runtime.ready,{executionAttemptId:t,runtimeGeneration:n,acceptedAt:r.runtimeReadyAt})}async function vi(e,t,n){let{executionAttemptId:r,executionId:i,runtimeIncarnationId:a,runtimeGeneration:o}=n,s=await e.authority.admitOperation({executionAttemptId:r,executionId:i,operationKind:`runtime-probe`,admissionKey:`probe:${a}`,runtimeGeneration:o});if(s.kind!==`admitted`&&s.kind!==`duplicate`)return null;let c=s.operationId,l=()=>yi(e,{executionAttemptId:r,operationId:c,runtimeGeneration:o}),u;try{u=(await e.bus.request(x.operation.deliver,{executionAttemptId:r,runtimeIncarnationId:a,operationId:c,operationKind:`runtime-probe`,runtimeGeneration:o},{timeout:t})).receipt}catch{return await l(),null}if(u!==`completed`&&u!==`duplicate`)return await l(),null;let d=await e.authority.completeOperation({executionAttemptId:r,operationId:c,runtimeGeneration:o});if(d.kind!==`completed`&&d.kind!==`duplicate`)return null;let f=await e.authority.markRuntimeReady({executionAttemptId:r,executionId:i,runtimeGeneration:o,readyAt:new Date().toISOString()});return f.kind!==`ready`&&f.kind!==`duplicate`?null:{kind:f.kind,acceptedAt:f.acceptedAt}}async function yi(e,t){try{await e.authority.completeOperation(t)}catch{}}function bi(e){return{decision:`refused`,runtimeGeneration:0,refusalReason:e}}function xi(e,t,n){n(gi(e,{bus:e,authority:t})),n(mi(e,{bus:e,authority:t}))}function Si(e,t){let r=new AbortController,i=e.on(x.bootstrap.awaitStart,async e=>{let i=n(e);if(i===null)throw Error(`Bootstrap start requires an authenticated workflow-execution-attempt peer`);let{executionAttemptId:a}=b[`bootstrap.awaitStart`].request.parse(e.payload);if(a!==i.executionAttemptId)throw Error(`Bootstrap start executionAttemptId does not match authenticated peer identity`);let o=e.signal?AbortSignal.any([e.signal,r.signal]):r.signal;e.setResult(await t.awaitBootstrapStart({executionAttemptId:a,executionId:i.executionId},{signal:o,deadline:e.deadline??Date.now()+31e3}))});return()=>{r.signal.aborted||(r.abort(Error(`Bootstrap start handler shut down`)),i())}}function Ci(e){return e.on(h.finalizeDelegateResult,async t=>{let n=t.payload;wi(t,n.executionId);let{execution:r}=await e.request(a.getExecution,{executionId:n.executionId});if(r===null||r.workflowId!==n.workflowId)throw Error(`delegate result finalization execution does not own the requested workflow`);let{runContext:i}=await e.request(a.getRunContext,{executionId:n.executionId});if(i===null||i.executionId!==n.executionId||i.workflowId!==n.workflowId)throw Error(`delegate result finalization run context does not own the requested workflow execution`);if(i.definitionSnapshot===void 0)throw Error(`delegate result finalization requires an Authority-owned definition snapshot`);Ti(i.definitionSnapshot,n.nodeId,n.nodeType,n.finalizerId);let{subjects:o}=ft(n.finalizerId),s=await e.request(o.finalize,{executionId:n.executionId,workflowId:n.workflowId,frameId:n.frameId,nodeId:n.nodeId,nodeType:n.nodeType,rawResult:n.rawResult,toolObservations:n.toolObservations,...n.economics===void 0?{}:{economics:n.economics}});t.setResult(s)})}function wi(e,t){if(!g(e,t))throw Error(`delegate result finalization requires its authenticated workflow-execution-attempt peer`)}function Ti(e,t,n,r){let i=!1;if(_t(e.root,{enter(e){if(!(e.type!==`delegate-agent`&&e.type!==`delegate-role`||e.id!==t||e.type!==n))return e.resultFinalizerId===r&&(i=!0),!1}}),!i)throw Error(`delegate result finalizer is not selected by the requested durable delegate node`)}async function Ei(e,n,r){let[{execution:i},{runContext:o}]=await Promise.all([e.bus.request(a.getExecution,{executionId:n}),e.bus.request(a.getRunContext,{executionId:n})]);if(!i)throw Error(`Authority execution not found: ${n}`);if(o?.executionId!==n||o.workflowId!==i.workflowId)throw Error(`authority technical failure run context identity mismatch`);if(o.terminalAuthority!==`authority`)throw Error(`authority technical failure requires terminalAuthority=authority`);if(i.status===`failed`||i.status===`cancelled`)return{accepted:!0,status:i.status};if(i.status!==`running`)throw Error(`Authority technical failure conflicts with execution status: ${i.status}`);await t(e,i,n,`${r.stage}: ${r.message}`);let s=await e.bus.request(a.getExecution,{executionId:n});if(s.execution?.status!==`failed`&&s.execution?.status!==`cancelled`)throw Error(`Authority technical failure did not settle as failed or cancelled`);return{accepted:!0,status:s.execution.status}}async function Di(e,t,n){let[{execution:r},{runContext:i}]=await Promise.all([e.bus.request(a.getExecution,{executionId:t}),e.bus.request(a.getRunContext,{executionId:t})]);if(!r)throw Error(`Authority execution not found: ${t}`);if(i?.executionId!==t||i.workflowId!==r.workflowId)throw Error(`authority cancellation run context identity mismatch`);if(i.terminalAuthority!==`authority`)throw Error(`authority cancellation requires terminalAuthority=authority`);if(r.status===`cancelled`)return{accepted:!0,status:`cancelled`};if(r.status!==`running`)throw Error(`Authority cancellation conflicts with execution status: ${r.status}`);if(await m(e,t,n.reason),(await e.bus.request(a.getExecution,{executionId:t})).execution?.status!==`cancelled`)throw Error(`Authority cancellation did not settle as cancelled`);return{accepted:!0,status:`cancelled`}}var Oi=class extends vt{workflowRunner;executionAttemptAuthority;static storage={drizzle:Or};config;stopBootstrapWaits;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;materializationSpecResolvers=new Set;constructor(e,t,n,r){super(e),this.workflowRunner=n,this.executionAttemptAuthority=r,this.config={...l,...t},this.gateTimeoutScheduler=new Kr(e,e=>this.resumePausedExecution(e))}registerWorkflowMaterializationSpecResolver(e){return this.materializationSpecResolvers.add(e),()=>this.materializationSpecResolvers.delete(e)}async registerSuccessFinalizer(e){if(!this.initialized)throw Error(`[WorkflowExecutor] Initialize the executor before registering success finalizers`);if(this.successFinalizers.has(e))throw Error(`[WorkflowExecutor] Success finalizer already registered: ${e}`);let{namespace:t,subjects:n}=pt(e);this.bus.registerNamespace(t);let r={finalizerId:e,finalizeSubject:n.finalize};this.successFinalizers.set(e,r);try{await d(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(a.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:o,workflow:s}=await this.loadAuthorityRunnerContext(e,t.workflowId),c=await this.registerAuthorityResultFinalizer(s),l=this.activeExecutions.get(e),d=!1;if(!l)this.activeExecutions.set(e,{execution:n,workflow:s,runContext:o,runtimeHandlers:new Map,runtimeLoopGates:new Map}),d=!0;else if(l.execution.workflowId!==t.workflowId)throw Error(`authority runner active execution identity mismatch`);try{await f({activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps()},t)}finally{d&&this.activeExecutions.delete(e),c?.()}let p=await this.bus.request(a.getExecution,{executionId:e});if(!p.execution||!u(p.execution.status,t.status))throw Error(`Authority runner result did not settle compatibly with ${t.status}`);return{accepted:!0,status:p.execution.status}}acceptAuthorityTechnicalFailure=(e,t)=>Ei(this.buildFinalizerDeps(),e,t);acceptAuthorityCancellation=(e,t)=>Di(this.buildFinalizerDeps(),e,t);async resolveAuthorityRunnerReplay(e,t){if(e.status===`finalizing`){if(t.status!==`completed`)throw Error(`authority runner result conflicts with terminal execution`);await d(this.buildFinalizerDeps());let n=await this.bus.request(a.getExecution,{executionId:e.id});if(!n.execution)throw Error(`Authority runner success finalization execution is missing`);if(!u(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(!u(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(a.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(a.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(Oe(this.bus,(e,t)=>{let n=this.activeExecutions.get(e);n!==void 0&&(n.workflow=t)})),this.addCleanup(Ci(this.bus)),this.executionAttemptAuthority!==void 0&&(this.stopBootstrapWaits=Si(this.bus,this.executionAttemptAuthority),this.addCleanup(this.stopBootstrapWaits),this.addCleanup(fi(this.bus,{bus:this.bus,authority:this.executionAttemptAuthority,acceptTerminalResult:(e,t)=>this.acceptAuthorityRunnerResult(e,t),acceptTechnicalFailure:this.acceptAuthorityTechnicalFailure,acceptCancellation:this.acceptAuthorityCancellation})),xi(this.bus,this.executionAttemptAuthority,e=>this.addCleanup(e))),Nr(this.bus).forEach(e=>this.addCleanup(e)),Lr(this.bus).forEach(e=>this.addCleanup(e)),await this.rehydratePausedGateTimeouts()}async onDestroy(){this.stopBootstrapWaits?.();let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await m(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(),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(tt.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}resolveEphemeralPlatformFields(){return ze(this.config.platformDefaults.cwd,this.config.makaioHome)}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Xr(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e),executionAttemptAuthority:this.executionAttemptAuthority,materializationSpecResolvers:this.materializationSpecResolvers}}registerExecutionHandlers(){this.registerHandler(h.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(h.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s}=e.payload;try{let c=await he(this.buildStartDeps(),t,{input:Yr(n),config:qr(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,scopeOverride:s});e.setResult({executionId:c})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(h.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,reason:l}=e.payload;try{let u=await Br(this.buildStartDeps(),{executionId:t,mode:n,input:Yr(r),config:qr(i),parentSessionId:a,triggerPayload:o,artifactRef:s,scopeOverride:c,reason:l});e.setResult({executionId:u})}catch(e){if(e instanceof S)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(h.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,materializationSpec:n,triggerPayload:r,triggerMode:i,scope:a}=e.payload;try{let o=await Me(this.buildStartDeps(),t,{...n===void 0?{}:{materializationSpec:n},triggerPayload:r,triggerMode:i,scopeOverride:a});e.setResult({executionId:o})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(h.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(dt(`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??nt);let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(h.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(h.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(h.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(a.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(ti(t))}async runExecution(e){let n=this.activeExecutions.get(e);if(!n)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let t=await de({definition:n.workflow,execution:n.execution,runContext:n.runContext,bus:this.bus}),a=new we(e,n.workflow.id,n.workflow,n.execution,n.runtimeHandlers,this.bus,r.signal,void 0,t,{context:this.resolveEphemeralPlatformFields(),env:n.runContext.env},{runtimeLoopGates:n.runtimeLoopGates});Fe(n.workflow,n.runtimeLoopGates);let o=a.buildExpressionContext();i=await xe(n.workflow.root,a,o)}catch(i){if(r.signal.aborted||n.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,nt);return}let a=i instanceof Error?i.message:String(i);await t(this.buildFinalizerDeps(),n.execution,e,a);return}let o=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||n.execution.status===`cancelled`?await m(o,e,nt):i.status===`failed`?await t(o,n.execution,e,i.error):i.status===`paused`?(n.execution.status=`paused`,await this.bus.request(a.setExecution,{execution:n.execution}),this.activeExecutions.delete(e)):await Ce(o,n.execution,e,n.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:n,frameId:r,resumeData:i,reason:o}=e,{execution:s}=await this.bus.request(a.getExecution,{executionId:t});if(!Zr(s))return!1;let c=await ni(this.bus,{executionId:t,nodeId:n,frameId:r});if(c===null||!Ae(n,c.schema,i).valid)return!1;let{runContext:l}=await this.bus.request(a.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await ei(this.bus,l);let{accepted:u}=await this.bus.request(a.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:i,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await $r(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,n),e}return this.gateTimeoutScheduler.clear(t,n,c.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(a.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(a.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(a.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await ei(this.bus,t);let o=r(t,n,{resume:!0}),s=_e(this.buildStartDeps(),o);await this.bus.request(a.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:n,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let c=ye(this.buildStartDeps(),o,s).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,c),!0}};const Q=`[WorkflowTriggerReconciler]`;function ki(e){return e.map(Ai)}function Ai(e){let t=at.parse(e);return{binding:t,matches:We(t),subscription:void 0}}function ji(e,t,n){let r=e.triggers??[];try{return n===void 0?ki(r):r.map(e=>n.has(e.kind)?Ai(e):void 0)}catch(i){if(t){console.error(`${Q} keeping last-good triggers for workflow "${e.id}": its trigger bindings are invalid`,i);return}return r.map((t,r)=>{if(!(n!==void 0&&!n.has(t.kind)))try{return Ai(t)}catch(t){console.error(`${Q} leaving invalid trigger ${r} of workflow "${e.id}" inactive`,t);return}})}}function Mi(e,t){return e.scope.type!==`global`||t.kind!==Xe}async function Ni(e,t,n,r){if(r!==void 0)for(let[i,a]of Array.from(r)){let o=e.triggers?.[i];if(o!==void 0&&n!==void 0&&!n.has(o.kind))continue;let s=t[i];s!==void 0&&Mi(e,s.binding)||(r.delete(i),await $(a.subscription))}}async function $(e){if(e!==void 0)try{await e.detach()}catch(t){console.error(`${Q} detach failed for '${e.bindingKey}':`,t)}}var Pi=class{bus;resolveRuntime;consumers=new Map;cleanupFns=[];initialized=!1;initialization;lane=new qe;pendingChanges=[];constructor(e,t){this.bus=e,this.resolveRuntime=t}async init(){if(this.initialized)return;if(this.initialization!==void 0)return this.initialization;let e=this.initialize();return this.initialization=e,e.then(()=>this.clearInitialization(e),()=>this.clearInitialization(e)),e}clearInitialization(e){this.initialization===e&&(this.initialization=void 0)}async initialize(){try{let e=({payload:e})=>{this.onSignal(`refresh of workflow "${e.id}"`,()=>this.refreshDefinition(e.id))};this.cleanupFns.push(this.bus.on(C.definition.created,e),this.bus.on(C.definition.updated,e),this.bus.on(C.definition.deleted,e),this.bus.on(Ye.changed,e=>{this.scheduleRegistryReconcile(e.payload)})),await this.reconcileStored(`keep-last-good`),this.initialized=!0}catch(e){throw await this.teardown(),e}}async destroy(){await this.teardown(),this.initialized=!1}activeConsumerCount(){let e=0;for(let t of this.consumers.values())e+=t.size;return e}onSignal(e,t){t().catch(t=>{console.error(`${Q} ${e} failed:`,t)})}scheduleRegistryReconcile(e){let t=this.pendingChanges.length>0;this.pendingChanges.push(e),!t&&queueMicrotask(()=>{if(this.pendingChanges.length===0)return;let e=this.pendingChanges.splice(0),t=new Set(e.flatMap(({kinds:e})=>e)),n=e.map(({owner:e,revision:t})=>`${e}@${t}`).join(`, `);this.onSignal(`reconciliation after trigger registry changes (${n})`,()=>this.reconcileStored(`drop-unavailable`,t))})}async reconcileStored(e,t){await this.lane.run(async()=>{let{workflows:n}=await this.bus.request(a.list,{}),r=new Set(n.map(e=>e.id));for(let r of n){let n=r.triggers??[];t!==void 0&&!n.some(e=>t.has(e.kind))||await this.applyDefinitionWithinLane(r,e,t)}for(let e of Array.from(this.consumers.keys()))r.has(e)||await this.forgetWorkflowWithinLane(e)})}async refreshDefinition(e){await this.lane.run(async()=>{let{workflow:t}=await this.bus.request(a.get,{id:e});if(t===null){await this.forgetWorkflowWithinLane(e);return}await this.applyDefinitionWithinLane(t,`keep-last-good`)})}async applyDefinitionWithinLane(e,t,n){let r=ji(e,(this.consumers.get(e.id)?.size??0)>0,n);if(r===void 0)return;let i=this.consumers.get(e.id);if(await Ni(e,r,n,i),i?.size===0&&this.consumers.delete(e.id),!r.some(t=>t!==void 0&&Mi(e,t.binding)&&(n===void 0||n.has(t.binding.kind))))return;let a=this.resolveRuntime();if(a===void 0){r.length>0&&console.warn(`${Q} no automation trigger binding runtime is available; declarative triggers of workflow "${e.id}" stay inactive`);return}let o=this.consumers.get(e.id);o===void 0&&(o=new Map,this.consumers.set(e.id,o));for(let[i,s]of r.entries())s!==void 0&&Mi(e,s.binding)&&(n!==void 0&&!n.has(s.binding.kind)||await this.refreshConsumerWithinLane(a,e.id,i,s,o,t));o.size===0&&this.consumers.delete(e.id)}async refreshConsumerWithinLane(e,t,n,r,i,a){let o=i.get(n),s=this.createListener(t,n,r);try{let t=o?.subscription?.bindingKey,a=e.prepareBinding(r.binding);if(a===void 0)throw Error(`Automation trigger kind '${r.binding.kind}' is not registered`);if(!a.workflowCompatible)throw Error(`Automation trigger kind '${r.binding.kind}' does not emit an object-root payload`);(t===void 0||t!==a.bindingKey)&&i.set(n,r),r.subscription=await a.subscribe(s),i.set(n,r),await $(o?.subscription);return}catch(e){if(o===void 0?i.delete(n):i.set(n,o),a===`keep-last-good`){console.error(`${Q} keeping last-good trigger ${n} of workflow "${t}": binding '${r.binding.kind}' could not be activated`,e);return}console.warn(`${Q} dropping trigger ${n} of workflow "${t}": binding '${r.binding.kind}' is no longer available`,e),i.delete(n),await $(o?.subscription)}}async forgetWorkflowWithinLane(e){let t=this.consumers.get(e);if(t!==void 0){this.consumers.delete(e);for(let e of t.values())await $(e.subscription)}}createListener(e,t,n){let r=`trigger ${t} ('${n.binding.kind}') of workflow "${e}"`;return async i=>{if(this.consumers.get(e)?.get(t)!==n)return;let a;try{a=n.matches(i.payload)}catch(e){console.error(`${Q} filter evaluation failed for ${r}:`,e);return}if(a)try{await this.bus.request(C.start,{workflowId:e,triggerPayload:Ue(i.payload)})}catch(t){console.error(`${Q} failed to start workflow "${e}" from ${r}:`,t)}}}async teardown(){this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.pendingChanges.length=0,await this.lane.run(async()=>{for(let e of Array.from(this.consumers.keys()))await this.forgetWorkflowWithinLane(e)})}};const Fi=1e3;function Ii(e){if(e===null)return{status:`refused`,reason:`not-found`};if(e.settled)return{status:`refused`,reason:`resolved`};if(!e.active)return{status:`refused`,reason:`fenced`};if(e.allocationTerminated)return{status:`refused`,reason:`allocation-terminated`};if(e.operationStartGate===`closed`)return{status:`refused`,reason:`gate-closed`};let t=e.bootstrapDeadlineAt===null?NaN:Date.parse(e.bootstrapDeadlineAt);return!Number.isFinite(t)||t<=Date.now()?{status:`refused`,reason:`bootstrap-expired`}:{status:e.allocated?`permitted`:`pending`}}function Li(e,t){return new Promise((n,r)=>{let i=()=>{t.removeEventListener(`abort`,i),r(t.reason)};t.addEventListener(`abort`,i,{once:!0}),t.aborted&&i(),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function Ri(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),n()},a=()=>{clearTimeout(o),t.removeEventListener(`abort`,a),r(t.reason)},o=setTimeout(i,e);t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}function zi(e,t){return setTimeout(()=>e.abort(Error(`Bootstrap start observation timed out`)),Math.max(0,t-Date.now()))}async function Bi(e,t,n){if(n.signal.throwIfAborted(),!Number.isFinite(n.deadline))throw Error(`Bootstrap start request requires a finite deadline`);let r=Math.min(Date.now()+3e4,n.deadline-Fi),i=new AbortController,a=AbortSignal.any([n.signal,i.signal]),o=Math.min(n.deadline,r+Fi),s=zi(i,o);try{for(;;){a.throwIfAborted();let n=await Li(e.readBootstrapStartState(t),a);a.throwIfAborted();let c=Ii(n);if(c.status!==`pending`)return c;let l=Date.parse(n?.bootstrapDeadlineAt??``);clearTimeout(s),s=zi(i,Math.min(o,l+Fi));let u=Math.min(r,l)-Date.now();if(u<=0)return c;await Ri(Math.min(100,u),a)}}finally{clearTimeout(s)}}var Vi=class{repository;bootstrapTimeoutMs;waiters=new Map;constructor(e,t){if(!Number.isSafeInteger(t?.bootstrapTimeoutMs)||t.bootstrapTimeoutMs<=0)throw Error(`ExecutionAttemptAuthority requires an explicit positive safe-integer bootstrapTimeoutMs`);this.repository=e,this.bootstrapTimeoutMs=t.bootstrapTimeoutMs}awaitBootstrapStart(e,t){return Bi(this.repository,e,t)}async createAttempt(e,t){let n=crypto.randomUUID(),r=await this.repository.createAttempt({executionAttemptId:n,executionId:e,instruction:t,bootstrapTimeoutMs:this.bootstrapTimeoutMs});return this.installWaiter(n),r}async ensureAttempt(e){let t=Ke(e);return this.repository.ensureAttempt({...t,executionAttemptId:crypto.randomUUID(),bootstrapTimeoutMs:this.bootstrapTimeoutMs})}async readAttemptSettlement(e){return this.repository.readAttemptSettlement(Ge(e))}async getInstruction(e){return this.repository.getInstruction(e)}async reportOperation(e){return this.repository.reportOperation(e)}async beginProvisioning(e){return this.repository.beginProvisioning(e)}async getProviderOperation(e){return this.repository.getProviderOperation(e)}async renewProviderOperationClaim(e){return this.repository.renewProviderOperationClaim(e)}async takeOverProviderOperation(e){return this.repository.takeOverProviderOperation(e)}async handoffProviderOperation(e){return this.repository.handoffProviderOperation(e)}async recordProviderOperationUncertainty(e){return this.repository.recordProviderOperationUncertainty(e)}async recordAllocation(e){return this.repository.recordAllocation(e)}async recordProvisioningAbsent(e){let t=await this.repository.recordProvisioningAbsent(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' provisioning produced no allocation: ${e.evidence.source} reported '${e.evidence.summary}'`)),t}async recordProvisionerIncarnationLost(e){let t=await this.repository.recordProvisionerIncarnationLost(e);if(t.kind===`recorded`){let{evidence:t,provisionerIncarnationId:n}=e.proof;this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' lost the provisioner incarnation '${n}' its allocation was bound to: ${t.source} reported '${t.summary}'`))}return t}async recordAllocationTerminated(e){return this.repository.recordAllocationTerminated(e)}async registerRuntime(e){return this.repository.registerRuntime(e)}async admitOperation(e){return this.repository.admitOperation(e)}async completeOperation(e){return this.repository.completeOperation(e)}async markRuntimeReady(e){return this.repository.markRuntimeReady(e)}async getAttemptControlState(e){return this.repository.getAttemptControlState(e)}async getActiveAttempt(e,t){return this.repository.getActiveAttempt(e,t)}canonicalizeOutcome(e){return this.repository.canonicalizeOutcome(e)}decodeOutcome(e){return this.repository.decodeOutcome(e)}async commitOutcome(e,t,n,r){let i=await this.repository.commitOutcome({executionAttemptId:e,executionId:t,result:n,...r===void 0?{}:{runtimeFence:r}});return(i.kind===`conflict`||i.kind===`fenced`)&&this.settleWaiterInternal(e,i),i}waitForOutcome(e){return this.waiters.get(e)?.promise}settleOutcome(e,t){this.settleWaiterInternal(e,t)}discardWaiter(e){this.waiters.delete(e)}rejectAndDiscardWaiter(e,t){this.rejectWaiterWith(e,()=>t)}rejectWaiterWith(e,t){let n=this.waiters.get(e);n!==void 0&&(n.promise.catch(()=>void 0),n.reject(t()),this.waiters.delete(e))}get supportsRecovery(){return this.repository.recovery!==void 0}async getAttemptWithAllocation(e){return this.requireRecovery(`getAttemptWithAllocation`).getAttemptWithAllocation(e)}async recordDiscoveredAllocation(e){return this.requireRecovery(`recordDiscoveredAllocation`).recordDiscoveredAllocation(e)}async evolveAllocationRef(e){let t=this.requireRecovery(`evolveAllocationRef`);if(e.currentRef.providerId!==e.nextRef.providerId)throw Error(`Provider identity mismatch in allocation ref evolution: currentRef.providerId '${e.currentRef.providerId}' !== nextRef.providerId '${e.nextRef.providerId}'. Provider identity must not change during correlation.`);return t.evolveAllocationRef(e)}async getRecoverableAttempts(e){return this.requireRecovery(`getRecoverableAttempts`).getRecoverableAttempts(e)}async recordInfrastructureFailure(e){let t=await this.repository.recordInfrastructureFailure(e);return t.kind===`recorded`&&this.rejectWaiterWith(e.claim.executionAttemptId,()=>Error(`Attempt '${e.claim.executionAttemptId}' suffered infrastructure failure: the provider allocation terminated without an acknowledged outcome`)),t}async abandonPendingAttempt(e,t){let n=await this.repository.abandonPendingAttempt(e,t);return(n.kind===`abandoned`||n.kind===`already-abandoned`)&&this.waiters.delete(e),n}requireRecovery(e){let{recovery:t}=this.repository;if(t===void 0)throw Error(`Recovery operation '${e}' requires a repository that exposes recovery operations. The injected repository does not support recovery.`);return t}installWaiter(e){this.waiters.set(e,le())}settleWaiterInternal(e,t){let n=this.waiters.get(e);if(n){switch(t.kind){case`accepted`:case`duplicate`:n.resolve(t.outcome);break;case`conflict`:n.reject(Error(`Outcome conflict for attempt '${e}': a different outcome was already committed`));break;case`fenced`:n.reject(Error(`Attempt '${e}' has been fenced: it is no longer the active attempt for this execution`));break}this.waiters.delete(e)}}},Hi=class extends vt{workflowExecutor;triggerReconcilerInstance;attemptAuthority;workspaceRootResolvers=new Set;constructor(e,t){super(e);let n=t?.executionAttemptAuthority;if(!n&&t?.executionAttemptRepository){let e=t.executionAttemptBootstrapTimeoutMs;if(e===void 0)throw Error(`An ExecutionAttemptRepository requires executionAttemptBootstrapTimeoutMs`);n=new Vi(t.executionAttemptRepository,{bootstrapTimeoutMs:e})}this.attemptAuthority=n,this.workflowExecutor=new Oi(e,t?.executorConfig,t?.workflowRunner,this.attemptAuthority);for(let e of t?.workflowMaterializationSpecResolvers??[])this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e);let r=t?.automationTriggerBindingRuntime;this.triggerReconcilerInstance=new Pi(e,()=>r?.())}get executor(){return this.workflowExecutor}get executionAttemptAuthority(){return this.attemptAuthority}registerSuccessFinalizer(e){return this.workflowExecutor.registerSuccessFinalizer(e)}acceptAuthorityRunnerResult(e,t){return this.workflowExecutor.acceptAuthorityRunnerResult(e,t)}get triggerReconciler(){return this.triggerReconcilerInstance}registerWorkflowMaterializationSpecResolver(e){return this.workflowExecutor.registerWorkflowMaterializationSpecResolver(e)}registerWorkspaceRootResolver(e){return this.workspaceRootResolvers.add(e),()=>{this.workspaceRootResolvers.delete(e)}}async resolveWorkspaceRoot(e){for(let t of this.workspaceRootResolvers){let n=await t(e);if(n!==void 0)return n}}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.triggerReconcilerInstance.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.triggerReconcilerInstance.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const Ui=ht(`makaio.workflow-engine`);function Wi(e){return{name:Ui.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[mt(kt.name),mt(At.name,void 0,!0)],critical:!0,namespaces:[st,re],storage:{registerHandlers:xt(Or)},create:t=>new Hi(t.bus,{...e,automationTriggerBindingRuntime:()=>t.getService(At)})}}const Gi=Wi();export{fn as _,Vi as a,Si as c,mi as d,si as f,un as g,dn as h,Hi as i,hi as l,Or as m,Wi as n,Pi as o,ri as p,Gi as r,Oi as s,Ui as t,gi as u};
|