@makaio/framework 1.0.0-dev-1784154668798 → 1.0.0-dev-1784706768858
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.makaio-build.json +2 -2
- package/dist/{adapter-B9vVBwli.mjs → adapter-CYobxqN_.mjs} +1 -1
- package/dist/adapters/claude/index.mjs +2 -2
- 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 +2 -2
- package/dist/adapters/node.d.mts +1 -1
- package/dist/adapters/node.mjs +1 -1
- package/dist/artifact-DCkizHkS.mjs +1 -0
- package/dist/attach-error-DCnzW-Yz.mjs +1 -0
- package/dist/authority-state-bootstrap-C_-F_dtq.mjs +1 -0
- package/dist/bus/index.d.mts +99 -4
- package/dist/bus/index.mjs +1 -1
- package/dist/bus-B6SAjgOC.mjs +2 -0
- package/dist/bus-C2l3K74u.mjs +1 -0
- package/dist/{canonical-model-C31NaBJs.mjs → canonical-model-EMRYCVjX.mjs} +1 -1
- package/dist/client-OYk0Ttck.mjs +1 -0
- package/dist/client-binary-version-verifier-Dv7TGFxh.mjs +2 -0
- package/dist/clients/index.d.mts +383 -13
- 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/{context-resolution-D5jHK1w-.d.mts → context-resolution-DZSBOCKY.d.mts} +10 -10
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +2 -2
- package/dist/contracts/artifact/index.mjs +1 -1
- package/dist/contracts/auth/index.d.mts +2 -2
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/canonical-model/index.mjs +1 -1
- package/dist/contracts/client/index.d.mts +3 -3
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/common/index.d.mts +1 -1
- package/dist/contracts/config/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +5 -4
- 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 +133 -94
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +4 -4
- 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/session/index.d.mts +2 -2
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/shared/index.d.mts +2 -2
- package/dist/contracts/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/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/core/index.d.mts +78 -3
- package/dist/core/index.mjs +1 -1
- package/dist/{detached-extension-handle-BVM-Ic-4.mjs → detached-extension-handle-BsywhHfk.mjs} +1 -1
- package/dist/{filesystem-service-qR9Zy5-r.mjs → filesystem-service-Cupz_Z7S.mjs} +1 -1
- package/dist/git/index.mjs +1 -1
- package/dist/{globby-DE358g5u.mjs → globby-DWp7V-P2.mjs} +1 -1
- package/dist/handlers-cMBmexF4.mjs +57 -0
- package/dist/hook-responses-mmqRa2Dq.d.mts +825 -0
- package/dist/{index-Du-AJm69.d.mts → index-0Ju2i8gV.d.mts} +20 -6
- package/dist/{index-DD9inq5h.d.mts → index-4NQLoI7R.d.mts} +1 -1
- package/dist/{index-DAVLhzkq.d.mts → index-8fJ6dkzR.d.mts} +2 -1
- package/dist/{index-BdsuBxEz.d.mts → index-BHQXXd-O.d.mts} +4 -4
- package/dist/{index-ZGPSCZdC.d.mts → index-BKeJ-Act.d.mts} +24 -10
- package/dist/{index-BPBSMsc8.d.mts → index-BWvTZJxe.d.mts} +20 -20
- package/dist/{index-BM7u_OTo.d.mts → index-B_aBwkE-.d.mts} +111 -94
- package/dist/{index-ChB3K_a12.d.mts → index-BhXCCgJV2.d.mts} +1 -1
- package/dist/{index-BcqWLD6J.d.mts → index-BsBvs0aK.d.mts} +117 -45
- package/dist/{index-D_lLZ2dU.d.mts → index-C81hMexK.d.mts} +129 -37
- package/dist/{index-DoJRv-c3.d.mts → index-CFqShlHD.d.mts} +85 -85
- package/dist/{index-DHejCnq8.d.mts → index-CHxWUmmA.d.mts} +3 -3
- package/dist/{index-BfNfKh4y.d.mts → index-CKccv4s2.d.mts} +20 -26
- package/dist/{index-TWs1TQ2-.d.mts → index-Cw7_69gV.d.mts} +1 -1
- package/dist/{index-DE29b4QM.d.mts → index-CzKLLQLw.d.mts} +8 -8
- package/dist/{index-CSyR9Fie2.d.mts → index-D73PTKXG2.d.mts} +3 -3
- package/dist/{index-DA5S_dj8.d.mts → index-DRiTICBU.d.mts} +1 -1
- package/dist/{index-XzetMf0e.d.mts → index-DitLUuR5.d.mts} +126 -42
- package/dist/{index-B_KmL_z8.d.mts → index-jbgHR5J2.d.mts} +1 -1
- package/dist/{index-B96HlWaM.d.mts → index-pjATMrvJ.d.mts} +10 -4
- package/dist/{index-CrbFA2kp.d.mts → index-t9fTvyq6.d.mts} +4 -4
- 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/{lib-DhbCgfYD.mjs → lib-B7TpTzkG.mjs} +3 -3
- package/dist/{lib-6P8_sBCe.mjs → lib-BeMM738r.mjs} +1 -1
- package/dist/{load-extensions-jGQgvw6Z.d.mts → load-extensions-BLdG90Zi.d.mts} +1 -1
- package/dist/{load-extensions-5VckHXuw.mjs → load-extensions-CUmFCcYi.mjs} +1 -1
- package/dist/materialization-s8eR1eQ4.mjs +1 -0
- package/dist/mcp-http-server/index.mjs +1 -1
- package/dist/{namespace-C_phrzqu2.d.mts → namespace-BWsPZGiq2.d.mts} +5 -5
- package/dist/{namespace-CzZmsumy.d.mts → namespace-BeV7LST-.d.mts} +2 -2
- package/dist/{namespace-BTp6-zD8.d.mts → namespace-BsF9IxJ9.d.mts} +53 -5
- package/dist/{namespace-CpSZfHLv.d.mts → namespace-Db_PFX3v.d.mts} +36 -18
- package/dist/{namespace-Bldr5X64.d.mts → namespace-Dvo_7BQw.d.mts} +2 -2
- package/dist/{namespace-BwAiuQ2_.d.mts → namespace-lWlqWTKu.d.mts} +48 -4
- 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 +5 -3
- package/dist/node/transports/index.mjs +2 -2
- package/dist/package-DKnzOvoR.mjs +1 -0
- package/dist/{package-Brt4dhRC.mjs → package-DW1Upu8E.mjs} +1 -1
- package/dist/package.json +1 -1
- package/dist/{packages-BBJsifai.d.mts → packages-DeIgn0Hn.d.mts} +2 -2
- package/dist/packages-zDnokBpl.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/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 +3 -3
- package/dist/runtime-node/index.mjs +22 -22
- package/dist/runtime-node/makaio-config.d.mts +1 -1
- package/dist/runtime-node/makaio-config.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +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/schemas-BJ8VMXhO.mjs +1 -0
- package/dist/schemas-BRxU_oqL.mjs +1 -0
- package/dist/schemas-Dgj3WaOI.mjs +1 -0
- package/dist/{schemas-BLJ2k226.d.mts → schemas-SsGbBOZ-.d.mts} +2 -2
- package/dist/{schemas-Ca3BLPH5.d.mts → schemas-oTIqxZN_.d.mts} +17 -17
- package/dist/scoped-bus-C9BdNwfM.mjs +1 -0
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/index.mjs +1 -1
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- package/dist/services/adapter-subsystem/index.d.mts +3 -3
- package/dist/services/adapter-subsystem/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/capability/index.d.mts +1 -1
- package/dist/services/capability/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/git/namespace.d.mts +2 -2
- package/dist/services/git/namespace.mjs +1 -1
- package/dist/services/git/schemas.d.mts +1 -1
- package/dist/services/git/schemas.mjs +1 -1
- package/dist/services/harness/index.d.mts +3 -3
- package/dist/services/harness/index.mjs +1 -1
- package/dist/services/index.d.mts +73 -51
- 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 +5 -5
- 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/handlers/index.mjs +1 -1
- package/dist/services/session/index.d.mts +9 -9
- package/dist/services/session/index.mjs +1 -1
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/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 +2 -2
- 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/session-editor/index.mjs +1 -1
- package/dist/services/settings/index.d.mts +3 -3
- package/dist/services/settings/namespace.d.mts +14 -14
- 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/turn/schemas.d.mts +24 -2
- package/dist/services/turn/schemas.mjs +1 -1
- package/dist/{session-BxWogVkD.mjs → session-Carng3Yk.mjs} +1 -1
- package/dist/session-idI1jk5X.mjs +76 -0
- package/dist/{session-lineage-CWlcOKBZ.d.mts → session-lineage-Cte63dGx.d.mts} +1 -1
- package/dist/src-XihJcAQS.mjs +1 -0
- package/dist/storage/drizzle/client.d.mts +1 -1
- package/dist/storage/drizzle/client.mjs +1 -1
- package/dist/storage/drizzle/index.d.mts +1 -1
- package/dist/storage/drizzle/index.mjs +1 -1
- package/dist/storage/handlers/drizzle/index.d.mts +1 -1
- package/dist/storage/handlers/drizzle/index.mjs +1 -1
- package/dist/storage/handlers/index.d.mts +1 -1
- package/dist/storage/handlers/index.mjs +1 -1
- package/dist/{tool-approval-service-BgSn_6NT.mjs → tool-approval-service-fIZ9x0kL.mjs} +1 -1
- package/dist/{tools-CWSuNk-M.mjs → tools-Cs2DwjCC.mjs} +1 -1
- package/dist/{transition-CukPcOG5.d.mts → transition-BMYk_IVK.d.mts} +2 -2
- package/dist/{types-DiZJnwN0.d.mts → types-CtSkJqzV.d.mts} +104 -14
- package/dist/{types-Be7wY1De.d.mts → types-LspCUW09.d.mts} +1 -1
- package/dist/ui-components/index.d.mts +4 -4
- package/dist/ui-components/index.mjs +2 -2
- package/dist/ui-kernel/index.d.mts +1 -1
- package/dist/ui-kernel/pages/schemas.d.mts +1 -1
- package/dist/{view-builder-DQiA4wDH.d.mts → view-builder-CpKzgyS2.d.mts} +77 -18
- package/dist/workflow-BX-FxDb0.mjs +1 -0
- package/dist/workflow-engine/index.d.mts +76 -76
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
- package/dist/workflow-worker-DR9qYOFc.mjs +1 -0
- package/package.json +4 -4
- package/dist/artifact-Dnpy5ei_.mjs +0 -1
- package/dist/authority-state-bootstrap-BlbmQ9A5.mjs +0 -1
- package/dist/bus-D-ioC0DE.mjs +0 -1
- package/dist/bus-rgUFuO2a.mjs +0 -2
- package/dist/client-CzPCSeyE.mjs +0 -1
- package/dist/client-binary-version-verifier-CaFlNNjs.mjs +0 -2
- package/dist/definition-ClKlXenJ.d.mts +0 -413
- package/dist/handlers-RGs3eC9X.mjs +0 -57
- package/dist/materialization-BBxXhthv.mjs +0 -1
- package/dist/package-3cW8oIkI.mjs +0 -1
- package/dist/packages-I0D3JP9L.mjs +0 -1
- package/dist/schemas-6H-dlMrB.mjs +0 -1
- package/dist/schemas-DyJHJ8Pm.mjs +0 -1
- package/dist/schemas-th_nuC5t.mjs +0 -1
- package/dist/scoped-bus-CZId-Df8.mjs +0 -1
- package/dist/session-CAjudDuJ.mjs +0 -76
- package/dist/src-T5DtFSyU.mjs +0 -1
- package/dist/workflow-DPeE6-Ta.mjs +0 -1
- package/dist/workflow-worker-CPCh68Qf.mjs +0 -1
- /package/dist/{adapter-auth-runtime-CotG_6M4.mjs → adapter-auth-runtime-DFBLXD5K.mjs} +0 -0
- /package/dist/{adapter-binding-DQ1HrGcH.d.mts → adapter-binding-Dfk_g-lP.d.mts} +0 -0
- /package/dist/{ajv-WvFKnw8d.mjs → ajv-C8r45sFs.mjs} +0 -0
- /package/dist/{await-trigger-COHFNyNi.mjs → await-trigger-UceeyCyi.mjs} +0 -0
- /package/dist/{base-orchestrator-p3zIcnaJ.d.mts → base-orchestrator-5yH3l39s.d.mts} +0 -0
- /package/dist/{capability-service-TCOwWrLi.mjs → capability-service-BzKBK0n2.mjs} +0 -0
- /package/dist/{client-CGEyBWKl.d.mts → client-DYEHDiJN.d.mts} +0 -0
- /package/dist/{client-binary-version-verifier-WsNRplFB.d.mts → client-binary-version-verifier-C12PvQmz.d.mts} +0 -0
- /package/dist/{clients-namespace-ClKm1GLT.d.mts → clients-namespace-DcFmhtLv.d.mts} +0 -0
- /package/dist/{config-namespace-DOw8R5eb.d.mts → config-namespace-DmP7NVju.d.mts} +0 -0
- /package/dist/{create-static-mount-DM9qO98Q.mjs → create-static-mount-BLbqGmva.mjs} +0 -0
- /package/dist/{cross-spawn-CVfmnMVP.mjs → cross-spawn-BXxQUsPS.mjs} +0 -0
- /package/dist/{cursor-storage-BoFVjVGq.mjs → cursor-storage-DCj4uUxr.mjs} +0 -0
- /package/dist/{definition-BZrouYAq.d.mts → definition-BEvV7tbD.d.mts} +0 -0
- /package/dist/{descriptor-to-package-DCwvJoUE.mjs → descriptor-to-package-VfB8lK5w.mjs} +0 -0
- /package/dist/{drizzle-BQDvlDL2.mjs → drizzle-oCH9H53q.mjs} +0 -0
- /package/dist/{esm-1UzF2r1U.mjs → esm-ClQELElL.mjs} +0 -0
- /package/dist/{event-Ddxe4yp9.mjs → event-BOLVCfhH.mjs} +0 -0
- /package/dist/{execution-target-D6PoGaO8.mjs → execution-target-CsZXIvli.mjs} +0 -0
- /package/dist/{extension-discovery-Cce4FmRu.d.mts → extension-discovery-B6p3iZaV.d.mts} +0 -0
- /package/dist/{filesystem-service-CWBzOEAA.d.mts → filesystem-service-CGdboor3.d.mts} +0 -0
- /package/dist/{handler-Bxs0moLY.mjs → handler-GGOD_ofd.mjs} +0 -0
- /package/dist/{identity-D481xSkS.mjs → identity-BmEHHoBw.mjs} +0 -0
- /package/dist/{index-BoCL9IHT.d.mts → index-BDDbcWNI.d.mts} +0 -0
- /package/dist/{index-p1N3ZuqF.d.mts → index-BG9-vQHD.d.mts} +0 -0
- /package/dist/{index-C2PHX5Em.d.mts → index-BSmwpgkR.d.mts} +0 -0
- /package/dist/{index-M8rNEeH8.d.mts → index-BUYyZm5I.d.mts} +0 -0
- /package/dist/{index-Jec13bI-2.d.mts → index-Bd1GC1kU2.d.mts} +0 -0
- /package/dist/{index-D3cH5U0n.d.mts → index-BgpYhR2z.d.mts} +0 -0
- /package/dist/{index-BrvsExEF.d.mts → index-Brdc35b-.d.mts} +0 -0
- /package/dist/{index-4b-ig5Uf.d.mts → index-C96LlS5m.d.mts} +0 -0
- /package/dist/{index-RtP5Mi4D.d.mts → index-CFeY8lfU.d.mts} +0 -0
- /package/dist/{index-NZ-gfUOw.d.mts → index-CcsJnJOD.d.mts} +0 -0
- /package/dist/{index-XLGBNeu0.d.mts → index-CdEhEXlY.d.mts} +0 -0
- /package/dist/{index-DKCFz7dL.d.mts → index-Chy9aknK.d.mts} +0 -0
- /package/dist/{index-BRdPSBFH2.d.mts → index-Ci3_i-WC2.d.mts} +0 -0
- /package/dist/{index-ChsmMZmN.d.mts → index-DC0yVsYL.d.mts} +0 -0
- /package/dist/{index-DIAmg04s.d.mts → index-DEchpaya.d.mts} +0 -0
- /package/dist/{index-CNS1jyBU.d.mts → index-DYUxNOIX.d.mts} +0 -0
- /package/dist/{index-fFSPF7N0.d.mts → index-DaMfTvfz.d.mts} +0 -0
- /package/dist/{index-Dx6P-ajY.d.mts → index-DquI_1X5.d.mts} +0 -0
- /package/dist/{index-DbP0yaRw.d.mts → index-GYZs75UP.d.mts} +0 -0
- /package/dist/{index-CQco6KNL.d.mts → index-oYGf2zIe.d.mts} +0 -0
- /package/dist/{index-BOlzcjwS.d.mts → index-pgYFJ5h6.d.mts} +0 -0
- /package/dist/{json-value-BsWNQQbr.d.mts → json-value-BwVdTylT.d.mts} +0 -0
- /package/dist/{jsonl-transport-B70HQ9l1.mjs → jsonl-transport-D8RBF0dK.mjs} +0 -0
- /package/dist/{lib-C_apP_9s.mjs → lib-3_xcE8J-.mjs} +0 -0
- /package/dist/{model-registry-C3NX834K.mjs → model-registry-CoegIvks.mjs} +0 -0
- /package/dist/{namespace-Bogua97s.d.mts → namespace-8-GrdcbF.d.mts} +0 -0
- /package/dist/{namespace-DNgZ_rfi.d.mts → namespace-B9CYb9Gh.d.mts} +0 -0
- /package/dist/{namespace-DDx4NVJm.mjs → namespace-BHj13hbA.mjs} +0 -0
- /package/dist/{namespace-Dzbt8LqQ.d.mts → namespace-BHliaabz.d.mts} +0 -0
- /package/dist/{namespace-BqlDkdht2.d.mts → namespace-BSXHdCVh2.d.mts} +0 -0
- /package/dist/{namespace-CU1jSw6E.d.mts → namespace-Bd49QmzS.d.mts} +0 -0
- /package/dist/{namespace-kIjqar0Y.mjs → namespace-BeED_Ojz.mjs} +0 -0
- /package/dist/{namespace-SwgMs4rw.d.mts → namespace-D9HNjIdc.d.mts} +0 -0
- /package/dist/{namespace-B1_egU5J.mjs → namespace-DWwWnLBu.mjs} +0 -0
- /package/dist/{namespace-UCwUrFRx.d.mts → namespace-De9Mg3zv.d.mts} +0 -0
- /package/dist/{namespace-CddQuUvG.d.mts → namespace-SQAGytmu.d.mts} +0 -0
- /package/dist/{orchestrator-shared-DrEFeZYw.d.mts → orchestrator-shared-BB6j8ezL.d.mts} +0 -0
- /package/dist/{orchestrator-shared-jYk9mi5C.mjs → orchestrator-shared-CY7Tu7kZ.mjs} +0 -0
- /package/dist/{out-B6fO6go6.mjs → out-CFkI17mk.mjs} +0 -0
- /package/dist/{package-BVm1EakP.d.mts → package-BSG1681x.d.mts} +0 -0
- /package/dist/{providers-namespace-Bl3M8Ibo.d.mts → providers-namespace-sPbGcZ6I.d.mts} +0 -0
- /package/dist/{quick-lru-Coxb6GVa.mjs → quick-lru-CTBjxfgD.mjs} +0 -0
- /package/dist/{registry-ElIHcMM2.mjs → registry-Dw6l7k3e.mjs} +0 -0
- /package/dist/{schema-DOPEco97.d.mts → schema-CfMsufSb.d.mts} +0 -0
- /package/dist/{schemas-B3K1ekm7.d.mts → schemas-B4FyOOJj.d.mts} +0 -0
- /package/dist/{schemas-Dq_g7Giu.d.mts → schemas-B5tMYfhC.d.mts} +0 -0
- /package/dist/{schemas-D_H0ztxl.d.mts → schemas-BAvt2HDy.d.mts} +0 -0
- /package/dist/{schemas-FiDj_kLq.mjs → schemas-BGS9RfqV.mjs} +0 -0
- /package/dist/{schemas-BKgUDm_a2.d.mts → schemas-BKKpQC4X2.d.mts} +0 -0
- /package/dist/{schemas-CzT0LApM.d.mts → schemas-ChF2z4RB.d.mts} +0 -0
- /package/dist/{schemas-DfZ85CRF2.d.mts → schemas-CiWCNQ9a2.d.mts} +0 -0
- /package/dist/{schemas-pl0mzEtO.d.mts → schemas-D55eXBgl.d.mts} +0 -0
- /package/dist/{schemas-CVbfHPw-.d.mts → schemas-DYvvMd3c.d.mts} +0 -0
- /package/dist/{schemas-DPosZWw-.d.mts → schemas-Dmij0PIc.d.mts} +0 -0
- /package/dist/{server-lifecycle-DzO3rjKP.d.mts → server-lifecycle-C-3OgoKi.d.mts} +0 -0
- /package/dist/{server-lifecycle-DLdh0-4H.mjs → server-lifecycle-DV6NMsgH.mjs} +0 -0
- /package/dist/{src-Dqa1n_kI.mjs → src-ftBp6GpR.mjs} +0 -0
- /package/dist/{storage-namespace-D4yQ--Sp.d.mts → storage-namespace-9N9R61pI.d.mts} +0 -0
- /package/dist/{storage-namespace-B1_x8Ho2.mjs → storage-namespace-B1GI4elv.mjs} +0 -0
- /package/dist/{storage-namespace-definition-BzSaRLtZ.d.mts → storage-namespace-definition-V8sc3drq.d.mts} +0 -0
- /package/dist/{supports-color-CCdGjFUY.mjs → supports-color-DwW9N6YC.mjs} +0 -0
- /package/dist/{tray-menu-service-BJ9r7IY3.mjs → tray-menu-service-Dgedanv-.mjs} +0 -0
- /package/dist/{types-Diu9uAnB.d.mts → types-Bju4dmAg.d.mts} +0 -0
- /package/dist/{types-C8_OhAFv.d.mts → types-DBb5jY4Z.d.mts} +0 -0
- /package/dist/{types-Bgb8eQkd.d.mts → types-DVLq657Y.d.mts} +0 -0
- /package/dist/{types-B9QOZAZ5.d.mts → types-DkFvBdIY.d.mts} +0 -0
- /package/dist/{window-registry-CHv3cgSN.d.mts → window-registry-Qcnvlhp7.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-5yH3l39s.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-DCj4uUxr.mjs";import{t as i}from"../globby-DWp7V-P2.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{Q as e,Z as t,a as n,d as r,f as i,l as a,m as o,n as s,o as c,r as l,s as u,x as d}from"./schemas-BRxU_oqL.mjs";import{z as f}from"zod";import{createBusNamespace as p}from"@makaio/framework/core";function m(e){let{$schema:t,...n}=f.toJSONSchema(e);return n}function h(e){return{...e,toRegistration:()=>({kind:e.kind,description:e.description,schemaVersion:e.schemaVersion,dataSchema:m(e.dataSchema),...e.scopeSchema?{scopeSchema:m(e.scopeSchema)}:{},...e.observationSchema?{observationSchema:m(e.observationSchema)}:{},...e.discriminator===void 0?{}:{discriminator:typeof e.discriminator==`string`?e.discriminator:Array.from(e.discriminator)},conflictPolicy:e.conflictPolicy,...e.status?{status:{...e.status,...e.status.values?{values:[...e.status.values]}:{}}}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.indexedFields?{indexedFields:[...e.indexedFields]}:{},...e.searchableFields?{searchableFields:[...e.searchableFields]}:{},...e.projection?{projection:{...e.projection,...e.projection.semanticEvents?{semanticEvents:[...e.projection.semanticEvents]}:{},...e.projection.projectedFields?{projectedFields:e.projection.projectedFields.map(e=>({...e}))}:{},...e.projection.affordances?{affordances:e.projection.affordances.map(e=>structuredClone(e))}:{}}}:{},...e.defaultContext?{defaultContext:structuredClone(e.defaultContext)}:{}})}}function g(e){return{hooks:[...e.hooks]}}function _(e){return JSON.stringify([e.kind,e.id,e.revision])}const v=f.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),y=f.object({target:i,sourceRef:a,relationType:f.string().min(1),hint:t,status:f.enum([`resolved`,`unresolved`]),reason:v.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:f.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:f.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:f.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),b=f.object({rootRef:a,refs:f.array(y),resolved:f.array(o)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(_));n.has(_(e.rootRef))||t.addIssue({code:f.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(_(e.sourceRef))||t.addIssue({code:f.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(_(e.target))||t.addIssue({code:f.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function x(e){let t=b.parse(e),n=new Map(t.resolved.map(e=>[E(e),e])),r=new Map;for(let e of t.refs){let t=E(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(E(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${E(t.rootRef)}'`);let a=S(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return T(a,e),e}}}function S(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:w(e,r,i,new Set([E(e)]))}}function C(e,t,n,r,i,a,o){let s=E(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:w(e,i,a,c)}}function w(e,t,n,r){return(t.get(E(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=E(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`}:C(e.target,a,e.relationType,e.hint,t,n,r)})}function T(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)T(n,t)}}function E(e){return JSON.stringify([e.kind,e.id,e.revision])}const D={"kind.register":{request:n,response:f.object({registered:f.boolean()})},"kind.list":{request:f.object({kind:f.string().min(1).optional()}),response:f.object({kinds:f.array(n)})},"relation-type.register":{request:d,response:f.object({registered:f.boolean()})},"relation-type.list":{request:f.object({type:f.string().min(1).optional()}),response:f.object({relationTypes:f.array(d)})},create:{request:o.omit({id:!0,revision:!0,timestamp:!0}),response:f.object({artifact:o})},revise:{request:f.object({previous:a,revision:o.omit({id:!0,revision:!0,timestamp:!0})}),response:f.object({artifact:o})},resolve:{request:f.object({ref:a}),response:f.object({artifact:o.nullable()})},query:{request:u,response:f.object({artifacts:f.array(o)})},compare:{request:s,response:l},resolveContext:{request:f.object({ref:a,selectors:e.optional(),maxDepth:f.number().int().min(1).max(20).default(5)}),response:f.object({context:b})},created:f.object({artifact:o}),revised:f.object({previous:a,artifact:o}),"relation.added":f.object({artifact:a,relation:r}),"observation.added":f.object({artifact:a,observation:c}),"status.changed":f.object({artifact:a,path:f.string().min(1),previous:f.unknown().optional(),current:f.unknown().optional()}),"kind.changed":f.object({kind:f.string().min(1),schemaVersion:f.string().min(1)})},O=p(`artifact`,D),k=O.subjects;export{y as a,g as c,x as i,h as l,D as n,v as o,k as r,b as s,O as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{stage;constructor(e,t){super(t instanceof Error?t.message:String(t),{cause:t}),this.stage=e,this.name=`SessionAgentAttachError`}};function t(t){let n=t,r=new Set;for(;n instanceof Error&&!r.has(n);){if(n instanceof e)return n;r.add(n),n=n.cause}}export{t as n,e as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./chunk-DTipWd-i.mjs";import{t}from"./ajv-C8r45sFs.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{realpathSync as c}from"node:fs";import{localSubject as l}from"@makaio/framework/core";import{NoHandlerError as u}from"@makaio/framework/bus";import{ArtifactSubjects as d,ExecutionLinkListQuerySchema as f,ExecutionLinkSchema as p,ExecutionListQuerySchema as m,ExecutionStatusSchema as h,ExecutionsByArtifactRefsQuerySchema as g,GateInstanceListQuerySchema as _,JsonPatchOperationSchema as v,JsonValueSchema as y,SessionSubjects as b,SpanRecordSchema as x,SubagentSubjects as S,WORKFLOW_CANCELLED_REASON as ee,WorkLogFrameEntrySchema as te,WorkerNodeSubjects as ne,WorkflowDefinitionSchema as re,WorkflowError as ie,WorkflowErrorCode as ae,WorkflowExecutionSchema as C,WorkflowFinalizationClaimSchema as w,WorkflowFinalizerIdSchema as oe,WorkflowFrameStateSchema as se,WorkflowGateInstanceSchema as T,WorkflowListQuerySchema as ce,WorkflowRunContextSchema as le,WorkflowSchemas as ue,WorkflowSubjects as de,WorkflowSubjects as E,WorkflowWorkerSourceSchema as fe,createStepCancelSubject as pe,createWorkflowDelegateResultFinalizerNamespace as me,walkWorkflowDefinition as he}from"@makaio/framework/contracts";import{index as D,primaryKey as ge,uniqueIndex as _e}from"drizzle-orm/sqlite-core";import{index as O,primaryKey as ve,uniqueIndex as ye}from"drizzle-orm/pg-core";import{defineDualTable as k}from"@makaio/framework/storage/drizzle";import{sql as be}from"drizzle-orm";import{createStorageNamespaceDefinition as xe}from"@makaio/framework/storage";import{evaluateSync as A,resolveTemplate as j}from"@makaio/framework/expression";import*as Se from"node:os";const Ce=k(`workflow_finalizations`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.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=>[_e(`uniq_workflow_finalizations_transition`).on(e.transitionKey),D(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)],postgres:e=>[ye(`uniq_workflow_finalizations_transition`).on(e.transitionKey),O(`idx_workflow_finalizations_recovery`).on(e.finalizerId,e.state)]}),we=Ce.sqlite;Ce.postgres;function Te(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 Ee=k(`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`),...Te(e),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull(),canvasLayout:e.jsonCol(`canvas_layout`),source:e.jsonCol(`source`),successFinalizerId:e.text(`success_finalizer_id`),executionHints:e.jsonCol(`execution_hints`)}),{sqlite:e=>[_e(`uniq_workflow_definitions_name_scope`).on(e.name,e.scopeType,e.scopeKind,e.scopeId),D(`idx_workflow_definitions_scope`).on(e.scopeType,e.scopeKind,e.scopeId)],postgres:e=>[ye(`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)]}),De=Ee.sqlite,M=k(`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`),...Te(e)}),{sqlite:e=>[D(`idx_workflow_executions_status`).on(e.status),D(`idx_workflow_executions_scope_started`).on(e.scopeType,e.scopeKind,e.scopeId,e.startedAt),D(`idx_workflow_executions_workflow_started`).on(e.workflowId,e.startedAt),D(`idx_workflow_executions_artifact`).on(e.artifactKind,e.artifactId,e.startedAt)],postgres: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)]}),Oe=M.sqlite,ke=k(`workflow_execution_frames`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[D(`idx_workflow_execution_frames_execution`).on(e.executionId),D(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)],postgres:e=>[O(`idx_workflow_execution_frames_execution`).on(e.executionId),O(`idx_workflow_execution_frames_parent`).on(e.parentFrameId)]}),Ae=ke.sqlite,je=k(`workflow_gate_instances`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[D(`idx_workflow_gate_instances_execution`).on(e.executionId),D(`idx_workflow_gate_instances_frame`).on(e.frameId)],postgres:e=>[O(`idx_workflow_gate_instances_execution`).on(e.executionId),O(`idx_workflow_gate_instances_frame`).on(e.frameId)]}),Me=je.sqlite,Ne=k(`workflow_step_spans`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[ge({columns:[e.executionId,e.frameId]}),D(`idx_workflow_step_spans_status`).on(e.status)],postgres:e=>[ve({columns:[e.executionId,e.frameId]}),O(`idx_workflow_step_spans_status`).on(e.status)]}),Pe=Ne.sqlite,Fe=k(`workflow_execution_links`,e=>({sourceExecutionId:e.text(`source_execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),targetExecutionId:e.text(`target_execution_id`).notNull().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),linkType:e.text(`link_type`).$type().notNull(),metadata:e.jsonCol(`metadata`)}),{sqlite:e=>[ge({columns:[e.sourceExecutionId,e.targetExecutionId]}),D(`idx_workflow_execution_links_target`).on(e.targetExecutionId)],postgres:e=>[ve({columns:[e.sourceExecutionId,e.targetExecutionId]}),O(`idx_workflow_execution_links_target`).on(e.targetExecutionId)]}),Ie=Fe.sqlite,Le=k(`workflow_run_contexts`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.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(be`'{}'`),triggerPayload:e.jsonCol(`trigger_payload`).notNull(),artifactRef:e.jsonCol(`artifact_ref`),executionHints:e.jsonCol(`execution_hints`),dispatchMetadata:e.jsonCol(`dispatch_metadata`),scopeType:e.textEnum(`scope_type`,{enum:[`global`,`workspace`,`session`,`external`]}).notNull().default(`global`).$type(),scopeKind:e.text(`scope_kind`).notNull().default(``),scopeId:e.text(`scope_id`).notNull().default(``),cancelSubject:e.text(`cancel_subject`).notNull(),context:e.jsonCol(`context`).notNull(),env:e.jsonCol(`env`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),suspensionStrategy:e.text(`suspension_strategy`).$type(),terminalAuthority:e.text(`terminal_authority`).$type()}),{sqlite:e=>[D(`idx_run_contexts_workflow`).on(e.workflowId)],postgres:e=>[O(`idx_run_contexts_workflow`).on(e.workflowId)]}),Re=Le.sqlite,ze=k(`worklog_summaries`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.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=>[D(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),D(`idx_worklog_summaries_status`).on(e.status)],postgres:e=>[O(`idx_worklog_summaries_workflow_started`).on(e.workflowId,e.startedAt),O(`idx_worklog_summaries_status`).on(e.status)]}),Be=ze.sqlite,Ve=k(`worklog_frame_entries`,e=>({frameId:e.text(`frame_id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[D(`idx_worklog_frame_entries_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_frame_entries_execution`).on(e.executionId)]}),He=Ve.sqlite,Ue=k(`worklog_artifact_writes`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[D(`idx_worklog_artifact_writes_execution`).on(e.executionId)],postgres:e=>[O(`idx_worklog_artifact_writes_execution`).on(e.executionId)]}),We=Ue.sqlite,Ge=k(`worklog_gate_events`,e=>({id:e.text(`id`).primaryKey(),executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[D(`idx_worklog_gate_events_execution`).on(e.executionId),D(`idx_worklog_gate_events_status`).on(e.status)],postgres:e=>[O(`idx_worklog_gate_events_execution`).on(e.executionId),O(`idx_worklog_gate_events_status`).on(e.status)]}),Ke=Ge.sqlite,qe=k(`workflow_execution_state`,e=>({executionId:e.text(`execution_id`).primaryKey().references(()=>M.columnPair(`id`),{onDelete:`cascade`}),sequence:e.int4(`sequence`).notNull().default(0),value:e.jsonCol(`value`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()})),Je=qe.sqlite,Ye=k(`workflow_execution_state_events`,e=>({executionId:e.text(`execution_id`).notNull().references(()=>M.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=>[ge({columns:[e.executionId,e.sequence]})],postgres:e=>[ve({columns:[e.executionId,e.sequence]})]}),Xe=Ye.sqlite,Ze=n.object({executionId:n.string().min(1),status:h.optional(),error:n.string().nullable().optional(),reason:n.string().nullable().optional(),completedAt:n.number().nullable().optional()}),Qe=n.enum([`completed`,`failed`,`cancelled`]),$e=te.extend({status:n.literal(`running`),startedAt:n.number().int().nonnegative()}),et=te.extend({status:Qe,startedAt:n.number().int().nonnegative(),completedAt:n.number().int().nonnegative(),durationMs:n.number().int().nonnegative()}),tt=xe(`workflow`,{schemas:{get:{request:n.object({id:n.string()}),response:n.object({workflow:re.nullable()})},set:{request:n.object({workflow:re}),response:n.object({id:n.string()})},delete:{request:n.object({id:n.string()}),response:n.object({deleted:n.boolean()})},list:{request:ce,response:n.object({workflows:n.array(re)})},getExecution:{request:n.object({executionId:n.string()}),response:n.object({execution:C.nullable()})},setExecution:{request:n.object({execution:C}),response:n.object({id:n.string()})},setExecutionStart:{request:n.object({execution:C,runContext:le,initialState:y.optional(),executionLinks:n.array(p).optional()}),response:n.object({id:n.string(),executionId:n.string()})},setExternalExecutionStart:l({request:n.object({execution:C.extend({status:n.literal(`running`)}),frame:$e.optional()}),response:n.object({executionId:n.string(),frameId:n.string().optional()})}),settleExternalExecution:l({request:n.object({executionId:n.string().min(1),status:Qe,error:n.string().min(1).optional(),reason:n.string().min(1).optional(),completedAt:n.number().int().nonnegative().optional(),frame:et.optional()}),response:n.object({success:n.boolean()})}),updateExecution:{request:Ze,response:n.object({success:n.boolean()})},pauseRunningExecution:l({request:n.object({executionId:n.string().min(1)}),response:n.object({paused:n.boolean()})}),claimFinalization:l({request:n.object({claim:w}),response:n.object({claimed:n.boolean()})}),listClaimedFinalizations:l({request:n.object({finalizerId:oe}),response:n.object({claims:n.array(w)})}),listUnpublishedFinalizations:l({request:n.object({finalizerId:oe}),response:n.object({claims:n.array(w)})}),publishFinalization:l({request:n.object({claim:w}),response:n.object({})}),acknowledgeFinalization:l({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:l({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:m,response:n.object({executions:n.array(C)})},listExecutionsByArtifactRefs:{request:g,response:n.object({executionsByRef:n.record(n.string(),n.array(C))})},setFrame:{request:n.object({executionId:n.string().min(1),frame:se}),response:n.object({frameId:n.string()})},getFrame:{request:n.object({frameId:n.string().min(1)}),response:n.object({frame:se.nullable()})},listFrames:{request:n.object({executionId:n.string().min(1)}),response:n.object({frames:n.array(se)})},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:C.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:_,response:n.object({gates:n.array(T)})},listPausedGateTimeouts:l({request:n.object({}),response:n.object({gates:n.array(T)})}),setSpan:{request:n.object({span:x}),response:n.object({id:n.string()})},listSpans:{request:n.object({executionId:n.string()}),response:n.object({spans:n.array(x)})},setExecutionLink:{request:n.object({link:p}),response:n.object({id:n.string()})},listExecutionLinks:{request:f,response:n.object({links:n.array(p)})},setRunContext:l({request:n.object({runContext:le,initialState:y.optional()}),response:n.object({executionId:n.string()})}),getRunContext:l({request:n.object({executionId:n.string().min(1)}),response:n.object({runContext:le.nullable()})}),initializeState:l({request:n.object({executionId:n.string().min(1),initialValue:y}),response:n.object({})}),getState:l({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:y}).nullable()})}),patchState:l({request:n.object({executionId:n.string().min(1),expectedSequence:n.number().int().nonnegative(),nextValue:y}),response:n.object({executionId:n.string().min(1),sequence:n.number().int().positive(),patch:n.array(v),value:y})})},extensions:{drizzle:{workflowDefinitions:De,workflowExecutions:Oe,workflowExecutionFrames:Ae,workflowGateInstances:Me,workflowStepSpans:Pe,workflowExecutionLinks:Ie,workflowRunContexts:Re,worklogSummaries:Be,worklogFrameEntries:He,worklogArtifactWrites:We,worklogGateEvents:Ke,workflowExecutionState:Je,workflowExecutionStateEvents:Xe,workflowFinalizations:we}}}),N=tt.subjects;var nt=e(t(),1);function rt(e,t){let n=[];return it(n,``,e,t),n}function it(e,t,n,r){if(Array.isArray(n)&&Array.isArray(r)){ot(e,t,n,r);return}if(st(n)&&st(r)){at(e,t,n,r);return}ut(n,r)||e.push({op:`replace`,path:t,value:r})}function at(e,t,n,r){let i=Array.from(new Set([...Object.keys(n),...Object.keys(r)])).sort();for(let a of i){let i=ct(n,a),o=ct(r,a),s=`${t}/${lt(a)}`;if(!i&&o){e.push({op:`add`,path:s,value:r[a]});continue}if(i&&!o){e.push({op:`remove`,path:s});continue}it(e,s,n[a],r[a])}}function ot(e,t,n,r){let i=Math.min(n.length,r.length);for(let a=0;a<i;a++)it(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 st(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ct(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function lt(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function ut(e,t){return Object.is(e,t)}const dt={stepTimeoutMs:300*1e3,stepCooldownMs:500,busAuth:{kind:`none`},platformDefaults:{cwd:process.cwd()},cancelTimeoutMs:1e4},ft=new nt.default({allErrors:!0,strict:!1}),pt=new Map,mt=new Map;function ht(e){let t=e.$id;return typeof t==`string`?t:void 0}function gt(e,t,n){let r=ht(t);return r===void 0?`workflow:${e}:${n}`:`schema-id:${r}`}function _t(e,t){try{return JSON.stringify(vt(t))}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Workflow '${e}' state schema is invalid: ${n}`)}}function vt(e){if(Array.isArray(e))return e.map(vt);if(typeof e!=`object`||!e)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,vt(t[e])]))}function yt(e,t,n){let r=mt.get(t);if(r!==void 0&&r!==n)throw Error(`Workflow '${e}' state schema reuses JSON Schema $id '${t}' with different content`);return ft.getSchema(t)}function bt(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 xt(e,t){let n=_t(e,t),r=gt(e,t,n),i=pt.get(r);if(i!==void 0)return i;let a=ht(t);if(a!==void 0){let t=yt(e,a,n);if(t!==void 0)return pt.set(r,t),t}try{let e=ft.compile(t);return pt.set(r,e),a!==void 0&&mt.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 St(e,t,n){if(e.state===void 0)return;let r=xt(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: ${bt(r.errors)}`)}function Ct(e){if(e.state===void 0)return;let t=e.state.initial===void 0?{}:e.state.initial;return St(e,t,`initial`),t}function P(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function wt(e,t,n){let r=e?j(e,n):t,i=s(t),l=s(a(r)?r:s(t,r)),u,d;try{u=c(i),d=c(l)}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 Tt(e){return e instanceof Error&&(`code`in e||`killed`in e)}function Et(e){let t=e[0];return t===void 0||t.trim()===``?null:t}function Dt(e){let{command:t,cwd:n,env:i,timeoutMs:a,signal:o}=e,s=Et(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 Ot(e){let{step:t,workspaceRoot:n,expressionContext:r,signal:i}=e,a=wt(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=>j(e,r));if(Et(o)===null)return{status:`failed`,error:`Shell step command is empty`};let s=Object.fromEntries(Object.entries(t.env??{}).map(([e,t])=>[e,j(t,r)])),c=t.timeoutMs??3e5;try{let{stdout:e}=await Dt({command:o,cwd:a,env:s,timeoutMs:c,signal:i});return{status:`completed`,stdout:e}}catch(e){if(!Tt(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 kt(e,t,n){if(!(await e.request(N.updateExecution,{executionId:t.id,status:n.status,error:n.error,reason:n.reason,completedAt:n.completedAt})).success)throw Error(`Workflow execution not found: ${t.id}`)}function At(e,t){return e===t||t===`completed`&&e===`finalizing`}async function jt(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){let i,a,o=!0,s=await jt(e,t,async()=>{let s=await n(),c=Promise.withResolvers(),l=e.lifecyclePublications.get(t)??Promise.resolve();return o=!e.publishingLifecycleExecutions.has(t),a=l.catch(()=>void 0).then(async()=>{await c.promise,e.publishingLifecycleExecutions.add(t);try{await r(s)}finally{e.publishingLifecycleExecutions.delete(t)}}),e.lifecyclePublications.set(t,a),i=c.resolve,s});if(i?.(),a!==void 0){let n=a;n.then(()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)},()=>{e.lifecyclePublications.get(t)===n&&e.lifecyclePublications.delete(t)}),o&&await n}return s}async function Mt(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(N.failFinalization,{executionId:n.executionId,claimToken:n.claimToken,error:r,settledAt:i});return}}async function Nt(e){for(let t of e.successFinalizers?.values()??[]){let{claims:n}=await e.bus.request(N.listClaimedFinalizations,{finalizerId:t.finalizerId});for(let r of n)await Mt(e,t,r);let{claims:r}=await e.bus.request(N.listUnpublishedFinalizations,{finalizerId:t.finalizerId});for(let t of r)await e.bus.request(N.publishFinalization,{claim:t})}}async function Pt(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(N.getExecution,{executionId:n})).execution?.status!==`running`||!(await e.bus.request(N.claimFinalization,{claim:i})).claimed?!1:(t.status=`finalizing`,e.activeExecutions.delete(n),!0),async t=>{t&&await Mt(e,a,i)});return}let o=Date.now();await F(e,n,async()=>(await e.bus.request(N.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`completed`,t.completedAt=o,await kt(e.bus,t,{status:t.status,completedAt:o}),e.activeExecutions.delete(n),!0):!1,async i=>{i&&await e.bus.emit(E.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(N.getExecution,{executionId:n})).execution?.status===`running`?(t.status=`failed`,t.error=r,t.completedAt=a,await kt(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(E.execution.failed,{executionId:n,workflowId:t.workflowId,error:r,completedAt:a})}})}function Ft(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(pe(o.cancelSubject),{executionId:t,stepId:r,reason:n}).catch(t=>{console.error(`[WorkflowFinalizer] Failed to emit cancellation for ${e}:`,t)})}}async function It(e,t,n){let r=await e.bus.request(N.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(N.cancelPausedExecution,{executionId:t,completedAt:a,reason:n});if(o)return e.activeExecutions.delete(t),{workflowId:i,completedAt:a,gates:s}}async function Lt(e,t,n){let r=e.activeExecutions.get(t);if(!r||r.execution.status!==`running`)return It(e,t,n);let{execution:i}=r;i.status=`cancelled`,i.reason=n,i.completedAt=Date.now();try{for(let[n,r]of e.shellAbortControllers)n.startsWith(`${t}:`)&&(r.abort(),e.shellAbortControllers.delete(n));Ft(e,t,n),await kt(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 Rt(e,t,n){return await F(e,t,()=>Lt(e,t,n),async r=>{if(r!==void 0){for(let n of r.gates)await e.bus.emit(E.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(E.execution.cancelled,{executionId:t,workflowId:r.workflowId,reason:n,completedAt:r.completedAt})}})!==void 0}const zt=[`darwin`,`linux`,`win32`];function Bt(e){return zt.find(t=>t===e)??`linux`}function Vt(e,t){return t}function Ht(e,t){return{...t}}function Ut(e){return e.reason instanceof Error?e.reason.message:typeof e.reason==`string`&&e.reason.length>0?e.reason:ee}async function Wt(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(N.getExecution,{executionId:t});a?.status===`running`&&(r.execution=a,await Rt(i,t,Ut(n))||console.error(`[WorkflowExecutor] Failed to persist runner cancellation for ${t}: execution not active`))}async function Gt(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(N.pauseRunningExecution,{executionId:t.executionId});if(!r){let{execution:e}=await n.bus.request(N.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(E.execution.paused,{executionId:t.executionId,workflowId:t.workflowId,pausedAtGateId:t.pausedAtGateId,pausedAtFrameId:t.pausedAtFrameId})})}async function Kt(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(N.getExecution,{executionId:t.executionId});if(i?.status===`running`){if(n.execution=i,t.status===`completed`){await Pt(r,n.execution,t.executionId,n.execution.startedAt);return}if(t.status===`cancelled`){await Rt(r,t.executionId,t.reason??ee);return}if(t.status===`failed`){await I(r,n.execution,t.executionId,t.error);return}}}function qt(e,t){return{source:{kind:`path`,path:t.filePath},executionId:t.executionId,workflowId:t.workflowId,triggerPayload:t.sanitizedTriggerPayload,inputs:t.boundInputs,config:t.boundConfig,...t.artifactRef===void 0?{}:{artifactRef:t.artifactRef},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:e.config.busUrl,busAuth:e.config.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:e.config.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:`wait-in-process`,terminalAuthority:`authority`}}function Jt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=qt(e,t);return Promise.resolve().then(()=>r.run(c,s.signal)).then(async t=>{if(t.status===`paused`){await Gt(e,t);return}await Kt(e,t)}).catch(async t=>{if(s.signal.aborted){await Wt(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 Yt(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},...t.executionHints===void 0?{}:{executionHints:t.executionHints},scope:t.scope,busUrl:n.busUrl,busAuth:n.busAuth,context:e.resolveWorkflowContext(t.workspaceRoot),env:n.platformDefaults.env??{},coordinatorSessionId:t.coordinatorSessionId,cancelSubject:`workflow.${t.executionId}.cancel`,suspensionStrategy:t.suspensionStrategy??`wait-in-process`,terminalAuthority:t.terminalAuthority??`authority`}}function Xt(e,t){let{executionId:n}=t,{workflowRunner:r,workflowAbortControllers:i,executionTasks:a,activeExecutions:o}=e,s=new AbortController;i.set(n,s);let c=Yt(e,t),l=t.dispatchMetadata===void 0?void 0:{dispatchMetadata:t.dispatchMetadata};return Promise.resolve().then(()=>r.run(c,s.signal,void 0,l)).then(async t=>{if(t.status===`paused`){await Gt(e,t);return}await Kt(e,t)}).catch(async t=>{if(s.signal.aborted){await Wt(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 Zt(e,t,n={}){let r=Qt(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},...e.executionHints===void 0?{}:{executionHints:e.executionHints},scope:e.scope,workspaceRoot:e.context.repoPath,suspensionStrategy:e.suspensionStrategy,terminalAuthority:e.terminalAuthority??`authority`,...r===void 0?{}:{dispatchMetadata:r}}}function Qt(e,t){return t.resume===!0?{...e.dispatchMetadata,resume:!0}:e.dispatchMetadata}const $t=/(?:^|[_-])(authorization|token|cookie|password|set[_-]?cookie|api[_-]?key|secret|credential|private[_-]?key|api[_-]?secret)(?:$|[_-])/i;function en(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=tn(e,i,0,t);r!==void 0&&(n[e]=r)}return Object.keys(n).length>0?n:void 0}function tn(e,t,n,r){if(!(r.remainingBytes<=0||n>6)&&(r.remainingBytes-=e.length,!(r.remainingBytes<=0))){if($t.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=tn(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=tn(t,a,n+1,r);i!==void 0&&(e[t]=i)}return e}}}function nn(e){return(e?.requirements?.capabilities??[]).length>0}function rn(e,t,n){let r=t?.requirements?.capabilities??[];if(nn(t))return{run:(t,i)=>e.request(ne.dispatch,{config:t,requirements:{customCapabilities:r},...n===void 0?{}:{metadata:n}},{signal:i})}}function an(e,t){let n=rn(e.bus,t.executionHints,t.dispatchMetadata);return n===void 0?e.workflowRunner===void 0?e.runExecution(t.executionId).finally(()=>{e.executionTasks.delete(t.executionId)}):Xt(e.buildRunnerTaskDeps(e.workflowRunner),t):Xt(e.buildRunnerTaskDeps(n),t)}async function on(e,t,n,r){let i=Ct(r);await e.request(N.setExecutionStart,{execution:t,runContext:n,initialState:i})}async function sn(e,t){try{await e.emit(E.execution.started,t)}catch(e){console.error(`[WorkflowExecutor] execution.started listener failed:`,e)}}async function cn(e,t){await e.request(b.close,{sessionId:t}).catch(e=>{console.error(`[WorkflowExecutor] Failed to close coordinator session "${t}" after launch failure:`,e)})}function ln(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 un(e,t,n,r,i){await e.request(N.setExecutionStart,{execution:t,runContext:n,...r===void 0?{}:{initialState:r},...i!==void 0&&i.length>0?{executionLinks:[...i]}:{}})}function dn(e,t){let n=e?.source;if(n===void 0)return;let r=fe.parse(n);return r.kind===`path`&&!a(r.path)?{...r,path:s(t,r.path)}:r}function fn(e,t,n){return dn(t,n)??{kind:`definition`,workflowId:e}}function pn(e,t,n,r){if(!(t.kind===`definition`||e.workflowRunner!==void 0||nn(n)))throw new ie(ae.NOT_EXECUTABLE,`Workflow source execution '${r}' requires a workflow runner or WorkerNode capability requirements.`)}async function mn(e,t,n,r){return e.set(t,n),await r,t}async function hn(e,t){let{workflow:n}=await e.request(N.get,{id:t});if(!n)throw Error(`Workflow not found: ${t}`);return n}function gn(e,t){if(e===void 0&&t===void 0)return;let n=[...new Set([...e?.capabilities??[],...t?.capabilities??[]])];return{...e,...t,...n.length>0&&{capabilities:n}}}function _n(e,t){if(e===void 0&&t===void 0)return;let n=gn(e?.requirements,t?.requirements),r=e?.providers!==void 0||t?.providers!==void 0?{...e?.providers,...t?.providers}:void 0;return{...e,...t,...n!==void 0&&{requirements:n},...r!==void 0&&{providers:r}}}async function vn(e,t,n,r){let{sessionId:i}=await e.request(b.create,{parentSessionId:t,branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function yn(e,t,n={}){let r=await hn(e.bus,t);return bn(e,t,{...n,workflow:r})}async function bn(e,t,n){let{bus:r,activeExecutions:i,executionTasks:a}=e,{workflow:o,parentSessionId:s,triggerPayload:c,artifactRef:l,executionHints:u,scopeOverride:d}=n,f=P(`wfx`),p=en(c),m=Vt(o,n.input===void 0?{}:n.input),h=Ht(o,n.config??{}),g=d??o.scope,_=_n(o.executionHints,u),v=await e.resolveExecutionWorkspaceRoot(s),y=n.executionSource??fn(t,_,v),b=n.definitionSnapshot??(y.kind===`definition`?o:void 0);pn(e,y,_,t);let x=await vn(r,s,o.name,v),S=!1;try{let s=e.buildRunContext({executionId:f,workflowId:t,coordinatorSessionId:x,source:y,...b===void 0?{}:{definitionSnapshot:b},inputs:m,config:h,scope:g,triggerPayload:p??{},...l===void 0?{}:{artifactRef:l},..._===void 0?{}:{executionHints:_},workspaceRoot:v}),c=ln(i,f,o,x,m,h,p,g,s);await un(r,c,s,y.kind===`definition`?Ct(o):void 0,n.executionLinks?.(f));let u=c.startedAt,d=sn(r,{executionId:f,workflowId:t,coordinatorSessionId:x,startedAt:u,...l===void 0?{}:{artifactRef:l}}),ee=an(e,{executionId:f,workflowId:t,workflow:o,...b===void 0?{}:{definitionSnapshot:b},source:y,coordinatorSessionId:x,sanitizedTriggerPayload:p??{},boundInputs:m,boundConfig:h,scope:g,...l===void 0?{}:{artifactRef:l},..._===void 0?{}:{executionHints:_},workspaceRoot:v,suspensionStrategy:s.suspensionStrategy});return S=!0,mn(a,f,ee,d)}catch(e){throw S||(i.delete(f),a.delete(f),await cn(r,x)),e}}function xn(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 Sn(e,t,n,r){let{sessionId:i}=await e.request(b.create,{...t===void 0?{}:{parentSessionId:t},branchKind:`coordinator`,title:`Workflow: ${n}`,targetWorkingDirectory:r});return i}async function Cn(e,t,n={}){let{bus:r,activeExecutions:i,executionTasks:a}=e,{artifactRef:o,executionHints:s,parentSessionId:c,triggerPayload:l,scopeOverride:u}=n,d=P(`wfx`),f=en(l),p=n.input===void 0?{}:n.input,m=n.config??{},h=u??{type:`global`},g=await e.resolveExecutionWorkspaceRoot(c),_=await Sn(r,c,t,g),v=d,y={id:d,workflowId:v,coordinatorSessionId:_,status:`running`,inputs:p,config:m,startedAt:Date.now(),triggerPayload:f,...o===void 0?{}:{artifactRef:o},scope:h},b=!1;try{let{workflowRunner:c}=e;if(c===void 0)throw Error(`[WorkflowExecutor] startFileExecution called without a workflow runner`);let l=e.buildRunContext({executionId:d,workflowId:v,coordinatorSessionId:_,source:{kind:`path`,path:t},inputs:p,config:m,scope:h,triggerPayload:f??{},...o===void 0?{}:{artifactRef:o},...s===void 0?{}:{executionHints:s},workspaceRoot:g});await un(r,y,l,void 0,n.executionLinks?.(d)),xn(i,y,t,h,l);let u=sn(r,{executionId:d,workflowId:v,coordinatorSessionId:_,startedAt:y.startedAt,...o===void 0?{}:{artifactRef:o}}),x=Jt(e.buildRunnerTaskDeps(c),{executionId:d,workflowId:v,filePath:t,coordinatorSessionId:_,sanitizedTriggerPayload:f??{},boundInputs:p,boundConfig:m,...o===void 0?{}:{artifactRef:o},...s===void 0?{}:{executionHints:s},scope:h,workspaceRoot:g});return b=!0,mn(a,d,x,u)}catch(e){throw b||(i.delete(d),a.delete(d),await cn(r,_)),e}}function wn(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 L(e){let t={...e,input:e.inputs,steps:e.frames};return{...t,ctx:t}}function Tn(){return{context:{repoPath:process.cwd(),makaioHome:process.env.MAKAIO_HOME??`${Se.homedir()}/.makaio`,os:process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`,arch:process.arch},env:{}}}function En(e){return{...e,path:[...e.path]}}function Dn(e){if(e===`station`||e===`delegate-agent`||e===`delegate-role`||e===`gate`)return e}function On(e,t){let n=Dn(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 kn=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=Tn(),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=P(`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=En(e),i=On(this.executionId,r),a=(this.framePersistenceTasks.get(e.frameId)??Promise.resolve()).catch(()=>void 0).then(async()=>{n?await this.bus.request(N.setFrame,{executionId:this.executionId,frame:r}):await this.bus.requestOptional(N.setFrame,{executionId:this.executionId,frame:r}),i!==void 0&&await this.bus.requestOptional(N.setSpan,{span:i})}).catch(t=>{if(n)throw t;console.warn(`[RuntimeContext] Failed to persist frame ${e.frameId}:`,t)});this.framePersistenceTasks.set(e.frameId,a);try{await a}finally{this.framePersistenceTasks.get(e.frameId)===a&&this.framePersistenceTasks.delete(e.frameId)}}async updateFrame(e,t,n={}){let r=this.frameRegistry.get(e);if(!r)throw Error(`Frame not found: ${e}`);Object.assign(r,t),await this.persistFrame(r,n)}getFrame(e){return this.frameRegistry.get(e)}getFramesByNodeId(e){let t=[];for(let n of this.frameRegistry.values())n.nodeId===e&&t.push(n);return t.sort((e,t)=>(e.startedAt??0)-(t.startedAt??0))}async emitFrameStarted(e){try{await this.bus.emit(E.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(E.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(E.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 An(e){return{kind:`workflow-execution`,id:e,displayName:`Workflow Engine`}}function jn(e,t,n){return{inputs:n.inputs,config:n.config??{},trigger:n.triggerPayload,scope:n.scope,context:n.context,env:n.env,execution:{id:t.id,workflowId:t.workflowId,scope:t.scope},workflow:{id:e.id,name:e.name,scope:e.scope}}}function Mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nn(e){if(e!=null){if(Mn(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 Pn(e){if(e!==void 0){if(Mn(e))return e;throw Error(`Artifact create expression must return an object.`)}}async function Fn(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(d.query,{kind:r.kind,ids:[r.id],currentOnly:!0});if(e.artifacts.length>0)c=e.artifacts[0];else return}else c=(await s.request(d.create,{kind:n.kind,schemaVersion:n.schemaVersion,scope:a??n.scope,data:o??{},relations:[],actor:An(i)})).artifact;return{current:c,schemaVersion:n.schemaVersion,statusPath:t.statusPath,zodSchema:t.schema}}async function In(e){let{definition:t,execution:n,runContext:r,zodSchema:i,bus:a}=e,o=t.artifact;if(o===void 0)return;let s=jn(t,n,r),c=r.artifactRef??(o.resolve===void 0?void 0:Nn(A(o.resolve,s))),l=c===void 0&&o.create!==void 0?Pn(A(o.create,s)):void 0,u=await Fn({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 Ln=new WeakMap;function Rn(e,t){let n=(Ln.get(e)??Promise.resolve()).catch(()=>void 0).then(t);return Ln.set(e,n.then(()=>void 0,()=>void 0)),n}function zn(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 Bn(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]:Bn(a,i,n)}}function Vn(e,t,n){return Bn(e,t.startsWith(`/`)?t.slice(1).split(`/`):t.split(`.`),n)}function Hn(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 Un(e,t){if(typeof t==`function`)return{nextData:await t(Object.freeze({...e})),operationLabel:`functional`,changedPaths:[]};let n=zn(e,t),r=Hn(e,n,t.operation);return{nextData:n,operationLabel:t.operation,changedPaths:r}}function Wn(e){let{executionId:t,frameId:n,bindingState:r,bus:i}=e,a=Object.freeze({...r.current.data}),o=async e=>Rn(r,async()=>{let a=r.current,{nextData:o,operationLabel:s,changedPaths:c}=await Un(a.data,e);if(r.zodSchema!==void 0){let e=r.zodSchema.safeParse(o);if(!e.success)throw Error(`Artifact data validation failed: ${e.error.message}`)}let l=await i.request(d.revise,{previous:{refClass:`artifact`,kind:a.kind,id:a.id,revision:a.revision},revision:{kind:a.kind,schemaVersion:r.schemaVersion,scope:a.scope,data:o,relations:a.relations,actor:An(t)}});r.current=l.artifact;let u=l.artifact.revision;return i.emit(de.artifact.updated,{executionId:t,frameId:n,artifactRef:{kind:l.artifact.kind,id:l.artifact.id},paths:c,operation:s,revision:u}).catch(e=>{console.error(`[ArtifactContext] Failed to emit artifact.updated event:`,e)}),u});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=>Vn(n,t,e))}}}function Gn(e,t){return{async get(){return(await t.request(E.state.get,{executionId:e})).value},async update(n){let r=await t.request(E.state.get,{executionId:e}),i=structuredClone(r.value),a=await n(i),o=a===void 0?i:a,s=rt(r.value,o);return(await t.request(E.state.patch,{executionId:e,expectedSequence:r.sequence,patch:s,nextValue:o})).value}}}function Kn(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 qn(e,t,n){if(t.signal.aborted)return{status:`cancelled`};let r=await t.bus.requestOptional(E.resolveRole,{roleId:e.roleId});if(!r.handled)return{status:`failed`,error:e.unresolvedRoleError};let i=j(e.prompt,L(n)),a=e.completion===void 0?r.data:{...r.data,completion:e.completion};return Jn({...e,task:i,resolvedConfig:a},t)}async function Jn(e,t){if(t.signal.aborted)return{status:`cancelled`};let n=performance.now(),r=await t.bus.requestOptional(S.spawn,{parentSessionId:t.execution.coordinatorSessionId??t.executionId,depth:1,config:tr(e.task,e.resolvedConfig,e.outputSchema)});if(!r.handled)return{status:`failed`,error:e.unavailableRuntimeError};let i=await Zn(e,t,r.data.subagentId,{attempts:5}),a=await nr(e,t,r.data.subagentId);if(a===`aborted`)return{status:`cancelled`};if(i||await Zn(e,t,r.data.subagentId,{attempts:1}),!a.handled)return await R(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 Yn({...e,toolObservations:a.data.toolObservations,usage:a.data.usage},t,r,Xn(n))}}catch(e){if(t.signal.aborted)return{status:`cancelled`};throw e}}return(a.data.status===`timeout`||a.data.status===`waiting_input`)&&await R(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 Yn(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{subjects:i}=me(e.resultFinalizerId);return(await t.bus.request(i.finalize,{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:Kn(e.resolvedConfig,r,e.usage)}},{signal:t.signal})).output}function Xn(e){let t=performance.now()-e;return!Number.isFinite(t)||t<=0?0:Math.min(2**53-1,Math.round(t))}async function Zn(e,t,n,r){if(e.frameId===void 0)return!0;try{let i=await Qn(t,n,r.attempts);return i===void 0?!1:(await t.bus.emit(E.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 Qn(e,t,n){for(let r=0;r<n;r+=1){if(e.signal?.aborted)return;let i=await $n(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 $n(e,t){try{return await e.bus.requestOptional(S.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 tr(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 nr(e,t,n){if(t.signal.aborted)return await R(e,t,n),`aborted`;let r=t.bus.requestOptional(S.await,{subagentId:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}},{timeout:0});if(t.signal.aborted)return await R(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 R(e,t,n),i}catch(r){throw await R(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 R(e,t,n,r){try{await t.bus.requestOptional(S.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 rr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=wn(n.frames),a=t.runtimeHandlers.get(e.id);if(a===void 0)return ir(e,t,n,r);let o=t.artifactBinding!==void 0&&r!==void 0?Wn({executionId:t.executionId,frameId:r,bindingState:t.artifactBinding,bus:t.bus}):void 0,s=t.definition.state===void 0?void 0:Gn(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=ue[`execution.progress`].parse({executionId:t.executionId,workflowId:t.workflowId,frameId:r,nodeId:e.id,progress:n,emittedAt:Date.now()});try{await t.bus.emit(E.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 ir(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 qn({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 ar(e,t){return t===void 0?e:{...e,tools:[...t],disallowedTools:void 0}}function or(e,t){let n=ar({...t,...e.completion===void 0?{}:{completion:e.completion}},e.allowedTools);return cr(n)?{...n,contextMode:`fresh`}:n}function sr(e,t){return ar({...t,completion:e.completion??t.completion??`tool`},e.allowedTools)}function cr(e){return e.completion===`turn`&&[e.harnessId,e.contextMode,e.adapterConfig,e.tools,e.disallowedTools,e.allowedDirectories].every(e=>e===void 0)}async function lr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(E.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=dr(e,n);if(a.status===`failed`)return a;let o=e.outputSchema===void 0?void 0:{schema:e.outputSchema},s=sr(e,i.data);return Jn({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 ur(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=await t.bus.requestOptional(E.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=j(e.prompt,L(n)),s=or(e,i.data);return Jn({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 dr(e,t){try{let n=L(t);return{status:`completed`,task:fr(e.inputExpression===void 0?n:A(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 fr(e){if(typeof e==`string`)return e;if(e===void 0)return``;try{return JSON.stringify(e,null,2)??``}catch{return String(e)}}function pr(e,t,n,r){try{let i=A(n,L(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 mr(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 hr(e,t,n){return mr(e.body,t,n)}function gr(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 _r=new Set([`completed`,`skipped`,`waiting`]);function z(e,t,n){let r=e?.byNodeId.get(t)??[],i=n.statuses??_r;return r.find(e=>e.parentFrameId===n.parentFrameId&&e.branchKey===n.branchKey&&e.iteration===n.iteration&&i.has(e.status))}function B(e,t,n){let r={...e.frames,[t]:n};return{...e,frames:r,previousSteps:wn(r),output:n.status===`completed`?n.output:e.output}}function vr(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 yr=new Set([`completed`,`running`]);function br(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function xr(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:wr({},o)};let c=new AbortController,l=new AbortController,u=t.suspensionStrategy!==`wait-in-process`,d=o===`fail-fast`?vr(c.signal,l.signal):u?l.signal:void 0,f=d===void 0?t.signal:vr(t.signal,d),p=f===t.signal?t:t.withSignal(f),m=s.map(([s,c])=>Sr(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:wr(Tr(s,e),o)}:t}let h=await Cr(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:wr(Tr(s,h.outcomes),o)}}async function Sr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l=z(r.resumeFrames,n.id,{parentFrameId:o,branchKey:e,statuses:yr});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 br(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=mr(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 br(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 Cr(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 wr(e,t){return{mode:t,branches:e}}function Tr(e,t){let n={};for(let r=0;r<e.length;r++){let[i]=e[r],a=t[r];n[i]=Er(a)}return n}function Er(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 Dr=new nt.default({allErrors:!0,strict:!1});function V(e,t){if(t===void 0)return{status:`ok`};try{return{status:`ok`,validator:Dr.compile(t)}}catch(t){return{status:`failed`,error:`Gate '${e}' has an invalid resumeSchema: ${t instanceof Error?t.message:String(t)}`}}}function H(e,t){return e===void 0||e(t)?{valid:!0}:{valid:!1,error:Or(e.errors??[])}}function U(e,t,n){let r=V(e,t);return r.status===`failed`?{valid:!1,error:r.error}:H(r.validator,n)}function Or(e){return e.length===0?`schema validation failed`:e.map(e=>`${e.instancePath.length>0?e.instancePath:`/`} ${e.message??`is invalid`}`).join(`; `)}function kr(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const Ar={action:`approve`,source:`timeout`};function jr(e){return e===void 0?{}:{reason:e}}async function Mr(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=kr();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 Nr(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=H(i,Ar);return s.valid?(await W(e,{...r,status:`resumed`,resumeData:Ar,resolvedAt:a},o),await G(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:{resumeData:Ar}}):(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,...jr(a.reason),resolvedAt:s},o);try{await e.bus.emit(E.gate.resumed,{executionId:e.executionId,frameId:n,nodeId:t.id,resumeData:a.resumeData}),await G(e,t.id,n,{action:a.action,source:`user`,...jr(a.reason)})}catch(e){console.error(`[GateNode] gate.resumed emit failed for '${t.id}':`,e)}return{status:`completed`,output:{resumeData:a.resumeData}}}async function Pr(e,t,n,r){if(t.signal.aborted)return{status:`cancelled`};let i=e.resumeSchema??{};if(t.suspensionStrategy!==`wait-in-process`){let n=await Rr(t,e,r);if(n!==void 0)return n}let a=V(e.id,e.resumeSchema);return a.status===`failed`?{status:`failed`,error:a.error}:Fr(t,e,n,r,i,a.validator)}async function Fr(e,t,n,r,i,a){let o=j(t.prompt,L(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 Ir(e,t,r,i,o,s.createdAt),{status:`paused`,pausedAtGateId:t.id,pausedAtFrameId:r};let l={value:!0},d=kr(),f=e.bus.on(E.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 u)n.setResult({accepted:!1});else throw e}return}if(!l.value){n.setResult({accepted:!1});return}if(!H(a,f).valid){n.setResult({accepted:!1});return}l.value=!1,n.setResult({accepted:!0}),d.resolve({action:c,resumeData:f,reason:p})});await Ir(e,t,r,i,o,s.createdAt);let p=await Mr(d,l,e.signal,t.timeoutMs);return f(),Nr(e,t,r,s,a,p)}async function Ir(e,t,n,r,i,a){try{await e.bus.emit(E.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 Lr(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function Rr(e,t,n){let r=await Lr(e,t.id,n);if((r?.status===`resumed`||r?.status===`rejected`)&&r.resumeData!==void 0){let i=U(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(E.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`,...jr(r.reason)}),{status:`completed`,output:{resumeData:r.resumeData}}}if(r?.status===`waiting`){if(r.timeoutMs!==null&&Date.now()>=r.createdAt+r.timeoutMs){let i=V(t.id,r.schema);return i.status===`failed`?{status:`failed`,error:i.error}:Nr(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(N.setGateInstance,{gate:t}):await e.bus.requestOptional(N.setGateInstance,{gate:t})}catch(e){if(n.required===!0)throw e;console.warn(`[GateNode] Failed to upsert gate instance for '${t.nodeId}':`,e)}}async function G(e,t,n,r){try{await e.bus.emit(E.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 zr=new Set([`completed`,`running`]);function Br(e,t){return e.status===`running`&&t.pauseSignal?.aborted===!0&&!t.outerSignal.aborted}async function Vr(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=pr(e.id,`iterate`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Gr([])};let c=await Hr(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:Gr(c)}:{status:`paused`,pausedAtGateId:l.pausedAtGateId,pausedAtFrameId:l.pausedAtFrameId}}async function Hr(e,t,n,r,i,a,o,s){let c=new AbortController,l=n.suspensionStrategy!==`wait-in-process`,u=l?vr(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)=>Wr(e,n,t,d,r,i,a,o,f));return Promise.all(l?n.map(e=>Ur(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(Wr(e[s],s,t,d,r,i,a,o,f));let h=await Promise.all(l?m.map(e=>Ur(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 Ur(e,t){return e.then(e=>(e.status===`paused`&&t.abort(),e))}async function Wr(e,t,n,r,i,a,o,s,c){if(r.signal.aborted)return{status:`cancelled`};let l={...i,item:e,index:t},u=z(r.resumeFrames,n.id,{parentFrameId:o,iteration:t,statuses:zr});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 Br(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=hr(n,d.frameId,r);return await Z(d,r,e),K(e)}case`skipped`:return await Z(d,r),K();case`cancelled`:return Br(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 Gr(e){return{items:e}}const Kr=new Set([`completed`,`running`]);async function qr(e,t,n,r,i,a){if(t.signal.aborted)return{status:`cancelled`};let o=pr(e.id,`iterate-chain`,e.collection,n);if(!Array.isArray(o))return o;let s=o;if(s.length===0)return{status:`completed`,output:Yr([])};let c=[],l;for(let o=0;o<s.length;o++){if(t.signal.aborted)return{status:`cancelled`};let u=s[o],d=await Jr(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:Yr(c)}}async function Jr(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=z(i.resumeFrames,r.id,{parentFrameId:s,iteration:t,statuses:Kr});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=hr(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 Yr(e){return{items:e}}async function Xr(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 Zr={action:`approve`,source:`timeout`};async function q(e,t,n){try{n?await e.bus.request(N.setGateInstance,{gate:t}):await e.bus.requestOptional(N.setGateInstance,{gate:t})}catch(e){if(n)throw e;console.warn(`[LoopNode] Failed to upsert escalation gate for '${t.nodeId}':`,e)}}async function Qr(e,t,n,r,i,a){try{await e.bus.emit(E.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(E.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 $r(e){let{node:t,ctx:n,parentFrameId:r,validator:i,pending:a,deferred:o}=e;return n.bus.on(E.gate.respond,async e=>{let{executionId:s,gateId:c,frameId:l,action:d,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 u)e.setResult({accepted:!1});else throw t}return}if(!a.value){e.setResult({accepted:!1});return}if(!H(i,f).valid){e.setResult({accepted:!1});return}a.value=!1,e.setResult({accepted:!0}),o.resolve({action:d,resumeData:f,reason:p})})}async function ei(e,t,n,r,i,a,o){let s=V(e.id,e.gate.escalation?.resumeSchema);if(s.status===`failed`)return{status:`failed`,error:s.error};let c={value:!0},l=kr(),u=$r({node:e,ctx:t,parentFrameId:n,validator:s.validator,pending:c,deferred:l});await Qr(t,e,n,r.schema,r.prompt??``,r.createdAt);try{let s=await Xr(l,c,t.signal,r.timeoutMs);return s.status===`timed-out`?ri(t,e,n,r,i,a,o,!1):s.status===`resolved`?ti(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 ti(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(E.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 ni(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=j(s.prompt,L(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 Qr(t,e,r,l,c,u.createdAt),{status:`paused`,pausedAtGateId:e.id,pausedAtFrameId:r}):ei(e,t,r,u,i,a,o)}async function ri(e,t,n,r,i,a,o,s=!0){let c=Date.now();if(r.autoAction===`approve`){let l=U(t.id,r.schema,Zr);return l.valid?(await q(e,{...r,status:`resumed`,resumeData:Zr,resolvedAt:c},s),await J(e,t.id,n,{action:`approve`,source:`timeout`}),{status:`completed`,output:Y(`escalate`,a,i,o,Zr)}):(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 ii(e,t,n){if(e.suspensionStrategy!==`wait-in-process`)return(await e.bus.request(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n})).gate;let r=await e.bus.requestOptional(N.getGateInstance,{executionId:e.executionId,nodeId:t,frameId:n});return r.handled?r.data.gate:null}async function ai(e,t,n,r,i,a){let o=await ii(e,t.id,n);if(o!==null){if((o.status===`resumed`||o.status===`rejected`)&&o.resumeData!==void 0){let s=U(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(E.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?ri(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 oi=new Set([`completed`,`running`]);async function si(e,t,n,r,i,a,o){let s=z(n.resumeFrames,e.id,{parentFrameId:a,iteration:t,statuses:oi});if(s?.status===`completed`)return{terminal:!1,output:s.output??null,replayed:!0,gateExpressionCtx:li(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 ui(e,c,n,r,i);if(l!==void 0)return{terminal:!0,outcome:l};let u=mr(e.body,c.frameId,n)??null;return await Z(c,n,u),{terminal:!1,output:u,replayed:!1,gateExpressionCtx:li(e,n,r,c.frameId)}}function ci(e,t,n,r){return z(n.resumeFrames,e.id,{parentFrameId:r,iteration:t,statuses:oi})!==void 0}function li(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=B(i,n.id,{status:`completed`,...e.output===void 0?{}:{output:e.output}}))}return i}async function ui(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 di(e,t,n,r,i){let a=null;if(e.gate.input!==void 0)try{let t=L(r);a=A(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 fi(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 si(e,c,t,n,r,i,a);if(l.terminal)return l.outcome;if(s.push(l.output),l.replayed){if(c++,ci(e,c,t,i))continue;if(e.gate.escalation!==void 0&&t.suspensionStrategy!==`wait-in-process`){let n=await ai(t,e,i,{kind:`escalate`,reason:`resumed_from_gate`},c,s);if(n!==void 0)return n}continue}let u=di(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)}:ni(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 pi(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 mi(e,t){return!!A(e,L(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 rr(e,t,n,i);case`delegate-agent`:return lr(e,t,n,i);case`delegate-role`:return ur(e,t,n,i);case`parallel`:return xr(e,t,n,r,i??``,a,e.mode??`all-settled`);case`gate`:return Pr(e,t,n,i??``);case`iterate`:return Vr(e,t,n,r,i??``,a);case`iterate-chain`:return qr(e,t,n,r,i??``,a);case`loop`:return fi(e,t,n,r,i??``,a);default:return{status:`failed`,error:`Unknown node type: ${String(e.type)}`}}}const gi=new Set([`completed`,`skipped`,`waiting`,`running`]);function _i(e){return e.type===`parallel`||e.type===`iterate`||e.type===`iterate-chain`||e.type===`loop`}function vi(e,t,n){return z(e.resumeFrames,t.id,{parentFrameId:n,..._i(t)?{statuses:gi}:{}})}function yi(e,t,n){if(n?.status===`completed`)return B(e,t.id,{status:`completed`,...n.output===void 0?{}:{output:n.output}});if(n?.status===`skipped`)return B(e,t.id,{status:`skipped`})}async function bi(e,t,n,r,i,a,o){try{return{result:mi(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 xi(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,Si,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:B(n,e.id,{status:`completed`,output:s.output})};case`skipped`:return await pi(o,t),{updatedCtx:B(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 Si(e,t,n,r,i=[]){let a=n;for(let n of e.nodes){if(t.signal.aborted)return{status:`cancelled`};let e=vi(t,n,r),o=yi(a,n,e);if(o!==void 0){a=o;continue}if(n.when!==void 0){let e=await bi(n.when,`when`,n,t,a,i,r);if(`status`in e)return e;if(!e.result){await pi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=B(a,n.id,{status:`skipped`});continue}}if(n.skip!==void 0){let e=await bi(n.skip,`skip`,n,t,a,i,r);if(`status`in e)return e;if(e.result){await pi(t.createFrame({nodeId:n.id,nodeType:n.type,path:i,parentFrameId:r}),t),a=B(a,n.id,{status:`skipped`});continue}}let s=e?.status===`waiting`&&n.type===`gate`||(e?.status===`running`||e?.status===`waiting`)&&_i(n)?e:void 0,{updatedCtx:c,outcome:l}=await xi(n,t,a,i,r,s);if(a=c,l!==void 0)return l}return{status:`completed`}}function Ci(e,t){let n=new Set;if(he(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(`, `)}`)}async function wi(e,t,n){if((await e.requestOptional(N.getRunContext,{executionId:t.executionId})).handled){await Ti(e,t.executionId,n);return}await e.request(E.bootstrapAuthorityState,{executionId:t.executionId,terminalAuthority:`authority`,definition:n})}async function Ti(e,t,n){return await Ei(e,t,n)!==void 0}async function Ei(e,t,n){let r=await e.request(N.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&&!Di(i,n))throw Error(`Authority bootstrap definition mismatch for '${t}'`);let a=i??n;return await e.request(N.setRunContext,{runContext:{...r.runContext,terminalAuthority:`authority`,definitionSnapshot:a},initialState:Ct(a)}),a}function Di(e,t){return i(JSON.parse(JSON.stringify(e)),JSON.parse(JSON.stringify(t)))}function Oi(e,t){return e.on(E.bootstrapAuthorityState,async n=>{let r=n.transport?.peer;if(!(n.origin.local||n.transport===void 0||r?.authenticated===!0&&r.id===n.payload.executionId&&(r.kind===`workflow-execution`||r.kind===`e2e`&&r.encrypted===!0)))throw Error(`authority state bootstrap is execution-bound`);let i=await Ei(e,n.payload.executionId,n.payload.definition);i!==void 0&&t?.(n.payload.executionId,i),n.setResult({persisted:i!==void 0})})}export{Be as $,Ee as A,M as B,Ot as C,tt as D,rt as E,Je as F,Pe as G,je as H,qe as I,Ue as J,Ne as K,Xe as L,ke as M,Ie as N,N as O,Fe as P,Ge as Q,Ye as R,P as S,dt as T,Re as U,Me as V,Le as W,Ve as X,He as Y,Ke as Z,Rt as _,U as a,At as b,kn as c,Cn as d,ze as et,bn as f,Bt as g,Kt as h,Si as i,E as it,Ae as j,De as k,on as l,Zt as m,Oi as n,Ce as nt,gr as o,an as p,We as q,Ci as r,ue as rt,In as s,wi as t,we as tt,yn as u,I as v,St as w,Nt as x,Pt as y,Oe as z};
|
package/dist/bus/index.d.mts
CHANGED
|
@@ -171,6 +171,17 @@ interface RequestContext<Payload, Response> extends BaseMessageContext {
|
|
|
171
171
|
payload: Payload;
|
|
172
172
|
/** AbortSignal supplied by the originating request, if any. */
|
|
173
173
|
signal?: AbortSignal;
|
|
174
|
+
/**
|
|
175
|
+
* Absolute Unix timestamp (ms) when this request expires.
|
|
176
|
+
*
|
|
177
|
+
* Computed once at the request entry point as `Date.now() + effectiveTimeout`
|
|
178
|
+
* and propagated unchanged through every local and remote handler in the
|
|
179
|
+
* dispatch chain. Handlers can compare `deadline` to `Date.now()` to determine
|
|
180
|
+
* their remaining time budget.
|
|
181
|
+
*
|
|
182
|
+
* Undefined when no deadline was set (timeout: 0).
|
|
183
|
+
*/
|
|
184
|
+
readonly deadline?: number;
|
|
174
185
|
/** Set the response value (ends the handler chain) */
|
|
175
186
|
setResult: (result: Response) => void;
|
|
176
187
|
/**
|
|
@@ -353,6 +364,20 @@ type ChannelSubjectSchema<T extends EventSchema | RequestSchema = EventSchema |
|
|
|
353
364
|
readonly __channel: true;
|
|
354
365
|
readonly schema: T;
|
|
355
366
|
};
|
|
367
|
+
/**
|
|
368
|
+
* Wrapper to mark a request subject as host-local.
|
|
369
|
+
*
|
|
370
|
+
* Host-local requests accept direct remote ingress (a transport may deliver
|
|
371
|
+
* the request to this host), but the receiving bus must never relay the
|
|
372
|
+
* request onward to other transports. Only request schemas are accepted;
|
|
373
|
+
* events are rejected at the type level.
|
|
374
|
+
*
|
|
375
|
+
* Use `hostLocalRequest()` from `@makaio/core` to create these.
|
|
376
|
+
*/
|
|
377
|
+
type HostLocalRequestSubjectSchema<T extends RequestSchema = RequestSchema> = {
|
|
378
|
+
readonly __hostLocalRequest: true;
|
|
379
|
+
readonly schema: T;
|
|
380
|
+
};
|
|
356
381
|
/**
|
|
357
382
|
* Wrapper to set a subject-level default transport routing policy.
|
|
358
383
|
*
|
|
@@ -370,7 +395,7 @@ type BaseSubjectSchema = EventSchema | RequestSchema;
|
|
|
370
395
|
/**
|
|
371
396
|
* Union of all subject schema types (including metadata wrappers).
|
|
372
397
|
*/
|
|
373
|
-
type SubjectSchema = BaseSubjectSchema | LocalSubjectSchema | CollectorOnlySubjectSchema | ChannelSubjectSchema | DefaultTransportsSubjectSchema;
|
|
398
|
+
type SubjectSchema = BaseSubjectSchema | LocalSubjectSchema | CollectorOnlySubjectSchema | ChannelSubjectSchema | HostLocalRequestSubjectSchema | DefaultTransportsSubjectSchema;
|
|
374
399
|
type SchemaRecord = Record<string, SubjectSchema>;
|
|
375
400
|
//#endregion
|
|
376
401
|
//#region core/makaio-core/src/types/type-helpers.d.ts
|
|
@@ -387,6 +412,9 @@ type UnwrapSchema<S> = S extends {
|
|
|
387
412
|
} ? Inner : S extends {
|
|
388
413
|
readonly __channel: true;
|
|
389
414
|
readonly schema: infer Inner;
|
|
415
|
+
} ? Inner : S extends {
|
|
416
|
+
readonly __hostLocalRequest: true;
|
|
417
|
+
readonly schema: infer Inner;
|
|
390
418
|
} ? Inner : S extends {
|
|
391
419
|
readonly __defaultTransports: TransportRoutingDefault;
|
|
392
420
|
readonly schema: infer Inner;
|
|
@@ -427,7 +455,14 @@ type InferSubjectMeta<S extends SubjectSchema, Ns extends string> = {
|
|
|
427
455
|
response: z.ZodType;
|
|
428
456
|
} ? true : false; /** True when the subject is wrapped with `localSubject()`. */
|
|
429
457
|
local: S extends LocalSubjectSchema ? true : false; /** True when the subject is wrapped with `channelSubject()`. */
|
|
430
|
-
channel: S extends ChannelSubjectSchema ? true : false;
|
|
458
|
+
channel: S extends ChannelSubjectSchema ? true : false;
|
|
459
|
+
/**
|
|
460
|
+
* True when the subject is wrapped with `hostLocalRequest()`.
|
|
461
|
+
*
|
|
462
|
+
* Host-local requests accept direct remote ingress but must never be
|
|
463
|
+
* relayed onward to other transports after ingress.
|
|
464
|
+
*/
|
|
465
|
+
hostLocalRequest: S extends HostLocalRequestSubjectSchema ? true : false; /** Inferred payload type (request/response pair or event payload). */
|
|
431
466
|
payload: InferSchemaPayload<S>; /** The namespace this subject belongs to. */
|
|
432
467
|
namespace: Ns;
|
|
433
468
|
} & (S extends DefaultTransportsSubjectSchema<EventSchema | RequestSchema, infer Default> ? {
|
|
@@ -462,6 +497,11 @@ type SubjectDefinitionMeta<Subject extends SubjectRecord = SubjectRecord<'defaul
|
|
|
462
497
|
* DirectChannel encrypted point-to-point transport.
|
|
463
498
|
*/
|
|
464
499
|
channel: boolean;
|
|
500
|
+
/**
|
|
501
|
+
* If true, this subject accepts direct remote ingress but must never be
|
|
502
|
+
* relayed onward to other transports after ingress.
|
|
503
|
+
*/
|
|
504
|
+
hostLocalRequest?: boolean;
|
|
465
505
|
/**
|
|
466
506
|
* Default transport routing for bus calls on this subject when the caller
|
|
467
507
|
* does not provide an explicit `transports` option.
|
|
@@ -752,6 +792,35 @@ declare function collectorOnlySubject<T extends EventSchema>(schema: T): Collect
|
|
|
752
792
|
*/
|
|
753
793
|
declare function channelSubject<T extends EventSchema | RequestSchema>(schema: T): ChannelSubjectSchema<T>;
|
|
754
794
|
//#endregion
|
|
795
|
+
//#region core/makaio-core/src/subject-helpers/host-local-request-schema.d.ts
|
|
796
|
+
/**
|
|
797
|
+
* Create a host-local request subject schema wrapper.
|
|
798
|
+
*
|
|
799
|
+
* Host-local requests accept direct remote ingress — a transport may deliver
|
|
800
|
+
* the request to this host — but the receiving bus must never relay the
|
|
801
|
+
* request onward to other transports after ingress. This is the correct
|
|
802
|
+
* wrapper for request subjects that should be answerable only by the
|
|
803
|
+
* receiving host, not forwarded across the bus topology.
|
|
804
|
+
*
|
|
805
|
+
* Only request schemas (with `request` and `response` fields) are accepted;
|
|
806
|
+
* plain event schemas are rejected at the type level.
|
|
807
|
+
* @param schema - The request schema to mark as host-local
|
|
808
|
+
* @returns A HostLocalRequestSubjectSchema wrapper
|
|
809
|
+
* @example
|
|
810
|
+
* ```typescript
|
|
811
|
+
* import { hostLocalRequest } from '@makaio/core';
|
|
812
|
+
*
|
|
813
|
+
* const AgentSchemas = {
|
|
814
|
+
* // Host-local request — answered locally, never relayed
|
|
815
|
+
* resolveCapability: hostLocalRequest({
|
|
816
|
+
* request: z.object({ capabilityId: z.string() }),
|
|
817
|
+
* response: z.object({ available: z.boolean() }),
|
|
818
|
+
* }),
|
|
819
|
+
* };
|
|
820
|
+
* ```
|
|
821
|
+
*/
|
|
822
|
+
declare function hostLocalRequest<T extends RequestSchema>(schema: T): HostLocalRequestSubjectSchema<T>;
|
|
823
|
+
//#endregion
|
|
755
824
|
//#region core/makaio-core/src/subject-helpers/default-transports-schema.d.ts
|
|
756
825
|
/**
|
|
757
826
|
* Create a subject schema wrapper with a subject-level default transport policy.
|
|
@@ -1274,6 +1343,8 @@ interface RegisteredSubjectSchema {
|
|
|
1274
1343
|
collectorOnly: boolean;
|
|
1275
1344
|
/** Whether the subject was registered through `channelSubject()`. */
|
|
1276
1345
|
channel: boolean;
|
|
1346
|
+
/** Whether the subject was registered through `hostLocalRequest()`. */
|
|
1347
|
+
hostLocalRequest: boolean;
|
|
1277
1348
|
}
|
|
1278
1349
|
/**
|
|
1279
1350
|
* Creates the namespace registry used by a bus context.
|
|
@@ -1351,6 +1422,16 @@ declare const createNamespaceRegistry: () => {
|
|
|
1351
1422
|
* @returns True if the subject was wrapped with `collectorOnlySubject()`
|
|
1352
1423
|
*/
|
|
1353
1424
|
isCollectorOnlySubject(subject: string): boolean;
|
|
1425
|
+
/**
|
|
1426
|
+
* Check if a subject was registered as a host-local request subject.
|
|
1427
|
+
*
|
|
1428
|
+
* Host-local request subjects accept direct remote ingress — a transport
|
|
1429
|
+
* may deliver the request to this host — but the receiving bus must never
|
|
1430
|
+
* relay the request onward to other transports after ingress.
|
|
1431
|
+
* @param subject - Full subject identifier (e.g., "agent.resolveCapability")
|
|
1432
|
+
* @returns True if the subject was wrapped with `hostLocalRequest()`
|
|
1433
|
+
*/
|
|
1434
|
+
isHostLocalRequestSubject(subject: string): boolean;
|
|
1354
1435
|
/**
|
|
1355
1436
|
* Get the default transport visibility for a subject.
|
|
1356
1437
|
*
|
|
@@ -1453,6 +1534,8 @@ declare const createTransportRegistry: (context: MakaioBusContext) => {
|
|
|
1453
1534
|
type TransportRegistry = ReturnType<typeof createTransportRegistry>;
|
|
1454
1535
|
//#endregion
|
|
1455
1536
|
//#region core/bus-core/src/types/transports.d.ts
|
|
1537
|
+
/** Controls whether a subscription may be advertised beyond its direct peer. */
|
|
1538
|
+
type SubscriptionDeliveryClass = 'relayable' | 'first-hop-only';
|
|
1456
1539
|
/**
|
|
1457
1540
|
* Subscribe message for client subscription management.
|
|
1458
1541
|
*
|
|
@@ -1487,6 +1570,13 @@ interface BusSubscribeMessage {
|
|
|
1487
1570
|
* An empty array indicates event-only handlers with no priority-based dispatch.
|
|
1488
1571
|
*/
|
|
1489
1572
|
subjects: Record<string, number[]>;
|
|
1573
|
+
/**
|
|
1574
|
+
* Owner-derived delivery semantics for every advertised subject.
|
|
1575
|
+
*
|
|
1576
|
+
* Receivers must treat missing or unknown values as `first-hop-only` so an
|
|
1577
|
+
* incomplete control message cannot weaken a no-relay boundary.
|
|
1578
|
+
*/
|
|
1579
|
+
deliveryClasses: Record<string, SubscriptionDeliveryClass>;
|
|
1490
1580
|
/**
|
|
1491
1581
|
* Optional payload filters per subject.
|
|
1492
1582
|
* Key is the subject pattern, value is the filter to apply.
|
|
@@ -1892,8 +1982,9 @@ interface BusTransport {
|
|
|
1892
1982
|
* @param filter - Optional payload filter for fine-grained routing
|
|
1893
1983
|
* @param priorities - Handler priorities registered for this subject; an empty
|
|
1894
1984
|
* array signals event-only handlers that do not participate in priority dispatch
|
|
1985
|
+
* @param deliveryClass - Whether the remote peer may advertise this subscription onward
|
|
1895
1986
|
*/
|
|
1896
|
-
subscribe(subject: string, filter?: PayloadFilter, priorities?: number[]): Promise<void>;
|
|
1987
|
+
subscribe(subject: string, filter?: PayloadFilter, priorities?: number[], deliveryClass?: SubscriptionDeliveryClass): Promise<void>;
|
|
1897
1988
|
/**
|
|
1898
1989
|
* Unsubscribe from a subject.
|
|
1899
1990
|
*
|
|
@@ -2129,6 +2220,8 @@ interface MakaioBusContext {
|
|
|
2129
2220
|
* `subscribe` (with an empty priority array) rather than an `unsubscribe`.
|
|
2130
2221
|
*/
|
|
2131
2222
|
remoteEventHandlers: Map<string, Set<string>>;
|
|
2223
|
+
/** Owner-derived delivery semantics keyed by subject pattern and source transport. */
|
|
2224
|
+
remoteSubscriptionDeliveryClasses: Map<string, Map<string, SubscriptionDeliveryClass>>;
|
|
2132
2225
|
}
|
|
2133
2226
|
/**
|
|
2134
2227
|
* Result of registering a transport on the bus.
|
|
@@ -3549,6 +3642,8 @@ interface SubscriptionEntry {
|
|
|
3549
3642
|
filter?: PayloadFilter;
|
|
3550
3643
|
/** Handler priorities registered for this subject. Empty array = event-only. */
|
|
3551
3644
|
priorities: number[];
|
|
3645
|
+
/** Whether the subscription may be advertised beyond its direct peer. */
|
|
3646
|
+
deliveryClass?: SubscriptionDeliveryClass;
|
|
3552
3647
|
}
|
|
3553
3648
|
/**
|
|
3554
3649
|
* Build a BusSubscribeMessage from local subscription state.
|
|
@@ -4030,4 +4125,4 @@ interface ProjectedTelemetryTransportOptions {
|
|
|
4030
4125
|
*/
|
|
4031
4126
|
declare function createProjectedTelemetryTransport(options: ProjectedTelemetryTransportOptions): BusTransport;
|
|
4032
4127
|
//#endregion
|
|
4033
|
-
export { type BroadcastContext, type BroadcastResult, type BusBroadcastMessage, type BusBroadcastResponseMessage, BusError, type BusEventMessage, type BusHeartbeatMessage, BusLifecycle, type BusMessage, type BusMessageObserver, type BusNamespace, type BusReceiveHandler, type BusRequestMessage, type BusResponseMessage, type BusSubscribeMessage, type BusSubscribeSyncCompleteMessage, type BusSubscriptionAckMessage, type BusTransport, type BusTransportError, type BusTransportKeys, type BusTransportRegistry, type BusUnsubscribeMessage, type BusUrlConfig, type BusValidationMode, CONNECTION_LOST_ERROR_CODE, ChannelAuthError, ChannelClosedError, type ChannelEndpoint, type ChannelEndpointOptions, ChannelOnlyError, type ConnectOptions, type ConnectedPayload, ConnectionLostError, CorrelationTracker, DEFAULT_REQUEST_TIMEOUT_MS, type DefinedSubjectExtension, type DisconnectedPayload, type EventSubjectExtension, type ExtendedSubjectDefinition, type ExtensionNamespace, type ExtensionNamespaceConfig, type ExtensionNamespaceExtensions, type ExtensionNamespaceFromConfig, type IDirectChannel, type IFilteredBus, type IMakaioBus, type InterceptorContext, LOCAL_ORIGIN, LocalSubjectError, MakaioBus, type MakaioBusContext, NO_HANDLER_ERROR_CODE, type NamespaceRegistrationOptions, NoHandlerError, type ObservedBusMessage, type OnOptions, OnceAbortError, type OptionalResult, type ProjectableBusMessage, type ProjectedTelemetryTransportOptions, REMOTE_ORIGIN, RequestError, type RequestSubjectExtension, type SchemaViolationCallback, type SchemaViolationReport, type ScopedBus, type ScopedBusFor, type SubjectExtension, type SubjectTelemetryAttributes, type SubjectTelemetryProjectionInput, type SubjectTelemetryProjector, type SubjectTelemetryProjectorInput, type SubjectTelemetryProjectorRegistry, type SubscriptionEntry, SystemChannelSchemas, TimeoutError, type TransportRegistration, ValidationError, __resetWarnedSubjects, buildSubscribeMessage, buildUnsubscribeMessage, channelSubject, collectorOnlySubject, createBusContext, createBusInstance, createChannelEndpoint, createExtensionNamespace, createFilteredBus, createProjectedTelemetryTransport, createSubjectTelemetryProjectorRegistry, defaultTransports, defineSubjectExtension, deserializeTransportError, extendSubjectImpl as extendSubject, getFullSubjectForSubjectDefinition, getPath, getSubjectFromBusMessage, handleCorrelationResponse, isNoHandlerErrorForSubject, isRequestSchema, localSubject, matchesAnySubscription, matchesFilter, matchesSubscription, mergeFilters, openChannel, parseBusUrl, projectSubjectTelemetryFacts, serializeTransportError, shouldReceiveMessage, trackMessageCorrelation, waitForSubscriptionPropagation };
|
|
4128
|
+
export { type BroadcastContext, type BroadcastResult, type BusBroadcastMessage, type BusBroadcastResponseMessage, BusError, type BusEventMessage, type BusHeartbeatMessage, BusLifecycle, type BusMessage, type BusMessageObserver, type BusNamespace, type BusReceiveHandler, type BusRequestMessage, type BusResponseMessage, type BusSubscribeMessage, type BusSubscribeSyncCompleteMessage, type BusSubscriptionAckMessage, type BusTransport, type BusTransportError, type BusTransportKeys, type BusTransportRegistry, type BusUnsubscribeMessage, type BusUrlConfig, type BusValidationMode, CONNECTION_LOST_ERROR_CODE, ChannelAuthError, ChannelClosedError, type ChannelEndpoint, type ChannelEndpointOptions, ChannelOnlyError, type ConnectOptions, type ConnectedPayload, ConnectionLostError, CorrelationTracker, DEFAULT_REQUEST_TIMEOUT_MS, type DefinedSubjectExtension, type DisconnectedPayload, type EventSubjectExtension, type ExtendedSubjectDefinition, type ExtensionNamespace, type ExtensionNamespaceConfig, type ExtensionNamespaceExtensions, type ExtensionNamespaceFromConfig, type IDirectChannel, type IFilteredBus, type IMakaioBus, type InterceptorContext, LOCAL_ORIGIN, LocalSubjectError, MakaioBus, type MakaioBusContext, NO_HANDLER_ERROR_CODE, type NamespaceRegistrationOptions, NoHandlerError, type ObservedBusMessage, type OnOptions, OnceAbortError, type OptionalResult, type ProjectableBusMessage, type ProjectedTelemetryTransportOptions, REMOTE_ORIGIN, RequestError, type RequestSubjectExtension, type SchemaViolationCallback, type SchemaViolationReport, type ScopedBus, type ScopedBusFor, type SubjectExtension, type SubjectTelemetryAttributes, type SubjectTelemetryProjectionInput, type SubjectTelemetryProjector, type SubjectTelemetryProjectorInput, type SubjectTelemetryProjectorRegistry, type SubscriptionDeliveryClass, type SubscriptionEntry, SystemChannelSchemas, TimeoutError, type TransportRegistration, ValidationError, __resetWarnedSubjects, buildSubscribeMessage, buildUnsubscribeMessage, channelSubject, collectorOnlySubject, createBusContext, createBusInstance, createChannelEndpoint, createExtensionNamespace, createFilteredBus, createProjectedTelemetryTransport, createSubjectTelemetryProjectorRegistry, defaultTransports, defineSubjectExtension, deserializeTransportError, extendSubjectImpl as extendSubject, getFullSubjectForSubjectDefinition, getPath, getSubjectFromBusMessage, handleCorrelationResponse, hostLocalRequest, isNoHandlerErrorForSubject, isRequestSchema, localSubject, matchesAnySubscription, matchesFilter, matchesSubscription, mergeFilters, openChannel, parseBusUrl, projectSubjectTelemetryFacts, serializeTransportError, shouldReceiveMessage, trackMessageCorrelation, waitForSubscriptionPropagation };
|