@skaile/workspaces 5.7.0 → 5.8.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 +114 -0
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-K36CR52Q.js → asset-feeds-EYRZR4K5.js} +54 -30
- package/dist/asset-feeds-EYRZR4K5.js.map +1 -0
- package/dist/asset-manager/catalog-deployer.js +9 -9
- package/dist/asset-manager/index.js +15 -15
- package/dist/asset-manager/installer.js +11 -11
- package/dist/asset-manager/renderers.js +10 -10
- package/dist/asset-manager/src/index.d.ts +268 -24
- package/dist/asset-manager/src/index.d.ts.map +1 -1
- package/dist/asset-manager/src/install-agent.d.ts +11 -0
- package/dist/asset-manager/src/install-agent.d.ts.map +1 -1
- package/dist/asset-manager/src/installer.d.ts +2 -2
- package/dist/asset-manager/src/installer.d.ts.map +1 -1
- package/dist/bridge/drivers/claude-sdk.js +147 -211
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +90 -66
- package/dist/bridge/drivers/codex.js.map +1 -1
- package/dist/bridge/drivers/continue.js +14 -15
- package/dist/bridge/drivers/continue.js.map +1 -1
- package/dist/bridge/drivers/echo.js +4 -4
- package/dist/bridge/drivers/gemini.js +8 -8
- package/dist/bridge/drivers/goose.js +14 -15
- package/dist/bridge/drivers/goose.js.map +1 -1
- package/dist/bridge/drivers/omp.js +68 -104
- package/dist/bridge/drivers/omp.js.map +1 -1
- package/dist/bridge/drivers/opencode.js +14 -15
- package/dist/bridge/drivers/opencode.js.map +1 -1
- package/dist/bridge/drivers/qwen.js +8 -8
- package/dist/bridge/index.js +16 -17
- package/dist/bridge/src/codex/managed-driver.d.ts +13 -10
- package/dist/bridge/src/codex/managed-driver.d.ts.map +1 -1
- package/dist/bridge/src/drivers/_subprocess-cli.d.ts +12 -2
- package/dist/bridge/src/drivers/_subprocess-cli.d.ts.map +1 -1
- package/dist/bridge/src/drivers/claude-sdk.d.ts +37 -62
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/drivers/codex.d.ts +26 -10
- package/dist/bridge/src/drivers/codex.d.ts.map +1 -1
- package/dist/bridge/src/drivers/continue.d.ts +2 -2
- package/dist/bridge/src/drivers/continue.d.ts.map +1 -1
- package/dist/bridge/src/drivers/gemini.d.ts +2 -2
- package/dist/bridge/src/drivers/gemini.d.ts.map +1 -1
- package/dist/bridge/src/drivers/goose.d.ts +2 -2
- package/dist/bridge/src/drivers/goose.d.ts.map +1 -1
- package/dist/bridge/src/drivers/omp.d.ts +24 -35
- package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
- package/dist/bridge/src/drivers/opencode.d.ts +2 -2
- package/dist/bridge/src/drivers/opencode.d.ts.map +1 -1
- package/dist/bridge/src/drivers/recovery-policy.d.ts +79 -0
- package/dist/bridge/src/drivers/recovery-policy.d.ts.map +1 -0
- package/dist/bridge/src/index.d.ts +1 -0
- package/dist/bridge/src/index.d.ts.map +1 -1
- package/dist/bridge/src/reconfigure-ledger.d.ts +117 -0
- package/dist/bridge/src/reconfigure-ledger.d.ts.map +1 -0
- package/dist/bridge/src/types.d.ts +57 -6
- package/dist/bridge/src/types.d.ts.map +1 -1
- package/dist/{chunk-WIEC3ZE4.js → chunk-2FRUUDZY.js} +5 -5
- package/dist/{chunk-WIEC3ZE4.js.map → chunk-2FRUUDZY.js.map} +1 -1
- package/dist/{chunk-O4Z7MAW7.js → chunk-2LWYNQK7.js} +3 -3
- package/dist/{chunk-O4Z7MAW7.js.map → chunk-2LWYNQK7.js.map} +1 -1
- package/dist/{chunk-OOLT6HGP.js → chunk-36AFURKZ.js} +7 -7
- package/dist/{chunk-OOLT6HGP.js.map → chunk-36AFURKZ.js.map} +1 -1
- package/dist/{chunk-DFFD4BFG.js → chunk-4MQS7CAF.js} +174 -86
- package/dist/chunk-4MQS7CAF.js.map +1 -0
- package/dist/{chunk-RNPHRRLG.js → chunk-4PTSR4UU.js} +3 -3
- package/dist/{chunk-RNPHRRLG.js.map → chunk-4PTSR4UU.js.map} +1 -1
- package/dist/{chunk-34C42MJX.js → chunk-6GRX5L6A.js} +5 -5
- package/dist/{chunk-34C42MJX.js.map → chunk-6GRX5L6A.js.map} +1 -1
- package/dist/{chunk-NFGRW3L7.js → chunk-7RGTAEG6.js} +3 -3
- package/dist/{chunk-NFGRW3L7.js.map → chunk-7RGTAEG6.js.map} +1 -1
- package/dist/{chunk-BTK7ECLH.js → chunk-AWQYXZVG.js} +15 -6
- package/dist/chunk-AWQYXZVG.js.map +1 -0
- package/dist/{chunk-XBSQ4KMC.js → chunk-B4X2N7JQ.js} +205 -3
- package/dist/chunk-B4X2N7JQ.js.map +1 -0
- package/dist/{chunk-FRHE7FFB.js → chunk-B6GIW55K.js} +5 -3
- package/dist/chunk-B6GIW55K.js.map +1 -0
- package/dist/{chunk-JLSCA5T5.js → chunk-BJNUNQAW.js} +3 -3
- package/dist/{chunk-JLSCA5T5.js.map → chunk-BJNUNQAW.js.map} +1 -1
- package/dist/{chunk-RVIZQ5XD.js → chunk-BTE2V4IW.js} +3 -3
- package/dist/{chunk-RVIZQ5XD.js.map → chunk-BTE2V4IW.js.map} +1 -1
- package/dist/{chunk-EB4XN3KE.js → chunk-CGT45WN7.js} +3 -3
- package/dist/{chunk-EB4XN3KE.js.map → chunk-CGT45WN7.js.map} +1 -1
- package/dist/{chunk-47ZD34KB.js → chunk-CIFS5K6T.js} +3 -3
- package/dist/{chunk-47ZD34KB.js.map → chunk-CIFS5K6T.js.map} +1 -1
- package/dist/{chunk-FAP63KV7.js → chunk-CKQEIY43.js} +4 -4
- package/dist/{chunk-FAP63KV7.js.map → chunk-CKQEIY43.js.map} +1 -1
- package/dist/{chunk-AVCUPPG6.js → chunk-EF7NPDDU.js} +4 -4
- package/dist/{chunk-AVCUPPG6.js.map → chunk-EF7NPDDU.js.map} +1 -1
- package/dist/chunk-EPBKISS5.js +84 -0
- package/dist/chunk-EPBKISS5.js.map +1 -0
- package/dist/{chunk-THEJJBOU.js → chunk-F2EKONM7.js} +3 -3
- package/dist/{chunk-THEJJBOU.js.map → chunk-F2EKONM7.js.map} +1 -1
- package/dist/{chunk-DMLDYFDS.js → chunk-F3RDEH5U.js} +7 -4
- package/dist/chunk-F3RDEH5U.js.map +1 -0
- package/dist/{chunk-SZWRPEF7.js → chunk-FTJJO3EM.js} +39 -29
- package/dist/chunk-FTJJO3EM.js.map +1 -0
- package/dist/{chunk-PSA6ONFB.js → chunk-FVJK4QWM.js} +4 -4
- package/dist/{chunk-PSA6ONFB.js.map → chunk-FVJK4QWM.js.map} +1 -1
- package/dist/{chunk-LBQ4BBX4.js → chunk-FZNG4V4J.js} +16 -30
- package/dist/chunk-FZNG4V4J.js.map +1 -0
- package/dist/{chunk-SWO25LTO.js → chunk-GB7WDMH2.js} +4 -4
- package/dist/{chunk-SWO25LTO.js.map → chunk-GB7WDMH2.js.map} +1 -1
- package/dist/{chunk-NARITJS2.js → chunk-GCICGXDD.js} +3 -3
- package/dist/{chunk-NARITJS2.js.map → chunk-GCICGXDD.js.map} +1 -1
- package/dist/{chunk-TTPSDC2G.js → chunk-GTILM2CI.js} +34 -13
- package/dist/chunk-GTILM2CI.js.map +1 -0
- package/dist/{chunk-EU3Q5AQ4.js → chunk-GXXFLBUQ.js} +23 -32
- package/dist/chunk-GXXFLBUQ.js.map +1 -0
- package/dist/{chunk-D5HOETOB.js → chunk-H7QUDDKH.js} +981 -126
- package/dist/chunk-H7QUDDKH.js.map +1 -0
- package/dist/{chunk-GIC3G5YG.js → chunk-HG34RNTK.js} +7 -13
- package/dist/chunk-HG34RNTK.js.map +1 -0
- package/dist/{chunk-LXY4BUA3.js → chunk-HYDRDNKN.js} +9 -5
- package/dist/chunk-HYDRDNKN.js.map +1 -0
- package/dist/{chunk-N6FBTXQ5.js → chunk-I6NLLJHZ.js} +2 -2
- package/dist/{chunk-N6FBTXQ5.js.map → chunk-I6NLLJHZ.js.map} +1 -1
- package/dist/{chunk-NWQB7UTY.js → chunk-IONAUNWB.js} +3 -3
- package/dist/{chunk-NWQB7UTY.js.map → chunk-IONAUNWB.js.map} +1 -1
- package/dist/{chunk-CT6NQSA4.js → chunk-ISHJITXJ.js} +3 -3
- package/dist/{chunk-CT6NQSA4.js.map → chunk-ISHJITXJ.js.map} +1 -1
- package/dist/chunk-IZCR27MU.js +60 -0
- package/dist/chunk-IZCR27MU.js.map +1 -0
- package/dist/{chunk-LCU5U5IW.js → chunk-JAKOMFC6.js} +67 -19
- package/dist/chunk-JAKOMFC6.js.map +1 -0
- package/dist/{chunk-VOOI7B2L.js → chunk-LEMHVDET.js} +86 -66
- package/dist/chunk-LEMHVDET.js.map +1 -0
- package/dist/{chunk-37FTLYFP.js → chunk-LNFKL23K.js} +3 -3
- package/dist/{chunk-37FTLYFP.js.map → chunk-LNFKL23K.js.map} +1 -1
- package/dist/{chunk-6UFFKMVC.js → chunk-LSXHED6I.js} +6 -6
- package/dist/{chunk-6UFFKMVC.js.map → chunk-LSXHED6I.js.map} +1 -1
- package/dist/{chunk-XUUYAS3Z.js → chunk-M3WPBTGJ.js} +3 -3
- package/dist/{chunk-XUUYAS3Z.js.map → chunk-M3WPBTGJ.js.map} +1 -1
- package/dist/{chunk-QZLWJETK.js → chunk-MGGFBZWA.js} +3 -3
- package/dist/{chunk-QZLWJETK.js.map → chunk-MGGFBZWA.js.map} +1 -1
- package/dist/{chunk-53MSCGR2.js → chunk-NPLPCRW5.js} +5 -5
- package/dist/{chunk-53MSCGR2.js.map → chunk-NPLPCRW5.js.map} +1 -1
- package/dist/{chunk-QCI6D7E4.js → chunk-NUELZWCF.js} +266 -170
- package/dist/chunk-NUELZWCF.js.map +1 -0
- package/dist/{chunk-BWZF2ZIF.js → chunk-OFBIWVCR.js} +3 -3
- package/dist/{chunk-BWZF2ZIF.js.map → chunk-OFBIWVCR.js.map} +1 -1
- package/dist/{chunk-IZLQ4GDO.js → chunk-P23M65LB.js} +43 -21
- package/dist/chunk-P23M65LB.js.map +1 -0
- package/dist/{chunk-G67BOI2J.js → chunk-PMECEZK3.js} +15 -9
- package/dist/chunk-PMECEZK3.js.map +1 -0
- package/dist/{chunk-GWXFSLBK.js → chunk-PTSGWKHR.js} +4 -4
- package/dist/{chunk-GWXFSLBK.js.map → chunk-PTSGWKHR.js.map} +1 -1
- package/dist/{chunk-OKGUDNDT.js → chunk-Q6E6FM7P.js} +35 -33
- package/dist/chunk-Q6E6FM7P.js.map +1 -0
- package/dist/{chunk-CWM3MYGX.js → chunk-QOP6KDFR.js} +8 -9
- package/dist/chunk-QOP6KDFR.js.map +1 -0
- package/dist/{chunk-O7VPNKYN.js → chunk-QVNRCDTV.js} +23 -7
- package/dist/chunk-QVNRCDTV.js.map +1 -0
- package/dist/{chunk-UX3K4RKE.js → chunk-S53LOR7B.js} +3 -3
- package/dist/{chunk-UX3K4RKE.js.map → chunk-S53LOR7B.js.map} +1 -1
- package/dist/{chunk-KNWCFEWU.js → chunk-SH5D7U7N.js} +20 -7
- package/dist/{chunk-KNWCFEWU.js.map → chunk-SH5D7U7N.js.map} +1 -1
- package/dist/{chunk-KM7XWC4Y.js → chunk-UAROCOXF.js} +3 -3
- package/dist/{chunk-KM7XWC4Y.js.map → chunk-UAROCOXF.js.map} +1 -1
- package/dist/{chunk-JMKB7IB4.js → chunk-UMVKJM4Q.js} +4 -4
- package/dist/chunk-UMVKJM4Q.js.map +1 -0
- package/dist/{chunk-HCYS7GFP.js → chunk-V2DXZYBB.js} +3 -3
- package/dist/{chunk-HCYS7GFP.js.map → chunk-V2DXZYBB.js.map} +1 -1
- package/dist/{chunk-IUUYRXT6.js → chunk-W5DWWE4Y.js} +4 -4
- package/dist/{chunk-IUUYRXT6.js.map → chunk-W5DWWE4Y.js.map} +1 -1
- package/dist/{chunk-FK6HPLQA.js → chunk-WTQ3TATB.js} +3 -3
- package/dist/{chunk-FK6HPLQA.js.map → chunk-WTQ3TATB.js.map} +1 -1
- package/dist/{chunk-7FJQT3GT.js → chunk-Y4N2NUZD.js} +4 -4
- package/dist/{chunk-7FJQT3GT.js.map → chunk-Y4N2NUZD.js.map} +1 -1
- package/dist/{chunk-6VRJH4MR.js → chunk-Y7QA2OLD.js} +6 -6
- package/dist/{chunk-6VRJH4MR.js.map → chunk-Y7QA2OLD.js.map} +1 -1
- package/dist/{chunk-74EEFB52.js → chunk-YSHVQGUS.js} +115 -27
- package/dist/chunk-YSHVQGUS.js.map +1 -0
- package/dist/{chunk-6C654TFI.js → chunk-ZAOGFXDO.js} +36 -8
- package/dist/chunk-ZAOGFXDO.js.map +1 -0
- package/dist/{chunk-MKLBK7HI.js → chunk-ZKSJMZKD.js} +17 -13
- package/dist/chunk-ZKSJMZKD.js.map +1 -0
- package/dist/cli/index.js +373 -188
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/asset-feeds.d.ts +5 -2
- package/dist/cli/src/asset-feeds.d.ts.map +1 -1
- package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/catalog.d.ts +15 -2
- package/dist/cli/src/commands/catalog.d.ts.map +1 -1
- package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/library-index.d.ts +8 -0
- package/dist/cli/src/commands/library-index.d.ts.map +1 -1
- package/dist/cli/src/commands/library-publish.d.ts.map +1 -1
- package/dist/cli/src/commands/manage.d.ts.map +1 -1
- package/dist/cli/src/commands/outdated.d.ts +7 -2
- package/dist/cli/src/commands/outdated.d.ts.map +1 -1
- package/dist/cli/src/commands/project.d.ts +2 -0
- package/dist/cli/src/commands/project.d.ts.map +1 -1
- package/dist/cli/src/commands/publish-core.d.ts +10 -1
- package/dist/cli/src/commands/publish-core.d.ts.map +1 -1
- package/dist/cli/src/commands/session.d.ts.map +1 -1
- package/dist/cli/src/commands/source.d.ts +14 -0
- package/dist/cli/src/commands/source.d.ts.map +1 -1
- package/dist/cli/src/commands/tree.d.ts.map +1 -1
- package/dist/cli/src/commands/update.d.ts.map +1 -1
- package/dist/cli/src/commands/validate.d.ts.map +1 -1
- package/dist/cli/src/flow-discovery.d.ts +8 -5
- package/dist/cli/src/flow-discovery.d.ts.map +1 -1
- package/dist/cli/src/open-library.d.ts +0 -11
- package/dist/cli/src/open-library.d.ts.map +1 -1
- package/dist/cli/src/skill-checks.d.ts +11 -2
- package/dist/cli/src/skill-checks.d.ts.map +1 -1
- package/dist/connectors/config.js +5 -5
- package/dist/connectors/index.js +25 -26
- package/dist/connectors/src/access-policy.d.ts +33 -0
- package/dist/connectors/src/access-policy.d.ts.map +1 -0
- package/dist/connectors/src/connector-manager.d.ts.map +1 -1
- package/dist/connectors/src/index.d.ts +2 -0
- package/dist/connectors/src/index.d.ts.map +1 -1
- package/dist/connectors-O6Y6VESP.js +44 -0
- package/dist/{connectors-SSOTIDHT.js.map → connectors-O6Y6VESP.js.map} +1 -1
- package/dist/connectors-shared/index.js +2 -2
- package/dist/core/index.js +8 -8
- package/dist/core/logging.js +1 -1
- package/dist/core/manifest.js +2 -2
- package/dist/core/models.js +1 -1
- package/dist/core/publish-manifest.js +2 -2
- package/dist/core/ref.js +1 -1
- package/dist/core/runtime-assets.js +5 -5
- package/dist/core/src/index.d.ts +3 -3
- package/dist/core/src/index.d.ts.map +1 -1
- package/dist/core/src/logging/config.d.ts +9 -1
- package/dist/core/src/logging/config.d.ts.map +1 -1
- package/dist/core/src/manifest.d.ts +11 -1
- package/dist/core/src/manifest.d.ts.map +1 -1
- package/dist/core/src/models.d.ts +14 -6
- package/dist/core/src/models.d.ts.map +1 -1
- package/dist/core/src/repo-manager.d.ts +41 -6
- package/dist/core/src/repo-manager.d.ts.map +1 -1
- package/dist/core/src/store.d.ts +16 -2
- package/dist/core/src/store.d.ts.map +1 -1
- package/dist/core/src/workspace-config.d.ts +10 -1
- package/dist/core/src/workspace-config.d.ts.map +1 -1
- package/dist/core/store.js +1 -1
- package/dist/core/workspace-config.js +4 -4
- package/dist/deploy/index.js +8 -8
- package/dist/discovery/index.js +5 -5
- package/dist/{ensure-sources-277VI7R3.js → ensure-sources-SKLNM4UZ.js} +18 -18
- package/dist/{ensure-sources-277VI7R3.js.map → ensure-sources-SKLNM4UZ.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +25 -26
- package/dist/factory-assets/connectors/deploy.js +25 -26
- package/dist/factory-assets/connectors/devserver.js +25 -26
- package/dist/factory-assets/connectors/flow/adapter.d.ts +6 -0
- package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/adapter.js +25 -26
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts +3 -0
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/output-fields.d.ts +1 -1
- package/dist/factory-assets/connectors/flow/contract/output-fields.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract.js +4 -4
- package/dist/factory-assets/connectors/flow/engine/flow-output.d.ts +4 -3
- package/dist/factory-assets/connectors/flow/engine/flow-output.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts +6 -1
- package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine.js +12 -12
- package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/prompt-fragments.js +3 -3
- package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/run-flow.js +27 -28
- package/dist/factory-assets/connectors/flow.js +25 -26
- package/dist/factory-assets/connectors/git/config.d.ts.map +1 -1
- package/dist/factory-assets/connectors/git.js +25 -26
- package/dist/factory-assets/connectors/gmail.js +25 -26
- package/dist/factory-assets/connectors/googledrive.js +25 -26
- package/dist/factory-assets/connectors/local.js +25 -26
- package/dist/factory-assets/connectors/mattermost.js +25 -26
- package/dist/factory-assets/connectors/memory.js +25 -26
- package/dist/factory-assets/connectors/minio.js +25 -26
- package/dist/factory-assets/connectors/postgres.js +25 -26
- package/dist/factory-assets/connectors/s3.js +25 -26
- package/dist/factory-assets/connectors/sharepoint.js +25 -26
- package/dist/factory-assets/connectors/sqlite.js +25 -26
- package/dist/factory-assets/connectors/static-server.js +25 -26
- package/dist/factory-assets/connectors/tunnel.js +25 -26
- package/dist/factory-assets/connectors/webdav.js +25 -26
- package/dist/factory-assets/connectors/xstate-store.js +25 -26
- package/dist/factory-assets/connectors/xstate.js +25 -26
- package/dist/factory-assets/skills/skaile-author-asset/SKILL.md +10 -7
- package/dist/{flows-J2UEU2QM.js → flows-CBYRSAGS.js} +13 -13
- package/dist/{flows-J2UEU2QM.js.map → flows-CBYRSAGS.js.map} +1 -1
- package/dist/{helpers-KC5O7CML.js → helpers-MWZDRBLD.js} +18 -18
- package/dist/{helpers-KC5O7CML.js.map → helpers-MWZDRBLD.js.map} +1 -1
- package/dist/library/index.js +12 -12
- package/dist/library/install.js +3 -3
- package/dist/library/src/index.d.ts +3 -1
- package/dist/library/src/index.d.ts.map +1 -1
- package/dist/library/src/local/scan-authoring-libraries.d.ts +43 -0
- package/dist/library/src/local/scan-authoring-libraries.d.ts.map +1 -0
- package/dist/library/src/manifest-writer.d.ts +26 -3
- package/dist/library/src/manifest-writer.d.ts.map +1 -1
- package/dist/library/src/sync/git-driver.d.ts.map +1 -1
- package/dist/{library-publish-FGXF5TJO.js → library-publish-PICMDSB2.js} +73 -37
- package/dist/library-publish-PICMDSB2.js.map +1 -0
- package/dist/open-library-OG457THY.js +40 -0
- package/dist/{open-library-P3D337NH.js.map → open-library-OG457THY.js.map} +1 -1
- package/dist/open-registry-ZUZJ7MS7.js +32 -0
- package/dist/{open-registry-Z3P2X2AB.js.map → open-registry-ZUZJ7MS7.js.map} +1 -1
- package/dist/paths-FQ64OLJG.js +22 -0
- package/dist/{paths-JKEKXM52.js.map → paths-FQ64OLJG.js.map} +1 -1
- package/dist/{plugin-store-WI4MZJLP.js → plugin-store-MPAMD5OT.js} +10 -10
- package/dist/{plugin-store-WI4MZJLP.js.map → plugin-store-MPAMD5OT.js.map} +1 -1
- package/dist/project-2GFT5LEZ.js +41 -0
- package/dist/{project-WFUDVYNN.js.map → project-2GFT5LEZ.js.map} +1 -1
- package/dist/resolver/index.js +9 -9
- package/dist/runner/index.js +40 -41
- package/dist/runner/src/logging-bootstrap.d.ts +6 -0
- package/dist/runner/src/logging-bootstrap.d.ts.map +1 -1
- package/dist/runner/src/reconfigure-handler.d.ts +38 -17
- package/dist/runner/src/reconfigure-handler.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/runner/src/session-capability-wiring.d.ts +0 -2
- package/dist/runner/src/session-capability-wiring.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +15 -15
- package/dist/sdk/bridge.js +16 -17
- package/dist/sdk/core.js +8 -8
- package/dist/sdk/flow.js +12 -12
- package/dist/sdk/index.js +68 -45
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/resolver.js +9 -9
- package/dist/sdk/runner.js +40 -41
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/src/agent-session.d.ts +8 -0
- package/dist/sdk/src/agent-session.d.ts.map +1 -1
- package/dist/sdk/store.js +2 -1
- package/dist/sdk/types.js +1 -1
- package/dist/session/index.js +2 -2
- package/dist/{setup-RAMLTORM.js → setup-WHMCSIF2.js} +26 -27
- package/dist/setup-WHMCSIF2.js.map +1 -0
- package/dist/skills-TVO26Y4V.js +26 -0
- package/dist/{skills-EOHZ2DZ4.js.map → skills-TVO26Y4V.js.map} +1 -1
- package/dist/source-LKOFTOEK.js +41 -0
- package/dist/{source-FYVSFYEI.js.map → source-LKOFTOEK.js.map} +1 -1
- package/dist/{source-manifest-publish-4FPIPPLV.js → source-manifest-publish-L5J3QXER.js} +27 -27
- package/dist/{source-manifest-publish-4FPIPPLV.js.map → source-manifest-publish-L5J3QXER.js.map} +1 -1
- package/dist/store/index.js +2 -1
- package/dist/store/src/store.d.ts +8 -5
- package/dist/store/src/store.d.ts.map +1 -1
- package/dist/tui/index.js +40 -41
- package/dist/tui/index.js.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/manifests.js +1 -1
- package/dist/types/src/ask-slots.d.ts +68 -0
- package/dist/types/src/ask-slots.d.ts.map +1 -0
- package/dist/types/src/delivery.d.ts.map +1 -1
- package/dist/types/src/events.d.ts +29 -1
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/manifests/index.d.ts +1 -1
- package/dist/types/src/manifests/index.d.ts.map +1 -1
- package/dist/types/src/manifests/preset.d.ts +4 -0
- package/dist/types/src/manifests/preset.d.ts.map +1 -1
- package/dist/types/src/version.d.ts +12 -1
- package/dist/types/src/version.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +32 -33
- package/dist/workspace-plugin/adapters/omp.js +14 -14
- package/dist/workspace-plugin/index.js +2 -2
- package/package.json +1 -1
- package/dist/asset-feeds-K36CR52Q.js.map +0 -1
- package/dist/chunk-6C654TFI.js.map +0 -1
- package/dist/chunk-74EEFB52.js.map +0 -1
- package/dist/chunk-BTK7ECLH.js.map +0 -1
- package/dist/chunk-CWM3MYGX.js.map +0 -1
- package/dist/chunk-D5HOETOB.js.map +0 -1
- package/dist/chunk-DFFD4BFG.js.map +0 -1
- package/dist/chunk-DMLDYFDS.js.map +0 -1
- package/dist/chunk-EINLFFP6.js +0 -59
- package/dist/chunk-EINLFFP6.js.map +0 -1
- package/dist/chunk-EU3Q5AQ4.js.map +0 -1
- package/dist/chunk-FRHE7FFB.js.map +0 -1
- package/dist/chunk-G67BOI2J.js.map +0 -1
- package/dist/chunk-GIC3G5YG.js.map +0 -1
- package/dist/chunk-IZLQ4GDO.js.map +0 -1
- package/dist/chunk-JMKB7IB4.js.map +0 -1
- package/dist/chunk-LBQ4BBX4.js.map +0 -1
- package/dist/chunk-LCU5U5IW.js.map +0 -1
- package/dist/chunk-LXY4BUA3.js.map +0 -1
- package/dist/chunk-MKLBK7HI.js.map +0 -1
- package/dist/chunk-O7VPNKYN.js.map +0 -1
- package/dist/chunk-OKGUDNDT.js.map +0 -1
- package/dist/chunk-QCI6D7E4.js.map +0 -1
- package/dist/chunk-SZWRPEF7.js.map +0 -1
- package/dist/chunk-TTPSDC2G.js.map +0 -1
- package/dist/chunk-VOOI7B2L.js.map +0 -1
- package/dist/chunk-XBSQ4KMC.js.map +0 -1
- package/dist/connectors-SSOTIDHT.js +0 -45
- package/dist/library-publish-FGXF5TJO.js.map +0 -1
- package/dist/open-library-P3D337NH.js +0 -40
- package/dist/open-registry-Z3P2X2AB.js +0 -32
- package/dist/paths-JKEKXM52.js +0 -22
- package/dist/project-WFUDVYNN.js +0 -41
- package/dist/setup-RAMLTORM.js.map +0 -1
- package/dist/skills-EOHZ2DZ4.js +0 -26
- package/dist/source-FYVSFYEI.js +0 -41
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../cli/src/store-auth.ts","../cli/src/store-client.ts","../cli/src/commands/publish-core.ts"],"names":["readFileSync"],"mappings":";;;;;;;AAsBA,SAAS,YAAA,GAAwD;AAC/D,EAAA,MAAM,QAAA,GAAW,WAAA,CAAY,EAAE,CAAA,CAAE,SAAS,WAAW,CAAA;AACrD,EAAA,MAAM,SAAA,GAAY,WAAW,QAAQ,CAAA,CAAE,OAAO,QAAQ,CAAA,CAAE,OAAO,WAAW,CAAA;AAC1E,EAAA,OAAO,EAAE,UAAU,SAAA,EAAU;AAC/B;AAUA,SAAS,kBAAkB,GAAA,EAAqB;AAC9C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC/B;AAQO,SAAS,mBAAA,GAAuC;AACrD,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,iBAAA,CAAkB,OAAA,CAAQ,GAAA,CAAI,uBAAuB,wBAAwB,CA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BAAA,EAAqB,MAAA,CAAO,MAAM,CAAA,CAAA,CAAA,IAC7D,KAAK,MAAA,GAAS,CAAA,EAAA,EAAK,KAAK,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,EAAA;AAAA,WAC5C;AACA,UAAA;AAAA,QACF;AAAA,MACF;AACA,MAAA,SAAA,CAAU,IAAA,CAAK,MAAA,CAAO,CAAA,CAAE,IAAA,EAAM,OAAA,CAAQ,SAAA,CAAU,kBAAA,EAAoB,CAAA,CAAE,IAAA,EAAM,CAAA,CAAE,OAAO,CAAC,CAAA;AAAA,IACxF,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,kBAAA,EAAqB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OAC5F;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,UAAA,EAAa,SAAA,CAAU,MAAM,CAAA,UAAA,CAAY,CAAA;AAC/C,EAAA,KAAA,MAAW,CAAA,IAAK,SAAA,EAAW,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC3C,EAAA,OAAO,EAAE,SAAA,EAAU;AACrB","file":"chunk-LXY4BUA3.js","sourcesContent":["/**\n * Keycloak Device Authorization Grant (RFC 8628) for the store CLI: a public\n * device-flow client (`skaile-store-cli`) issues a plain realm JWT the store's\n * `AuthGuard` accepts — a CLI can't use the storefront's confidential browser\n * client. Tokens cache at `~/.skaile/auth.json` (0600, shared with `store/cli`);\n * `getAccessToken` refreshes transparently. All targets are env-overridable.\n *\n * @docLink cli/dev-guide#store-auth\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { globalSkaileDir } from \"@skaile/workspaces/core\";\n\n/**\n * A PKCE (RFC 7636) `code_verifier` + its S256 `code_challenge`. Keycloak\n * enforces PKCE on the `skaile-store-cli` device flow (the device-authorization\n * request 400s with \"Missing parameter: code_challenge_method\" otherwise), so\n * every `deviceLogin` mints a fresh pair: the challenge goes on the device-auth\n * request, the verifier on the matching token poll. `base64url` (no padding)\n * per the spec.\n */\nfunction makePkcePair(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString(\"base64url\");\n const challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\");\n return { verifier, challenge };\n}\n\n/** Resolved auth targets — every field has a prod default, all env-overridable. */\nexport interface StoreAuthConfig {\n keycloakUrl: string;\n realm: string;\n clientId: string;\n authFile: string;\n}\n\nfunction trimTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/**\n * Load the auth config. Defaults target the production store\n * (`auth.skaile.ai`, realm `skaile-store`, public client `skaile-store-cli`);\n * override with `SKAILE_KEYCLOAK_URL` / `SKAILE_STORE_REALM` /\n * `SKAILE_STORE_CLI_CLIENT` / `SKAILE_AUTH_FILE` for dev or a preview deploy.\n */\nexport function loadStoreAuthConfig(): StoreAuthConfig {\n return {\n keycloakUrl: trimTrailingSlash(process.env.SKAILE_KEYCLOAK_URL ?? \"https://auth.skaile.ai\"),\n realm: process.env.SKAILE_STORE_REALM ?? \"skaile-store\",\n clientId: process.env.SKAILE_STORE_CLI_CLIENT ?? \"skaile-store-cli\",\n authFile: process.env.SKAILE_AUTH_FILE ?? join(globalSkaileDir(), \"auth.json\"),\n };\n}\n\n/** Keycloak OIDC endpoints derived from the realm base. */\nfunction oidc(config: StoreAuthConfig): { deviceAuth: string; token: string } {\n const base = `${config.keycloakUrl}/realms/${config.realm}/protocol/openid-connect`;\n return { deviceAuth: `${base}/auth/device`, token: `${base}/token` };\n}\n\nexport interface StoredAuth {\n access_token: string;\n refresh_token?: string;\n /** Epoch ms when the access token expires (with a safety margin already applied). */\n expires_at: number;\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n error?: string;\n error_description?: string;\n}\n\ninterface DeviceAuthResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n interval?: number;\n expires_in: number;\n}\n\n/** Refresh this many ms before real expiry so an in-flight call never 401s. */\nconst EXPIRY_MARGIN_MS = 30_000;\n\n/** Injectable seams so the poll loop is unit-testable without real time or network. */\nexport interface AuthDeps {\n fetchImpl?: typeof fetch;\n sleep?: (ms: number) => Promise<void>;\n /** Called once with the verification URL + user code (default: write to stderr). */\n onPrompt?: (url: string, userCode: string) => void;\n}\n\nfunction readAuth(config: StoreAuthConfig): StoredAuth | null {\n try {\n const parsed = JSON.parse(readFileSync(config.authFile, \"utf-8\"));\n // Reject a corrupt / hand-edited file rather than treat it as a session.\n if (parsed && typeof parsed.access_token === \"string\") return parsed as StoredAuth;\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * The caller's store identity, decoded LOCALLY from the cached token's JWT\n * payload (no network, no signature check — this is an author-side hint, not an\n * authorization decision). Returns `null` when not signed in or the token is\n * unreadable. `githubLogin` is the verified GitHub handle (the preferred\n * publisher namespace); `username` is the Keycloak `preferred_username`.\n */\nexport function getStoreIdentity(\n config: StoreAuthConfig = loadStoreAuthConfig(),\n): { username?: string; githubLogin?: string } | null {\n const auth = readAuth(config);\n if (!auth) return null;\n try {\n const payload = auth.access_token.split(\".\")[1];\n const json = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf-8\"));\n const username =\n typeof json.preferred_username === \"string\" ? json.preferred_username : undefined;\n const githubLogin = typeof json.github_login === \"string\" ? json.github_login : undefined;\n return username || githubLogin ? { username, githubLogin } : null;\n } catch {\n return null;\n }\n}\n\nfunction writeAuth(config: StoreAuthConfig, auth: StoredAuth): void {\n mkdirSync(dirname(config.authFile), { recursive: true });\n writeFileSync(config.authFile, JSON.stringify(auth, null, 2), { mode: 0o600 });\n chmodSync(config.authFile, 0o600);\n}\n\n/** Remove the cached session (sign out). */\nexport function logout(config: StoreAuthConfig): void {\n try {\n rmSync(config.authFile);\n } catch {\n // already absent — nothing to do\n }\n}\n\n/** True when a cached, well-formed session exists (validity/refresh resolved on use). */\nexport function hasStoredAuth(config: StoreAuthConfig): boolean {\n return readAuth(config) !== null;\n}\n\nfunction tokenToStored(token: TokenResponse): StoredAuth {\n return {\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n expires_at: Date.now() + (token.expires_in ?? 300) * 1000 - EXPIRY_MARGIN_MS,\n };\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nfunction defaultPrompt(url: string, userCode: string): void {\n process.stderr.write(\n `\\nTo sign in, open:\\n\\n ${url}\\n\\nand enter the code: ${userCode}\\n\\nWaiting for approval…\\n`,\n );\n}\n\n/**\n * Run the device flow to completion, persisting tokens on success. Prints the\n * verification URL + user code for the operator to approve in a browser.\n */\nexport async function deviceLogin(\n config: StoreAuthConfig,\n deps: AuthDeps = {},\n): Promise<StoredAuth> {\n const fetchImpl = deps.fetchImpl ?? fetch;\n const sleep = deps.sleep ?? defaultSleep;\n const onPrompt = deps.onPrompt ?? defaultPrompt;\n const endpoints = oidc(config);\n const pkce = makePkcePair();\n\n const deviceRes = await fetchImpl(endpoints.deviceAuth, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n scope: \"openid profile\",\n code_challenge: pkce.challenge,\n code_challenge_method: \"S256\",\n }),\n });\n if (!deviceRes.ok) {\n throw new Error(\n `Device authorization request failed (${deviceRes.status}): ${await deviceRes.text()}`,\n );\n }\n const device = (await deviceRes.json()) as DeviceAuthResponse;\n\n onPrompt(device.verification_uri_complete ?? device.verification_uri, device.user_code);\n\n const intervalMs = (device.interval ?? 5) * 1000;\n const deadline = Date.now() + device.expires_in * 1000;\n let waitMs = intervalMs;\n\n while (Date.now() < deadline) {\n await sleep(waitMs);\n const tokenRes = await fetchImpl(endpoints.token, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: device.device_code,\n client_id: config.clientId,\n code_verifier: pkce.verifier,\n }),\n });\n const token = (await tokenRes.json()) as TokenResponse;\n if (tokenRes.ok) {\n const stored = tokenToStored(token);\n writeAuth(config, stored);\n return stored;\n }\n // RFC 8628 §3.5 pending / slow-down handling.\n if (token.error === \"authorization_pending\") continue;\n if (token.error === \"slow_down\") {\n waitMs += 5_000;\n continue;\n }\n throw new Error(`Sign-in failed: ${token.error_description ?? token.error ?? \"unknown error\"}`);\n }\n throw new Error(\"Sign-in timed out before approval.\");\n}\n\n/** Exchange a refresh token for a fresh access token; persist on success. */\nasync function refresh(\n config: StoreAuthConfig,\n refreshToken: string,\n fetchImpl: typeof fetch,\n): Promise<StoredAuth> {\n const res = await fetchImpl(oidc(config).token, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: config.clientId,\n }),\n });\n const token = (await res.json()) as TokenResponse;\n if (!res.ok) {\n throw new Error(\n `Token refresh failed: ${token.error_description ?? token.error ?? res.status}`,\n );\n }\n const stored = tokenToStored(token);\n writeAuth(config, stored);\n return stored;\n}\n\n/**\n * Return a valid access token, refreshing if it is expired (or about to). Throws\n * a clear \"run `skaile store login`\" error when there is no usable session.\n */\nexport async function getAccessToken(\n config: StoreAuthConfig,\n deps: AuthDeps = {},\n): Promise<string> {\n const fetchImpl = deps.fetchImpl ?? fetch;\n const auth = readAuth(config);\n if (!auth) throw new Error(\"Not signed in. Run `skaile store login` first.\");\n if (Date.now() < auth.expires_at) return auth.access_token;\n if (!auth.refresh_token) throw new Error(\"Session expired. Run `skaile store login` again.\");\n try {\n return (await refresh(config, auth.refresh_token, fetchImpl)).access_token;\n } catch {\n throw new Error(\"Session expired and refresh failed. Run `skaile store login` again.\");\n }\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { globalSettingsPath, mapLegacyFields } from \"@skaile/workspaces/core\";\nimport { type AuthDeps, getAccessToken, hasStoredAuth, loadStoreAuthConfig } from \"./store-auth.ts\";\n\n/**\n * Connection configuration for the AI Asset Store API. `jwt` is normally left\n * null here and filled per-call by the caller from {@link getStoreToken} (the\n * device-flow session); it stays on the type for the `{ ...config, jwt }` spread.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport interface StoreConfig {\n url: string;\n jwt: string | null;\n}\n\n/**\n * Read the store API base URL (settings `storeUrl` → `SKAILE_STORE_URL` →\n * default). Auth is not read here — it lives in the device-flow session; see\n * {@link getStoreToken}.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport function getStoreConfig(): StoreConfig {\n const settingsPath = globalSettingsPath();\n let settings: Record<string, any> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = mapLegacyFields(JSON.parse(readFileSync(settingsPath, \"utf-8\")));\n } catch {\n settings = {};\n }\n }\n return {\n url: settings.storeUrl ?? process.env.SKAILE_STORE_URL ?? \"https://api.skaile.store\",\n jwt: null,\n };\n}\n\n/**\n * Return a valid store access token (Keycloak device-flow session, refreshed if\n * needed). Throws a \"run `skaile store login`\" error when there is no session.\n * This is the auth source for every `/api/v1/*` publisher call.\n */\nexport function getStoreToken(deps?: AuthDeps): Promise<string> {\n return getAccessToken(loadStoreAuthConfig(), deps);\n}\n\n/**\n * Make an authenticated HTTP request to the store REST API.\n *\n * @param config - Store connection config (URL + auth token).\n * @param path - API path (e.g. `/api/assets`).\n * @param opts - Optional method, body, query params, extra headers, and\n * `timeoutMs` (default 1500). Publisher calls pass a longer timeout because\n * they trigger server-side clone/sync work.\n * @returns Parsed JSON response body.\n * @docLink cli/dev-guide#store-client\n */\nexport async function storeFetch<T = any>(\n config: StoreConfig,\n path: string,\n opts?: {\n method?: string;\n body?: unknown;\n params?: Record<string, string>;\n headers?: Record<string, string>;\n timeoutMs?: number;\n },\n): Promise<T> {\n let url = `${config.url}${path}`;\n if (opts?.params) {\n const sp = new URLSearchParams(opts.params);\n url += `?${sp}`;\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n ...(opts?.headers ?? {}),\n };\n if (config.jwt) {\n headers.Authorization = `Bearer ${config.jwt}`;\n }\n\n const fetchOpts: RequestInit = {\n method: opts?.method ?? \"GET\",\n headers,\n };\n if (opts?.body) {\n fetchOpts.body = JSON.stringify(opts.body);\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), opts?.timeoutMs ?? 1_500);\n try {\n const res = await fetch(url, { ...fetchOpts, signal: controller.signal });\n if (!res.ok) {\n const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));\n // Prefer the store's human-readable `message` (e.g. \"Namespace '@x' is\n // reserved … Sign in with GitHub to claim it\") over the bare `error` code\n // (`UNPROCESSABLE_CONTENT`) — the message is the actionable part.\n const b = body as { message?: string; error?: string };\n throw new Error(b.message ?? b.error ?? `Store API error: ${res.status}`);\n }\n return res.json() as Promise<T>;\n } finally {\n clearTimeout(timeout);\n }\n}\n\n/**\n * Return `true` when a store session exists (a Keycloak device-flow token cached\n * at `~/.skaile/auth.json`). Validity/refresh is resolved on use via\n * {@link getStoreToken}.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport function isStoreAuthenticated(): boolean {\n return hasStoredAuth(loadStoreAuthConfig());\n}\n","/**\n * Shared store-interaction core for the two publish front-ends — the curator\n * sidecar flow (`source manifest publish`) and the first-party library flow\n * (`library publish`). Both differ only in their git side-effects + how they\n * resolve the source repo; the store orchestration below (register → sync →\n * candidates → per-asset preview+publish) is identical.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * so the orchestration stays unit/integration-testable without a live store.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport type { SkPublishManifest } from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport type { PublisherClient } from \"../store-publisher.ts\";\n\n/**\n * One-line rendering of a namespace-availability probe for a `--dry-run` plan.\n * The `message` is store-authored (identical to what a real publish would echo)\n * — we only prepend a status glyph so the reader sees green/amber/red at a\n * glance without the CLI re-deriving any authorization logic.\n */\nexport function formatNamespaceAvailability(a: {\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n message: string;\n}): string {\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return `${S.ok(\"✓\")} ${a.message}`;\n case \"claimable-by-you\":\n return `${S.warn(\"!\")} ${a.message}`;\n default:\n return `${S.err(\"✗\")} ${a.message}`;\n }\n}\n\n/**\n * Preflight the target namespace against the store's availability probe BEFORE a\n * publish does any irreversible work (a public git push). Returns `{ ok: false }`\n * with a guided message for `reserved` (not yours) and `claimable-by-you` (must\n * claim first) — the two states a real publish would reject — so the caller can\n * abort with actionable guidance instead of a raw 422 after pushing bytes.\n *\n * The probe is advisory: any failure (offline, older store) returns `{ ok: true }`\n * so the store stays the authority and a valid publish is never blocked.\n */\nexport async function preflightNamespace(\n client: PublisherClient,\n namespace: string,\n): Promise<{ ok: boolean; message?: string }> {\n let a: Awaited<ReturnType<PublisherClient[\"namespaceAvailability\"]>>;\n try {\n a = await client.namespaceAvailability(namespace);\n } catch {\n return { ok: true };\n }\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return { ok: true };\n case \"claimable-by-you\":\n return {\n ok: false,\n message:\n `@${namespace} isn't yours yet — claim it in the store first` +\n `${a.claimMethod ? ` (${a.claimMethod})` : \"\"}, then re-run. ${a.message}`,\n };\n default: // reserved, or any unrecognized future status (fail safe → block)\n return { ok: false, message: `Cannot publish under @${namespace} — ${a.message}` };\n }\n}\n\n/** One candidate row shape the matcher operates on (kind + name are the key). */\ninterface CandidateLike {\n kind: string;\n name: string;\n}\n\n/**\n * Keep only candidates whose `(kind, name)` pair is declared in the manifest.\n * The backend may merge extra assets from the base repo into the candidate\n * list; a publish only touches what the manifest curated/declared.\n */\nexport function matchCandidatesToManifest<T extends CandidateLike>(\n candidates: T[],\n manifest: SkPublishManifest,\n): T[] {\n const wanted = new Set((manifest.assets ?? []).map((a) => `${a.kind}:${a.name}`));\n return candidates.filter((c) => wanted.has(`${c.kind}:${c.name}`));\n}\n\n/** A canonical ref string `kind:@publisher/name[#version]` for reporting. */\nexport function refFor(kind: string, publisher: string, name: string, version?: string): string {\n const base = `${kind}:@${publisher}/${name}`;\n return version ? `${base}#${version}` : base;\n}\n\n/** Placeholder namespace shown when neither the asset nor the manifest names a publisher. */\nconst UNSET_NAMESPACE = \"<manifest publisher>\";\n\n/**\n * The publisher namespace one manifest asset publishes under:\n * `assets[].publisher` first, else the manifest's top-level `publisher` —\n * the same priority discovery applies when it indexes the asset. `undefined`\n * when neither is declared.\n */\nexport function assetNamespace(\n asset: { publisher?: string },\n manifest: SkPublishManifest,\n): string | undefined {\n return asset.publisher ?? manifest.publisher;\n}\n\n/**\n * The version-less canonical ref of one manifest asset for messages:\n * `kind:@<publisher>/<name>` (`assets[].publisher ?? publisher`), or the bare\n * `kind:name` when the manifest declares no namespace.\n */\nexport function assetEntryRef(\n asset: { kind: string; name: string; publisher?: string },\n manifest: SkPublishManifest,\n): string {\n const ns = assetNamespace(asset, manifest);\n return ns ? refFor(asset.kind, ns, asset.name) : `${asset.kind}:${asset.name}`;\n}\n\n/**\n * Every distinct namespace the manifest's assets (optionally narrowed to\n * `assetName`) publish under, in first-seen order. A manifest whose assets\n * carry no namespace at all falls back to its top-level `publisher` so an\n * empty inventory still reports the namespace it would claim.\n */\nexport function manifestNamespaces(manifest: SkPublishManifest, assetName?: string): string[] {\n const out = new Set<string>();\n for (const a of manifest.assets ?? []) {\n if (assetName && a.name !== assetName) continue;\n const ns = assetNamespace(a, manifest);\n if (ns) out.add(ns);\n }\n if (out.size === 0 && manifest.publisher) out.add(manifest.publisher);\n return [...out];\n}\n\n/**\n * The canonical refs a publish would produce, one per manifest asset (optionally\n * narrowed to `assetName`), each under its own `assets[].publisher ?? publisher`.\n */\nexport function plannedRefs(manifest: SkPublishManifest, assetName?: string): string[] {\n return (manifest.assets ?? [])\n .filter((a) => !assetName || a.name === assetName)\n .map((a) =>\n refFor(\n a.kind,\n assetNamespace(a, manifest) ?? UNSET_NAMESPACE,\n a.name,\n a.version ?? manifest.version,\n ),\n );\n}\n\n/** The bare asset name from a `kind:@publisher/name#version` ref or a plain name. */\nexport function bareName(ref: string): string {\n const afterKind = ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref;\n const afterScope = afterKind.includes(\"/\")\n ? afterKind.slice(afterKind.indexOf(\"/\") + 1)\n : afterKind;\n return afterScope.split(\"#\")[0];\n}\n\n/**\n * Poll a job until it leaves `running` or the deadline passes. Returns the last\n * observed state — the caller MUST treat a still-`running` result as a timeout\n * (not success), since it means the deadline was hit before the job finished.\n */\nexport async function pollJob(\n client: PublisherClient,\n jobId: string,\n intervalMs = 1_500,\n timeoutMs = 60_000,\n): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }> {\n const deadline = Date.now() + timeoutMs;\n let job = await client.jobGet(jobId);\n while (job.status === \"running\" && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, intervalMs));\n job = await client.jobGet(jobId);\n }\n return job;\n}\n\n/**\n * True when a `sourcesAdd` rejection is a duplicate-URL conflict (the source is\n * already registered) — the only error the publish flow recovers from by looking\n * the existing row up. Every other failure (auth, 5xx, network) must propagate.\n */\nexport function isDupSourceError(err: unknown): boolean {\n const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n return /\\b409\\b|conflict|duplicate|already exists|already registered|unique/.test(msg);\n}\n\n/**\n * Register + sync the source, then publish its curated/declared candidates —\n * the store-side steps shared by both publish front-ends. Git side-effects (the\n * sidecar push, or the library commit+push) happen in the caller *before* this;\n * this function is purely store interaction.\n *\n * The sidecar front-end passes `sidecar` (so `sourcesAdd` carries the sidecar\n * pin); the library front-end omits it (the source repo IS the manifest host).\n * `assetName`, when set, narrows publication to the single candidate of that\n * name. Fatal store states (`sourcesAdd` non-dup failure) surface; sync failures\n * and empty candidate sets `process.exit(1)` with the same messages as before.\n */\nexport async function publishToStore(opts: {\n sourceUrl: string;\n ref: string;\n sidecar?: { url: string; ref: string };\n manifest: SkPublishManifest;\n assetName?: string;\n client: PublisherClient;\n}): Promise<{ published: string[] }> {\n const { sourceUrl, ref, sidecar, manifest, assetName, client: pub } = opts;\n\n let sourceId: string;\n try {\n const added = await pub.sourcesAdd({\n url: sourceUrl,\n ref,\n ...(sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {}),\n // Publish under the manifest's declared namespace; the store resolves a\n // claimed Publisher when it differs from the caller's login, else defaults\n // to `@<username>`. Omitted when the manifest carries no publisher.\n ...(manifest.publisher ? { namespace: manifest.publisher } : {}),\n });\n sourceId = added.id;\n } catch (err) {\n // Only a duplicate-url conflict is recoverable (source already registered);\n // auth/5xx/network failures must surface, not silently reuse a stale row.\n if (!isDupSourceError(err)) throw err;\n const rows = await pub.sourcesList();\n const found = rows.find((r) => r.url === sourceUrl);\n if (!found) {\n throw new Error(\n `Source ${sourceUrl} looked already-registered but no owned row matched: ` +\n `${err instanceof Error ? err.message : String(err)}`,\n );\n }\n sourceId = found.id;\n }\n\n const { jobId } = await pub.sourceSync(sourceId);\n const job = await pollJob(pub, jobId);\n if (job.status === \"failed\" || job.status === \"cancelled\") {\n const failed = (job.items ?? []).filter((i) => i.status === \"failed\");\n for (const i of failed) logErr(`sync: ${i.label}: ${i.error ?? \"failed\"}`);\n logErr(`Source sync ${job.status}.`);\n process.exit(1);\n }\n // A still-`running` job means the poll deadline was hit — do NOT proceed on an\n // unfinished sync (it would read incomplete candidates).\n if (job.status === \"running\") {\n logErr(\"Source sync timed out before completing — re-run `publish`, or check the store.\");\n process.exit(1);\n }\n\n let candidates = matchCandidatesToManifest(await pub.sourceCandidates(sourceId), manifest);\n if (assetName) candidates = candidates.filter((c) => c.name === assetName);\n if (candidates.length === 0) {\n logWarn(\"No candidates discovered — check the manifest and the source ref.\");\n process.exit(1);\n }\n\n const published: string[] = [];\n for (const c of candidates) {\n try {\n const preview = await pub.assetPreview(c.id);\n const res = await pub.assetPublish(c.id, { ref, files: preview.discoveredFiles });\n // Publish is async — wait for the job so we only report refs that actually\n // landed, not ones whose import is still in flight or about to fail.\n if (res.jobId) {\n const pubJob = await pollJob(pub, res.jobId);\n if (pubJob.status !== \"succeeded\") {\n const errs = (pubJob.items ?? [])\n .filter((i) => i.status === \"failed\")\n .map((i) => i.error)\n .filter(Boolean);\n logWarn(\n `Publish of ${c.kind}:${c.name} did not succeed (${pubJob.status})` +\n (errs.length ? `: ${errs.join(\"; \")}` : \"\"),\n );\n continue;\n }\n }\n published.push(refFor(c.kind, preview.candidate.publisherNamespace, c.name, c.version));\n } catch (err) {\n logWarn(\n `Failed to publish ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Published ${published.length} asset(s):`);\n for (const r of published) logInfo(` ${r}`);\n return { published };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;;AAiEA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AAEjD,IAAM,0BAAA,uBAAiC,GAAA,CAAI;AAAA,EACzC,eAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,eAAA;AAAA,E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,KAAA,CAA+B,OAAA,IAChC,aAAA;AACF,QAAA,IAAA,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-MKLBK7HI.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n findKindDirs,\n isValidAssetName,\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution, FlowPromptEvent } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n findFlowFileInRoots,\n FLOW_FILE_EXTENSIONS,\n type FlowLookupMiss,\n flowLookupRoots,\n loadFlow,\n} from \"./engine/index.js\";\nimport { flowSkillVersionPins } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.js\";\nimport { driveOrchestratorTurn } from \"./orchestrator-turn.js\";\nimport { renderStimulusPrompt, type TurnStimulus } from \"./prompt-fragments.js\";\nimport { SessionSubpromptRunner } from \"./subprompt-runner.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent harness. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n */\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs. Defaults to true; first-class gate nodes are never bypassed. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: wsConfigEarly.logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown, _signal?: AbortSignal, callId?: string) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId, callId }),\n };\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n // Same endpoints and credentials the session driver used: the registry\n // and the credential env `createAgentSession` already resolved — not a\n // new resolution, not a new secret channel.\n const subpromptRunner = new SessionSubpromptRunner({\n driverType: agentSession.driverType,\n sessionModel: agentSession.model,\n workspaceDir: opts.projectDir,\n registry: agentSession.registry,\n credentialEnv: agentSession.credentialEnv,\n ...(agentSession.modelRef ? { modelRef: agentSession.modelRef } : {}),\n });\n let driverStarted = false;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It hands the turn to\n // `driveOrchestratorTurn`, which rebuilds the five-section prompt so the\n // agent sees the same flow context the legacy orchestrator produced — and\n // announces it, so a CLI consumer's `onEvent` stream carries the prompt too.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n // Same widening the `state_changed` forwarder below performs: `onEvent` is\n // typed against the bridge's driver-level union, which has no case for a\n // runtime-level event.\n const emitFlowPrompt = (event: FlowPromptEvent): void => {\n opts.onEvent?.(event as unknown as AgentEvent);\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n subpromptRunner,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow: childFlow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n });\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals. It is\n // discarded in favour of the structured stimulus, which\n // `driveOrchestratorTurn` rebuilds the full prompt from; that keeps the\n // prompt shape stable and the structured form already contains\n // everything the fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n nodeExecutor,\n subpromptRunner,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: wsConfigEarly.logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flowSkillVersionPins(flow);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.skillId;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const checks = validateFlowVersions(pinnedNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\n/**\n * Assert `found` sits inside one of `roots`.\n *\n * A backstop, not the primary control: `isValidAssetName` already rejects every\n * id containing a separator, and `findFlowFileInRoots` skips any candidate that\n * escapes its search dir. So on today's code this cannot fire — it is here to\n * fail loudly rather than silently if a future lookup stops enforcing\n * containment itself. Widening the accepted extensions must never widen which\n * paths are reachable, and this is the line that keeps that honest.\n */\nfunction assertContainedInAnyRoot(found: string, roots: string[], flowId: string): void {\n const resolved = path.resolve(found);\n const inside = roots.some((root) => {\n const relative = path.relative(path.resolve(root), resolved);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n if (!inside) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n}\n\n/** One line per near-miss: a file that is right there but was still rejected. */\nfunction describeMisses(misses: FlowLookupMiss[], heading: string): string {\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const miss of misses) {\n if (seen.has(miss.path)) continue;\n seen.add(miss.path);\n lines.push(\n miss.reason === \"id-mismatch\"\n ? ` ${miss.path}: declares id ${JSON.stringify(miss.declaredId ?? \"\")}`\n : ` ${miss.path}: could not be parsed (${miss.error ?? \"unknown error\"})`,\n );\n }\n return lines.length > 0 ? `\\n${heading}\\n${lines.join(\"\\n\")}` : \"\";\n}\n\n/**\n * Resolve one flow identity through the CLI/serve host's normal lookup order —\n * the same roots and filenames `skaile run` and `flow list` use, via\n * {@link flowLookupRoots} / {@link findFlowFileInRoots}. Resolution is by the\n * **declared** `id`, not by filename.\n *\n * @throws {Error} When `flowId` is not a canonical asset name, when no file\n * declares it, or when a match somehow resolves outside every lookup root.\n */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n // Sub-flow targets and resumed session records are the two callers, so an\n // identity that is not canonical is a bug in the caller, not a missing file.\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const roots = flowLookupRoots(projectDir);\n const misses: FlowLookupMiss[] = [];\n const found = findFlowFileInRoots(flowId, roots, { onMiss: (m) => misses.push(m) });\n if (found) {\n assertContainedInAnyRoot(found, roots, flowId);\n return found;\n }\n\n // A file that is present but unparseable is a different problem from a missing\n // one, and \"not found\" is the wrong headline for it — that exact misdirection\n // is what this change exists to remove, so don't reintroduce it here.\n if (misses.length > 0 && misses.every((m) => m.reason === \"unparseable\")) {\n throw new Error(\n `Flow ${flowId} was found but could not be loaded.` + describeMisses(misses, \"Candidates:\"),\n );\n }\n\n const shown = roots.slice(0, 3).join(\", \");\n const more = roots.length > 3 ? \", …\" : \"\";\n // Spelled from FLOW_FILE_EXTENSIONS so the message cannot drift from the\n // candidate list the lookup actually probes.\n const accepted = FLOW_FILE_EXTENSIONS.map((ext) => `${flowId}${ext}`).join(\" | \");\n throw new Error(\n `Flow not found: ${flowId}. Searched ${roots.length} root(s) (${shown || \"none\"}${more}) ` +\n `for ${accepted} — flat, or inside a ${flowId}/ directory.` +\n describeMisses(misses, \"Near misses:\"),\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID in any `skills/` directory under ai-assets */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const skillsDir of findKindDirs(aiResourcesDir, \"skills\")) {\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on an `error` that is not an in-place retry).\n * Identical contract to the legacy `awaitAgentEnd` helper from\n * `flow-orchestrator.ts`. Phase 4 lifts the helper into `run-flow.ts` because\n * the bus now owns turn driving. Exported for tests only.\n */\nexport function awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n // An in-place retry replays this same turn; its own end settles it.\n else if (event.type === \"error\" && event.retrying !== true) {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../core/src/models.ts"],"names":[],"mappings":";;;AAuCO,SAAS,SAAS,CAAA,EAAuB;AAC9C,EAAA,MAAM,CAAA,GAAI,CAAA,CAAE,OAAA,CAAQ,GAAG,CAAA;AACvB,EAAA,IAAI,MAAM,EAAA,EAAI;AACZ,IAAA,MAAM,OAAO,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,EAAE,IAAA,EAAK;AAChC,IAAA,MAAM,OAAO,CAAA,CAAE,KAAA,CAAM,CAAA,GAAI,CAAC,EAAE,IAAA,EAAK;AACjC,IAAA,OAAO,EAAE,MAAM,IAAA,EAAK;AAAA,EACtB;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,CAAA,CAAE,MAAK,EAAE;AACzC;AASO,SAAS,SAAS,CAAA,EAAuB;AAC9C,EAAA,OAAO,CAAA,EAAG,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,EAAE,IAAI,CAAA,CAAA;AAC5B;AAsEO,SAAS,aAAa,CAAA,EAA0C;AACrE,EAAA,MAAM,UAAU,CAAA,CAAE,YAAA;AAClB,EAAA,MAAM,IAAA,GAAO,MAAM,OAAA,CAAQ,OAAO,IAAK,OAAA,CAAqB,MAAA,CAAO,OAAO,CAAA,GAAI,EAAC;AAC/E,EAAA,MAAM,KAAA,GAAsB;AAAA,IAC1B,IAAA,EAAM,MAAA,CAAO,CAAA,CAAE,IAAA,IAAQ,EAAE,CAAA;AAAA,IACzB,IAAA,EAAM,MAAA,CAAO,CAAA,CAAE,IAAA,IAAQ,OA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AA,IAC9B,IAAA,EAAM,MAAA,CAAO,CAAA,CAAE,IAAA,IAAQ,EAAE,CAAA;AAAA,IACzB,MAAA,EAAQ,MAAA,CAAO,CAAA,CAAE,MAAA,IAAU,MAAM,CAAA;AAAA,IACjC,UAAU,CAAA,CAAE,QAAA,IAAY,OAAO,MAAA,CAAO,CAAA,CAAE,QAAQ,CAAA,GAAI;AAAA,GACtD;AACF;AAUO,SAAS,gBAAgB,CAAA,EAAwC;AACtE,EAAA,MAAM,CAAA,GAA6B;AAAA,IACjC,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,MAAM,CAAA,CAAE;AAAA,GACV;AACA,EAAA,IAAI,CAAA,CAAE,MAAA,KAAW,MAAA,EAAQ,CAAA,CAAE,SAAS,CAAA,CAAE,MAAA;AACtC,EAAA,IAAI,CAAA,CAAE,QAAA,IAAY,IAAA,EAAM,CAAA,CAAE,WAAW,CAAA,CAAE,QAAA;AACvC,EAAA,OAAO,CAAA;AACT","file":"chunk-O7VPNKYN.js","sourcesContent":["/**\n * Pure data models — no I/O, no side effects.\n */\n\nimport semver from \"semver\";\n\n/**\n * Discriminator for catalog entries and asset references.\n * Used in asset ref strings (e.g. `'skill:my-skill'`, `'agent:my-agent'`).\n *\n * Any string: the provider registry (`@skaile/workspaces/discovery`\n * `AssetKindRegistry`) is the only authority on which kinds exist — a kind exists\n * iff a provider is registered for it.\n * @docLink packages/core/concepts#asset-kind\n */\nexport type AssetKind = string;\n\n// ── Dependency ────────────────────────────────────────────────────────────────\n\n/**\n * Declared dependency on another catalog asset.\n * @docLink packages/core/concepts#dependency\n */\nexport interface Dependency {\n /** Asset kind (e.g. \"skill\", \"agent\", \"contract\"). */\n kind: string;\n /** Asset name within that kind. */\n name: string;\n /** Canonical publisher namespace (when known). */\n publisher?: string;\n}\n\n/**\n * Parse a `\"kind:name\"` dependency string, or a bare `\"name\"` (defaults kind to `\"skill\"`).\n *\n * @param s - Dependency string, e.g. `\"skill:use-exa\"` or `\"use-exa\"`\n * @returns Parsed `{ kind, name }` dependency object\n * @docLink packages/core/concepts#parse-dep\n */\nexport function parseDep(s: string): Dependency {\n const i = s.indexOf(\":\");\n if (i !== -1) {\n const kind = s.slice(0, i).trim();\n const name = s.slice(i + 1).trim();\n return { kind, name };\n }\n return { kind: \"skill\", name: s.trim() };\n}\n\n/**\n * Serialize a Dependency back to its `\"kind:name\"` string form.\n *\n * @param d - Dependency to serialize\n * @returns String in `\"kind:name\"` format\n * @docLink packages/core/concepts#dep-to-str\n */\nexport function depToStr(d: Dependency): string {\n return `${d.kind}:${d.name}`;\n}\n\n// ── CatalogEntry ──────────────────────────────────────────────────────────────\n\n/**\n * A resolved catalog entry describing an installable asset.\n * Produced by manifest parsers and stored in the catalog YAML.\n * @docLink packages/core/concepts#catalog-entry\n */\nexport interface CatalogEntry {\n /** Unique asset name within its kind. */\n name: string;\n /** Asset kind discriminator. */\n kind: AssetKind;\n /** Short description of what this asset does. */\n description: string;\n /** Absolute path to manifest file */\n source: string;\n /** Canonical publisher namespace this asset belongs to (formerly `repository`). */\n publisher?: string;\n /**\n * Canonical ref (`kind:@publisher/name#version`) the CLI prints for this entry.\n * Set by the asset manager where `publisher` is not the real publisher (a\n * clone-sourced entry carries its clone key there); absent → derived from\n * `publisher` + `version`.\n */\n canonicalRef?: string;\n /**\n * `\"<org>/<repo>\"` coordinate the asset came from. Absent → the asset groups\n * directly under its publisher (local library with no git remote, or a\n * non-GitHub source).\n */\n repo?: string;\n /**\n * Claude plugin (from `.claude-plugin/marketplace.json` / `plugin.json`\n * membership) this asset belongs to, or absent when no plugin lists it.\n * Display-only — groups assets in the manage TUI; never part of identity or\n * the install layout.\n */\n plugin?: string;\n /** Semantic version string (may be empty if not declared in the manifest). */\n version: string;\n /** Skills, agents, or other assets this entry depends on. */\n requires: Dependency[];\n /** Asset refs this entry pulls in (presets: the asset items; flows: `requires`). */\n dependencies: string[];\n /**\n * Kind-specific metadata extracted from the manifest frontmatter.\n * Used by MCP servers to carry default config (transport, command, args, env, url, headers)\n * so that `mcp:name` dependency refs resolve to a runnable declaration without\n * requiring verbose inline config in `skaile.yaml`.\n */\n metadata?: Record<string, unknown>;\n /** Curated facet, surfaced as a badge in the manage TUI (not a tree axis). */\n category?: string;\n /** Store-listing keywords (manifest `assets[].keywords`, else frontmatter). */\n keywords?: string[];\n /** Store-listing license (manifest `assets[].license`, else repo-level default). */\n license?: string;\n /** Store-listing homepage (manifest `assets[].homepage`, else repo-level default). */\n homepage?: string;\n}\n\n/**\n * Construct a CatalogEntry from a raw deserialized record (e.g. from catalog.yaml).\n *\n * @param d - Raw object with loosely typed fields\n * @returns Normalized CatalogEntry\n * @docLink packages/core/concepts#entry-from-raw\n */\nexport function entryFromRaw(d: Record<string, unknown>): CatalogEntry {\n const rawDeps = d.dependencies;\n const deps = Array.isArray(rawDeps) ? (rawDeps as string[]).filter(Boolean) : [];\n const entry: CatalogEntry = {\n name: String(d.name ?? \"\"),\n kind: String(d.kind ?? \"skill\") as AssetKind,\n description: String(d.description ?? \"\"),\n source: String(d.source ?? \"\"),\n publisher: d.publisher != null ? String(d.publisher) : undefined,\n repo: d.repo != null ? String(d.repo) : undefined,\n plugin: d.plugin != null ? String(d.plugin) : undefined,\n version: String(d.version ?? \"\"),\n requires: Array.isArray(d.requires)\n ? (d.requires as string[]).filter(Boolean).map(parseDep)\n : [],\n dependencies: deps,\n };\n if (d.metadata != null && typeof d.metadata === \"object\" && !Array.isArray(d.metadata)) {\n entry.metadata = d.metadata as Record<string, unknown>;\n }\n if (d.category != null) entry.category = String(d.category);\n if (Array.isArray(d.keywords)) {\n entry.keywords = (d.keywords as unknown[]).filter((k): k is string => typeof k === \"string\");\n }\n if (d.license != null) entry.license = String(d.license);\n if (d.homepage != null) entry.homepage = String(d.homepage);\n return entry;\n}\n\n/**\n * Serialize a CatalogEntry to a plain record suitable for YAML/JSON persistence.\n *\n * @param e - CatalogEntry to serialize\n * @returns Plain object with string-serialized requires and dependencies\n * @docLink packages/core/concepts#entry-to-raw\n */\nexport function entryToRaw(e: CatalogEntry): Record<string, unknown> {\n const raw: Record<string, unknown> = {\n name: e.name,\n kind: e.kind,\n description: e.description,\n source: e.source,\n publisher: e.publisher,\n repo: e.repo,\n version: e.version,\n ...(e.plugin != null ? { plugin: e.plugin } : {}),\n requires: e.requires.map(depToStr),\n dependencies: e.dependencies,\n };\n if (e.metadata) raw.metadata = e.metadata;\n if (e.category != null) raw.category = e.category;\n if (e.keywords && e.keywords.length > 0) raw.keywords = e.keywords;\n if (e.license != null) raw.license = e.license;\n if (e.homepage != null) raw.homepage = e.homepage;\n return raw;\n}\n\n// ── AssetRef ─────────────────────────────────────────────────────────────────\n\n/**\n * A parsed asset reference: `kind:@<publisher>/name[#pin]`.\n *\n * `publisher` is the canonical, GitHub-shaped publisher namespace (≤39 chars,\n * alphanumeric+hyphen). `pin` is a SemVer constraint, exact SHA, or absent.\n * Floating refs (`main`, `latest`, `HEAD`) are rejected at parse time.\n *\n * Produced by `parseAssetRef`; consumed by `resolveAsset` and `resolveAll`.\n * @docLink packages/core/concepts#asset-ref\n */\nexport interface AssetRef {\n kind: string;\n name: string;\n /** Canonical publisher namespace. Optional only for ambiguity-resolution\n * during migration; new manifests require it. */\n publisher?: string;\n /** SemVer constraint (^1.4.0, ~1.4, 1.x, exact 1.4.0), 40-char SHA, or undefined. */\n pin?: string;\n}\n\nconst SHA_RE = /^[0-9a-f]{40}$/i;\n\n// Scoped grammar: `kind:@publisher/name[#version]`. The publisher sub-pattern is\n// GitHub-shaped (1-39 chars, alphanumeric + single hyphens, no leading/trailing or\n// double hyphen); `@` is the scope sigil and `#` the version sigil. `name` is\n// intentionally permissive (`[^/#\\s]+` — only the structural separators are\n// forbidden); floating-ref rejection stays in `isValidPin`, so `#main`/`#latest`\n// match here and fail there with a clear message.\nconst SCOPED_REF_RE =\n /^(?:([a-z][a-z0-9-]*):)?@([A-Za-z0-9](?:[A-Za-z0-9]|-(?!-)){0,37}[A-Za-z0-9]|[A-Za-z0-9])\\/([^/#\\s]+)(?:#(.+))?$/;\n\n// Canonical asset-name grammar: lowercase kebab-case (npm-style, scope-free) —\n// `a-z` / `0-9` segments joined by single hyphens, no leading/trailing hyphen,\n// no uppercase, spaces, dots, or underscores. Names become directory names,\n// lock keys, and CLI args, so the constraint is intentionally narrow.\nconst ASSET_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n// Diagnostic-only matcher: a ref carrying a `kind:@publisher/` scope prefix,\n// capturing whatever follows (sans `#pin`) as the candidate name. Used solely\n// to tell \"missing publisher\" apart from \"malformed name\" when the strict\n// grammar above fails (e.g. a space in the name).\nconst SCOPE_PREFIX_RE = /^(?:[a-z][a-z0-9-]*:)?@[^/\\s]+\\/([^#]+?)(?:#.*)?$/;\n\n/** Human-readable statement of the canonical asset-name rule. */\nexport const ASSET_NAME_HINT =\n 'names must be lowercase kebab-case (a-z, 0-9, single hyphens; e.g. \"cli-concept\")';\n\n/**\n * True when `name` is a canonical asset name: lowercase kebab-case, scope-free.\n *\n * This is the single source of truth for asset-name validity — `parseAssetRef`\n * enforces it, and `skaile validate` reports violations across a repo tree.\n * @docLink packages/core/concepts#is-valid-asset-name\n */\nexport function isValidAssetName(name: string): boolean {\n return ASSET_NAME_RE.test(name);\n}\n\n// Bare publisher namespace: no scope sigil, path separator, pin marker or whitespace.\nconst PUBLISHER_RE = /^[^\\s/#@]+$/;\n\n/** Human-readable statement of the publisher rule (bare namespace, no scope sigil). */\nexport const PUBLISHER_HINT = 'publishers must be a bare name like \"acme\" (no @, /, # or spaces)';\n\n/**\n * True when `publisher` is a usable bare publisher: non-empty, no `@`, `/`, `#`\n * or whitespace. The one rule behind `library create --publisher`, `library set\n * <lib> publisher=` and `library init`; the caller strips a leading `@` first.\n */\nexport function isValidPublisher(publisher: string): boolean {\n return PUBLISHER_RE.test(publisher);\n}\n\n/**\n * Coerce an arbitrary string into a canonical asset name (lowercase kebab-case).\n *\n * For **third-party sources we don't control**, an upstream asset may carry a\n * human-styled identity (`\"Complex App\"`, `\"CLI_Concept\"`). The canonical grammar\n * (`isValidAssetName`) rejects those, so the ingestion boundary slugifies them to\n * a valid identity rather than crashing: Unicode is folded to ASCII, the result is\n * lowercased, every run of non-`[a-z0-9]` becomes a single hyphen, and\n * leading/trailing hyphens are trimmed. The transform is idempotent and a no-op on\n * already-canonical names.\n *\n * This is intentionally **lossy** — the pretty original is not part of identity.\n * Callers that want to preserve it for display must stash it themselves (e.g. on\n * `CatalogEntry.metadata.displayName`). Authoring-time validation (`skaile validate`)\n * still uses `isValidAssetName` on raw frontmatter, so first-party typos surface there.\n *\n * @throws When `raw` contains no `[a-z0-9]` character (nothing to slugify).\n * @docLink packages/core/concepts#slugify-asset-name\n */\nexport function slugifyAssetName(raw: string): string {\n const slug = raw\n .normalize(\"NFKD\")\n .replace(/[\\u0300-\\u036f]/g, \"\") // strip combining accents\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (!slug) {\n throw new Error(`cannot derive a canonical asset name from \"${raw}\" — ${ASSET_NAME_HINT}.`);\n }\n return slug;\n}\n\n/** True when `pin` is a SemVer constraint, exact SemVer, or 40-char SHA. */\nfunction isValidPin(pin: string): boolean {\n if (SHA_RE.test(pin)) return true;\n if (semver.valid(pin)) return true;\n if (semver.validRange(pin)) return true;\n return false;\n}\n\n/** Throw the canonical non-canonical-pin error for a ref `s` carrying `pin`. */\nfunction rejectFloatingPin(s: string, pin: string): never {\n throw new Error(\n `non-canonical pin \"${pin}\" in \"${s}\" — pin must be a SemVer ` +\n \"constraint (1.4.0, ^1.4, ~1.4, 1.x), a 40-char SHA, or absent. \" +\n \"Floating refs (main/latest/HEAD) are not allowed.\",\n );\n}\n\n/** Throw the canonical malformed-name error for a ref `s` carrying `name`. */\nfunction rejectInvalidName(s: string, name: string): never {\n throw new Error(\n `invalid asset name \"${name}\" in ref \"${s}\" — ${ASSET_NAME_HINT}. ` +\n \"Run the `migrate-skaile-manifest` skill on legacy manifests.\",\n );\n}\n\n/**\n * Parse a canonical asset reference string into an `AssetRef` object.\n *\n * Grammar: `kind:@<publisher>/name[#version]`\n * \"skill:@skaile-ai/audit\" → { kind: \"skill\", name: \"audit\", publisher: \"skaile-ai\" }\n * \"skill:@skaile-ai/audit#^1.4.0\" → { …, pin: \"^1.4.0\" }\n * \"skill:@skaile-ai/audit#<40-sha>\" → { …, pin: \"<40-sha>\" }\n *\n * `@` is the scope sigil and `#` the version sigil. `<publisher>` is GitHub-shaped\n * (≤39 chars, alphanumeric+hyphen, no leading/trailing or double hyphen). `pin`\n * accepts a SemVer constraint (`^`, `~`, `x`, exact), a 40-char SHA, or is absent.\n * Floating refs (`main`/`latest`/`HEAD`/anything non-canonical) are parse-time errors.\n *\n * The shorthand `mcp:` is normalized to `mcp-server:`. `kind` defaults to `\"skill\"`.\n *\n * @param s - Asset reference string\n * @returns Parsed `AssetRef`\n * @throws When the ref matches no grammar, the publisher is malformed, or the pin\n * is a floating ref.\n * @docLink packages/core/concepts#parse-asset-ref\n */\nexport function parseAssetRef(s: string): AssetRef {\n const trimmed = s.trim();\n const m = SCOPED_REF_RE.exec(trimmed);\n if (m) {\n const kindRaw = m[1] ?? \"skill\";\n const kind = kindRaw === \"mcp\" ? \"mcp-server\" : kindRaw;\n const publisher = m[2];\n const name = m[3];\n const pin = m[4]?.trim() || undefined;\n if (!isValidAssetName(name)) rejectInvalidName(s, name);\n if (pin !== undefined && !isValidPin(pin)) rejectFloatingPin(s, pin);\n return { kind, name, publisher, pin };\n }\n\n // The strict grammar failed. If the ref nonetheless carries a `@publisher/`\n // scope and the fault is the name (e.g. an embedded space), surface a\n // name-specific error rather than the misleading \"publisher required\" — the\n // publisher is plainly present. A *valid* captured name means the publisher\n // itself is malformed, so fall through to the publisher error below.\n const scoped = SCOPE_PREFIX_RE.exec(trimmed);\n if (scoped) {\n const candidate = scoped[1].trim();\n if (!isValidAssetName(candidate)) rejectInvalidName(s, candidate);\n }\n\n throw new Error(\n `publisher required in asset ref \"${s}\" — use \\`kind:@<publisher>/name\\`. ` +\n \"Run the `migrate-skaile-manifest` skill on legacy manifests.\",\n );\n}\n\n/**\n * Parse a ref for identity matching, tolerating a non-canonical pin. A lock key\n * can pin a content-sha pseudo-version (`#0.0.0-sha.<hash>`) that\n * {@link parseAssetRef} rejects; matchers only need the version-agnostic\n * `kind/publisher/name`, so drop the pin and retry before giving up.\n *\n * @returns The parsed ref (its `pin` empty when the pin was dropped), or `null`.\n */\nexport function parseAssetRefLoose(ref: string): AssetRef | null {\n try {\n return parseAssetRef(ref);\n } catch {\n const hash = ref.indexOf(\"#\");\n if (hash < 0) return null;\n try {\n return parseAssetRef(ref.slice(0, hash));\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Serialize an AssetRef back to its canonical string form.\n *\n * Emits the scope form `kind:@publisher/name[#pin]` when `publisher` is present,\n * and the bare `kind:name[#pin]` form for transitive refs that inherit it.\n *\n * @param ref - AssetRef to serialize\n * @returns String in `\"kind:@publisher/name[#pin]\"` (or bare `\"kind:name[#pin]\"`) format\n * @docLink packages/core/concepts#asset-ref-to-str\n */\nexport function assetRefToStr(ref: AssetRef): string {\n const scope = ref.publisher ? `@${ref.publisher}/${ref.name}` : ref.name;\n return `${ref.kind}:${scope}${ref.pin ? `#${ref.pin}` : \"\"}`;\n}\n\n/**\n * Convert an AssetRef to a simple Dependency, dropping the repository and pin qualifiers.\n *\n * @param ref - Full asset reference (may include repository and pin)\n * @returns Dependency with only kind and name\n * @docLink packages/core/concepts#asset-ref-to-dep\n */\nexport function assetRefToDep(ref: AssetRef): Dependency {\n // Grammar-agnostic — drops publisher/pin, so the scope-sigil change doesn't touch it.\n return { kind: ref.kind, name: ref.name };\n}\n\n// ── Lock File ────────────────────────────────────────────────────────────────\n\n/** A path/sha256 pair recorded for one file inside a locked asset. */\nexport interface LockFileEntry {\n path: string;\n sha256: string;\n}\n\n/**\n * Library-origin marker on a {@link LockEntry}: the asset was resolved from a\n * registered library (a local authoring place) rather than a git source/store.\n */\nexport interface LockLibraryOrigin {\n /** Name of the library the asset was resolved from. */\n name: string;\n /** Library version of the asset at lock time. */\n version: string;\n /** Content hash recorded in the library index at lock time; absent when the library was never indexed. */\n sha256?: string;\n /**\n * Set by `skaile asset install`: the files were copied or linked straight into\n * the project, not deployed from a `skaile.yaml` dependency. `skaile install`\n * leaves such an entry and its files alone instead of reconciling them away.\n */\n installed?: \"copy\" | \"link\";\n}\n\n/**\n * Per-asset entry in the lock file (v3 schema).\n * Keyed in `LockFile.assets` by canonical ref (`<kind>:@<publisher>/<name>#<version>`).\n * Source-origin entries carry `source` + `files`; library-origin entries carry\n * `library` instead (no `source`, empty `files`). Both fields are additive, so\n * lock files written before library origin existed still load unchanged.\n * @docLink packages/core/api-reference#lock-entry\n */\nexport interface LockEntry {\n /** Composite sha256 over sorted `<path>:<sha256>\\n` rows (library-origin: the library's hash, `\"\"` when unknown). */\n sha256: string;\n /** Resolved upstream source + commit. Absent for library-origin entries. */\n source?: { url: string; commit: string };\n /** Files that constitute the asset. Empty for library-origin entries. */\n files: LockFileEntry[];\n /** True when an `overrides[]` entry pinned this resolution. */\n override_applied: boolean;\n /** Set when the asset was resolved from a registered library. */\n library?: LockLibraryOrigin;\n}\n\n/** Per-source-URL entry in `LockFile.sources`. */\nexport interface LockSourceEntry {\n url: string;\n commit: string;\n}\n\n/**\n * Full skaile.lock.yaml structure (v3 schema).\n * @docLink packages/core/api-reference#lock-file\n */\nexport interface LockFile {\n /**\n * Lock file schema version: 3, or 4 when the lock holds a library-origin\n * entry (no `source`), so CLIs that predate library origin reject it cleanly.\n */\n schema_version: 3 | 4;\n /** ISO timestamp of when the lock was generated. */\n locked_at: string;\n /** Resolved assets keyed by canonical ref `<kind>:@<publisher>/<name>#<version>`. */\n assets: Record<string, LockEntry>;\n /** Every source URL that contributed at least one resolved asset. */\n sources: LockSourceEntry[];\n /**\n * Resolved plugin packages (from `skaile.yaml` `plugins:`), keyed by package\n * name. The plugin-store reconciler reads this slice into its reconcile-hash\n * so a lock change reinstalls even when the manifest list is unchanged.\n */\n plugins?: Record<string, LockPluginEntry>;\n}\n\n/** One pinned plugin package in the lock file's `plugins` slice. */\nexport interface LockPluginEntry {\n /** Resolved exact version (e.g. \"0.1.3\"). */\n version: string;\n /** Package integrity hash (e.g. \"sha512-...\"); may be empty until populated from bun's output. */\n integrity: string;\n}\n\n// ── Repository ───────────────────────────────────────────────────────────────\n\ntype RepositoryKind = \"local\" | \"github\";\n\n/**\n * A registered asset repository (local path or cloned GitHub repo).\n * Stored in the catalog; consumed by `repo-manager` for cloning and scanning.\n * @docLink packages/core/concepts#repository\n */\nexport interface Repository {\n /** Logical repository name. */\n name: string;\n /** Storage kind: \"local\" for paths, \"github\" for remote URLs. */\n kind: RepositoryKind;\n /** Absolute path (local) or remote URL (github). */\n path: string;\n /** Active branch. */\n branch: string;\n /** Upstream fork URL (for fork-based workflows). */\n upstream?: string;\n}\n\n/**\n * Construct a `Repository` from a raw deserialized record.\n *\n * @param d - Raw object from YAML/JSON\n * @returns Normalized `Repository`\n * @docLink packages/core/concepts#repository-from-raw\n */\nexport function repositoryFromRaw(d: Record<string, unknown>): Repository {\n return {\n name: String(d.name ?? \"\"),\n kind: String(d.kind ?? \"local\") as RepositoryKind,\n path: String(d.path ?? \"\"),\n branch: String(d.branch ?? \"main\"),\n upstream: d.upstream != null ? String(d.upstream) : undefined,\n };\n}\n\n/**\n * Serialize a `Repository` to a plain record for YAML/JSON persistence.\n * Omits the `branch` field when it equals `\"main\"` to keep serialized output clean.\n *\n * @param r - Repository to serialize\n * @returns Plain object suitable for YAML/JSON\n * @docLink packages/core/concepts#repository-to-raw\n */\nexport function repositoryToRaw(r: Repository): Record<string, unknown> {\n const d: Record<string, unknown> = {\n name: r.name,\n kind: r.kind,\n path: r.path,\n };\n if (r.branch !== \"main\") d.branch = r.branch;\n if (r.upstream != null) d.upstream = r.upstream;\n return d;\n}\n"]}
|
|
@@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n ConnectorOperation,\n ConnectorResponseEvent,\n ConnectorResponseFailureCode,\n ConnectorStat,\n ConnectorStatusEvent,\n ListOptions,\n MountInfo,\n ReadOptions,\n SearchOptions,\n StatOptions,\n} from \"@skaile/workspaces/types\";\nimport type {\n ConnectorStatus,\n ResourceClientSnapshot,\n StoreTransport,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Rejection for a `resource_response` that carried an `error`. `code` is the\n * runner's machine-readable failure class, absent from runners older than\n * protocol 4.2.0.\n */\nexport class ResourceRequestError extends Error {\n readonly code: ConnectorResponseFailureCode | undefined;\n\n constructor(message: string, code?: ConnectorResponseFailureCode) {\n super(message);\n this.name = \"ResourceRequestError\";\n this.code = code;\n }\n}\n\n/**\n * Lazy resource browser for agent connectors.\n *\n * Provides a reactive list of connected mounts and connectors, and\n * request/response methods for browsing connector contents. Shares\n * the same transport (`send` + `onEvent`) as `AgentStore`.\n * @docLink packages/store/concepts#resource-client\n */\nexport class ResourceClient implements SubscribableStore<ResourceClientSnapshot> {\n private readonly _send: StoreTransport[\"send\"];\n private _mounts: readonly MountInfo[] = [];\n private _connectors: readonly ConnectorInfo[] = [];\n\n /** Live connection status per connector, keyed by connector ID. Updated by connector_status events. */\n connectorStatus: Map<string, ConnectorStatus> = new Map();\n\n private _snapshot: ResourceClientSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _pendingRequests = new Map<\n string,\n {\n resolve: (event: ConnectorResponseEvent) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private readonly _unsubEvent: () => void;\n\n /**\n * @param transport - Shared transport (same instance as the AgentStore for this session).\n */\n constructor(transport: StoreTransport) {\n this._send = transport.send;\n this._unsubEvent = transport.onEvent((event) => this._handleEvent(event));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Mounts available in this session, populated from `resources_available` events. */\n get mounts(): readonly MountInfo[] {\n return this._mounts;\n }\n\n /** Tool-based connectors available in this session, populated from `resources_available` events. */\n get connectors(): readonly ConnectorInfo[] {\n return this._connectors;\n }\n\n // -- Resource operations ---------------------------------------------------\n\n /**\n * List directory entries at the given path within a connector.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Directory path to list. Omit for the connector root.\n * @param opts - Optional pagination and filter options.\n * @returns Array of entries (files, directories, etc.) at the given path.\n * @throws If the request times out or the connector returns an error.\n */\n async list(connectorId: string, path?: string, opts?: ListOptions): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"list\", path, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n /**\n * Read the content of a single resource.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Full path to the resource within the connector.\n * @param opts - `{ encoding: \"binary\" }` asks a filesystem mount for base64\n * of the bytes instead of text guessed from a NUL sniff (protocol 4.6.0;\n * an older runner ignores it).\n * @returns The resource content object.\n * @throws If the request times out or the connector returns an error.\n */\n async read(connectorId: string, path: string, opts?: ReadOptions): Promise<ConnectorContent> {\n const response = await this._request(connectorId, \"read\", path, opts);\n return response.data as ConnectorContent;\n }\n\n /**\n * Write content to a resource, creating it if it does not exist.\n *\n * @param connectorId - ID of the connector to write to.\n * @param path - Full path to the resource within the connector.\n * @param content - Content to write.\n * @throws If the request times out or the connector returns an error.\n */\n async write(connectorId: string, path: string, content: ConnectorContent): Promise<void> {\n await this._request(connectorId, \"write\", path, undefined, content);\n }\n\n /**\n * Delete a resource from a connector.\n *\n * @param connectorId - ID of the connector to delete from.\n * @param path - Full path to the resource within the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async delete(connectorId: string, path: string): Promise<void> {\n await this._request(connectorId, \"delete\", path);\n }\n\n /**\n * Full-text search within a connector.\n *\n * @param connectorId - ID of the connector to search.\n * @param query - Search query string.\n * @param opts - Optional search options (e.g. path prefix, result limit).\n * @returns Matching entries, ordered by relevance as determined by the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async search(\n connectorId: string,\n query: string,\n opts?: SearchOptions,\n ): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"search\", query, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n /**\n * Create an empty directory on a filesystem mount, parents included.\n *\n * @param connectorId - ID of the mount.\n * @param path - Directory path within the mount.\n * @throws {ResourceRequestError} with `code: \"already_exists\"` if something\n * is already at `path`; also if the target is not a filesystem mount or the\n * runner predates protocol 4.2.0 (then `code` is absent).\n */\n async mkdir(connectorId: string, path: string): Promise<void> {\n await this._request(connectorId, \"mkdir\", path);\n }\n\n /**\n * Describe one path on a filesystem mount; with `opts.recursive`, a\n * directory also carries capped recursive totals.\n *\n * @param connectorId - ID of the mount.\n * @param path - Path within the mount; omit for the mount root.\n * @param opts - Optional stat options.\n * @throws If the path does not exist, the target is not a filesystem mount,\n * or the runner predates protocol 4.2.0.\n */\n async stat(connectorId: string, path?: string, opts?: StatOptions): Promise<ConnectorStat> {\n const response = await this._request(connectorId, \"stat\", path, opts);\n return response.data as ConnectorStat;\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called after every resource availability change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever mounts or connectors change.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable resource snapshot.\n *\n * A new object is produced lazily after each `resources_available` event.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): ResourceClientSnapshot => {\n if (!this._snapshot) {\n this._snapshot = { mounts: this._mounts, connectors: this._connectors };\n }\n return this._snapshot;\n };\n\n // -- Connector config mutations --------------------------------------------\n\n /**\n * Send a `connector_config` add command to wire a new connector at runtime,\n * without restarting the session. The runner receives this command and\n * calls `ConnectorManager.connect()`, which fires a `connector_status` event\n * back to the store once the connector is live.\n *\n * @param declaration - Connector declaration (id, driver, access level, options).\n */\n addConnector(declaration: {\n id: string;\n driver: string;\n access?: \"read-only\" | \"read-write\";\n options?: Record<string, unknown>;\n }): void {\n this._send({ type: \"connector_config\", action: \"add\", declaration });\n }\n\n /**\n * Send a `connector_config` remove command to disconnect a connector by ID\n * without restarting the session.\n *\n * @param connectorId - ID of the connector to disconnect and remove.\n */\n removeConnector(connectorId: string): void {\n this._send({ type: \"connector_config\", action: \"remove\", connectorId });\n }\n\n /**\n * Send a `connector_config` refresh command to reconnect all configured\n * connectors (e.g. after a credentials change).\n */\n refreshConnectors(): void {\n this._send({ type: \"connector_config\", action: \"refresh\" });\n }\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events, reject all pending requests, and\n * clear all change listeners.\n *\n * All in-flight resource requests will reject\n * with `\"ResourceClient disposed\"`.\n */\n dispose(): void {\n this._unsubEvent();\n for (const [, pending] of this._pendingRequests) {\n clearTimeout(pending.timer);\n pending.reject(new Error(\"ResourceClient disposed\"));\n }\n this._pendingRequests.clear();\n this._listeners.clear();\n }\n\n // -- Internal --------------------------------------------------------------\n\n private _handleEvent(event: AgentEvent): void {\n if (event.type === \"connector_status\") {\n const e = event as ConnectorStatusEvent;\n const existing = this.connectorStatus.get(e.connectorId);\n const next = new Map(this.connectorStatus);\n next.set(e.connectorId, {\n id: e.connectorId,\n driver:\n existing?.driver ?? this._connectors.find((c) => c.id === e.connectorId)?.driver ?? \"\",\n state: e.status,\n ...(e.error !== undefined ? { error: e.error } : {}),\n ...(e.errorKind !== undefined ? { errorKind: e.errorKind } : {}),\n ...(e.latencyMs !== undefined ? { latencyMs: e.latencyMs } : {}),\n lastUpdated: new Date(),\n });\n this.connectorStatus = next;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resources_available\") {\n this._mounts = event.mounts;\n this._connectors = event.connectors;\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resource_response\") {\n const pending = this._pendingRequests.get(event.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timer);\n this._pendingRequests.delete(event.requestId);\n\n if (event.error) {\n pending.reject(new ResourceRequestError(event.error, event.code));\n } else {\n pending.resolve(event);\n }\n }\n }\n\n private _request(\n connectorId: string,\n operation: ConnectorOperation,\n path?: string,\n options?: ListOptions | SearchOptions | StatOptions | ReadOptions,\n content?: ConnectorContent,\n ): Promise<ConnectorResponseEvent> {\n const requestId = crypto.randomUUID();\n\n return new Promise<ConnectorResponseEvent>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingRequests.delete(requestId);\n reject(\n new Error(\n `Resource request timed out after ${DEFAULT_TIMEOUT_MS}ms: ${operation} ${connectorId}${path ? ` ${path}` : \"\"}`,\n ),\n );\n }, DEFAULT_TIMEOUT_MS);\n\n this._pendingRequests.set(requestId, { resolve, reject, timer });\n\n this._send({\n type: \"resource_request\",\n requestId,\n connectorId,\n operation,\n ...(path !== undefined ? { path } : {}),\n ...(options ? { options } : {}),\n ...(content ? { content } : {}),\n });\n });\n }\n}\n","import type {\n AgentCommand,\n AgentEvent,\n AgentPhase,\n Capability,\n IncompatibleProtocolEvent,\n Message,\n ProtocolInfoEvent,\n QuestionEvent,\n RenderInvokedEvent,\n} from \"@skaile/workspaces/types\";\nimport type {\n AgentClientLike,\n AgentStoreOptions,\n AgentStoreSnapshot,\n ConnectionStatus,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_PAGE_SIZE = 50;\n\n/** Conservative equality for plain JSON data; unsupported or unverifiable values fail open. */\nfunction isSameJsonValue<T>(a: T | undefined, b: T, conservativeCommandInput = false): boolean {\n const aObjects = new WeakSet<object>();\n const bObjects = new WeakSet<object>();\n\n const compare = (left: unknown, right: unknown): boolean => {\n if (left === null || right === null) return left === right;\n if (typeof left !== typeof right) return false;\n\n switch (typeof left) {\n case \"string\":\n case \"boolean\":\n return left === right;\n case \"number\":\n return (\n Number.isFinite(left) &&\n Number.isFinite(right) &&\n !Object.is(left, -0) &&\n !Object.is(right, -0) &&\n left === right\n );\n case \"object\":\n break;\n default:\n return false;\n }\n\n const leftObject = left as object;\n const rightObject = right as object;\n if (aObjects.has(leftObject) || bObjects.has(rightObject)) return false;\n if (conservativeCommandInput) {\n if (leftObject === rightObject || bObjects.has(leftObject) || aObjects.has(rightObject)) {\n return false;\n }\n }\n aObjects.add(leftObject);\n bObjects.add(rightObject);\n\n const leftIsArray = Array.isArray(leftObject);\n if (leftIsArray !== Array.isArray(rightObject)) return false;\n\n const leftPrototype = Object.getPrototypeOf(leftObject);\n const rightPrototype = Object.getPrototypeOf(rightObject);\n const leftHasPlainPrototype = leftIsArray\n ? leftPrototype === Array.prototype\n : leftPrototype === Object.prototype || leftPrototype === null;\n const rightHasPlainPrototype = leftIsArray\n ? rightPrototype === Array.prototype\n : rightPrototype === Object.prototype || rightPrototype === null;\n if (\n !leftHasPlainPrototype ||\n !rightHasPlainPrototype ||\n leftPrototype !== rightPrototype ||\n !Object.isExtensible(leftObject) ||\n !Object.isExtensible(rightObject)\n ) {\n return false;\n }\n\n const leftKeys = Reflect.ownKeys(leftObject);\n const rightKeys = Reflect.ownKeys(rightObject);\n if (\n leftKeys.length !== rightKeys.length ||\n leftKeys.some((key) => typeof key !== \"string\") ||\n rightKeys.some((key) => typeof key !== \"string\")\n ) {\n return false;\n }\n\n if (leftIsArray) {\n const leftLengthDescriptor = Object.getOwnPropertyDescriptor(leftObject, \"length\");\n const rightLengthDescriptor = Object.getOwnPropertyDescriptor(rightObject, \"length\");\n const leftLength = leftLengthDescriptor?.value;\n const rightLength = rightLengthDescriptor?.value;\n if (\n !leftLengthDescriptor ||\n !(\"value\" in leftLengthDescriptor) ||\n !leftLengthDescriptor.writable ||\n leftLengthDescriptor.enumerable ||\n leftLengthDescriptor.configurable ||\n !rightLengthDescriptor ||\n !(\"value\" in rightLengthDescriptor) ||\n !rightLengthDescriptor.writable ||\n rightLengthDescriptor.enumerable ||\n rightLengthDescriptor.configurable ||\n typeof leftLength !== \"number\" ||\n leftLength !== rightLength ||\n leftKeys.length !== leftLength + 1\n ) {\n return false;\n }\n\n for (let index = 0; index < leftLength; index++) {\n const key = String(index);\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, key);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, key);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n }\n\n for (let index = 0; index < leftKeys.length; index++) {\n const leftKey = leftKeys[index] as string;\n const rightKey = rightKeys[index] as string;\n if (leftKey !== rightKey) return false;\n\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, leftKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, rightKey);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n };\n\n try {\n const same = compare(a, b);\n if (!same || !conservativeCommandInput) return same;\n structuredClone(a);\n structuredClone(b);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Headless reactive store for agent conversation state.\n *\n * Framework-agnostic — works with React (`useSyncExternalStore`),\n * Vue (`shallowRef` + `subscribe`), or any other UI framework.\n *\n * Accepts a minimal transport interface (`send` + `onEvent`) so it works\n * with WebSocket, tRPC, SSE, or any other delivery mechanism.\n * @docLink packages/store/concepts#agent-store\n */\nexport class AgentStore implements SubscribableStore<AgentStoreSnapshot> {\n private readonly _options: AgentStoreOptions;\n private _messages: Message[];\n private _streamingText = \"\";\n private _cancelledText = \"\";\n private _status: ConnectionStatus = \"idle\";\n private _phase: AgentPhase = \"idle\";\n private _pendingQuestion: AgentStoreSnapshot[\"pendingQuestion\"] = null;\n /**\n * Unanswered sub-questions of the parked ask, oldest first. Drivers resume\n * only once every one has an answer; `_pendingQuestion` is its last entry.\n */\n private _openQuestions: QuestionEvent[] = [];\n /** Every sub-question text of the parked ask, answered or not. */\n private _askQuestions = new Set<string>();\n /**\n * Own unnamed replies whose runner echo has not arrived yet. Best effort: a\n * reply the driver rejects is never echoed, and its count lingers until the\n * ask ends.\n */\n private _unnamedEchoesOwed = 0;\n private _error: AgentStoreSnapshot[\"error\"] = null;\n private _isAllLoaded: boolean;\n /** Prompts a cancel dropped before they ran; new Set on every change. */\n private _notSentPromptIds: ReadonlySet<string> = new Set();\n private _seq: number;\n private _streamingFlushed = true;\n /** Shared state per store namespace — new Map instance on every mutation. */\n private _sharedState: Map<string, Record<string, unknown>> = new Map();\n /** Protocol v2 capability registry — new Map instance on every mutation. */\n private _capabilities: Map<string, Capability> = new Map();\n /** Protocol v2 active render invocations — new Map instance on every mutation. */\n private _activeRenderInvocations: Map<string, RenderInvokedEvent> = new Map();\n /** Protocol v2 — most recent `protocol_info` event from the runner. */\n private _protocolInfo: ProtocolInfoEvent | null = null;\n /** Protocol v2 — latest incompatible-protocol notice. */\n private _incompatibleProtocol: IncompatibleProtocolEvent | null = null;\n\n private _snapshot: AgentStoreSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _unsubEvent: () => void;\n private readonly _unsubStatus: (() => void) | undefined;\n\n /**\n * @param options - Store configuration including transport and optional pagination support.\n */\n constructor(options: AgentStoreOptions) {\n this._options = options;\n this._messages = options.initialMessages ? [...options.initialMessages] : [];\n this._isAllLoaded = !options.loadMessages;\n this._seq = this._messages.reduce((max, m) => Math.max(max, m.seq), 0);\n\n this._unsubEvent = options.onEvent((event) => this._handleEvent(event));\n this._unsubStatus = options.onStatusChange?.((status) => this.setStatus(status));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Accumulated conversation messages, oldest first. */\n get messages(): readonly Message[] {\n return this._messages;\n }\n\n /** Text currently streaming from the agent. Empty when not streaming. */\n get streamingText(): string {\n return this._streamingText;\n }\n\n /** Current connection lifecycle state. */\n get status(): ConnectionStatus {\n return this._status;\n }\n\n /** Current agent execution phase (e.g. `\"idle\"`, `\"thinking\"`, `\"executing\"`). */\n get phase(): AgentPhase {\n return this._phase;\n }\n\n /** The pending question the agent is waiting for the user to answer, or null. */\n get pendingQuestion(): AgentStoreSnapshot[\"pendingQuestion\"] {\n return this._pendingQuestion;\n }\n\n /** Most recent error, or null when no error is active. */\n get error(): AgentStoreSnapshot[\"error\"] {\n return this._error;\n }\n\n /** Partial text that was visible when the user cancelled. Empty when not cancelled. */\n get cancelledText(): string {\n return this._cancelledText;\n }\n\n /** True when there are no more older messages to load via pagination. */\n get isAllLoaded(): boolean {\n return this._isAllLoaded;\n }\n\n /** `messageId`s of prompts a cancel dropped before they ran. */\n get notSentPromptIds(): ReadonlySet<string> {\n return this._notSentPromptIds;\n }\n\n /**\n * Whether `message` is a prompt a cancel dropped before it ran, so the UI\n * shows it as \"Not sent\". Matches on the prompt payload's `messageId`.\n */\n isPromptNotSent(message: Message): boolean {\n const payload = message.payload as { type: string; messageId?: unknown };\n return (\n payload.type === \"prompt\" &&\n typeof payload.messageId === \"string\" &&\n this._notSentPromptIds.has(payload.messageId)\n );\n }\n\n // -- Commands --------------------------------------------------------------\n\n /**\n * Send a user prompt to the agent and optimistically update local state.\n *\n * Clears any previous error and cancelled text, sets phase to `\"thinking\"`,\n * and appends the prompt as a local message before forwarding to the agent.\n *\n * @param text - The user's prompt text.\n */\n prompt(text: string): void {\n // A prompt sent mid-turn (sender interjecting while the agent streams) is a\n // boundary: finalize the in-flight text before this prompt so the two don't\n // merge into one bubble. No-op at turn start (nothing streaming).\n this._flushStreaming();\n this._error = null;\n this._cancelledText = \"\";\n this._streamingFlushed = false;\n // A free-form prompt abandons any unanswered question: the turn it belonged\n // to is over. Left set, it would gate every status of the new turn.\n this._setOpenQuestions([]);\n this._phase = \"thinking\";\n const userId = this._options.userId;\n if (userId) {\n // The local message id doubles as the receipt token, so a drop report\n // for this prompt finds its message.\n const id = crypto.randomUUID();\n const command = { type: \"prompt\", prompt: text, messageId: id, senderId: userId } as const;\n this._appendMessage(command, \"user\", id);\n this._options.send(command);\n } else {\n this._appendMessage({ type: \"prompt\", prompt: text }, \"user\");\n this._options.send({ type: \"prompt\", prompt: text });\n }\n this._notify();\n }\n\n /**\n * Send a reply to the agent's pending question.\n *\n * Closes the answered sub-question locally before forwarding the reply command.\n *\n * @param answer - The user's answer text.\n * @param question - The sub-question being answered, verbatim from its\n * `question` event. Required for correctness in hosts that surface several\n * queued questions at once ({@link pendingQuestion} tracks only the latest,\n * so those hosts drive this from their own message history): without it the\n * agent files the answer under its next unanswered sub-question, which\n * mismatches any non-sequential reply.\n * @param requestId - Exact identity from the rendered question; never inferred from pending state.\n *\n * A multi-question ask stays parked until every sub-question has an answer:\n * until the last one, the phase stays idle and {@link pendingQuestion} moves\n * to the latest sub-question still open.\n */\n reply(answer: string, question?: string, requestId?: string): void {\n // A reply to a stale card must not clear a newer request in this client.\n if (this._pendingQuestion?.requestId && this._pendingQuestion.requestId !== requestId) return;\n if (this._openQuestions.length > 0) {\n // Same slot rule as the drivers: a name from this ask binds to its own\n // sub-question (re-answering a closed one closes nothing else), anything\n // else fills the oldest open one.\n const known = question !== undefined && this._askQuestions.has(question);\n const index = known ? this._openIndexOf(question) : 0;\n if (index !== -1) {\n this._setOpenQuestions(this._openQuestions.filter((_, i) => i !== index));\n }\n if (question === undefined && this._openQuestions.length > 0) this._unnamedEchoesOwed++;\n }\n // Answering the last open question resumes the agent turn — restore the\n // busy phase (mirrors prompt()) so the thinking indicator reappears at once\n // rather than after the agent's first resumed event lands.\n if (this._openQuestions.length === 0) this._phase = \"thinking\";\n const command = {\n type: \"reply\",\n answer,\n ...(question !== undefined ? { question } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n } as const;\n this._appendMessage(command, \"user\");\n this._options.send(command);\n this._notify();\n }\n\n /**\n * Cancel the current agent turn.\n *\n * Preserves partial streaming text in {@link cancelledText} so the UI can\n * display it. Clears streaming state, sets phase to `\"cancelling\"` (not\n * yet confirmed idle — see {@link AgentPhase}), and sends a `cancel`\n * command to the agent.\n */\n cancel(): void {\n // Preserve partial streaming text so the UI can still display it\n this._cancelledText = this._streamingText;\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"cancelling\";\n const userId = this._options.userId;\n this._options.send(userId ? { type: \"cancel\", senderId: userId } : { type: \"cancel\" });\n this._notify();\n }\n\n /**\n * Update shared state for a store namespace.\n *\n * Sends a `state_update` command to the agent and optimistically\n * updates local state so the change is reflected immediately.\n *\n * @param store - Store namespace (e.g. \"app\", \"component:render-123\").\n * @param state - Full state snapshot (replaces previous).\n */\n updateState(store: string, state: Record<string, unknown>): void {\n this._options.send({ type: \"state_update\", store, state });\n if (isSameJsonValue(this._sharedState.get(store), state, true)) return;\n // Optimistic local update\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(store, state);\n this._notify();\n }\n\n /**\n * Send an arbitrary command to the agent.\n *\n * Use this for commands that don't have a dedicated convenience method\n * (e.g. `ui_interaction`). No local state changes — the command is\n * forwarded as-is to the transport.\n *\n * @param cmd - The command to send.\n */\n send(cmd: AgentCommand): void {\n this._options.send(cmd);\n }\n\n /**\n * Load the previous page of messages and prepend them to the current list.\n *\n * No-op when `loadMessages` was not provided at construction time or when\n * all history has already been loaded ({@link isAllLoaded} is true).\n * Sets {@link isAllLoaded} to true once the server returns fewer messages\n * than the configured page size.\n */\n async loadPreviousMessages(): Promise<void> {\n if (!this._options.loadMessages || this._isAllLoaded) return;\n\n const pageSize = this._options.pageSize ?? DEFAULT_PAGE_SIZE;\n const before = this._messages.length > 0 ? this._messages[0].seq : undefined;\n const older = await this._options.loadMessages({ before, limit: pageSize });\n\n if (older.length < pageSize) this._isAllLoaded = true;\n\n const existingIds = new Set(this._messages.map((m) => m.id));\n const unique = older.filter((m) => !existingIds.has(m.id));\n this._messages = [...unique, ...this._messages];\n\n this._notify();\n }\n\n // -- External control ------------------------------------------------------\n\n /**\n * Programmatically update the connection status.\n *\n * Called by transport wrappers that cannot use the `onStatusChange`\n * callback (e.g. tRPC subscriptions that track status externally).\n *\n * Writing the status the store already holds is a no-op: it neither rotates\n * the snapshot nor notifies listeners.\n *\n * @param status - The new connection status.\n */\n setStatus(status: ConnectionStatus): void {\n if (this._status === status) return;\n this._status = status;\n this._notify();\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called synchronously after every state change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever state changes.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable state snapshot.\n *\n * A new object is produced lazily on the first call after each state change.\n * Subsequent calls return the same cached object until the next change.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): AgentStoreSnapshot => {\n if (!this._snapshot) {\n this._snapshot = {\n messages: this._messages,\n streamingText: this._streamingText,\n cancelledText: this._cancelledText,\n status: this._status,\n phase: this._phase,\n pendingQuestion: this._pendingQuestion,\n error: this._error,\n isAllLoaded: this._isAllLoaded,\n notSentPromptIds: this._notSentPromptIds,\n sharedState: this._sharedState,\n capabilities: this._capabilities,\n activeRenderInvocations: this._activeRenderInvocations,\n protocolInfo: this._protocolInfo,\n incompatibleProtocol: this._incompatibleProtocol,\n };\n }\n return this._snapshot;\n };\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events and clear all change listeners.\n *\n * Call this when the component or service that owns the store unmounts or\n * shuts down to prevent memory leaks.\n */\n dispose(): void {\n this._unsubEvent();\n this._unsubStatus?.();\n this._listeners.clear();\n }\n\n // -- Factory ---------------------------------------------------------------\n\n /**\n * Create an {@link AgentStore} connected to a duck-typed agent client.\n *\n * Adapts the client's `send`/`onEvent`/`offEvent` API to the\n * {@link StoreTransport} interface expected by the constructor, without\n * creating a hard runtime dependency on `@skaile/workspaces/client`.\n *\n * @param client - Any object implementing {@link AgentClientLike}.\n * @param opts - Optional store configuration.\n * @param opts.sessionId - Session ID for message envelopes (defaults to a new UUID).\n * @param opts.initialMessages - Messages to pre-populate the store with.\n *\n * @example\n * ```ts\n * const store = AgentStore.fromClient(agentClient, { sessionId: 'sess-123' })\n * ```\n */\n static fromClient(\n client: AgentClientLike,\n opts?: { sessionId?: string; initialMessages?: Message[] },\n ): AgentStore {\n return new AgentStore({\n sessionId: opts?.sessionId ?? crypto.randomUUID(),\n send: (cmd) => client.send(cmd),\n onEvent: (handler) => {\n client.onEvent(handler);\n return () => client.offEvent(handler);\n },\n initialMessages: opts?.initialMessages,\n });\n }\n\n // -- Internal --------------------------------------------------------------\n\n /** Replace the open sub-questions; `pendingQuestion` follows the latest one. */\n private _setOpenQuestions(open: QuestionEvent[]): void {\n this._openQuestions = open;\n this._pendingQuestion = open.at(-1) ?? null;\n if (open.length === 0) {\n this._askQuestions = new Set();\n this._unnamedEchoesOwed = 0;\n }\n }\n\n private _openIndexOf(question: string): number {\n return this._openQuestions.findIndex((q) => q.question === question);\n }\n\n private _handleEvent(event: AgentEvent): void {\n switch (event.type) {\n case \"text\":\n this._cancelledText = \"\";\n this._streamingText += event.content;\n this._streamingFlushed = false;\n break;\n\n case \"text_retract\":\n // The driver abandoned an attempt mid-message and is replaying it. Cut\n // only a matching tail: text already flushed into a message, or a\n // stream that no longer ends in the fragment, is left as it is.\n if (!event.content || !this._streamingText.endsWith(event.content)) return;\n this._streamingText = this._streamingText.slice(\n 0,\n this._streamingText.length - event.content.length,\n );\n break;\n\n case \"finished\":\n this._cancelledText = \"\";\n this._flushStreaming();\n this._appendMessage(event);\n // A cancelled finished is synthetic (persisted immediately for reload-\n // durability) and precedes the driver's real abort/kill sequence — stay\n // \"cancelling\" until the later, genuine status event reports \"idle\".\n if (!event.cancelled) this._phase = \"idle\";\n this._setOpenQuestions([]);\n break;\n\n case \"status\":\n // While cancelling, the driver's interrupt/unwind window can still emit\n // stale \"working\" statuses for already-buffered tool activity — ignore\n // anything but the genuine idle confirmation.\n if (this._phase === \"cancelling\" && event.phase !== \"idle\") return;\n // A parked question is the same shape: the driver re-emits the turn's\n // buffered tool activity — including one call for the question tool\n // itself — while nothing is actually running. Only the genuine idle\n // confirmation may move the phase until the user answers.\n if (this._pendingQuestion !== null && event.phase !== \"idle\") return;\n // The bridge re-emits phase:\"working\" on every tool call, so most status\n // events in a turn carry the phase we already hold. `_notify()` rotates\n // the snapshot, so notifying for them re-renders consumers for nothing.\n if (this._phase === event.phase) return;\n this._phase = event.phase;\n break;\n\n case \"user_message\":\n // A peer's message mid-turn is a boundary: finalize the in-flight text\n // so it renders before the interjection. Flush-only — the peer message\n // is delivered via the host's history, not this transient echo. The\n // flush is internally conditional, so an echo arriving while nothing is\n // streaming (the common case — peers talk between turns) changed no\n // state and notifying for it was a pure fanout.\n if (!this._flushStreaming()) return;\n break;\n\n case \"question_reply\": {\n // A peer answered: close its sub-question the same way `reply()` does.\n // The runner echoes every reply to all clients, so the replier's own\n // echo (its sub-question already closed) must leave this client\n // untouched. A named echo finds nothing left to close; an unnamed one\n // is matched by count. A complete arm rather than a fall through into\n // the group below: sharing that body once let a tool_call clear the flag.\n const pending = this._pendingQuestion;\n if (pending === null) return;\n if (pending.requestId !== undefined && pending.requestId !== event.requestId) return;\n let index = 0;\n if (event.question !== undefined) {\n index = this._openIndexOf(event.question);\n if (index === -1) return;\n } else if (this._unnamedEchoesOwed > 0) {\n this._unnamedEchoesOwed--;\n return;\n }\n this._setOpenQuestions(this._openQuestions.filter((_, i) => i !== index));\n this._flushStreaming();\n this._appendMessage(event);\n break;\n }\n\n case \"tool_call\":\n case \"tool_result\":\n case \"file_changed\":\n case \"subagent\":\n case \"dev_server\":\n case \"handoff\":\n // Flush in-flight text first so each text block becomes its own\n // Message, interleaved with tool activity in order — otherwise text\n // before and after a tool call merges into one wall-of-text blob.\n this._flushStreaming();\n this._appendMessage(event);\n break;\n\n case \"question\":\n // A pending question is a human-in-the-loop pause — the agent is waiting\n // for the user, not working. Reset to idle (like finished/error) so any\n // phase-derived busy indicator clears until the user replies.\n this._flushStreaming();\n this._phase = \"idle\";\n // One event arrives per sub-question. A different requestId is a new\n // ask; the same one (or none, as claude-sdk sends) extends the open set.\n if (this._openQuestions[0]?.requestId !== event.requestId) this._setOpenQuestions([]);\n this._setOpenQuestions([\n ...this._openQuestions.filter((q) => q.question !== event.question),\n event,\n ]);\n this._askQuestions.add(event.question);\n this._appendMessage(event);\n break;\n\n case \"error\":\n this._error = { message: event.message, fatal: event.fatal };\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"idle\";\n // A fatal error ends the turn like `finished`; a surviving question would\n // keep the status gate shut. Non-fatal side-channel errors leave it parked.\n if (event.fatal) this._setOpenQuestions([]);\n this._appendMessage(event);\n break;\n\n case \"state_changed\": {\n // Accumulate state per store namespace (notify only — no message).\n // Re-emits of unchanged state are routine, not exceptional: `serve.ts`\n // replays every namespace on connect (`buildStoreSnapshotReplay`), on a\n // seeded execution, on re-registering an already-registered store, and\n // immediately after registration — and the `xstate-store` adapter is\n // equality-free, so writing a key its current value emits too. Each of\n // those rebuilt the Map and rotated the snapshot for identical state.\n if (isSameJsonValue(this._sharedState.get(event.store), event.state)) return;\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(event.store, event.state);\n break;\n }\n\n // ── Protocol v2 ────────────────────────────────────────────────────────\n\n case \"capability_register\": {\n // TRANSIENT — accumulate v2 capabilities into the registry (no message).\n // The gateway replays the whole set on every (re)attach; a byte-identical\n // replay must not rotate the Map identity or notify, or a reconnect storm\n // compounds into an unbounded render loop in consumers.\n if (\n event.capabilities.every((cap) => isSameJsonValue(this._capabilities.get(cap.name), cap))\n ) {\n return;\n }\n this._capabilities = new Map(this._capabilities);\n for (const cap of event.capabilities) {\n this._capabilities.set(cap.name, cap);\n }\n break;\n }\n\n case \"capability_deregister\": {\n // TRANSIENT — drop capabilities by name. Names we never had are a no-op:\n // rebuilding the Map for them would notify with an identical registry.\n const present = event.names.filter((name) => this._capabilities.has(name));\n if (present.length === 0) return;\n this._capabilities = new Map(this._capabilities);\n for (const name of present) {\n this._capabilities.delete(name);\n }\n break;\n }\n\n case \"render_invoked\":\n // TRANSIENT — record latest render invocation (frontend pairs with\n // the matching `Capability.render` for placement).\n this._activeRenderInvocations = new Map(this._activeRenderInvocations);\n this._activeRenderInvocations.set(event.callId, event);\n break;\n\n case \"protocol_info\": {\n // TRANSIENT — runner announced its protocol version. It announces on\n // every attach, so tab mounts, StrictMode remounts and SSE reconnects\n // almost always carry the version we already hold. `ProtocolInfoEvent`\n // is nothing but `version`, and `ProtocolVersion` is exactly three\n // numbers, so the field comparison is complete, not conservative.\n //\n // A fresh announcement also retires any incompatibility notice: the\n // platform restarts the session on `incompatible_protocol`, and this\n // event is the replacement container introducing itself. Nothing cleared\n // `_incompatibleProtocol` before, so the restart banner was sticky for\n // the life of the store even though the platform's debug pane documents\n // this clear as already happening. Guarding without clearing would make\n // that permanent, since a repeat announcement would never get here.\n const held = this._protocolInfo?.version;\n const sameVersion =\n held !== undefined &&\n held.major === event.version.major &&\n held.minor === event.version.minor &&\n held.patch === event.version.patch;\n if (sameVersion && this._incompatibleProtocol === null) return;\n // Keep the held event object when the version is unchanged so consumers\n // with an effect keyed on `snapshot.protocolInfo` do not re-fire.\n if (!sameVersion) this._protocolInfo = event;\n this._incompatibleProtocol = null;\n break;\n }\n\n case \"queued_prompts_dropped\": {\n // TRANSIENT — the runner dropped these queued prompts on a cancel.\n // Ids already held are a no-op: no Set rebuild, no notify.\n const fresh = event.messageIds.filter((id) => !this._notSentPromptIds.has(id));\n if (fresh.length === 0) return;\n this._notSentPromptIds = new Set([...this._notSentPromptIds, ...fresh]);\n break;\n }\n\n case \"incompatible_protocol\":\n // TRANSIENT — runner detected version drift; platform restarts session.\n this._incompatibleProtocol = event;\n break;\n\n case \"capability_invoked\":\n // Backend intercepts client-side invocations and dispatches them\n // through V2CapabilityRegistryService — frontends should not see\n // these. Drop silently if one slips through.\n return;\n\n case \"resource_response\":\n case \"resources_available\":\n // Transient — handled by ResourceClient, not AgentStore\n return;\n\n default:\n // The switch names 24 of `AgentEvent`'s 61 members. The other 37 —\n // `log_entry` above all, one per line of container output — hold no\n // AgentStore state, so falling through to the trailing `_notify()`\n // rotated the snapshot and re-rendered every consumer for state that\n // had not changed. Unlike the guarded cases this was not a replay\n // artifact: it happened on every single occurrence. Hosts that need\n // these events (log panels, mount indicators, typing bubbles) read them\n // off the transport upstream of the store, not out of the snapshot.\n //\n // Deliberately not an `assertNever` exhaustiveness check: that is a\n // compile error while 37 members are unnamed, and naming all 61 would\n // enumerate events the store holds no state for just to satisfy it.\n return;\n }\n\n this._notify();\n }\n\n /**\n * Finalize buffered streaming text as a `text` Message.\n *\n * @returns true when text was flushed; false when there was nothing to flush,\n * so callers can skip a notify that would change nothing.\n */\n private _flushStreaming(): boolean {\n if (this._streamingFlushed || !this._streamingText) return false;\n this._appendMessage({ type: \"text\", content: this._streamingText });\n this._streamingText = \"\";\n this._streamingFlushed = true;\n return true;\n }\n\n private _appendMessage(\n payload: AgentCommand | AgentEvent,\n senderId?: string,\n id: string = crypto.randomUUID(),\n ): void {\n this._seq++;\n this._messages = [\n ...this._messages,\n {\n id,\n seq: this._seq,\n timestamp: new Date().toISOString(),\n sessionId: this._options.sessionId,\n ...(senderId ? { senderId } : {}),\n payload,\n },\n ];\n }\n\n private _notify(): void {\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n }\n}\n"]}
|