@skaile/workspaces 2.3.0 → 2.5.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 +60 -0
- package/README.md +32 -13
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-DKNYRLED.js → asset-feeds-4AWAT5PW.js} +6 -6
- package/dist/{asset-feeds-DKNYRLED.js.map → asset-feeds-4AWAT5PW.js.map} +1 -1
- package/dist/asset-manager/catalog-deployer.js +1 -1
- package/dist/asset-manager/index.js +5 -5
- package/dist/asset-manager/installer.js +2 -2
- package/dist/bridge/drivers/claude-sdk.js +108 -5
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +1 -1
- package/dist/bridge/drivers/continue.js +2 -2
- package/dist/bridge/drivers/echo.js +1 -1
- package/dist/bridge/drivers/gemini.js +3 -3
- package/dist/bridge/drivers/goose.js +2 -2
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/drivers/opencode.js +2 -2
- package/dist/bridge/drivers/qwen.js +3 -3
- package/dist/bridge/index.js +2 -2
- package/dist/bridge/src/drivers/claude-sdk.d.ts +33 -0
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/{chunk-CERGXDGG.js → chunk-2OCYS5EP.js} +3 -3
- package/dist/{chunk-CERGXDGG.js.map → chunk-2OCYS5EP.js.map} +1 -1
- package/dist/{chunk-W3Q37HEF.js → chunk-3HVASHBF.js} +3 -3
- package/dist/{chunk-W3Q37HEF.js.map → chunk-3HVASHBF.js.map} +1 -1
- package/dist/{chunk-UQ3RJKDD.js → chunk-4O2RAXKJ.js} +179 -52
- package/dist/chunk-4O2RAXKJ.js.map +1 -0
- package/dist/{chunk-DZM33LQO.js → chunk-4QROZZ5Z.js} +15 -3
- package/dist/chunk-4QROZZ5Z.js.map +1 -0
- package/dist/{chunk-G2ILW47R.js → chunk-57RFYEVM.js} +3 -3
- package/dist/{chunk-G2ILW47R.js.map → chunk-57RFYEVM.js.map} +1 -1
- package/dist/{chunk-BLWNI5KW.js → chunk-AKVAZ5CB.js} +2 -2
- package/dist/{chunk-BLWNI5KW.js.map → chunk-AKVAZ5CB.js.map} +1 -1
- package/dist/{chunk-BFIK6NPZ.js → chunk-AM5LFRXJ.js} +3 -3
- package/dist/{chunk-BFIK6NPZ.js.map → chunk-AM5LFRXJ.js.map} +1 -1
- package/dist/{chunk-RDE43ORT.js → chunk-D4VHBAJC.js} +4 -4
- package/dist/{chunk-RDE43ORT.js.map → chunk-D4VHBAJC.js.map} +1 -1
- package/dist/{chunk-PTS3QN5P.js → chunk-EEHOMCRU.js} +1021 -115
- package/dist/chunk-EEHOMCRU.js.map +1 -0
- package/dist/{chunk-CXX3UGJP.js → chunk-ENBTXMPL.js} +7 -7
- package/dist/{chunk-CXX3UGJP.js.map → chunk-ENBTXMPL.js.map} +1 -1
- package/dist/{chunk-LD6YGIKZ.js → chunk-EUWN4EK4.js} +60 -21
- package/dist/chunk-EUWN4EK4.js.map +1 -0
- package/dist/{chunk-FB4GPWYC.js → chunk-FKBQRV4J.js} +57 -16
- package/dist/chunk-FKBQRV4J.js.map +1 -0
- package/dist/{chunk-WG3L5VHF.js → chunk-HY3MBSNC.js} +2 -2
- package/dist/{chunk-WG3L5VHF.js.map → chunk-HY3MBSNC.js.map} +1 -1
- package/dist/{chunk-7IRH7MGV.js → chunk-IHX2SN35.js} +9 -9
- package/dist/{chunk-7IRH7MGV.js.map → chunk-IHX2SN35.js.map} +1 -1
- package/dist/{chunk-3F54MH2T.js → chunk-JAFEMG7W.js} +4 -4
- package/dist/{chunk-3F54MH2T.js.map → chunk-JAFEMG7W.js.map} +1 -1
- package/dist/{chunk-X6BPVUV2.js → chunk-L3TS7ZO4.js} +3 -3
- package/dist/{chunk-X6BPVUV2.js.map → chunk-L3TS7ZO4.js.map} +1 -1
- package/dist/{chunk-RIEXN7WA.js → chunk-MADO7PH5.js} +2 -2
- package/dist/{chunk-RIEXN7WA.js.map → chunk-MADO7PH5.js.map} +1 -1
- package/dist/{chunk-BCTU4TN7.js → chunk-MWFYXUFK.js} +3 -3
- package/dist/{chunk-BCTU4TN7.js.map → chunk-MWFYXUFK.js.map} +1 -1
- package/dist/{chunk-TK66CMXV.js → chunk-NU4E7C5I.js} +7 -3
- package/dist/chunk-NU4E7C5I.js.map +1 -0
- package/dist/{chunk-ZE2KEPE2.js → chunk-OEGHKO5N.js} +258 -24
- package/dist/chunk-OEGHKO5N.js.map +1 -0
- package/dist/{chunk-63ZPKREA.js → chunk-P43HBWKK.js} +11 -4
- package/dist/chunk-P43HBWKK.js.map +1 -0
- package/dist/{chunk-7UZGKVSK.js → chunk-PJ6INYDD.js} +3 -3
- package/dist/{chunk-7UZGKVSK.js.map → chunk-PJ6INYDD.js.map} +1 -1
- package/dist/{chunk-CA5CWLGN.js → chunk-PKEAYYEJ.js} +7 -4
- package/dist/chunk-PKEAYYEJ.js.map +1 -0
- package/dist/{chunk-ETFETLLB.js → chunk-UZYTSIX6.js} +6 -6
- package/dist/{chunk-ETFETLLB.js.map → chunk-UZYTSIX6.js.map} +1 -1
- package/dist/{chunk-SIF5F5SN.js → chunk-V4ZLZJFN.js} +3 -3
- package/dist/{chunk-SIF5F5SN.js.map → chunk-V4ZLZJFN.js.map} +1 -1
- package/dist/{chunk-ZR5Q4KZK.js → chunk-VNIKF66R.js} +3 -3
- package/dist/{chunk-ZR5Q4KZK.js.map → chunk-VNIKF66R.js.map} +1 -1
- package/dist/{chunk-CILACPUC.js → chunk-WSARNOPP.js} +5 -5
- package/dist/{chunk-CILACPUC.js.map → chunk-WSARNOPP.js.map} +1 -1
- package/dist/{chunk-TAJBFYCT.js → chunk-YWPEDILM.js} +83 -36
- package/dist/chunk-YWPEDILM.js.map +1 -0
- package/dist/{chunk-UNP4M5ZZ.js → chunk-ZR2X4SIG.js} +4 -4
- package/dist/{chunk-UNP4M5ZZ.js.map → chunk-ZR2X4SIG.js.map} +1 -1
- package/dist/cli/index.js +50 -50
- package/dist/connectors/config.js +1 -1
- package/dist/connectors/index.js +6 -6
- package/dist/core/index.js +1 -1
- package/dist/core/src/subprocess.d.ts +5 -1
- package/dist/core/src/subprocess.d.ts.map +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/discovery/index.js +1 -1
- package/dist/{ensure-sources-R6KW7K3M.js → ensure-sources-QF72HVUM.js} +8 -8
- package/dist/{ensure-sources-R6KW7K3M.js.map → ensure-sources-QF72HVUM.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +6 -6
- package/dist/factory-assets/connectors/deploy.js +6 -6
- package/dist/factory-assets/connectors/devserver.js +6 -6
- package/dist/factory-assets/connectors/flow/CONNECTOR.md +61 -14
- package/dist/factory-assets/connectors/flow/adapter.d.ts +78 -34
- package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/adapter.js +6 -6
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts +55 -0
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/flow.v2.schema.json +61 -134
- package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
- package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/normalize.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts +14 -2
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract.js +2 -2
- package/dist/factory-assets/connectors/flow/engine/bindings.d.ts +9 -0
- package/dist/factory-assets/connectors/flow/engine/bindings.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts +11 -6
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/flow-kind-provider.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/index.d.ts +2 -0
- package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts +22 -0
- package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts +18 -0
- package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/engine/types.d.ts +21 -15
- package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine.js +4 -4
- package/dist/factory-assets/connectors/flow/index.d.ts +3 -0
- package/dist/factory-assets/connectors/flow/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts +48 -0
- package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/node-executor.d.ts +45 -0
- package/dist/factory-assets/connectors/flow/node-executor.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts +3 -2
- package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/prompt-fragments.js +2 -2
- package/dist/factory-assets/connectors/flow/run-flow.d.ts +10 -9
- package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/run-flow.js +7 -7
- package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts +73 -0
- package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow.js +6 -6
- package/dist/factory-assets/connectors/git.js +6 -6
- package/dist/factory-assets/connectors/gmail.js +6 -6
- package/dist/factory-assets/connectors/googledrive.js +6 -6
- package/dist/factory-assets/connectors/local.js +6 -6
- package/dist/factory-assets/connectors/mattermost.js +6 -6
- package/dist/factory-assets/connectors/memory.js +6 -6
- package/dist/factory-assets/connectors/minio.js +6 -6
- package/dist/factory-assets/connectors/postgres.js +6 -6
- package/dist/factory-assets/connectors/s3.js +6 -6
- package/dist/factory-assets/connectors/sharepoint.js +6 -6
- package/dist/factory-assets/connectors/sqlite.js +6 -6
- package/dist/factory-assets/connectors/static-server.js +6 -6
- package/dist/factory-assets/connectors/tunnel.js +6 -6
- package/dist/factory-assets/connectors/webdav.js +6 -6
- package/dist/factory-assets/connectors/xstate-store.js +6 -6
- package/dist/factory-assets/connectors/xstate.js +6 -6
- package/dist/{flows-F3CJNMK6.js → flows-YIW4HL3L.js} +4 -4
- package/dist/{flows-F3CJNMK6.js.map → flows-YIW4HL3L.js.map} +1 -1
- package/dist/{helpers-KPOLCGKX.js → helpers-LURCZHA4.js} +8 -8
- package/dist/{helpers-KPOLCGKX.js.map → helpers-LURCZHA4.js.map} +1 -1
- package/dist/library/index.js +3 -3
- package/dist/library/install.js +1 -1
- package/dist/{library-publish-ZAPZS64O.js → library-publish-2GMJM3NZ.js} +14 -14
- package/dist/{library-publish-ZAPZS64O.js.map → library-publish-2GMJM3NZ.js.map} +1 -1
- package/dist/{open-library-I4F2UNOY.js → open-library-POFOXZWH.js} +12 -12
- package/dist/{open-library-I4F2UNOY.js.map → open-library-POFOXZWH.js.map} +1 -1
- package/dist/{paths-KBACHM5B.js → paths-ZLX4ITAQ.js} +6 -6
- package/dist/{paths-KBACHM5B.js.map → paths-ZLX4ITAQ.js.map} +1 -1
- package/dist/{plugin-store-CYSNVZIX.js → plugin-store-YIMNH2FH.js} +3 -3
- package/dist/{plugin-store-CYSNVZIX.js.map → plugin-store-YIMNH2FH.js.map} +1 -1
- package/dist/{project-SIHZBTGB.js → project-GVOPZEJZ.js} +9 -9
- package/dist/{project-SIHZBTGB.js.map → project-GVOPZEJZ.js.map} +1 -1
- package/dist/resolver/index.js +1 -1
- package/dist/runner/index.js +15 -12
- package/dist/runner/src/serve.d.ts +3 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +5 -5
- package/dist/sdk/bridge.js +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/flow.js +4 -4
- package/dist/sdk/index.js +15 -12
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/resolver.js +1 -1
- package/dist/sdk/runner.js +15 -12
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/types.js +1 -1
- package/dist/session/index.js +2 -2
- package/dist/session/src/dispatcher.d.ts.map +1 -1
- package/dist/{setup-KMBXMV25.js → setup-RHWARBBB.js} +5 -5
- package/dist/{setup-KMBXMV25.js.map → setup-RHWARBBB.js.map} +1 -1
- package/dist/{skills-LHS4TOKK.js → skills-HGVH6UTA.js} +5 -5
- package/dist/{skills-LHS4TOKK.js.map → skills-HGVH6UTA.js.map} +1 -1
- package/dist/{source-X226ZJPR.js → source-FB3T4IHP.js} +13 -13
- package/dist/{source-X226ZJPR.js.map → source-FB3T4IHP.js.map} +1 -1
- package/dist/{source-manifest-publish-N2QVUR5U.js → source-manifest-publish-XTRDVPSC.js} +15 -15
- package/dist/{source-manifest-publish-N2QVUR5U.js.map → source-manifest-publish-XTRDVPSC.js.map} +1 -1
- package/dist/tui/index.js +15 -12
- package/dist/tui/index.js.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/src/events.d.ts +20 -1
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/types/src/flow.d.ts +26 -0
- package/dist/types/src/flow.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/protocol.d.ts +1 -0
- package/dist/types/src/protocol.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 +4 -4
- package/dist/workspace-plugin/adapters/omp.js +7 -7
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-63ZPKREA.js.map +0 -1
- package/dist/chunk-CA5CWLGN.js.map +0 -1
- package/dist/chunk-DZM33LQO.js.map +0 -1
- package/dist/chunk-FB4GPWYC.js.map +0 -1
- package/dist/chunk-LD6YGIKZ.js.map +0 -1
- package/dist/chunk-PTS3QN5P.js.map +0 -1
- package/dist/chunk-TAJBFYCT.js.map +0 -1
- package/dist/chunk-TK66CMXV.js.map +0 -1
- package/dist/chunk-UQ3RJKDD.js.map +0 -1
- package/dist/chunk-ZE2KEPE2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../workspace-plugin/src/adapters/claude-code.ts","../workspace-plugin/src/store.ts","../workspace-plugin/src/plugin.ts","../workspace-plugin/src/utils/project-dir.ts"],"names":["err"],"mappings":";;;;;;AAeA,IAAM,WAAA,GAAc;AAAA,EAClB,IAAA,EAAM,QAAA;AAAA,EACN,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,yEAAA;AAAA,EACb,MAAA,EAAQ,EAAE,IAAA,EAAM,WAAA,EAAa,KAAK,8BAAA,EAA+B;AAAA,EACjE,UAAA,EAAY,yCAAA;AAAA,EACZ,QAAA,EAAU,CAAC,QAAA,EAAU,YAAA,EAAc,aAAa,WAAW,CAAA;AAAA,EAC3D,KAAA,EAAO,oBAAA;AAAA,EACP,UAAA,EAAY,aAAA;AAAA,EACZ,UAAA,EAAY;AAAA,IACV,gBAAA,EAAkB;AAAA,MAChB,IAAA,EAAM,QAAA;AAAA,MACN,KAAA,EAAO,kBAAA;AAAA,MACP,WAAA,EAAa;AAAA;AACf;AAEJ,CAAA;AAOA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO;AAAA,IACL,YAAA,EAAc,CAAC,EAAE,KAAA,EAAO,CAAC,EAAE,IAAA,EAAM,SAAA,EAAW,OAAA,EAAS,kCAAA,EAAoC,CAAA,EAAG,CAAA;AAAA,IAC5F,UAAA,EAAY,CAAC,EAAE,KAAA,EAAO,CAAC,EAAE,IAAA,EAAM,SAAA,EAAW,OAAA,EAAS,gCAAA,EAAkC,CAAA,EAAG,CAAA;AAAA,IACxF,gBAAA,EAAkB;AAA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B,IAAI,CAAA;AAAA,EAC7B;AAAA,EAEA,MAAM,uBAAA,GAA2C;AAC/C,IAAA,MAAM,EAAE,uBAAA,EAAwB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AACpE,IAAA,OAAO,uBAAA,CAAwB,KAAK,UAAU,CAAA;AAAA,EAChD;AAAA,EAEA,MAAM,kBAAA,CAAmB,KAAA,EAAe,IAAA,EAAiC;AACvE,IAAA,MAAM,EAAE,kBAAA,EAAmB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AAC/D,IAAA,OAAO,kBAAA,CAAmB,IAAA,EAAM,KAAA,EAAO,IAAI,CAAA;AAAA,EAC7C;AACF;;;AC1OO,SAAS,kBAAkB,iBAAA,EAAsC;AACtE,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,kBAAA,EAAoB,OAAO,QAAQ,GAAA,CAAI,kBAAA;AACvD,EAAA,KAAA,MAAW,GAAA,IAAO,iBAAA,IAAqB,EAAC,EAAG;AACzC,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC3B,IAAA,IAAI,KAAK,OAAO,GAAA;AAAA,EAClB;AACA,EAAA,OAAO,QAAQ,GAAA,EAAI;AACrB","file":"chunk-BLWNI5KW.js","sourcesContent":["// ── Claude Code plugin-directory generator (STATELESS) ──────────────────────\n// Generates the contents of a Claude Code plugin directory\n// (`.claude/plugins/skaile/`) as an in-memory file map. No plugin instance or\n// boot() is required — safe to call from install commands.\n//\n// The previous standalone `@skaile/workspace-plugin-claude` package shipped\n// these as static files plus loose `.mjs` hook scripts; they are now\n// CLI-owned templates. Hooks invoke the `skaile` binary directly\n// (`skaile plugin hook <event>`) and MCP runs via `skaile mcp-server` — no\n// generated script files, no shebang, no runtime assumption.\n\n/**\n * The Claude Code plugin manifest. `name` is `skaile`; `hooks` and\n * `mcpServers` point at sibling files in the generated directory.\n */\nconst PLUGIN_JSON = {\n name: \"skaile\",\n version: \"0.1.0\",\n description: \"Skaile workspace — connectors, mounts, skills, flows, shared state\",\n author: { name: \"skaile-ai\", url: \"https://github.com/skaile-ai\" },\n repository: \"https://github.com/skaile-ai/workspaces\",\n keywords: [\"skaile\", \"connectors\", \"workspace\", \"ai-assets\"],\n hooks: \"./hooks/hooks.json\",\n mcpServers: \"./.mcp.json\",\n userConfig: {\n skaile_yaml_path: {\n type: \"string\",\n title: \"skaile.yaml path\",\n description: \"Override path to skaile.yaml (default: auto-detect from project root)\",\n },\n },\n};\n\n/**\n * Hook wiring. Each lifecycle event invokes the `skaile` binary directly —\n * no loose `.mjs` scripts. `skaile plugin hook <event>` resolves the project\n * directory itself (`CLAUDE_PROJECT_DIR` / cwd) and always exits 0.\n */\nconst HOOKS_JSON = {\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-start\" }] }],\n SessionEnd: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-end\" }] }],\n UserPromptSubmit: [\n { hooks: [{ type: \"command\", command: \"skaile plugin hook user-prompt-submit\" }] },\n ],\n },\n};\n\n/**\n * MCP server wiring. Spawns `skaile mcp-server` — a stdio MCP subprocess that\n * runs on plain Node (no Claude Agent SDK).\n */\nconst MCP_JSON = {\n mcpServers: {\n \"skaile-workspace\": {\n command: \"skaile\",\n args: [\"mcp-server\"],\n env: {},\n },\n },\n};\n\n/**\n * Build the Claude Code plugin directory as an in-memory file map.\n *\n * Returns `{ relativePath: contents }` for every file the installer must\n * write under `<projectDir>/.claude/plugins/skaile/`. The installer is also\n * responsible for populating `skills/` from the project's `.skaile/skills/`.\n *\n * Stateless — no plugin instance, no `boot()`. The generated artifacts carry\n * no project-specific paths: hooks and the MCP server resolve the project\n * directory themselves at runtime.\n *\n * @returns A map of plugin-relative file paths to their string contents.\n *\n * @docLink packages/workspace-plugin/concepts#adapters\n */\nexport function buildClaudePluginFiles(): Record<string, string> {\n return {\n \".claude-plugin/plugin.json\": `${JSON.stringify(PLUGIN_JSON, null, 2)}\\n`,\n \"hooks/hooks.json\": `${JSON.stringify(HOOKS_JSON, null, 2)}\\n`,\n \".mcp.json\": `${JSON.stringify(MCP_JSON, null, 2)}\\n`,\n \"skills/.gitkeep\": \"\",\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\ninterface Subscriber {\n regex: RegExp;\n handler: (key: string, value: unknown) => void;\n}\n\n/**\n * Disk-backed reactive key-value store for plugin state.\n *\n * Keeps an in-memory map that can be flushed to / loaded from a JSON file.\n * Supports glob-style subscriptions (`connector:*`, `*`).\n *\n * State is persisted to `<projectDir>/.skaile/plugin-state.json`.\n * The instance is available on {@link WorkspacePlugin} as the public `store`\n * field after `boot()` resolves.\n *\n * @docLink packages/workspace-plugin/concepts#plugin-store\n */\nexport class PluginStore {\n private readonly statePath: string;\n private data: Map<string, unknown> = new Map();\n private subscribers: Subscriber[] = [];\n\n constructor(statePath: string) {\n this.statePath = statePath;\n }\n\n /** Synchronous read from in-memory map. */\n get<T>(key: string): T | undefined {\n return this.data.get(key) as T | undefined;\n }\n\n /** Write to in-memory map and notify matching subscribers. */\n set<T>(key: string, value: T): void {\n this.data.set(key, value);\n this.notify(key, value);\n }\n\n /** Remove key and notify matching subscribers. */\n delete(key: string): void {\n this.data.delete(key);\n this.notify(key, undefined);\n }\n\n /**\n * Subscribe to changes matching a glob-style pattern.\n * `*` matches any sequence of characters.\n * Returns an unsubscribe function.\n */\n subscribe(pattern: string, handler: (key: string, value: unknown) => void): () => void {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexStr = `^${escaped.replace(/\\*/g, \".*\")}$`;\n const sub: Subscriber = { regex: new RegExp(regexStr), handler };\n this.subscribers.push(sub);\n\n return () => {\n const idx = this.subscribers.indexOf(sub);\n if (idx !== -1) this.subscribers.splice(idx, 1);\n };\n }\n\n /** Rehydrate from disk JSON. Missing file = empty store (no throw). */\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n this.data = new Map(Object.entries(parsed));\n }\n } catch (e: unknown) {\n // Missing file or invalid JSON — start with empty store\n }\n }\n\n /** Write entire store to disk as JSON. Creates parent dirs if needed. */\n async flush(): Promise<void> {\n const obj = Object.fromEntries(this.data);\n const json = JSON.stringify(obj, null, 2);\n await mkdir(dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, json, \"utf-8\");\n }\n\n private notify(key: string, value: unknown): void {\n for (const sub of this.subscribers) {\n if (sub.regex.test(key)) {\n sub.handler(key, value);\n }\n }\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { PluginStore } from \"./store.js\";\n\n/**\n * Construction options for {@link WorkspacePlugin}.\n *\n * At minimum `projectDir` must be supplied. All other fields are optional\n * and are pre-resolved by the caller when available (e.g. the runner already\n * knows `driver`/`provider`/`model` from its own settings resolution).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport interface WorkspacePluginOpts {\n projectDir: string;\n /**\n * Active connector manager. The unified `ConnectorManager` owns both\n * filesystem-face (mountable) and tool-face connectors.\n */\n connectorManager?: ConnectorManager;\n bootOwned?: boolean;\n onLog?: (msg: string) => void;\n /** Pre-resolved driver type (avoids needing boot() to read settings). */\n driver?: string;\n /** Pre-resolved provider. */\n provider?: string;\n /** Pre-resolved model. */\n model?: string;\n}\n\n/**\n * Shared runtime core for the skaile workspace plugin.\n *\n * Manages the full lifecycle (`boot` → tools available → `shutdown`) and\n * surfaces workspace capabilities — mounts, connectors, flows, skills,\n * sessions, and config validation — through two adapter backends:\n *\n * - **MCP, in-process** (runner): call {@link buildWorkspaceMcpServer} for the\n * Claude Agent SDK server the runner embeds into its `query()` call.\n * - **MCP, stdio** (`skaile mcp-server`): call {@link runMcpServerStdio} for a\n * raw `@modelcontextprotocol/sdk` server — no Claude Agent SDK.\n * - **OMP**: call {@link buildOmpToolSet} for the 13-tool native subset and\n * {@link buildOmpExtensionSource} for the generated extension file.\n *\n * Two boot modes are supported via {@link WorkspacePluginOpts.bootOwned}:\n * - `bootOwned: false` (default) — managers injected externally by the runner.\n * - `bootOwned: true` — plugin owns the full manager lifecycle (standalone MCP\n * subprocess or OMP extension).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport class WorkspacePlugin {\n readonly projectDir: string;\n connectorManager: ConnectorManager | null;\n readonly store: PluginStore;\n\n private readonly bootOwned: boolean;\n private readonly onLog: (msg: string) => void;\n private readonly log: Logger = createLogger({\n kind: \"mcp\",\n subkind: \"skaile-workspace\",\n });\n driver?: string;\n provider?: string;\n model?: string;\n\n constructor(opts: WorkspacePluginOpts) {\n this.projectDir = opts.projectDir;\n this.connectorManager = opts.connectorManager ?? null;\n this.store = new PluginStore(join(opts.projectDir, \".skaile\", \"plugin-state.json\"));\n this.bootOwned = opts.bootOwned ?? false;\n if (opts.driver) this.driver = opts.driver;\n if (opts.provider) this.provider = opts.provider;\n if (opts.model) this.model = opts.model;\n this.onLog = opts.onLog ?? (() => {});\n this.log.debug(\"plugin constructed\", {\n driver: opts.driver,\n hasConnectors: !!opts.connectorManager,\n provider: opts.provider,\n model: opts.model,\n bootOwned: this.bootOwned,\n });\n }\n\n async boot(): Promise<void> {\n if (!this.bootOwned) {\n // Managers were injected externally — resolve settings only (non-fatal)\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n await this.store.load();\n return;\n }\n\n // bootOwned: we own the managers lifecycle\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n\n try {\n const {\n ConnectorManager,\n loadConnectorDeclarations,\n registerBuiltinConnectors,\n createCliSecretProviderChain,\n } = await import(\"@skaile/workspaces/connectors\");\n\n registerBuiltinConnectors();\n\n const secrets = createCliSecretProviderChain();\n\n const connectorDecls = await loadConnectorDeclarations(this.projectDir);\n const cm = new ConnectorManager(this.projectDir, { secrets });\n await cm.connectAll(connectorDecls);\n this.connectorManager = cm;\n\n this.log.info(\"workspace plugin booted\", {\n connectors: connectorDecls.length,\n });\n this.onLog(`WorkspacePlugin booted: ${connectorDecls.length} connectors`);\n } catch (err) {\n this.log.warn(\"workspace plugin boot warning\", {\n error: err instanceof Error ? err.message : String(err),\n });\n this.onLog(`WorkspacePlugin boot warning: ${err}`);\n }\n\n await this.store.load();\n }\n\n async reload(): Promise<void> {\n if (!this.bootOwned) return;\n await this.shutdown();\n await this.boot();\n }\n\n async shutdown(): Promise<void> {\n this.log.info(\"workspace plugin shutdown\");\n await this.store.flush();\n if (!this.bootOwned) return;\n try {\n await (this.connectorManager as any)?.disconnectAll?.();\n } catch {\n /* best-effort */\n }\n this.connectorManager = null;\n }\n\n buildSystemPromptSection(driver?: string): string {\n const d = driver ?? this.driver ?? \"unknown\";\n // The unified ConnectorManager owns both mountable (filesystem-face) and\n // tool-face connectors. Filesystem-face connectors expose a `mountPath`.\n const all = (this.connectorManager as any)?.listConnectors?.() ?? [];\n const mounts = (all as any[]).filter((c) => typeof c.mountPath === \"string\");\n const connectors = (all as any[]).filter((c) => typeof c.mountPath !== \"string\");\n const lines = [\"## Workspace (skaile)\", \"\", `Driver: ${d}`, `Project: ${this.projectDir}`];\n if (mounts.length > 0) {\n lines.push(\"\", \"Mounts:\");\n for (const v of mounts) {\n lines.push(` · ${v.id} (${v.driver}) → ${v.mountPath ?? \"(unmounted)\"}`);\n }\n }\n if (connectors.length > 0) {\n lines.push(\"\", \"Connectors:\");\n for (const c of connectors) {\n lines.push(` · ${c.id} (${c.driver})`);\n }\n }\n lines.push(\"\", \"Use workspace_info for full details. Use workspace_validate to check health.\");\n\n for (const name of [\"SOUL.md\", \"RULES.md\"]) {\n const skaileOverride = join(this.projectDir, \".skaile\", name);\n const rootFile = join(this.projectDir, name);\n for (const candidate of [skaileOverride, rootFile]) {\n try {\n const content = readFileSync(candidate, \"utf-8\").trim();\n if (content) {\n lines.push(\"\", `## ${name.replace(\".md\", \"\")}`, \"\", content);\n break;\n }\n } catch {\n // file not found, try next\n }\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Build the in-process Claude Agent SDK MCP server (runner embedding).\n * Returns `null` when `@anthropic-ai/claude-agent-sdk` is unavailable.\n */\n async buildWorkspaceMcpServer(): Promise<unknown | null> {\n this.log.info(\"building workspace MCP server\");\n try {\n const { buildWorkspaceMcpServer } = await import(\"./adapters/mcp.js\");\n const server = await buildWorkspaceMcpServer(this);\n if (server) this.log.info(\"workspace MCP server ready\");\n else this.log.debug(\"workspace MCP server skipped (no tools)\");\n return server;\n } catch (err) {\n this.log.error(\"workspace MCP server build failed\", err);\n throw err;\n }\n }\n\n /**\n * Build the raw `@modelcontextprotocol/sdk` stdio MCP server — no Claude\n * Agent SDK. Used by the `skaile mcp-server` subprocess. The returned\n * server is not yet connected to a transport.\n */\n async buildWorkspaceMcpStdioServer(): Promise<unknown> {\n this.log.info(\"building workspace stdio MCP server\");\n const { buildWorkspaceMcpStdioServer } = await import(\"./adapters/mcp.js\");\n return buildWorkspaceMcpStdioServer(this);\n }\n\n /**\n * Build and run the stdio MCP server: builds the raw\n * `@modelcontextprotocol/sdk` server and connects a `StdioServerTransport`.\n * Used by the `skaile mcp-server` subprocess.\n */\n async runMcpServerStdio(): Promise<void> {\n this.log.info(\"starting workspace stdio MCP server\");\n const { runMcpServerStdio } = await import(\"./adapters/mcp.js\");\n await runMcpServerStdio(this);\n }\n\n async buildOmpToolSet(): Promise<unknown[]> {\n const { buildOmpToolSet } = await import(\"./adapters/omp.js\");\n return buildOmpToolSet(this);\n }\n\n async buildOmpExtensionSource(): Promise<string> {\n const { buildOmpExtensionSource } = await import(\"./adapters/omp.js\");\n return buildOmpExtensionSource(this.projectDir);\n }\n\n async handleSlashCommand(group: string, args: string[]): Promise<string> {\n const { handleSlashCommand } = await import(\"./adapters/omp.js\");\n return handleSlashCommand(this, group, args);\n }\n}\n","// utils/project-dir.ts\n// Centralised project-directory resolution used by all plugin entry points.\n\n/**\n * Resolve the skaile project directory from environment variables.\n *\n * Resolution order:\n * 1. `SKAILE_PROJECT_DIR` (always checked first)\n * 2. Any additional env var keys supplied by the caller (in order)\n * 3. `process.cwd()` as final fallback\n *\n * @param additionalEnvVars - Optional list of extra environment variable names\n * to check before falling back to `process.cwd()`.\n * @returns Absolute path to the resolved project directory.\n *\n * @example\n * // Claude Code — also checks CLAUDE_PROJECT_DIR\n * const projectDir = resolveProjectDir([\"CLAUDE_PROJECT_DIR\"]);\n *\n * // OMP / standalone — SKAILE_PROJECT_DIR or cwd only\n * const projectDir = resolveProjectDir();\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function resolveProjectDir(additionalEnvVars?: string[]): string {\n if (process.env.SKAILE_PROJECT_DIR) return process.env.SKAILE_PROJECT_DIR;\n for (const key of additionalEnvVars ?? []) {\n const val = process.env[key];\n if (val) return val;\n }\n return process.cwd();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../workspace-plugin/src/adapters/claude-code.ts","../workspace-plugin/src/store.ts","../workspace-plugin/src/plugin.ts","../workspace-plugin/src/utils/project-dir.ts"],"names":["err"],"mappings":";;;;;;AAeA,IAAM,WAAA,GAAc;AAAA,EAClB,IAAA,EAAM,QAAA;AAAA,EACN,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,yEAAA;AAAA,EACb,MAAA,EAAQ,EAAE,IAAA,EAAM,WAAA,EAAa,KAAK,8BAAA,EAA+B;AAAA,EACjE,UAAA,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AC,EAAG;AACzC,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC3B,IAAA,IAAI,KAAK,OAAO,GAAA;AAAA,EAClB;AACA,EAAA,OAAO,QAAQ,GAAA,EAAI;AACrB","file":"chunk-AKVAZ5CB.js","sourcesContent":["// ── Claude Code plugin-directory generator (STATELESS) ──────────────────────\n// Generates the contents of a Claude Code plugin directory\n// (`.claude/plugins/skaile/`) as an in-memory file map. No plugin instance or\n// boot() is required — safe to call from install commands.\n//\n// The previous standalone `@skaile/workspace-plugin-claude` package shipped\n// these as static files plus loose `.mjs` hook scripts; they are now\n// CLI-owned templates. Hooks invoke the `skaile` binary directly\n// (`skaile plugin hook <event>`) and MCP runs via `skaile mcp-server` — no\n// generated script files, no shebang, no runtime assumption.\n\n/**\n * The Claude Code plugin manifest. `name` is `skaile`; `hooks` and\n * `mcpServers` point at sibling files in the generated directory.\n */\nconst PLUGIN_JSON = {\n name: \"skaile\",\n version: \"0.1.0\",\n description: \"Skaile workspace — connectors, mounts, skills, flows, shared state\",\n author: { name: \"skaile-ai\", url: \"https://github.com/skaile-ai\" },\n repository: \"https://github.com/skaile-ai/workspaces\",\n keywords: [\"skaile\", \"connectors\", \"workspace\", \"ai-assets\"],\n hooks: \"./hooks/hooks.json\",\n mcpServers: \"./.mcp.json\",\n userConfig: {\n skaile_yaml_path: {\n type: \"string\",\n title: \"skaile.yaml path\",\n description: \"Override path to skaile.yaml (default: auto-detect from project root)\",\n },\n },\n};\n\n/**\n * Hook wiring. Each lifecycle event invokes the `skaile` binary directly —\n * no loose `.mjs` scripts. `skaile plugin hook <event>` resolves the project\n * directory itself (`CLAUDE_PROJECT_DIR` / cwd) and always exits 0.\n */\nconst HOOKS_JSON = {\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-start\" }] }],\n SessionEnd: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-end\" }] }],\n UserPromptSubmit: [\n { hooks: [{ type: \"command\", command: \"skaile plugin hook user-prompt-submit\" }] },\n ],\n },\n};\n\n/**\n * MCP server wiring. Spawns `skaile mcp-server` — a stdio MCP subprocess that\n * runs on plain Node (no Claude Agent SDK).\n */\nconst MCP_JSON = {\n mcpServers: {\n \"skaile-workspace\": {\n command: \"skaile\",\n args: [\"mcp-server\"],\n env: {},\n },\n },\n};\n\n/**\n * Build the Claude Code plugin directory as an in-memory file map.\n *\n * Returns `{ relativePath: contents }` for every file the installer must\n * write under `<projectDir>/.claude/plugins/skaile/`. The installer is also\n * responsible for populating `skills/` from the project's `.skaile/skills/`.\n *\n * Stateless — no plugin instance, no `boot()`. The generated artifacts carry\n * no project-specific paths: hooks and the MCP server resolve the project\n * directory themselves at runtime.\n *\n * @returns A map of plugin-relative file paths to their string contents.\n *\n * @docLink packages/workspace-plugin/concepts#adapters\n */\nexport function buildClaudePluginFiles(): Record<string, string> {\n return {\n \".claude-plugin/plugin.json\": `${JSON.stringify(PLUGIN_JSON, null, 2)}\\n`,\n \"hooks/hooks.json\": `${JSON.stringify(HOOKS_JSON, null, 2)}\\n`,\n \".mcp.json\": `${JSON.stringify(MCP_JSON, null, 2)}\\n`,\n \"skills/.gitkeep\": \"\",\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\ninterface Subscriber {\n regex: RegExp;\n handler: (key: string, value: unknown) => void;\n}\n\n/**\n * Disk-backed reactive key-value store for plugin state.\n *\n * Keeps an in-memory map that can be flushed to / loaded from a JSON file.\n * Supports glob-style subscriptions (`connector:*`, `*`).\n *\n * State is persisted to `<projectDir>/.skaile/plugin-state.json`.\n * The instance is available on {@link WorkspacePlugin} as the public `store`\n * field after `boot()` resolves.\n *\n * @docLink packages/workspace-plugin/concepts#plugin-store\n */\nexport class PluginStore {\n private readonly statePath: string;\n private data: Map<string, unknown> = new Map();\n private subscribers: Subscriber[] = [];\n\n constructor(statePath: string) {\n this.statePath = statePath;\n }\n\n /** Synchronous read from in-memory map. */\n get<T>(key: string): T | undefined {\n return this.data.get(key) as T | undefined;\n }\n\n /** Write to in-memory map and notify matching subscribers. */\n set<T>(key: string, value: T): void {\n this.data.set(key, value);\n this.notify(key, value);\n }\n\n /** Remove key and notify matching subscribers. */\n delete(key: string): void {\n this.data.delete(key);\n this.notify(key, undefined);\n }\n\n /**\n * Subscribe to changes matching a glob-style pattern.\n * `*` matches any sequence of characters.\n * Returns an unsubscribe function.\n */\n subscribe(pattern: string, handler: (key: string, value: unknown) => void): () => void {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexStr = `^${escaped.replace(/\\*/g, \".*\")}$`;\n const sub: Subscriber = { regex: new RegExp(regexStr), handler };\n this.subscribers.push(sub);\n\n return () => {\n const idx = this.subscribers.indexOf(sub);\n if (idx !== -1) this.subscribers.splice(idx, 1);\n };\n }\n\n /** Rehydrate from disk JSON. Missing file = empty store (no throw). */\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n this.data = new Map(Object.entries(parsed));\n }\n } catch (e: unknown) {\n // Missing file or invalid JSON — start with empty store\n }\n }\n\n /** Write entire store to disk as JSON. Creates parent dirs if needed. */\n async flush(): Promise<void> {\n const obj = Object.fromEntries(this.data);\n const json = JSON.stringify(obj, null, 2);\n await mkdir(dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, json, \"utf-8\");\n }\n\n private notify(key: string, value: unknown): void {\n for (const sub of this.subscribers) {\n if (sub.regex.test(key)) {\n sub.handler(key, value);\n }\n }\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { PluginStore } from \"./store.js\";\n\n/**\n * Construction options for {@link WorkspacePlugin}.\n *\n * At minimum `projectDir` must be supplied. All other fields are optional\n * and are pre-resolved by the caller when available (e.g. the runner already\n * knows `driver`/`provider`/`model` from its own settings resolution).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport interface WorkspacePluginOpts {\n projectDir: string;\n /**\n * Active connector manager. The unified `ConnectorManager` owns both\n * filesystem-face (mountable) and tool-face connectors.\n */\n connectorManager?: ConnectorManager;\n bootOwned?: boolean;\n onLog?: (msg: string) => void;\n /** Pre-resolved driver type (avoids needing boot() to read settings). */\n driver?: string;\n /** Pre-resolved provider. */\n provider?: string;\n /** Pre-resolved model. */\n model?: string;\n}\n\n/**\n * Shared runtime core for the skaile workspace plugin.\n *\n * Manages the full lifecycle (`boot` → tools available → `shutdown`) and\n * surfaces workspace capabilities — mounts, connectors, flows, skills,\n * sessions, and config validation — through two adapter backends:\n *\n * - **MCP, in-process** (runner): call {@link buildWorkspaceMcpServer} for the\n * Claude Agent SDK server the runner embeds into its `query()` call.\n * - **MCP, stdio** (`skaile mcp-server`): call {@link runMcpServerStdio} for a\n * raw `@modelcontextprotocol/sdk` server — no Claude Agent SDK.\n * - **OMP**: call {@link buildOmpToolSet} for the 13-tool native subset and\n * {@link buildOmpExtensionSource} for the generated extension file.\n *\n * Two boot modes are supported via {@link WorkspacePluginOpts.bootOwned}:\n * - `bootOwned: false` (default) — managers injected externally by the runner.\n * - `bootOwned: true` — plugin owns the full manager lifecycle (standalone MCP\n * subprocess or OMP extension).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport class WorkspacePlugin {\n readonly projectDir: string;\n connectorManager: ConnectorManager | null;\n readonly store: PluginStore;\n\n private readonly bootOwned: boolean;\n private readonly onLog: (msg: string) => void;\n private readonly log: Logger = createLogger({\n kind: \"mcp\",\n subkind: \"skaile-workspace\",\n });\n driver?: string;\n provider?: string;\n model?: string;\n\n constructor(opts: WorkspacePluginOpts) {\n this.projectDir = opts.projectDir;\n this.connectorManager = opts.connectorManager ?? null;\n this.store = new PluginStore(join(opts.projectDir, \".skaile\", \"plugin-state.json\"));\n this.bootOwned = opts.bootOwned ?? false;\n if (opts.driver) this.driver = opts.driver;\n if (opts.provider) this.provider = opts.provider;\n if (opts.model) this.model = opts.model;\n this.onLog = opts.onLog ?? (() => {});\n this.log.debug(\"plugin constructed\", {\n driver: opts.driver,\n hasConnectors: !!opts.connectorManager,\n provider: opts.provider,\n model: opts.model,\n bootOwned: this.bootOwned,\n });\n }\n\n async boot(): Promise<void> {\n if (!this.bootOwned) {\n // Managers were injected externally — resolve settings only (non-fatal)\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n await this.store.load();\n return;\n }\n\n // bootOwned: we own the managers lifecycle\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n\n try {\n const {\n ConnectorManager,\n loadConnectorDeclarations,\n registerBuiltinConnectors,\n createCliSecretProviderChain,\n } = await import(\"@skaile/workspaces/connectors\");\n\n registerBuiltinConnectors();\n\n const secrets = createCliSecretProviderChain();\n\n const connectorDecls = await loadConnectorDeclarations(this.projectDir);\n const cm = new ConnectorManager(this.projectDir, { secrets });\n await cm.connectAll(connectorDecls);\n this.connectorManager = cm;\n\n this.log.info(\"workspace plugin booted\", {\n connectors: connectorDecls.length,\n });\n this.onLog(`WorkspacePlugin booted: ${connectorDecls.length} connectors`);\n } catch (err) {\n this.log.warn(\"workspace plugin boot warning\", {\n error: err instanceof Error ? err.message : String(err),\n });\n this.onLog(`WorkspacePlugin boot warning: ${err}`);\n }\n\n await this.store.load();\n }\n\n async reload(): Promise<void> {\n if (!this.bootOwned) return;\n await this.shutdown();\n await this.boot();\n }\n\n async shutdown(): Promise<void> {\n this.log.info(\"workspace plugin shutdown\");\n await this.store.flush();\n if (!this.bootOwned) return;\n try {\n await (this.connectorManager as any)?.disconnectAll?.();\n } catch {\n /* best-effort */\n }\n this.connectorManager = null;\n }\n\n buildSystemPromptSection(driver?: string): string {\n const d = driver ?? this.driver ?? \"unknown\";\n // The unified ConnectorManager owns both mountable (filesystem-face) and\n // tool-face connectors. Filesystem-face connectors expose a `mountPath`.\n const all = (this.connectorManager as any)?.listConnectors?.() ?? [];\n const mounts = (all as any[]).filter((c) => typeof c.mountPath === \"string\");\n const connectors = (all as any[]).filter((c) => typeof c.mountPath !== \"string\");\n const lines = [\"## Workspace (skaile)\", \"\", `Driver: ${d}`, `Project: ${this.projectDir}`];\n if (mounts.length > 0) {\n lines.push(\"\", \"Mounts:\");\n for (const v of mounts) {\n lines.push(` · ${v.id} (${v.driver}) → ${v.mountPath ?? \"(unmounted)\"}`);\n }\n }\n if (connectors.length > 0) {\n lines.push(\"\", \"Connectors:\");\n for (const c of connectors) {\n lines.push(` · ${c.id} (${c.driver})`);\n }\n }\n lines.push(\"\", \"Use workspace_info for full details. Use workspace_validate to check health.\");\n\n for (const name of [\"SOUL.md\", \"RULES.md\"]) {\n const skaileOverride = join(this.projectDir, \".skaile\", name);\n const rootFile = join(this.projectDir, name);\n for (const candidate of [skaileOverride, rootFile]) {\n try {\n const content = readFileSync(candidate, \"utf-8\").trim();\n if (content) {\n lines.push(\"\", `## ${name.replace(\".md\", \"\")}`, \"\", content);\n break;\n }\n } catch {\n // file not found, try next\n }\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Build the in-process Claude Agent SDK MCP server (runner embedding).\n * Returns `null` when `@anthropic-ai/claude-agent-sdk` is unavailable.\n */\n async buildWorkspaceMcpServer(): Promise<unknown | null> {\n this.log.info(\"building workspace MCP server\");\n try {\n const { buildWorkspaceMcpServer } = await import(\"./adapters/mcp.js\");\n const server = await buildWorkspaceMcpServer(this);\n if (server) this.log.info(\"workspace MCP server ready\");\n else this.log.debug(\"workspace MCP server skipped (no tools)\");\n return server;\n } catch (err) {\n this.log.error(\"workspace MCP server build failed\", err);\n throw err;\n }\n }\n\n /**\n * Build the raw `@modelcontextprotocol/sdk` stdio MCP server — no Claude\n * Agent SDK. Used by the `skaile mcp-server` subprocess. The returned\n * server is not yet connected to a transport.\n */\n async buildWorkspaceMcpStdioServer(): Promise<unknown> {\n this.log.info(\"building workspace stdio MCP server\");\n const { buildWorkspaceMcpStdioServer } = await import(\"./adapters/mcp.js\");\n return buildWorkspaceMcpStdioServer(this);\n }\n\n /**\n * Build and run the stdio MCP server: builds the raw\n * `@modelcontextprotocol/sdk` server and connects a `StdioServerTransport`.\n * Used by the `skaile mcp-server` subprocess.\n */\n async runMcpServerStdio(): Promise<void> {\n this.log.info(\"starting workspace stdio MCP server\");\n const { runMcpServerStdio } = await import(\"./adapters/mcp.js\");\n await runMcpServerStdio(this);\n }\n\n async buildOmpToolSet(): Promise<unknown[]> {\n const { buildOmpToolSet } = await import(\"./adapters/omp.js\");\n return buildOmpToolSet(this);\n }\n\n async buildOmpExtensionSource(): Promise<string> {\n const { buildOmpExtensionSource } = await import(\"./adapters/omp.js\");\n return buildOmpExtensionSource(this.projectDir);\n }\n\n async handleSlashCommand(group: string, args: string[]): Promise<string> {\n const { handleSlashCommand } = await import(\"./adapters/omp.js\");\n return handleSlashCommand(this, group, args);\n }\n}\n","// utils/project-dir.ts\n// Centralised project-directory resolution used by all plugin entry points.\n\n/**\n * Resolve the skaile project directory from environment variables.\n *\n * Resolution order:\n * 1. `SKAILE_PROJECT_DIR` (always checked first)\n * 2. Any additional env var keys supplied by the caller (in order)\n * 3. `process.cwd()` as final fallback\n *\n * @param additionalEnvVars - Optional list of extra environment variable names\n * to check before falling back to `process.cwd()`.\n * @returns Absolute path to the resolved project directory.\n *\n * @example\n * // Claude Code — also checks CLAUDE_PROJECT_DIR\n * const projectDir = resolveProjectDir([\"CLAUDE_PROJECT_DIR\"]);\n *\n * // OMP / standalone — SKAILE_PROJECT_DIR or cwd only\n * const projectDir = resolveProjectDir();\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function resolveProjectDir(additionalEnvVars?: string[]): string {\n if (process.env.SKAILE_PROJECT_DIR) return process.env.SKAILE_PROJECT_DIR;\n for (const key of additionalEnvVars ?? []) {\n const val = process.env[key];\n if (val) return val;\n }\n return process.cwd();\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { globalSettingsPath, mapLegacyFields } from './chunk-
|
|
1
|
+
import { globalSettingsPath, mapLegacyFields } from './chunk-P43HBWKK.js';
|
|
2
2
|
import { rmSync, existsSync, readFileSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
|
|
3
3
|
import { randomBytes, createHash } from 'crypto';
|
|
4
4
|
import { homedir } from 'os';
|
|
@@ -228,5 +228,5 @@ function isStoreAuthenticated() {
|
|
|
228
228
|
}
|
|
229
229
|
|
|
230
230
|
export { deviceLogin, getStoreConfig, getStoreIdentity, getStoreToken, hasStoredAuth, isStoreAuthenticated, loadStoreAuthConfig, logout, storeFetch };
|
|
231
|
-
//# sourceMappingURL=chunk-
|
|
232
|
-
//# sourceMappingURL=chunk-
|
|
231
|
+
//# sourceMappingURL=chunk-AM5LFRXJ.js.map
|
|
232
|
+
//# sourceMappingURL=chunk-AM5LFRXJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../cli/src/store-auth.ts","../cli/src/store-client.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;A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AAA,IAAS,CAAA,iBAAA,EAAoB,GAAA,CAAI,MAAM,CAAA,CAAE,CAAA;AAAA,IAC1E;AACA,IAAA,OAAO,IAAI,IAAA,EAAK;AAAA,EAClB,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,OAAO,CAAA;AAAA,EACtB;AACF;AASO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OAAO,aAAA,CAAc,qBAAqB,CAAA;AAC5C","file":"chunk-BFIK6NPZ.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 { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\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 const home = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\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(home, \"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 = 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"]}
|
|
1
|
+
{"version":3,"sources":["../cli/src/store-auth.ts","../cli/src/store-client.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,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,eAAe,IAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AACjE,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,iBAAA,CAAkB,OAAA,CAAQ,GAAA,CAAI,uBAAuB,wBAAwB,CAAA;AAAA,IAC1F,KAAA,EAAO,OAAA,CAAQ,GAAA,CAAI,kBAAA,IAAsB,cAAA;AAAA,IACzC,QAAA,EAAU,OAAA,CAAQ,GAAA,CAAI,uBAAA,IAA2B,kBAAA;AAAA,IACjD,UAAU,OAAA,CAAQ,GAAA,CAAI,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IAAI,MAAM,IAAA,EAAM;AACd,IAAA,SAAA,CAAU,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA;AAAA,EAC3C;AAEA,EAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AACvC,EAAA,MAAM,OAAA,GAAU,WAAW,MAAM,UAAA,CAAW,OAAM,EAAG,IAAA,EAAM,aAAa,IAAK,CAAA;AAC7E,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,GAAG,SAAA,EAAW,MAAA,EAAQ,UAAA,CAAW,MAAA,EAAQ,CAAA;AACxE,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,MAAM,IAAA,GAAO,MAAM,GAAA,CAAI,IAAA,EAAK,CAAE,KAAA,CAAM,OAAO,EAAE,KAAA,EAAO,CAAA,KAAA,EAAQ,GAAA,CAAI,MAAM,IAAG,CAAE,CAAA;AAI3E,MAAA,MAAM,CAAA,GAAI,IAAA;AACV,MAAA,MAAM,IAAI,MAAM,CAAA,CAAE,OAAA,IAAW,EAAE,KAAA,IAAS,CAAA,iBAAA,EAAoB,GAAA,CAAI,MAAM,CAAA,CAAE,CAAA;AAAA,IAC1E;AACA,IAAA,OAAO,IAAI,IAAA,EAAK;AAAA,EAClB,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,OAAO,CAAA;AAAA,EACtB;AACF;AASO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OAAO,aAAA,CAAc,qBAAqB,CAAA;AAC5C","file":"chunk-AM5LFRXJ.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 { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\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 const home = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\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(home, \"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 = 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"]}
|
|
@@ -43,8 +43,8 @@ function isUserInvokable(cap) {
|
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
// types/src/version.ts
|
|
46
|
-
var PROTOCOL_VERSION = { major: 3, minor:
|
|
47
|
-
var PROTOCOL_VERSION_STRING = "3.
|
|
46
|
+
var PROTOCOL_VERSION = { major: 3, minor: 8, patch: 0 };
|
|
47
|
+
var PROTOCOL_VERSION_STRING = "3.8.0";
|
|
48
48
|
function parseVersion(s) {
|
|
49
49
|
const parts = s.split(".");
|
|
50
50
|
if (parts.length !== 3) {
|
|
@@ -64,5 +64,5 @@ function formatVersion(v) {
|
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
export { MENTION_GROUPS, PROTOCOL_VERSION, PROTOCOL_VERSION_STRING, QUICK_REACTIONS, formatVersion, isRenderCapability, isUserInvokable, parseVersion };
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
68
|
-
//# sourceMappingURL=chunk-
|
|
67
|
+
//# sourceMappingURL=chunk-D4VHBAJC.js.map
|
|
68
|
+
//# sourceMappingURL=chunk-D4VHBAJC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../types/src/mentions.ts","../types/src/reactions.ts","../types/src/capabilities.ts","../types/src/version.ts"],"names":[],"mappings":";AAmBO,IAAM,iBAAiB,CAAC,OAAA,EAAS,QAAA,EAAU,aAAA,EAAe,QAAQ,KAAK;;;ACevE,IAAM,eAAA,GAAkB;AAAA,EAC7B,WAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,cAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;;;AC8LO,SAAS,mBAAmB,GAAA,EAA0C;AAC3E,EAAA,OAAO,IAAI,MAAA,KAAW,MAAA;AACxB;AAsCO,SAAS,gBAAgB,GAAA,EAA0B;AACxD,EAAA,IAAI,GAAA,CAAI,aAAa,MAAA,EAAW;AAC9B,IAAA,OAAO,GAAA,CAAI,QAAA,CAAS,QAAA,CAAS,MAAM,CAAA;AAAA,EACrC;AACA,EAAA,IAAI,GAAA,CAAI,kBAAkB,MAAA,EAAW;AACnC,IAAA,OAAO,GAAA,CAAI,aAAA;AAAA,E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;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,4CAAA,CAA8C,CAAA;AAAA,EAC9F;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAM;AAC/B;AAiBO,SAAS,cAAc,CAAA,EAA4B;AACxD,EAAA,OAAO,CAAA,EAAG,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA;AACzC","file":"chunk-RDE43ORT.js","sourcesContent":["/**\n * Mentions — types for @-mention support in session messages.\n *\n * A Mention records who was addressed in a message, whether a specific user\n * or a well-known group. Group mentions carry a resolved array of user IDs\n * so consumers can perform membership checks without the resolver.\n */\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\n/**\n * Well-known group mention targets as a `const` array.\n *\n * Use this for validation or exhaustive checks against `MentionGroup`.\n *\n * @docLink packages/types/messages#mention\n */\nexport const MENTION_GROUPS = [\"agent\", \"humans\", \"humans_here\", \"here\", \"all\"] as const;\n\n/**\n * A well-known group that can be `@`-mentioned: `'agent' | 'humans' | 'humans_here' | 'here' | 'all'`.\n *\n * @docLink packages/types/messages#mention\n */\nexport type MentionGroup = (typeof MENTION_GROUPS)[number];\n\n// ---------------------------------------------------------------------------\n// Mention discriminated union\n// ---------------------------------------------------------------------------\n\n/**\n * A parsed `@`-mention in a session message. Records who was addressed — either a\n * specific user or a well-known group — along with the source text position.\n *\n * Group mentions carry a resolved array of user IDs so consumers can perform\n * membership checks without needing the resolver.\n *\n * @docLink packages/types/messages#mention\n */\nexport type Mention =\n | {\n type: \"user\";\n userId: string;\n name: string;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"group\";\n group: MentionGroup;\n /** User IDs resolved at parse time (e.g. all online users for `@here`). */\n resolved: string[];\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"custom\";\n /** Consumer-defined mention kind, e.g. \"assistant\". */\n kind: string;\n /** User IDs this mention resolves to (so isMentioned works); may be empty. */\n resolved: string[];\n /** Optional consumer payload, e.g. { sessionId, ownerId }. */\n data?: Record<string, unknown>;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n };\n","/**\n * Reactions -- emoji reactions on session messages.\n *\n * Any session participant (user or agent) can react to any message.\n * Reactions are persisted in a dedicated DB model and broadcast as\n * transient events for real-time updates.\n */\n\n/**\n * A single emoji reaction on a message, set by any session participant (user or agent).\n *\n * Reactions are persisted in a dedicated DB model and broadcast as transient events\n * for real-time updates.\n *\n * @docLink packages/types/messages#reaction\n */\nexport type Reaction = {\n /** Unicode emoji character (e.g. \"thumbs up\", not \":thumbsup:\"). */\n emoji: string;\n /** ID of the user (or \"agent\" for agent reactions). */\n userId: string;\n /** Display name at reaction time (avoids extra lookups for tooltip rendering). */\n userName: string;\n /** Unix epoch milliseconds. */\n timestamp: number;\n};\n\n/**\n * Quick-access emojis shown in the reaction bar picker.\n *\n * An `as const` array of eight Unicode emoji characters in display order.\n *\n * @docLink packages/types/messages#reaction\n */\nexport const QUICK_REACTIONS = [\n \"\\u{1F44D}\",\n \"\\u{1F440}\",\n \"\\u2705\",\n \"\\u2764\\uFE0F\",\n \"\\u{1F914}\",\n \"\\u{1FAE1}\",\n \"\\u{1F44F}\",\n \"\\u{1F389}\",\n] as const;\n","/**\n * Capability layer — Protocol v2's unified registry of LLM-invokable entry points.\n *\n * A {@link Capability} is a named, schema-typed entry point that the LLM can call\n * during a session. Capabilities are registered into a per-session\n * registry by either side (host platform via `side: 'client'` or runtime via\n * `side: 'agent'`) and routed by the bridge at invocation time.\n *\n * This module defines the wire types only; the runtime registry, the\n * `defineCapability` helper, and the per-handler logger live in\n * `@skaile/workspaces/runner`.\n *\n * @see {@link MessageV2} envelope that carries capability commands and events\n * @see {@link ProtocolVersion} for the version contract\n *\n * @category Capabilities\n * @since 2.0.0\n */\n\n// ---------------------------------------------------------------------------\n// Capability shape\n// ---------------------------------------------------------------------------\n\n/**\n * Visibility scope for a capability. Determines which surfaces the capability\n * appears on and which callers can invoke it.\n *\n * - `'llm'`: registered as an LLM tool, surfaced in the `<CAPABILITIES>` system\n * prompt section. The agent driver can invoke it.\n * - `'user'`: appears in user-facing surfaces — the command palette (cmdK),\n * debug menus, capability lists.\n * - `'runtime'`: invocable only by trusted runner / platform code paths. Never\n * reaches the LLM tool list. Never reaches the command palette. Used for\n * host RPCs (`host.refresh_credential`, `host.audit`, `host.notify_user`,\n * `host.persist_compaction_attempt`) and runner RPCs (`runner.add_mount`,\n * `runner.set_log_level`, `runner.lifecycle`, ...).\n *\n * Multiple audiences are allowed (e.g. `['llm', 'user']`). The default when\n * {@link Capability.audience} is omitted is `['llm', 'user']`, preserving the\n * v2.x default visibility for capabilities that haven't migrated yet.\n *\n * @category Capabilities\n * @since 3.0.0\n * @docLink packages/types/capabilities#capability-audience\n */\nexport type CapabilityAudience = \"llm\" | \"user\" | \"runtime\";\n\n/**\n * Source of truth for who registered a capability. Used for trust enforcement\n * (the bridge rejects mismatches between registering side and origin kind)\n * and for the `capability:<origin>:<name>` log taxonomy.\n *\n * Variants:\n * - `framework`: built-in (e.g. `__capabilities.list`)\n * - `client`: host platform (e.g. `platform.react`)\n * - `agent`: self-registered by the agent runtime\n * - `flow`: injected by an active flow execution\n * - `skill`: from a skill's MCP surface\n * - `mcp`: from a generic MCP server\n * - `connector`: from a connector (e.g. `postgres.query`)\n * - `mount`: surfaced by a filesystem mount\n * - `app`: from an embedded, agent-controllable app (carries the originating\n * `appId`). Handlers run in the app itself — see {@link Capability.side} `'app'`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-origin\n */\nexport type CapabilityOrigin =\n | { kind: \"framework\" }\n | { kind: \"client\" }\n | { kind: \"agent\" }\n | { kind: \"flow\"; flowId: string }\n | { kind: \"skill\"; skillId: string }\n | { kind: \"mcp\"; serverId: string }\n | { kind: \"connector\"; connectorId: string }\n | { kind: \"mount\"; mountId: string }\n | { kind: \"app\"; appId: string };\n\n/**\n * Render contract for a capability that produces a UI surface when invoked.\n *\n * When the LLM invokes a capability whose `render` is set, the bridge emits\n * a {@link RenderInvokedEvent} carrying the capability name and props. The\n * client renders the configured `source` at the chosen `target`. Clients\n * without a render layer can fall back to the markdown `fallback` template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-spec\n */\nexport type RenderSpec = {\n /** Where the rendered component lives. */\n source: { kind: \"web-component\"; url: string; tagName: string } | { kind: \"iframe\"; url: string };\n /** Render placements supported by the component. */\n targets: (\"chat\" | \"preview\" | \"modal\" | \"input-extension\")[];\n /** Markdown template with `{{prop}}` placeholders for clients without a render layer. */\n fallback?: string;\n /** True when props may be partial during streaming. */\n streaming?: boolean;\n /** Interaction names the rendered component may fire back as state events. */\n interactions?: string[];\n};\n\n/**\n * A named, schema-typed entry point that the LLM can invoke during a session.\n *\n * Capabilities can be declared statically (via `ConfigureCommand.capabilities`)\n * or dynamically (via {@link CapabilityRegisterCommand} /\n * {@link CapabilityRegisterEvent}). They are cached for replay across\n * subscriber reconnects and session hibernation.\n *\n * @example Defining a client-side fire-and-forget tool (uses the runner's\n * `defineCapability` helper, which serializes a {@link Capability} to the wire):\n * ```ts\n * const reactTool = defineCapability({\n * name: 'platform.react',\n * description: 'Acknowledge a user message with a Unicode emoji.',\n * side: 'client',\n * origin: { kind: 'client' },\n * fireAndForget: true,\n * input: z.object({ emoji: z.string(), targetSeq: z.number().optional() }),\n * handler: async ({ emoji, targetSeq }, ctx) => { ... },\n * });\n * ```\n *\n * @see {@link RenderCapability} for capabilities that render UI components\n * @see {@link CapabilityOrigin} for who-registered-it metadata\n * @see {@link isRenderCapability} for the type-guard\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability\n */\nexport type Capability = {\n /** Unique within a session. Convention: namespaced as `<origin>.<name>` (e.g. `platform.react`, `ui.gif`). */\n name: string;\n /**\n * Human-readable label for user-facing surfaces (cmdK action palette,\n * capability menus, debug panels). Falls back to {@link Capability.name}\n * when omitted. Pure presentation — the LLM sees `name`, not `displayName`.\n */\n displayName?: string;\n /** Human/LLM-readable summary. Shown to the LLM as part of tool registration. */\n description: string;\n /** JSON Schema validating the invocation arguments. Authored as Zod, converted at register time. */\n inputSchema: Record<string, unknown>;\n /** Optional return shape. Omit for fire-and-forget effects. */\n outputSchema?: Record<string, unknown>;\n /** Where the handler runs. `client` = host platform, `agent` = runtime/skill/connector, `app` = embedded app. */\n side: \"client\" | \"agent\" | \"app\";\n /** Discriminated tag identifying who registered the capability. Used for trust enforcement and audit. */\n origin: CapabilityOrigin;\n /** Lifetime: `session` survives the whole session, `turn` is dropped at end-of-turn. */\n scope?: \"session\" | \"turn\";\n /** When true, the bridge auto-resolves with `{}` immediately and runs the handler in the background. */\n fireAndForget?: boolean;\n /** When true, the platform shows a confirm UI before dispatch and waits for {@link CapabilityApproveCommand}. */\n requiresApproval?: boolean;\n /** Documentation hint (not enforced) describing whether this is a side-effect, render, or pure query. */\n kind?: \"effect\" | \"render\" | \"query\";\n /**\n * Whether this capability should be exposed in user-facing surfaces (cmdK\n * action palette, capability menus). When omitted, the consumer applies a\n * default per-origin via {@link isUserInvokable}.\n *\n * - `true`: surface in cmdK and capability menus.\n * - `false`: hide from user surfaces (LLM-only or low-level).\n * - `undefined`: defer to {@link isUserInvokable}'s inference rules.\n *\n * @deprecated Set {@link Capability.audience} instead. `userInvokable` is\n * kept as a read-only shim for v2.x consumers and is honoured by\n * {@link isUserInvokable} when {@link Capability.audience} is absent.\n */\n userInvokable?: boolean;\n /**\n * Audience scoping for this capability. See {@link CapabilityAudience} for\n * the meaning of each value and combinations.\n *\n * When omitted, consumers treat the capability as `['llm', 'user']` (the\n * v2.x default). Host RPCs and runner RPCs MUST set this to `['runtime']`\n * so they never leak to the LLM tool list or the user-facing surfaces.\n *\n * @category Capabilities\n * @since 3.0.0\n */\n audience?: CapabilityAudience[];\n /** Appended to the system prompt's `<CAPABILITIES>` section. Use for usage hints the LLM should always see. */\n promptFragment?: string;\n /**\n * Per-capability override for how long the runner waits on the\n * `capability_result` round-trip before timing out. When omitted the\n * runner applies its default (`DEFAULT_CAPABILITY_CALL_TIMEOUT_MS`, 60s).\n *\n * Set this for capabilities that legitimately block far longer than a\n * normal tool call — e.g. `platform.ask_session` suspends the caller's\n * turn until a peer session answers, which can take minutes.\n *\n * @category Capabilities\n * @since 3.3.0\n */\n callTimeoutMs?: number;\n /** Present iff this is a render capability — see {@link RenderCapability}. */\n render?: RenderSpec;\n};\n\n/**\n * A {@link Capability} that produces a UI surface when invoked. The narrowed\n * type guarantees `render` is set, which simplifies frontend lookup.\n *\n * @see {@link isRenderCapability}\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-capability\n */\nexport type RenderCapability = Capability & { render: NonNullable<Capability[\"render\"]> };\n\n/**\n * Type-guard for {@link RenderCapability}. Use after {@link Capability}\n * lookup to narrow the type before reading `render`.\n *\n * @example\n * ```ts\n * for (const cap of registry.list()) {\n * if (isRenderCapability(cap)) console.log(cap.render.targets);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#is-render-capability\n */\nexport function isRenderCapability(cap: Capability): cap is RenderCapability {\n return cap.render !== undefined;\n}\n\n/**\n * Decide whether a capability should be surfaced in user-facing actions\n * (cmdK action palette, capability menus).\n *\n * Resolution order (first match wins):\n *\n * 1. {@link Capability.audience} is set — return `audience.includes('user')`.\n * Capabilities scoped to `'runtime'` only never appear in user surfaces.\n * 2. {@link Capability.userInvokable} is set (v2.x shim) — return that value.\n * 3. Default per-origin inference table below.\n *\n * Default-inference rules (when both `audience` and `userInvokable` are\n * omitted):\n * | Origin | Default |\n * | ------------ | ---------------------------------------------------------------------- |\n * | `framework` | `false` (LLM discovery surfaces, e.g. `__capabilities.list`) |\n * | `client` | `false` (platform ack tools — `platform.react`, `platform.pass`) |\n * | `agent` | `false` (agent-defined; assume internal unless flagged) |\n * | `flow` | `false` (per-cap opt-in) |\n * | `connector` | `false` (low-level FS / data ops) |\n * | `mount` | `false` (low-level FS ops) |\n * | `app` | `false` (LLM-only; app authors opt in via `audience: ['llm','user']`) |\n * | `mcp` | `true` if `kind === 'effect'`, else `false` |\n * | `skill` | `true` if `kind` ∈ {`effect`, `render`}, else `false` |\n *\n * @example\n * ```ts\n * for (const cap of capabilities.values()) {\n * if (isUserInvokable(cap)) registerCommandPaletteAction(cap);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.1.0\n * @docLink packages/types/capabilities#is-user-invokable\n */\nexport function isUserInvokable(cap: Capability): boolean {\n if (cap.audience !== undefined) {\n return cap.audience.includes(\"user\");\n }\n if (cap.userInvokable !== undefined) {\n return cap.userInvokable;\n }\n switch (cap.origin.kind) {\n case \"framework\":\n case \"client\":\n case \"agent\":\n case \"flow\":\n case \"connector\":\n case \"mount\":\n case \"app\":\n return false;\n case \"mcp\":\n return cap.kind === \"effect\";\n case \"skill\":\n return cap.kind === \"effect\" || cap.kind === \"render\";\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Capability commands (client → agent)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (client → agent).\n *\n * The platform sends this when a new client-side tool becomes available\n * after `configure` has already returned (e.g. a user installs a new\n * extension during the session).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-command\n */\nexport type CapabilityRegisterCommand = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (client → agent). Names that are not\n * currently registered are ignored silently.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-command\n */\nexport type CapabilityDeregisterCommand = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Return the result of a previously {@link CapabilityInvokedEvent | invoked} client-side\n * capability (client → agent). Bridges that registered the capability with\n * `fireAndForget: true` MAY skip this command; the bridge auto-resolves with `{}`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-result-command\n */\nexport type CapabilityResultCommand = {\n type: \"capability_result\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** Successful result payload, or an error envelope. */\n result: unknown | { error: string };\n};\n\n/**\n * Approve or reject a capability call that was invoked with\n * `requiresApproval: true` (client → agent). The platform shows a confirm\n * UI and forwards the user's decision via this command.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-approve-command\n */\nexport type CapabilityApproveCommand = {\n type: \"capability_approve\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** User's decision. */\n decision: \"approved\" | \"rejected\";\n /** Optional rationale stored alongside the decision for audit. */\n feedback?: string;\n /** User ID of the decider (informational — framework enforces no policy). */\n decidedBy: string;\n};\n\n// ---------------------------------------------------------------------------\n// Capability events (agent → client)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (agent → client). Mirrors\n * {@link CapabilityRegisterCommand} for the agent-initiated direction; used\n * when the runtime adds a capability after `configure` (e.g. when a flow\n * starts and injects flow-scoped tools).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-event\n */\nexport type CapabilityRegisterEvent = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (agent → client).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-event\n */\nexport type CapabilityDeregisterEvent = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Notify the client that a capability has been invoked by the LLM (agent →\n * client). For client-side capabilities the platform's handler runs in\n * response to this event and replies with {@link CapabilityResultCommand}.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-invoked-event\n */\nexport type CapabilityInvokedEvent = {\n type: \"capability_invoked\";\n /** Correlation token for the eventual {@link CapabilityResultCommand}. */\n callId: string;\n /** Name of the invoked {@link Capability}. */\n name: string;\n /** Validated input payload (already conforms to the capability's `inputSchema`). */\n input: unknown;\n /** In v2.0.0 the LLM is the only invoker. */\n invokedBy: \"agent\";\n};\n\n/**\n * Notify the client that a render capability should be drawn (agent →\n * client). Emitted alongside {@link CapabilityInvokedEvent} when the\n * invoked capability's `render` block is populated.\n *\n * Clients without a render layer can fall back to the capability's\n * `render.fallback` markdown template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-invoked-event\n */\nexport type RenderInvokedEvent = {\n type: \"render_invoked\";\n /** Name of the invoked render capability. */\n capabilityName: string;\n /** Props passed to the rendered component (already conforms to `inputSchema`). */\n props: unknown;\n /** Correlation token shared with the matching {@link CapabilityInvokedEvent}. */\n callId: string;\n};\n","/**\n * Protocol versioning primitives for Skaile Agent Protocol v2.\n *\n * The protocol is versioned by a structured {@link ProtocolVersion} record\n * (`major.minor.patch`). The compatibility rule applied at handshake is\n * **major-equality**: a runner emits {@link IncompatibleProtocolEvent} and\n * shuts down when its declared major does not match the platform's announced\n * major. Minor and patch differences ride through transparently because\n * unknown fields are preserved on round-trip (see `MessageMeta` round-trip\n * contract in `messaging.ts`).\n *\n * @category Protocol\n * @since 2.0.0\n */\n\n/**\n * Structured semantic version triple for the agent protocol.\n *\n * @example\n * ```ts\n * const v: ProtocolVersion = { major: 2, minor: 0, patch: 0 };\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#protocol-version\n */\nexport type ProtocolVersion = {\n /** Incremented on breaking wire-format changes (field removed, semantics changed, required field added). */\n major: number;\n /** Incremented on additive wire-format changes (new optional fields, new event types). */\n minor: number;\n /** Incremented on bug-fix or doc-only changes that do not affect the wire. */\n patch: number;\n};\n\n/**\n * The protocol version the framework currently speaks. Runners and platforms\n * compare this against the peer's announced version at session boot via\n * `SessionInitCommand.protocolVersion`.\n *\n * @example\n * ```ts\n * import { PROTOCOL_VERSION } from '@skaile/workspaces/types';\n * if (cmd.protocolVersion.major !== PROTOCOL_VERSION.major) {\n * emit({ type: 'incompatible_protocol', agentVersion: PROTOCOL_VERSION, platformVersion: cmd.protocolVersion });\n * }\n * ```\n *\n * @category Protocol\n * @since 3.0.0\n *\n * Changed in 3.7.0:\n * Additive `connector_mutate` acknowledgement + flow-hydrate reconciliation.\n * Three changes, all additive under the major-equality rule:\n * - `ConnectorMutateCommand` gains an optional `requestId`. When set, the\n * runner emits exactly one new `connector_mutate_response` event (with\n * `ok` / `result` / `error` / `code` / `reconciled`) on every terminal path,\n * including the paths that previously only logged. When absent nothing is\n * emitted, so a 3.6 host sees byte-identical behaviour.\n * - `flow.hydrate` accepts an optional `payload.pendingDecisions` —\n * `PendingGateDecision[]` the runner replays against the snapshot in the\n * same invocation that creates the flow connector, reporting the outcome as\n * `reconciled`. A host that omits the key gets today's hydrate.\n * - A flow-targeted mutate whose connector is not yet registered now waits\n * (bounded, `SKAILE_FLOW_MUTATE_CONNECTOR_WAIT_MS`, default 8000 ms) and\n * re-plans instead of failing — a behaviour change on a path that used to\n * fail silently, visible to a 3.6 host only as the op succeeding.\n * A 3.6 peer is unaffected: no symbol was removed or re-shaped, the ack is\n * opt-in on a field a 3.6 host never sets, and unknown fields ride through the\n * round-trip. A 3.7 host against a 3.6 runner sees `requestId` ignored and no\n * response, which it must treat as \"unacknowledged\" (feature-detect on\n * `major === 3 && minor >= 7`). Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.6.0:\n * Additive resolved-agent-config wire field. `ResolvedSkaileConfig` gains an\n * optional `agentConfig?: ResolvedAgentConfig` carrying the platform-resolved\n * driver / provider / model / cloud / cloudConfig / thinking / effort — the\n * same values the platform bakes into the generated skaile.yaml\n * `agent-config.default`. The runner applies it disk-first: any on-disk\n * `agent-config` profile with at least one agent setting disables the wire\n * value outright, so yaml-on-disk (docker-mode) sessions are byte-identical.\n * Additive under the major-equality rule: an older runner ignores the field\n * and an older platform simply omits it.\n *\n * Changed in 3.5.0:\n * Flow-connector host-contract fix (workspaces#379). Three coordinated changes,\n * all additive under the major-equality rule:\n * - `op:\"hydrate\"` on the bare `\"flow\"` connector now auto-creates the\n * `flow:<runId>` connector on a cold container from its `{ state, flow }`\n * payload, so a persisted run rehydrates in one op. A peer that still issues\n * `start` then `hydrate` keeps working unchanged.\n * - The dead `SessionInit.activeFlows` field (never read by the runner) and its\n * `ActiveFlowRehydration` type are removed — wire-compatible (nothing produced\n * or consumed them) but source-breaking for typed hosts, hence the bump.\n * - Malformed / conflicting flow `start` and `hydrate` payloads now fail loudly\n * (warn with a reason) instead of silently falling through.\n * Because the handshake compares only `major`, a 3.4 host and a 3.5 runner\n * interoperate: the auto-create path is opt-in on the payload the host sends, and\n * the removed field was already inert. Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.4.0:\n * Additive embedded-app capability source. `CapabilityOrigin` gains a\n * `{ kind: 'app'; appId: string }` variant and `Capability.side` gains `'app'`\n * (\"the handler runs in the embedded app\"). Both are additive: a peer that does\n * not understand `origin:'app'` / `side:'app'` never produces or routes them, so\n * they ride through transparently under the major-equality rule. No new message\n * types — `capability_register` / `capability_invoked` / `capability_result` /\n * `capability_approve` / `render_invoked` are reused verbatim. Spec:\n * `_devlog/specs/2026-07-07-app-capability-source.md`.\n *\n * Changed in 3.3.0:\n * Additive agent-to-agent (session-to-session) communication extension.\n * `AgentEvent` gains an `a2a_message` variant carrying cross-session messages\n * (`direction`, `peerSessionId`, `peerName`, `exchangeId`, `text`). `Capability`\n * gains an optional `callTimeoutMs?: number` so a long-running capability call\n * (e.g. a 5-minute `platform.ask_session`) can exceed the default capability-call\n * timeout. Both are additive: a peer that does not understand them ignores the\n * event / falls back to the default timeout, so they ride through transparently\n * under the major-equality rule.\n *\n * Changed in 3.2.0:\n * Additive wake-time resume cascade. `AgentReconfigureOptions` gains optional\n * `resumeSessionId` and `expectedCapabilitySignature` fields driving the tier-1\n * native SDK resume path; `AgentEvent` gains `ResumeAttemptedEvent` and\n * `ResumeFailedEvent`. `FinishedEvent` gains optional `customType` /\n * `customData` for capability-routed custom payloads. All additive — clients\n * that omit the resume hint or ignore the new events keep working unchanged.\n *\n * Changed in 3.1.0:\n * Additive cost / token usage extension. `FinishedEvent` gains an optional\n * `tokens?: TokenUsage` field carrying per-turn input / output / cache-read /\n * cache-creation / reasoning token counts. `AgentDriver.getTokenUsage()` is\n * widened to return the same `TokenUsage` shape (existing consumers reading\n * `inputTokens` / `outputTokens` keep working unchanged). Drivers that do not\n * surface token usage continue to return `null` / omit the field.\n *\n * Changed in 3.0.0:\n * Major bump for the deterministic session bootstrap rewrite. `ConfigureCommandV2`,\n * `provision_secrets`, `request_access_token`, `add_resource`, `remove_resource`,\n * `set_log_level`, `state_action`, `lifecycle`, `remount_mount`, `compact`, and\n * `reconfigure_agent` are removed from the `AgentCommand` union. Their semantics\n * are reachable through:\n * - `session_init` (one deterministic envelope at session start that delivers\n * identity, resolved config, pre-minted credentials, secrets, capabilities,\n * shared state, active flows, resume hints, and logging config),\n * - `host.refresh_credential` (capability invocation that replaces the\n * refresh-on-401 path of `request_access_token`), and\n * - `runner.*` capabilities (`runner.add_mount`, `runner.add_connector`,\n * `runner.remove_resource`, `runner.update_credential`, `runner.set_log_level`,\n * `runner.set_state`, `runner.lifecycle`) invoked by the platform via the\n * bidirectional capability registry.\n *\n * Capabilities gain an `audience: ('llm' | 'user' | 'runtime')[]` field that\n * scopes visibility: host RPCs (`host.*`) and runner RPCs (`runner.*`) are\n * `['runtime']` and never reach the LLM tool list or the user-facing command\n * palette. v2.x capabilities without an explicit `audience` default to\n * `['llm', 'user']`, preserving prior behaviour.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 3, minor: 7, patch: 0 };\n\n/**\n * String form of {@link PROTOCOL_VERSION}, kept in lock-step. Useful for\n * `package.json` version fields and HTTP `User-Agent` strings.\n *\n * @category Protocol\n * @since 3.0.0\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION_STRING = \"3.7.0\";\n\n/**\n * Parse a `\"major.minor.patch\"` string into a {@link ProtocolVersion}.\n *\n * @param s - the version string to parse, exactly three dot-separated non-negative integers\n * @returns the parsed protocol version\n * @throws {Error} if the string is not exactly three dot-separated non-negative integers\n *\n * @example\n * ```ts\n * parseVersion('2.0.0'); // { major: 2, minor: 0, patch: 0 }\n * parseVersion('2.1'); // throws\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#parse-version\n */\nexport function parseVersion(s: string): ProtocolVersion {\n const parts = s.split(\".\");\n if (parts.length !== 3) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (expected \"major.minor.patch\")`);\n }\n const [maj, min, pat] = parts;\n const major = Number(maj);\n const minor = Number(min);\n const patch = Number(pat);\n if (\n !Number.isInteger(major) ||\n !Number.isInteger(minor) ||\n !Number.isInteger(patch) ||\n major < 0 ||\n minor < 0 ||\n patch < 0\n ) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (each part must be a non-negative integer)`);\n }\n return { major, minor, patch };\n}\n\n/**\n * Format a {@link ProtocolVersion} record into its `\"major.minor.patch\"` string form.\n *\n * @param v - the protocol version to format\n * @returns the dot-joined string form\n *\n * @example\n * ```ts\n * formatVersion({ major: 2, minor: 0, patch: 0 }); // '2.0.0'\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#format-version\n */\nexport function formatVersion(v: ProtocolVersion): string {\n return `${v.major}.${v.minor}.${v.patch}`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../types/src/mentions.ts","../types/src/reactions.ts","../types/src/capabilities.ts","../types/src/version.ts"],"names":[],"mappings":";AAmBO,IAAM,iBAAiB,CAA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AAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,gCAAA,CAAkC,CAAA;AAAA,EAClF;AACA,EAAA,MAAM,CAAC,GAAA,EAAK,GAAA,EAAK,GAAG,CAAA,GAAI,KAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,IACE,CAAC,OAAO,SAAA,CAAU,KAAK,KACvB,CAAC,MAAA,CAAO,UAAU,KAAK,CAAA,IACvB,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IACvB,KAAA,GAAQ,KACR,KAAA,GAAQ,CAAA,IACR,QAAQ,CAAA,EACR;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,4CAAA,CAA8C,CAAA;AAAA,EAC9F;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAM;AAC/B;AAiBO,SAAS,cAAc,CAAA,EAA4B;AACxD,EAAA,OAAO,CAAA,EAAG,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA;AACzC","file":"chunk-D4VHBAJC.js","sourcesContent":["/**\n * Mentions — types for @-mention support in session messages.\n *\n * A Mention records who was addressed in a message, whether a specific user\n * or a well-known group. Group mentions carry a resolved array of user IDs\n * so consumers can perform membership checks without the resolver.\n */\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\n/**\n * Well-known group mention targets as a `const` array.\n *\n * Use this for validation or exhaustive checks against `MentionGroup`.\n *\n * @docLink packages/types/messages#mention\n */\nexport const MENTION_GROUPS = [\"agent\", \"humans\", \"humans_here\", \"here\", \"all\"] as const;\n\n/**\n * A well-known group that can be `@`-mentioned: `'agent' | 'humans' | 'humans_here' | 'here' | 'all'`.\n *\n * @docLink packages/types/messages#mention\n */\nexport type MentionGroup = (typeof MENTION_GROUPS)[number];\n\n// ---------------------------------------------------------------------------\n// Mention discriminated union\n// ---------------------------------------------------------------------------\n\n/**\n * A parsed `@`-mention in a session message. Records who was addressed — either a\n * specific user or a well-known group — along with the source text position.\n *\n * Group mentions carry a resolved array of user IDs so consumers can perform\n * membership checks without needing the resolver.\n *\n * @docLink packages/types/messages#mention\n */\nexport type Mention =\n | {\n type: \"user\";\n userId: string;\n name: string;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"group\";\n group: MentionGroup;\n /** User IDs resolved at parse time (e.g. all online users for `@here`). */\n resolved: string[];\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"custom\";\n /** Consumer-defined mention kind, e.g. \"assistant\". */\n kind: string;\n /** User IDs this mention resolves to (so isMentioned works); may be empty. */\n resolved: string[];\n /** Optional consumer payload, e.g. { sessionId, ownerId }. */\n data?: Record<string, unknown>;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n };\n","/**\n * Reactions -- emoji reactions on session messages.\n *\n * Any session participant (user or agent) can react to any message.\n * Reactions are persisted in a dedicated DB model and broadcast as\n * transient events for real-time updates.\n */\n\n/**\n * A single emoji reaction on a message, set by any session participant (user or agent).\n *\n * Reactions are persisted in a dedicated DB model and broadcast as transient events\n * for real-time updates.\n *\n * @docLink packages/types/messages#reaction\n */\nexport type Reaction = {\n /** Unicode emoji character (e.g. \"thumbs up\", not \":thumbsup:\"). */\n emoji: string;\n /** ID of the user (or \"agent\" for agent reactions). */\n userId: string;\n /** Display name at reaction time (avoids extra lookups for tooltip rendering). */\n userName: string;\n /** Unix epoch milliseconds. */\n timestamp: number;\n};\n\n/**\n * Quick-access emojis shown in the reaction bar picker.\n *\n * An `as const` array of eight Unicode emoji characters in display order.\n *\n * @docLink packages/types/messages#reaction\n */\nexport const QUICK_REACTIONS = [\n \"\\u{1F44D}\",\n \"\\u{1F440}\",\n \"\\u2705\",\n \"\\u2764\\uFE0F\",\n \"\\u{1F914}\",\n \"\\u{1FAE1}\",\n \"\\u{1F44F}\",\n \"\\u{1F389}\",\n] as const;\n","/**\n * Capability layer — Protocol v2's unified registry of LLM-invokable entry points.\n *\n * A {@link Capability} is a named, schema-typed entry point that the LLM can call\n * during a session. Capabilities are registered into a per-session\n * registry by either side (host platform via `side: 'client'` or runtime via\n * `side: 'agent'`) and routed by the bridge at invocation time.\n *\n * This module defines the wire types only; the runtime registry, the\n * `defineCapability` helper, and the per-handler logger live in\n * `@skaile/workspaces/runner`.\n *\n * @see {@link MessageV2} envelope that carries capability commands and events\n * @see {@link ProtocolVersion} for the version contract\n *\n * @category Capabilities\n * @since 2.0.0\n */\n\n// ---------------------------------------------------------------------------\n// Capability shape\n// ---------------------------------------------------------------------------\n\n/**\n * Visibility scope for a capability. Determines which surfaces the capability\n * appears on and which callers can invoke it.\n *\n * - `'llm'`: registered as an LLM tool, surfaced in the `<CAPABILITIES>` system\n * prompt section. The agent driver can invoke it.\n * - `'user'`: appears in user-facing surfaces — the command palette (cmdK),\n * debug menus, capability lists.\n * - `'runtime'`: invocable only by trusted runner / platform code paths. Never\n * reaches the LLM tool list. Never reaches the command palette. Used for\n * host RPCs (`host.refresh_credential`, `host.audit`, `host.notify_user`,\n * `host.persist_compaction_attempt`) and runner RPCs (`runner.add_mount`,\n * `runner.set_log_level`, `runner.lifecycle`, ...).\n *\n * Multiple audiences are allowed (e.g. `['llm', 'user']`). The default when\n * {@link Capability.audience} is omitted is `['llm', 'user']`, preserving the\n * v2.x default visibility for capabilities that haven't migrated yet.\n *\n * @category Capabilities\n * @since 3.0.0\n * @docLink packages/types/capabilities#capability-audience\n */\nexport type CapabilityAudience = \"llm\" | \"user\" | \"runtime\";\n\n/**\n * Source of truth for who registered a capability. Used for trust enforcement\n * (the bridge rejects mismatches between registering side and origin kind)\n * and for the `capability:<origin>:<name>` log taxonomy.\n *\n * Variants:\n * - `framework`: built-in (e.g. `__capabilities.list`)\n * - `client`: host platform (e.g. `platform.react`)\n * - `agent`: self-registered by the agent runtime\n * - `flow`: injected by an active flow execution\n * - `skill`: from a skill's MCP surface\n * - `mcp`: from a generic MCP server\n * - `connector`: from a connector (e.g. `postgres.query`)\n * - `mount`: surfaced by a filesystem mount\n * - `app`: from an embedded, agent-controllable app (carries the originating\n * `appId`). Handlers run in the app itself — see {@link Capability.side} `'app'`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-origin\n */\nexport type CapabilityOrigin =\n | { kind: \"framework\" }\n | { kind: \"client\" }\n | { kind: \"agent\" }\n | { kind: \"flow\"; flowId: string }\n | { kind: \"skill\"; skillId: string }\n | { kind: \"mcp\"; serverId: string }\n | { kind: \"connector\"; connectorId: string }\n | { kind: \"mount\"; mountId: string }\n | { kind: \"app\"; appId: string };\n\n/**\n * Render contract for a capability that produces a UI surface when invoked.\n *\n * When the LLM invokes a capability whose `render` is set, the bridge emits\n * a {@link RenderInvokedEvent} carrying the capability name and props. The\n * client renders the configured `source` at the chosen `target`. Clients\n * without a render layer can fall back to the markdown `fallback` template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-spec\n */\nexport type RenderSpec = {\n /** Where the rendered component lives. */\n source: { kind: \"web-component\"; url: string; tagName: string } | { kind: \"iframe\"; url: string };\n /** Render placements supported by the component. */\n targets: (\"chat\" | \"preview\" | \"modal\" | \"input-extension\")[];\n /** Markdown template with `{{prop}}` placeholders for clients without a render layer. */\n fallback?: string;\n /** True when props may be partial during streaming. */\n streaming?: boolean;\n /** Interaction names the rendered component may fire back as state events. */\n interactions?: string[];\n};\n\n/**\n * A named, schema-typed entry point that the LLM can invoke during a session.\n *\n * Capabilities can be declared statically (via `ConfigureCommand.capabilities`)\n * or dynamically (via {@link CapabilityRegisterCommand} /\n * {@link CapabilityRegisterEvent}). They are cached for replay across\n * subscriber reconnects and session hibernation.\n *\n * @example Defining a client-side fire-and-forget tool (uses the runner's\n * `defineCapability` helper, which serializes a {@link Capability} to the wire):\n * ```ts\n * const reactTool = defineCapability({\n * name: 'platform.react',\n * description: 'Acknowledge a user message with a Unicode emoji.',\n * side: 'client',\n * origin: { kind: 'client' },\n * fireAndForget: true,\n * input: z.object({ emoji: z.string(), targetSeq: z.number().optional() }),\n * handler: async ({ emoji, targetSeq }, ctx) => { ... },\n * });\n * ```\n *\n * @see {@link RenderCapability} for capabilities that render UI components\n * @see {@link CapabilityOrigin} for who-registered-it metadata\n * @see {@link isRenderCapability} for the type-guard\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability\n */\nexport type Capability = {\n /** Unique within a session. Convention: namespaced as `<origin>.<name>` (e.g. `platform.react`, `ui.gif`). */\n name: string;\n /**\n * Human-readable label for user-facing surfaces (cmdK action palette,\n * capability menus, debug panels). Falls back to {@link Capability.name}\n * when omitted. Pure presentation — the LLM sees `name`, not `displayName`.\n */\n displayName?: string;\n /** Human/LLM-readable summary. Shown to the LLM as part of tool registration. */\n description: string;\n /** JSON Schema validating the invocation arguments. Authored as Zod, converted at register time. */\n inputSchema: Record<string, unknown>;\n /** Optional return shape. Omit for fire-and-forget effects. */\n outputSchema?: Record<string, unknown>;\n /** Where the handler runs. `client` = host platform, `agent` = runtime/skill/connector, `app` = embedded app. */\n side: \"client\" | \"agent\" | \"app\";\n /** Discriminated tag identifying who registered the capability. Used for trust enforcement and audit. */\n origin: CapabilityOrigin;\n /** Lifetime: `session` survives the whole session, `turn` is dropped at end-of-turn. */\n scope?: \"session\" | \"turn\";\n /** When true, the bridge auto-resolves with `{}` immediately and runs the handler in the background. */\n fireAndForget?: boolean;\n /** When true, the platform shows a confirm UI before dispatch and waits for {@link CapabilityApproveCommand}. */\n requiresApproval?: boolean;\n /** Documentation hint (not enforced) describing whether this is a side-effect, render, or pure query. */\n kind?: \"effect\" | \"render\" | \"query\";\n /**\n * Whether this capability should be exposed in user-facing surfaces (cmdK\n * action palette, capability menus). When omitted, the consumer applies a\n * default per-origin via {@link isUserInvokable}.\n *\n * - `true`: surface in cmdK and capability menus.\n * - `false`: hide from user surfaces (LLM-only or low-level).\n * - `undefined`: defer to {@link isUserInvokable}'s inference rules.\n *\n * @deprecated Set {@link Capability.audience} instead. `userInvokable` is\n * kept as a read-only shim for v2.x consumers and is honoured by\n * {@link isUserInvokable} when {@link Capability.audience} is absent.\n */\n userInvokable?: boolean;\n /**\n * Audience scoping for this capability. See {@link CapabilityAudience} for\n * the meaning of each value and combinations.\n *\n * When omitted, consumers treat the capability as `['llm', 'user']` (the\n * v2.x default). Host RPCs and runner RPCs MUST set this to `['runtime']`\n * so they never leak to the LLM tool list or the user-facing surfaces.\n *\n * @category Capabilities\n * @since 3.0.0\n */\n audience?: CapabilityAudience[];\n /** Appended to the system prompt's `<CAPABILITIES>` section. Use for usage hints the LLM should always see. */\n promptFragment?: string;\n /**\n * Per-capability override for how long the runner waits on the\n * `capability_result` round-trip before timing out. When omitted the\n * runner applies its default (`DEFAULT_CAPABILITY_CALL_TIMEOUT_MS`, 60s).\n *\n * Set this for capabilities that legitimately block far longer than a\n * normal tool call — e.g. `platform.ask_session` suspends the caller's\n * turn until a peer session answers, which can take minutes.\n *\n * @category Capabilities\n * @since 3.3.0\n */\n callTimeoutMs?: number;\n /** Present iff this is a render capability — see {@link RenderCapability}. */\n render?: RenderSpec;\n};\n\n/**\n * A {@link Capability} that produces a UI surface when invoked. The narrowed\n * type guarantees `render` is set, which simplifies frontend lookup.\n *\n * @see {@link isRenderCapability}\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-capability\n */\nexport type RenderCapability = Capability & { render: NonNullable<Capability[\"render\"]> };\n\n/**\n * Type-guard for {@link RenderCapability}. Use after {@link Capability}\n * lookup to narrow the type before reading `render`.\n *\n * @example\n * ```ts\n * for (const cap of registry.list()) {\n * if (isRenderCapability(cap)) console.log(cap.render.targets);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#is-render-capability\n */\nexport function isRenderCapability(cap: Capability): cap is RenderCapability {\n return cap.render !== undefined;\n}\n\n/**\n * Decide whether a capability should be surfaced in user-facing actions\n * (cmdK action palette, capability menus).\n *\n * Resolution order (first match wins):\n *\n * 1. {@link Capability.audience} is set — return `audience.includes('user')`.\n * Capabilities scoped to `'runtime'` only never appear in user surfaces.\n * 2. {@link Capability.userInvokable} is set (v2.x shim) — return that value.\n * 3. Default per-origin inference table below.\n *\n * Default-inference rules (when both `audience` and `userInvokable` are\n * omitted):\n * | Origin | Default |\n * | ------------ | ---------------------------------------------------------------------- |\n * | `framework` | `false` (LLM discovery surfaces, e.g. `__capabilities.list`) |\n * | `client` | `false` (platform ack tools — `platform.react`, `platform.pass`) |\n * | `agent` | `false` (agent-defined; assume internal unless flagged) |\n * | `flow` | `false` (per-cap opt-in) |\n * | `connector` | `false` (low-level FS / data ops) |\n * | `mount` | `false` (low-level FS ops) |\n * | `app` | `false` (LLM-only; app authors opt in via `audience: ['llm','user']`) |\n * | `mcp` | `true` if `kind === 'effect'`, else `false` |\n * | `skill` | `true` if `kind` ∈ {`effect`, `render`}, else `false` |\n *\n * @example\n * ```ts\n * for (const cap of capabilities.values()) {\n * if (isUserInvokable(cap)) registerCommandPaletteAction(cap);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.1.0\n * @docLink packages/types/capabilities#is-user-invokable\n */\nexport function isUserInvokable(cap: Capability): boolean {\n if (cap.audience !== undefined) {\n return cap.audience.includes(\"user\");\n }\n if (cap.userInvokable !== undefined) {\n return cap.userInvokable;\n }\n switch (cap.origin.kind) {\n case \"framework\":\n case \"client\":\n case \"agent\":\n case \"flow\":\n case \"connector\":\n case \"mount\":\n case \"app\":\n return false;\n case \"mcp\":\n return cap.kind === \"effect\";\n case \"skill\":\n return cap.kind === \"effect\" || cap.kind === \"render\";\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Capability commands (client → agent)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (client → agent).\n *\n * The platform sends this when a new client-side tool becomes available\n * after `configure` has already returned (e.g. a user installs a new\n * extension during the session).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-command\n */\nexport type CapabilityRegisterCommand = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (client → agent). Names that are not\n * currently registered are ignored silently.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-command\n */\nexport type CapabilityDeregisterCommand = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Return the result of a previously {@link CapabilityInvokedEvent | invoked} client-side\n * capability (client → agent). Bridges that registered the capability with\n * `fireAndForget: true` MAY skip this command; the bridge auto-resolves with `{}`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-result-command\n */\nexport type CapabilityResultCommand = {\n type: \"capability_result\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** Successful result payload, or an error envelope. */\n result: unknown | { error: string };\n};\n\n/**\n * Approve or reject a capability call that was invoked with\n * `requiresApproval: true` (client → agent). The platform shows a confirm\n * UI and forwards the user's decision via this command.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-approve-command\n */\nexport type CapabilityApproveCommand = {\n type: \"capability_approve\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** User's decision. */\n decision: \"approved\" | \"rejected\";\n /** Optional rationale stored alongside the decision for audit. */\n feedback?: string;\n /** User ID of the decider (informational — framework enforces no policy). */\n decidedBy: string;\n};\n\n// ---------------------------------------------------------------------------\n// Capability events (agent → client)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (agent → client). Mirrors\n * {@link CapabilityRegisterCommand} for the agent-initiated direction; used\n * when the runtime adds a capability after `configure` (e.g. when a flow\n * starts and injects flow-scoped tools).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-event\n */\nexport type CapabilityRegisterEvent = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (agent → client).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-event\n */\nexport type CapabilityDeregisterEvent = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Notify the client that a capability has been invoked by the LLM (agent →\n * client). For client-side capabilities the platform's handler runs in\n * response to this event and replies with {@link CapabilityResultCommand}.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-invoked-event\n */\nexport type CapabilityInvokedEvent = {\n type: \"capability_invoked\";\n /** Correlation token for the eventual {@link CapabilityResultCommand}. */\n callId: string;\n /** Name of the invoked {@link Capability}. */\n name: string;\n /** Validated input payload (already conforms to the capability's `inputSchema`). */\n input: unknown;\n /** In v2.0.0 the LLM is the only invoker. */\n invokedBy: \"agent\";\n};\n\n/**\n * Notify the client that a render capability should be drawn (agent →\n * client). Emitted alongside {@link CapabilityInvokedEvent} when the\n * invoked capability's `render` block is populated.\n *\n * Clients without a render layer can fall back to the capability's\n * `render.fallback` markdown template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-invoked-event\n */\nexport type RenderInvokedEvent = {\n type: \"render_invoked\";\n /** Name of the invoked render capability. */\n capabilityName: string;\n /** Props passed to the rendered component (already conforms to `inputSchema`). */\n props: unknown;\n /** Correlation token shared with the matching {@link CapabilityInvokedEvent}. */\n callId: string;\n};\n","/**\n * Protocol versioning primitives for Skaile Agent Protocol v2.\n *\n * The protocol is versioned by a structured {@link ProtocolVersion} record\n * (`major.minor.patch`). The compatibility rule applied at handshake is\n * **major-equality**: a runner emits {@link IncompatibleProtocolEvent} and\n * shuts down when its declared major does not match the platform's announced\n * major. Minor and patch differences ride through transparently because\n * unknown fields are preserved on round-trip (see `MessageMeta` round-trip\n * contract in `messaging.ts`).\n *\n * @category Protocol\n * @since 2.0.0\n */\n\n/**\n * Structured semantic version triple for the agent protocol.\n *\n * @example\n * ```ts\n * const v: ProtocolVersion = { major: 2, minor: 0, patch: 0 };\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#protocol-version\n */\nexport type ProtocolVersion = {\n /** Incremented on breaking wire-format changes (field removed, semantics changed, required field added). */\n major: number;\n /** Incremented on additive wire-format changes (new optional fields, new event types). */\n minor: number;\n /** Incremented on bug-fix or doc-only changes that do not affect the wire. */\n patch: number;\n};\n\n/**\n * The protocol version the framework currently speaks. Runners and platforms\n * compare this against the peer's announced version at session boot via\n * `SessionInitCommand.protocolVersion`.\n *\n * @example\n * ```ts\n * import { PROTOCOL_VERSION } from '@skaile/workspaces/types';\n * if (cmd.protocolVersion.major !== PROTOCOL_VERSION.major) {\n * emit({ type: 'incompatible_protocol', agentVersion: PROTOCOL_VERSION, platformVersion: cmd.protocolVersion });\n * }\n * ```\n *\n * @category Protocol\n * @since 3.0.0\n *\n * Changed in 3.8.0:\n * Additive `prompt` receipt acknowledgement. The `prompt` command gains an\n * optional `messageId`; when set the runner emits exactly one new `prompt_ack`\n * event echoing it, as the first act of handling the frame — before the\n * session-readiness gate, the secrets check and the driver start, each of which\n * could previously drop a prompt with no trace at all. When absent nothing is\n * emitted, so a 3.7 host sees byte-identical behaviour. A 3.8 host against a\n * 3.7 runner gets no ack and must not read that as a lost prompt — feature-detect\n * on `major === 3 && minor >= 8`. The ack is receipt-only: it says the frame\n * arrived, never that the turn ran.\n *\n * Changed in 3.7.0:\n * Additive `connector_mutate` acknowledgement + flow-hydrate reconciliation.\n * Three changes, all additive under the major-equality rule:\n * - `ConnectorMutateCommand` gains an optional `requestId`. When set, the\n * runner emits exactly one new `connector_mutate_response` event (with\n * `ok` / `result` / `error` / `code` / `reconciled`) on every terminal path,\n * including the paths that previously only logged. When absent nothing is\n * emitted, so a 3.6 host sees byte-identical behaviour.\n * - `flow.hydrate` accepts an optional `payload.pendingDecisions` —\n * `PendingGateDecision[]` the runner replays against the snapshot in the\n * same invocation that creates the flow connector, reporting the outcome as\n * `reconciled`. A host that omits the key gets today's hydrate.\n * - A flow-targeted mutate whose connector is not yet registered now waits\n * (bounded, `SKAILE_FLOW_MUTATE_CONNECTOR_WAIT_MS`, default 8000 ms) and\n * re-plans instead of failing — a behaviour change on a path that used to\n * fail silently, visible to a 3.6 host only as the op succeeding.\n * A 3.6 peer is unaffected: no symbol was removed or re-shaped, the ack is\n * opt-in on a field a 3.6 host never sets, and unknown fields ride through the\n * round-trip. A 3.7 host against a 3.6 runner sees `requestId` ignored and no\n * response, which it must treat as \"unacknowledged\" (feature-detect on\n * `major === 3 && minor >= 7`). Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.6.0:\n * Additive resolved-agent-config wire field. `ResolvedSkaileConfig` gains an\n * optional `agentConfig?: ResolvedAgentConfig` carrying the platform-resolved\n * driver / provider / model / cloud / cloudConfig / thinking / effort — the\n * same values the platform bakes into the generated skaile.yaml\n * `agent-config.default`. The runner applies it disk-first: any on-disk\n * `agent-config` profile with at least one agent setting disables the wire\n * value outright, so yaml-on-disk (docker-mode) sessions are byte-identical.\n * Additive under the major-equality rule: an older runner ignores the field\n * and an older platform simply omits it.\n *\n * Changed in 3.5.0:\n * Flow-connector host-contract fix (workspaces#379). Three coordinated changes,\n * all additive under the major-equality rule:\n * - `op:\"hydrate\"` on the bare `\"flow\"` connector now auto-creates the\n * `flow:<runId>` connector on a cold container from its `{ state, flow }`\n * payload, so a persisted run rehydrates in one op. A peer that still issues\n * `start` then `hydrate` keeps working unchanged.\n * - The dead `SessionInit.activeFlows` field (never read by the runner) and its\n * `ActiveFlowRehydration` type are removed — wire-compatible (nothing produced\n * or consumed them) but source-breaking for typed hosts, hence the bump.\n * - Malformed / conflicting flow `start` and `hydrate` payloads now fail loudly\n * (warn with a reason) instead of silently falling through.\n * Because the handshake compares only `major`, a 3.4 host and a 3.5 runner\n * interoperate: the auto-create path is opt-in on the payload the host sends, and\n * the removed field was already inert. Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.4.0:\n * Additive embedded-app capability source. `CapabilityOrigin` gains a\n * `{ kind: 'app'; appId: string }` variant and `Capability.side` gains `'app'`\n * (\"the handler runs in the embedded app\"). Both are additive: a peer that does\n * not understand `origin:'app'` / `side:'app'` never produces or routes them, so\n * they ride through transparently under the major-equality rule. No new message\n * types — `capability_register` / `capability_invoked` / `capability_result` /\n * `capability_approve` / `render_invoked` are reused verbatim. Spec:\n * `_devlog/specs/2026-07-07-app-capability-source.md`.\n *\n * Changed in 3.3.0:\n * Additive agent-to-agent (session-to-session) communication extension.\n * `AgentEvent` gains an `a2a_message` variant carrying cross-session messages\n * (`direction`, `peerSessionId`, `peerName`, `exchangeId`, `text`). `Capability`\n * gains an optional `callTimeoutMs?: number` so a long-running capability call\n * (e.g. a 5-minute `platform.ask_session`) can exceed the default capability-call\n * timeout. Both are additive: a peer that does not understand them ignores the\n * event / falls back to the default timeout, so they ride through transparently\n * under the major-equality rule.\n *\n * Changed in 3.2.0:\n * Additive wake-time resume cascade. `AgentReconfigureOptions` gains optional\n * `resumeSessionId` and `expectedCapabilitySignature` fields driving the tier-1\n * native SDK resume path; `AgentEvent` gains `ResumeAttemptedEvent` and\n * `ResumeFailedEvent`. `FinishedEvent` gains optional `customType` /\n * `customData` for capability-routed custom payloads. All additive — clients\n * that omit the resume hint or ignore the new events keep working unchanged.\n *\n * Changed in 3.1.0:\n * Additive cost / token usage extension. `FinishedEvent` gains an optional\n * `tokens?: TokenUsage` field carrying per-turn input / output / cache-read /\n * cache-creation / reasoning token counts. `AgentDriver.getTokenUsage()` is\n * widened to return the same `TokenUsage` shape (existing consumers reading\n * `inputTokens` / `outputTokens` keep working unchanged). Drivers that do not\n * surface token usage continue to return `null` / omit the field.\n *\n * Changed in 3.0.0:\n * Major bump for the deterministic session bootstrap rewrite. `ConfigureCommandV2`,\n * `provision_secrets`, `request_access_token`, `add_resource`, `remove_resource`,\n * `set_log_level`, `state_action`, `lifecycle`, `remount_mount`, `compact`, and\n * `reconfigure_agent` are removed from the `AgentCommand` union. Their semantics\n * are reachable through:\n * - `session_init` (one deterministic envelope at session start that delivers\n * identity, resolved config, pre-minted credentials, secrets, capabilities,\n * shared state, active flows, resume hints, and logging config),\n * - `host.refresh_credential` (capability invocation that replaces the\n * refresh-on-401 path of `request_access_token`), and\n * - `runner.*` capabilities (`runner.add_mount`, `runner.add_connector`,\n * `runner.remove_resource`, `runner.update_credential`, `runner.set_log_level`,\n * `runner.set_state`, `runner.lifecycle`) invoked by the platform via the\n * bidirectional capability registry.\n *\n * Capabilities gain an `audience: ('llm' | 'user' | 'runtime')[]` field that\n * scopes visibility: host RPCs (`host.*`) and runner RPCs (`runner.*`) are\n * `['runtime']` and never reach the LLM tool list or the user-facing command\n * palette. v2.x capabilities without an explicit `audience` default to\n * `['llm', 'user']`, preserving prior behaviour.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 3, minor: 8, patch: 0 };\n\n/**\n * String form of {@link PROTOCOL_VERSION}, kept in lock-step. Useful for\n * `package.json` version fields and HTTP `User-Agent` strings.\n *\n * @category Protocol\n * @since 3.0.0\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION_STRING = \"3.8.0\";\n\n/**\n * Parse a `\"major.minor.patch\"` string into a {@link ProtocolVersion}.\n *\n * @param s - the version string to parse, exactly three dot-separated non-negative integers\n * @returns the parsed protocol version\n * @throws {Error} if the string is not exactly three dot-separated non-negative integers\n *\n * @example\n * ```ts\n * parseVersion('2.0.0'); // { major: 2, minor: 0, patch: 0 }\n * parseVersion('2.1'); // throws\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#parse-version\n */\nexport function parseVersion(s: string): ProtocolVersion {\n const parts = s.split(\".\");\n if (parts.length !== 3) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (expected \"major.minor.patch\")`);\n }\n const [maj, min, pat] = parts;\n const major = Number(maj);\n const minor = Number(min);\n const patch = Number(pat);\n if (\n !Number.isInteger(major) ||\n !Number.isInteger(minor) ||\n !Number.isInteger(patch) ||\n major < 0 ||\n minor < 0 ||\n patch < 0\n ) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (each part must be a non-negative integer)`);\n }\n return { major, minor, patch };\n}\n\n/**\n * Format a {@link ProtocolVersion} record into its `\"major.minor.patch\"` string form.\n *\n * @param v - the protocol version to format\n * @returns the dot-joined string form\n *\n * @example\n * ```ts\n * formatVersion({ major: 2, minor: 0, patch: 0 }); // '2.0.0'\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#format-version\n */\nexport function formatVersion(v: ProtocolVersion): string {\n return `${v.major}.${v.minor}.${v.patch}`;\n}\n"]}
|