@makaio/framework 1.0.0-dev-1788897280508 → 1.0.0-dev-1788914730846
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/2020-Bl3Yx3In.mjs +1 -0
- 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 +6 -6
- package/dist/adapters/node.d.mts +1 -1
- package/dist/adapters/node.mjs +1 -1
- package/dist/artifact-DtmJR46g.mjs +1 -0
- package/dist/{attempt-record-codec-CqKq0NIB.mjs → attempt-record-codec-6jpayBMY.mjs} +1 -1
- package/dist/authority-state-bootstrap-DnwkMieA.mjs +1 -0
- package/dist/bus/index.mjs +1 -1
- package/dist/{capabilities-DGqMG9M3.mjs → capabilities-BhJ3wzI8.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-B9wr0b972.mjs +1 -0
- package/dist/{code-execution-Mo1jztUH.mjs → code-execution-DRCzkGzO.mjs} +1 -1
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +3 -3
- package/dist/contracts/artifact/index.mjs +1 -1
- package/dist/contracts/auth/index.d.mts +2 -2
- package/dist/contracts/automation-trigger/index.d.mts +3 -3
- package/dist/contracts/canonical-model/index.d.mts +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/code-execution/index.d.mts +1 -1
- package/dist/contracts/common/index.d.mts +1 -1
- package/dist/contracts/config/index.d.mts +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/harness/index.d.mts +1 -1
- package/dist/contracts/host/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +104 -104
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +2 -2
- package/dist/contracts/materialization/index.mjs +1 -1
- package/dist/contracts/model-registry/index.d.mts +1 -1
- package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
- package/dist/contracts/platform/index.d.mts +1 -1
- package/dist/contracts/provider/index.d.mts +2 -2
- package/dist/contracts/reaction/index.d.mts +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/shared/index.d.mts +2 -2
- package/dist/contracts/skill/index.d.mts +1 -1
- package/dist/contracts/telemetry/index.d.mts +1 -1
- package/dist/contracts/timeout/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/{contribution-BoTMoHVB.d.mts → contribution-B4t0OXKs.d.mts} +2 -2
- package/dist/{definition-BgY763Q4.d.mts → definition-Bs5hzhsT.d.mts} +1 -1
- package/dist/{detached-extension-handle-B9c_6Pcb.mjs → detached-extension-handle-CgJiXaqv.mjs} +1 -1
- package/dist/dist-CfANkKSb.mjs +1 -0
- package/dist/{execution-attempt-owner-recovery-BNERIDH0.mjs → execution-attempt-owner-recovery-CdH04iwP.mjs} +1 -1
- package/dist/{execution-attempt-repository-CtFZfBfp.d.mts → execution-attempt-repository-dE889kHj.d.mts} +553 -155
- package/dist/{extension-C4lFc8-j.mjs → extension-C1CwxkCN.mjs} +1 -1
- package/dist/{filesystem-service-DGqU-6x-.mjs → filesystem-service-yB8KhUGz.mjs} +1 -1
- package/dist/framework-packages-B3SQPHD7.mjs +1 -0
- package/dist/git/index.mjs +1 -1
- package/dist/{globby-BT0rrriG.mjs → globby-z2SR0jRo.mjs} +1 -1
- package/dist/{hook-responses-BSCAdJ3i.d.mts → hook-responses-Cs8A07ZP.d.mts} +1 -1
- package/dist/{index-LwOw7ZLk2.d.mts → index-Aomg_qFA2.d.mts} +164 -32
- package/dist/{index-RpG4EP3u.d.mts → index-B6aoVzdA.d.mts} +1 -1
- package/dist/{index-BVRQOZbm.d.mts → index-BHZlMm_I.d.mts} +1 -1
- package/dist/{index-BkY6zO7p.d.mts → index-BQv9mUzn.d.mts} +2 -1
- package/dist/{index-oucWFlFP2.d.mts → index-B_rFtKIO2.d.mts} +12 -12
- package/dist/{index-D0DfEO45.d.mts → index-BfXf_CcM.d.mts} +14 -16
- package/dist/{index-DIYgFhTZ2.d.mts → index-BgY_UzH82.d.mts} +4 -4
- package/dist/{index-BZtasAZP.d.mts → index-BjcJH3I-.d.mts} +1 -1
- package/dist/{index-nPpqnP7P.d.mts → index-BtC1JP5D.d.mts} +1 -1
- package/dist/{index-PTp68NH1.d.mts → index-C50sVXO7.d.mts} +780 -66
- package/dist/{index-CYwbfa0_.d.mts → index-CKvOECeR.d.mts} +2 -2
- package/dist/{index-DJ0Muy2s.d.mts → index-CRQ2U0jE.d.mts} +9 -9
- package/dist/{index-BZlmWCcW.d.mts → index-CmAJx-cX.d.mts} +3 -3
- package/dist/{index-F6hV4tWI.d.mts → index-CtlurrJF.d.mts} +98 -44
- package/dist/{index-Cau0jTTM.d.mts → index-D3-21gUP.d.mts} +1 -1
- package/dist/{index-CQtttPGm.d.mts → index-D7j6v0-L.d.mts} +1 -1
- package/dist/{index-mylsCg6V2.d.mts → index-DI-1HK7v2.d.mts} +1 -1
- package/dist/{index-BdbYIlDL.d.mts → index-DRryNq7D.d.mts} +13 -13
- package/dist/{index-R2BZejEz.d.mts → index-DfYMmJDZ.d.mts} +1963 -408
- package/dist/{index-CoGo6HFE.d.mts → index-DzeUtJtE.d.mts} +8 -8
- package/dist/{index-CYmQt2lF.d.mts → index-KZ4YllPp.d.mts} +81 -81
- package/dist/{index-C_OLvAr_.d.mts → index-ZEQDAT9K.d.mts} +1 -1
- package/dist/{index-dL0Oet1j.d.mts → index-fzrPfhS0.d.mts} +1 -1
- package/dist/{index-CDLHgV7v.d.mts → index-jXU4dntl.d.mts} +16 -16
- package/dist/{index-BcTwLu9C2.d.mts → index-ksNVQHeY2.d.mts} +8 -8
- package/dist/kernel/cli/index.d.mts +2 -2
- package/dist/kernel/cli/register.d.mts +1 -1
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +5 -5
- package/dist/kernel/namespace/index.d.mts +1 -1
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/kernel/providers/index.d.mts +1 -1
- package/dist/kernel/window/index.d.mts +1 -1
- package/dist/kind-registration-DggkrLkv.mjs +1 -0
- package/dist/{lib-hwdGyO-m.mjs → lib-0MqNtDuH.mjs} +5 -5
- package/dist/{lib-B8Yv4IY-.mjs → lib-dlyJT26K.mjs} +1 -1
- package/dist/{load-extensions-CNT2Nd9h.mjs → load-extensions-BHTj3d_P.mjs} +1 -1
- package/dist/{load-extensions-D0yT_Kta.d.mts → load-extensions-un9Md47Z.d.mts} +1 -1
- package/dist/{materialization-Dx1z_MDj.mjs → materialization-CDemi12q.mjs} +1 -1
- package/dist/mcp-http-server/index.mjs +4 -4
- package/dist/{namespace-D1qK-Ed3.d.mts → namespace-CePc0U4N.d.mts} +2 -2
- package/dist/{namespace-C7wggVcn.d.mts → namespace-Ciyw6FxO.d.mts} +18 -18
- package/dist/{namespace-BY5-nA4j.d.mts → namespace-CizM5GXh.d.mts} +6 -6
- package/dist/{namespace-WeSQXdAL.d.mts → namespace-D9ToNQPp.d.mts} +25 -25
- package/dist/{namespace-CPC1vbOu.d.mts → namespace-DF9m7PLi.d.mts} +5 -5
- package/dist/{namespace-Dh5fTXYt.d.mts → namespace-thsiHTFH.d.mts} +2 -2
- 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/node/transports/index.d.mts +12 -1
- package/dist/node/transports/index.mjs +2 -2
- package/dist/{orchestrator-shared-BKMtjTE9.mjs → orchestrator-shared-5vhs4wvU.mjs} +1 -1
- package/dist/{package-C9XYuN9J.d.mts → package-BR0pO5BI.d.mts} +101 -17
- package/dist/package-DKfzsJVl.mjs +7 -0
- package/dist/package.json +1 -1
- package/dist/packages-7CsXP86g.mjs +1 -0
- 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 +7 -6
- package/dist/runtime-node/index.mjs +24 -24
- package/dist/runtime-node/makaio-config.d.mts +1 -1
- package/dist/runtime-node/makaio-config.mjs +1 -1
- package/dist/runtime-node/workflow-execution-bus-access.d.mts +16 -1
- package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
- package/dist/runtime-node/workflow-worker/index.mjs +1 -1
- package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
- package/dist/{schema-wArHaxA9.d.mts → schema-7GukLoee.d.mts} +1 -1
- package/dist/{schemas-C5FreSE0.d.mts → schemas-6FlRULSc.d.mts} +211 -79
- package/dist/schemas-BahXrOYa.mjs +1 -0
- package/dist/{schemas-gfrOgGau.d.mts → schemas-CKGHlsMd.d.mts} +1 -1
- package/dist/{schemas-DmE-a0kN.d.mts → schemas-CkOVC3ip.d.mts} +4 -4
- package/dist/{schemas-BjNlwTDl.d.mts → schemas-DQ5iRisA.d.mts} +2 -2
- package/dist/{schemas-BSBb1KFq.d.mts → schemas-Df52igU4.d.mts} +8 -8
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- package/dist/services/adapter-subsystem/index.d.mts +3 -3
- package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/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 +4 -4
- 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/schemas.d.mts +1 -1
- package/dist/services/filesystem/index.d.mts +1 -1
- package/dist/services/filesystem/index.mjs +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/git/namespace.d.mts +2 -2
- package/dist/services/git/namespace.mjs +1 -1
- package/dist/services/git/schemas.d.mts +2 -2
- package/dist/services/git/schemas.mjs +1 -1
- package/dist/services/harness/index.mjs +1 -1
- package/dist/services/index.d.mts +55 -55
- 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 +1 -1
- 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-runtime/index.mjs +1 -1
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/index.d.mts +9 -9
- package/dist/services/session/messages/namespace.d.mts +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/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-editor/index.d.mts +1 -1
- package/dist/services/settings/index.d.mts +3 -3
- package/dist/services/settings/namespace.d.mts +8 -8
- package/dist/services/settings/namespace.mjs +1 -1
- package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/settings/storage/index.d.mts +3 -3
- package/dist/services/settings/storage/providers-namespace.d.mts +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/{src-D4Gx0QHf.mjs → src-Dlpw-Gh5.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/{tools-Cyo6BuGM.mjs → tools-2INrWlnS.mjs} +1 -1
- package/dist/{transition-CwMPKBjz.d.mts → transition-C1rMI1ue.d.mts} +2 -2
- package/dist/{types-BOF825V52.d.mts → types-CR415CdC2.d.mts} +1 -1
- package/dist/{types-Dg_acP9p.d.mts → types-DIHb_m2K.d.mts} +29 -29
- package/dist/ui-kernel/index.d.mts +1 -1
- package/dist/ui-kernel/pages/schemas.d.mts +1 -1
- package/dist/{view-builder-D76L0Db8.d.mts → view-builder-Dt9UEsPc.d.mts} +1 -1
- package/dist/{worker-9X0QNB1k.mjs → worker-Bn0x5MSH.mjs} +1 -1
- package/dist/worker-qgJToDTN.mjs +1 -0
- package/dist/workflow-B6C3Pf66.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 +21 -20
- 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 +2 -2
- package/dist/workflow-engine/provider-operation.mjs +1 -1
- package/dist/workflow-engine/testing/conformance.d.mts +1 -1
- package/dist/workflow-engine/testing/conformance.mjs +2 -2
- package/dist/workflow-engine/testing/index.d.mts +3 -2
- 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 +86 -48
- package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
- package/dist/{workflow-transitions-B7HtjuAn.mjs → workflow-transitions-BbhM_zPm.mjs} +1 -1
- package/dist/workflow-worker-BSJ6F4P0.mjs +2 -0
- package/package.json +1 -1
- package/dist/artifact-OnwP6uaD.mjs +0 -1
- package/dist/authority-state-bootstrap-rnsTk0u7.mjs +0 -1
- package/dist/code-execution-C2PgBdmE.mjs +0 -1
- package/dist/framework-packages-CZJDukan.mjs +0 -1
- package/dist/kind-registration-BNhVCSaT.mjs +0 -1
- package/dist/package-D7c2HC-S.mjs +0 -7
- package/dist/packages-BhhBcPgz.mjs +0 -1
- package/dist/provider-operation-BwrIrOeY.d.mts +0 -207
- package/dist/schemas-hzbKeyyt.mjs +0 -1
- package/dist/worker-BwUhRg7i.mjs +0 -1
- package/dist/workflow-B3MWrYhG.mjs +0 -1
- package/dist/workflow-worker-zYb2UguP.mjs +0 -2
- /package/dist/{adapter-auth-runtime-DGY1CDxj.mjs → adapter-auth-runtime-BnPqQChk.mjs} +0 -0
- /package/dist/{adapter-binding-fGIz-ss3.d.mts → adapter-binding-BU7STlfd.d.mts} +0 -0
- /package/dist/{ajv-DWgn_plp.mjs → ajv-Dtk5hCZS.mjs} +0 -0
- /package/dist/{attempt-fixtures-Dpfgqll0.mjs → attempt-fixtures-C-jQE_7B.mjs} +0 -0
- /package/dist/{base-orchestrator-BeLqYKJG.d.mts → base-orchestrator-DXiejwQ3.d.mts} +0 -0
- /package/dist/{bootstrap-start-client-BYoxrgMk.mjs → bootstrap-start-client-Bdv-_2Q9.mjs} +0 -0
- /package/dist/{caller-owned-adapter-stub-egWCuKcE.mjs → caller-owned-adapter-stub-B-Sq7ZvF.mjs} +0 -0
- /package/dist/{capability-service-BlYnun2M.d.mts → capability-service-CsWaOwvH.d.mts} +0 -0
- /package/dist/{client-CtOWHpFB.d.mts → client-DP4ksY9q.d.mts} +0 -0
- /package/dist/{client-binary-version-verifier-BwmToeS1.d.mts → client-binary-version-verifier-BoXRTyae.d.mts} +0 -0
- /package/dist/{client-binary-version-verifier-sv-Uv0lB.mjs → client-binary-version-verifier-DHBAzg3-.mjs} +0 -0
- /package/dist/{clients-namespace-Bf73bcZh.d.mts → clients-namespace-BVDmj8uV.d.mts} +0 -0
- /package/dist/{config-namespace-BbLLd4V0.d.mts → config-namespace-BMOKEuyf.d.mts} +0 -0
- /package/dist/{create-static-mount-BQnyEUH1.mjs → create-static-mount-GSdckRQx.mjs} +0 -0
- /package/dist/{cross-spawn-DPrJR9Nq.mjs → cross-spawn-Bx_VEdpd.mjs} +0 -0
- /package/dist/{cursor-storage-iJ6vBOWd.mjs → cursor-storage-Co4itf44.mjs} +0 -0
- /package/dist/{definition-aS9AM2ht.d.mts → definition-ByVJ3n6o.d.mts} +0 -0
- /package/dist/{descriptor-to-package-FBkLjHZo.mjs → descriptor-to-package-CZLujoiv.mjs} +0 -0
- /package/dist/{drizzle-CIf_jdYI.mjs → drizzle-me-95ICP.mjs} +0 -0
- /package/dist/{esm-BH4Kmq3r.mjs → esm-DILYVXmW.mjs} +0 -0
- /package/dist/{event-m7_IdhOS.mjs → event-DmQPb5MB.mjs} +0 -0
- /package/dist/{execution-attempt-repository-D_qR7NyG.mjs → execution-attempt-repository-DXyh1hgz.mjs} +0 -0
- /package/dist/{execution-target-CqaBmnvX.mjs → execution-target-B9jZgDQz.mjs} +0 -0
- /package/dist/{extension-context-41A1ZUus.d.mts → extension-context-Cx8CetW3.d.mts} +0 -0
- /package/dist/{extension-discovery-DNB1VVsV.d.mts → extension-discovery-C0Nj5EVZ.d.mts} +0 -0
- /package/dist/{extension-package-provenance-CTYdo0yF.mjs → extension-package-provenance-BzvG6rDO.mjs} +0 -0
- /package/dist/{filesystem-service-DOrm4Llq.d.mts → filesystem-service-C6D7oABi.d.mts} +0 -0
- /package/dist/{handler-COkV00I9.mjs → handler-BYQPNm8O.mjs} +0 -0
- /package/dist/{index-Cb3NfGSV2.d.mts → index-B04VAxlm2.d.mts} +0 -0
- /package/dist/{index-jW7MJ2_q.d.mts → index-B7g7e7_f.d.mts} +0 -0
- /package/dist/{index-BKvzOrbF.d.mts → index-B9-1l1oh.d.mts} +0 -0
- /package/dist/{index-ClJjlOox.d.mts → index-BGWkmG9i.d.mts} +0 -0
- /package/dist/{index-BbAqoQmv.d.mts → index-BR7IiCib.d.mts} +0 -0
- /package/dist/{index-BiXqOfhl.d.mts → index-B_VcKELo.d.mts} +0 -0
- /package/dist/{index-BBq5I7SB2.d.mts → index-BbjxBrcp2.d.mts} +0 -0
- /package/dist/{index-Bq4PHWe9.d.mts → index-BnLp-7qH.d.mts} +0 -0
- /package/dist/{index-Bg5iXHk5.d.mts → index-BpWoCe22.d.mts} +0 -0
- /package/dist/{index-BO8n7zAS.d.mts → index-Bpv8EpBa.d.mts} +0 -0
- /package/dist/{index-Ce_l029J.d.mts → index-BrRCVo9r.d.mts} +0 -0
- /package/dist/{index-z-YJG2cw.d.mts → index-CHuB40EK.d.mts} +0 -0
- /package/dist/{index-CavvxFdG2.d.mts → index-CIV2G6uX2.d.mts} +0 -0
- /package/dist/{index-CgVdz5IV.d.mts → index-CNOqYviR.d.mts} +0 -0
- /package/dist/{index-Bk865qJX.d.mts → index-CSEhxhIc.d.mts} +0 -0
- /package/dist/{index-gK54T8Am.d.mts → index-C_R6ifn9.d.mts} +0 -0
- /package/dist/{index-CUHWylh4.d.mts → index-D3_QOfke.d.mts} +0 -0
- /package/dist/{index-BB4EWIf3.d.mts → index-D6qlh6Td.d.mts} +0 -0
- /package/dist/{index-BjaQsfAr.d.mts → index-DLlTuugR.d.mts} +0 -0
- /package/dist/{index-VVJqONaI.d.mts → index-DOKPbF-y2.d.mts} +0 -0
- /package/dist/{index-BJjdUzfw2.d.mts → index-DZv9yNKF2.d.mts} +0 -0
- /package/dist/{index-DR9-fFwc.d.mts → index-DxaQ-ceV.d.mts} +0 -0
- /package/dist/{index-zvgQ8ErF.d.mts → index-HRn0Kun0.d.mts} +0 -0
- /package/dist/{index-Ck5amD5_.d.mts → index-IkeLI7uY.d.mts} +0 -0
- /package/dist/{index-Q29tcu5N.d.mts → index-_Ngf4KAa.d.mts} +0 -0
- /package/dist/{index-l5HeyxKn.d.mts → index-l9WK9El6.d.mts} +0 -0
- /package/dist/{json-value-C57MkQrB.d.mts → json-value-DyMQrwGz.d.mts} +0 -0
- /package/dist/{jsonl-transport-QQuABrN7.mjs → jsonl-transport-Dfv3RLzi.mjs} +0 -0
- /package/dist/{lib-Sx8gBJvV.mjs → lib-BdfAJKDj.mjs} +0 -0
- /package/dist/{model-registry-DNHDnyvs.mjs → model-registry-DlUErRRt.mjs} +0 -0
- /package/dist/{namespace-BGgY903U.mjs → namespace-B8kUQpwo.mjs} +0 -0
- /package/dist/{namespace-By3nEmBH.d.mts → namespace-B_Gw6BMX.d.mts} +0 -0
- /package/dist/{namespace-DInMixc8.d.mts → namespace-CQaL10rI.d.mts} +0 -0
- /package/dist/{namespace-DE3oGhaN.d.mts → namespace-CcHA54E1.d.mts} +0 -0
- /package/dist/{namespace-DHrItZyM.mjs → namespace-ChjzkJIl.mjs} +0 -0
- /package/dist/{namespace-DkAlBY9o.d.mts → namespace-Ct2DKREI.d.mts} +0 -0
- /package/dist/{namespace-DENdNdK0.d.mts → namespace-DdcRYk7b.d.mts} +0 -0
- /package/dist/{namespace-Ca4sQ8X-.d.mts → namespace-DtXYm32M.d.mts} +0 -0
- /package/dist/{namespace-Bn-ryJn5.d.mts → namespace-nE7vRctI.d.mts} +0 -0
- /package/dist/{namespace-DP0WWpTO.d.mts → namespace-sTMm1voF.d.mts} +0 -0
- /package/dist/{orchestrator-shared-2vuCvljs.d.mts → orchestrator-shared-CYnIz5Zd.d.mts} +0 -0
- /package/dist/{out-Rz-t3WeC.mjs → out-Cn6vBxlH.mjs} +0 -0
- /package/dist/{package-Tt2uoAFf.mjs → package-BUSXHPOT.mjs} +0 -0
- /package/dist/{package-buHQFmTH.mjs → package-BiZ6ehWk.mjs} +0 -0
- /package/dist/{package-DfjGt5oK.mjs → package-D4eLGGv4.mjs} +0 -0
- /package/dist/{packages-DAqep89i.d.mts → packages-DtsjAYuf.d.mts} +0 -0
- /package/dist/{providers-namespace-C56pGeTO.d.mts → providers-namespace-BxknJ03z.d.mts} +0 -0
- /package/dist/{quick-lru-uXa2PNb5.mjs → quick-lru-CVryNCTx.mjs} +0 -0
- /package/dist/{registry-CZf8VGBh.mjs → registry-Q9gCZtxz.mjs} +0 -0
- /package/dist/{schemas-BsZJHdvY.d.mts → schemas-0VbIjfrW.d.mts} +0 -0
- /package/dist/{schemas-DDCAGKRi.mjs → schemas-BFgsIiSb.mjs} +0 -0
- /package/dist/{schemas-B2Q284-G.d.mts → schemas-Cg2gAars.d.mts} +0 -0
- /package/dist/{schemas-CITR9cWN.d.mts → schemas-CmUWeOkr.d.mts} +0 -0
- /package/dist/{schemas-BMGJLkdK2.d.mts → schemas-CsRcSlvA2.d.mts} +0 -0
- /package/dist/{schemas-wPB7RnHB.d.mts → schemas-DzDVjYjt.d.mts} +0 -0
- /package/dist/{schemas-B0zhTfet.d.mts → schemas-KDl7p-wr.d.mts} +0 -0
- /package/dist/{schemas-BJKx29Sp.d.mts → schemas-Yp3PvwsM.d.mts} +0 -0
- /package/dist/{server-lifecycle-CREtXADx.d.mts → server-lifecycle-Ck6_8o8v.d.mts} +0 -0
- /package/dist/{server-lifecycle-AvBVeCFR.mjs → server-lifecycle-hNz8U-QJ.mjs} +0 -0
- /package/dist/{session-lineage-CRLvurB-.d.mts → session-lineage-BtvnGkoC.d.mts} +0 -0
- /package/dist/{src-DnLncoLg.mjs → src-Du_285FN.mjs} +0 -0
- /package/dist/{storage-namespace-JBh9nkKw.d.mts → storage-namespace-CRdQoXZ9.d.mts} +0 -0
- /package/dist/{storage-namespace-CH4j0_Zs.mjs → storage-namespace-Dtz2G1if.mjs} +0 -0
- /package/dist/{storage-namespace-definition-C0mnpnC_.d.mts → storage-namespace-definition-NBw1Y8Pa.d.mts} +0 -0
- /package/dist/{supports-color-BBMFnbC4.mjs → supports-color-BNmyqLq0.mjs} +0 -0
- /package/dist/{tool-approval-service-7mzJVMo_.mjs → tool-approval-service-rpV94znP.mjs} +0 -0
- /package/dist/{tray-menu-service-thAhpcPA.mjs → tray-menu-service-TWrmvXSo.mjs} +0 -0
- /package/dist/{types-9ldZyQTb.d.mts → types-BFv-EK2G.d.mts} +0 -0
- /package/dist/{types-DJuxNrac.d.mts → types-BcGXdeva.d.mts} +0 -0
- /package/dist/{types-eCGV_g6P.d.mts → types-CUCFeisO.d.mts} +0 -0
- /package/dist/{types-xXv0lUeU.d.mts → types-CXrp5ldz.d.mts} +0 -0
- /package/dist/{types-BMkn9jOe.d.mts → types-D4N56a4O.d.mts} +0 -0
- /package/dist/{types-CjjNAiHa.mjs → types-D9GJ7FyQ.mjs} +0 -0
- /package/dist/{window-registry-CGaYVD7l.d.mts → window-registry-Chi2qJ5k.d.mts} +0 -0
package/dist/adapters/node.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as LogImporter, i as LogFileChangeEvent, n as LogOrchestratorConfig, t as BaseLogOrchestrator } from "../base-orchestrator-
|
|
1
|
+
import { _ as LogImporter, i as LogFileChangeEvent, n as LogOrchestratorConfig, t as BaseLogOrchestrator } from "../base-orchestrator-DXiejwQ3.mjs";
|
|
2
2
|
|
|
3
3
|
//#region adapters/core/src/log-importer/jsonl-parser.d.ts
|
|
4
4
|
/**
|
package/dist/adapters/node.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as e,t}from"../chunk-DTipWd-i.mjs";import{i as n,r}from"../cursor-storage-
|
|
1
|
+
import{o as e,t}from"../chunk-DTipWd-i.mjs";import{i as n,r}from"../cursor-storage-Co4itf44.mjs";import{t as i}from"../globby-z2SR0jRo.mjs";import*as a from"node:fs/promises";import*as o from"node:path";import{MakaioBus as s}from"@makaio/framework/bus";import{AdapterSubjects as c,ClientSubjects as l,SessionStorageSubjects as u,SessionSubjects as d}from"@makaio/framework/contracts";const f=65536;async function p(e){let{filePath:t,startOffset:n=0}=e,r=[],i=[],o=n,s;try{s=await a.open(t,`r`);let e=await s.stat();if(n>=e.size)return{records:r,bytesRead:n,errors:i};let c=Buffer.alloc(f),l=``,u=n,d=0;for(n>0&&(d=await v(s,n));u<e.size;){let{bytesRead:e}=await s.read(c,0,f,u);if(e===0)break;l+=c.toString(`utf8`,0,e),u+=e;let t=l.split(`
|
|
2
2
|
`),n=t.pop();for(let e of t){if(d++,e.trim()===``){o+=Buffer.byteLength(e,`utf8`)+1;continue}let t=g(e,d);t.success?r.push(t.record):i.push(t.error),o+=Buffer.byteLength(e,`utf8`)+1}l=n??``}return{records:r,bytesRead:o,errors:i}}finally{s&&await s.close()}}async function m(e,t){let n=[],r;try{r=await a.open(e,`r`);let i=Buffer.alloc(f),o=``,s=0;for(;n.length<t;){let{bytesRead:e}=await r.read(i,0,f,s);if(e===0)break;o+=i.toString(`utf8`,0,e),s+=e;let a=o.split(`
|
|
3
3
|
`);o=a.pop()??``;for(let e of a){if(n.length>=t)break;let r=e.trim();if(r!==``)try{n.push(JSON.parse(r))}catch{}}}return n}finally{r&&await r.close()}}async function h(e,t){let n;try{n=await a.open(e,`r`);let r=Buffer.alloc(f),i=``,o=0;for(;;){let{bytesRead:e}=await n.read(r,0,f,o);if(e===0)break;i+=r.toString(`utf8`,0,e),o+=e;let a=i.split(`
|
|
4
4
|
`);i=a.pop()??``;for(let e of a){let n=e.trim();if(n!==``)try{if(t(JSON.parse(n)))return!0}catch{}}}return!1}finally{n&&await n.close()}}function g(e,t){try{return{success:!0,record:JSON.parse(e)}}catch(n){return{success:!1,error:{line:t,error:n instanceof Error?n.message:String(n),content:_(e)}}}}function _(e){return e.length<=200?e:e.slice(0,200)+`...`}async function v(e,t){let n=0,r=Buffer.alloc(f),i=0;for(;i<t;){let a=Math.min(f,t-i),{bytesRead:o}=await e.read(r,0,a,i);if(o===0)break;for(let e=0;e<o;e++)r[e]===10&&n++;i+=o}return n}var y=e(t(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}))(),1),b=class e extends Error{name=`TimeoutError`;constructor(t,n){super(t,n),Error.captureStackTrace?.(this,e)}};const x=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function S(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:a={setTimeout,clearTimeout},signal:o}=t,s,c,l=new Promise((t,l)=>{if(typeof n!=`number`||Math.sign(n)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(o?.aborted){l(x(o));return}if(o&&(c=()=>{l(x(o))},o.addEventListener(`abort`,c,{once:!0})),e.then(t,l),n===1/0)return;let u=new b;s=a.setTimeout.call(void 0,()=>{if(r){try{t(r())}catch(e){l(e)}return}typeof e.cancel==`function`&&e.cancel(),i===!1?t():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${n} milliseconds`,l(u))},n)}).finally(()=>{l.clear(),c&&o&&o.removeEventListener(`abort`,c)});return l.clear=()=>{a.clearTimeout.call(void 0,s),s=void 0},l}function C(e,t,n){let r=0,i=e.length;for(;i>0;){let a=Math.trunc(i/2),o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}var w=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:r}=t??{},{size:i}=this,a={priority:n,id:r,run:e};if(i===0){this.#e.length=0,this.#t=0,this.#e.push(a);return}if(this.#e.at(-1).priority>=n){this.#e.push(a);return}this.#n();let o=C(this.#e,a,(e,t)=>t.priority-e.priority);this.#e.splice(o,0,a)}setPriority(e,t){let n=this.#e.findIndex((t,n)=>n>=this.#t&&t.id===e);if(n===-1)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[r]=this.#e.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((t,n)=>n<this.#t?!1:typeof e==`string`?t.id===e:t.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>100&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let r=this.#e[n];r.priority===e.priority&&t.push(r.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}},T=class extends y.default{#e;#t;#n=0;#r;#i=!1;#a=!1;#o;#s=0;#c=0;#l;#u;#d;#f=[];#p=0;#m;#h;#g=0;#_;#v;#y=1n;#b=new Map;#x=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:w,strict:!1,...e},!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===1/0)throw TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===1/0||e.interval===0,this.#r=e.intervalCap,this.#o=e.interval,this.#d=e.strict,this.#m=new e.queueClass,this.#h=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#v=e.autoStart===!1,this.#z()}#S(e){for(;this.#p<this.#f.length;){let t=this.#f[this.#p];if(t!==void 0&&e-t>=this.#o)this.#p++;else break}(this.#p>100&&this.#p>this.#f.length/2||this.#p===this.#f.length)&&(this.#f=this.#f.slice(this.#p),this.#p=0)}#C(e){this.#d?this.#f.push(e):this.#n++}#w(){this.#d?this.#f.length>this.#p&&this.#f.pop():this.#n>0&&this.#n--}#T(){return this.#f.length-this.#p}get#E(){return this.#t?!0:this.#d?this.#T()<this.#r:this.#n<this.#r}get#D(){return this.#g<this.#_}#O(){this.#g--,this.#g===0&&this.emit(`pendingZero`),this.#P(),this.emit(`next`)}#k(){this.#u=void 0,this.#I(),this.#F()}#A(e){if(this.#d){if(this.#S(e),this.#T()>=this.#r){let t=this.#f[this.#p],n=this.#o-(e-t);return this.#j(n),!0}return!1}if(this.#l===void 0){let t=this.#s-e;if(t<0){if(this.#c>0){let t=e-this.#c;if(t<this.#o)return this.#j(this.#o-t),!0}this.#n=this.#e?this.#g:0}else return this.#j(t),!0}return!1}#j(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#k()},e))}#M(){this.#l&&=(clearInterval(this.#l),void 0)}#N(){this.#u&&=(clearTimeout(this.#u),void 0)}#P(){if(this.#m.size===0){if(this.#M(),this.emit(`empty`),this.#g===0){if(this.#N(),this.#d&&this.#p>0){let e=Date.now();this.#S(e)}this.emit(`idle`)}return!1}let e=!1;if(!this.#v){let t=Date.now(),n=!this.#A(t);if(this.#E&&this.#D){let r=this.#m.dequeue();this.#t||(this.#C(t),this.#B()),this.emit(`active`),r(),n&&this.#F(),e=!0}}return e}#F(){this.#t||this.#l!==void 0||this.#d||(this.#l=setInterval(()=>{this.#I()},this.#o),this.#s=Date.now()+this.#o)}#I(){this.#d||(this.#n===0&&this.#g===0&&this.#l&&this.#M(),this.#n=this.#e?this.#g:0),this.#L(),this.#B()}#L(){for(;this.#P(););}get concurrency(){return this.#_}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#_=e,this.#L()}setPriority(e,t){if(typeof t!=`number`||!Number.isFinite(t))throw TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#m.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#y++).toString()},new Promise((n,r)=>{let i=Symbol(`task-${t.id}`),a=()=>void 0,o=async()=>{a(),this.#g++,this.#b.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let o;try{try{t.signal?.throwIfAborted()}catch(e){throw this.#V(),this.#b.delete(i),e}this.#c=Date.now();let r=e({signal:t.signal});if(t.timeout&&(r=S(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#g} running, ${this.#m.size} waiting)`})),t.signal){let{signal:e}=t;r=Promise.race([r,new Promise((t,n)=>{o=()=>{n(e.reason)},e.addEventListener(`abort`,o,{once:!0})})])}let a=await r;n(a),this.emit(`completed`,a)}catch(e){r(e),this.emit(`error`,e)}finally{o&&t.signal?.removeEventListener(`abort`,o),this.#b.delete(i),queueMicrotask(()=>{this.#O()})}};this.#m.enqueue(o,t);let s=()=>{if(this.#m instanceof w){this.#m.remove(o);return}this.#m.remove?.(t.id)};if(t.signal){let{signal:e}=t,n=()=>{a(),s(),r(e.reason),this.#P(),this.emit(`next`)};if(a=()=>{e.removeEventListener(`abort`,n),this.#x.delete(a)},e.aborted){n();return}e.addEventListener(`abort`,n,{once:!0}),this.#x.add(a)}this.emit(`add`),this.#P()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#v?(this.#v=!1,this.#L(),this):this}pause(){this.#v=!0}clear(){for(let e of this.#x)e();this.#m=new this.#h,this.#M(),this.#H(),this.emit(`empty`),this.#g===0&&(this.#N(),this.emit(`idle`)),this.emit(`next`)}async onEmpty(){this.#m.size!==0&&await this.#R(`empty`)}async onSizeLessThan(e){this.#m.size<e||await this.#R([`next`,`active`],()=>this.#m.size<e)}async onIdle(){this.#g===0&&this.#m.size===0||await this.#R(`idle`)}async onPendingZero(){this.#g!==0&&await this.#R(`pendingZero`)}async onRateLimit(){this.isRateLimited||await this.#R(`rateLimit`)}async onRateLimitCleared(){this.isRateLimited&&await this.#R(`rateLimitCleared`)}onError(){return new Promise((e,t)=>{let n=e=>{this.off(`error`,n),t(e)};this.on(`error`,n)})}async#R(e,t){let n=Array.isArray(e)?e:[e];return new Promise(e=>{let r=()=>{if(!(t&&!t())){for(let e of n)this.off(e,r);e()}};for(let e of n)this.on(e,r)})}get size(){return this.#m.size}sizeBy(e){return this.#m.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#v}#z(){this.#t||(this.on(`add`,()=>{this.#m.size>0&&this.#B()}),this.on(`next`,()=>{this.#B()}))}#B(){this.#t||this.#a||(this.#a=!0,queueMicrotask(()=>{this.#a=!1,this.#H()}))}#V(){this.#t||(this.#w(),this.#B())}#H(){let e=this.#i;if(this.#t||this.#m.size===0){e&&(this.#i=!1,this.emit(`rateLimitCleared`));return}let t;if(this.#d){let e=Date.now();this.#S(e),t=this.#T()}else t=this.#n;let n=t>=this.#r;n!==e&&(this.#i=n,this.emit(n?`rateLimit`:`rateLimitCleared`))}get isRateLimited(){return this.#i}get isSaturated(){return this.#g===this.#_&&this.#m.size>0||this.isRateLimited&&this.#m.size>0}get runningTasks(){return[...this.#b.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}},E=class{eventQueue;cursorQueue;onEventEmitted;constructor(e){this.onEventEmitted=e.onEventEmitted,this.eventQueue=new T({concurrency:1,interval:1e3,intervalCap:e.eventsPerSecond}),this.cursorQueue=new T({concurrency:1})}queueEvent(e){return this.eventQueue.add(async()=>{await s.emit(e.subject,e.payload),this.onEventEmitted()})}queueAfterEvents(e,t=[]){let n=Promise.all(t);return n.catch(()=>void 0),this.cursorQueue.add(async()=>{await n,await e()})}async drain(){await Promise.all([this.eventQueue.onIdle(),this.cursorQueue.onIdle()])}async onIdle(){await this.drain()}},D=class{options;emittery=new n;trackedFiles=new Map;pollTimer;isPolling=!1;isDisposed=!1;inFlightChecks=new Map;constructor(e){if(!o.isAbsolute(e.directory))throw Error(`Directory must be an absolute path: ${e.directory}`);this.options={directory:e.directory,pattern:e.pattern,pollIntervalMs:e.pollIntervalMs??1e4}}on(e,t){return this.emittery.on(e,t)}once(e,t){return this.emittery.once(e,t)}async start(){this.isDisposed||this.pollTimer===void 0&&(await this.poll(),this.pollTimer=setInterval(()=>{this.poll()},this.options.pollIntervalMs))}stop(){this.pollTimer!==void 0&&(clearInterval(this.pollTimer),this.pollTimer=void 0)}dispose(){this.isDisposed=!0,this.stop(),this.emittery.clearListeners(),this.trackedFiles.clear(),this.inFlightChecks.clear()}isRunning(){return this.pollTimer!==void 0}getTrackedFiles(){return this.trackedFiles}seedFromCursors(e){for(let t of e)this.trackedFiles.set(t.filePath,{size:t.bytesRead,mtimeMs:new Date(t.lastModified).getTime()})}async poll(){if(!this.isDisposed&&!this.isPolling){this.isPolling=!0;try{let e=await this.discoverFiles(),t=new Set(e);for(let e of this.trackedFiles.keys())if(!t.has(e)){if(this.isDisposed)return;this.trackedFiles.delete(e),await this.emittery.emit(`deleted`,{filePath:e})}for(let t of e)try{await this.runFileCheck(t)}catch(e){await this.emitWatcherError(e,t)}if(this.isDisposed)return;await this.emittery.emit(`polled`,{trackedFilePaths:new Set(this.trackedFiles.keys())})}catch(e){await this.emitWatcherError(e)}finally{this.isPolling=!1}}}async discoverFiles(){return i(this.options.pattern,{cwd:this.options.directory,absolute:!0,onlyFiles:!0})}async checkFile(e){if(this.isDisposed)return;let t=await a.stat(e);if(this.isDisposed)return;let n={size:t.size,mtimeMs:t.mtimeMs},r=this.trackedFiles.get(e);if(!r){if(this.trackedFiles.set(e,n),this.isDisposed){this.trackedFiles.delete(e);return}await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:`created`});return}if(n.mtimeMs!==r.mtimeMs){let i=n.size<r.size?`rotated`:`modified`;if(this.trackedFiles.set(e,n),this.isDisposed)return;await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:i})}}clearTrackedFile(e){return this.trackedFiles.delete(e)}clearAllTrackedFiles(){this.trackedFiles.clear()}triggerImmediatePoll(e){this.runFileCheck(e).catch(t=>{this.emitWatcherError(t,e)})}async runFileCheck(e){if(this.isDisposed)return;let t=this.inFlightChecks.get(e);if(t){await t;return}let n=(async()=>{try{await this.checkFile(e)}finally{this.inFlightChecks.delete(e)}})();this.inFlightChecks.set(e,n),await n}async emitWatcherError(e,t){let n=e instanceof Error?e:Error(String(e));try{await this.emittery.emit(`error`,{error:n,filePath:t})}catch(e){console.error(`[LogFileWatcher] Error listener failed:`,e instanceof Error?e.message:String(e))}}},O=class{watcher;constructor(e){this.watcher=new D(e)}isRunning(){return this.watcher.isRunning()}async start(){await this.watcher.start()}stop(){this.watcher.stop()}dispose(){this.watcher.dispose()}onChange(e){return this.watcher.on(`change`,e)}onError(e){return this.watcher.on(`error`,e)}onDeleted(e){return this.watcher.on(`deleted`,e)}onPolled(e){return this.watcher.on(`polled`,({trackedFilePaths:t})=>e(t))}getTrackedFileMtimeMs(e){return this.watcher.getTrackedFiles().get(e)?.mtimeMs}triggerImmediatePoll(e){this.watcher.triggerImmediatePoll(e)}seedFromCursors(e){this.watcher.seedFromCursors(e)}},k=class{filesProcessed=0;eventsEmitted=0;sessionsImported=new Set;sessionsSkipped=new Set;lastLoggedEventCount=0;lastLoggedSnapshot=``;reset(){this.filesProcessed=0,this.eventsEmitted=0,this.sessionsImported.clear(),this.sessionsSkipped.clear(),this.lastLoggedEventCount=0,this.lastLoggedSnapshot=``}recordFileProcessed(){this.filesProcessed++}recordEventEmitted(e){this.eventsEmitted++,!(this.eventsEmitted-this.lastLoggedEventCount<1e3)&&(console.info(`${e} Imported ${this.eventsEmitted} events (${this.sessionsImported.size} sessions)...`),this.lastLoggedEventCount=this.eventsEmitted)}recordSessionImported(e){this.sessionsImported.add(e)}recordSessionSkipped(e){this.sessionsSkipped.add(e)}hasActivity(){return this.eventsEmitted>0||this.filesProcessed>0}stoppedMessage(e){return`${e} Stopped - ${this.eventsEmitted} events from ${this.sessionsImported.size} sessions (${this.sessionsSkipped.size} skipped)`}logProgress(e){if(!this.hasActivity())return;let t=JSON.stringify({eventsEmitted:this.eventsEmitted,filesProcessed:this.filesProcessed,sessionsImported:this.sessionsImported.size,sessionsSkipped:this.sessionsSkipped.size});t!==this.lastLoggedSnapshot&&(this.lastLoggedSnapshot=t,console.info(`${e} Progress: ${this.eventsEmitted} events, ${this.sessionsImported.size} sessions, ${this.filesProcessed} files, ${this.sessionsSkipped.size} skipped`))}};function A(e){return async t=>{try{if(e!==void 0)try{let n=await s.requestOptional(l.runtime.isAdapterManaged,{adapterSessionId:t,clientId:e});if(n.handled&&n.data.managed)return!0}catch{}let n=await s.request(d.getByAdapterSessionId,{adapterSessionId:t});return n.session!==null&&!n.session.isImported}catch{return!1}}}var j=class{checkedSessions=new Map;inFlight=new Map;generations=new Map;async isSkipped(e,t,n){for(;;){let r=this.checkedSessions.get(e);if(r!==void 0)return r;let i=this.generations.get(e)??0,a=this.inFlight.get(e),o;if(a&&a.generation===i?o=a.promise:(o=t(e).then(t=>((this.generations.get(e)??0)===i&&(this.checkedSessions.set(e,t),t&&n(e)),t)).finally(()=>{let t=this.inFlight.get(e);t&&t.generation===i&&this.inFlight.delete(e)}),this.inFlight.set(e,{generation:i,promise:o})),await o,(this.generations.get(e)??0)===i){let t=this.checkedSessions.get(e);if(t!==void 0)return t;continue}}}invalidate(e){this.checkedSessions.delete(e),this.inFlight.delete(e),this.generations.set(e,(this.generations.get(e)??0)+1)}clear(){this.checkedSessions.clear(),this.inFlight.clear(),this.generations.clear()}};function M(e,t,n,r){return!n||!e||r===`rotated`?!1:new Date(e)>=t}function N(e,t,n){for(let r of n??[]){let n=r.line===void 0?``:` at line ${r.line}`;console.warn(`${e} Parse error in ${t}${n}: ${r.error}`)}}async function P(e,t,n,i){let{cursor:a}=await s.request(r.get,{filePath:e});return a&&a.bytesRead>0&&!a.sessionContext&&!t?(await s.request(r.delete,{filePath:e}).catch(()=>{}),i(n),`retry`):a}async function F(e,t,n,r,i,a){let o=await a.parseFile(e,0);N(i,e,o.errors);let s=a.validateRecords(o.records);s.length>0&&await a.handleFirstRead(e,s,o.bytesRead??0,t,n,0,r)}function I(e,t,n,r,i){let a=[];n&&(a.push(i(t.sessionEvent)),a.push(i(t.startedEvent)));let o=r(e,t);for(let e of o)a.push(i(e));return a}function L(e,t){let n=[];for(let r of e)n.push(t(r));return n}function R(e){return typeof e==`object`&&!!e&&`compactionDetected`in e&&e.compactionDetected===!0}function z(e,t,n){return{...e,state:n(t)}}var B=class{tasks=new Set;track(e){this.tasks.add(e),e.finally(()=>{this.tasks.delete(e)})}async drain(){for(;this.tasks.size>0;)await Promise.allSettled([...this.tasks])}},V=class{config;watcher;eventQueue;importer;managedSessionCache=new j;unsubscribeChange;unsubscribeError;unsubscribeDeleted;unsubscribeRuntimeStarted;stats=new k;watcherTasks=new B;progressTimer;constructor(e,t){this.importer=t;let n=e.directory??t.getLogDirectory();this.config={enabled:e.enabled,directory:e.directory,pollIntervalMs:e.pollIntervalMs??1e4,eventsPerSecond:e.eventsPerSecond??100,adapterId:e.adapterId,adapterName:e.adapterName,checkMakaioManaged:e.checkMakaioManaged,clientId:e.clientId,machineId:e.machineId},this.watcher=new O({directory:n,pattern:this.getLogFilePattern(),pollIntervalMs:this.config.pollIntervalMs}),this.eventQueue=new E({eventsPerSecond:this.config.eventsPerSecond,onEventEmitted:()=>{this.stats.recordEventEmitted(this.logPrefix)}})}shouldSkipFile(e){return!1}validateRecords(e){return e}getMaxRecords(){}buildCursorSessionContext(e){let{adapterSessionId:t,sessionEvent:n,startedEvent:r,state:i,...a}=e;return{...a,adapterSessionId:t,sessionEvent:n,startedEvent:r,state:this.importer.serializeState(i)}}usesJsonFormat(){let e=this.getLogFilePattern();return e.includes(`.json`)&&!e.includes(`.jsonl`)}isEnabled(){return this.config.enabled}isRunning(){return this.watcher.isRunning()}async start(){if(!this.config.enabled||this.isRunning())return;let e=this.config.directory??this.importer.getLogDirectory();console.info(`${this.logPrefix} Starting - watching ${e}`),this.stats.reset(),this.managedSessionCache.clear(),this.progressTimer=setInterval(()=>this.stats.logProgress(this.logPrefix),1e4),this.unsubscribeChange=this.watcher.onChange(e=>{this.trackFileChange(e)}),this.unsubscribeError=this.watcher.onError(({error:e,filePath:t})=>{console.warn(`${this.logPrefix} Error${t?` for ${t}`:``}: ${e.message}`)}),this.unsubscribeDeleted=this.watcher.onDeleted(({filePath:e})=>{this.watcherTasks.track(s.request(r.delete,{filePath:e}).then(()=>void 0).catch(()=>{}))}),this.unsubscribeRuntimeStarted=s.on(l.runtime.started,e=>{e.payload.source.layer===`adapter`&&e.payload.adapterSessionId!==void 0&&this.managedSessionCache.invalidate(e.payload.adapterSessionId)}),await this.watcher.start()}async stop(){this.progressTimer&&=(clearInterval(this.progressTimer),void 0),this.unsubscribeChange?.(),this.unsubscribeError?.(),this.unsubscribeDeleted?.(),this.unsubscribeRuntimeStarted?.(),this.unsubscribeChange=void 0,this.unsubscribeError=void 0,this.unsubscribeDeleted=void 0,this.unsubscribeRuntimeStarted=void 0,this.watcher.stop(),await this.watcherTasks.drain(),await this.eventQueue.drain(),this.stats.hasActivity()&&console.info(this.stats.stoppedMessage(this.logPrefix))}async dispose(){await this.stop(),this.watcher.dispose(),this.managedSessionCache.clear()}static createDefaultCheckMakaioManaged(e){return A(e)}async updateCursor(e,t,n,i){await s.request(r.set,{filePath:e,bytesRead:t,lastModified:n.toISOString(),sessionContext:i})}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let a=this.usesJsonFormat();n===`rotated`&&await s.request(r.delete,{filePath:t}).catch(()=>{});let o=await P(t,a,e,e=>this.trackFileChange(e));if(o===`retry`)return;let c=o?.sessionContext!==void 0,l=c?o?.bytesRead??0:0;if(M(o?.lastModified,i.mtime,a,n))return;let u=await this.parseFile(t,a?0:l,this.getMaxRecords());N(this.logPrefix,t,u.errors),this.stats.recordFileProcessed();let d=this.validateRecords(u.records),f=u.bytesRead??0;if(d.length===0){await this.maybeUpdateCursor(t,f,l,i.mtime,a,o?.sessionContext);return}c&&o?.sessionContext?await this.handleIncrementalRead(t,d,o.sessionContext,f,i.mtime,a,l):await this.handleFirstRead(t,d,f,i.mtime,a,l)}trackFileChange(e){let t=this.handleFileChange(e).catch(e=>{console.error(`${this.logPrefix} Error handling file change:`,e instanceof Error?e.message:String(e))});this.watcherTasks.track(t)}async handleFirstRead(e,t,n,r,i,a,o=!0){let s=this.importer.extractSessionContext(t);if(await this.isSessionSkipped(s.adapterSessionId)){await this.maybeUpdateCursor(e,n,a,r,i,this.buildCursorSessionContext(s));return}let c=I(t,s,o,(e,t)=>this.importer.processRecords(e,t),e=>this.queueEvent(e));this.trackImportedSession(s.adapterSessionId),await this.queueCursorUpdate(e,n,a,r,i,this.buildCursorSessionContext(s),c)}trackImportedSession(e){this.stats.recordSessionImported(e)}async handleIncrementalRead(e,t,n,i,a,o,c){if(await this.isSessionSkipped(n.adapterSessionId)){await this.maybeUpdateCursor(e,i,c,a,o,n);return}let l;try{l=this.importer.deserializeState(n.state)}catch(t){console.warn(`${this.logPrefix} Corrupted cursor state for ${e}, deleting cursor and re-importing.`,t instanceof Error?t.message:String(t)),await s.request(r.delete,{filePath:e}).catch(t=>{console.warn(`${this.logPrefix} Failed to delete corrupted cursor for ${e}.`,t instanceof Error?t.message:String(t))}),await F(e,a,o,!0,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let u={adapterSessionId:n.adapterSessionId,model:n.model,cwd:n.cwd,sessionEvent:n.sessionEvent,startedEvent:n.startedEvent,state:l},d=this.importer.processRecords(t,u);if(R(u.state)){await F(e,a,o,!1,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let f=L(d,e=>this.queueEvent(e)),p=z(n,u.state,e=>this.importer.serializeState(e));await this.queueCursorUpdate(e,i,c,a,o,p,f)}async maybeUpdateCursor(e,t,n,r,i,a){(t>n||i)&&await this.updateCursor(e,t,r,a)}async isSessionSkipped(e){return this.managedSessionCache.isSkipped(e,e=>this.importer.isMakaioManaged(e),e=>this.stats.recordSessionSkipped(e))}queueEvent(e){return this.eventQueue.queueEvent(e)}queueCursorUpdate(e,t,n,r,i,a,o=[]){return this.eventQueue.queueAfterEvents(()=>this.maybeUpdateCursor(e,t,n,r,i,a),o)}},H=class extends V{trackingFilePaths=new Set;trackingInactiveCount=new Map;lastSeenMtimeMs=new Map;unsubscribePolled;constructor(e,t){super(e,t)}clearTrackingState(e){this.trackingFilePaths.delete(e),this.trackingInactiveCount.delete(e),this.lastSeenMtimeMs.delete(e)}async persistImportedStatus(e){let{session:t}=await s.request(u.getByLogFilePath,{logFilePath:e});return!t||t.importStatus!==`tracking`||(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success?!0:(console.warn(`${this.logPrefix} Failed to persist imported status for ${e}`),!1)}async start(){!this.isEnabled()||this.isRunning()||(await super.start(),this.unsubscribePolled=this.watcher.onPolled(e=>{this.onPollCycle(e).catch(e=>{console.error(`${this.logPrefix} Error handling poll cycle:`,e instanceof Error?e.message:String(e))})}),await this.restorePersistedTrackingState())}async stop(){this.unsubscribePolled?.(),this.unsubscribePolled=void 0,await super.stop()}async dispose(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear(),await super.dispose()}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let{cursor:a}=await s.request(r.get,{filePath:t});if(!a){await this.discoverNewFile(e);return}n===`modified`&&await this.handleModifiedImportedFile(t,e,i.mtime)}async restorePersistedTrackingState(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear();try{let{sessions:e}=await s.request(u.listImported,{source:this.config.adapterName,importStatus:`tracking`});for(let t of e){if(t.source!==this.config.adapterName)continue;if(!t.logFilePath){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for session ${t.sessionId}`);continue}let e=this.watcher.getTrackedFileMtimeMs(t.logFilePath);if(e===void 0){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for ${t.logFilePath}`);continue}this.trackingFilePaths.add(t.logFilePath),this.trackingInactiveCount.set(t.logFilePath,0),this.lastSeenMtimeMs.set(t.logFilePath,e)}}catch(e){console.warn(`[DiscoveryOrchestrator] Failed to restore persisted tracking state:`,e instanceof Error?e.message:String(e))}}async discoverNewFile(e){let{filePath:t,stat:n}=e,r=await this.importer.extractDiscoveryMetadata(t);if(!(r.hasMessages??!1)){await this.updateCursor(t,0,n.mtime);return}if(await this.isSessionSkipped(r.adapterSessionId)){await this.updateCursor(t,0,n.mtime);return}let i=this.queueEvent({subject:c.session.discovered,payload:{adapterId:this.config.adapterId,adapterName:this.config.adapterName,adapterSessionId:r.adapterSessionId,model:r.model??null,cwd:r.cwd??null,title:r.title,parentAdapterSessionId:r.parentAdapterSessionId??null,forkPointMessageId:r.forkPointMessageId??null,kind:r.kind??`root`,startedAt:r.startedAt,logFilePath:t}});await this.eventQueue.queueAfterEvents(()=>this.updateCursor(t,0,n.mtime),[i])}async handleModifiedImportedFile(e,t,n){let{session:r}=await s.request(u.getByLogFilePath,{logFilePath:e});if(!r){await this.discoverNewFile(t);return}if(r.source===this.config.adapterName&&!(r.importStatus!==`imported`&&r.importStatus!==`tracking`)){if(await super.handleFileChange(t),r.importStatus===`imported`&&!(await s.request(u.updateImportStatus,{sessionId:r.sessionId,importStatus:`tracking`})).success){console.warn(`${this.logPrefix} Failed to persist tracking status for ${e}`);return}this.trackingFilePaths.add(e),this.lastSeenMtimeMs.set(e,n.getTime()),this.trackingInactiveCount.delete(e),this.watcher.triggerImmediatePoll(e)}}async onPollCycle(e){for(let t of[...this.trackingFilePaths]){if(!e.has(t)){await this.persistImportedStatus(t)&&this.clearTrackingState(t);continue}let n=this.watcher.getTrackedFileMtimeMs(t),r=this.lastSeenMtimeMs.get(t);if(!(n===void 0||r===void 0))try{if(n===r){let e=(this.trackingInactiveCount.get(t)??0)+1;e>=3?await this.persistImportedStatus(t)&&this.clearTrackingState(t):this.trackingInactiveCount.set(t,e)}else this.lastSeenMtimeMs.set(t,n),this.trackingInactiveCount.delete(t)}catch(e){console.warn(`${this.logPrefix} Failed to process tracked file ${t}:`,e instanceof Error?e.message:String(e))}}}};export{V as BaseLogOrchestrator,H as DiscoveryOrchestrator,p as parseJsonlFile,m as readFirstJsonlRecords,h as someJsonlRecord};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,c as t,d as n,i as r,l as i,n as a,r as o,x as s,y as c}from"./schemas-BahXrOYa.mjs";import{a as l,c as u,d,f}from"./kind-registration-DggkrLkv.mjs";import{t as p}from"./zod-json-schema-B9TYYq3e.mjs";import{z as m}from"zod";import{createBusNamespace as h}from"@makaio/framework/core";function g(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...p(t)};d(i);let a=l.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=m.fromJSONSchema(a.dataSchema),s=m.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{f(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}function _(e){return{hooks:[...e.hooks]}}const v=[`inline`,`summary`,`link`,`omit`],y=m.string().min(1),b=m.object({kinds:m.array(m.string().min(1)).optional(),hint:y.optional(),depth:m.number().int().min(1).max(20).optional(),nested:m.lazy(()=>x).optional()}),x=m.record(m.string().min(1),b);function S(e){return JSON.stringify([e.kind,e.id,e.revision])}const C=m.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),w=m.object({target:i,sourceRef:s,relationType:m.string().min(1),hint:y,status:m.enum([`resolved`,`unresolved`]),reason:C.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:m.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:m.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:m.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),T=m.object({rootRef:s,refs:m.array(w),resolved:m.array(n)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(S));n.has(S(e.rootRef))||t.addIssue({code:m.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(S(e.sourceRef))||t.addIssue({code:m.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(S(e.target))||t.addIssue({code:m.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function E(e){let t=T.parse(e),n=new Map(t.resolved.map(e=>[j(e),e])),r=new Map;for(let e of t.refs){let t=j(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(j(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${j(t.rootRef)}'`);let a=D(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return A(a,e),e}}}function D(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:k(e,r,i,new Set([j(e)]))}}function O(e,t,n,r,i,a,o){let s=j(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:k(e,i,a,c)}}function k(e,t,n,r){return(t.get(j(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=j(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:O(e.target,a,e.relationType,e.hint,t,n,r)})}function A(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)A(n,t)}}function j(e){return JSON.stringify([e.kind,e.id,e.revision])}const M={"kind.register":{request:l,response:m.object({registered:m.boolean()})},"kind.list":{request:m.object({kind:m.string().min(1).optional()}),response:m.object({kinds:m.array(l)})},"relation-type.register":{request:c,response:m.object({registered:m.boolean()})},"relation-type.list":{request:m.object({type:m.string().min(1).optional()}),response:m.object({relationTypes:m.array(c)})},create:{request:n.omit({id:!0,revision:!0,timestamp:!0}).extend({id:s.shape.id.optional()}),response:m.object({artifact:n})},revise:{request:m.object({previous:s,statusPath:m.string().regex(/^(?:\/(?:[^~/]|~[01])*)+$/,`Expected a data-relative JSON Pointer`).optional(),revision:n.omit({id:!0,revision:!0,timestamp:!0})}),response:m.object({artifact:n})},resolve:{request:m.object({ref:s}),response:m.object({artifact:n.nullable()})},query:{request:e,response:m.object({artifacts:m.array(n)})},compare:{request:a,response:o},resolveContext:{request:m.object({ref:s,selectors:x.optional(),maxDepth:m.number().int().min(1).max(20).default(5)}),response:m.object({context:T})},created:m.object({artifact:n}),revised:m.object({previous:s,artifact:n}),"relation.added":m.object({artifact:s,relation:t}),"observation.added":m.object({artifact:s,observation:r}),"status.changed":m.object({artifact:s,path:m.string().min(1),previous:m.unknown().optional(),current:m.unknown().optional()}),"kind.changed":m.object({kind:m.string().min(1),schemaVersion:u})},N=h(`artifact`,M),P=N.subjects;export{w as a,v as c,x as d,_ as f,E as i,b as l,M as n,C as o,g as p,P as r,T as s,N as t,y as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as e}from"./execution-attempt-owner-recovery-
|
|
1
|
+
import{s as e}from"./execution-attempt-owner-recovery-CdH04iwP.mjs";import{z as t}from"zod";import{ExecutionAttemptPreparationResultSchema as n,ProviderAllocationRefSchema as r,WorkerAllocationLifetimeSchema as i}from"@makaio/framework/contracts";function a(e){let t=Date.parse(e);if(Number.isNaN(t))throw Error(`Expected an ISO-8601 timestamp, received '${e}'`);return t}function o(e){return new Date(a(e)).toISOString()}function s(e){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`bootstrapTimeoutMs must be a positive safe integer`);let t=Date.now(),n=t+e;if(!Number.isSafeInteger(n)||!Number.isFinite(new Date(n).getTime()))throw RangeError(`bootstrapTimeoutMs produces an unrepresentable bootstrap deadline`);return{createdAt:new Date(t).toISOString(),bootstrapDeadlineAt:new Date(n).toISOString()}}function c(t){return e(t,e=>n.parse(e))}const l=t.array(t.object({operationId:t.string().min(1),runtimeGeneration:t.number().int().positive(),result:n}).strict());function u(t){return e(t,e=>l.parse(e))}function d(t){return e(t,e=>r.parse(e))}function f(e){return i.parse(e)}function p(e){let t=r.parse(e.currentRef),n=d(e.nextRef);if(t.providerId!==n.providerId)throw Error(`Allocation reference evolution must keep one provider, received '${t.providerId}' and '${n.providerId}'`);return{currentRef:t,nextRef:n}}function m(e,t){if(e.providerId!==t.providerId)throw Error(`Allocation reference for attempt '${e.executionAttemptId}' names provider '${t.providerId}' but the attempt is bound to '${e.providerId??`no provider`}'`)}const h={runtimeGeneration:0,runtimeIncarnationId:null,runtimeReadyAt:null,operationStartGate:`open`,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:null};function g(e){return{runtimeGeneration:e.runtimeGeneration,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:e.runtimeReadyAt,operationStartGate:e.operationStartGate,activeOperationId:e.activeOperationId,activeOperationKind:e.activeOperationKind,activeOperationKey:e.activeOperationKey,activeOperationGeneration:e.activeOperationGeneration,activeOperationAdmittedAt:e.activeOperationAdmittedAt,lastCompletedOperationId:e.lastCompletedOperationId}}function _(e,t){let n=a(e.createdAt)-a(t.createdAt);return n===0?e.executionAttemptId<t.executionAttemptId?-1:+(e.executionAttemptId>t.executionAttemptId):n}function v(e){let{status:t,claimable:n,settlementKind:r,allocationRef:i,providerId:a}=e,{allocationLifetime:o,provisionerIncarnationId:s}=e;if(t!==`allocated`||n!==!0||r!=null||i===null||a===null||o===null||s===null)throw Error(`Attempt '${e.executionAttemptId}' was selected as recoverable but is not: status '${t}', claimable '${String(n)}', settlement '${String(r)}', allocation '${i===null?`none`:`present`}', provider '${String(a)}', lifetime '${String(o)}', provisioner '${String(s)}'`);return{...e,status:t,claimable:!0,settlementKind:null,allocationRef:i,providerId:a,allocationLifetime:o,provisionerIncarnationId:s}}export{o as a,p as c,m as d,g as f,a as i,u as l,_ as n,f as o,v as p,s as r,d as s,h as t,c as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./chunk-DTipWd-i.mjs";import{t}from"./ajv-Dtk5hCZS.mjs";import{z as n}from"zod";import{execFile as r}from"node:child_process";import{isDeepStrictEqual as i}from"node:util";import{isAbsolute as a,relative as o,resolve as s}from"node:path";import{randomUUID as c}from"node:crypto";import{realpathSync as l}from"node:fs";import{localSubject as u}from"@makaio/framework/core";import{NoHandlerError as d}from"@makaio/framework/bus";import{ArtifactSchemas as f,ArtifactSubjects as p,ExecutionAttemptInstructionSchema as m,ExecutionAttemptOutcomeSchema as h,ExecutionLinkListQuerySchema as g,ExecutionLinkSchema as _,ExecutionListQuerySchema as v,ExecutionStatusSchema as y,ExecutionsByArtifactRefsQuerySchema as b,GateInstanceListQuerySchema as x,JsonPatchOperationSchema as S,JsonValueSchema as C,SessionSubjects as ee,SpanRecordSchema as te,SubagentSubjects as ne,WORKFLOW_CANCELLED_REASON as re,WorkLogFrameEntrySchema as ie,WorkerSubjects as ae,WorkflowDefinitionSchema as oe,WorkflowError as se,WorkflowErrorCode as ce,WorkflowExecutionSchema as w,WorkflowFinalizationClaimSchema as le,WorkflowFinalizerIdSchema as ue,WorkflowFrameStateSchema as de,WorkflowGateInstanceSchema as T,WorkflowListQuerySchema as fe,WorkflowRunContextSchema as E,WorkflowRunResultSchema as pe,WorkflowSchemas as me,WorkflowSubjects as he,WorkflowSubjects as D,createStepCancelSubject as ge,createWorkflowDelegateResultFinalizerNamespace as _e,walkWorkflowDefinition as ve}from"@makaio/framework/contracts";import{index as O,primaryKey as ye,uniqueIndex as be}from"drizzle-orm/sqlite-core";import{index as k,primaryKey as xe,uniqueIndex as Se}from"drizzle-orm/pg-core";import{defineDualTable as A}from"@makaio/framework/storage/drizzle";import{sql as Ce}from"drizzle-orm";import{createStorageNamespaceDefinition as we}from"@makaio/framework/storage";import{evaluateSync as j,resolveTemplate as M}from"@makaio/framework/expression";import*as Te from"node:os";const Ee=A(`workflow_finalizations`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),finalizerId:e.text(`finalizer_id`).notNull(),transitionKey:e.text(`transition_key`).notNull(),claimToken:e.text(`claim_token`).notNull(),intent:e.jsonCol(`intent`).notNull(),state:e.textEnum(`state`,{enum:[`claimed`,`acknowledged`,`failed`]}).notNull(),claimedAt:e.epochMs(`claimed_at`).notNull(),settledAt:e.epochMs(`settled_at`),failure:e.text(`failure`),publishedAt:e.epochMs(`published_at`)}),{sqlite:e=>[be(`uniq_workflow_finalizations_transition`).on(e.transitionKey),O(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)],postgres:e=>[Se(`uniq_workflow_finalizations_transition`).on(e.transitionKey),k(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)]}),De=Ee.sqlite;Ee.postgres;function Oe(e){return{scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``)}}const ke=A(`workflow_definitions`,e=>({id:e.text(`id`).primaryKey(),name:e.text(`name`).notNull(),description:e.text(`description`),root:e.jsonCol(`root`).notNull(),inputSchema:e.jsonCol(`input_schema`),configSchema:e.jsonCol(`config_schema`),outputSchema:e.jsonCol(`output_schema`),state:e.jsonCol(`state`),artifact:e.jsonCol(`artifact`),triggers:e.jsonCol(`triggers`),...Oe(e),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull(),canvasLayout:e.jsonCol(`canvas_layout`),source:e.jsonCol(`source`),executableSource:e.jsonCol(`executable_source`),requirements:e.jsonCol(`requirements`),successFinalizerId:e.text(`success_finalizer_id`)}),{sqlite:e=>[be(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),O(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)],postgres:e=>[Se(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),k(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)]}),Ae=ke.sqlite,N=A(`workflow_executions`,e=>({id:e.text(`id`).primaryKey(),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`finalizing`,`completed`,`failed`,`cancelled`]}).notNull(),inputs:e.jsonCol(`inputs`),error:e.text(`error`),reason:e.text(`reason`),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),externalSettlementFingerprint:e.text(`external_settlement_fingerprint`),externalRegistrationFrameId:e.text(`external_registration_frame_id`),triggerPayload:e.jsonCol(`trigger_payload`),artifactKind:e.text(`artifact_kind`),artifactId:e.text(`artifact_id`),...Oe(e)}),{sqlite:e=>[O(`idx_workflow_executions_status`).on(e.status),O(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),O(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),O(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)],postgres:e=>[k(`idx_workflow_executions_status`).on(e.status),k(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),k(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),k(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)]}),je=N.sqlite,Me=A(`workflow_execution_frames`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),parentFrameId:e.text(`parent_frame_id`),status:e.text(`status`).notNull().default(`pending`).$type(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),output:e.jsonCol(`output`),outputPresent:e.bool(`output_present`).notNull().default(!1),error:e.text(`error`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`)}),{sqlite:e=>[O(`idx_workflow_execution_frames_execution`).on(e.executionId),O(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)],postgres:e=>[k(`idx_workflow_execution_frames_execution`).on(e.executionId),k(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)]}),Ne=Me.sqlite,Pe=A(`workflow_gate_instances`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),schema:e.jsonCol(`schema`).notNull(),prompt:e.text(`prompt`),status:e.text(`status`).notNull().default(`waiting`).$type(),autoAction:e.textEnum(`auto_action`,{enum:[`approve`,`reject`]}).notNull().default(`reject`),timeoutMs:e.int4(`timeout_ms`),resumeData:e.jsonCol(`resume_data`),reason:e.text(`reason`),resumeDataPresent:e.bool(`resume_data_present`).notNull().default(!1),createdAt:e.epochMs(`created_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`)}),{sqlite:e=>[O(`idx_workflow_gate_instances_execution`).on(e.executionId),O(`idx_workflow_gate_instances_frame`).on(e.frameId)],postgres:e=>[k(`idx_workflow_gate_instances_execution`).on(e.executionId),k(`idx_workflow_gate_instances_frame`).on(e.frameId)]}),Fe=Pe.sqlite,Ie=A(`workflow_step_spans`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),stepId:e.text(`step_id`).notNull(),stepType:e.text(`step_type`).notNull(),status:e.text(`status`).$type().notNull(),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),toolCallCount:e.int4(`tool_call_count`),input:e.text(`input`),output:e.text(`output`)}),{sqlite:e=>[ye({columns:[e.executionId,e.frameId]}),O(`idx_workflow_step_spans_status`).on(e.status)],postgres:e=>[xe({columns:[e.executionId,e.frameId]}),k(`idx_workflow_step_spans_status`).on(e.status)]}),Le=Ie.sqlite,Re=A(`workflow_execution_links`,e=>({sourceExecutionId:e.text(`source_execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),targetExecutionId:e.text(`target_execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),linkType:e.text(`link_type`).$type().notNull(),metadata:e.jsonCol(`metadata`)}),{sqlite:e=>[ye({columns:[e.sourceExecutionId,e.targetExecutionId]}),O(`idx_workflow_execution_links_target`).on(e.targetExecutionId)],postgres:e=>[xe({columns:[e.sourceExecutionId,e.targetExecutionId]}),k(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]}),ze=Re.sqlite,Be=A(`workflow_run_contexts`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),coordinatorSessionId:e.text(`coordinator_session_id`).notNull(),sourceKind:e.text(`source_kind`).notNull(),sourcePath:e.text(`source_path`),sourceFilename:e.text(`source_filename`),sourceCode:e.text(`source_code`),definitionSnapshot:e.jsonCol(`definition_snapshot`),workerManifest:e.jsonCol(`worker_manifest`).notNull(),inputs:e.jsonCol(`inputs`),config:e.jsonCol(`config`).notNull().default(Ce`'{}'`),triggerPayload:e.jsonCol(`trigger_payload`).notNull(),triggerMode:e.textEnum(`trigger_mode`,{enum:[`immediate`,`await-trigger`]}).notNull().default(`immediate`).$type(),artifactRef:e.jsonCol(`artifact_ref`),dispatchMetadata:e.jsonCol(`dispatch_metadata`),scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().default(`global`).$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``),cancelSubject:e.text(`cancel_subject`).notNull(),env:e.jsonCol(`env`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),suspensionStrategy:e.text(`suspension_strategy`).$type(),terminalAuthority:e.text(`terminal_authority`).$type(),materializationSpec:e.jsonCol(`materialization_spec`)}),{sqlite:e=>[O(`idx_run_contexts_workflow`).on(e.workflowId)],postgres:e=>[k(`idx_run_contexts_workflow`).on(e.workflowId)]}),Ve=Be.sqlite,He=A(`worklog_summaries`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),workflowId:e.text(`workflow_id`).notNull(),workflowName:e.text(`workflow_name`),status:e.textEnum(`status`,{enum:[`pending`,`running`,`paused`,`finalizing`,`completed`,`failed`,`cancelled`]}).notNull(),startedAt:e.epochMs(`started_at`).notNull(),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),totalInputTokens:e.int4(`total_input_tokens`),totalOutputTokens:e.int4(`total_output_tokens`),totalEstimatedCost:e.float8(`total_estimated_cost`),error:e.text(`error`),failedNodeId:e.text(`failed_node_id`)}),{sqlite:e=>[O(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),O(`idx_worklog_summaries_status`).on(e.status)],postgres:e=>[k(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),k(`idx_worklog_summaries_status`).on(e.status)]}),Ue=He.sqlite,We=A(`worklog_frame_entries`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),nodeType:e.text(`node_type`).notNull().$type(),path:e.jsonCol(`path`).notNull(),status:e.textEnum(`status`,{enum:[`pending`,`running`,`waiting`,`completed`,`failed`,`skipped`,`cancelled`]}).notNull(),attempt:e.int4(`attempt`).notNull().default(0),iteration:e.int4(`iteration`),branchKey:e.text(`branch_key`),startedAt:e.epochMs(`started_at`),completedAt:e.epochMs(`completed_at`),durationMs:e.int4(`duration_ms`),inputTokens:e.int4(`input_tokens`),outputTokens:e.int4(`output_tokens`),estimatedCost:e.float8(`estimated_cost`),error:e.text(`error`)}),{sqlite:e=>[O(`idx_worklog_frame_entries_execution`).on(e.executionId)],postgres:e=>[k(`idx_worklog_frame_entries_execution`).on(e.executionId)]}),Ge=We.sqlite,Ke=A(`worklog_artifact_writes`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),frameId:e.text(`frame_id`).notNull(),nodeId:e.text(`node_id`).notNull(),artifact:e.jsonCol(`artifact`).notNull(),revision:e.text(`revision`),writtenAt:e.epochMs(`written_at`).notNull()}),{sqlite:e=>[O(`idx_worklog_artifact_writes_execution`).on(e.executionId)],postgres:e=>[k(`idx_worklog_artifact_writes_execution`).on(e.executionId)]}),qe=Ke.sqlite,Je=A(`worklog_gate_events`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),nodeId:e.text(`node_id`).notNull(),frameId:e.text(`frame_id`).notNull(),status:e.textEnum(`status`,{enum:[`waiting`,`resumed`,`rejected`,`timed-out`,`cancelled`]}).notNull().$type(),prompt:e.text(`prompt`),openedAt:e.epochMs(`opened_at`).notNull(),resolvedAt:e.epochMs(`resolved_at`),resumeData:e.jsonCol(`resume_data`)}),{sqlite:e=>[O(`idx_worklog_gate_events_execution`).on(e.executionId),O(`idx_worklog_gate_events_status`).on(e.status)],postgres:e=>[k(`idx_worklog_gate_events_execution`).on(e.executionId),k(`idx_worklog_gate_events_status`).on(e.status)]}),Ye=Je.sqlite,Xe=A(`workflow_execution_state`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),sequence:e.int4(`sequence`).notNull().default(0),value:e.jsonCol(`value`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()})),Ze=Xe.sqlite,Qe=A(`workflow_execution_state_events`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>N.columnPair(`id`),{onDelete:`cascade`}),sequence:e.int4(`sequence`).notNull(),patch:e.jsonCol(`patch`).notNull(),value:e.jsonCol(`value`).notNull(),createdAt:e.epochMs(`created_at`).notNull()}),{sqlite:e=>[ye({columns:[e.executionId,e.sequence]})],postgres:e=>[xe({columns:[e.executionId,e.sequence]})]}),$e=Qe.sqlite,et=n.object({executionId:n.string().min(1),status:y.optional(),error:n.string().nullable().optional(),reason:n.string().nullable().optional(),completedAt:n.number().nullable().optional()}),tt=n.enum([`completed`,`failed`,`cancelled`]),nt=ie.extend({status:n.literal(`running`),startedAt:n.number().int().nonnegative()}),rt=ie.extend({status:tt,startedAt:n.number().int().nonnegative(),completedAt:n.number().int().nonnegative(),durationMs:n.number().int().nonnegative()}),it=we(`workflow`,{schemas:{get:{request:n.object({id:n.string()}),response:n.object({workflow:oe.nullable()})},set:{request:n.object({workflow:oe}),response:n.object({id:n.string()})},delete:{request:n.object({id:n.string()}),response:n.object({deleted:n.boolean()})},list:{request:fe,response:n.object({workflows:n.array(oe)})},getExecution:{request:n.object({executionId:n.string()}),response:n.object({execution:w.nullable()})},setExecution:{request:n.object({execution:w}),response:n.object({id:n.string()})},setExecutionStart:{request:n.object({execution:w,runContext:E,initialState:C.optional(),executionLinks:n.array(_).optional()}),response:n.object({id:n.string(),executionId:n.string()})},setExternalExecutionStart:u({request:n.object({execution:w.extend({status:n.literal(`running`)}),frame:nt.optional()}),response:n.object({executionId:n.string(),frameId:n.string().optional()})}),settleExternalExecution:u({request:n.object({executionId:n.string().min(1),status:tt,error:n.string().min(1).optional(),reason:n.string().min(1).optional(),completedAt:n.number().int().nonnegative().optional(),frame:rt.optional()}),response:n.object({success:n.boolean()})}),updateExecution:{request:et,response:n.object({success:n.boolean()})},pauseRunningExecution:u({request:n.object({executionId:n.string().min(1)}),response:n.object({paused:n.boolean()})}),claimFinalization:u({request:n.object({claim:le}),response:n.object({claimed:n.boolean()})}),listClaimedFinalizations:u({request:n.object({finalizerId:ue}),response:n.object({claims:n.array(le)})}),listUnpublishedFinalizations:u({request:n.object({finalizerId:ue}),response:n.object({claims:n.array(le)})}),publishFinalization:u({request:n.object({claim:le}),response:n.object({})}),acknowledgeFinalization:u({request:n.object({executionId:n.string().min(1),claimToken:n.string().min(1),settledAt:n.number().int().nonnegative()}),response:n.object({acknowledged:n.boolean()})}),failFinalization:u({request:n.object({executionId:n.string().min(1),claimToken:n.string().min(1),error:n.string().min(1),settledAt:n.number().int().nonnegative()}),response:n.object({failed:n.boolean()})}),cancelPausedExecution:{request:n.object({executionId:n.string().min(1),completedAt:n.number(),reason:n.string().optional()}),response:n.object({cancelled:n.boolean(),gates:n.array(T.extend({status:n.literal(`cancelled`)}))})},listExecutions:{request:v,response:n.object({executions:n.array(w)})},listExecutionsByArtifactRefs:{request:b,response:n.object({executionsByRef:n.record(n.string(),n.array(w))})},setFrame:{request:n.object({executionId:n.string().min(1),frame:de}),response:n.object({frameId:n.string()})},getFrame:{request:n.object({frameId:n.string().min(1)}),response:n.object({frame:de.nullable()})},listFrames:{request:n.object({executionId:n.string().min(1)}),response:n.object({frames:n.array(de)})},setGateInstance:{request:n.object({gate:T}),response:n.object({id:n.string()})},resolveWaitingGateInstance:{request:n.object({gate:T.extend({status:n.enum([`resumed`,`rejected`])})}),response:n.object({accepted:n.boolean()})},restorePausedGateResumeState:{request:n.object({execution:w.extend({status:n.literal(`paused`)}),gate:T.extend({status:n.literal(`waiting`)})}),response:n.object({executionId:n.string(),gateId:n.string()})},getGateInstance:{request:n.object({executionId:n.string().min(1),nodeId:n.string().min(1),frameId:n.string().min(1).optional()}),response:n.object({gate:T.nullable()})},listGateInstances:{request:x,response:n.object({gates:n.array(T)})},listPausedGateTimeouts:u({request:n.object({}),response:n.object({gates:n.array(T)})}),setSpan:{request:n.object({span:te}),response:n.object({id:n.string()})},listSpans:{request:n.object({executionId:n.string()}),response:n.object({spans:n.array(te)})},setExecutionLink:{request:n.object({link:_}),response:n.object({id:n.string()})},listExecutionLinks:{request:g,response:n.object({links:n.array(_)})},setRunContext:u({request:n.object({runContext:E,initialState:C.optional()}),response:n.object({executionId:n.string()})}),getRunContext:u({request:n.object({executionId:n.string().min(1)}),response:n.object({runContext:E.nullable()})}),initializeState:u({request:n.object({executionId:n.string().min(1),initialValue:C}),response:n.object({})}),getState:u({request:n.object({executionId:n.string().min(1)}),response:n.object({state:n.object({executionId:n.string().min(1),sequence:n.number().int().nonnegative(),value:C}).nullable()})}),patchState:u({request:n.object({executionId:n.string().min(1),expectedSequence:n.number().int().nonnegative(),nextValue:C}),response:n.object({executionId:n.string().min(1),sequence:n.number().int().positive(),patch:n.array(S),value:C})})},extensions:{drizzle:{workflowDefinitions:Ae,workflowExecutions:je,workflowExecutionFrames:Ne,workflowGateInstances:Fe,workflowStepSpans:Le,workflowExecutionLinks:ze,workflowRunContexts:Ve,worklogSummaries:Ue,worklogFrameEntries:Ge,worklogArtifactWrites:qe,worklogGateEvents:Ye,workflowExecutionState:Ze,workflowExecutionStateEvents:$e,workflowFinalizations:De}}}),P=it.subjects;var at=e(t(),1);function ot(e){let t=e.transport?.peer;if(t?.authenticated!==!0||t.kind!==`workflow-execution-attempt`)return null;let n=t.id,r=t.claims?.executionId;return typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0?null:{executionAttemptId:n,executionId:r}}function st(e,t){return e.origin.local?!0:ot(e)?.executionId===t}function ct(e,t){let n=[];return lt(n,``,e,t),n}function lt(e,t,n,r){if(Array.isArray(n)&&Array.isArray(r)){dt(e,t,n,r);return}if(ft(n)&&ft(r)){ut(e,t,n,r);return}ht(n,r)||e.push({op:`replace`,path:t,value:r})}function ut(e,t,n,r){let i=Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let a of i){let i=pt(n,a),o=pt(r,a),s=`${t}/${mt(a)}`;if(!i&&o){e.push({op:`add`,path:s,value:r[a]});continue}if(i&&!o){e.push({op:`remove`,path:s});continue}lt(e,s,n[a],r[a])}}function dt(e,t,n,r){let i=Math.min(n.length,r.length);for(let a=0;a<i;a++)lt(e,`${t}/${String(a)}`,n[a],r[a]);for(let i=n.length-1;i>=r.length;i--)e.push({op:`remove`,path:`${t}/${String(i)}`});for(let i=n.length;i<r.length;i++)e.push({op:`add`,path:`${t}/${String(i)}`,value:r[i]})}function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function mt(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function ht(e,t){return Object.is(e,t)}const gt={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4},_t=new at.default({allErrors:!0,strict:!1}),vt=new Map,yt=new Map;function bt(e){let t=e.$id;return typeof t==`string`?t:void 0}function xt(e,t,n){let r=bt(t);return r===void 0?`workflow:${e}:${n}`:`schema-id:${r}`}function St(e,t){try{return JSON.stringify(Ct(t))}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function Ct(e){if(Array.isArray(e))return e.map(Ct);if(typeof e!=`object`||!e)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,Ct(t[e])]))}function wt(e,t,n){let r=yt.get(t);if(r!==void 0&&r!==n)throw Error(`Workflow '${e}' state schema reuses JSON Schema $id '${t}' with different content`);return _t.getSchema(t)}function Tt(e){return e==null||e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`<root>`} ${e.message??`is invalid`}`).join(`; `)}function Et(e,t){let n=St(e,t),r=xt(e,t,n),i=vt.get(r);if(i!==void 0)return i;let a=bt(t);if(a!==void 0){let t=wt(e,a,n);if(t!==void 0)return vt.set(r,t),t}try{let e=_t.compile(t);return vt.set(r,e),a!==void 0&&yt.set(a,n),e}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function Dt(e,t,n){if(e.state===void 0)return;let r=Et(e.id,e.state.schema);if(r(t))return;let i=n===`initial`?`initial state`:`next state`;throw Error(`Workflow '${e.id}' ${i} does not match workflow state schema: ${Tt(r.errors)}`)}function Ot(e){if(e.state===void 0)return;let t=e.state.initial===void 0?{}:e.state.initial;return Dt(e,t,`initial`),t}function kt(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function At(e,t,n){let r=e?M(e,n):t,i=s(t),c=s(a(r)?r:s(t,r)),u,d;try{u=l(i),d=l(c)}catch{return null}let f=o(process.platform===`win32`?u.toLowerCase():u,process.platform===`win32`?d.toLowerCase():d);return f===``||!f.startsWith(`..`)&&!a(f)?d:null}function jt(e){return e instanceof Error&&(`code`in e||`killed`in e)}function Mt(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function Nt(e){let{command:t,cwd:n,env:i,timeoutMs:a,signal:o}=e,s=Mt(t);if(s===null)return Promise.reject(Error(`Shell step command is empty`));let c=t.slice(1);return new Promise((e,t)=>{let l=null,u=!1,d=r(s,c,{cwd:n,env:{...process.env,...i},timeout:0,maxBuffer:10*1024*1024,shell:!1},(n,r,i)=>{n?t(Object.assign(n,{stdout:r,stderr:i,aborted:u})):e({stdout:r,stderr:i})}),f=()=>{d.exitCode===null&&(d.kill(`SIGTERM`),l=setTimeout(()=>{d.exitCode===null&&d.kill(`SIGKILL`)},5e3))},p=setTimeout(()=>{f()},a);if(d.on(`close`,()=>{clearTimeout(p),l!==null&&clearTimeout(l)}),o){let e=()=>{u=!0,f()};o.aborted?e():(o.addEventListener(`abort`,e,{once:!0}),d.on(`close`,()=>o.removeEventListener(`abort`,e)))}})}async function Pt(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=At(t.cwd,n,r);if(a===null)return{status:`failed`,error:`Shell step cwd '${t.cwd}' is outside workspace root '${n}'`};let o=t.command.map(e=>M(e,r));if(Mt(o)===null)return{status:`failed`,error:`Shell step command is empty`};let s=Object.fromEntries(Object.entries(t.env??{}).map(([e,t])=>[e,M(t,r)])),c=t.timeoutMs??3e5;try{let{stdout:e}=await Nt({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!jt(e))return{status:`failed`,error:String(e)};let t=e.aborted===!0,n=!t&&(e.killed===!0||e.signal!=null);return{status:`failed`,error:t?`Command cancelled`:n?`Command timed out after ${c}ms`:e.stderr?.trim()||e.stdout?.trim()||e.message}}}async function Ft(e,t,n){if(!(await e.request(P.updateExecution,{executionId:t.id,status:n.status,error:n.error,reason:n.reason,completedAt:n.completedAt})).success)throw Error(`Workflow execution not found: ${t.id}`)}function It(e,t){return e===t||t===`completed`&&e===`finalizing`}async function Lt(e,t,n){let r=e.durableLifecycleTransitions.get(t)??Promise.resolve(),i=Promise.withResolvers(),a=r.catch(()=>void 0).then(()=>i.promise);e.durableLifecycleTransitions.set(t,a),await r.catch(()=>void 0);try{return await n()}finally{i.resolve(),e.durableLifecycleTransitions.get(t)===a&&e.durableLifecycleTransitions.delete(t)}}async function F(e,t,n,r,i){let a,o,s=!0,c=await Lt(e,t,async()=>{let i=await n(),c=Promise.withResolvers(),l=e.lifecyclePublications.get(t)??Promise.resolve();return s=!e.publishingLifecycleExecutions.has(t),o=l.catch(()=>void 0).then(async()=>{await c.promise,e.publishingLifecycleExecutions.add(t);try{await r(i)}finally{e.publishingLifecycleExecutions.delete(t)}}),e.lifecyclePublications.set(t,o),a=c.resolve,i});if(o!==void 0){let n=o;n.then(()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)},()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)})}let l;try{l=i?.(c)}finally{a?.()}return await l,s&&o!==void 0&&await o,c}async function Rt(e,t,n){if(!(await e.bus.request(t.finalizeSubject,n)).accepted){let r=`Workflow success finalizer "${t.finalizerId}" rejected transition ${n.transitionKey}`,i=Date.now(),{failed:a}=await e.bus.request(P.failFinalization,{executionId:n.executionId,claimToken:n.claimToken,error:r,settledAt:i});return}}async function zt(e){for(let t of e.successFinalizers?.values()??[]){let{claims:n}=await e.bus.request(P.listClaimedFinalizations,{finalizerId:t.finalizerId});for(let r of n)await Rt(e,t,r);let{claims:r}=await e.bus.request(P.listUnpublishedFinalizations,{finalizerId:t.finalizerId});for(let t of r)await e.bus.request(P.publishFinalization,{claim:t})}}async function Bt(e,t,n,r){let i=e.resolveSuccessFinalizerId?.(n),a=i===void 0?void 0:e.successFinalizers?.get(i);if(i!==void 0&&a===void 0){await I(e,t,n,`Workflow success finalizer "${i}" is unavailable`);return}if(a!==void 0){let r=Date.now(),i={executionId:n,workflowId:t.workflowId,finalizerId:a.finalizerId,transitionKey:`${n}:terminal`,claimToken:crypto.randomUUID(),intent:{status:`completed`,completedAt:r},claimedAt:r};await F(e,n,async()=>(await e.bus.request(P.getExecution,{executionId:n})).execution?.status!==`running`||!(await e.bus.request(P.claimFinalization,{claim:i})).claimed?!1:(t.status=`finalizing`,e.activeExecutions.delete(n),!0),async t=>{t&&await Rt(e,a,i)});return}let o=Date.now();await F(e,n,async()=>(await e.bus.request(P.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`completed`,t.completedAt=o,await Ft(e.bus,t,{status:t.status,completedAt:o}),e.activeExecutions.delete(n),!0):!1,async i=>{i&&await e.bus.emit(D.execution.completed,{executionId:n,workflowId:t.workflowId,totalDuration:o-r,completedAt:o})})}async function I(e,t,n,r,i){let a=Date.now();await F(e,n,async()=>(await e.bus.request(P.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`failed`,t.error=r,t.completedAt=a,await Ft(e.bus,t,{status:t.status,error:r,completedAt:a}),e.activeExecutions.delete(n),!0):!1,async o=>{if(o){try{await i?.()}catch(e){console.error(`[WorkflowFinalizer] Failed to run failure pre-emit hook:`,e)}await e.bus.emit(D.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:a})}})}function Vt(e,t,n){let{activeRunnerSteps:r,bus:i}=e,a=`${t}:`;for(let[e,o]of r){if(!e.startsWith(a))continue;let r=e.slice(a.length);o.controller.abort(),i.emit(ge(o.cancelSubject),{executionId:t,stepId:r,reason:n}).catch(t=>{console.error(`[WorkflowFinalizer] Failed to emit cancellation for ${e}:`,t)})}}async function Ht(e,t,n){let r=await e.bus.request(P.getExecution,{executionId:t});if(r.execution==null)return;let i=r.execution.workflowId;if(i===void 0)throw Error(`Paused execution ${t} is missing stored workflowId`);let a=Date.now(),{cancelled:o,gates:s}=await e.bus.request(P.cancelPausedExecution,{executionId:t,completedAt:a,reason:n});if(o)return e.activeExecutions.delete(t),{workflowId:i,completedAt:a,gates:s}}async function Ut(e,t,n,r=`converge`){let{execution:i}=await e.bus.request(P.getExecution,{executionId:t});if(i?.status!==`running`&&i?.status!==`paused`)return;if(r===`request`&&await e.requestAttemptCancellation?.(t,n),i?.status!==`running`)return Ht(e,t,n);i.status=`cancelled`,i.reason=n,i.completedAt=Date.now();let a=e.activeExecutions.get(t);a!==void 0&&Object.assign(a.execution,i);try{for(let[n,r]of e.shellAbortControllers)n.startsWith(`${t}:`)&&(r.abort(),e.shellAbortControllers.delete(n));Vt(e,t,n),await Ft(e.bus,i,{status:i.status,reason:n,completedAt:i.completedAt})}finally{e.activeExecutions.delete(t)}return{workflowId:i.workflowId,completedAt:i.completedAt,gates:[]}}async function Wt(e,t,n){return Kt(e,t,n,`converge`)}async function Gt(e,t,n){return Kt(e,t,n,`request`)}async function Kt(e,t,n,r){return await F(e,t,()=>Ut(e,t,n,r),async r=>{if(r!==void 0){for(let n of r.gates)await e.bus.emit(D.gate.resolved,{executionId:t,stepId:n.nodeId,stepType:`gate`,frameId:n.frameId,source:`cancelled`}).catch(e=>{console.error(`[WorkflowFinalizer] Failed to emit cancelled gate resolution for ${n.frameId}:`,e)});await e.bus.emit(D.execution.cancelled,{executionId:t,workflowId:r.workflowId,reason:n,completedAt:r.completedAt})}},i=>{if(i!==void 0&&r===`request`)return e.notifyAttemptCancellation?.(t,n)})!==void 0}function qt(e,t){return t}function Jt(e,t){return{...t}}function Yt(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:re}async function Xt(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return;let i=e.buildFinalizerDeps(),{execution:a}=await i.bus.request(P.getExecution,{executionId:t});a?.status===`running`&&(r.execution=a,await Wt(i,t,Yt(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function Zt(e,t){if(t.pausedAtGateId===void 0||t.pausedAtFrameId===void 0)throw Error(`Paused runner result for '${t.executionId}' is missing gate identity`);let n=e.buildFinalizerDeps();await F(n,t.executionId,async()=>{let{paused:r}=await n.bus.request(P.pauseRunningExecution,{executionId:t.executionId});if(!r){let{execution:e}=await n.bus.request(P.getExecution,{executionId:t.executionId});if(e?.status!==`paused`)return!1}let i=e.activeExecutions.get(t.executionId);return i!==void 0&&(i.execution.status=`paused`),e.activeExecutions.delete(t.executionId),r},async e=>{e&&await n.bus.emit(D.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId})})}async function Qt(e,t){let n=e.activeExecutions.get(t.executionId);if(!n||n.execution.status!==`running`)return;let r=e.buildFinalizerDeps(),{execution:i}=await r.bus.request(P.getExecution,{executionId:t.executionId});if(i?.status===`running`){if(n.execution=i,t.status===`completed`){await Bt(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await Wt(r,t.executionId,t.reason??re);return}if(t.status===`failed`){await I(r,n.execution,t.executionId,t.error);return}}}async function $t(e,t){let{result:n}=t;if(t.state===`authority-committed`){let{execution:t}=await e.buildFinalizerDeps().bus.request(P.getExecution,{executionId:n.executionId}),r=t?.status===`cancelled`&&n.status===`failed`&&e.workflowAbortControllers.get(n.executionId)?.signal.aborted===!0;if(!t||t.workflowId!==n.workflowId||!It(t.status,n.status)&&!r)throw Error(`Authority-committed runner result was not durably converged for '${n.executionId}'`);e.activeExecutions.delete(n.executionId);return}if(n.status===`paused`){await Zt(e,n);return}await Qt(e,n)}function en(e,t){return{source:{kind:`path`,path:t.filePath},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,triggerMode:t.triggerMode,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope,busUrl:e.config.busUrl,busAuth:e.config.busAuth,env:e.config.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:`wait-in-process`,materializationSpec:t.materializationSpec}}function tn(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=en(e,t),l=an(e,n,s.signal);return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{await $t(e,t)}).catch(async t=>{if(s.signal.aborted){await Xt(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await I(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist file runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function nn(e,t){let{config:n}=e,r=t.definitionSnapshot??(t.source.kind===`definition`?t.workflow:void 0);return{source:t.source,...r===void 0?{}:{definition:r},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`,...t.terminalAuthority!==void 0&&{terminalAuthority:t.terminalAuthority},...t.materializationSpec===void 0?{}:{materializationSpec:t.materializationSpec}}}function rn(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=nn(e,t),l={...an(e,n,s.signal),...t.dispatchMetadata===void 0?{}:{dispatchMetadata:t.dispatchMetadata}};return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{await $t(e,t)}).catch(async t=>{if(s.signal.aborted){await Xt(e,n,s.signal).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${n}:`,e)});return}let r=o.get(n);if(r){let i=t instanceof Error?t.message:String(t);await I(e.buildFinalizerDeps(),r.execution,n,i).catch(e=>{console.error(`[WorkflowExecutor] Failed to persist runner boot failure for ${n}:`,e)})}}).finally(()=>{i.delete(n),a.delete(n),o.delete(n)})}function an(e,t,n){return{withAttemptCreation:r=>{let i=e.buildFinalizerDeps();return Lt(i,t,async()=>{n.throwIfAborted();let{execution:e}=await i.bus.request(P.getExecution,{executionId:t});if(n.throwIfAborted(),e?.status!==`running`)throw Error(`Execution '${t}' no longer permits attempt creation`);return r()})}}}function on(e,t,n={}){let r=sn(e,n);return{executionId:e.executionId,workflowId:e.workflowId,workflow:t,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},source:e.source,coordinatorSessionId:e.coordinatorSessionId,sanitizedTriggerPayload:e.triggerPayload,boundInputs:e.inputs,boundConfig:e.config??{},...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},scope:e.scope,...e.materializationSpec===void 0?{}:{materializationSpec:e.materializationSpec},suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??`worker`,...r===void 0?{}:{dispatchMetadata:r}}}function sn(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const cn=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function ln(e){if(!e)return;let t={remainingBytes:65536},n={},r=Object.entries(e).slice(0,100);for(let[e,i]of r){if(t.remainingBytes<=0)break;let r=un(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function un(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if(cn.test(e))return r.remainingBytes-=10,`[REDACTED]`;if(t===null)return r.remainingBytes-=4,null;if(typeof t==`string`){let e=t.slice(0,2e3);return r.remainingBytes-=e.length,e}if(typeof t==`number`||typeof t==`boolean`)return r.remainingBytes-=String(t).length,t;if(Array.isArray(t)){let i=[];for(let a of t.slice(0,100)){if(r.remainingBytes<=0)break;let t=un(e,a,n+1,r);t!==void 0&&i.push(t)}return i}if(typeof t==`object`){let e={},i=Object.entries(t).slice(0,100);for(let[t,a]of i){if(r.remainingBytes<=0)break;let i=un(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}async function dn(e){let{authority:t,executionId:n,instruction:r,dispatch:i}=e,a=()=>t.createAttempt(n,r),o=await(e.withAttemptCreation?.(a)??a()),s=t.waitForOutcome(o.executionAttemptId);if(s===void 0)throw Error(`No outcome waiter for attempt '${o.executionAttemptId}': waiter was not installed during attempt creation`);s.catch(()=>void 0);try{await i(o.executionAttemptId)}catch(e){return fn({authority:t,executionId:n,executionAttemptId:o.executionAttemptId,outcomePromise:s,dispatchError:e})}return s}async function fn(e){let{authority:t,executionId:n,executionAttemptId:r,outcomePromise:i,dispatchError:a}=e,o;try{o=await t.abandonPendingAttempt(r,n)}catch(e){throw t.discardWaiter(r),AggregateError([a,e],`Dispatch acknowledgement failed and pending attempt '${r}' could not be abandoned`,{cause:a})}switch(o.kind){case`abandoned`:case`already-abandoned`:throw t.discardWaiter(r),a;case`allocated`:case`provisioning`:case`already-settled`:return i;case`fenced`:t.settleOutcome(r,{kind:`fenced`});try{return await i}catch(e){throw AggregateError([a,e],`Dispatch acknowledgement failed after attempt '${r}' was fenced`,{cause:a})}}}const pn=`workflow`,mn=`1`,L=E.shape,hn=n.object({executionId:L.executionId,workflowId:L.workflowId,source:L.source,definitionSnapshot:L.definitionSnapshot,inputs:L.inputs,config:L.config,scope:L.scope,triggerPayload:L.triggerPayload,triggerMode:L.triggerMode,artifactRef:L.artifactRef,coordinatorSessionId:L.coordinatorSessionId,cancelSubject:L.cancelSubject,materializationSpec:L.materializationSpec,terminalAuthority:n.literal(`authority`)}).strict().superRefine((e,t)=>{let n=E.safeParse({...e,createdAt:0});if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message});e.source.kind===`path`&&(e.source.path.includes(`\\`)||/^[A-Za-z]:/.test(e.source.path)||e.source.path.split(`/`).includes(`..`))&&t.addIssue({code:`custom`,path:[`source`,`path`],message:`Workflow source must stay within its executable root`}),e.source.kind===`definition`&&e.source.workflowId!==e.workflowId&&t.addIssue({code:`custom`,path:[`source`],message:`Workflow source identity does not match the invocation`}),e.definitionSnapshot!==void 0&&e.definitionSnapshot.id!==e.workflowId&&t.addIssue({code:`custom`,path:[`definitionSnapshot`],message:`Workflow definition identity does not match the invocation`})});function gn(e,t){if(t===void 0&&e.source.kind===`path`)throw Error(`Path-backed workflow instructions require a portable run context`);if(t!==void 0&&(t.executionId!==e.executionId||t.workflowId!==e.workflowId))throw Error(`Workflow run context does not belong to the dispatched execution`);let n=t??e,r=t===void 0?e.definition:t.definitionSnapshot;return hn.parse({executionId:n.executionId,workflowId:n.workflowId,source:n.source,...r===void 0?{}:{definitionSnapshot:r},inputs:n.inputs,...n.config===void 0?{}:{config:n.config},scope:n.scope,triggerPayload:n.triggerPayload,...n.triggerMode===void 0?{}:{triggerMode:n.triggerMode},...n.artifactRef===void 0?{}:{artifactRef:n.artifactRef},coordinatorSessionId:n.coordinatorSessionId,cancelSubject:n.cancelSubject,...n.materializationSpec===void 0?{}:{materializationSpec:n.materializationSpec},terminalAuthority:`authority`})}function _n(e){let t=gn(e.config,e.runContext),n=JSON.parse(JSON.stringify(t));return m.parse({id:e.id,revision:e.revision,workload:{kind:pn,version:`1`,input:n},...e.workspace===void 0?{}:{workspace:e.workspace},preservation:e.preservation})}function vn(e){if(e.workload.kind!==`workflow`||e.workload.version!==`1`)throw Error(`Instruction does not target the supported workflow workload adapter`);return hn.parse(e.workload.input)}const yn=h.transform((e,t)=>e.kind===`technical-failure`||e.kind===`cancelled`?e:(t.addIssue({code:`custom`,message:`Expected a runtime outcome, not an opaque workload result`}),n.NEVER)),bn=n.union([pe,yn]),xn={parse:e=>bn.parse(e),serialize:e=>JSON.stringify(e)};function Sn(e){let t=h.parse(e.outcome);if(t.kind===`technical-failure`||t.kind===`cancelled`)return t;let n=vn(e.instruction),r=pe.parse(t.result);if(r.executionId!==n.executionId||r.workflowId!==n.workflowId)throw Error(`Workflow result identity does not match the frozen instruction`);return r}function Cn(e,t){if(`kind`in e)return e.kind===`cancelled`?{executionId:t.executionId,workflowId:t.workflowId,status:`cancelled`,...e.reason===void 0?{}:{reason:e.reason}}:{executionId:t.executionId,workflowId:t.workflowId,status:`failed`,error:`${e.stage}: ${e.message}`};if(e.executionId!==t.executionId||e.workflowId!==t.workflowId)throw Error(`Committed workflow result does not match its owner identity`);return pe.parse(e)}function wn(e){return e===void 0?!1:(e.customCapabilities??[]).length>0||e.persistentStorage!==void 0||e.maxRuntimeMs!==void 0||e.recoverableAllocation!==void 0||e.materializationModes!==void 0&&e.materializationModes.length>0}function Tn(e){let{bus:t,requirements:n,dispatchMetadata:r,authority:i}=e;if(wn(n))return{terminalAuthority:`authority`,run:async(e,a,o,s)=>{a.throwIfAborted();let l=e.source.kind===`path`?(await t.request(P.getRunContext,{executionId:e.executionId},{signal:a})).runContext:void 0;a.throwIfAborted();let u=_n({id:c(),revision:`1`,config:e,...l==null?{}:{runContext:l},preservation:{required:[]}});return{state:`authority-committed`,result:Cn(await dn({authority:i,executionId:e.executionId,instruction:u,withAttemptCreation:s?.withAttemptCreation,dispatch:i=>t.request(ae.dispatch,{executionAttemptId:i,config:{...e,terminalAuthority:`authority`},requirements:n,...o===void 0?{}:{manifest:o},...r!==void 0||s?.dispatchMetadata!==void 0?{metadata:{...r,...s?.dispatchMetadata}}:{}},{signal:a})}),e)}}}}function En(e,t){let n=(e.executionAttemptAuthority===void 0?void 0:Tn({bus:e.bus,requirements:t.workflow.requirements,dispatchMetadata:t.dispatchMetadata,authority:e.executionAttemptAuthority}))??e.workflowRunner;if(t.terminalAuthority!==void 0&&t.terminalAuthority!==(n?.terminalAuthority??`worker`))throw Error(`Selected workflow runner is incompatible with the persisted terminal authority`);return{runner:n}}function Dn(e,t,n=En(e,t)){return n.runner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):rn(e.buildRunnerTaskDeps(n.runner),{...t,terminalAuthority:t.terminalAuthority??n.runner.terminalAuthority})}async function On(e,t,n,r){let i=Ot(r);await e.request(P.setExecutionStart,{execution:t,runContext:n,initialState:i})}async function kn(e,t){try{await e.emit(D.execution.started,{executionId:t.id,workflowId:t.workflowId,coordinatorSessionId:t.coordinatorSessionId,startedAt:t.startedAt,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef}})}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function An(e,t){await e.request(ee.close,{sessionId:t}).catch(e=>{console.error(`[WorkflowExecutor] Failed to close coordinator session "${t}" after launch failure:`,e)})}function jn(e,t,n,r,i,a,o,s,c){let l={id:t,workflowId:n.id,coordinatorSessionId:r,status:`running`,inputs:i,config:a,startedAt:Date.now(),triggerPayload:o,...c.artifactRef===void 0?{}:{artifactRef:c.artifactRef},scope:s};return e.set(t,{execution:l,workflow:n,runContext:c,runtimeHandlers:new Map,runtimeLoopGates:new Map}),l}async function Mn(e,t,n,r,i){await e.request(P.setExecutionStart,{execution:t,runContext:n,...r===void 0?{}:{initialState:r},...i!==void 0&&i.length>0?{executionLinks:[...i]}:{}})}function Nn(e,t){return e.executableSource??{kind:`definition`,workflowId:t}}function Pn(e,t){return e.kind===`definition`||t!==void 0}function Fn(e,t,n){if(!(t.kind===`definition`||e!==void 0))throw new se(ce.NOT_EXECUTABLE,`Workflow source execution '${n}' requires a workflow runner.`)}async function In(e,t,n){if(t.source.kind===`path`){if(n!==void 0)return n;for(let n of e.materializationSpecResolvers){let e=await n.resolve({executionId:t.executionId,workflowId:t.workflowId,sourcePath:t.source.path,workspaceRoot:t.workspaceRoot});if(e!==void 0)return e}throw Error(`[WorkflowExecutor] path-backed execution requires a resolved materializationSpec`)}}async function Ln(e,t,n){let r=await In(e,t,n);return{source:t.source.kind===`path`&&r!==void 0?{kind:`path`,path:r.sourcePath}:t.source,materializationSpec:r}}async function Rn(e,t,n,r){return e.set(t,n),await r,t}async function zn(e,t){let{workflow:n}=await e.request(P.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}async function Bn(e,t,n,r){let{sessionId:i}=await e.request(ee.create,{parentSessionId:t,branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function Vn(e,t,n={}){let r=await zn(e.bus,t);return Hn(e,t,{...n,workflow:r})}async function Hn(e,t,n){let{bus:r,activeExecutions:i,executionTasks:a}=e,{workflow:o,parentSessionId:s,triggerPayload:c,artifactRef:l,scopeOverride:u}=n,d=kt(`wfx`),f=ln(c),p=qt(o,n.input===void 0?{}:n.input),m=Jt(o,n.config??{}),h=u??o.scope,g=await e.resolveExecutionWorkspaceRoot(s),_=n.executionSource??Nn(o,t),v=n.definitionSnapshot??o,y=En(e,{workflow:o});Fn(y.runner,_,t);let{source:b,materializationSpec:x}=await Ln(e,{executionId:d,workflowId:t,source:_,workspaceRoot:g},n.materializationSpec),S=await Bn(r,s,o.name,g),C=!1;try{let s=e.buildRunContext({executionId:d,workflowId:t,coordinatorSessionId:S,source:b,...v===void 0?{}:{definitionSnapshot:v},inputs:p,config:m,scope:h,triggerPayload:f??{},triggerMode:`immediate`,terminalAuthority:y.runner?.terminalAuthority,...l===void 0?{}:{artifactRef:l},...x===void 0?{}:{materializationSpec:x}}),c=jn(i,d,o,S,p,m,f,h,s);await Mn(r,c,s,_.kind===`definition`?Ot(o):void 0,n.executionLinks?.(d));let u=kn(r,c),g=Dn(e,{executionId:d,workflowId:t,workflow:o,...Pn(_,n.definitionSnapshot)?{definitionSnapshot:v}:{},source:_,coordinatorSessionId:S,sanitizedTriggerPayload:f??{},boundInputs:p,boundConfig:m,scope:h,...l===void 0?{}:{artifactRef:l},suspensionStrategy:s.suspensionStrategy,...x===void 0?{}:{materializationSpec:x}},y);return C=!0,Rn(a,d,g,u)}catch(e){throw C||(i.delete(d),a.delete(d),await An(r,S)),e}}function Un(e,t,n,r,i){e.set(t.id,{execution:t,workflow:{id:t.workflowId,name:n,scope:r,root:{id:`${t.workflowId}-root`,type:`sequence`,nodes:[]}},runContext:i,runtimeHandlers:new Map,runtimeLoopGates:new Map})}async function Wn(e,t,n,r){let{sessionId:i}=await e.request(ee.create,{...t===void 0?{}:{parentSessionId:t},branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}function Gn(e){if(e===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);return e}function Kn(e){if(e===void 0)throw Error(`[WorkflowExecutor] path-backed execution requires a resolved materializationSpec`);return e}async function qn(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{artifactRef:o,parentSessionId:s,triggerPayload:c,scopeOverride:l}=n,u=n.triggerMode??`immediate`,d=kt(`wfx`),f=ln(c),p=n.input===void 0?{}:n.input,m=n.config??{},h=l??{type:`global`},g=await e.resolveExecutionWorkspaceRoot(s),_=Gn(e.workflowRunner),v=d,y=Kn(await In(e,{executionId:d,workflowId:v,source:{kind:`path`,path:t},workspaceRoot:g},n.materializationSpec)),b=await Wn(r,s,t,g),x={id:d,workflowId:v,coordinatorSessionId:b,status:`running`,inputs:p,config:m,startedAt:Date.now(),triggerPayload:f,...o===void 0?{}:{artifactRef:o},scope:h},S=!1;try{let s=e.buildRunContext({executionId:d,workflowId:v,coordinatorSessionId:b,source:{kind:`path`,path:y.sourcePath},inputs:p,config:m,scope:h,triggerPayload:f??{},triggerMode:u,terminalAuthority:_.terminalAuthority,...o===void 0?{}:{artifactRef:o},materializationSpec:y});await Mn(r,x,s,void 0,n.executionLinks?.(d)),Un(i,x,t,h,s);let c=kn(r,x),l=tn(e.buildRunnerTaskDeps(_),{executionId:d,workflowId:v,filePath:t,coordinatorSessionId:b,sanitizedTriggerPayload:f??{},triggerMode:u,boundInputs:p,boundConfig:m,...o===void 0?{}:{artifactRef:o},scope:h,materializationSpec:y});return S=!0,Rn(a,d,l,c)}catch(e){throw S||(i.delete(d),a.delete(d),await An(r,b)),e}}function Jn(e){let t={};for(let[n,r]of Object.entries(e))r.status===`completed`?t[n]={status:`completed`,output:r.output}:r.status===`skipped`&&(t[n]={status:`skipped`});return t}function R(e){let t={...e,input:e.inputs,steps:e.frames};return{...t,ctx:t}}function Yn(e,t){let n=process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`;return{repoPath:e??process.cwd(),makaioHome:t??process.env.MAKAIO_HOME??`${Te.homedir()}/.makaio`,os:n,arch:process.arch}}function Xn(){return{context:Yn(),env:{}}}function Zn(e){return{...e,path:[...e.path]}}function Qn(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function $n(e,t){let n=Qn(t.nodeType);if(n===void 0||t.status!==`running`&&t.status!==`completed`&&t.status!==`failed`&&t.status!==`skipped`)return;let r=t.startedAt!==void 0&&t.completedAt!==void 0?Math.max(0,t.completedAt-t.startedAt):void 0;return{executionId:e,frameId:t.frameId,stepId:t.nodeId,stepType:n,status:t.status,...t.startedAt===void 0?{}:{startedAt:t.startedAt},...t.completedAt===void 0?{}:{completedAt:t.completedAt},...r===void 0?{}:{durationMs:r},...t.output===void 0?{}:{output:JSON.stringify(t.output)}}}var er=class e{executionId;workflowId;definition;execution;runtimeHandlers;bus;signal;frameRegistry;framePersistenceTasks=new Map;artifactBinding;constructor(e,t,n,r,i,a,o,s,c,l=Xn(),u={}){this.executionId=e,this.workflowId=t,this.definition=n,this.execution=r,this.runtimeHandlers=i,this.bus=a,this.signal=o,this.frameRegistry=s??new Map,this.artifactBinding=c,this.platformContext=l.context,this.env=l.env,this.suspensionStrategy=u.suspensionStrategy??`wait-in-process`,this.resumeFrames=u.resumeFrames,this.runtimeLoopGates=u.runtimeLoopGates??new Map}platformContext;env;suspensionStrategy;resumeFrames;runtimeLoopGates;withSignal(t){return new e(this.executionId,this.workflowId,this.definition,this.execution,this.runtimeHandlers,this.bus,t,this.frameRegistry,this.artifactBinding,{context:this.platformContext,env:this.env},{suspensionStrategy:this.suspensionStrategy,resumeFrames:this.resumeFrames,runtimeLoopGates:this.runtimeLoopGates})}buildExpressionContext(){return{inputs:this.execution.inputs,config:this.execution.config??{},trigger:this.execution.triggerPayload??{},frames:{},previousSteps:{}}}createFrame(e){let t=kt(`frm`),n=[...e.path,t],r={frameId:t,nodeId:e.nodeId,nodeType:e.nodeType,path:n,parentFrameId:e.parentFrameId,status:`pending`,attempt:0,iteration:e.iteration,branchKey:e.branchKey};return this.frameRegistry.set(t,r),this.persistFrame(r).catch(()=>void 0),r}async persistFrame(e,t={}){let n=t.requireFrameStorage===!0||this.suspensionStrategy!==`wait-in-process`,r=Zn(e),i=$n(this.executionId,r),a=(this.framePersistenceTasks.get(e.frameId)??Promise.resolve()).catch(()=>void 0).then(async()=>{n?await this.bus.request(P.setFrame,{executionId:this.executionId,frame:r}):await this.bus.requestOptional(P.setFrame,{executionId:this.executionId,frame:r}),i!==void 0&&await this.bus.requestOptional(P.setSpan,{span:i})}).catch(t=>{if(n)throw t;console.warn(`[RuntimeContext] Failed to persist frame ${e.frameId}:`,t)});this.framePersistenceTasks.set(e.frameId,a);try{await a}finally{this.framePersistenceTasks.get(e.frameId)===a&&this.framePersistenceTasks.delete(e.frameId)}}async updateFrame(e,t,n={}){let r=this.frameRegistry.get(e);if(!r)throw Error(`Frame not found: ${e}`);Object.assign(r,t),await this.persistFrame(r,n)}getFrame(e){return this.frameRegistry.get(e)}getFramesByNodeId(e){let t=[];for(let n of this.frameRegistry.values())n.nodeId===e&&t.push(n);return t.sort((e,t)=>(e.startedAt??0)-(t.startedAt??0))}async emitFrameStarted(e){try{await this.bus.emit(D.frame.started,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId,startedAt:e.startedAt})}catch(t){console.error(`[RuntimeContext] frame.started observer failed for ${e.frameId}:`,t)}}async emitFrameCompleted(e,t){try{await this.bus.emit(D.frame.completed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,output:e.output,duration:t,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.completed observer failed for ${e.frameId}:`,t)}}async emitFrameFailed(e,t,n){try{await this.bus.emit(D.frame.failed,{executionId:this.executionId,frameId:e.frameId,nodeId:e.nodeId,error:t,duration:n,completedAt:e.completedAt})}catch(t){console.error(`[RuntimeContext] frame.failed observer failed for ${e.frameId}:`,t)}}};function tr(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function nr(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function rr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ir(e){if(e!=null){if(rr(e)&&typeof e.kind==`string`&&typeof e.id==`string`)return{kind:e.kind,id:e.id};throw Error(`Artifact resolve expression must return an object with string kind and id fields.`)}}function ar(e){if(e!==void 0){if(rr(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function or(e){let{bindingOptions:t,binding:n,existingArtifactRef:r,executionId:i,scope:a,initialData:o,bus:s}=e,c=null;if(r!==void 0){let e=await s.request(p.query,{kind:r.kind,ids:[r.id],currentOnly:!0});if(e.artifacts.length>0)c=e.artifacts[0];else return}else{if(o===void 0)throw Error(`Workflow artifact binding for '${n.kind}' requires an existing artifact reference or explicit initial data from its create expression.`);c=(await s.request(p.create,{kind:n.kind,schemaVersion:n.schemaVersion,scope:a??n.scope,data:o,relations:[],actor:tr(i)})).artifact}return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function sr(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=nr(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:ir(j(o.resolve,s))),l=c===void 0&&o.create!==void 0?ar(j(o.create,s)):void 0,u=await or({bindingOptions:{kind:o.kind,schemaVersion:o.schemaVersion,scope:o.scope,...o.resolve===void 0?{}:{resolve:o.resolve},...o.create===void 0?{}:{create:o.create},...o.statusPath===void 0?{}:{statusPath:o.statusPath},...i===void 0?{}:{schema:i}},binding:o,existingArtifactRef:c,executionId:n.id,scope:o.scope,initialData:l,bus:a});if(u===void 0)throw Error(`Workflow artifact binding could not be resolved for the configured artifact reference.`);return u}const cr=new WeakMap;function lr(e,t){let n=(cr.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return cr.set(e,n.then(()=>void 0,()=>void 0)),n}function ur(e,t){switch(t.operation){case`set`:return t.data;case`merge`:return{...e,...t.data};case`append`:{let n={...e};for(let[r,i]of Object.entries(t.data)){let t=e[r];Array.isArray(t)&&Array.isArray(i)?n[r]=[...t,...i]:n[r]=i}return n}}}function dr(e,t,n){let[r,...i]=t;if(i.length===0)return{...e,[r]:n};let a=e[r]!==null&&typeof e[r]==`object`&&!Array.isArray(e[r])?e[r]:{};return{...e,[r]:dr(a,i,n)}}function fr(e,t,n){return dr(e,pr(t).slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),n)}function pr(e){if(!e.startsWith(`/`)&&e.split(`.`).some(e=>e.length===0))throw Error(`Status path must contain nonempty dot-separated segments`);let t=e.startsWith(`/`)?e:`/${e.split(`.`).map(e=>e.replace(/~/g,`~0`).replace(/\//g,`~1`)).join(`/`)}`;return f.revise.request.shape.statusPath.unwrap().parse(t)}function mr(e,t,n){if(n===`set`||n===`functional`)return[];let r=[];for(let n of Object.keys(t))e[n]!==t[n]&&r.push(`/${n}`);return r}async function hr(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=ur(e,t),r=mr(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function gr(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>lr(r,async()=>{let a=r.statusPath===void 0?void 0:pr(r.statusPath),o=r.current,{nextData:s,operationLabel:c,changedPaths:l}=await hr(o.data,e);if(r.zodSchema!==void 0){let e=r.zodSchema.safeParse(s);if(!e.success)throw Error(`Artifact data validation failed: ${e.error.message}`)}let u=await i.request(p.revise,{...a!==void 0&&{statusPath:a},previous:{refClass:`artifact`,kind:o.kind,id:o.id,revision:o.revision},revision:{kind:o.kind,schemaVersion:r.schemaVersion,scope:o.scope,data:s,relations:o.relations,actor:tr(t)}});r.current=u.artifact;let d=u.artifact.revision;return i.emit(he.artifact.updated,{executionId:t,frameId:n,artifactRef:{kind:u.artifact.kind,id:u.artifact.id},paths:l,operation:c,revision:d}).catch(e=>{console.error(`[ArtifactContext] Failed to emit artifact.updated event:`,e)}),d});return{data:a,updateArtifact:o,updateStatus:async e=>{if(r.statusPath===void 0)throw Error(`updateStatus() called but no statusPath is configured on the artifact binding. Set statusPath in the .artifact() builder call to use updateStatus().`);let t=r.statusPath;return o(n=>fr(n,t,e))}}}function _r(e,t){return{async get(){return(await t.request(D.state.get,{executionId:e})).value},async update(n){let r=await t.request(D.state.get,{executionId:e}),i=structuredClone(r.value),a=await n(i),o=a===void 0?i:a,s=ct(r.value,o);return(await t.request(D.state.patch,{executionId:e,expectedSequence:r.sequence,patch:s,nextValue:o})).value}}}function vr(e,t,n){let r=e.providerContext?.state===`resolved`?e.providerContext:void 0,i=e.providerConfigId??r?.providerConfigId;return{durationMs:t,...n===void 0?{}:{...n.inputTokens===void 0?{}:{inputTokens:n.inputTokens},...n.cachedInputTokens===void 0?{}:{cachedInputTokens:n.cachedInputTokens},...n.outputTokens===void 0?{}:{outputTokens:n.outputTokens},toolCallCount:n.toolCallCount},binding:{adapterName:e.adapterName,...i===void 0?{}:{providerConfigId:i},...r===void 0?{}:{providerDefinitionId:r.definitionId},...e.model===void 0?{}:{model:e.model},...r===void 0?{}:{auth:{mode:r.auth.mode,owner:r.auth.method.owner,methodId:r.auth.method.methodId}}}}}async function yr(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(D.resolveRole,{roleId:e.roleId});if(!r.handled)return{status:`failed`,error:e.unresolvedRoleError};let i=M(e.prompt,R(n)),a=e.completion===void 0?r.data:{...r.data,completion:e.completion};return br({...e,task:i,resolvedConfig:a},t)}async function br(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=performance.now(),r=await t.bus.requestOptional(ne.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:Dr(e.task,e.resolvedConfig,e.outputSchema)});if(!r.handled)return{status:`failed`,error:e.unavailableRuntimeError};let i=await Cr(e,t,r.data.subagentId,{attempts:5}),a=await Or(e,t,r.data.subagentId);if(a===`aborted`)return{status:`cancelled`};if(i||await Cr(e,t,r.data.subagentId,{attempts:1}),!a.handled)return await z(e,t,r.data.subagentId,`Workflow execution '${t.executionId}' could not await ${e.cancellationLabel} '${e.nodeId}'`),{status:`failed`,error:e.unavailableAwaitError};if(t.signal.aborted||a.data.status===`cancelled`)return{status:`cancelled`};if(a.data.status===`completed`){let r=a.data.result??null;try{return{status:`completed`,output:await xr({...e,toolObservations:a.data.toolObservations,usage:a.data.usage},t,r,Sr(n))}}catch(e){if(t.signal.aborted)return{status:`cancelled`};throw e}}return(a.data.status===`timeout`||a.data.status===`waiting_input`)&&await z(e,t,r.data.subagentId,`Workflow execution '${t.executionId}' abandoned non-terminal ${e.cancellationLabel} '${e.nodeId}'`),{status:`failed`,error:`${e.nodeLabel} '${e.nodeId}' subagent ${a.data.status}: ${a.data.error??`no result`}`}}async function xr(e,t,n,r=0){if(e.resultFinalizerId===void 0)return n;if(e.frameId===void 0||e.delegateNodeType===void 0)throw Error(`Delegate result finalizer '${e.resultFinalizerId}' requires frame and delegate node identity`);let i={finalizerId:e.resultFinalizerId,executionId:t.executionId,workflowId:t.workflowId,frameId:e.frameId,nodeId:e.nodeId,nodeType:e.delegateNodeType,rawResult:n,toolObservations:[...e.toolObservations??[]],...e.resolvedConfig===void 0?{}:{economics:vr(e.resolvedConfig,r,e.usage)}},a=await t.bus.requestOptional(D.finalizeDelegateResult,i,{signal:t.signal});if(a.handled)return a.data.output;let{subjects:o}=_e(e.resultFinalizerId),{finalizerId:s,...c}=i;return(await t.bus.request(o.finalize,c,{signal:t.signal})).output}function Sr(e){let t=performance.now()-e;return!Number.isFinite(t)||t<=0?0:Math.min(2**53-1,Math.round(t))}async function Cr(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await wr(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(D.frame.sessionLinked,{executionId:t.executionId,frameId:e.frameId,sessionId:i}),!0)}catch(t){return console.warn(`[workflow-engine] Failed to emit frame.sessionLinked for frame '${e.frameId}' and subagent '${n}'`,t),!1}}async function wr(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await Tr(e,t);if(i===void 0||!i.handled)return;if(i.data.childSessionId!==void 0)return i.data.childSessionId;if(r<n-1&&!await Er(e.signal,20))return}}async function Tr(e,t){try{return await e.bus.requestOptional(ne.getStatus,{subagentId:t},{timeout:25,signal:e.signal})}catch{return}}function Er(e,t){return e.aborted?Promise.resolve(!1):new Promise(n=>{let r,i=t=>{r!==void 0&&(clearTimeout(r),r=void 0),e.removeEventListener(`abort`,a),n(t)},a=()=>i(!1);r=setTimeout(()=>i(!0),t),e.addEventListener(`abort`,a,{once:!0}),e.aborted&&i(!1)})}function Dr(e,t,n){return{task:e,adapterName:t.adapterName,...t.providerConfigId===void 0?{}:{providerConfigId:t.providerConfigId},...t.model===void 0?{}:{model:t.model},...t.reasoningEffort===void 0?{}:{reasoningEffort:t.reasoningEffort},...t.harnessId===void 0?{}:{harnessId:t.harnessId},...t.systemPrompt===void 0?{}:{systemPrompt:t.systemPrompt},...t.contextMode===void 0?{}:{contextMode:t.contextMode},...t.providerContext===void 0?{}:{providerContext:t.providerContext},...t.adapterConfig===void 0?{}:{adapterConfig:t.adapterConfig},...t.tools===void 0?{}:{tools:t.tools},...t.disallowedTools===void 0?{}:{disallowedTools:t.disallowedTools},...t.allowedDirectories===void 0?{}:{allowedDirectories:t.allowedDirectories},...t.completion===void 0?{}:{completion:t.completion},...n===void 0?{}:{responseSchema:n}}}async function Or(e,t,n){if(t.signal.aborted)return await z(e,t,n),`aborted`;let r=t.bus.requestOptional(ne.await,{subagentId:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}},{timeout:0});if(t.signal.aborted)return await z(e,t,n),`aborted`;let i,a=new Promise(e=>{i=()=>e(`aborted`),t.signal.addEventListener(`abort`,i,{once:!0})});try{let i=await Promise.race([r,a]);return i===`aborted`&&await z(e,t,n),i}catch(r){throw await z(e,t,n,`Workflow execution '${t.executionId}' failed awaiting ${e.cancellationLabel} '${e.nodeId}'`),r}finally{i!==void 0&&t.signal.removeEventListener(`abort`,i)}}async function z(e,t,n,r){try{await t.bus.requestOptional(ne.kill,{subagentId:n,reason:r??`Workflow execution '${t.executionId}' cancelled ${e.cancellationLabel} '${e.nodeId}'`})}catch(t){console.warn(`[workflow-engine] Best-effort subagent kill failed for '${n}' (${e.cancellationLabel} '${e.nodeId}')`,t)}}async function kr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=Jn(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return Ar(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?gr({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0,s=t.definition.state===void 0?void 0:_r(t.executionId,t.bus);async function c(n){if(r===void 0){console.warn(`[station-node] updateProgress called without frameId for node '${e.id}'; skipping emit`);return}let i=me[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(D.execution.progress,i)}catch(t){console.error(`[station-node] execution.progress observer failed for ${e.id}:`,t)}}let l;try{l=await a({...t.platformContext,env:t.env,executionId:t.executionId,workflowId:t.workflowId,inputs:t.execution.inputs,config:t.execution.config??{},trigger:t.execution.triggerPayload??{},previousSteps:i,...n.item!==void 0&&{item:n.item},...n.index!==void 0&&{index:n.index},...n.previous!==void 0&&{previous:n.previous},signal:t.signal,...o!==void 0&&{artifact:o},...s!==void 0&&{state:s},bus:t.bus,updateProgress:c})}catch(e){return{status:`failed`,error:e instanceof Error?e.message:String(e)}}return{status:`completed`,output:l}}async function Ar(e,t,n,r){if(e.role===void 0)return{status:`failed`,error:`No handler registered for station node '${e.id}'`};let i=e.outputSchema===void 0?void 0:{schema:e.outputSchema};return yr({nodeId:e.id,nodeLabel:`Station node`,roleId:e.role,prompt:e.prompt,...i===void 0?{}:{outputSchema:i},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.completion===void 0?{}:{completion:e.completion},unresolvedRoleError:`No runtime handler registered for station node '${e.id}', and role '${e.role}' could not be resolved`,unavailableRuntimeError:`Subagent runtime is not available for station node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await station node '${e.id}'`,cancellationLabel:`station`,...r===void 0?{}:{frameId:r}},t,n)}function jr(e,t){return t===void 0?e:{...e,tools:[...t],disallowedTools:void 0}}function Mr(e,t){let n=jr({...t,...e.completion===void 0?{}:{completion:e.completion}},e.allowedTools);return Pr(n)?{...n,contextMode:`fresh`}:n}function Nr(e,t){return jr({...t,completion:e.completion??t.completion??`tool`},e.allowedTools)}function Pr(e){return e.completion===`turn`&&[e.harnessId,e.contextMode,e.adapterConfig,e.tools,e.disallowedTools,e.allowedDirectories].every(e=>e===void 0)}async function Fr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(D.resolveAgent,{agentId:e.agentId});if(!i.handled)return{status:`failed`,error:`Agent '${e.agentId}' could not be resolved for delegate-agent node '${e.id}'`};if(t.signal.aborted)return{status:`cancelled`};let a=Lr(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema},s=Nr(e,i.data);return br({nodeId:e.id,nodeLabel:`Delegate-agent node`,task:a.task,resolvedConfig:s,...o===void 0?{}:{outputSchema:o},unavailableRuntimeError:`Subagent runtime is not available for delegate-agent node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-agent node '${e.id}'`,cancellationLabel:`delegate-agent`,...r===void 0?{}:{frameId:r},...e.resultFinalizerId===void 0?{}:{resultFinalizerId:e.resultFinalizerId},delegateNodeType:`delegate-agent`},t)}async function Ir(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(D.resolveRole,{roleId:e.role});if(!i.handled)return{status:`failed`,error:`Role '${e.role}' could not be resolved for delegate-role node '${e.id}'`};let a=e.outputSchema===void 0?void 0:{schema:e.outputSchema},o=M(e.prompt,R(n)),s=Mr(e,i.data);return br({nodeId:e.id,nodeLabel:`Delegate-role node`,task:o,resolvedConfig:s,...a===void 0?{}:{outputSchema:a},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},unavailableRuntimeError:`Subagent runtime is not available for delegate-role node '${e.id}'`,unavailableAwaitError:`Subagent runtime cannot await delegate-role node '${e.id}'`,cancellationLabel:`delegate-role`,...r===void 0?{}:{frameId:r},...e.resultFinalizerId===void 0?{}:{resultFinalizerId:e.resultFinalizerId},delegateNodeType:`delegate-role`},t)}function Lr(e,t){try{let n=R(t);return{status:`completed`,task:Rr(e.inputExpression===void 0?n:j(e.inputExpression,n))}}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`delegate-agent node '${e.id}': input expression evaluation failed: ${n}`}}}function Rr(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function zr(e,t,n,r){try{let i=j(n,R(r));return Array.isArray(i)?i:{status:`failed`,error:`${t} node '${e}': collection expression did not resolve to an array (got ${typeof i})`}}catch(n){return{status:`failed`,error:`${t} node '${e}': collection expression evaluation failed: ${n instanceof Error?n.message:String(n)}`}}}function Br(e,t,n){for(let r of[...e.nodes].reverse()){let e=n.getFramesByNodeId(r.id);for(let n of e)if(n.parentFrameId===t&&n.status===`completed`)return n.output}}function Vr(e,t,n){return Br(e.body,t,n)}function Hr(e){if(e.length===0)return;let t=new Map,n=new Map;for(let r of e){n.set(r.frameId,r);let e=t.get(r.nodeId)??[];e.push(r),t.set(r.nodeId,e)}return{byNodeId:t,byFrameId:n}}const Ur=new Set([`completed`,`skipped`,`waiting`]);function B(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??Ur;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function V(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:Jn(r),output:n.status===`completed`?n.output:e.output}}function Wr(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController,r=()=>n.abort();return e.addEventListener(`abort`,r,{once:!0}),t.addEventListener(`abort`,r,{once:!0}),n.signal}const Gr=new Set([`completed`,`running`]);function Kr(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function qr(e,t,n,r,i,a,o=`all-settled`){if(t.signal.aborted)return{status:`cancelled`};let s=Object.entries(e.branches);if(s.length===0)return{status:`completed`,output:Xr({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?Wr(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:Wr(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>Jr(s,c,e,p,n,r,i,a,{outerSignal:t.signal,pauseSignal:o===`fail-fast`||u?l.signal:void 0}));if(o===`all-settled`){let e=await Promise.all(u?m.map(e=>e.then(e=>(e.status===`paused`&&l.abort(),e))):m),t=e.find(e=>e.status===`paused`);return t===void 0?{status:`completed`,output:Xr(Zr(s,e),o)}:t}let h=await Yr(s,m,c,l);return h.type===`cancelled`?{status:`cancelled`}:h.type===`paused`?h.outcome:h.type===`failed`?{status:`failed`,error:h.error}:{status:`completed`,output:Xr(Zr(s,h.outcomes),o)}}async function Jr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=B(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:Gr});if(l?.status===`completed`)return{status:`completed`,...l.output===void 0?{}:{output:l.output}};let u=l??r.createFrame({nodeId:n.id,nodeType:`parallel`,path:s,parentFrameId:o,branchKey:e});if(r.signal.aborted)return Kr(u,c)||await $(u,r),{status:`cancelled`};l===void 0&&await X(u,r);let d;try{d=await a(t,r,i,u.frameId,u.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(u,r,t),{status:`failed`,error:t}}switch(d.status){case`completed`:{let e=Br(t,u.frameId,r);return await Z(u,r,e),{status:`completed`,output:e}}case`skipped`:return await Z(u,r),{status:`completed`};case`cancelled`:return Kr(u,c)||await $(u,r),{status:`cancelled`};case`paused`:return d;case`failed`:return await Q(u,r,d.error),{status:`failed`,error:d.error}}}async function Yr(e,t,n,r){let i,a,o=t.map(e=>e.then(e=>(e.status===`failed`&&i===void 0?(i=e.error,n.abort()):e.status===`paused`&&a===void 0&&(a=e,r.abort()),e),e=>{let t=e instanceof Error?e.message:String(e);return i===void 0&&(i=t,n.abort()),{status:`failed`,error:t}})),s=await Promise.all(o);return a===void 0?s.some(e=>e.status===`cancelled`)&&i===void 0?{type:`cancelled`}:i===void 0?{type:`completed`,outcomes:s}:{type:`failed`,error:i}:{type:`paused`,outcome:a}}function Xr(e,t){return{mode:t,branches:e}}function Zr(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=Qr(a)}return n}function Qr(e){switch(e.status){case`completed`:return{status:`fulfilled`,...e.output===void 0?{}:{value:e.output}};case`skipped`:return{status:`fulfilled`,value:null};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:e.pausedAtGateId,pausedAtFrameId:e.pausedAtFrameId};case`failed`:return{status:`rejected`,reason:e.error}}}const $r=new at.default({allErrors:!0,strict:!1});function H(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:$r.compile(t)}}catch(t){return{status:`failed`,error:`Gate '${e}' has an invalid resumeSchema: ${t instanceof Error?t.message:String(t)}`}}}function U(e,t){return e===void 0||e(t)?{valid:!0}:{valid:!1,error:ti(e.errors??[])}}function ei(e,t,n){let r=H(e,t);return r.status===`failed`?{valid:!1,error:r.error}:U(r.validator,n)}function ti(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}function ni(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const ri={action:`approve`,source:`timeout`};function ii(e){return e===void 0?{}:{reason:e}}async function ai(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=ni();o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),e.reject(`timed-out`))},r),a.push(e.promise)}try{let e=await Promise.race(a);return n.removeEventListener(`abort`,i),o!==void 0&&clearTimeout(o),{action:e.action,resumeData:e.resumeData,timedOut:!1,wasCancelled:!1,reason:e.reason}}catch(e){return o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i),e===`timed-out`?{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1}:{action:`reject`,resumeData:null,timedOut:!1,wasCancelled:!0}}}async function oi(e,t,n,r,i,a){let o={required:e.suspensionStrategy!==`wait-in-process`};if(a.timedOut){let a=Date.now();if(r.autoAction===`approve`){let s=U(i,ri);return s.valid?(await W(e,{...r,status:`resumed`,resumeData:ri,resolvedAt:a},o),await G(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:ri}}):(await W(e,{...r,status:`timed-out`,resolvedAt:a},o),await G(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' auto-approve timeout resume data does not match resumeSchema: ${s.error}`})}return await W(e,{...r,status:`timed-out`,resolvedAt:a},o),await G(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Gate '${t.id}' timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}if(a.wasCancelled||e.signal.aborted)return await W(e,{...r,status:`cancelled`,resolvedAt:Date.now()},o),await G(e,t.id,n,{source:`cancelled`}),{status:`cancelled`};let s=Date.now();await W(e,{...r,status:a.action===`reject`?`rejected`:`resumed`,resumeData:a.resumeData,...ii(a.reason),resolvedAt:s},o);try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await G(e,t.id,n,{action:a.action,source:`user`,...ii(a.reason)})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function si(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await di(t,e,r);if(n!==void 0)return n}let a=H(e.id,e.resumeSchema);return a.status===`failed`?{status:`failed`,error:a.error}:ci(t,e,n,r,i,a.validator)}async function ci(e,t,n,r,i,a){let o=M(t.prompt,R(n)),s={executionId:e.executionId,nodeId:t.id,frameId:r,schema:i,prompt:o,status:`waiting`,autoAction:t.autoAction,timeoutMs:t.timeoutMs,createdAt:Date.now()},c=e.suspensionStrategy!==`wait-in-process`;if(await W(e,s,{required:c}),await e.updateFrame(r,{status:`waiting`},{requireFrameStorage:c}),c)return await li(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let l={value:!0},u=ni(),f=e.bus.on(D.gate.respond,async n=>{let{executionId:i,gateId:o,frameId:s,action:c,resumeData:f,reason:p}=n.payload;if(i!==e.executionId||o!==t.id||s!==void 0&&s!==r){try{await n.next()}catch(e){if(e instanceof d)n.setResult({accepted:!1});else throw e}return}if(!l.value){n.setResult({accepted:!1});return}if(!U(a,f).valid){n.setResult({accepted:!1});return}l.value=!1,n.setResult({accepted:!0}),u.resolve({action:c,resumeData:f,reason:p})});await li(e,t,r,i,o,s.createdAt);let p=await ai(u,l,e.signal,t.timeoutMs);return f(),oi(e,t,r,s,a,p)}async function li(e,t,n,r,i,a){try{await e.bus.emit(D.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.title!==void 0&&{title:t.title},autoAction:t.autoAction,timeoutMs:t.timeoutMs,openedAt:a})}catch(e){console.error(`[GateNode] gate.suspended emit failed for '${t.id}':`,e)}}async function ui(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(P.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(P.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function di(e,t,n){let r=await ui(e,t.id,n);if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData!==void 0){let i=ei(t.id,r.schema,r.resumeData);if(!i.valid)return{status:`failed`,error:`Gate '${t.id}' persisted resumeData is invalid: ${i.error}`};try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:r.resumeData})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return await G(e,t.id,n,{action:r.status===`rejected`?`reject`:`approve`,source:`user`,...ii(r.reason)}),{status:`completed`,output:{resumeData:r.resumeData}}}if(r?.status===`waiting`){if(r.timeoutMs!==null&&Date.now()>=r.createdAt+r.timeoutMs){let i=H(t.id,r.schema);return i.status===`failed`?{status:`failed`,error:i.error}:oi(e,t,n,r,i.validator,{action:`reject`,resumeData:null,timedOut:!0,wasCancelled:!1})}return{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}}if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData===void 0)return{status:`failed`,error:`Gate '${t.id}' has status '${r.status}' but resumeData is missing — cannot reconstruct output`};if(r!==null)return{status:`failed`,error:`Gate '${t.id}' cannot resume from status '${r.status}'`}}async function W(e,t,n={}){try{n.required===!0?await e.bus.request(P.setGateInstance,{gate:t}):await e.bus.requestOptional(P.setGateInstance,{gate:t})}catch(e){if(n.required===!0)throw e;console.warn(`[GateNode] Failed to upsert gate instance for '${t.nodeId}':`,e)}}async function G(e,t,n,r){try{await e.bus.emit(D.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[GateNode] gate.resolved emit failed for '${t}':`,e)}}function K(e){return{status:`fulfilled`,...e===void 0?{}:{value:e}}}const fi=new Set([`completed`,`running`]);function pi(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function mi(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=zr(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:vi([])};let c=await hi(s,e,t,n,r,i,a,e.concurrency!==void 0&&e.concurrency>0?e.concurrency:0);if(t.signal.aborted&&c.every(e=>e.status===`cancelled`))return{status:`cancelled`};let l=c.find(e=>e.status===`paused`);return l===void 0?{status:`completed`,output:vi(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function hi(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?Wr(n.signal,c.signal):n.signal,d=u===n.signal?n:n.withSignal(u),f={outerSignal:n.signal,...l?{pauseSignal:c.signal}:{}};if(s===0){let n=e.map((e,n)=>_i(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>gi(e,c)):n)}let p=Array(e.length);for(let n=0;n<e.length;n+=s){if(d.signal.aborted){for(let t=n;t<e.length;t++)p[t]={status:`cancelled`};break}let u=Math.min(n+s,e.length),m=[];for(let s=n;s<u;s++)m.push(_i(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>gi(e,c)):m);for(let e=0;e<h.length;e++)p[n+e]=h[e];if(h.some(e=>e.status===`paused`)){for(let t=u;t<e.length;t++)p[t]={status:`cancelled`};break}}return p}function gi(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function _i(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=B(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:fi});if(u?.status===`completed`)return K(u.output);let d=u??r.createFrame({nodeId:n.id,nodeType:`iterate`,path:s,parentFrameId:o,iteration:t});if(r.signal.aborted)return pi(d,c)||await $(d,r),{status:`cancelled`};u===void 0&&await X(d,r);let f;try{f=await a(n.body,r,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,r,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=Vr(n,d.frameId,r);return await Z(d,r,e),K(e)}case`skipped`:return await Z(d,r),K();case`cancelled`:return pi(d,c)||await $(d,r),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,r,f.error),{status:`rejected`,reason:f.error}}}function vi(e){return{items:e}}const yi=new Set([`completed`,`running`]);async function bi(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=zr(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Si([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await xi(u,o,l,e,t,n,r,i,a);switch(c.push(d),d.status){case`fulfilled`:l=d.value;break;case`rejected`:return{status:`failed`,error:d.reason};case`cancelled`:return{status:`cancelled`};case`paused`:return{status:`paused`,pausedAtGateId:d.pausedAtGateId,pausedAtFrameId:d.pausedAtFrameId}}}return{status:`completed`,output:Si(c)}}async function xi(e,t,n,r,i,a,o,s,c){if(i.signal.aborted)return{status:`cancelled`};let l={...a,item:e,index:t,...n!==void 0&&{previous:n}},u=B(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:yi});if(u?.status===`completed`)return K(u.output);let d=u??i.createFrame({nodeId:r.id,nodeType:`iterate-chain`,path:c,parentFrameId:s,iteration:t});if(i.signal.aborted)return await $(d,i),{status:`cancelled`};u===void 0&&await X(d,i);let f;try{f=await o(r.body,i,l,d.frameId,d.path)}catch(e){let t=e instanceof Error?e.message:String(e);return await Q(d,i,t),{status:`rejected`,reason:t}}switch(f.status){case`completed`:{let e=Vr(r,d.frameId,i);return await Z(d,i,e),K(e)}case`skipped`:return await Z(d,i),K();case`cancelled`:return await $(d,i),{status:`cancelled`};case`paused`:return f;case`failed`:return await Q(d,i,f.error),{status:`rejected`,reason:f.error}}}function Si(e){return{items:e}}async function Ci(e,t,n,r){let i=()=>{t.value&&(t.value=!1,e.reject(`cancelled`))};n.addEventListener(`abort`,i,{once:!0}),n.aborted&&i();let a=[e.promise],o;if(r!==null){let e=new Promise((e,a)=>{o=setTimeout(()=>{t.value&&(t.value=!1,n.removeEventListener(`abort`,i),a(`timed-out`))},r)});a.push(e)}try{return{status:`resolved`,value:await Promise.race(a)}}catch(e){if(e===`timed-out`)return{status:`timed-out`};if(e===`cancelled`)return{status:`cancelled`};throw e}finally{o!==void 0&&clearTimeout(o),n.removeEventListener(`abort`,i)}}const wi={action:`approve`,source:`timeout`};async function q(e,t,n){try{n?await e.bus.request(P.setGateInstance,{gate:t}):await e.bus.requestOptional(P.setGateInstance,{gate:t})}catch(e){if(n)throw e;console.warn(`[LoopNode] Failed to upsert escalation gate for '${t.nodeId}':`,e)}}async function Ti(e,t,n,r,i,a){try{await e.bus.emit(D.gate.suspended,{executionId:e.executionId,frameId:n,nodeId:t.id,schema:r,prompt:i,...t.gate.escalation?.title!==void 0&&{title:t.gate.escalation.title},autoAction:t.gate.escalation?.autoAction??`reject`,timeoutMs:t.gate.escalation?.timeoutMs??null,openedAt:a})}catch(e){console.error(`[LoopNode] gate.suspended emit failed for '${t.id}':`,e)}}async function J(e,t,n,r){try{await e.bus.emit(D.gate.resolved,{executionId:e.executionId,stepId:t,stepType:`gate`,frameId:n,...r})}catch(e){console.error(`[LoopNode] gate.resolved emit failed for '${t}':`,e)}}function Ei(e){let{node:t,ctx:n,parentFrameId:r,validator:i,pending:a,deferred:o}=e;return n.bus.on(D.gate.respond,async e=>{let{executionId:s,gateId:c,frameId:l,action:u,resumeData:f,reason:p}=e.payload;if(s!==n.executionId||c!==t.id||l!==void 0&&l!==r){try{await e.next()}catch(t){if(t instanceof d)e.setResult({accepted:!1});else throw t}return}if(!a.value){e.setResult({accepted:!1});return}if(!U(i,f).valid){e.setResult({accepted:!1});return}a.value=!1,e.setResult({accepted:!0}),o.resolve({action:u,resumeData:f,reason:p})})}async function Di(e,t,n,r,i,a,o){let s=H(e.id,e.gate.escalation?.resumeSchema);if(s.status===`failed`)return{status:`failed`,error:s.error};let c={value:!0},l=ni(),u=Ei({node:e,ctx:t,parentFrameId:n,validator:s.validator,pending:c,deferred:l});await Ti(t,e,n,r.schema,r.prompt??``,r.createdAt);try{let s=await Ci(l,c,t.signal,r.timeoutMs);return s.status===`timed-out`?Ai(t,e,n,r,i,a,o,!1):s.status===`resolved`?Oi(t,e.id,n,r,s.value,i,a,o):(await q(t,{...r,status:`cancelled`,resolvedAt:Date.now()},!1),await J(t,e.id,n,{source:`cancelled`}),{status:`cancelled`})}finally{u()}}async function Oi(e,t,n,r,i,a,o,s){let c=Date.now(),l=i.action===`reject`?`rejected`:`resumed`;await q(e,{...r,status:l,resumeData:i.resumeData,...i.reason===void 0?{}:{reason:i.reason},resolvedAt:c},!1);try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t,resumeData:i.resumeData}),await J(e,t,n,{action:i.action,source:`user`,...i.reason===void 0?{}:{reason:i.reason}})}catch(e){console.error(`[LoopNode] gate.resumed emit failed for '${t}':`,e)}return{status:`completed`,output:Y(`escalate`,o,a,s,i.resumeData)}}async function ki(e,t,n,r,i,a,o){let s=e.gate.escalation;if(s===void 0)return{status:`completed`,output:Y(`escalate`,a,i,o)};let c=M(s.prompt,R(n)),l=s.resumeSchema??{},u={executionId:t.executionId,nodeId:e.id,frameId:r,schema:l,prompt:c,status:`waiting`,autoAction:s.autoAction??`reject`,timeoutMs:s.timeoutMs??null,createdAt:Date.now()},d=t.suspensionStrategy!==`wait-in-process`;return await q(t,u,d),await t.updateFrame(r,{status:`waiting`},{requireFrameStorage:d}),d?(await Ti(t,e,r,l,c,u.createdAt),{status:`paused`,pausedAtGateId:e.id,pausedAtFrameId:r}):Di(e,t,r,u,i,a,o)}async function Ai(e,t,n,r,i,a,o,s=!0){let c=Date.now();if(r.autoAction===`approve`){let l=ei(t.id,r.schema,wi);return l.valid?(await q(e,{...r,status:`resumed`,resumeData:wi,resolvedAt:c},s),await J(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:Y(`escalate`,a,i,o,wi)}):(await q(e,{...r,status:`timed-out`,resolvedAt:c},s),await J(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Loop '${t.id}' escalation gate auto-approve timeout resume data does not match resumeSchema: ${l.error}`})}return await q(e,{...r,status:`timed-out`,resolvedAt:c},s),await J(e,t.id,n,{action:`reject`,source:`timeout`}),{status:`failed`,error:`Loop '${t.id}' escalation gate timed out after ${String(r.timeoutMs)}ms and auto-rejected`}}async function ji(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(P.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(P.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function Mi(e,t,n,r,i,a){let o=await ji(e,t.id,n);if(o!==null){if((o.status===`resumed`||o.status===`rejected`)&&o.resumeData!==void 0){let s=ei(t.id,o.schema,o.resumeData);if(!s.valid)return{status:`failed`,error:`Loop '${t.id}' escalation gate resumeData is invalid: ${s.error}`};try{await e.bus.emit(D.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:o.resumeData})}catch(e){console.error(`[LoopNode] gate.resumed emit failed for '${t.id}':`,e)}return await J(e,t.id,n,{action:o.status===`rejected`?`reject`:`approve`,source:`user`,...o.reason===void 0?{}:{reason:o.reason}}),{status:`completed`,output:Y(`escalate`,i,r,a,o.resumeData)}}return o.status===`waiting`?o.timeoutMs!==null&&Date.now()>=o.createdAt+o.timeoutMs?Ai(e,t,n,o,r,i,a):{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:n}:(o.status===`resumed`||o.status===`rejected`)&&o.resumeData===void 0?{status:`failed`,error:`Loop '${t.id}' escalation gate has status '${o.status}' but resumeData is missing`}:{status:`failed`,error:`Loop '${t.id}' escalation gate cannot resume from status '${o.status}'`}}}const Ni=new Set([`completed`,`running`]);async function Pi(e,t,n,r,i,a,o){let s=B(n.resumeFrames,e.id,{parentFrameId:a,iteration:t,statuses:Ni});if(s?.status===`completed`)return{terminal:!1,output:s.output??null,replayed:!0,gateExpressionCtx:Ii(e,n,r,s.frameId)};let c=s??n.createFrame({nodeId:e.id,nodeType:`loop`,path:o,parentFrameId:a,iteration:t});if(n.signal.aborted)return await $(c,n),{terminal:!0,outcome:{status:`cancelled`}};s===void 0&&await X(c,n);let l=await Li(e,c,n,r,i);if(l!==void 0)return{terminal:!0,outcome:l};let u=Br(e.body,c.frameId,n)??null;return await Z(c,n,u),{terminal:!1,output:u,replayed:!1,gateExpressionCtx:Ii(e,n,r,c.frameId)}}function Fi(e,t,n,r){return B(n.resumeFrames,e.id,{parentFrameId:r,iteration:t,statuses:Ni})!==void 0}function Ii(e,t,n,r){let i=n;for(let n of e.body.nodes){let e=t.getFramesByNodeId(n.id).find(e=>e.parentFrameId===r&&e.status===`completed`);e!==void 0&&(i=V(i,n.id,{status:`completed`,...e.output===void 0?{}:{output:e.output}}))}return i}async function Li(e,t,n,r,i){let a;try{a=await i(e.body,n,r,t.frameId,t.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Q(t,n,r),{status:`failed`,error:r}}switch(a.status){case`failed`:return await Q(t,n,a.error),{status:`failed`,error:a.error};case`cancelled`:return await $(t,n),{status:`cancelled`};case`paused`:return a;case`skipped`:case`completed`:return}}function Ri(e,t,n,r,i){let a=null;if(e.gate.input!==void 0)try{let t=R(r);a=j(e.gate.input,t)}catch(t){let n=t instanceof Error?t.message:String(t);return{status:`failed`,error:`Loop node '${e.id}': gate input expression evaluation failed: ${n}`}}let o=e.gate.config??null,s=i(a,o,{executionId:n.executionId,nodeId:e.id,round:t+1,maxRounds:e.maxRounds});return s.kind===`loop`&&t+1>=e.maxRounds?{kind:`escalate`,reason:`max_rounds_reached`}:s}async function zi(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=t.runtimeLoopGates.get(e.gate.handler);if(o===void 0)return{status:`failed`,error:`Loop node '${e.id}': no gate handler registered for '${e.gate.handler}'`};let s=[],c=0;for(;;){if(t.signal.aborted)return{status:`cancelled`};let l=await Pi(e,c,t,n,r,i,a);if(l.terminal)return l.outcome;if(s.push(l.output),l.replayed){if(c++,Fi(e,c,t,i))continue;if(e.gate.escalation!==void 0&&t.suspensionStrategy!==`wait-in-process`){let n=await Mi(t,e,i,{kind:`escalate`,reason:`resumed_from_gate`},c,s);if(n!==void 0)return n}continue}let u=Ri(e,c,t,l.gateExpressionCtx,o);if(`status`in u)return u;if(u.kind===`pass`)return{status:`completed`,output:Y(`pass`,c+1,u,s)};if(u.kind===`escalate`)return e.gate.escalation===void 0?{status:`completed`,output:Y(`escalate`,c+1,u,s)}:ki(e,t,n,i,u,c+1,s);c++}}function Y(e,t,n,r,i){return{outcome:e,rounds:t,lastGateOutcome:n,bodyOutputs:r,...i===void 0?{}:{resumeData:i}}}async function X(e,t){e.status=`running`,e.startedAt=Date.now(),await t.persistFrame(e),await t.emitFrameStarted(e)}async function Z(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`completed`,e.output=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameCompleted(e,i)}async function Q(e,t,n){let r=Date.now(),i=e.startedAt===void 0?void 0:Math.max(0,r-e.startedAt);e.status=`failed`,e.error=n,e.completedAt=r,await t.persistFrame(e),await t.emitFrameFailed(e,n,i)}async function Bi(e,t){e.status=`skipped`,e.completedAt=Date.now(),await t.persistFrame(e)}async function $(e,t){e.status=`cancelled`,e.completedAt=Date.now(),await t.persistFrame(e)}function Vi(e,t){return!!j(e,R(t))}async function Hi(e,t,n,r,i,a=[]){if(t.signal.aborted)return{status:`cancelled`};switch(e.type){case`sequence`:return r(e,t,n,i,a);case`station`:return kr(e,t,n,i);case`delegate-agent`:return Fr(e,t,n,i);case`delegate-role`:return Ir(e,t,n,i);case`parallel`:return qr(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return si(e,t,n,i??``);case`iterate`:return mi(e,t,n,r,i??``,a);case`iterate-chain`:return bi(e,t,n,r,i??``,a);case`loop`:return zi(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const Ui=new Set([`completed`,`skipped`,`waiting`,`running`]);function Wi(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`||e.type===`loop`}function Gi(e,t,n){return B(e.resumeFrames,t.id,{parentFrameId:n,...Wi(t)?{statuses:Ui}:{}})}function Ki(e,t,n){if(n?.status===`completed`)return V(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return V(e,t.id,{status:`skipped`})}async function qi(e,t,n,r,i,a,o){try{return{result:Vi(e,i)}}catch(e){let i=e instanceof Error?e.message:String(e);return await Q(r.createFrame({nodeId:n.id,nodeType:n.type,path:a,parentFrameId:o}),r,`'${t}' condition evaluation failed: ${i}`),{status:`failed`,error:`'${t}' condition evaluation failed for '${n.id}': ${i}`}}}async function Ji(e,t,n,r,i,a){let o=a??t.createFrame({nodeId:e.id,nodeType:e.type,path:r,parentFrameId:i});if(t.signal.aborted)return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};a===void 0&&await X(o,t);let s;try{s=await Hi(e,t,n,Yi,o.frameId,o.path)}catch(e){let r=e instanceof Error?e.message:String(e);return await Q(o,t,r),{updatedCtx:n,outcome:{status:`failed`,error:r}}}switch(s.status){case`completed`:return await Z(o,t,s.output),{updatedCtx:V(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await Bi(o,t),{updatedCtx:V(n,e.id,{status:`skipped`})};case`cancelled`:return await $(o,t),{updatedCtx:n,outcome:{status:`cancelled`}};case`paused`:return{updatedCtx:n,outcome:s};case`failed`:return await Q(o,t,s.error),{updatedCtx:n,outcome:{status:`failed`,error:s.error}}}}async function Yi(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=Gi(t,n,r),o=Ki(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await qi(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await Bi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=V(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await qi(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await Bi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=V(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||(e?.status===`running`||e?.status===`waiting`)&&Wi(n)?e:void 0,{updatedCtx:c,outcome:l}=await Ji(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}function Xi(e,t){let n=new Set;if(ve(e.root,{enter(e){if(e.type!==`loop`)return;let r=e;t.has(r.gate.handler)||n.add(r.gate.handler)}}),n.size>0)throw Error(`Workflow '${e.id}' is missing loop gate handler(s): ${[...n].join(`, `)}`)}const Zi=new Set;async function Qi(e,t,n){if((await e.requestOptional(P.getRunContext,{executionId:t.executionId})).handled){await $i(e,t.executionId,n);return}await e.request(D.bootstrapAuthorityState,{executionId:t.executionId,terminalAuthority:`authority`,definition:n})}async function $i(e,t,n){return await ea(e,t,n)!==void 0}async function ea(e,t,n){let r=await e.request(P.getRunContext,{executionId:t});if(r.runContext===null)return;if(r.runContext.executionId!==t)throw Error(`Authority bootstrap identity mismatch for '${t}'`);let i=r.runContext.definitionSnapshot;if(i===void 0){await e.request(P.setRunContext,{runContext:{...r.runContext,terminalAuthority:`authority`}});return}if(!ta(i,n))throw Error(`Authority bootstrap definition mismatch for '${t}'`);let a=i;return await e.request(P.setRunContext,{runContext:{...r.runContext,terminalAuthority:`authority`,definitionSnapshot:a},initialState:Ot(a)}),a}function ta(e,t){return i(JSON.parse(JSON.stringify(e)),JSON.parse(JSON.stringify(t)))}function na(e,t){return e.on(D.bootstrapAuthorityState,async n=>{if(!st(n,n.payload.executionId))throw Error(`authority state bootstrap is execution-bound`);let r=await ea(e,n.payload.executionId,n.payload.definition);if(r!==void 0){t?.(n.payload.executionId,r);for(let t of Zi)await t({bus:e,executionId:n.payload.executionId,definition:r,transport:n.transport})}n.setResult({persisted:r!==void 0})})}export{$e as $,I as A,ct as B,hn as C,on as D,dn as E,Lt as F,Ae as G,ot as H,kt as I,Me as J,ke as K,Pt as L,It as M,zt as N,Qt as O,Gt as P,Xe as Q,Dt as R,mn as S,vn as T,it as U,st as V,P as W,Re as X,ze as Y,Ze as Z,bn as _,De as _t,ni as a,Ve as at,xn as b,D as bt,sr as c,Ie as ct,On as d,Ge as dt,Qe as et,Vn as f,We as ft,En as g,He as gt,Dn as h,Ue as ht,Yi as i,Pe as it,Bt as j,Wt as k,er as l,qe as lt,Hn as m,Je as mt,na as n,N as nt,ei as o,Be as ot,qn as p,Ye as pt,Ne as q,Xi as r,Fe as rt,Hr as s,Le as st,Qi as t,je as tt,Yn as u,Ke as ut,Sn as v,Ee as vt,_n as w,pn as x,Cn as y,me as yt,gt as z};
|