@skaile/workspaces 6.6.0 → 6.7.0
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/CHANGELOG.md +28 -0
- package/dist/ai-sdk.js +10 -17
- package/dist/ai-sdk.js.map +1 -1
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-WQ6YQPHV.js → asset-feeds-4A7PJ4OB.js} +18 -18
- package/dist/{asset-feeds-WQ6YQPHV.js.map → asset-feeds-4A7PJ4OB.js.map} +1 -1
- package/dist/asset-manager/catalog-deployer.js +4 -4
- package/dist/asset-manager/index.js +10 -10
- package/dist/asset-manager/installer.js +6 -6
- package/dist/asset-manager/renderers.js +5 -5
- package/dist/asset-manager/src/index.d.ts +89 -15
- package/dist/asset-manager/src/index.d.ts.map +1 -1
- package/dist/asset-manager/src/install-agent.d.ts +22 -1
- package/dist/asset-manager/src/install-agent.d.ts.map +1 -1
- package/dist/asset-manager/src/install-instances.d.ts +30 -1
- package/dist/asset-manager/src/install-instances.d.ts.map +1 -1
- package/dist/asset-manager/src/installer.d.ts +12 -0
- package/dist/asset-manager/src/installer.d.ts.map +1 -1
- package/dist/asset-manager/src/renderers.d.ts.map +1 -1
- package/dist/bridge/harnesses/claude-sdk.js +21 -15
- package/dist/bridge/harnesses/claude-sdk.js.map +1 -1
- package/dist/bridge/harnesses/codex.js +9 -8
- package/dist/bridge/harnesses/codex.js.map +1 -1
- package/dist/bridge/harnesses/continue.js +11 -9
- package/dist/bridge/harnesses/continue.js.map +1 -1
- package/dist/bridge/harnesses/echo.js +5 -4
- package/dist/bridge/harnesses/echo.js.map +1 -1
- package/dist/bridge/harnesses/gemini.js +8 -6
- package/dist/bridge/harnesses/goose.js +11 -9
- package/dist/bridge/harnesses/goose.js.map +1 -1
- package/dist/bridge/harnesses/omp.js +9 -7
- package/dist/bridge/harnesses/omp.js.map +1 -1
- package/dist/bridge/harnesses/opencode.js +11 -9
- package/dist/bridge/harnesses/opencode.js.map +1 -1
- package/dist/bridge/harnesses/qwen.js +9 -7
- package/dist/bridge/harnesses/qwen.js.map +1 -1
- package/dist/bridge/index.js +17 -15
- package/dist/bridge/src/ai-sdk.d.ts.map +1 -1
- package/dist/bridge/src/claude-sdk-surface.d.ts +2 -1
- package/dist/bridge/src/claude-sdk-surface.d.ts.map +1 -1
- package/dist/bridge/src/harness-binaries.d.ts +21 -0
- package/dist/bridge/src/harness-binaries.d.ts.map +1 -0
- package/dist/bridge/src/harness-model-check.d.ts +22 -6
- package/dist/bridge/src/harness-model-check.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/continue.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/gemini.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/goose.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/omp-models-yml.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/omp.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/opencode.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/qwen.d.ts.map +1 -1
- package/dist/bridge/src/index.d.ts +2 -1
- package/dist/bridge/src/index.d.ts.map +1 -1
- package/dist/{chunk-LBJ4M5J2.js → chunk-237BMOZW.js} +4 -4
- package/dist/{chunk-LBJ4M5J2.js.map → chunk-237BMOZW.js.map} +1 -1
- package/dist/{chunk-2TLPC6TQ.js → chunk-37AYPPOO.js} +41 -19
- package/dist/chunk-37AYPPOO.js.map +1 -0
- package/dist/{chunk-GTGWRKMJ.js → chunk-37X4A6VZ.js} +6 -6
- package/dist/{chunk-GTGWRKMJ.js.map → chunk-37X4A6VZ.js.map} +1 -1
- package/dist/{chunk-MXI3XWV6.js → chunk-3HSLJAMJ.js} +4 -4
- package/dist/{chunk-MXI3XWV6.js.map → chunk-3HSLJAMJ.js.map} +1 -1
- package/dist/{chunk-RHCEX2EV.js → chunk-3W6XZQ2Y.js} +3 -3
- package/dist/{chunk-RHCEX2EV.js.map → chunk-3W6XZQ2Y.js.map} +1 -1
- package/dist/{chunk-F4CZQD3T.js → chunk-4C2E5QUP.js} +4 -3
- package/dist/chunk-4C2E5QUP.js.map +1 -0
- package/dist/{chunk-DS6UUCFG.js → chunk-4CD2R4MJ.js} +5 -4
- package/dist/chunk-4CD2R4MJ.js.map +1 -0
- package/dist/{chunk-AQNW2FET.js → chunk-6RPS7JEH.js} +92 -39
- package/dist/chunk-6RPS7JEH.js.map +1 -0
- package/dist/{chunk-BSMW3PX2.js → chunk-6UP2EDFN.js} +4 -313
- package/dist/chunk-6UP2EDFN.js.map +1 -0
- package/dist/{chunk-4J7JQX4G.js → chunk-72TLO2AG.js} +4 -4
- package/dist/{chunk-4J7JQX4G.js.map → chunk-72TLO2AG.js.map} +1 -1
- package/dist/{chunk-I5IF3JCG.js → chunk-AO57IFME.js} +3 -3
- package/dist/{chunk-I5IF3JCG.js.map → chunk-AO57IFME.js.map} +1 -1
- package/dist/{chunk-G5SYFFMD.js → chunk-ASBZOTEO.js} +2 -2
- package/dist/{chunk-G5SYFFMD.js.map → chunk-ASBZOTEO.js.map} +1 -1
- package/dist/{chunk-O7QZI6MQ.js → chunk-BB5EJLKZ.js} +2 -2
- package/dist/{chunk-O7QZI6MQ.js.map → chunk-BB5EJLKZ.js.map} +1 -1
- package/dist/{chunk-N2PBAXAA.js → chunk-BKLDBUQA.js} +3 -3
- package/dist/{chunk-N2PBAXAA.js.map → chunk-BKLDBUQA.js.map} +1 -1
- package/dist/{chunk-XD3RYAMR.js → chunk-CTRTFMCX.js} +6 -6
- package/dist/{chunk-XD3RYAMR.js.map → chunk-CTRTFMCX.js.map} +1 -1
- package/dist/{chunk-EPXZQIC6.js → chunk-DFP476EU.js} +8 -4
- package/dist/chunk-DFP476EU.js.map +1 -0
- package/dist/{chunk-MMOWIRHP.js → chunk-G44FFUMA.js} +12 -10
- package/dist/chunk-G44FFUMA.js.map +1 -0
- package/dist/{chunk-JIQUF3X2.js → chunk-G7NMF5WQ.js} +3 -3
- package/dist/{chunk-JIQUF3X2.js.map → chunk-G7NMF5WQ.js.map} +1 -1
- package/dist/{chunk-SHTXMERQ.js → chunk-GAIMSCZ7.js} +10 -8
- package/dist/chunk-GAIMSCZ7.js.map +1 -0
- package/dist/{chunk-6A6HE5LW.js → chunk-HLAEYFUN.js} +3 -3
- package/dist/{chunk-6A6HE5LW.js.map → chunk-HLAEYFUN.js.map} +1 -1
- package/dist/{chunk-YN6N3RBM.js → chunk-HMVAGPYR.js} +47 -11
- package/dist/chunk-HMVAGPYR.js.map +1 -0
- package/dist/{chunk-U3UDOX6I.js → chunk-HPXONAI2.js} +6 -4
- package/dist/chunk-HPXONAI2.js.map +1 -0
- package/dist/{chunk-5ETYBC2X.js → chunk-IRK3LNG3.js} +6 -6
- package/dist/{chunk-5ETYBC2X.js.map → chunk-IRK3LNG3.js.map} +1 -1
- package/dist/{chunk-J262X4JU.js → chunk-J7VEQORJ.js} +69 -16
- package/dist/chunk-J7VEQORJ.js.map +1 -0
- package/dist/{chunk-DI6J2PJB.js → chunk-KO3VSZQP.js} +47 -18
- package/dist/chunk-KO3VSZQP.js.map +1 -0
- package/dist/{chunk-KSH5CFQS.js → chunk-KORDNXKA.js} +3 -3
- package/dist/{chunk-KSH5CFQS.js.map → chunk-KORDNXKA.js.map} +1 -1
- package/dist/{chunk-SCRYXAHH.js → chunk-L3JQJ6D5.js} +6 -6
- package/dist/{chunk-SCRYXAHH.js.map → chunk-L3JQJ6D5.js.map} +1 -1
- package/dist/{chunk-7I5PNB2G.js → chunk-L7QOZG5V.js} +3 -3
- package/dist/{chunk-7I5PNB2G.js.map → chunk-L7QOZG5V.js.map} +1 -1
- package/dist/{chunk-VXYZ5M7Z.js → chunk-LX4TTTRR.js} +64 -27
- package/dist/chunk-LX4TTTRR.js.map +1 -0
- package/dist/{chunk-KSUT5KAE.js → chunk-LZPJOF7Y.js} +3 -3
- package/dist/{chunk-KSUT5KAE.js.map → chunk-LZPJOF7Y.js.map} +1 -1
- package/dist/{chunk-65UAC3ZR.js → chunk-N6ZGB5ES.js} +4 -3
- package/dist/chunk-N6ZGB5ES.js.map +1 -0
- package/dist/{chunk-2M3VLKT2.js → chunk-NURTGAWM.js} +3 -3
- package/dist/{chunk-2M3VLKT2.js.map → chunk-NURTGAWM.js.map} +1 -1
- package/dist/{chunk-J4WKNJHO.js → chunk-O5Y7VMVQ.js} +15 -14
- package/dist/chunk-O5Y7VMVQ.js.map +1 -0
- package/dist/{chunk-6SXSVKQY.js → chunk-O7ADRMCR.js} +63 -14
- package/dist/chunk-O7ADRMCR.js.map +1 -0
- package/dist/{chunk-7PVGND4J.js → chunk-OGTQUEAO.js} +21 -14
- package/dist/chunk-OGTQUEAO.js.map +1 -0
- package/dist/{chunk-VJRL6ZK6.js → chunk-OSABUEWA.js} +3 -3
- package/dist/{chunk-VJRL6ZK6.js.map → chunk-OSABUEWA.js.map} +1 -1
- package/dist/{chunk-WW5NAU6N.js → chunk-PLLZSKOO.js} +3 -3
- package/dist/{chunk-WW5NAU6N.js.map → chunk-PLLZSKOO.js.map} +1 -1
- package/dist/{chunk-7SJHSGUV.js → chunk-Q2NYTMT6.js} +16 -15
- package/dist/chunk-Q2NYTMT6.js.map +1 -0
- package/dist/{chunk-E2EC6SAX.js → chunk-QC5BYUED.js} +51 -15
- package/dist/chunk-QC5BYUED.js.map +1 -0
- package/dist/{chunk-RAU5QPI6.js → chunk-QCR5AE5E.js} +5 -5
- package/dist/{chunk-RAU5QPI6.js.map → chunk-QCR5AE5E.js.map} +1 -1
- package/dist/{chunk-TUFNY6OD.js → chunk-QW5B3TEO.js} +10 -4
- package/dist/chunk-QW5B3TEO.js.map +1 -0
- package/dist/{chunk-Z4FERR4U.js → chunk-RAHAZ7LP.js} +2 -2
- package/dist/{chunk-Z4FERR4U.js.map → chunk-RAHAZ7LP.js.map} +1 -1
- package/dist/{chunk-OY22B7E2.js → chunk-SBNUXJ6E.js} +3 -3
- package/dist/{chunk-OY22B7E2.js.map → chunk-SBNUXJ6E.js.map} +1 -1
- package/dist/{chunk-6ARPZHOV.js → chunk-TMJBEGS4.js} +35 -6
- package/dist/chunk-TMJBEGS4.js.map +1 -0
- package/dist/{chunk-6RHWTZPT.js → chunk-TXX3OUYI.js} +3 -3
- package/dist/{chunk-6RHWTZPT.js.map → chunk-TXX3OUYI.js.map} +1 -1
- package/dist/{chunk-SZKCE7EC.js → chunk-U52FYGK5.js} +5 -5
- package/dist/{chunk-SZKCE7EC.js.map → chunk-U52FYGK5.js.map} +1 -1
- package/dist/{chunk-TCH5UDKT.js → chunk-UCB7FK25.js} +10 -8
- package/dist/chunk-UCB7FK25.js.map +1 -0
- package/dist/{chunk-5XHQBCB5.js → chunk-WFK4MUBL.js} +21 -7
- package/dist/chunk-WFK4MUBL.js.map +1 -0
- package/dist/{chunk-HGZN6JLP.js → chunk-WIYVR24B.js} +4 -4
- package/dist/{chunk-HGZN6JLP.js.map → chunk-WIYVR24B.js.map} +1 -1
- package/dist/{chunk-B6N653ZG.js → chunk-WKENHNDM.js} +6 -6
- package/dist/{chunk-B6N653ZG.js.map → chunk-WKENHNDM.js.map} +1 -1
- package/dist/chunk-WWSRIT3J.js +59 -0
- package/dist/chunk-WWSRIT3J.js.map +1 -0
- package/dist/chunk-XON6ODIC.js +315 -0
- package/dist/chunk-XON6ODIC.js.map +1 -0
- package/dist/{chunk-4BFEPZ6J.js → chunk-ZBA4P5TD.js} +3 -3
- package/dist/{chunk-4BFEPZ6J.js.map → chunk-ZBA4P5TD.js.map} +1 -1
- package/dist/{chunk-JRVQV7WC.js → chunk-ZDTDS62B.js} +595 -126
- package/dist/chunk-ZDTDS62B.js.map +1 -0
- package/dist/{chunk-XYCYGN3Q.js → chunk-ZM4SDVUV.js} +79 -20
- package/dist/chunk-ZM4SDVUV.js.map +1 -0
- package/dist/{claude-code-LZH7Y4Y5.js → claude-code-BLFRZU2X.js} +4 -4
- package/dist/{claude-code-LZH7Y4Y5.js.map → claude-code-BLFRZU2X.js.map} +1 -1
- package/dist/cli/index.js +474 -198
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/agent-pins.d.ts +9 -3
- package/dist/cli/src/agent-pins.d.ts.map +1 -1
- package/dist/cli/src/commands/asset-cmd.d.ts +1 -1
- package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/cache.d.ts.map +1 -1
- package/dist/cli/src/commands/catalog.d.ts +2 -0
- package/dist/cli/src/commands/catalog.d.ts.map +1 -1
- package/dist/cli/src/commands/config.d.ts.map +1 -1
- package/dist/cli/src/commands/harness-preflight.d.ts +38 -0
- package/dist/cli/src/commands/harness-preflight.d.ts.map +1 -0
- package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/library-index.d.ts +16 -0
- package/dist/cli/src/commands/library-index.d.ts.map +1 -1
- package/dist/cli/src/commands/migrate-assets.d.ts +5 -0
- package/dist/cli/src/commands/migrate-assets.d.ts.map +1 -1
- package/dist/cli/src/commands/migrate-harness.d.ts +15 -7
- package/dist/cli/src/commands/migrate-harness.d.ts.map +1 -1
- package/dist/cli/src/commands/migrate.d.ts.map +1 -1
- package/dist/cli/src/commands/outdated.d.ts.map +1 -1
- package/dist/cli/src/commands/plugin-registry-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/project.d.ts +14 -0
- package/dist/cli/src/commands/project.d.ts.map +1 -1
- package/dist/cli/src/commands/run.d.ts.map +1 -1
- package/dist/cli/src/commands/serve-preflight.d.ts +6 -5
- package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
- package/dist/cli/src/commands/serve.d.ts.map +1 -1
- package/dist/cli/src/commands/session.d.ts.map +1 -1
- package/dist/cli/src/commands/source.d.ts +11 -0
- package/dist/cli/src/commands/source.d.ts.map +1 -1
- package/dist/cli/src/commands/update.d.ts.map +1 -1
- package/dist/cli/src/commands/validate-instances.d.ts +6 -0
- package/dist/cli/src/commands/validate-instances.d.ts.map +1 -1
- package/dist/cli/src/commands/validate.d.ts.map +1 -1
- package/dist/cli/src/commands/why.d.ts.map +1 -1
- package/dist/cli/src/plugin-store/reconcile.d.ts.map +1 -1
- package/dist/cli/src/session-hint.d.ts +7 -0
- package/dist/cli/src/session-hint.d.ts.map +1 -0
- package/dist/connectors/config.js +3 -3
- package/dist/connectors/index.js +21 -19
- package/dist/connectors/src/managed-gitconfig.d.ts +6 -4
- package/dist/connectors/src/managed-gitconfig.d.ts.map +1 -1
- package/dist/{connectors-HU5MHSUJ.js → connectors-OJJU4LSN.js} +24 -22
- package/dist/{connectors-HU5MHSUJ.js.map → connectors-OJJU4LSN.js.map} +1 -1
- package/dist/connectors-shared/index.js +2 -2
- package/dist/core/index.js +4 -4
- package/dist/core/publish-manifest.js +1 -1
- package/dist/core/runtime-assets.js +3 -3
- package/dist/core/src/agent-instances.d.ts +11 -0
- package/dist/core/src/agent-instances.d.ts.map +1 -1
- package/dist/core/src/index.d.ts +3 -2
- package/dist/core/src/index.d.ts.map +1 -1
- package/dist/core/src/publish-manifest.d.ts +20 -6
- package/dist/core/src/publish-manifest.d.ts.map +1 -1
- package/dist/core/src/repo-manager.d.ts +9 -0
- package/dist/core/src/repo-manager.d.ts.map +1 -1
- package/dist/core/src/run-state-ignore.d.ts +17 -0
- package/dist/core/src/run-state-ignore.d.ts.map +1 -0
- package/dist/core/src/workspace-config.d.ts.map +1 -1
- package/dist/core/workspace-config.js +2 -2
- package/dist/deploy/index.js +4 -4
- package/dist/discovery/index.js +2 -2
- package/dist/discovery/src/builtin-providers.d.ts.map +1 -1
- package/dist/discovery/src/discover-manifest.d.ts.map +1 -1
- package/dist/discovery/src/tree-entries.d.ts.map +1 -1
- package/dist/{ensure-sources-CAMWJTMR.js → ensure-sources-F6VQDCWY.js} +26 -24
- package/dist/ensure-sources-F6VQDCWY.js.map +1 -0
- package/dist/factory-assets/connectors/box.js +21 -19
- package/dist/factory-assets/connectors/deploy.js +21 -19
- package/dist/factory-assets/connectors/devserver.js +21 -19
- package/dist/factory-assets/connectors/flow/adapter.js +21 -19
- package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts +2 -0
- package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine.js +5 -5
- package/dist/factory-assets/connectors/flow/run-flow.js +22 -20
- package/dist/factory-assets/connectors/flow.js +21 -19
- package/dist/factory-assets/connectors/git/CONNECTOR.md +4 -1
- package/dist/factory-assets/connectors/git/exec.d.ts.map +1 -1
- package/dist/factory-assets/connectors/git.js +21 -19
- package/dist/factory-assets/connectors/gmail.js +21 -19
- package/dist/factory-assets/connectors/googledrive.js +21 -19
- package/dist/factory-assets/connectors/local.js +21 -19
- package/dist/factory-assets/connectors/mattermost.js +21 -19
- package/dist/factory-assets/connectors/memory.js +21 -19
- package/dist/factory-assets/connectors/minio.js +21 -19
- package/dist/factory-assets/connectors/postgres.js +21 -19
- package/dist/factory-assets/connectors/s3.js +21 -19
- package/dist/factory-assets/connectors/sharepoint.js +21 -19
- package/dist/factory-assets/connectors/sqlite.js +21 -19
- package/dist/factory-assets/connectors/static-server.js +21 -19
- package/dist/factory-assets/connectors/tunnel.js +21 -19
- package/dist/factory-assets/connectors/webdav.js +21 -19
- package/dist/factory-assets/connectors/xstate-store.js +21 -19
- package/dist/factory-assets/connectors/xstate.js +21 -19
- package/dist/factory-assets/skills/authoring-skaile-assets/SKILL.md +14 -1
- package/dist/{flows-GVOVQGQW.js → flows-I6ODIPZZ.js} +7 -7
- package/dist/{flows-GVOVQGQW.js.map → flows-I6ODIPZZ.js.map} +1 -1
- package/dist/{helpers-WMCCODAV.js → helpers-PJNUTZXZ.js} +26 -24
- package/dist/{helpers-WMCCODAV.js.map → helpers-PJNUTZXZ.js.map} +1 -1
- package/dist/library/index.js +7 -7
- package/dist/library/install.js +2 -2
- package/dist/library/src/manifest-writer.d.ts +5 -0
- package/dist/library/src/manifest-writer.d.ts.map +1 -1
- package/dist/{library-publish-UQQMHTND.js → library-publish-FNNDWVBO.js} +47 -45
- package/dist/library-publish-FNNDWVBO.js.map +1 -0
- package/dist/model-endpoint/index.js +8 -7
- package/dist/{open-library-OJ4HT2X4.js → open-library-R5EZROFN.js} +29 -27
- package/dist/{open-library-OJ4HT2X4.js.map → open-library-R5EZROFN.js.map} +1 -1
- package/dist/{open-registry-LWGIOJDK.js → open-registry-RZW2AFD6.js} +11 -11
- package/dist/{open-registry-LWGIOJDK.js.map → open-registry-RZW2AFD6.js.map} +1 -1
- package/dist/{paths-FR2752HV.js → paths-RPK5PNZQ.js} +7 -7
- package/dist/{paths-FR2752HV.js.map → paths-RPK5PNZQ.js.map} +1 -1
- package/dist/{plugin-store-IALJUBN2.js → plugin-store-OJTERUEZ.js} +7 -7
- package/dist/{plugin-store-IALJUBN2.js.map → plugin-store-OJTERUEZ.js.map} +1 -1
- package/dist/{project-UQFCYHYS.js → project-S2FT3LLR.js} +43 -41
- package/dist/{project-UQFCYHYS.js.map → project-S2FT3LLR.js.map} +1 -1
- package/dist/resolver/index.js +4 -4
- package/dist/runner/index.js +32 -30
- package/dist/runner/src/capability-roundtrip.d.ts +6 -6
- package/dist/runner/src/capability-roundtrip.d.ts.map +1 -1
- package/dist/runner/src/composition/run-snapshot.d.ts +7 -1
- package/dist/runner/src/composition/run-snapshot.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +10 -10
- package/dist/sdk/bridge.js +17 -15
- package/dist/sdk/core.js +4 -4
- package/dist/sdk/flow.js +5 -5
- package/dist/sdk/index.js +32 -30
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/resolver.js +4 -4
- package/dist/sdk/runner.js +32 -30
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/transport/ws/server.js +5 -5
- package/dist/sdk/transport/ws.js +5 -5
- package/dist/sdk/transport.js +5 -5
- package/dist/sdk/types.js +1 -1
- package/dist/serve-preflight-AADSOUO2.js +58 -0
- package/dist/{serve-preflight-TYEKHC32.js.map → serve-preflight-AADSOUO2.js.map} +1 -1
- package/dist/session/index.js +2 -2
- package/dist/{setup-4JV2IMCB.js → setup-HOAJHUFQ.js} +27 -25
- package/dist/setup-HOAJHUFQ.js.map +1 -0
- package/dist/{skills-6QTKFMLW.js → skills-KHHW3RZ3.js} +6 -6
- package/dist/{skills-6QTKFMLW.js.map → skills-KHHW3RZ3.js.map} +1 -1
- package/dist/source-FOELFCY6.js +88 -0
- package/dist/{source-XYMMJVKR.js.map → source-FOELFCY6.js.map} +1 -1
- package/dist/{source-manifest-publish-SZFGGKB4.js → source-manifest-publish-Q7P5AEVU.js} +44 -42
- package/dist/source-manifest-publish-Q7P5AEVU.js.map +1 -0
- package/dist/transport/index.js +5 -5
- package/dist/transport/ws/server.js +5 -5
- package/dist/transport/ws.js +5 -5
- package/dist/tui/index.js +56 -37
- package/dist/tui/index.js.map +1 -1
- package/dist/tui/src/repl.d.ts +10 -0
- package/dist/tui/src/repl.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/src/version.d.ts +4 -4
- package/dist/workspace-plugin/adapters/mcp.js +24 -22
- package/dist/workspace-plugin/adapters/omp.js +14 -14
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2TLPC6TQ.js.map +0 -1
- package/dist/chunk-5XHQBCB5.js.map +0 -1
- package/dist/chunk-65UAC3ZR.js.map +0 -1
- package/dist/chunk-6ARPZHOV.js.map +0 -1
- package/dist/chunk-6SXSVKQY.js.map +0 -1
- package/dist/chunk-7PVGND4J.js.map +0 -1
- package/dist/chunk-7SJHSGUV.js.map +0 -1
- package/dist/chunk-AQNW2FET.js.map +0 -1
- package/dist/chunk-BSMW3PX2.js.map +0 -1
- package/dist/chunk-DI6J2PJB.js.map +0 -1
- package/dist/chunk-DS6UUCFG.js.map +0 -1
- package/dist/chunk-E2EC6SAX.js.map +0 -1
- package/dist/chunk-EPXZQIC6.js.map +0 -1
- package/dist/chunk-F4CZQD3T.js.map +0 -1
- package/dist/chunk-J262X4JU.js.map +0 -1
- package/dist/chunk-J4WKNJHO.js.map +0 -1
- package/dist/chunk-JRVQV7WC.js.map +0 -1
- package/dist/chunk-MMOWIRHP.js.map +0 -1
- package/dist/chunk-SHTXMERQ.js.map +0 -1
- package/dist/chunk-TCH5UDKT.js.map +0 -1
- package/dist/chunk-TUFNY6OD.js.map +0 -1
- package/dist/chunk-U3UDOX6I.js.map +0 -1
- package/dist/chunk-VXYZ5M7Z.js.map +0 -1
- package/dist/chunk-XYCYGN3Q.js.map +0 -1
- package/dist/chunk-YN6N3RBM.js.map +0 -1
- package/dist/ensure-sources-CAMWJTMR.js.map +0 -1
- package/dist/library-publish-UQQMHTND.js.map +0 -1
- package/dist/serve-preflight-TYEKHC32.js +0 -56
- package/dist/setup-4JV2IMCB.js.map +0 -1
- package/dist/source-XYMMJVKR.js +0 -86
- package/dist/source-manifest-publish-SZFGGKB4.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { entrySurface } from './chunk-
|
|
2
|
-
import { unresolvedProviderCredentials, entryCredentialValue, providerCredentialEnvName } from './chunk-
|
|
1
|
+
import { entrySurface } from './chunk-4C2E5QUP.js';
|
|
2
|
+
import { unresolvedProviderCredentials, entryCredentialValue, providerCredentialEnvName } from './chunk-XON6ODIC.js';
|
|
3
3
|
import { AI_PROVIDER_SURFACES, registryEntries, isEntryEnabled, parseModelRef, normalizeEntryBaseUrl, resolveEntryBaseUrl } from './chunk-RXGPFAMN.js';
|
|
4
4
|
import { createHash } from 'crypto';
|
|
5
5
|
import fs from 'fs/promises';
|
|
@@ -148,11 +148,13 @@ function renderModelRoles(registry, roles, modelRef, warnings) {
|
|
|
148
148
|
);
|
|
149
149
|
continue;
|
|
150
150
|
}
|
|
151
|
-
out[role] = `${ref.providerId}/${ref.providerModelId}`;
|
|
151
|
+
out[role] = ref.fallback ? trimmed : `${ref.providerId}/${ref.providerModelId}`;
|
|
152
152
|
}
|
|
153
153
|
if (out.default === void 0 && modelRef) {
|
|
154
154
|
const ref = parseModelRef(modelRef, registry, roles);
|
|
155
|
-
if (ref?.providerModelId
|
|
155
|
+
if (ref?.providerModelId && !ref.fallback) {
|
|
156
|
+
out.default = `${ref.providerId}/${ref.providerModelId}`;
|
|
157
|
+
}
|
|
156
158
|
}
|
|
157
159
|
return out;
|
|
158
160
|
}
|
|
@@ -435,7 +437,7 @@ async function materializeOmpProviders(config) {
|
|
|
435
437
|
...config.modelRef ? { modelRef: config.modelRef } : {}
|
|
436
438
|
}).providerIds;
|
|
437
439
|
if (usable.length === 0) return void 0;
|
|
438
|
-
if (selected && !usable.includes(selected.providerId)) return void 0;
|
|
440
|
+
if (selected && !selected.fallback && !usable.includes(selected.providerId)) return void 0;
|
|
439
441
|
const plan = await planOmpAgentDir({
|
|
440
442
|
cwd: config.cwd,
|
|
441
443
|
...config.sessionId ? { sessionId: config.sessionId } : {},
|
|
@@ -464,7 +466,7 @@ async function materializeOmpProviders(config) {
|
|
|
464
466
|
return {
|
|
465
467
|
...rendered,
|
|
466
468
|
ephemeral: plan.ephemeral,
|
|
467
|
-
...selected?.providerModelId ? { modelArg: `${selected.providerId}/${selected.providerModelId}` } : {}
|
|
469
|
+
...selected?.providerModelId && !selected.fallback ? { modelArg: `${selected.providerId}/${selected.providerModelId}` } : {}
|
|
468
470
|
};
|
|
469
471
|
}
|
|
470
472
|
async function materializeOmpIdentityDir(config) {
|
|
@@ -501,5 +503,5 @@ async function materializeOmpIdentityDir(config) {
|
|
|
501
503
|
}
|
|
502
504
|
|
|
503
505
|
export { isCredentialOmissionWarning, materializeOmpIdentityDir, materializeOmpProviders, ompRegistryModelRefusal, registryModelEntries };
|
|
504
|
-
//# sourceMappingURL=chunk-
|
|
505
|
-
//# sourceMappingURL=chunk-
|
|
506
|
+
//# sourceMappingURL=chunk-UCB7FK25.js.map
|
|
507
|
+
//# sourceMappingURL=chunk-UCB7FK25.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bridge/src/harnesses/omp-models-y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A,EAAW,MAAM,CAAA;AACjD,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,QAAA,GAAW,MAAM,cAAA,CAAe,KAAK,QAAA,EAAU,IAAA,CAAK,QAAQ,CAAA,GAAI,EAAC;AACrF,IAAA,IAAI,KAAK,QAAA,EAAU;AACjB,MAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,IAAA,CAAK,qBAAqB,CAAA,EAAG;AACrD,QAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,UAAU,IAAI,CAAA;AAC1C,QAAA,IAAI;AACF,UAAA,IAAI,EAAE,MAAM,EAAA,CAAG,KAAK,IAAI,CAAA,EAAG,QAAO,EAAG;AAAA,QACvC,CAAA,CAAA,MAAQ;AACN,UAAA;AAAA,QACF;AACA,QAAA,MAAM,EAAA,GAAK,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,UAAU,IAAI,CAAA;AACxC,QAAA,MAAM,YAAY,EAAE,CAAA;AACpB,QAAA,MAAM,EAAA,CAAG,QAAA,CAAS,IAAA,EAAM,EAAE,CAAA;AAAA,MAC5B;AAAA,IACF;AACA,IAAA,MAAM,QAAA,GAAW,MAAM,QAAA,CAAS,IAAA,CAAK,UAAU,WAAA,EAAa;AAAA,MAC1D,GAAG,qBAAA;AAAA,MACH,GAAG;AAAA,KACJ,CAAA;AACD,IAAA,OAAO,EAAE,UAAU,IAAA,CAAK,QAAA,EAAU,WAAW,IAAA,CAAK,SAAA,EAAW,QAAQ,QAAA,EAAS;AAAA,EAChF,CAAC,CAAA;AACH","file":"chunk-UCB7FK25.js","sourcesContent":["/**\n * The omp adapter: an AI provider registry serialized into omp's own\n * configuration files, inside a session-private agent directory.\n *\n * omp already implements the target schema — `~/.omp/agent/models.yml` is a\n * `providers:` map with `baseUrl`, `api`, `apiKey`, `headers`, `authHeader`,\n * `auth`, `discovery` and `models[]` (`omp://models.md`) — so this module is a\n * *serializer*, not a translator. Our `surface` enum is omp's `api` enum\n * verbatim (§1.2); {@link OMP_API_VALUES} encodes that assertion so a future\n * surface that omp does not know is reported instead of silently written into\n * a file omp will then reject wholesale.\n *\n * Two files are produced:\n *\n * - `models.yml` — one entry per enabled `llm`/`embed` registry entry. `apiKey`\n * holds the **name** of the per-entry environment variable\n * (`SKAILE_AIP_<ID>_KEY`, {@link providerCredentialEnvName}), never a value:\n * omp resolves a `models.yml` `apiKey` as an env-var name first and only\n * falls back to treating it as a literal token. The values travel in the\n * child environment.\n * - `config.yml` — omp's settings file, carrying `modelRoles` rendered from the\n * `skaile.yaml` `roles` table. `models.yml`'s root accepts only `providers:`;\n * unknown root keys fail its schema, so roles cannot live there.\n *\n * `PI_CODING_AGENT_DIR` relocates omp's whole agent base — `config.yml`,\n * `models.yml` **and** the auth store `agent.db` (`omp://settings.md`). Pointing\n * it at a session-private directory is what makes N providers per session\n * possible without ever writing the user's `~/.omp/agent`. The cost is that a\n * standalone developer session would also lose the OAuth logins stored in that\n * auth store, so {@link materializeOmpAgentDir} seeds the session directory\n * with symlinks to everything in the user's agent directory *except* the two\n * files this module owns. Verified against omp 18.2.6: a ChatGPT/Codex OAuth\n * account stored in `~/.omp/agent/agent.db` still resolves (`omp token\n * openai-codex`) from a relocated directory that only symlinks `agent.db*`.\n * Under the platform the user directory does not exist, the seed is a no-op,\n * and the session starts empty — which is the correct behaviour there.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3 (omp row), §5, §9\n * @see omp://models.md, omp://settings.md\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport net from \"node:net\";\nimport path from \"node:path\";\nimport {\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n AI_PROVIDER_SURFACES,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n normalizeEntryBaseUrl,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { parse, stringify } from \"yaml\";\nimport type { ModelEntry } from \"../models.js\";\nimport {\n entryCredentialValue,\n providerCredentialEnvName,\n type RegistryCredentialEnvOptions,\n unresolvedProviderCredentials,\n} from \"../provider-materialize/credential-env.js\";\nimport { entrySurface } from \"../provider-materialize/env-harnesses.js\";\nimport type { AgentConfig, OmpHarnessOptions } from \"../types.js\";\n\n/**\n * omp's allowed provider/model `api` values (`omp://models.md`, \"Allowed\n * provider/model `api` values\").\n *\n * Every {@link AI_PROVIDER_SURFACES} member is in this list — that equality is\n * the premise the whole adapter rests on (§1.2). `google-gemini-cli` is omp's\n * one extra value, which the registry has no surface for.\n */\nexport const OMP_API_VALUES: readonly string[] = [...AI_PROVIDER_SURFACES, \"google-gemini-cli\"];\n\n/**\n * `discovery.type` values omp accepts. The registry's own enum is wider on one\n * side (`anthropic-models-list`, `google-models-list`, `none`) and narrower on\n * the other, so a discovery block is emitted only when omp can act on it.\n */\nconst OMP_DISCOVERY_TYPES: readonly string[] = [\n \"ollama\",\n \"llama.cpp\",\n \"lm-studio\",\n \"openai-models-list\",\n \"proxy\",\n \"litellm\",\n];\n\n/** One `providers.<id>` block of `models.yml`. */\ninterface OmpProviderBlock {\n baseUrl?: string;\n api?: string;\n /** The *name* of the env var holding the credential — never a value. */\n apiKey?: string;\n auth?: \"apiKey\" | \"none\" | \"oauth\";\n authHeader?: boolean;\n headers?: Record<string, string>;\n discovery?: { type: string };\n models?: OmpModelBlock[];\n}\n\n/** One entry of a provider's `models[]`. */\ninterface OmpModelBlock {\n id: string;\n name?: string;\n input?: string[];\n contextWindow?: number;\n supportsTools?: boolean;\n}\n\n/** The two files this module owns inside the agent directory. */\nexport const OMP_MODELS_FILENAME = \"models.yml\";\n\n/** omp's settings file; `modelRoles` lives here, not in `models.yml`. */\nexport const OMP_CONFIG_FILENAME = \"config.yml\";\n\n/**\n * Names {@link materializeOmpAgentDir} never links in from the user's agent\n * directory: the two files it writes itself, their alternate spellings, and\n * the legacy `settings.json` omp would migrate into `config.yml`.\n */\nconst OWNED_AGENT_DIR_FILES: Record<string, true> = {\n \"models.yml\": true,\n \"models.yaml\": true,\n \"models.json\": true,\n \"config.yml\": true,\n \"config.yaml\": true,\n \"config.yml.lock\": true,\n \"config.yaml.lock\": true,\n \"settings.json\": true,\n};\n\n/**\n * omp's own runtime state inside its home. An agent directory that an older release used as\n * omp's home still holds these; they are never agent files, so the identity link skips them\n * and the user's own login (`agent.db`) linked in from their agent directory stays in place.\n */\nconst OMP_RUNTIME_ENTRIES: Record<string, true> = {\n \"agent.db\": true,\n \"agent.db-shm\": true,\n \"agent.db-wal\": true,\n \"models.db\": true,\n \"models.db-shm\": true,\n \"models.db-wal\": true,\n \"skill-descriptions.db\": true,\n \"skill-descriptions.db-shm\": true,\n \"skill-descriptions.db-wal\": true,\n \"custom-session-files\": true,\n intercom: true,\n sessions: true,\n};\n\n/**\n * The only entries of the user's own omp agent directory a session's private home links in:\n * omp's credential store, so the login the developer already has keeps working. Sessions,\n * history, `mcp.json`, extensions and blobs stay out: a run must not write into the user's\n * session store or load their MCP servers and extensions. `config.yml` is copied, not linked.\n */\nconst OMP_LOGIN_FILES = [\"agent.db\", \"agent.db-shm\", \"agent.db-wal\"] as const;\n\n/** Options for {@link renderOmpRegistry}. */\nexport interface RenderOmpRegistryOptions extends RegistryCredentialEnvOptions {\n /** `skaile.yaml` `roles`: role name → model selector. Rendered as `modelRoles`. */\n roles?: Record<string, string>;\n /**\n * The session's own selector. When `roles` names no `default`, the resolved\n * model becomes `modelRoles.default` so `@default` (and omp's `*` alias)\n * resolve to the entry the session actually runs on.\n */\n modelRef?: string;\n /**\n * Settings to render underneath `modelRoles` — the user's own `config.yml`\n * when a standalone session seeds one. `modelRoles` is replaced wholesale,\n * not deep-merged: a seeded role pointing at a provider this session does\n * not define would otherwise survive as a dangling selector.\n */\n baseSettings?: Record<string, unknown>;\n}\n\n/** What {@link renderOmpRegistry} produced. */\nexport interface OmpRegistryRender {\n /** `models.yml` contents. */\n modelsYml: string;\n /** `config.yml` contents. */\n configYml: string;\n /**\n * `SKAILE_AIP_<ID>_KEY` → secret, for the child environment. The only place\n * a credential value appears; both rendered files hold names alone.\n */\n credentialEnv: Record<string, string>;\n /** Entry ids written to `models.yml`, in registry order. */\n providerIds: string[];\n /** `modelRoles` as written, role name → `<providerId>/<providerModelId>`. */\n modelRoles: Record<string, string>;\n /** Entries and roles that could not be rendered, and why. */\n warnings: string[];\n}\n\n/** The provider-side model ids an entry declares, keyed by logical id. */\nfunction entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logical = new Set<string>([\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}),\n ]);\n const seen = new Set<string>();\n const out: Array<[string, string]> = [];\n for (const id of logical) {\n const providerSide = entry.model_map?.[id] ?? id;\n if (seen.has(providerSide)) continue;\n seen.add(providerSide);\n out.push([id, providerSide]);\n }\n return out;\n}\n\n/**\n * Serialize one entry into an omp provider block, or report why it cannot be.\n *\n * omp requires `baseUrl` on any provider that declares `models[]`, and\n * provider-level `api` whenever `discovery` is set (except `discovery.type:\n * proxy`, where the wire is auto-detected per model). A file that violates its\n * schema is rejected *wholesale* — the registry keeps operating on built-in\n * models and the error only surfaces through `ModelRegistry.getError()` — so an\n * entry that cannot satisfy those rules is dropped here, loudly, rather than\n * taking every other provider down with it.\n */\nfunction renderProvider(\n id: string,\n entry: AIProviderLlmEntry,\n warnings: string[],\n): OmpProviderBlock | undefined {\n // The Anthropic SDK inside omp appends `/v1/messages`: a stored `…/v1` must\n // not reach the file as written. Not `entryBaseUrl`: omp gets no preset\n // literal, so an entry without an endpoint of its own is reported below.\n const baseUrl = normalizeEntryBaseUrl(resolveEntryBaseUrl(entry), entrySurface(entry));\n if (!baseUrl) {\n warnings.push(\n `provider '${id}' has no resolvable base_url (missing transport params?) — omitted from models.yml`,\n );\n return undefined;\n }\n\n // Only the entry's own surface becomes `api`; an inherited one stays omp's\n // to infer, as before. The preset's surface above only picks the URL rule.\n const surface = entry.surface;\n if (surface && !OMP_API_VALUES.includes(surface)) {\n warnings.push(\n `provider '${id}' has surface '${surface}', which omp's api enum does not accept`,\n );\n return undefined;\n }\n\n const block: OmpProviderBlock = { baseUrl };\n if (surface) block.api = surface;\n\n const kind = entry.credential?.kind ?? \"none\";\n if (kind === \"none\") {\n block.auth = \"none\";\n } else if (kind === \"sigv4\" || kind === \"google_adc\" || kind === \"azure_entra\") {\n // Ambient signing chains: the AWS/Google/Azure SDK inside omp signs the\n // request from its own environment. There is no token to hand over, and\n // omp must not treat the provider as unavailable for the lack of one.\n block.auth = \"none\";\n } else {\n block.apiKey = providerCredentialEnvName(id);\n // `bearer` is the only kind that needs the header injected; the Anthropic\n // and Azure surfaces place an `api_key_header` credential themselves.\n if (kind === \"bearer\" || kind === \"oauth\") block.authHeader = true;\n }\n\n const headers = { ...entry.headers };\n if (entry.query_params && Object.keys(entry.query_params).length > 0) {\n if (surface === \"bedrock-converse-stream\") {\n // omp keeps a query string on a Bedrock `baseUrl` and appends it to the\n // final URL (and to SigV4's canonical request) — the documented carrier\n // for gateways that authenticate by query parameter.\n const search = new URLSearchParams(entry.query_params).toString();\n block.baseUrl = `${baseUrl}${baseUrl.includes(\"?\") ? \"&\" : \"?\"}${search}`;\n } else {\n warnings.push(\n `provider '${id}' declares query_params, which omp's models.yml has no slot for on surface ` +\n `'${surface ?? \"unset\"}' — they were dropped`,\n );\n }\n }\n if (Object.keys(headers).length > 0) block.headers = headers;\n\n const discoveryType = entry.discovery?.type;\n if (discoveryType) {\n if (!OMP_DISCOVERY_TYPES.includes(discoveryType)) {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}', which omp does not implement — ` +\n `models come from model_map only`,\n );\n } else if (!surface && discoveryType !== \"proxy\") {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}' but no surface — omp requires ` +\n `provider-level api for every discovery type but 'proxy'`,\n );\n } else {\n block.discovery = { type: discoveryType };\n }\n }\n\n const models: OmpModelBlock[] = [];\n for (const [logical, providerSide] of entryModelIds(entry)) {\n const model: OmpModelBlock = { id: providerSide };\n if (logical !== providerSide) model.name = logical;\n const caps = entry.capabilities?.[logical];\n if (caps?.context_window !== undefined) model.contextWindow = caps.context_window;\n if (caps?.images !== undefined) model.input = caps.images ? [\"text\", \"image\"] : [\"text\"];\n if (caps?.tools !== undefined) model.supportsTools = caps.tools;\n models.push(model);\n }\n if (models.length > 0) {\n if (!surface) {\n warnings.push(\n `provider '${id}' declares models but no surface — omp requires api at provider or model level`,\n );\n return undefined;\n }\n block.models = models;\n } else if (!block.discovery) {\n warnings.push(\n `provider '${id}' declares neither model_map/capabilities nor a discovery omp implements — ` +\n `it will only override an omp built-in provider of the same id`,\n );\n }\n\n return block;\n}\n\n/**\n * Resolve the `roles` table into omp `modelRoles` selectors.\n *\n * Roles do not chain, so each value is resolved as a plain selector rather than\n * through `@role` expansion. A trailing omp thinking suffix (`:high`) survives\n * untouched: it is not part of any `model_map` key, so it falls through\n * `parseModelRef`'s literal path and is re-emitted on the provider-side id.\n */\nfunction renderModelRoles(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n roles: Record<string, string> | undefined,\n modelRef: string | undefined,\n warnings: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [role, selector] of Object.entries(roles ?? {})) {\n const trimmed = selector.trim();\n if (!trimmed) continue;\n const ref = parseModelRef(trimmed, registry);\n if (!ref?.providerModelId) {\n warnings.push(\n `role '${role}' ('${selector}') resolves to no model in this registry — dropped`,\n );\n continue;\n }\n // An id no entry lists is passed on as typed, never under the first entry's name.\n out[role] = ref.fallback ? trimmed : `${ref.providerId}/${ref.providerModelId}`;\n }\n if (out.default === undefined && modelRef) {\n const ref = parseModelRef(modelRef, registry, roles);\n if (ref?.providerModelId && !ref.fallback) {\n out.default = `${ref.providerId}/${ref.providerModelId}`;\n }\n }\n return out;\n}\n\n/**\n * The warning for an entry left out of `models.yml` because its credential does not resolve.\n * `skaile run` and `skaile repl` print the same fact as one `! provider ... is not used` line\n * (runner `credential-notice.ts`), so the harness keeps this warning off the console.\n */\nfunction credentialOmissionWarning(id: string, reason: string): string {\n return `provider '${id}' omitted from models.yml: ${reason}`;\n}\n\n/** True for a warning built by {@link credentialOmissionWarning}. */\nexport function isCredentialOmissionWarning(warning: string): boolean {\n return /^provider '[^']+' omitted from models\\.yml: /.test(warning);\n}\n\n/**\n * Serialize a registry into the two omp files plus the credential environment\n * that carries their secrets.\n *\n * Only enabled `llm`/`embed` entries are rendered: `stt`/`tts` entries have no\n * wire surface and omp has no slot for them. The credential environment is\n * scoped to the same set — the omp child has no use for a Deepgram key, and a\n * secret that reaches a process which cannot spend it is pure exposure.\n *\n * An entry whose credential does not resolve here still gets its\n * `SKAILE_AIP_<ID>_KEY` name written into `models.yml`: a `platform:` ref is\n * resolved by the session boundary, which materializes the value into\n * `AgentConfig.env` under that same programme-standard name.\n */\nexport function renderOmpRegistry(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: RenderOmpRegistryOptions = {},\n): OmpRegistryRender {\n const warnings: string[] = [];\n const providers: Record<string, OmpProviderBlock> = {};\n const providerIds: string[] = [];\n const credentialEnv: Record<string, string> = {};\n\n // An entry whose credential cannot be resolved here is not handed to omp: it\n // would send an empty key (`invalid x-api-key`) and shadow omp's own login for\n // the same provider.\n const unresolved = new Map(\n unresolvedProviderCredentials(registry, options).map((u) => [u.providerId, u.reason]),\n );\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const reason = unresolved.get(id);\n if (reason) {\n warnings.push(credentialOmissionWarning(id, reason));\n continue;\n }\n const block = renderProvider(id, entry as AIProviderLlmEntry, warnings);\n if (!block) continue;\n providers[id] = block;\n providerIds.push(id);\n // Only the canonical name, never a vendor-conventional alias: every\n // endpoint omp may address is named in models.yml with its own variable,\n // and a stray `ANTHROPIC_API_KEY` would silently make omp's *built-in*\n // Anthropic provider look authenticated with some gateway entry's key.\n const secret = entryCredentialValue(id, entry, options);\n if (secret) credentialEnv[providerCredentialEnvName(id)] = secret;\n }\n\n const modelRoles = renderModelRoles(registry, options.roles, options.modelRef, warnings);\n\n const settings: Record<string, unknown> = { ...options.baseSettings };\n if (Object.keys(modelRoles).length > 0) settings.modelRoles = modelRoles;\n\n return {\n modelsYml: stringify({ providers }),\n configYml: stringify(settings),\n credentialEnv,\n providerIds,\n modelRoles,\n warnings,\n };\n}\n\n/**\n * The models a registry makes selectable, as the harness-neutral catalog entry.\n *\n * ids are `<providerId>/<providerModelId>` — the exact selector omp's `--model`\n * and `modelRoles` take, and unambiguous when two entries serve the same model\n * id, which is the normal case once a session carries N providers.\n */\nexport function registryModelEntries(\n registry: AIProviderRegistry | MergedAIProviderRegistry | undefined,\n): ModelEntry[] {\n if (!registry) return [];\n const out: ModelEntry[] = [];\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const label = entry.label ?? id;\n for (const [logical, providerSide] of entryModelIds(entry as AIProviderLlmEntry)) {\n out.push({ id: `${id}/${providerSide}`, name: `${label} ${logical}` });\n }\n }\n return out;\n}\n\n/**\n * Why omp cannot serve `<providerId>/<model>` from this registry, or `undefined` when it can (or\n * when this check cannot tell). omp knows only the models a registry entry declares\n * (`model_map`, `capabilities`) or its `discovery` lists: for a provider id omp has no login for\n * and an entry that declares neither, `omp --model fake/fake-1` exits with `Model \"fake/fake-1\"\n * not found` on the first prompt (p1334). `nativeProviders` are the ids omp ships a login for;\n * their entry only overrides the built-in provider, so the model may still be omp's own.\n */\nexport function ompRegistryModelRefusal(\n registry: AIProviderRegistry | MergedAIProviderRegistry | undefined,\n selector: string,\n nativeProviders: ReadonlySet<string>,\n): string | undefined {\n if (!registry) return undefined;\n const slash = selector.indexOf(\"/\");\n if (slash <= 0) return undefined;\n const head = selector.slice(0, slash);\n // A trailing omp thinking suffix (`:high`) is not part of the model id.\n const model = selector.slice(slash + 1).replace(/:(off|minimal|low|medium|high|xhigh)$/i, \"\");\n if (!model || nativeProviders.has(head)) return undefined;\n const found = registryEntries(registry).find(([id]) => id === head);\n if (!found) return undefined;\n const [, entry] = found;\n if ((entry.kind !== \"llm\" && entry.kind !== \"embed\") || !isEntryEnabled(entry)) return undefined;\n const llm = entry as AIProviderLlmEntry;\n if (llm.discovery?.type && OMP_DISCOVERY_TYPES.includes(llm.discovery.type)) return undefined;\n const known = entryModelIds(llm).flatMap(([logical, providerSide]) => [logical, providerSide]);\n if (known.includes(model)) return undefined;\n return known.length === 0\n ? `omp cannot serve model '${selector}': registry entry '${head}' declares no models (add model_map or capabilities to it in providers.yml), and omp has no login for '${head}'. Pick a model omp lists.`\n : `omp cannot serve model '${selector}': registry entry '${head}' declares ${known.join(\", \")}, not '${model}'. Pick one of those, or add '${model}' to the entry's model_map.`;\n}\n\n/** Options for {@link materializeOmpAgentDir}. */\nexport interface MaterializeOmpAgentDirOptions extends RenderOmpRegistryOptions {\n /**\n * The user's own omp agent directory to seed from — its auth store\n * (`agent.db`) is linked in so a standalone session keeps the login the\n * developer already has, and its `config.yml` is read as base settings.\n * Sessions, history, `mcp.json` and extensions are not linked. Absent (the\n * platform case) seeds nothing. A missing directory is not an error: it is the platform case.\n */\n seedFrom?: string;\n /**\n * GitAgent identity directory (`AgentConfig.agentDir`) whose contents omp\n * reads out of the same base: `agent.yaml`, `SOUL.md`, `RULES.md`,\n * `knowledge/`. Linked in after the seed, so identity wins a name clash.\n */\n identityDir?: string;\n}\n\n/** What {@link materializeOmpAgentDir} wrote. */\nexport interface OmpAgentDirMaterialization extends OmpRegistryRender {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the harness's temporary home: remove it when the run ends. */\n ephemeral?: boolean;\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.seedFrom}. */\n seeded: string[];\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.identityDir}. */\n identity: string[];\n}\n\n/** Inputs {@link planOmpAgentDir} derives the session directory layout from. */\nexport interface OmpAgentDirPlanInput {\n /** Session working directory. Distinguishes two default-named sessions. */\n cwd: string;\n /** Session id — the directory key, so concurrent sessions never collide. */\n sessionId?: string;\n /** `AgentConfig.harnessOptions.omp`. */\n options?: OmpHarnessOptions;\n /** Home the default seed source resolves against. Defaults to `os.homedir()`. */\n homeDir?: string;\n /** Root the private directory is created under. Defaults to `os.tmpdir()`. */\n tmpDir?: string;\n}\n\n/** Where a session's omp agent directory lives, and what it inherits. */\nexport interface OmpAgentDirPlan {\n /** Session-private directory `PI_CODING_AGENT_DIR` points at. */\n agentDir: string;\n /** User agent directory whose login is linked in, when there is one to inherit. */\n seedFrom?: string;\n /**\n * The directory is the harness's own temporary home, to be removed when the run ends. False\n * when the session named its own `harnessOptions.omp.agentHome`, which belongs to the user.\n */\n ephemeral: boolean;\n}\n\n/**\n * Decide the session-private agent directory and whether it inherits the\n * developer's omp state.\n *\n * The directory is deliberately **outside `cwd`**. It holds omp's credential\n * store — a symlink to the developer's `agent.db` on a standalone machine —\n * and `cwd` is the one tree the agent has write access to by design; managed\n * codex draws the same line and rejects a private directory nested in the\n * workspace (`codex/instance-state.ts`). Sessions are keyed by id, falling\n * back to a digest of the workspace path. The temporary directory is `<key>-<random>`, created per\n * call, so no two runs share one (and one run's cleanup never removes another's).\n *\n * Seeding keys on the user directory *existing*, which is exactly the\n * platform/standalone distinction the plan draws: a platform container has no\n * `~/.omp/agent`, so the session correctly starts empty; a developer machine\n * has one, so the session keeps the logins already stored there.\n * `harnessOptions.omp.seedUserAgentDir: false` forces the empty case anyway.\n */\nexport async function planOmpAgentDir(input: OmpAgentDirPlanInput): Promise<OmpAgentDirPlan> {\n const options = input.options;\n const key =\n input.sessionId?.trim() ||\n createHash(\"sha256\").update(path.resolve(input.cwd)).digest(\"hex\").slice(0, 16);\n const ephemeral = options?.agentHome === undefined;\n // The temporary home is unique per spawn: callers key sessions loosely (`skaile chat` passes\n // none, `serve` without --session-id uses one shared id, sub-prompt harnesses share a hash), and\n // the harness deletes its home when its run ends, which must never reach a sibling's home.\n let agentDir = options?.agentHome ?? \"\";\n if (ephemeral) {\n const root = path.join(input.tmpDir ?? os.tmpdir(), \"skaile-omp-agent\");\n await fs.mkdir(root, { recursive: true });\n await sweepStaleOmpHomes(root);\n agentDir = await fs.mkdtemp(path.join(root, `${key.replace(/[^A-Za-z0-9._-]/g, \"_\")}-`));\n await fs.writeFile(path.join(agentDir, OWNER_FILE), String(process.pid));\n }\n if (options?.seedUserAgentDir === false) return { agentDir, ephemeral };\n\n const seedFrom =\n options?.userAgentDir ?? path.join(input.homeDir ?? os.homedir(), \".omp\", \"agent\");\n if (path.resolve(seedFrom) === path.resolve(agentDir)) return { agentDir, ephemeral };\n try {\n if (!(await fs.stat(seedFrom)).isDirectory()) return { agentDir, ephemeral };\n } catch {\n return { agentDir, ephemeral };\n }\n return { agentDir, seedFrom, ephemeral };\n}\n\n/** Names the process that created a temporary home; the sweep keeps a home whose owner lives. */\nconst OWNER_FILE = \".skaile-owner-pid\";\n/** A temporary home older than this whose owner is gone is removed at the next start. */\nconst STALE_HOME_MS = 24 * 60 * 60 * 1000;\n\n/**\n * The names skaile gave a temporary home: `<key>-<six random characters>` (`mkdtemp`), and\n * `<key>-<12 hex>` from releases before 5.16 (p1151).\n */\nconst SKAILE_HOME_NAME = /^[A-Za-z0-9._-]+-(?:[A-Za-z0-9]{6}|[0-9a-f]{12})$/;\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Whether nothing listens on the unix socket `file`: a connect is refused (the process that\n * bound it is gone) or finds no socket. A socket somebody still serves, or one that does not\n * answer within a second, counts as in use.\n */\nfunction socketIsDead(file: string): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n const conn = net.connect(file);\n const done = (dead: boolean) => {\n conn.destroy();\n resolve(dead);\n };\n conn.setTimeout(1000, () => done(false));\n conn.once(\"connect\", () => done(false));\n conn.once(\"error\", (err: NodeJS.ErrnoException) =>\n done(err.code === \"ECONNREFUSED\" || err.code === \"ENOENT\"),\n );\n });\n}\n\n/**\n * Remove temporary homes older than a day whose creating process is gone: a run that was killed\n * never reached the harness's own cleanup, and every one leaves symlinks and databases behind\n * (p811). A home of a live process is kept whatever its age. A unix socket of that age that\n * nobody listens on is removed too (omp binds one beside the homes and a killed run leaves it,\n * p1316). Best effort: a failure is ignored.\n */\nasync function sweepStaleOmpHomes(root: string, now = Date.now()): Promise<void> {\n let names: string[];\n try {\n names = await fs.readdir(root);\n } catch {\n return;\n }\n await Promise.all(\n names.map(async (name) => {\n const home = path.join(root, name);\n try {\n const stat = await fs.lstat(home);\n if (now - stat.mtimeMs < STALE_HOME_MS) return;\n if (stat.isSocket()) {\n if (await socketIsDead(home)) await fs.rm(home, { force: true });\n return;\n }\n if (!stat.isDirectory()) return;\n const owner = Number.parseInt(\n await fs.readFile(path.join(home, OWNER_FILE), \"utf8\").catch(() => \"\"),\n 10,\n );\n if (Number.isInteger(owner) && processAlive(owner)) return;\n // A home with no owner file is one an older version made: remove it only when its\n // name has the `<key>-<six random characters>` shape `mkdtemp` gives (never a folder\n // somebody else put in this directory).\n if (!Number.isInteger(owner) && !SKAILE_HOME_NAME.test(name)) return;\n await fs.rm(home, { recursive: true, force: true });\n } catch {\n /* another process may be sweeping the same home */\n }\n }),\n );\n}\n\n/**\n * Run the steps that fill a planned home; when one throws, remove a temporary home before\n * rethrowing. The harness only learns the home (and deletes it at cleanup) once these steps\n * return, so a failure here would otherwise leave a new directory per spawn behind.\n */\nasync function removeHomeOnThrow<T>(plan: OmpAgentDirPlan, fill: () => Promise<T>): Promise<T> {\n try {\n return await fill();\n } catch (err) {\n if (plan.ephemeral) await fs.rm(plan.agentDir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/** Remove a path whatever it is, without following a symlink into its target. */\nasync function removeEntry(target: string): Promise<void> {\n let stat: Stats;\n try {\n stat = await fs.lstat(target);\n } catch {\n return;\n }\n if (stat.isSymbolicLink() || stat.isFile()) {\n await fs.unlink(target);\n return;\n }\n await fs.rm(target, { recursive: true, force: true });\n}\n\n/** Symlink every entry of `sourceDir` into `dir`, skipping the owned names. */\nasync function linkInto(\n dir: string,\n sourceDir: string,\n skip: Record<string, true>,\n): Promise<string[]> {\n let names: string[];\n try {\n names = await fs.readdir(sourceDir);\n } catch {\n return [];\n }\n const linked: string[] = [];\n for (const name of names) {\n if (skip[name]) continue;\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(path.join(sourceDir, name), target);\n linked.push(name);\n }\n return linked;\n}\n\n/**\n * Remove the symlinks into the user's agent directory that an older release (or a home the\n * session named itself) left in `dir`: only the login files may point there (p811).\n */\nasync function dropStaleSeedLinks(dir: string, sourceDir: string): Promise<void> {\n let names: string[];\n try {\n names = await fs.readdir(dir);\n } catch {\n return;\n }\n const root = path.resolve(sourceDir);\n for (const name of names) {\n if ((OMP_LOGIN_FILES as readonly string[]).includes(name)) continue;\n const entry = path.join(dir, name);\n try {\n if (!(await fs.lstat(entry)).isSymbolicLink()) continue;\n const to = path.resolve(dir, await fs.readlink(entry));\n if (to === root || to.startsWith(root + path.sep)) await fs.unlink(entry);\n } catch {\n // Gone or unreadable: nothing to drop.\n }\n }\n}\n\n/** Symlink the login files (see {@link OMP_LOGIN_FILES}) of the user's agent directory into `dir`. */\nasync function linkLoginFiles(dir: string, sourceDir: string): Promise<string[]> {\n await dropStaleSeedLinks(dir, sourceDir);\n const linked: string[] = [];\n for (const name of OMP_LOGIN_FILES) {\n const from = path.join(sourceDir, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(from, target);\n linked.push(name);\n }\n return linked;\n}\n\n/** Read a seeded `config.yml` as the base settings, or `{}` when unusable. */\nasync function readSeededSettings(seedFrom: string): Promise<Record<string, unknown>> {\n for (const name of [\"config.yml\", \"config.yaml\"]) {\n let raw: string;\n try {\n raw = await fs.readFile(path.join(seedFrom, name), \"utf-8\");\n } catch {\n continue;\n }\n const parsed = parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n }\n return {};\n}\n\n/**\n * The model selector of the user's own omp default (`modelRoles.default` in their `config.yml`)\n * when it can only be served by their own `models.yml`, else `undefined` (p1172).\n *\n * The session-private home never copies the user's `models.yml`: it holds their credentials.\n * A default such as `anthropic/claude-opus-5-5` that their `models.yml` defines (a gateway, a\n * local server) then names a provider the private home does not have, and omp quietly picks\n * another model. A default on a built-in omp provider keeps working there (its login is linked\n * in), and a provider the registry renders is there too, so neither is reported.\n */\nasync function ownDefaultNeedingOwnModels(\n seedFrom: string,\n rendered: readonly string[],\n): Promise<string | undefined> {\n const selector = (await readSeededSettings(seedFrom)).modelRoles;\n const own =\n selector && typeof selector === \"object\" && !Array.isArray(selector)\n ? (selector as Record<string, unknown>).default\n : undefined;\n if (typeof own !== \"string\" || !own.includes(\"/\")) return undefined;\n const providerId = own.slice(0, own.indexOf(\"/\"));\n if (rendered.includes(providerId)) return undefined;\n let raw: string;\n try {\n raw = await fs.readFile(path.join(seedFrom, OMP_MODELS_FILENAME), \"utf-8\");\n } catch {\n return undefined;\n }\n const providers = (parse(raw) as { providers?: unknown } | null)?.providers;\n if (!providers || typeof providers !== \"object\" || Array.isArray(providers)) return undefined;\n return providerId in providers ? own : undefined;\n}\n\n/**\n * Build the session-private agent directory and write omp's two files into it.\n *\n * The user's `~/.omp/agent/models.yml` and `config.yml` are never opened for\n * writing: `config.yml` is *copied* into the session (so a token refresh or a\n * settings write inside the session cannot reach back through a symlink),\n * `models.yml` is not seeded at all, and everything else — `agent.db*` above\n * all — is symlinked so the session shares the developer's logins and caches.\n */\nexport async function materializeOmpAgentDir(\n agentDir: string,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: MaterializeOmpAgentDirOptions = {},\n): Promise<OmpAgentDirMaterialization> {\n await fs.mkdir(agentDir, { recursive: true });\n\n const seeded = options.seedFrom ? await linkLoginFiles(agentDir, options.seedFrom) : [];\n const identity = options.identityDir\n ? await linkInto(agentDir, options.identityDir, OWNED_AGENT_DIR_FILES)\n : [];\n\n const baseSettings =\n options.baseSettings ??\n (options.seedFrom ? await readSeededSettings(options.seedFrom) : undefined);\n\n const render = renderOmpRegistry(registry, { ...options, baseSettings });\n\n await fs.writeFile(path.join(agentDir, OMP_MODELS_FILENAME), render.modelsYml, \"utf-8\");\n await fs.writeFile(path.join(agentDir, OMP_CONFIG_FILENAME), render.configYml, \"utf-8\");\n\n return { ...render, agentDir, seeded, identity };\n}\n\n/** What the omp harness gets back from {@link materializeOmpProviders}. */\nexport interface OmpProviderMaterialization extends OmpAgentDirMaterialization {\n /**\n * The `--model` argument for this session: `<providerId>/<providerModelId>`,\n * the one selector form omp treats as unambiguous when several providers\n * carry the same model id. Absent when the session named no model.\n */\n modelArg?: string;\n}\n\n/**\n * The whole omp adapter for one session: decide the private agent directory,\n * inherit the developer's omp state where there is any, write `models.yml` and\n * `config.yml`, and report the credential environment and `--model` selector\n * the child needs.\n *\n * Returns `undefined` when the session carries no registry with a selectable\n * entry — the harness then behaves exactly as it did before the registry\n * existed, which is what keeps this an expand-and-contract change.\n *\n * Also returns `undefined` when the session names no model (no `--model`, no\n * `default` role) and the user's own omp default is served by the user's own\n * `models.yml`, which a private home does not carry (p1172): the registry would\n * only swap that default for whatever model omp finds first.\n *\n * Also returns `undefined` when no entry can be handed to omp (every\n * credential unresolved) or when the entry the session's model selects was\n * left out: a session-private agent directory would then start omp without the\n * user's own settings, and a model that only the user's own omp login can\n * serve would fail with `No API key found` although native omp answers. The\n * harness then starts omp on the user's agent directory, so \"omp falls back to\n * its own login\" is true.\n *\n * `env:` references resolve against the runner's environment *overlaid with*\n * `config.env`, so a credential the session boundary already resolved (a\n * `platform:` secret it turned into an env var, for instance) is found here\n * under the name the registry entry points at.\n */\nexport async function materializeOmpProviders(\n config: AgentConfig,\n): Promise<OmpProviderMaterialization | undefined> {\n const registry = config.registry;\n if (!registry) return undefined;\n const selectable = registryEntries(registry).some(\n ([, entry]) => (entry.kind === \"llm\" || entry.kind === \"embed\") && isEntryEnabled(entry),\n );\n if (!selectable) return undefined;\n\n const env = { ...process.env, ...config.env };\n const selected = config.modelRef\n ? parseModelRef(config.modelRef, registry, config.roles)\n : undefined;\n const usable = renderOmpRegistry(registry, {\n env,\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }).providerIds;\n if (usable.length === 0) return undefined;\n // An id no entry lists is no entry's model: omp gets it as typed, whichever entry is first.\n if (selected && !selected.fallback && !usable.includes(selected.providerId)) return undefined;\n\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.harnessOptions?.omp ? { options: config.harnessOptions.omp } : {}),\n });\n\n if (!selected && !config.model && plan.seedFrom) {\n const named = renderOmpRegistry(registry, {\n env,\n ...(config.roles ? { roles: config.roles } : {}),\n }).modelRoles;\n if (named.default === undefined && (await ownDefaultNeedingOwnModels(plan.seedFrom, usable))) {\n if (plan.ephemeral) await fs.rm(plan.agentDir, { recursive: true, force: true });\n return undefined;\n }\n }\n\n const rendered = await removeHomeOnThrow(plan, () =>\n materializeOmpAgentDir(plan.agentDir, registry, {\n env,\n ...(plan.seedFrom ? { seedFrom: plan.seedFrom } : {}),\n ...(config.agentDir ? { identityDir: config.agentDir } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }),\n );\n\n return {\n ...rendered,\n ephemeral: plan.ephemeral,\n ...(selected?.providerModelId && !selected.fallback\n ? { modelArg: `${selected.providerId}/${selected.providerModelId}` }\n : {}),\n };\n}\n\n/** What {@link materializeOmpIdentityDir} wrote. */\nexport interface OmpIdentityDirMaterialization {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the harness's temporary home: remove it when the run ends. */\n ephemeral: boolean;\n /** Names linked in from the user's own omp agent directory. */\n seeded: string[];\n /** Names linked in from `AgentConfig.agentDir`. */\n identity: string[];\n}\n\n/**\n * The omp home of a session that has an agent directory but no provider registry.\n *\n * omp keeps its runtime state (`agent.db`, `models.db`, `skill-descriptions.db`, session\n * scratch, `intercom/`) in `PI_CODING_AGENT_DIR`. Pointing that at the agent directory itself\n * put those files beside `SOUL.md` in a pinned, shared source (`.skaile/cache/agents/<name>/`)\n * and made omp name a path inside the cache when it lacks a credential. So the home is a\n * private directory outside `cwd` (see {@link planOmpAgentDir}): the developer's own omp state\n * is linked in (their login keeps working), their `config.yml` / `models.yml` are copied (a\n * settings write cannot reach back), and the agent directory's entries are linked in last,\n * so the agent files stay where they are and omp can still read them.\n *\n * Returns `undefined` when the session has no `agentDir`.\n */\nexport async function materializeOmpIdentityDir(\n config: AgentConfig,\n): Promise<OmpIdentityDirMaterialization | undefined> {\n const identityDir = config.agentDir;\n if (!identityDir) return undefined;\n // Keyed by the agent and the workspace too: two role children of one session, each with\n // its own agent directory, must not link their entries into one home.\n const agentKey = createHash(\"sha256\")\n .update(`${path.resolve(identityDir)}\\0${path.resolve(config.cwd)}`)\n .digest(\"hex\")\n .slice(0, 12);\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n sessionId: `${config.sessionId?.trim() || \"agent\"}-${agentKey}`,\n ...(config.harnessOptions?.omp ? { options: config.harnessOptions.omp } : {}),\n });\n return removeHomeOnThrow(plan, async () => {\n await fs.mkdir(plan.agentDir, { recursive: true });\n const seeded = plan.seedFrom ? await linkLoginFiles(plan.agentDir, plan.seedFrom) : [];\n if (plan.seedFrom) {\n for (const name of Object.keys(OWNED_AGENT_DIR_FILES)) {\n const from = path.join(plan.seedFrom, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const to = path.join(plan.agentDir, name);\n await removeEntry(to);\n await fs.copyFile(from, to);\n }\n }\n const identity = await linkInto(plan.agentDir, identityDir, {\n ...OWNED_AGENT_DIR_FILES,\n ...OMP_RUNTIME_ENTRIES,\n });\n return { agentDir: plan.agentDir, ephemeral: plan.ephemeral, seeded, identity };\n });\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isAgentNode, isSubpromptNode, isSubFlowNode, nodeBindings, isRouterNode, nodeIsOptional, nodeSkillId, nodeLabel, isActiveRuntimeNode } from './chunk-7RGTAEG6.js';
|
|
2
2
|
import { parseFlowDefinition } from './chunk-JRN5QF4C.js';
|
|
3
3
|
import { resolveFlowBindings, stableFlowJson, evaluateFlowExpression, FlowExpressionError, getConsumedOutputSchema, compileOutputFieldsSchema } from './chunk-NUELZWCF.js';
|
|
4
|
-
import { projectAssetRoots } from './chunk-
|
|
4
|
+
import { projectAssetRoots } from './chunk-TMJBEGS4.js';
|
|
5
5
|
import { findKindDirs } from './chunk-MWXYN6NY.js';
|
|
6
6
|
import * as path2 from 'path';
|
|
7
7
|
import path2__default from 'path';
|
|
@@ -269,7 +269,7 @@ function planRouterSkips(flow, snapshots, settlements) {
|
|
|
269
269
|
losingRouteEdges.add(edgeKey(router.id, target));
|
|
270
270
|
}
|
|
271
271
|
}
|
|
272
|
-
const
|
|
272
|
+
const regions = /* @__PURE__ */ new Map();
|
|
273
273
|
for (const root of losingRoots) {
|
|
274
274
|
const visited = /* @__PURE__ */ new Set();
|
|
275
275
|
const queue = [root];
|
|
@@ -277,10 +277,22 @@ function planRouterSkips(flow, snapshots, settlements) {
|
|
|
277
277
|
const nodeId = queue[index];
|
|
278
278
|
if (visited.has(nodeId)) continue;
|
|
279
279
|
visited.add(nodeId);
|
|
280
|
+
for (const target of outgoing.get(nodeId) ?? []) queue.push(target);
|
|
281
|
+
}
|
|
282
|
+
regions.set(root, visited);
|
|
283
|
+
}
|
|
284
|
+
const regionEntries = [...regions];
|
|
285
|
+
const nestedRoots = new Set(
|
|
286
|
+
[...losingRoots].filter(
|
|
287
|
+
(root) => regionEntries.some(([other, region]) => other !== root && region.has(root))
|
|
288
|
+
)
|
|
289
|
+
);
|
|
290
|
+
const candidateOrigins = /* @__PURE__ */ new Map();
|
|
291
|
+
for (const [root, region] of regions) {
|
|
292
|
+
for (const nodeId of region) {
|
|
280
293
|
const origins = candidateOrigins.get(nodeId) ?? /* @__PURE__ */ new Set();
|
|
281
|
-
origins.add(root);
|
|
294
|
+
if (!nestedRoots.has(root)) origins.add(root);
|
|
282
295
|
candidateOrigins.set(nodeId, origins);
|
|
283
|
-
for (const target of outgoing.get(nodeId) ?? []) queue.push(target);
|
|
284
296
|
}
|
|
285
297
|
}
|
|
286
298
|
const candidates = new Set(candidateOrigins.keys());
|
|
@@ -309,7 +321,9 @@ function planRouterSkips(flow, snapshots, settlements) {
|
|
|
309
321
|
const nodeId = protectionQueue[index];
|
|
310
322
|
if (protectedNodes.has(nodeId)) continue;
|
|
311
323
|
protectedNodes.add(nodeId);
|
|
312
|
-
|
|
324
|
+
for (const target of outgoing.get(nodeId) ?? []) {
|
|
325
|
+
if (!losingRouteEdges.has(edgeKey(nodeId, target))) protectionQueue.push(target);
|
|
326
|
+
}
|
|
313
327
|
protectionQueue.push(...unknownSelections.get(nodeId) ?? []);
|
|
314
328
|
}
|
|
315
329
|
return flow.nodes.flatMap(
|
|
@@ -979,5 +993,5 @@ function findFlowFileInRoots(flowId, roots, opts = {}) {
|
|
|
979
993
|
}
|
|
980
994
|
|
|
981
995
|
export { FLOW_FILE_EXTENSIONS, FlowManifestSchema, appendAttempt, availableRouterFrontier, buildFlowExpressionContext, computeFlowState, computeFlowStateFromSnapshots, computeSkippable, countFailedAttempts, deriveCheckEvidence, evaluateRouterSelection, findFlowFileInRoots, flowFileCandidates, flowKindProvider, flowLookupRoots, hasAutomaticRetryBudget, interpolateNodeInstruction, isActiveExecutionExpired, isBlocking, loadAllFlowEntries, loadAllFlows, loadFlow, loadFlowEntriesFromDir, loadFlowsFromDir, nextAttemptNumber, persistedRouterSelection, planRouterSkips, producerOutputObtainedBy, projectAiAssetsRoots, remainingActiveExecutionMs, resolveAvailableRouter, resolveFlowOutputFields, resolveNextNodes, resolveNodeBindings, resolveTerminalFailureStatus, routerSelectionOutput, unsettledRouterBranchIds, validateConsumedNodeOutput, validateFlow };
|
|
982
|
-
//# sourceMappingURL=chunk-
|
|
983
|
-
//# sourceMappingURL=chunk-
|
|
996
|
+
//# sourceMappingURL=chunk-WFK4MUBL.js.map
|
|
997
|
+
//# sourceMappingURL=chunk-WFK4MUBL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../factory-assets/connectors/flow/engine/bindings.ts","../factory-assets/connectors/flow/engine/router-settlement.ts","../factory-assets/connectors/flow/engine/engine.ts","../factory-assets/connectors/flow/engine/output-schema.ts","../factory-assets/connectors/flow/engine/flow-output.ts","../factory-assets/connectors/flow/engine/node-deadline.ts","../factory-assets/connectors/flow/engine/node-attempts.ts","../factory-assets/connectors/flow/engine/optional-failure.ts","../factory-assets/connectors/flow/engine/check-provenance.ts","../factory-assets/connectors/flow/engine/flow-manifest.ts","../factory-assets/connectors/flow/engine/flow-kind-provider.ts","../factory-assets/connectors/flow/engine/loader.ts","../factory-assets/connectors/flow/engine/locate.ts"],"names":["process","path","parseYaml","fs"],"mappings":";;;;;;;;;;;;AAWO,SAAS,0BAAA,CACd,MACA,SAAA,EACuB;AACvB,EAAA,MAAM,QAAwC,EAAC;AAC/C,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,KAAA,EAAO;AAC7B,IAAA,MAAM,QAAA,GAAW,SAAA,CAAU,GAAA,CAAI,IAAA,CAAK,EAAE,CAAA;AACtC,IAAA,MAAM,MAAA,GACJ,QAAA,EAAU,MAAA,KAAW,UAAA,IAAc,QAAA,CAAS,MAAA,EAAQ,MAAA,GAChD,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,CAAO,MAAA,EAAO,GACjC,MAAA;AACN,IAAA,K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,CAAA,CAAE,IAAA,CAAK,EAAA,KAAO,MAAM,CAAA;AAC7F,IAAA,IAAI,KAAA,SAAc,KAAA,CAAM,IAAA;AAAA,EAC1B;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-WFK4MUBL.js","sourcesContent":["import {\n resolveFlowBindings,\n stableFlowJson,\n type BindingOrigin,\n type FlowExpressionContext,\n type ResolvedNodeBindings,\n} from \"../contract/expression.js\";\nimport { isAgentNode, isSubFlowNode, isSubpromptNode, nodeBindings } from \"./node-shape.js\";\nimport type { FlowDefinition, FlowNode, NodeExecutionSnapshot } from \"./types.js\";\n\n/** Build the bounded expression context from immutable definition and snapshot state. */\nexport function buildFlowExpressionContext(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowExpressionContext {\n const nodes: FlowExpressionContext[\"nodes\"] = {};\n for (const node of flow.nodes) {\n const snapshot = snapshots.get(node.id);\n const output =\n snapshot?.status === \"complete\" && snapshot.output?.fields\n ? { fields: snapshot.output.fields }\n : undefined;\n nodes[node.id] = { status: snapshot?.status ?? \"not_started\", output };\n }\n return {\n flow: { input: flow.defaults?.run_input ?? {} },\n defaults: flow.defaults,\n nodes,\n };\n}\n\n/**\n * Classify what one producer node's output counts as for a downstream binding.\n *\n * Transitive by induction, in a single lookup: a producer's persisted\n * `inputOrigins` were themselves classified under this rule when it ran, so\n * they already carry any taint from its own ancestors — no graph walk. Absent\n * origins read as `\"agent\"` (fail-closed): a snapshot persisted before the\n * field existed cannot prove the node's inputs were clean, and this label is\n * one a human approver acts on. `{}` — a node that bound nothing — is\n * `\"runtime\"`.\n */\nexport function producerOutputObtainedBy(\n producer: FlowNode,\n snapshot: NodeExecutionSnapshot | undefined,\n): \"agent\" | \"runtime\" {\n // A subprompt's output is model-generated the same as an agent's, even though\n // the runtime (not the session agent) makes the call — so a downstream check\n // must derive \"asserted\", never \"verified\", over it. See engine/check-provenance.ts.\n // A sub-flow returns what any node inside the child produced, agents included;\n // its inputOrigins cover only what the parent passed in, so they cannot clear it.\n if (isAgentNode(producer) || isSubpromptNode(producer) || isSubFlowNode(producer)) {\n return \"agent\";\n }\n const inputOrigins = snapshot?.inputOrigins;\n if (!inputOrigins) return \"agent\";\n const tainted = Object.values(inputOrigins).some((origins) =>\n // A hydrated snapshot is host-supplied and only shape-checked as JSON, so a\n // malformed entry is unreadable rather than clean — fail closed, never throw.\n Array.isArray(origins) ? origins.some((origin) => origin?.obtainedBy === \"agent\") : true,\n );\n return tainted ? \"agent\" : \"runtime\";\n}\n\n/** Resolve one node's named inputs and derive their runtime/agent origins. */\nexport function resolveNodeBindings(\n flow: FlowDefinition,\n node: FlowNode,\n snapshots: Map<string, NodeExecutionSnapshot>,\n flowInputOrigins: Record<string, BindingOrigin[]> = {},\n): ResolvedNodeBindings {\n const origins = Object.fromEntries(\n flow.nodes.map((producer) => [\n producer.id,\n producerOutputObtainedBy(producer, snapshots.get(producer.id)),\n ]),\n ) as Record<string, \"agent\" | \"runtime\">;\n return resolveFlowBindings(\n nodeBindings(node),\n buildFlowExpressionContext(flow, snapshots),\n origins,\n flowInputOrigins,\n );\n}\n\n/** Interpolate named, already-resolved binding values into an agent instruction. */\nexport function interpolateNodeInstruction(\n instruction: string,\n values: Record<string, unknown>,\n): string {\n return instruction.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_-]*)\\}/g, (_placeholder, name: string) => {\n if (!Object.hasOwn(values, name)) {\n throw new Error(`Node instruction binding ${name} is missing`);\n }\n const value = values[name];\n return typeof value === \"string\" ? value : stableFlowJson(value);\n });\n}\n","import type { NodeOutput } from \"@skaile/workspaces/types\";\nimport { evaluateFlowExpression, FlowExpressionError } from \"../contract/expression.js\";\nimport { buildFlowExpressionContext } from \"./bindings.js\";\nimport { isRouterNode } from \"./node-shape.js\";\nimport type { FlowDefinition, FlowNode, NodeExecutionSnapshot } from \"./types.js\";\n\nconst ROUTER_SELECTION_MARKER = \"\\n\\n[skaile:flow-router-selection:\";\n\n/** One deterministic router choice being settled in the current atomic batch. */\nexport interface RouterSettlement {\n routerNodeId: string;\n selectedTarget: string | null;\n}\n\n/**\n * Internal result of evaluating one already-admitted router. `failed` carries a\n * route expression error that no later stimulus can clear (a missing field on a\n * terminal producer, non-comparable operands): the router is decided, and what\n * it decided is to fail.\n */\nexport type RouterSelection =\n | { selectedTarget: string | null }\n | { unresolved: \"not-ready\" | \"no-match\" }\n | { failed: FlowExpressionError };\n\nfunction pendingProducerOutput(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n missingPath: string | undefined,\n): boolean {\n if (!missingPath) return false;\n const segments = missingPath.split(\".\");\n if (\n segments.length < 5 ||\n segments[0] !== \"nodes\" ||\n segments[2] !== \"output\" ||\n segments[3] !== \"fields\"\n ) {\n return false;\n }\n const producer = flow.nodes.find(({ id }) => id === segments[1]);\n if (!producer?.contract?.output?.fields) return false;\n // Only a producer that can still produce is worth waiting for — a terminal\n // one never will, and calling it \"pending\" parks the router forever.\n return ![\"complete\", \"skipped\", \"failed\"].includes(\n snapshots.get(producer.id)?.status ?? \"not_started\",\n );\n}\n\n/** Evaluate ordered routes for a router whose availability was already established. */\nexport function evaluateRouterSelection(\n flow: FlowDefinition,\n router: FlowNode,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterSelection {\n if (!isRouterNode(router)) return { unresolved: \"no-match\" };\n const context = buildFlowExpressionContext(flow, snapshots);\n for (const route of router.run.routes) {\n try {\n if (evaluateFlowExpression(route.when, context)) {\n return { selectedTarget: route.target };\n }\n } catch (error) {\n if (\n error instanceof FlowExpressionError &&\n pendingProducerOutput(flow, snapshots, error.missingPath)\n ) {\n return { unresolved: \"not-ready\" };\n }\n // Rethrowing here escaped the whole drain and wedged the run: the router\n // stayed available and threw again on every later stimulus.\n if (error instanceof FlowExpressionError) return { failed: error };\n throw error;\n }\n }\n return { unresolved: \"no-match\" };\n}\n\n/** Encode a router choice in the existing durable node-output envelope. */\nexport function routerSelectionOutput(selectedTarget: string | null): NodeOutput {\n const summary =\n selectedTarget === null\n ? \"Router completed without selecting a target.\"\n : `Router selected ${selectedTarget}.`;\n return {\n summary: `${summary}${ROUTER_SELECTION_MARKER}${JSON.stringify(selectedTarget)}]`,\n artifacts: [],\n };\n}\n\nfunction routeTargets(router: FlowNode): string[] {\n if (!isRouterNode(router)) return [];\n return [...new Set(router.run.routes.flatMap(({ target }) => (target === null ? [] : [target])))];\n}\n\ninterface RouterOwnershipIndex {\n routers: FlowNode[];\n outgoing: Map<string, string[]>;\n}\n\n/** Index router-to-router ownership through route targets and hard-flow descendants. */\nfunction routerOwnershipIndex(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterOwnershipIndex {\n const routers = flow.nodes.filter(\n (node) =>\n isRouterNode(node) &&\n ![\"complete\", \"failed\", \"skipped\"].includes(snapshots.get(node.id)?.status ?? \"not_started\"),\n );\n const routerIds = new Set(routers.map(({ id }) => id));\n const hardOutgoing = new Map<string, string[]>();\n for (const edge of flow.edges) {\n if (edge.type !== \"flow\") continue;\n const targets = hardOutgoing.get(edge.source) ?? [];\n targets.push(edge.target);\n hardOutgoing.set(edge.source, targets);\n }\n\n const outgoing = new Map<string, string[]>();\n for (const router of routers) {\n const owned = new Set<string>();\n const visited = new Set<string>();\n const queue = routeTargets(router);\n for (let index = 0; index < queue.length; index++) {\n const nodeId = queue[index];\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n if (routerIds.has(nodeId)) owned.add(nodeId);\n queue.push(...(hardOutgoing.get(nodeId) ?? []));\n }\n outgoing.set(router.id, [...owned]);\n }\n return { routers, outgoing };\n}\n\n/**\n * Return every member of each source router-ownership SCC.\n *\n * Route ownership is deliberately not a dependency arc and may cycle even though hard flow is\n * acyclic. Source SCC members are ungated so normal hard-edge/precondition admission and ordered\n * decidability select the settlement frontier. Ordinary parent components remain ahead of nested\n * children, while self-targeting and mutually targeting routers cannot deadlock admission. The\n * graph is preindexed and both SCC passes are iterative.\n */\nfunction routerOwnershipSourceComponents(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): string[][] {\n const { routers, outgoing } = routerOwnershipIndex(flow, snapshots);\n const reverse = new Map<string, string[]>();\n for (const router of routers) reverse.set(router.id, []);\n for (const [source, targets] of outgoing) {\n for (const target of targets) reverse.get(target)?.push(source);\n }\n\n const visited = new Set<string>();\n const finished: string[] = [];\n for (const router of routers) {\n if (visited.has(router.id)) continue;\n const stack: Array<{ nodeId: string; exiting: boolean }> = [\n { nodeId: router.id, exiting: false },\n ];\n while (stack.length > 0) {\n const frame = stack.pop();\n if (!frame) break;\n if (frame.exiting) {\n finished.push(frame.nodeId);\n continue;\n }\n if (visited.has(frame.nodeId)) continue;\n visited.add(frame.nodeId);\n stack.push({ nodeId: frame.nodeId, exiting: true });\n const targets = outgoing.get(frame.nodeId) ?? [];\n for (let index = targets.length - 1; index >= 0; index--) {\n if (!visited.has(targets[index])) {\n stack.push({ nodeId: targets[index], exiting: false });\n }\n }\n }\n }\n\n const componentByRouter = new Map<string, number>();\n const components: string[][] = [];\n for (let index = finished.length - 1; index >= 0; index--) {\n const start = finished[index];\n if (componentByRouter.has(start)) continue;\n const componentId = components.length;\n const component: string[] = [];\n const stack = [start];\n componentByRouter.set(start, componentId);\n while (stack.length > 0) {\n const nodeId = stack.pop();\n if (!nodeId) break;\n component.push(nodeId);\n for (const source of reverse.get(nodeId) ?? []) {\n if (componentByRouter.has(source)) continue;\n componentByRouter.set(source, componentId);\n stack.push(source);\n }\n }\n components.push(component);\n }\n\n const incomingComponents = new Set<number>();\n for (const [source, targets] of outgoing) {\n const sourceComponent = componentByRouter.get(source);\n for (const target of targets) {\n const targetComponent = componentByRouter.get(target);\n if (\n sourceComponent !== undefined &&\n targetComponent !== undefined &&\n sourceComponent !== targetComponent\n ) {\n incomingComponents.add(targetComponent);\n }\n }\n }\n\n const definitionOrder = new Map(flow.nodes.map((node, index) => [node.id, index]));\n const sourceComponents = components.filter(\n (_, componentId) => !incomingComponents.has(componentId),\n );\n for (const component of sourceComponents) {\n component.sort(\n (left, right) =>\n (definitionOrder.get(left) ?? Number.MAX_SAFE_INTEGER) -\n (definitionOrder.get(right) ?? Number.MAX_SAFE_INTEGER),\n );\n }\n return sourceComponents.sort(\n (left, right) =>\n (definitionOrder.get(left[0]) ?? Number.MAX_SAFE_INTEGER) -\n (definitionOrder.get(right[0]) ?? Number.MAX_SAFE_INTEGER),\n );\n}\n\n/** Decode and validate a completed router's engine-owned selection summary. */\nexport function persistedRouterSelection(\n router: FlowNode,\n snapshot: NodeExecutionSnapshot | undefined,\n): { selectedTarget: string | null } | undefined {\n if (!isRouterNode(router) || snapshot?.status !== \"complete\") return undefined;\n const summary = snapshot.output?.summary;\n const markerIndex = summary?.lastIndexOf(ROUTER_SELECTION_MARKER) ?? -1;\n if (!summary || markerIndex < 0 || !summary.endsWith(\"]\")) return undefined;\n let selectedTarget: unknown;\n try {\n selectedTarget = JSON.parse(summary.slice(markerIndex + ROUTER_SELECTION_MARKER.length, -1));\n } catch {\n return undefined;\n }\n if (\n selectedTarget !== null &&\n (typeof selectedTarget !== \"string\" || !routeTargets(router).includes(selectedTarget))\n ) {\n return undefined;\n }\n if (selectedTarget === null && !router.run.routes.some(({ target }) => target === null)) {\n return undefined;\n }\n return summary === routerSelectionOutput(selectedTarget).summary ? { selectedTarget } : undefined;\n}\n\nfunction edgeKey(source: string, target: string): string {\n return `${source}\\u0000${target}`;\n}\n\n/**\n * Plan exclusive branch skips for all known router choices as one coordinated settlement.\n *\n * Only hard `flow` edges participate. The graph is indexed once, then each distinct losing\n * target performs a linear adjacency walk; optional and parallel edges can neither spread nor\n * preserve exclusivity. A selected route, a still-live unsettled router, shared convergence, or\n * an incoming hard predecessor outside the losing region protects that node and its descendants.\n * Protection never crosses a losing route edge, so a settled router nested in a protected branch\n * still skips its own losing targets.\n */\nexport function planRouterSkips(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n settlements: readonly RouterSettlement[],\n): string[] {\n const routers = flow.nodes.filter(isRouterNode);\n const currentSelections = new Map(\n settlements.map(({ routerNodeId, selectedTarget }) => [routerNodeId, selectedTarget]),\n );\n const knownSelections = new Map<string, string | null>();\n for (const router of routers) {\n if (currentSelections.has(router.id)) {\n knownSelections.set(router.id, currentSelections.get(router.id) ?? null);\n continue;\n }\n const persisted = persistedRouterSelection(router, snapshots.get(router.id));\n if (persisted) knownSelections.set(router.id, persisted.selectedTarget);\n }\n\n const outgoing = new Map<string, string[]>();\n const incoming = new Map<string, string[]>();\n for (const edge of flow.edges) {\n if (edge.type !== \"flow\") continue;\n const targets = outgoing.get(edge.source) ?? [];\n targets.push(edge.target);\n outgoing.set(edge.source, targets);\n const sources = incoming.get(edge.target) ?? [];\n sources.push(edge.source);\n incoming.set(edge.target, sources);\n }\n\n const losingRoots = new Set<string>();\n const selectedRoots = new Set<string>();\n const losingRouteEdges = new Set<string>();\n for (const router of routers) {\n if (!knownSelections.has(router.id)) continue;\n const selectedTarget = knownSelections.get(router.id) ?? null;\n if (selectedTarget !== null) selectedRoots.add(selectedTarget);\n for (const target of routeTargets(router)) {\n if (target === selectedTarget) continue;\n losingRoots.add(target);\n losingRouteEdges.add(edgeKey(router.id, target));\n }\n }\n\n const regions = new Map<string, Set<string>>();\n for (const root of losingRoots) {\n const visited = new Set<string>();\n const queue = [root];\n for (let index = 0; index < queue.length; index++) {\n const nodeId = queue[index];\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n for (const target of outgoing.get(nodeId) ?? []) queue.push(target);\n }\n regions.set(root, visited);\n }\n // A losing root inside another losing root's region (the targets of a router that is\n // itself being skipped) is part of that branch, not a second origin of a shared join.\n const regionEntries = [...regions];\n const nestedRoots = new Set(\n [...losingRoots].filter((root) =>\n regionEntries.some(([other, region]) => other !== root && region.has(root)),\n ),\n );\n const candidateOrigins = new Map<string, Set<string>>();\n for (const [root, region] of regions) {\n for (const nodeId of region) {\n const origins = candidateOrigins.get(nodeId) ?? new Set<string>();\n if (!nestedRoots.has(root)) origins.add(root);\n candidateOrigins.set(nodeId, origins);\n }\n }\n const candidates = new Set(candidateOrigins.keys());\n\n const protectionQueue = [...selectedRoots];\n for (const [nodeId, origins] of candidateOrigins) {\n if (origins.size >= 2) protectionQueue.push(nodeId);\n for (const source of incoming.get(nodeId) ?? []) {\n if (candidates.has(source)) continue;\n if (losingRouteEdges.has(edgeKey(source, nodeId))) continue;\n if ([\"failed\", \"skipped\"].includes(snapshots.get(source)?.status ?? \"not_started\")) continue;\n protectionQueue.push(nodeId);\n break;\n }\n }\n\n const unknownSelections = new Map<string, string[]>();\n for (const router of routers) {\n if (knownSelections.has(router.id)) continue;\n const status = snapshots.get(router.id)?.status ?? \"not_started\";\n if (status === \"failed\" || status === \"skipped\") continue;\n const targets = routeTargets(router);\n unknownSelections.set(router.id, targets);\n if (!candidates.has(router.id)) protectionQueue.push(...targets);\n }\n\n const protectedNodes = new Set<string>();\n for (let index = 0; index < protectionQueue.length; index++) {\n const nodeId = protectionQueue[index];\n if (protectedNodes.has(nodeId)) continue;\n protectedNodes.add(nodeId);\n // A settled router inside a protected branch protects only its selected route.\n for (const target of outgoing.get(nodeId) ?? []) {\n if (!losingRouteEdges.has(edgeKey(nodeId, target))) protectionQueue.push(target);\n }\n protectionQueue.push(...(unknownSelections.get(nodeId) ?? []));\n }\n\n return flow.nodes.flatMap((node) =>\n candidates.has(node.id) && !protectedNodes.has(node.id) ? [node.id] : [],\n );\n}\n\n/**\n * Return every possible target branch gated by an unsettled router.\n *\n * Gating follows hard `flow` descendants only. A selected route, shared convergence, or another\n * live hard predecessor protects a node, matching settlement pruning without mutating snapshots.\n */\nexport function unsettledRouterBranchIds(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): Set<string> {\n const unsettled = flow.nodes.filter(\n (node) =>\n isRouterNode(node) &&\n ![\"complete\", \"failed\", \"skipped\"].includes(snapshots.get(node.id)?.status ?? \"not_started\"),\n );\n const branches = new Set(\n planRouterSkips(\n flow,\n snapshots,\n unsettled.map(({ id }) => ({ routerNodeId: id, selectedTarget: null })),\n ),\n );\n for (const component of routerOwnershipSourceComponents(flow, snapshots)) {\n for (const routerId of component) branches.delete(routerId);\n }\n return branches;\n}\n\n/**\n * Return one actually available, decidable router per source ownership component.\n *\n * Every source-component member remains ungated for normal admission. Within a settlement wave,\n * definition order chooses the first member that is both available and decidable; unresolved or\n * blocked peers cannot starve it. Limiting each component to one choice prevents a router from\n * completing atomically after that same wave makes its branch losing. Independent source\n * components can still settle together.\n */\nexport function availableRouterFrontier(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowNode[] {\n const nodesById = new Map(flow.nodes.map((node) => [node.id, node]));\n return routerOwnershipSourceComponents(flow, snapshots).flatMap((component) => {\n for (const routerId of component) {\n const node = nodesById.get(routerId);\n if (!node || snapshots.get(routerId)?.status !== \"available\") continue;\n if (\"unresolved\" in evaluateRouterSelection(flow, node, snapshots)) continue;\n return [node];\n }\n return [];\n });\n}\n","import type {\n FlowDefinition,\n FlowEdge,\n FlowNode,\n FlowState,\n NodeExecutionSnapshot,\n NodePreconditionFailure,\n NodeState,\n NodeStatus,\n} from \"./types.js\";\nimport { evaluateFlowExpression, type FlowExpressionContext } from \"../contract/expression.js\";\nimport { buildFlowExpressionContext } from \"./bindings.js\";\nimport {\n isActiveRuntimeNode,\n isRouterNode,\n nodeIsOptional,\n nodeLabel,\n nodeSkillId,\n} from \"./node-shape.js\";\nimport {\n evaluateRouterSelection,\n planRouterSkips,\n unsettledRouterBranchIds,\n} from \"./router-settlement.js\";\n\n// ---------------------------------------------------------------------------\n// Core engine — stateless, pure functions\n// ---------------------------------------------------------------------------\n\n/** Return nodes with state owned by the current runtime. */\nfunction activeRuntimeNodes(flow: FlowDefinition): FlowNode[] {\n return flow.nodes.filter(isActiveRuntimeNode);\n}\n\n/** Evaluate every authored admission condition without mutating runtime state. */\nfunction failedPreconditions(\n node: FlowNode,\n context: FlowExpressionContext,\n): NodePreconditionFailure[] {\n const failures: NodePreconditionFailure[] = [];\n for (const requirement of node.contract?.requires ?? []) {\n const message = requirement.message ?? `Precondition failed: ${requirement.expr}`;\n try {\n if (!evaluateFlowExpression(requirement.expr, context)) {\n failures.push({ expression: requirement.expr, message, reason: \"false\" });\n }\n } catch (error) {\n failures.push({\n expression: requirement.expr,\n message,\n reason: \"error\",\n detail: error instanceof Error ? error.message : \"Flow expression evaluation failed\",\n });\n }\n }\n return failures;\n}\n\n/** Build adjacency: target → sources[] (incoming edges per node) */\nfunction buildIncoming(edges: FlowEdge[]): Map<string, FlowEdge[]> {\n const map = new Map<string, FlowEdge[]>();\n for (const edge of edges) {\n if (!map.has(edge.target)) map.set(edge.target, []);\n map.get(edge.target)!.push(edge);\n }\n return map;\n}\n\n/** Build adjacency: source → targets[] (outgoing edges per node) */\nfunction buildOutgoing(edges: FlowEdge[]): Map<string, FlowEdge[]> {\n const map = new Map<string, FlowEdge[]>();\n for (const edge of edges) {\n if (!map.has(edge.source)) map.set(edge.source, []);\n map.get(edge.source)!.push(edge);\n }\n return map;\n}\n\n/** Result of resolving one available router against the current expression context. */\nexport interface RouterResolution {\n /** First matching route target. `null` means every branch loses. */\n selectedTarget: string | null;\n /** Exclusive nodes belonging only to unselected route targets, in definition order. */\n skippedNodeIds: string[];\n}\n\n/** Available router that cannot make a deterministic choice from the current snapshot. */\nexport interface UnresolvedRouterResolution {\n /** Why the router remains available for a later drain pass. */\n unresolved: \"not-ready\" | \"no-match\";\n}\n\n/**\n * Resolve the first matching route for a router that is currently available.\n *\n * Route conditions use the same bounded context as node preconditions and bindings. Resolution\n * is deliberately separate from state computation: unavailable routers return `undefined`\n * without evaluating any route. Losing route targets and their exclusive downstream paths are\n * returned for the caller to mark skipped. Exclusivity follows hard `flow` edges only and keeps\n * selected routes, unsettled-router targets, shared convergence, and externally reachable nodes\n * live. A declared producer output that is not complete yet returns a retryable unresolved result;\n * malformed expressions still throw their path-bearing evaluator error.\n *\n * @param flow - Parsed flow containing the router and branch graph.\n * @param routerNodeId - Router execution identity.\n * @param snapshots - Current node snapshots used for admission and expression values.\n * @returns The selected target and losing nodes, an unresolved reason while available but not\n * decidable, or `undefined` while the router is unavailable.\n */\nexport function resolveAvailableRouter(\n flow: FlowDefinition,\n routerNodeId: string,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterResolution | UnresolvedRouterResolution | undefined {\n const router = flow.nodes.find((node) => node.id === routerNodeId);\n if (!router || !isRouterNode(router)) return undefined;\n const state = computeFlowStateFromSnapshots(flow, snapshots);\n if (!state.available.includes(routerNodeId)) return undefined;\n\n const selected = evaluateRouterSelection(flow, router, snapshots);\n if (\"unresolved\" in selected) return selected;\n if (\"failed\" in selected) throw selected.failed;\n\n return {\n selectedTarget: selected.selectedTarget,\n skippedNodeIds: planRouterSkips(flow, snapshots, [\n { routerNodeId, selectedTarget: selected.selectedTarget },\n ]),\n };\n}\n\n/**\n * Compute the full {@link FlowState} from a flow definition and caller-supplied node ID sets.\n *\n * This is the primary engine function. It is stateless and side-effect-free — calling it\n * twice with the same arguments always returns an equivalent result.\n *\n * Edge semantics applied during computation:\n * - `'flow'` — hard dependency: target cannot start until source is `complete` or `skipped`.\n * - `'parallel'` — soft dependency: target may run while source is still running.\n * - `'optional'` — advisory: target can start regardless of source state.\n *\n * A node is `available` when every incoming `'flow'`-type edge has a complete or skipped source\n * and every authored precondition evaluates true.\n * A node is `not_started` when at least one hard predecessor is still pending.\n * The flow is `done` when every non-optional node is `complete` or `skipped`.\n *\n * This set-based overload has statuses but no completed output fields. Use\n * {@link computeFlowStateFromSnapshots} when a precondition reads node output.\n *\n * Prefer {@link computeFlowStateFromSnapshots} for callers that track full `NodeExecution`\n * state (interaction statuses such as `awaiting_approval`, `awaiting_input`, `failed`).\n *\n * @param flow - The parsed flow definition.\n * @param completedIds - Set of node IDs that have finished successfully.\n * @param runningIds - Set of node IDs currently executing. Defaults to an empty set.\n * @param skippedIds - Set of node IDs that were explicitly skipped. Skipped nodes count\n * as satisfied for downstream dependency checks. Defaults to an empty set.\n * @returns A {@link FlowState} describing every active runtime node.\n * @docLink packages/flow-engine/concepts#compute-flow-state\n */\nexport function computeFlowState(\n flow: FlowDefinition,\n completedIds: Set<string>,\n runningIds: Set<string> = new Set(),\n skippedIds: Set<string> = new Set(),\n): FlowState {\n const nodes = activeRuntimeNodes(flow);\n const incoming = buildIncoming(flow.edges);\n const snapshots = new Map<string, NodeExecutionSnapshot>();\n for (const node of nodes) {\n const status: NodeStatus = completedIds.has(node.id)\n ? \"complete\"\n : runningIds.has(node.id)\n ? \"running\"\n : skippedIds.has(node.id)\n ? \"skipped\"\n : \"not_started\";\n snapshots.set(node.id, { status });\n }\n const gatedBranches = unsettledRouterBranchIds(flow, snapshots);\n const context = buildFlowExpressionContext(flow, snapshots);\n\n const nodeStates: NodeState[] = nodes.map((node) => {\n const optional = nodeIsOptional(node);\n const skillId = nodeSkillId(node);\n const label = nodeLabel(node);\n\n if (completedIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"complete\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n if (runningIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"running\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n if (skippedIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"skipped\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n\n if (gatedBranches.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"not_started\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n\n const edges = incoming.get(node.id) ?? [];\n\n // Hard blockers: flow-type edges whose source is neither complete nor skipped\n const hardBlockers = edges\n .filter((e) => e.type === \"flow\")\n .filter((e) => !completedIds.has(e.source) && !skippedIds.has(e.source))\n .map((e) => e.source);\n\n const preconditionFailures = failedPreconditions(node, context);\n const canRun = hardBlockers.length === 0 && preconditionFailures.length === 0;\n\n let status: NodeStatus;\n if (!canRun) {\n status = \"not_started\";\n } else {\n status = \"available\";\n }\n\n return {\n nodeId: node.id,\n skillId,\n label,\n status,\n optional,\n canRun,\n blockers: hardBlockers,\n failedPreconditions: preconditionFailures,\n };\n });\n\n const _stateMap = new Map(nodeStates.map((s) => [s.nodeId, s]));\n\n const available = nodeStates.filter((s) => s.status === \"available\").map((s) => s.nodeId);\n const completed = nodeStates.filter((s) => s.status === \"complete\").map((s) => s.nodeId);\n const focus = nodeStates\n .filter(\n (s) =>\n s.status === \"running\" || s.status === \"awaiting_approval\" || s.status === \"awaiting_input\",\n )\n .map((s) => s.nodeId);\n\n // Flow is done when all required nodes are complete or skipped\n const requiredNodes = nodes.filter((n) => !nodeIsOptional(n));\n const done = requiredNodes.every((n) => completedIds.has(n.id) || skippedIds.has(n.id));\n\n return { flowId: flow.id, nodes: nodeStates, available, completed, focus, done };\n}\n\n/**\n * Snapshot-based variant of {@link computeFlowState}.\n *\n * Accepts a map of `NodeExecutionSnapshot` values carrying the current status and\n * interaction metadata for every node the caller knows about. Nodes absent from the\n * map are treated as `not_started`.\n *\n * This is the preferred API for the turn-based runner, which has a full `FlowExecution`\n * and needs to convey richer statuses (`awaiting_approval`, `awaiting_input`, `failed`)\n * back to the engine so downstream availability is computed correctly.\n *\n * Engine semantics:\n * - A node is `available` when all its incoming `'flow'`-type predecessors are `complete`\n * or `skipped`. Any other upstream status — including `awaiting_approval`,\n * `awaiting_input`, and `failed` — is treated as blocking. Every authored precondition\n * must also evaluate true against the snapshot expression context.\n * - Optionality is **not** a term here: `failed` blocks whether or not the node is optional.\n * An optional node's dependents proceed because an optional node never reaches a terminal\n * `failed` in the first place — its exhausted failure resolves to `skipped`\n * (`resolveTerminalFailureStatus`), which passes. The one exception is a router, which\n * stays `failed` even when optional.\n * - The flow is `done` when every non-optional node is `complete` or `skipped`. A single\n * required node stuck in `failed` keeps `done` false.\n *\n * @param flow - The parsed flow definition.\n * @param snapshots - Map from node ID to its current {@link NodeExecutionSnapshot}.\n * Missing entries default to `not_started` with no interaction metadata.\n * @returns A {@link FlowState} describing every active runtime node,\n * including interaction fields (`approval`, `input`, `output`, `error`) copied\n * from the matching snapshot.\n * @docLink packages/flow-engine/concepts#compute-flow-state-from-snapshots\n */\nexport function computeFlowStateFromSnapshots(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowState {\n const nodes = activeRuntimeNodes(flow);\n const incoming = buildIncoming(flow.edges);\n const gatedBranches = unsettledRouterBranchIds(flow, snapshots);\n const context = buildFlowExpressionContext(flow, snapshots);\n\n /** Resolve the effective status for a node — defaulting to `not_started`. */\n const statusFor = (nodeId: string): NodeStatus => snapshots.get(nodeId)?.status ?? \"not_started\";\n\n /** A predecessor \"passes\" when it is complete or skipped. */\n const passed = (nodeId: string): boolean => {\n const s = statusFor(nodeId);\n return s === \"complete\" || s === \"skipped\";\n };\n\n const nodeStates: NodeState[] = nodes.map((node) => {\n const snapshot = snapshots.get(node.id);\n const optional = nodeIsOptional(node);\n const skillId = nodeSkillId(node);\n const label = nodeLabel(node);\n const status = snapshot?.status ?? \"not_started\";\n\n const edges = incoming.get(node.id) ?? [];\n const flowPreds = edges.filter((e) => e.type === \"flow\");\n const hardBlockers = flowPreds.filter((e) => !passed(e.source)).map((e) => e.source);\n\n const isAdmissionState = status === \"not_started\" || status === \"available\";\n const preconditionFailures = isAdmissionState ? failedPreconditions(node, context) : [];\n\n // Recompute admission in both directions after fresh start or hydrate.\n let effectiveStatus: NodeStatus = status;\n if (isAdmissionState && gatedBranches.has(node.id)) {\n effectiveStatus = \"not_started\";\n } else if (isAdmissionState) {\n effectiveStatus =\n hardBlockers.length === 0 && preconditionFailures.length === 0\n ? \"available\"\n : \"not_started\";\n }\n\n return {\n nodeId: node.id,\n skillId,\n label,\n status: effectiveStatus,\n optional,\n canRun:\n hardBlockers.length === 0 &&\n preconditionFailures.length === 0 &&\n effectiveStatus === \"available\",\n blockers: hardBlockers,\n failedPreconditions: preconditionFailures,\n approval: snapshot?.approval,\n input: snapshot?.input,\n output: snapshot?.output,\n error: snapshot?.error,\n };\n });\n\n const available = nodeStates.filter((s) => s.status === \"available\").map((s) => s.nodeId);\n const completed = nodeStates.filter((s) => s.status === \"complete\").map((s) => s.nodeId);\n const focus = nodeStates\n .filter(\n (s) =>\n s.status === \"running\" || s.status === \"awaiting_approval\" || s.status === \"awaiting_input\",\n )\n .map((s) => s.nodeId);\n\n const requiredNodes = nodes.filter((n) => !nodeIsOptional(n));\n const done = requiredNodes.every((n) => {\n const s = statusFor(n.id);\n return s === \"complete\" || s === \"skipped\";\n });\n\n return { flowId: flow.id, nodes: nodeStates, available, completed, focus, done };\n}\n\n/**\n * Returns `true` when the given status prevents downstream nodes from starting.\n *\n * Only `'complete'` and `'skipped'` satisfy a hard (`'flow'`-type) edge dependency.\n * All other statuses — including `'awaiting_approval'`, `'awaiting_input'`, and\n * `'failed'` — are considered blocking.\n *\n * Use this helper in the FlowAdapter and the turn-based orchestrator instead of\n * hard-coding the two-value whitelist inline.\n *\n * @param status - The {@link NodeStatus} to evaluate.\n * @returns `true` if the status prevents dependents from becoming `available`.\n * @docLink packages/flow-engine/concepts#is-blocking\n */\nexport function isBlocking(status: NodeStatus): boolean {\n return status !== \"complete\" && status !== \"skipped\";\n}\n\n/**\n * Returns the IDs of nodes that become newly `available` after a specific node completes.\n *\n * More efficient than recomputing the full {@link FlowState} when only the downstream\n * impact of a single completion is needed. Only the direct successors of `justCompleted`\n * are evaluated — the rest of the graph is untouched.\n *\n * @param flow - The parsed flow definition.\n * @param justCompleted - ID of the node that just finished (will be added to the\n * effective completed set before evaluating successors).\n * @param completedIds - Set of node IDs already known to be complete before this call.\n * @param skippedIds - Set of node IDs that were explicitly skipped. Defaults to an empty set.\n * @returns Array of node IDs whose hard dependencies are now fully satisfied and that\n * were not already available before `justCompleted` finished. Unlike executable-node-filtered\n * helpers, this walks raw edge targets and does not filter by node type — if a `group`,\n * `sub-flow`, or `router` node is a direct successor, its ID can appear here. Callers that\n * dispatch these IDs are responsible for filtering inert nodes.\n * @docLink packages/flow-engine/concepts#resolve-next-nodes\n */\nexport function resolveNextNodes(\n flow: FlowDefinition,\n justCompleted: string,\n completedIds: Set<string>,\n skippedIds: Set<string> = new Set(),\n): string[] {\n const outgoing = buildOutgoing(flow.edges);\n const incoming = buildIncoming(flow.edges);\n const candidates = (outgoing.get(justCompleted) ?? []).map((e) => e.target);\n\n const nextCompleted = new Set([...completedIds, justCompleted]);\n const result: string[] = [];\n\n for (const candidateId of candidates) {\n const edges = incoming.get(candidateId) ?? [];\n const hardBlockers = edges\n .filter((e) => e.type === \"flow\")\n .filter((e) => !nextCompleted.has(e.source) && !skippedIds.has(e.source));\n if (hardBlockers.length === 0) {\n result.push(candidateId);\n }\n }\n\n return result;\n}\n\n/**\n * Returns the IDs of optional nodes that have not yet started and can be safely skipped.\n *\n * A node is skippable when it is:\n * 1. Not yet complete (absent from `completedIds`).\n * 2. Marked `optional` (`FlowNode.data.optional === true`).\n * 3. Not connected via a `'flow'`-type edge to any non-optional downstream node\n * (i.e. skipping it cannot starve a required node of a hard dependency).\n *\n * The runner may call this to present the user with a list of nodes they can bypass\n * without breaking the flow's required path.\n *\n * @param flow - The parsed flow definition.\n * @param completedIds - Set of node IDs that have already completed (excluded from results).\n * @returns Array of node IDs that are safe to skip at this point in the execution.\n * @docLink packages/flow-engine/concepts#compute-skippable\n */\nexport function computeSkippable(flow: FlowDefinition, completedIds: Set<string>): string[] {\n const nodes = activeRuntimeNodes(flow);\n const outgoing = buildOutgoing(flow.edges);\n\n return nodes\n .filter((n) => !completedIds.has(n.id))\n .filter(nodeIsOptional)\n .filter((n) => {\n // A node is skippable if none of its outgoing flow-type edges go to a required node\n const deps = (outgoing.get(n.id) ?? []).filter((e) => e.type === \"flow\");\n return deps.every((e) => {\n const target = flow.nodes.find((t) => t.id === e.target);\n return target ? nodeIsOptional(target) : false;\n });\n })\n .map((n) => n.id);\n}\n","import { compileOutputFieldsSchema, getConsumedOutputSchema } from \"../contract/output-fields.js\";\nimport type { FlowDefinition } from \"./types.js\";\n\nexport { getConsumedOutputSchema };\n\n/** Result of validating fields at a producer's consumed-output boundary. */\nexport interface NodeOutputValidationResult {\n /** Whether the fields may be exposed to downstream consumers. */\n valid: boolean;\n /** Stable, path-bearing failures. Empty when validation is not required. */\n issues: string[];\n}\n\n/**\n * Validate proposed fields only when a downstream deterministic consumer requires them.\n *\n * `parseFlowDefinition` already refuses a consumed `output.fields` schema that does not\n * compile, so compiling it here cannot fail for a parsed flow.\n */\nexport function validateConsumedNodeOutput(\n flow: FlowDefinition,\n producerId: string,\n fields: Record<string, unknown> | undefined,\n): NodeOutputValidationResult {\n const schema = getConsumedOutputSchema(flow, producerId);\n if (!schema) return { valid: true, issues: [] };\n\n const parsed = compileOutputFieldsSchema(schema).safeParse(fields ?? {});\n if (parsed.success) return { valid: true, issues: [] };\n return {\n valid: false,\n issues: parsed.error.issues\n .map((issue) => {\n const suffix = issue.path.map(String).join(\".\");\n return `fields${suffix ? `.${suffix}` : \"\"}: ${issue.message}`;\n })\n .sort(),\n };\n}\n","import { FlowExpressionError, resolveFlowBindings } from \"../contract/expression.js\";\nimport { compileOutputFieldsSchema } from \"../contract/output-fields.js\";\nimport { buildFlowExpressionContext, producerOutputObtainedBy } from \"./bindings.js\";\nimport type { FlowDefinition, NodeExecutionSnapshot } from \"./types.js\";\n\n/**\n * Resolve what a completed flow returns to a parent sub-flow node.\n *\n * `undefined` when the flow declares no `output.bindings`: it returns nothing.\n * Otherwise each binding resolves like a node input binding, and the result is\n * validated against `output.schema`, which `parseFlowDefinition` already refused to\n * accept uncompiled. Throws an error naming the field and the source node when a\n * binding source did not produce its value, or naming the flow when the values do\n * not match the schema.\n */\nexport function resolveFlowOutputFields(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): Record<string, unknown> | undefined {\n const output = flow.output;\n if (output?.bindings === undefined) return undefined;\n\n const context = buildFlowExpressionContext(flow, snapshots);\n // Origins are required by the resolver but discarded: the parent classifies\n // every returned field as agent-obtained, whatever produced it in here.\n const origins = Object.fromEntries(\n flow.nodes.map((node) => [node.id, producerOutputObtainedBy(node, snapshots.get(node.id))]),\n );\n const fields: Record<string, unknown> = {};\n for (const [name, binding] of Object.entries(output.bindings)) {\n try {\n fields[name] = resolveFlowBindings({ [name]: binding }, context, origins).values[name];\n } catch (error) {\n if (!(error instanceof FlowExpressionError) || error.missingPath === undefined) throw error;\n const producer = error.missingPath.startsWith(\"nodes.\")\n ? error.missingPath.split(\".\")[1]\n : undefined;\n const source = producer\n ? `node ${producer} did not produce ${error.missingPath}`\n : `${error.missingPath} is missing`;\n throw new Error(`Flow ${flow.id} output field ${name} has no value: ${source}`);\n }\n }\n\n const parsed = compileOutputFieldsSchema(output.schema).safeParse(fields);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((issue) => `${issue.path.map(String).join(\".\") || \"fields\"}: ${issue.message}`)\n .sort();\n throw new Error(`Flow ${flow.id} output does not match output.schema: ${issues.join(\"; \")}`);\n }\n return fields;\n}\n","/**\n * Pure derived-deadline arithmetic for `control.timeoutSec`.\n *\n * \"Active execution only\" is the scope every node-timeout ruling shares: the\n * clock runs from `startedAt` but stops counting while the node was parked\n * for a human decision. Rather than persist a separate \"paused\" duration,\n * this module recomputes the deadline on demand from `startedAt` plus the\n * already-durable `approvalHistory` / `inputHistory` — so it is correct\n * immediately after `hydrate()` or a reconnect with no extra wiring, and a\n * live timer is never the source of truth.\n *\n * @docLink packages/flow-engine/concepts#node-deadline\n */\n\nimport type { NodeExecution } from \"@skaile/workspaces/types\";\n\n/** Milliseconds spent parked in a resolved approval/input wait since `sinceMs`. */\nfunction pausedIntervalMs(execution: NodeExecution, sinceMs: number): number {\n let total = 0;\n for (const approval of execution.approvalHistory) {\n const startMs = Date.parse(approval.requestedAt);\n if (!Number.isFinite(startMs) || startMs < sinceMs) continue;\n if (!approval.decidedAt) continue; // still open — status wouldn't be \"running\" here\n const endMs = Date.parse(approval.decidedAt);\n if (Number.isFinite(endMs) && endMs > startMs) total += endMs - startMs;\n }\n for (const input of execution.inputHistory) {\n const startMs = Date.parse(input.requestedAt);\n if (!Number.isFinite(startMs) || startMs < sinceMs) continue;\n if (!input.providedAt) continue;\n const endMs = Date.parse(input.providedAt);\n if (Number.isFinite(endMs) && endMs > startMs) total += endMs - startMs;\n }\n return total;\n}\n\n/**\n * Milliseconds remaining before `execution`'s active-execution deadline, given\n * `timeoutSec`. Negative once the deadline has passed. `undefined` when no\n * timeout applies — `timeoutSec` is unset, or the node has no `startedAt` to\n * measure from (e.g. it hasn't actually started).\n *\n * Active time is wall-clock since `startedAt` minus every *resolved*\n * approval/input interval recorded at or after that `startedAt` (an\n * interval opened before a retry's fresh `startedAt` never counts against\n * the new attempt; a still-open interval never counts because the node\n * would not be `running` while parked).\n *\n * @param execution - Current node snapshot. Only `startedAt`, `approvalHistory`,\n * and `inputHistory` are read.\n * @param timeoutSec - Authored `control.timeoutSec`, or `undefined` for no timeout.\n * @param nowMs - Caller-supplied wall clock (`Date.now()` in production, injectable\n * for tests).\n * @docLink packages/flow-engine/concepts#remaining-active-execution-ms\n */\nexport function remainingActiveExecutionMs(\n execution: NodeExecution,\n timeoutSec: number | undefined,\n nowMs: number,\n): number | undefined {\n if (timeoutSec === undefined || !execution.startedAt) return undefined;\n const startedAtMs = Date.parse(execution.startedAt);\n if (!Number.isFinite(startedAtMs)) return undefined;\n const pausedMs = pausedIntervalMs(execution, startedAtMs);\n const deadlineMs = startedAtMs + timeoutSec * 1000 + pausedMs;\n return deadlineMs - nowMs;\n}\n\n/**\n * Whether `execution` has exceeded its derived active-execution deadline.\n * `false` when no timeout applies. Convenience wrapper over\n * {@link remainingActiveExecutionMs} for call sites that only need the\n * boolean.\n *\n * @docLink packages/flow-engine/concepts#is-active-execution-expired\n */\nexport function isActiveExecutionExpired(\n execution: NodeExecution,\n timeoutSec: number | undefined,\n nowMs: number,\n): boolean {\n const remaining = remainingActiveExecutionMs(execution, timeoutSec, nowMs);\n return remaining !== undefined && remaining <= 0;\n}\n","/**\n * Pure bookkeeping for `NodeExecution.outputHistory` and the bounded\n * automatic-retry budget derived from `control.retries`.\n *\n * `retries: N` means the first attempt plus N automatic retries — so an\n * automatic retry remains available while fewer than N attempts have\n * already failed. The budget is derived from `outputHistory` itself (a\n * count of prior `'failed'` entries) rather than a separate durable\n * counter, so it composes for free with hydration and needs no new field.\n *\n * The manual `retryNode` operator override never pushes an entry here (it\n * only flips `status` back to `available`). The agent's own\n * `doFailNode(recoverable: true)` self-retry DOES push an entry — every\n * actual start closes out an attempt — but marks it `selfRetry` so\n * `countFailedAttempts` excludes it: neither self-retry nor the manual\n * override consumes the automatic budget this module tracks.\n *\n * @docLink packages/flow-engine/concepts#node-attempts\n */\n\nimport type {\n CheckEvidence,\n NodeError,\n NodeExecutionAttempt,\n NodeOutput,\n} from \"@skaile/workspaces/types\";\n\n/** Next 1-based attempt number given the attempts already recorded. */\nexport function nextAttemptNumber(history: NodeExecutionAttempt[] | undefined): number {\n if (!history || history.length === 0) return 1;\n return Math.max(...history.map((entry) => entry.attempt)) + 1;\n}\n\n/** Rarely-set trailing facts about one appended attempt. */\nexport interface AppendAttemptOptions {\n /** True for the agent's own `doFailNode(recoverable: true)` self-retry: the\n * entry still records a genuine start-to-failure attempt, but is excluded\n * from {@link countFailedAttempts} so it never consumes the automatic\n * `control.retries` budget. */\n selfRetry?: boolean;\n /** Derived check evidence, when this attempt belongs to a `check` node that\n * actually produced a verdict (pass or fail). Omit for every other node\n * kind and for a check's infrastructure failure, which produced no verdict\n * to attach. */\n check?: CheckEvidence;\n}\n\n/**\n * Appends one terminal attempt to `history`, numbered `max(attempt) + 1`.\n * Never mutates `history` — returns a fresh array so callers can assign it\n * straight onto a cloned `NodeExecution`.\n *\n * @param history - Existing attempt history, oldest first (or `undefined`).\n * @param result - True outcome of this attempt — independent of any\n * compatibility status degrade the caller applies separately (e.g. an\n * optional node's failed execution still records `'failed'` here even\n * though its `NodeExecution.status` becomes `'skipped'`).\n * @param startedAtIso - This attempt's actual start time.\n * @param completedAtIso - This attempt's terminal outcome time.\n * @param options - See {@link AppendAttemptOptions}. Both fields default to absent.\n * @docLink packages/flow-engine/concepts#append-attempt\n */\nexport function appendAttempt(\n history: NodeExecutionAttempt[] | undefined,\n result: NodeExecutionAttempt[\"result\"],\n startedAtIso: string,\n completedAtIso: string,\n output: NodeOutput | undefined,\n error: NodeError | undefined,\n options: AppendAttemptOptions = {},\n): NodeExecutionAttempt[] {\n const attempt: NodeExecutionAttempt = {\n attempt: nextAttemptNumber(history),\n result,\n startedAt: startedAtIso,\n completedAt: completedAtIso,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error } : {}),\n ...(options.selfRetry ? { selfRetry: true } : {}),\n ...(options.check !== undefined ? { check: options.check } : {}),\n };\n return [...(history ?? []), attempt];\n}\n\n/**\n * Count of attempts in `history` whose true outcome was `'failed'`,\n * excluding self-retry entries (see {@link appendAttempt}) — this feeds only\n * the automatic-retry budget, which self-retry sits outside of.\n */\nexport function countFailedAttempts(history: NodeExecutionAttempt[] | undefined): number {\n if (!history) return 0;\n return history.filter((entry) => entry.result === \"failed\" && !entry.selfRetry).length;\n}\n\n/**\n * Whether an automatic retry remains, given how many attempts have already\n * failed and the authored `control.retries` budget. `retries: N` allows the\n * first attempt plus N automatic retries — so a retry remains available\n * while `priorFailedAttempts < N`. No `retries` (or `0`) means no automatic\n * retry ever.\n *\n * @docLink packages/flow-engine/concepts#has-automatic-retry-budget\n */\nexport function hasAutomaticRetryBudget(\n priorFailedAttempts: number,\n retries: number | undefined,\n): boolean {\n if (!retries) return false;\n return priorFailedAttempts < retries;\n}\n","/**\n * The single statement of the rule that decides an exhausted failure's\n * terminal status.\n *\n * Previously each terminal-failure write site restated the rule and only two\n * of them implemented it, so `control.optional` meant different things per\n * node kind. Every such site now routes through here.\n *\n * @docLink packages/flow-engine/concepts#optional-failure\n */\n\nimport { isRouterNode, nodeIsOptional } from \"./node-shape.js\";\nimport type { FlowNode } from \"./types.js\";\n\n/**\n * Terminal status for a node whose execution failed with no retry budget left.\n *\n * Invariant: an optional node never ends terminally `failed`. Only `complete`\n * and `skipped` satisfy a hard `flow` edge (see `isBlocking`), so leaving one\n * `failed` stalls every dependent at the node the author called expendable.\n *\n * A router is the deliberate exception: a `skipped` router leaves the gated\n * set (`unsettledRouterBranchIds`) while satisfying every outgoing hard edge,\n * so skipping it admits *all* of its branches instead of selecting one.\n */\nexport function resolveTerminalFailureStatus(node: FlowNode): \"failed\" | \"skipped\" {\n return nodeIsOptional(node) && !isRouterNode(node) ? \"skipped\" : \"failed\";\n}\n","/**\n * Pure derivation of a `check` node's evidence payload — what was compared,\n * where each value came from, and whether that makes the verdict\n * runtime-`\"verified\"` or agent-`\"asserted\"`.\n *\n * Ruling: re-running a check is not required to reproduce the same answer,\n * so there is no snapshot materialization, no hashing, and no reproducibility\n * guarantee here — this module records integrity of *what was observed*, not\n * a promise that observing it again would agree. Provenance is derived\n * exclusively from {@link BindingOrigin.obtainedBy}, the flow engine's\n * existing (and only) provenance mechanism, so it can never be influenced by\n * how a flow author names a binding. That label is transitive before it\n * arrives here — a deterministic node that carries an agent's value forward\n * stays agent-obtained — so this module compares origins as given and makes\n * no one-hop caveat.\n *\n * The claim is that provenance cannot be asserted by flow *configuration*.\n * It is not a claim against a caller holding the read-write connector handle:\n * taint now derives from persisted `NodeExecution.inputOrigins`, which the\n * `hydrate` op writes verbatim. Such a caller could already forge `output`\n * itself, so this widens no existing trust boundary.\n *\n * No I/O and no clock: `observedAt` is supplied by the caller so this stays\n * trivially testable and replayable.\n *\n * @docLink packages/flow-engine/concepts#check-provenance\n */\n\nimport type {\n BindingOrigin,\n CheckComparedValue,\n CheckEvidence,\n CheckInputCurrency,\n CheckProvenance,\n} from \"@skaile/workspaces/types\";\nimport type { ResolvedNodeBindings } from \"../contract/expression.js\";\n\n/** The check's process facts, captured alongside its verdict so a persisted attempt is self-describing. */\nexport interface CheckProcessRecord {\n runtime: \"shell\" | \"node\" | \"python\";\n command: string;\n cwd?: string;\n successExit: number[];\n exitStatus: number;\n passed: boolean;\n}\n\nconst FLOW_LOCAL_SOURCES = new Set<BindingOrigin[\"source\"]>([\"literal\", \"default\", \"flow-input\"]);\n\n/**\n * Derive one check's evidence from its already-resolved bindings and its\n * process outcome. `provenance` and `inputs` are computed only from\n * `bindings.origins` — never from `bindings.values` or their names — so\n * authoring a binding literally named `provenance` or `verified` cannot\n * influence the verdict.\n *\n * `provenance` is `\"verified\"` iff every origin of every compared value has\n * `obtainedBy: \"runtime\"`, `\"asserted\"` if any does not, and **absent** when\n * there are no compared values — neither label is honest about an empty set.\n * `obtainedBy` is already transitive when it reaches here (see\n * `producerOutputObtainedBy`), so `\"verified\"` means no agent-produced value\n * contributed anywhere in the ancestry, not merely one hop back.\n * `inputs` is `\"live\"` — the floor for any check that runs a process —\n * unless there is at least one compared value and every one of them has\n * origins that are all `literal`/`default`/`flow-input`, in which case it is\n * `\"flow-local\"`.\n */\nexport function deriveCheckEvidence(\n bindings: ResolvedNodeBindings,\n process: CheckProcessRecord,\n observedAt: string,\n): CheckEvidence {\n const values: CheckComparedValue[] = Object.entries(bindings.values).map(([name, value]) => {\n const origins = bindings.origins[name] ?? [];\n const obtainedBy = origins.some((origin) => origin.obtainedBy === \"agent\")\n ? \"agent\"\n : \"runtime\";\n return { name, value, origins, obtainedBy };\n });\n const provenance: CheckProvenance | undefined =\n values.length === 0\n ? undefined\n : values.every((compared) => compared.obtainedBy === \"runtime\")\n ? \"verified\"\n : \"asserted\";\n const inputs: CheckInputCurrency =\n values.length > 0 &&\n values.every((compared) =>\n compared.origins.every((origin) => FLOW_LOCAL_SOURCES.has(origin.source)),\n )\n ? \"flow-local\"\n : \"live\";\n return {\n values,\n ...(provenance !== undefined ? { provenance } : {}),\n inputs,\n observedAt,\n ...process,\n };\n}\n","/**\n * Flow manifest schema and validation.\n *\n * Moved from @skaile/workspaces/types/manifests/flow.ts in Phase 1.7.3.\n * This is now the canonical location for flow manifest validation.\n */\n\nimport * as z from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Validation result (inline — avoids importing from types/manifests/_shared)\n// ---------------------------------------------------------------------------\n\nexport interface ManifestValidationSuccess<T> {\n ok: true;\n data: T;\n}\n\nexport interface ManifestValidationFailure {\n ok: false;\n errors: Array<{ path: string; message: string }>;\n}\n\nexport type ManifestValidationResult<T> = ManifestValidationSuccess<T> | ManifestValidationFailure;\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst FlowNodeSchema = z.looseObject({\n id: z.string().min(1),\n skill: z.string().optional(),\n type: z.string().optional(),\n label: z.string().optional(),\n description: z.string().optional(),\n data: z\n .looseObject({\n optional: z.boolean().optional(),\n // Mandatory approval gate — autonomous mode cannot skip it.\n approval: z.looseObject({ mandatory: z.boolean().optional() }).optional(),\n })\n .refine((d) => !(d.optional === true && d.approval?.mandatory === true), {\n // A mandatory gate can never be skipped, so optional+mandatory is a\n // contradiction — reject it rather than silently letting mandatory win.\n message: \"a node cannot be both optional and a mandatory approval gate\",\n })\n .optional(),\n});\n\nconst FlowEdgeSchema = z.looseObject({\n id: z.string().optional(),\n source: z.string().min(1),\n target: z.string().min(1),\n condition: z.string().optional(),\n});\n\nexport const FlowManifestSchema = z.looseObject({\n id: z.string().min(1),\n version: z.string().optional(),\n name: z.string().min(1),\n description: z.string().optional(),\n metadata: z\n .looseObject({\n tags: z.array(z.string()).optional(),\n stage: z.string().optional(),\n icon: z.string().optional(),\n category: z.string().optional(),\n onboarding: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n globals: z.record(z.string(), z.unknown()).optional(),\n modes: z.record(z.string(), z.unknown()).optional(),\n tier_presets: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),\n artifact_handoff: z.unknown().optional(),\n entry: z.string().optional(),\n nodes: z.array(FlowNodeSchema).optional(),\n edges: z.array(FlowEdgeSchema).optional(),\n});\n\nexport type FlowManifest = z.infer<typeof FlowManifestSchema>;\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport function validateFlow(data: unknown): ManifestValidationResult<FlowManifest> {\n const result = FlowManifestSchema.safeParse(data);\n if (result.success) {\n return { ok: true, data: result.data };\n }\n return {\n ok: false,\n errors: result.error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n })),\n };\n}\n","/**\n * Flow asset kind provider.\n *\n * Exported from @skaile/workspaces/factory-assets/connectors/flow/engine for explicit registration\n * by the CLI at bootstrap. Discovery does NOT auto-include this provider\n * (discovery must stay a leaf — no flow-engine imports).\n *\n * Implements IAssetKindProvider with flow-specific:\n * - Discovery patterns: *.flow.yaml, *.flow.json\n * - Manifest validation via FlowManifestSchema\n * - Requires extraction: nodes[].run.assets plus legacy skill/sub-flow references\n * - File filter: just the manifest file (flows are single-file)\n */\n\nimport * as path from \"node:path\";\nimport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"@skaile/workspaces/plugins\";\nimport { validateFlow } from \"./flow-manifest.js\";\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport const flowKindProvider: IAssetKindProvider = {\n kind: \"flow\",\n displayName: \"Flow\",\n providerVersion: \"1.1.0\",\n installTarget: \"flow\",\n discoveryPatterns: [\"**/*.flow.yaml\", \"**/*.flow.json\"],\n\n matchesPath(relativePath: string): boolean {\n return relativePath.endsWith(\".flow.yaml\") || relativePath.endsWith(\".flow.json\");\n },\n\n validateManifest(data: unknown) {\n return validateFlow(data);\n },\n\n defaultFileFilter(manifestPath: string): AssetKindFileFilter {\n return {\n assetRoot: path.dirname(manifestPath),\n files: [path.basename(manifestPath)],\n };\n },\n\n extractRequires(assetRef: string, manifest: Record<string, unknown>): AssetKindRequiresEdge[] {\n const edges: AssetKindRequiresEdge[] = [];\n const seen = new Set<string>();\n const add = (to: string, field: string): void => {\n if (seen.has(to)) return;\n seen.add(to);\n edges.push({ from: assetRef, to, field });\n };\n\n const nodes = manifest.nodes;\n if (Array.isArray(nodes)) {\n for (const node of nodes) {\n if (typeof node !== \"object\" || node === null) continue;\n const n = node as Record<string, unknown>;\n const data = (\n typeof n.data === \"object\" && n.data !== null ? (n.data as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const run =\n typeof n.run === \"object\" && n.run !== null ? (n.run as Record<string, unknown>) : {};\n\n if (Array.isArray(run.assets)) {\n for (const asset of run.assets) {\n if (typeof asset === \"string\") add(asset, \"nodes[].run.assets\");\n }\n }\n\n if (run.kind === \"sub-flow\" && typeof run.flow === \"string\") {\n const flowRef = run.flow.startsWith(\"flow:\") ? run.flow : `flow:${run.flow}`;\n add(flowRef, \"nodes[].run.flow\");\n }\n\n const skill = typeof data.skill === \"string\" ? data.skill : n.skill;\n if (typeof skill === \"string\") {\n add(skill, \"nodes[].data.skill\");\n }\n\n const subFlow = typeof data.flow === \"string\" ? data.flow : n.flow;\n if (typeof subFlow === \"string\") {\n add(subFlow.startsWith(\"flow:\") ? subFlow : `flow:${subFlow}`, \"nodes[].data.flow\");\n }\n }\n }\n\n return edges;\n },\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findKindDirs } from \"@skaile/workspaces/core\";\nimport { parse as parseYaml } from \"yaml\";\nimport { parseFlowDefinition } from \"../contract/normalize.js\";\nimport type { FlowDefinition } from \"./types.js\";\n\n/**\n * The filename suffixes a flow file may carry, in probe order. `.json` is the\n * legacy bare form and stays last so an explicit `.flow.json` wins a tie.\n *\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport const FLOW_FILE_EXTENSIONS = [\".flow.yaml\", \".flow.yml\", \".flow.json\", \".json\"] as const;\n\n/** A discovered flow paired with the file it was loaded from. */\nexport interface FlowFileEntry {\n flow: FlowDefinition;\n path: string;\n}\n\n/**\n * The conventional on-disk locations of flow `flowId` inside one `flows/` search\n * dir: the flat `<dir>/<id><ext>` and the per-flow-directory\n * `<dir>/<id>/<id><ext>`, for every {@link FLOW_FILE_EXTENSIONS}. Existence is\n * NOT checked. Shared with `findFlowFileInRoots` so the naming convention has\n * exactly one definition.\n *\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function flowFileCandidates(dirPath: string, flowId: string): string[] {\n return [\n ...FLOW_FILE_EXTENSIONS.map((ext) => path.join(dirPath, `${flowId}${ext}`)),\n ...FLOW_FILE_EXTENSIONS.map((ext) => path.join(dirPath, flowId, `${flowId}${ext}`)),\n ];\n}\n\n/** Matches `flow.yaml` as well as `<anything>.flow.yaml` (and `.yml` / `.json`). */\nconst FLOW_SHAPED_FILE = /(^|\\.)flow\\.(ya?ml|json)$/i;\n\n/** How far below a per-flow directory a stray flow file is still reported. */\nconst STRAY_SCAN_DEPTH = 3;\n\nfunction isDirectory(entry: fs.Dirent, fullPath: string): boolean {\n if (entry.isDirectory()) return true;\n if (!entry.isSymbolicLink()) return false;\n try {\n return fs.statSync(fullPath).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * First flow-shaped file at or below `dirPath`, used only to decide whether a\n * subdirectory that yielded no conventional flow deserves a warning. Deliberately\n * ignores bare `.json` so sibling assets (`package.json`, fixtures) stay silent.\n */\nfunction findStrayFlowFile(dirPath: string, depth: number = STRAY_SCAN_DEPTH): string | undefined {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dirPath, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const entry of entries) {\n if (!isDirectory(entry, path.join(dirPath, entry.name)) && FLOW_SHAPED_FILE.test(entry.name)) {\n return path.join(dirPath, entry.name);\n }\n }\n if (depth <= 1) return undefined;\n for (const entry of entries) {\n const full = path.join(dirPath, entry.name);\n if (!isDirectory(entry, full)) continue;\n if (entry.name.startsWith(\"_\") || entry.name.startsWith(\".\") || entry.name === \"node_modules\") {\n continue;\n }\n const stray = findStrayFlowFile(full, depth - 1);\n if (stray) return stray;\n }\n return undefined;\n}\n\n/**\n * Load a single {@link FlowDefinition} from a YAML or JSON file on disk.\n *\n * Format detection is based on file extension:\n * - `.yaml` / `.yml` — parsed with the `yaml` library.\n * - Everything else — parsed as JSON.\n *\n * @param filePath - Absolute path to the flow file.\n * @returns The parsed {@link FlowDefinition}.\n * @throws {Error} If the file does not exist, cannot be read, or fails to parse.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadFlow(filePath: string): FlowDefinition {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const ext = path.extname(filePath).toLowerCase();\n const authored = ext === \".yaml\" || ext === \".yml\" ? parseYaml(raw) : JSON.parse(raw);\n const parsed = parseFlowDefinition(authored);\n if (!parsed.ok) {\n const details = parsed.errors\n .map((issue) => ` ${issue.path || \"<root>\"}: ${issue.message}`)\n .join(\"\\n\");\n throw new Error(`Invalid flow definition:\\n${details}`);\n }\n return parsed.data;\n}\n\n/**\n * Load every flow in a `flows/` directory, in both supported shapes, keeping the\n * file each one came from.\n *\n * Two tiers, and nothing else:\n * 1. **Flat** — a file directly in `dirPath` ending in one of {@link FLOW_FILE_EXTENSIONS}.\n * 2. **Per-flow directory** — `<dir>/<sub>/<sub><ext>`; the file MUST be named after\n * its directory, which is what lets a flow keep sibling assets (README, fixtures,\n * prompts) without them being parsed as flows.\n *\n * A subdirectory that holds something flow-shaped but no conventional file is\n * **reported** through `onWarn` rather than dropped silently — silence is the\n * defect this contract exists to remove. Files/dirs prefixed with `_` are the\n * explicit opt-out and stay silent. Parse failures are warned about and skipped,\n * never thrown.\n *\n * @param dirPath - Absolute path to the directory to scan.\n * @param opts.onWarn - Sink for warnings; defaults to `stderr`. Pass a no-op on\n * hot paths where a probe miss is normal (e.g. resolving an arbitrary CLI arg).\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadFlowEntriesFromDir(\n dirPath: string,\n opts: { onWarn?: (message: string) => void } = {},\n): FlowFileEntry[] {\n const warn = opts.onWarn ?? ((message: string) => void process.stderr.write(`${message}\\n`));\n\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dirPath, { withFileTypes: true });\n } catch {\n return [];\n }\n\n const found: FlowFileEntry[] = [];\n const load = (filePath: string, label: string) => {\n try {\n const def = loadFlow(filePath);\n if (def.id && def.nodes && def.edges) found.push({ flow: def, path: filePath });\n } catch (err) {\n warn(`[agent-flow-engine] skipping ${label}: ${(err as Error).message}`);\n }\n };\n\n for (const entry of entries) {\n if (entry.name.startsWith(\"_\")) continue;\n const full = path.join(dirPath, entry.name);\n\n if (!isDirectory(entry, full)) {\n if (FLOW_FILE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) load(full, entry.name);\n continue;\n }\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\n const conventional = FLOW_FILE_EXTENSIONS.map((ext) =>\n path.join(full, `${entry.name}${ext}`),\n ).find((candidate) => fs.existsSync(candidate));\n if (conventional) {\n load(conventional, path.join(entry.name, path.basename(conventional)));\n continue;\n }\n\n const stray = findStrayFlowFile(full);\n if (stray) {\n warn(\n `[agent-flow-engine] ignoring ${stray}: a flow directory must hold ` +\n `${entry.name}.flow.yaml (or .flow.yml / .flow.json / .json)`,\n );\n }\n }\n\n return found;\n}\n\n/**\n * Load all flows from a directory — {@link loadFlowEntriesFromDir} without the\n * originating file paths. See it for the two supported layouts, the warning\n * contract, and the `_`-prefix opt-out.\n *\n * @param dirPath - Absolute path to the directory to scan.\n * @returns Array of successfully parsed {@link FlowDefinition} objects. Empty if the\n * directory does not exist or contains no valid flow files.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadFlowsFromDir(dirPath: string): FlowDefinition[] {\n return loadFlowEntriesFromDir(dirPath).map((entry) => entry.flow);\n}\n\n/**\n * Discover every flow under a content root, keeping the file each came from.\n *\n * Covers every `flows/` directory at any depth under the root via\n * `findKindDirs`, and within each of those both flow layouts via\n * {@link loadFlowEntriesFromDir}. De-duped by **declared id**, first search dir\n * wins — the same identity every other flow surface resolves by.\n *\n * @param aiResourcesRoot - Absolute path to a content root (`ai-assets/` or equivalent).\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadAllFlowEntries(\n aiResourcesRoot: string,\n opts: { onWarn?: (message: string) => void } = {},\n): FlowFileEntry[] {\n if (!fs.existsSync(aiResourcesRoot)) return [];\n\n const byId = new Map<string, FlowFileEntry>();\n for (const dir of findKindDirs(aiResourcesRoot, \"flows\")) {\n for (const entry of loadFlowEntriesFromDir(dir, opts)) {\n if (!byId.has(entry.flow.id)) byId.set(entry.flow.id, entry);\n }\n }\n return [...byId.values()];\n}\n\n/**\n * Discover and load all flow definitions under a content root —\n * {@link loadAllFlowEntries} without the originating file paths.\n *\n * @param aiResourcesRoot - Absolute path to the `ai-assets/` directory (or equivalent\n * resource root). Typically the `ai-assets/` folder at the monorepo root.\n * @returns Flat array of all successfully parsed {@link FlowDefinition} objects across\n * all `flows/` directories. Empty if the root directory does not exist.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadAllFlows(aiResourcesRoot: string): FlowDefinition[] {\n return loadAllFlowEntries(aiResourcesRoot).map((entry) => entry.flow);\n}\n","/**\n * locate.ts — the one place that answers \"where do flows live, and what are\n * they called\".\n *\n * It sits in the engine, next to `flowFileCandidates` / `loadAllFlowEntries`,\n * because both sides of the question have to agree: the CLI's *listing*\n * surfaces (`flow list`, completions) and the *resolution* surfaces that live\n * in this tree (`resume`, sub-flow `run.flow` targets, `serve`). They used to\n * hold two hand-maintained candidate lists, and only one of them ever grew.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findKindDirs, projectAssetRoots } from \"@skaile/workspaces/core\";\nimport { flowFileCandidates, loadAllFlowEntries, loadFlow } from \"./loader.js\";\n\n/** How far up from the project the `ai-assets/` walk looks before giving up. */\nconst AI_ASSETS_WALK_LEVELS = 6;\n\n/**\n * Walk upward from `startDir` (checking at most `AI_ASSETS_WALK_LEVELS`\n * directories, never the filesystem root itself) for an `ai-assets/`\n * subdirectory. Returns its absolute path, or `null` when none is found.\n */\nfunction findAiAssetsDir(startDir: string): string | null {\n let dir = path.resolve(startDir);\n const fsRoot = path.parse(dir).root;\n\n for (let i = 0; i < AI_ASSETS_WALK_LEVELS; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir || parent === fsRoot) break;\n dir = parent;\n }\n return null;\n}\n\n/**\n * Roots that only the *resolution* surfaces prepend: the project's own\n * `ai-assets/` tree, so a workspace can shadow a built-in flow.\n *\n * Returns at most one root — the nearest `ai-assets/` at or above `projectDir`.\n * Listing deliberately does **not** include it; see `cli/src/flow-discovery.ts`.\n *\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function projectAiAssetsRoots(projectDir: string): string[] {\n const found = findAiAssetsDir(projectDir);\n return found ? [found] : [];\n}\n\n/**\n * Every root a flow lookup walks, in priority order: the project's own\n * `ai-assets/` tree first, then the project's roots ({@link projectAssetRoots}: its\n * `.skaile/` install root and the first-party factory-assets layers).\n *\n * This is the **project** scope (p1353): `skaile run <id>`, `flow list`, `resume`,\n * sub-flow `run.flow` targets and `serve` all resolve over it, so a flow that runs\n * for you runs for a teammate with the same `skaile.yaml`. The registered\n * libraries, the source clones in `~/.skaile/cache/` and the global `~/.skaile/`\n * root are not part of it; a flow that lives only there needs `skaile add` first.\n *\n * The authored `ai-assets/` tree leading is deliberate and is what `skaile run`\n * has always done: a workspace must be able to shadow a built-in flow. It is the\n * opposite of the `.skaile/`-first ordering of `aiResourceRoots`, where the deployed\n * `.skaile/` copy leads because `deployAll` applies `patches:` to it — so for a\n * flow id present in *both*, resolution takes the authored source. Resume must\n * execute the bytes `run` executed; that agreement is the point of this module.\n *\n * @param projectDir - Project whose `.skaile/` and `ai-assets/` roots to\n * include (default: `process.cwd()`).\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function flowLookupRoots(projectDir?: string): string[] {\n const dir = path.resolve(projectDir ?? process.cwd());\n return [...new Set([...projectAiAssetsRoots(dir), ...projectAssetRoots(dir)])];\n}\n\n/**\n * Why a conventional candidate that exists on disk was still not accepted —\n * the difference between \"no such flow\" and \"that file is right there but\n * declares something else\", which a bare \"not found\" used to hide.\n *\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport interface FlowLookupMiss {\n path: string;\n reason: \"unparseable\" | \"id-mismatch\";\n declaredId?: string;\n error?: string;\n}\n\n/** `candidate` resolves inside `dir` rather than escaping it via `..`. */\nfunction contained(dir: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(dir), path.resolve(candidate));\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\n/**\n * Locate the file of the flow whose **declared id** is `flowId`, across `roots`.\n *\n * Per root: the conventional paths first (every `flows/` directory at any depth\n * via `findKindDirs`, both flow layouts and all four extensions via\n * `flowFileCandidates`), then the full enumeration `loadAllFlowEntries` — the\n * same one `discoverFlows` lists from, which is what keeps listing and\n * resolution agreeing by construction. The fallback stays *inside* the loop so\n * an earlier root always wins over a later one.\n *\n * A candidate that resolves outside the search dir it was built from is\n * **skipped, not thrown**: this is on the `skaile run \"<free-text prompt>\"`\n * path, where a miss is normal and must fall through to single-shot mode.\n *\n * @param opts.onMiss - Called for a conventional candidate that exists but was\n * rejected. Discovery warnings are suppressed regardless.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function findFlowFileInRoots(\n flowId: string,\n roots: string[],\n opts: { onMiss?: (miss: FlowLookupMiss) => void } = {},\n): string | undefined {\n for (const root of roots) {\n for (const dir of findKindDirs(root, \"flows\")) {\n for (const candidate of flowFileCandidates(dir, flowId)) {\n if (!contained(dir, candidate) || !fs.existsSync(candidate)) continue;\n let declaredId: string;\n try {\n declaredId = loadFlow(candidate).id;\n } catch (err) {\n opts.onMiss?.({\n path: candidate,\n reason: \"unparseable\",\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (declaredId === flowId) return candidate;\n opts.onMiss?.({ path: candidate, reason: \"id-mismatch\", declaredId });\n }\n }\n const entry = loadAllFlowEntries(root, { onWarn: () => {} }).find((e) => e.flow.id === flowId);\n if (entry) return entry.path;\n }\n return undefined;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getKindRegistry } from './chunk-
|
|
2
|
-
import { logErr } from './chunk-
|
|
1
|
+
import { getKindRegistry } from './chunk-QCR5AE5E.js';
|
|
2
|
+
import { logErr } from './chunk-L3JQJ6D5.js';
|
|
3
3
|
import { userConfigPath } from './chunk-L5VSIPQD.js';
|
|
4
4
|
|
|
5
5
|
// cli/src/open-library.ts
|
|
@@ -90,5 +90,5 @@ async function openLibraryManager() {
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
export { LocalCatalogDisabledError, openCatalogSource, openLibrary, openLibraryManager, resolveCatalogSource };
|
|
93
|
-
//# sourceMappingURL=chunk-
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
93
|
+
//# sourceMappingURL=chunk-WIYVR24B.js.map
|
|
94
|
+
//# sourceMappingURL=chunk-WIYVR24B.js.map
|