@skaile/workspaces 0.20.0 → 0.22.0-beta.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.
Files changed (212) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/{asset-feeds-JSHWTTJC.js → asset-feeds-PJDJ3QYI.js} +11 -11
  3. package/dist/{asset-feeds-JSHWTTJC.js.map → asset-feeds-PJDJ3QYI.js.map} +1 -1
  4. package/dist/asset-manager/index.js +9 -9
  5. package/dist/asset-manager/installer.js +8 -8
  6. package/dist/base-assets/connectors/deploy.js +10 -9
  7. package/dist/base-assets/connectors/devserver.js +10 -9
  8. package/dist/base-assets/connectors/flow/adapter.js +10 -9
  9. package/dist/base-assets/connectors/flow/run-flow.js +11 -10
  10. package/dist/base-assets/connectors/flow.js +10 -9
  11. package/dist/base-assets/connectors/git.js +10 -9
  12. package/dist/base-assets/connectors/gmail.js +10 -9
  13. package/dist/base-assets/connectors/googledrive.js +10 -9
  14. package/dist/base-assets/connectors/local.js +10 -9
  15. package/dist/base-assets/connectors/mattermost.js +10 -9
  16. package/dist/base-assets/connectors/memory.js +10 -9
  17. package/dist/base-assets/connectors/minio.js +10 -9
  18. package/dist/base-assets/connectors/postgres.js +10 -9
  19. package/dist/base-assets/connectors/s3.js +10 -9
  20. package/dist/base-assets/connectors/sharepoint.js +10 -9
  21. package/dist/base-assets/connectors/sqlite.js +10 -9
  22. package/dist/base-assets/connectors/static-server.js +10 -9
  23. package/dist/base-assets/connectors/tunnel.js +10 -9
  24. package/dist/base-assets/connectors/webdav.js +10 -9
  25. package/dist/base-assets/connectors/xstate-store.js +10 -9
  26. package/dist/base-assets/connectors/xstate.js +10 -9
  27. package/dist/bridge/drivers/claude-sdk.js +13 -3
  28. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  29. package/dist/bridge/drivers/codex.js +13 -3
  30. package/dist/bridge/drivers/codex.js.map +1 -1
  31. package/dist/bridge/drivers/echo.js +13 -4
  32. package/dist/bridge/drivers/echo.js.map +1 -1
  33. package/dist/bridge/drivers/omp.js +13 -3
  34. package/dist/bridge/drivers/omp.js.map +1 -1
  35. package/dist/bridge/index.js +3 -2
  36. package/dist/bridge/src/drivers/claude-sdk.d.ts +7 -0
  37. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  38. package/dist/bridge/src/drivers/codex.d.ts +7 -0
  39. package/dist/bridge/src/drivers/codex.d.ts.map +1 -1
  40. package/dist/bridge/src/drivers/echo.d.ts +6 -0
  41. package/dist/bridge/src/drivers/echo.d.ts.map +1 -1
  42. package/dist/bridge/src/drivers/omp.d.ts +6 -0
  43. package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
  44. package/dist/bridge/src/registry.d.ts +32 -34
  45. package/dist/bridge/src/registry.d.ts.map +1 -1
  46. package/dist/{chunk-4YG2AAFV.js → chunk-2DNSSQ22.js} +7 -7
  47. package/dist/{chunk-4YG2AAFV.js.map → chunk-2DNSSQ22.js.map} +1 -1
  48. package/dist/{chunk-ZWIG55ZX.js → chunk-2XY6732A.js} +3 -3
  49. package/dist/{chunk-ZWIG55ZX.js.map → chunk-2XY6732A.js.map} +1 -1
  50. package/dist/{chunk-2DKWQLFS.js → chunk-CSDQBWE6.js} +5 -5
  51. package/dist/{chunk-2DKWQLFS.js.map → chunk-CSDQBWE6.js.map} +1 -1
  52. package/dist/{chunk-KYYMP5PT.js → chunk-F3MGZ5E6.js} +3 -3
  53. package/dist/{chunk-KYYMP5PT.js.map → chunk-F3MGZ5E6.js.map} +1 -1
  54. package/dist/{chunk-IQYWI5OG.js → chunk-G6GKWGOW.js} +114 -619
  55. package/dist/chunk-G6GKWGOW.js.map +1 -0
  56. package/dist/{chunk-LMDRMZ4F.js → chunk-GKM6MDUC.js} +3 -3
  57. package/dist/{chunk-LMDRMZ4F.js.map → chunk-GKM6MDUC.js.map} +1 -1
  58. package/dist/{chunk-4ACWI5YT.js → chunk-IGQEXBBG.js} +44 -36
  59. package/dist/chunk-IGQEXBBG.js.map +1 -0
  60. package/dist/{chunk-BZGDESAG.js → chunk-J2FCO6TM.js} +2 -2
  61. package/dist/{chunk-BZGDESAG.js.map → chunk-J2FCO6TM.js.map} +1 -1
  62. package/dist/{chunk-BSY56QS7.js → chunk-KA46DUM4.js} +3 -3
  63. package/dist/{chunk-BSY56QS7.js.map → chunk-KA46DUM4.js.map} +1 -1
  64. package/dist/{chunk-RCPFXP3Y.js → chunk-MO4JPTRD.js} +4 -4
  65. package/dist/{chunk-RCPFXP3Y.js.map → chunk-MO4JPTRD.js.map} +1 -1
  66. package/dist/{chunk-FNP4OGGY.js → chunk-NGC7ZQI4.js} +10 -10
  67. package/dist/{chunk-FNP4OGGY.js.map → chunk-NGC7ZQI4.js.map} +1 -1
  68. package/dist/{chunk-2ACJB6JF.js → chunk-RENHNO4J.js} +81 -4
  69. package/dist/chunk-RENHNO4J.js.map +1 -0
  70. package/dist/{chunk-4S4TZDCD.js → chunk-SL6JVGRD.js} +3 -3
  71. package/dist/{chunk-4S4TZDCD.js.map → chunk-SL6JVGRD.js.map} +1 -1
  72. package/dist/{chunk-VVS7MACX.js → chunk-TKOLD2O7.js} +213 -20
  73. package/dist/chunk-TKOLD2O7.js.map +1 -0
  74. package/dist/{chunk-R4FRSB47.js → chunk-TTY56FQQ.js} +4 -4
  75. package/dist/{chunk-R4FRSB47.js.map → chunk-TTY56FQQ.js.map} +1 -1
  76. package/dist/chunk-UZRY5UI2.js +96 -0
  77. package/dist/chunk-UZRY5UI2.js.map +1 -0
  78. package/dist/{chunk-NCUTHLRV.js → chunk-UZVHJ7LX.js} +4 -4
  79. package/dist/{chunk-NCUTHLRV.js.map → chunk-UZVHJ7LX.js.map} +1 -1
  80. package/dist/{chunk-FRPKLIEZ.js → chunk-WIR34WMU.js} +3 -3
  81. package/dist/{chunk-FRPKLIEZ.js.map → chunk-WIR34WMU.js.map} +1 -1
  82. package/dist/{chunk-37JKX6D7.js → chunk-X5Y4EGZB.js} +2 -2
  83. package/dist/{chunk-37JKX6D7.js.map → chunk-X5Y4EGZB.js.map} +1 -1
  84. package/dist/{chunk-S2OVTCAL.js → chunk-XHFMUGDD.js} +3 -3
  85. package/dist/{chunk-S2OVTCAL.js.map → chunk-XHFMUGDD.js.map} +1 -1
  86. package/dist/cli/index.js +701 -413
  87. package/dist/cli/index.js.map +1 -1
  88. package/dist/cli/src/commands/deploy.d.ts +24 -0
  89. package/dist/cli/src/commands/deploy.d.ts.map +1 -0
  90. package/dist/cli/src/commands/integration.d.ts +19 -0
  91. package/dist/cli/src/commands/integration.d.ts.map +1 -0
  92. package/dist/cli/src/commands/plugin-registry-cmd.d.ts +22 -0
  93. package/dist/cli/src/commands/plugin-registry-cmd.d.ts.map +1 -0
  94. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  95. package/dist/cli/src/plugin-store/index.d.ts +37 -0
  96. package/dist/cli/src/plugin-store/index.d.ts.map +1 -0
  97. package/dist/cli/src/plugin-store/load.d.ts +35 -0
  98. package/dist/cli/src/plugin-store/load.d.ts.map +1 -0
  99. package/dist/cli/src/plugin-store/paths.d.ts +23 -0
  100. package/dist/cli/src/plugin-store/paths.d.ts.map +1 -0
  101. package/dist/cli/src/plugin-store/reconcile.d.ts +50 -0
  102. package/dist/cli/src/plugin-store/reconcile.d.ts.map +1 -0
  103. package/dist/cli/src/plugin-store/spec.d.ts +25 -0
  104. package/dist/cli/src/plugin-store/spec.d.ts.map +1 -0
  105. package/dist/connectors/config.js +8 -8
  106. package/dist/connectors/index.js +10 -9
  107. package/dist/connectors/src/connector-manager.d.ts.map +1 -1
  108. package/dist/connectors/src/connector-registry.d.ts +42 -22
  109. package/dist/connectors/src/connector-registry.d.ts.map +1 -1
  110. package/dist/connectors/src/index.d.ts +2 -3
  111. package/dist/connectors/src/index.d.ts.map +1 -1
  112. package/dist/connectors-shared/index.js +8 -0
  113. package/dist/connectors-shared/index.js.map +1 -0
  114. package/dist/connectors-shared/src/index.d.ts +11 -0
  115. package/dist/connectors-shared/src/index.d.ts.map +1 -0
  116. package/dist/connectors-shared/src/schemas.d.ts +10 -0
  117. package/dist/connectors-shared/src/schemas.d.ts.map +1 -0
  118. package/dist/connectors-shared/src/types.d.ts +11 -0
  119. package/dist/connectors-shared/src/types.d.ts.map +1 -0
  120. package/dist/core/index.js +7 -7
  121. package/dist/core/manifest.js +2 -2
  122. package/dist/core/models.js +1 -1
  123. package/dist/core/runtime-assets.js +4 -4
  124. package/dist/core/src/index.d.ts +4 -4
  125. package/dist/core/src/index.d.ts.map +1 -1
  126. package/dist/core/src/lock.d.ts +20 -1
  127. package/dist/core/src/lock.d.ts.map +1 -1
  128. package/dist/core/src/models.d.ts +13 -0
  129. package/dist/core/src/models.d.ts.map +1 -1
  130. package/dist/core/src/workspace-config.d.ts +68 -3
  131. package/dist/core/src/workspace-config.d.ts.map +1 -1
  132. package/dist/core/src/workspace-yaml-editor.d.ts +20 -0
  133. package/dist/core/src/workspace-yaml-editor.d.ts.map +1 -1
  134. package/dist/core/workspace-config.js +3 -3
  135. package/dist/deploy/index.js +454 -0
  136. package/dist/deploy/index.js.map +1 -0
  137. package/dist/deploy/src/handle-store.d.ts +22 -0
  138. package/dist/deploy/src/handle-store.d.ts.map +1 -0
  139. package/dist/deploy/src/index.d.ts +21 -0
  140. package/dist/deploy/src/index.d.ts.map +1 -0
  141. package/dist/deploy/src/targets/container-runtime.d.ts +38 -0
  142. package/dist/deploy/src/targets/container-runtime.d.ts.map +1 -0
  143. package/dist/deploy/src/targets/docker.d.ts +18 -0
  144. package/dist/deploy/src/targets/docker.d.ts.map +1 -0
  145. package/dist/deploy/src/targets/local.d.ts +30 -0
  146. package/dist/deploy/src/targets/local.d.ts.map +1 -0
  147. package/dist/deploy/src/targets/podman.d.ts +18 -0
  148. package/dist/deploy/src/targets/podman.d.ts.map +1 -0
  149. package/dist/deploy/src/targets/port.d.ts +10 -0
  150. package/dist/deploy/src/targets/port.d.ts.map +1 -0
  151. package/dist/deploy/src/targets/stream-lines.d.ts +44 -0
  152. package/dist/deploy/src/targets/stream-lines.d.ts.map +1 -0
  153. package/dist/discovery/index.js +3 -3
  154. package/dist/{ensure-sources-LRT3TIWI.js → ensure-sources-COGVKY44.js} +11 -11
  155. package/dist/{ensure-sources-LRT3TIWI.js.map → ensure-sources-COGVKY44.js.map} +1 -1
  156. package/dist/{flows-6BNO4GKK.js → flows-DYFTPCPM.js} +4 -4
  157. package/dist/{flows-6BNO4GKK.js.map → flows-DYFTPCPM.js.map} +1 -1
  158. package/dist/library/index.js +4 -4
  159. package/dist/open-library-DWAQFUSQ.js +13 -0
  160. package/dist/{open-library-IOYWFK7M.js.map → open-library-DWAQFUSQ.js.map} +1 -1
  161. package/dist/plugin-registry/index.js +4 -0
  162. package/dist/plugin-registry/index.js.map +1 -0
  163. package/dist/plugin-registry/src/context.d.ts +29 -0
  164. package/dist/plugin-registry/src/context.d.ts.map +1 -0
  165. package/dist/plugin-registry/src/deploy-handle.d.ts +60 -0
  166. package/dist/plugin-registry/src/deploy-handle.d.ts.map +1 -0
  167. package/dist/plugin-registry/src/errors.d.ts +23 -0
  168. package/dist/plugin-registry/src/errors.d.ts.map +1 -0
  169. package/dist/plugin-registry/src/index.d.ts +16 -0
  170. package/dist/plugin-registry/src/index.d.ts.map +1 -0
  171. package/dist/plugin-registry/src/internal.d.ts +13 -0
  172. package/dist/plugin-registry/src/internal.d.ts.map +1 -0
  173. package/dist/plugin-registry/src/registry.d.ts +25 -0
  174. package/dist/plugin-registry/src/registry.d.ts.map +1 -0
  175. package/dist/plugin-registry/src/targets.d.ts +42 -0
  176. package/dist/plugin-registry/src/targets.d.ts.map +1 -0
  177. package/dist/plugin-store-6OENKNFW.js +144 -0
  178. package/dist/plugin-store-6OENKNFW.js.map +1 -0
  179. package/dist/runner/index.js +14 -13
  180. package/dist/sdk/asset-manager.js +9 -9
  181. package/dist/sdk/bridge.js +3 -2
  182. package/dist/sdk/core.js +7 -7
  183. package/dist/sdk/index.js +15 -14
  184. package/dist/sdk/index.js.map +1 -1
  185. package/dist/sdk/runner.js +14 -13
  186. package/dist/{setup-CJWJWYEO.js → setup-ACMP3QZC.js} +12 -11
  187. package/dist/setup-ACMP3QZC.js.map +1 -0
  188. package/dist/store-client-ZSLNOOQG.js +14 -0
  189. package/dist/{store-client-H6BTDCA4.js.map → store-client-ZSLNOOQG.js.map} +1 -1
  190. package/dist/tui/index.js +14 -13
  191. package/dist/tui/index.js.map +1 -1
  192. package/dist/workspace-plugin/adapters/mcp.js +2 -2
  193. package/dist/workspace-plugin/adapters/omp.js +3 -3
  194. package/dist/workspace-plugin/index.js +1 -1
  195. package/package.json +20 -23
  196. package/dist/base-assets/connectors/redis/adapter.d.ts +0 -39
  197. package/dist/base-assets/connectors/redis/adapter.d.ts.map +0 -1
  198. package/dist/base-assets/connectors/redis.js +0 -20
  199. package/dist/base-assets/connectors/redis.js.map +0 -1
  200. package/dist/base-assets/connectors/yjs/adapter.d.ts +0 -50
  201. package/dist/base-assets/connectors/yjs/adapter.d.ts.map +0 -1
  202. package/dist/base-assets/connectors/yjs.js +0 -20
  203. package/dist/base-assets/connectors/yjs.js.map +0 -1
  204. package/dist/chunk-2ACJB6JF.js.map +0 -1
  205. package/dist/chunk-4ACWI5YT.js.map +0 -1
  206. package/dist/chunk-IQYWI5OG.js.map +0 -1
  207. package/dist/chunk-VVS7MACX.js.map +0 -1
  208. package/dist/cli/src/commands/plugin.d.ts +0 -14
  209. package/dist/cli/src/commands/plugin.d.ts.map +0 -1
  210. package/dist/open-library-IOYWFK7M.js +0 -13
  211. package/dist/setup-CJWJWYEO.js.map +0 -1
  212. package/dist/store-client-H6BTDCA4.js +0 -14
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../core/src/repo-manager.ts","../core/src/workspace-config.ts"],"names":["resolve","join","existsSync","mkdirSync","writeFileSync","homedir","parsePath","parse","stringify","readFileSync"],"mappings":";;;;;;;;AAmCO,SAAS,iBAAA,GAA4B;AAC1C,EAAA,OAAO,QAAQ,GAAA,CAAI,gBAAA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EAAA,MAAM,UAAA,GAAa,OAAO,KAAA,EAAO,UAAA;AACjC,EAAA,IAAI,CAAC,YAAY,OAAO,MAAA;AAGxB,EAAA,IAAI,UAAA,CAAW,UAAA,CAAW,cAAc,CAAA,EAAG;AACzC,IAAA,MAAM,OAAA,GAAU,UAAA,CAAW,KAAA,CAAM,cAAA,CAAe,MAAM,CAAA;AACtD,IAAA,MAAM,WAAA,GAAc,gBAAgB,UAAU,CAAA;AAC9C,IAAA,IAAI,CAAC,aAAa,OAAO,MAAA;AACzB,IAAA,OAAOC,IAAAA,CAAK,aAAa,OAAO,CAAA;AAAA,EAClC;AAGA,EAAA,IAAI,UAAA,CAAW,UAAA,CAAW,QAAQ,CAAA,EAAG;AACnC,IAAA,MAAM,GAAA,GAAM,cAAc,UAAU,CAAA;AACpC,IAAA,MAAM,YAAA,GAAe,MAAA,CAAO,YAAA,IAAgB,EAAC;AAC7C,IAAA,MAAM,WAAW,iBAAA,EAAkB;AACnC,IAAA,MAAM,QAAQ,YAAA,CAAa,GAAA,EAAK,cAAc,QAAA,EAAU,EAAE,YAAY,CAAA;AACtE,IAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,IAAA,OAAO,OAAA,CAAQ,MAAM,MAAM,CAAA;AAAA,EAC7B;AAGA,EAAA,OAAOD,OAAAA,CAAQ,YAAY,UAAU,CAAA;AACvC","file":"chunk-TKOLD2O7.js","sourcesContent":["/**\n * Repository operations — clone, pull, scan, resolve, link.\n *\n * Remote repos are cloned to a shared global cache (~/.skaile/repos/<name>/).\n * Projects reference the cache via symlinks at .skaile/repos/<name>/.\n * Local repos (path:) are used directly. Linked repos override remote URLs.\n *\n * Supports partial clone + sparse checkout for large repos.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n symlinkSync,\n lstatSync,\n writeFileSync,\n} from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { parse, stringify } from \"yaml\";\nimport type { AssetRef, CatalogEntry } from \"./models.js\";\nimport { parseAssetRef } from \"./models.js\";\nimport type { RepositoryDeclaration } from \"./workspace-config.js\";\nimport { scanDirectory } from \"./manifest.js\";\n\n// ── Global cache ─────────────────────────────────────────────────────────────\n\n/**\n * Return the global shared repo cache directory (`~/.skaile/repos` by default).\n * Override with the `SKAILE_CACHE_DIR` environment variable.\n * @docLink packages/core/api-reference#get-global-cache-dir\n */\nexport function getGlobalCacheDir(): string {\n return process.env.SKAILE_CACHE_DIR ?? join(homedir(), \".skaile\", \"repos\");\n}\n\n// ── Git operations ───────────────────────────────────────────────────────────\n\n/**\n * Shared env for all git subprocess spawns.\n * GIT_TERMINAL_PROMPT=0 prevents git from opening /dev/tty to ask for\n * credentials when running inside a CLI spinner (which holds the terminal in\n * raw mode). Without this, git bypasses stdio: \"pipe\" and the process hangs\n * indefinitely waiting for input that can never arrive.\n */\nconst GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: \"0\" };\n\n/**\n * Clone a remote git repository using partial clone (treeless) with sparse checkout.\n * Falls back to a regular shallow clone if the server does not support partial clones.\n *\n * @param url - Remote git URL\n * @param branch - Branch to clone\n * @param dest - Local destination directory\n * @returns `true` on success, `false` on failure\n * @docLink packages/core/api-reference#clone-repo\n */\nexport function cloneRepo(url: string, branch: string, dest: string): boolean {\n mkdirSync(dest, { recursive: true });\n // Try partial clone first (requires git 2.25+ and server support)\n const r = spawnSync(\n \"git\",\n [\"clone\", \"--depth=1\", \"--filter=blob:none\", \"--sparse\", \"--branch\", branch, url, dest],\n { stdio: \"pipe\", env: GIT_ENV },\n );\n if (r.status === 0) {\n // Enable cone mode for sparse checkout\n spawnSync(\"git\", [\"-C\", dest, \"sparse-checkout\", \"init\", \"--cone\"], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n // Check out everything initially (for discovery)\n spawnSync(\"git\", [\"-C\", dest, \"sparse-checkout\", \"disable\"], { stdio: \"pipe\", env: GIT_ENV });\n return true;\n }\n // Fallback: regular shallow clone\n const fallback = spawnSync(\"git\", [\"clone\", \"--depth=1\", \"--branch\", branch, url, dest], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n return fallback.status === 0;\n}\n\n/**\n * Pull the latest commits for a cloned repository.\n * On shallow clone divergence, falls back to `git fetch --depth=1` + `git reset --hard`.\n *\n * @param dest - Local repo directory\n * @param branch - Branch to pull\n * @returns `true` on success, `false` on failure\n * @docLink packages/core/api-reference#pull-repo\n */\nexport function pullRepo(dest: string, branch: string): boolean {\n const r = spawnSync(\"git\", [\"-C\", dest, \"pull\", \"--depth=1\", \"--ff-only\"], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n if (r.status === 0) return true;\n // Shallow clones can diverge — force-sync via fetch + reset\n const fetch = spawnSync(\"git\", [\"-C\", dest, \"fetch\", \"--depth=1\", \"origin\", branch], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n if (fetch.status !== 0) return false;\n const reset = spawnSync(\"git\", [\"-C\", dest, \"reset\", \"--hard\", `origin/${branch}`], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n return reset.status === 0;\n}\n\n/**\n * Return the current HEAD commit SHA for a local repository.\n *\n * @param repoDir - Absolute path to the cloned repository\n * @returns Full commit SHA string, or `null` on failure\n * @docLink packages/core/api-reference#get-repo-commit\n */\nexport function getRepoCommit(repoDir: string): string | null {\n const r = spawnSync(\"git\", [\"-C\", repoDir, \"rev-parse\", \"HEAD\"], {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n return r.status === 0 ? r.stdout.trim() : null;\n}\n\n/**\n * Check out a specific tag, branch, or commit SHA in a local repository.\n * Fetches the ref from `origin` first, then attempts `FETCH_HEAD` checkout.\n *\n * @param repoDir - Absolute path to the cloned repository\n * @param pin - Tag, branch name, or commit SHA\n * @returns `true` on success, `false` on failure\n * @docLink packages/core/api-reference#checkout-pin\n */\nexport function checkoutPin(repoDir: string, pin: string): boolean {\n // Fetch the ref first (works for tags, branches, and commits)\n spawnSync(\"git\", [\"-C\", repoDir, \"fetch\", \"--depth=1\", \"origin\", pin], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n const r = spawnSync(\"git\", [\"-C\", repoDir, \"checkout\", \"FETCH_HEAD\"], {\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n if (r.status === 0) return true;\n // Fallback: try direct checkout (for branches already fetched)\n const r2 = spawnSync(\"git\", [\"-C\", repoDir, \"checkout\", pin], { stdio: \"pipe\", env: GIT_ENV });\n return r2.status === 0;\n}\n\n// ── Link management ──────────────────────────────────────────────────────────\n\n/**\n * Map of repo name → local filesystem path for development overrides.\n * Stored in `.skaile/links.yaml`; used to redirect a named repo to a local clone.\n * @docLink packages/core/api-reference#link-config\n */\nexport interface LinkConfig {\n [repoName: string]: string; // repo name → local path\n}\n\n/** Path to the project-local links file. */\nfunction linksFile(projectDir: string): string {\n return join(projectDir, \".skaile\", \"links.yaml\");\n}\n\n/**\n * Read the dev-link map from `.skaile/links.yaml` in the project directory.\n * Returns an empty object when no links file exists.\n *\n * @param projectDir - Absolute path to the project root\n * @returns `LinkConfig` map (may be empty)\n * @docLink packages/core/api-reference#read-links\n */\nexport function readLinks(projectDir: string): LinkConfig {\n const file = linksFile(projectDir);\n if (!existsSync(file)) return {};\n try {\n return (parse(readFileSync(file, \"utf8\")) as LinkConfig) ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Persist the dev-link map to `.skaile/links.yaml` in the project directory.\n *\n * @param projectDir - Absolute path to the project root\n * @param links - Updated `LinkConfig` to write\n * @docLink packages/core/api-reference#write-links\n */\nexport function writeLinks(projectDir: string, links: LinkConfig): void {\n const dir = join(projectDir, \".skaile\");\n mkdirSync(dir, { recursive: true });\n writeFileSync(linksFile(projectDir), stringify(links));\n}\n\n/**\n * Register a local filesystem path as a dev override for a named repository.\n * The path is stored in `.skaile/links.yaml` and takes priority over the remote URL at runtime.\n *\n * @param projectDir - Absolute path to the project root\n * @param repoName - Name of the repository to override\n * @param localPath - Local path (absolute or relative to `projectDir`) to use instead\n * @throws When the resolved path does not exist\n * @docLink packages/core/api-reference#link-repo\n */\nexport function linkRepo(projectDir: string, repoName: string, localPath: string): void {\n const resolved = resolve(projectDir, localPath);\n if (!existsSync(resolved)) {\n throw new Error(`Path not found: ${localPath} (resolved: ${resolved})`);\n }\n const links = readLinks(projectDir);\n links[repoName] = resolved;\n writeLinks(projectDir, links);\n}\n\n/**\n * Remove the dev-link override for a named repository, reverting it to the remote URL.\n *\n * @param projectDir - Absolute path to the project root\n * @param repoName - Name of the repository to unlink\n * @returns `true` if the link existed and was removed, `false` if no link was found\n * @docLink packages/core/api-reference#unlink-repo\n */\nexport function unlinkRepo(projectDir: string, repoName: string): boolean {\n const links = readLinks(projectDir);\n if (!links[repoName]) return false;\n delete links[repoName];\n writeLinks(projectDir, links);\n return true;\n}\n\n// ── Repo lifecycle ───────────────────────────────────────────────────────────\n\n/**\n * Ensure a repository is available locally, cloning or symlinking as needed.\n *\n * Resolution order:\n * 1. Linked override (`.skaile/links.yaml`) — highest priority\n * 2. Local path (`decl.path`) — direct filesystem reference\n * 3. Remote URL (`decl.url`) — cloned to the shared global cache, symlinked into `.skaile/repos/`\n *\n * Pin support: when `opts.pin` is provided, the tag/commit is checked out after clone.\n *\n * @param decl - Repository declaration from `skaile.yaml`\n * @param name - Logical repository name (cache key)\n * @param reposDir - Project-local repos directory (`.skaile/repos/`)\n * @param opts - Optional: `pin` for a specific commit/tag, `projectDir` for link lookup\n * @returns Absolute path to the local repository directory\n * @throws When the repository cannot be resolved or cloned\n * @docLink packages/core/api-reference#ensure-repo\n */\nexport function ensureRepo(\n decl: RepositoryDeclaration,\n name: string,\n reposDir: string,\n opts?: { pin?: string; projectDir?: string },\n): string {\n // 1. Check for linked override\n if (opts?.projectDir) {\n const links = readLinks(opts.projectDir);\n if (links[name]) {\n const linked = links[name];\n if (!existsSync(linked)) {\n throw new Error(\n `Linked path not found: ${linked}. Remove the .skaile/links.yaml entry to clear it.`,\n );\n }\n return linked;\n }\n }\n\n // 2. Local path\n if (decl.path) {\n const projectDir = opts?.projectDir ?? resolve(reposDir, \"..\");\n const resolved = resolve(projectDir, decl.path);\n if (!existsSync(resolved)) {\n throw new Error(`Local repository path not found: ${decl.path} (resolved: ${resolved})`);\n }\n return resolved;\n }\n\n // 3. Remote URL — clone to shared global cache\n if (decl.url) {\n const branch = decl.branch ?? \"main\";\n const globalCache = getGlobalCacheDir();\n const cacheDest = join(globalCache, name);\n\n // Clone or pull in global cache\n if (existsSync(join(cacheDest, \".git\"))) {\n if (!opts?.pin) pullRepo(cacheDest, branch);\n } else {\n if (!cloneRepo(decl.url, branch, cacheDest)) {\n throw new Error(`Failed to clone ${decl.url} (branch: ${branch})`);\n }\n }\n\n // Checkout pin if specified\n if (opts?.pin) {\n checkoutPin(cacheDest, opts.pin);\n }\n\n // Create symlink in project-local .skaile/repos/ → global cache\n const projectDest = join(reposDir, name);\n const projectExists = existsSync(projectDest);\n const isSymlink = projectExists && lstatSync(projectDest).isSymbolicLink();\n\n if (!projectExists) {\n mkdirSync(reposDir, { recursive: true });\n try {\n symlinkSync(cacheDest, projectDest);\n } catch {\n // Symlink failed (Windows?), just use cache dir directly\n return cacheDest;\n }\n } else if (!isSymlink) {\n // Stale real directory (legacy clone) — replace with symlink to global cache\n rmSync(projectDest, { recursive: true });\n try {\n symlinkSync(cacheDest, projectDest);\n } catch {\n // Symlink failed, fall through to return cacheDest\n }\n }\n\n return cacheDest;\n }\n\n throw new Error(`Repository \"${name}\" has neither url nor path`);\n}\n\n// ── Scanning ─────────────────────────────────────────────────────────────────\n\n/**\n * Scan a repository directory and return all discovered asset catalog entries.\n * Delegates to `scanDirectory` from `manifest.ts`.\n *\n * @param repoDir - Absolute path to the repository root\n * @param repoName - Repository name attached to each produced entry\n * @returns Array of `CatalogEntry` objects found in the repository\n * @docLink packages/core/api-reference#scan-repo\n */\nexport function scanRepo(repoDir: string, repoName: string): CatalogEntry[] {\n return scanDirectory(repoDir, repoName);\n}\n\n// ── Resolution ───────────────────────────────────────────────────────────────\n\n/**\n * Resolve a single asset reference to its `CatalogEntry` by scanning declared repositories.\n *\n * Search order:\n * 1. Explicit `@repository` qualifier on the ref — only that repo is searched.\n * 2. `opts.preferRepo` — searched first when set (repo affinity for transitive deps).\n * 3. All declared repos in declaration order.\n *\n * @param ref - Parsed asset reference to resolve\n * @param repositories - Repository declarations from `skaile.yaml`\n * @param reposDir - Project-local repos directory (`.skaile/repos/`)\n * @param opts - Optional: `projectDir` for link lookup, `preferRepo` for affinity\n * @returns Matching `CatalogEntry`, or `null` if not found in any repository\n * @docLink packages/core/api-reference#resolve-asset\n */\nexport function resolveAsset(\n ref: AssetRef,\n repositories: Record<string, RepositoryDeclaration>,\n reposDir: string,\n opts?: { projectDir?: string; preferRepo?: string },\n): CatalogEntry | null {\n let repoNames: string[];\n if (ref.repository) {\n // Explicit @repo qualifier — only search that repo\n repoNames = [ref.repository];\n } else if (opts?.preferRepo && opts.preferRepo in repositories) {\n // Repo affinity from parent — search preferred repo first, then others\n const rest = Object.keys(repositories).filter((n) => n !== opts.preferRepo);\n repoNames = [opts.preferRepo, ...rest];\n } else {\n repoNames = Object.keys(repositories);\n }\n\n for (const repoName of repoNames) {\n const decl = repositories[repoName];\n if (!decl) continue;\n\n const repoDir = resolveRepoDir(decl, repoName, reposDir, opts?.projectDir);\n if (!repoDir || !existsSync(repoDir)) continue;\n\n const entries = scanRepo(repoDir, repoName);\n const match = entries.find((e) => e.kind === ref.kind && e.name === ref.name);\n if (match) return match;\n }\n\n return null;\n}\n\n/** Resolve repo dir without cloning (for lookups). Checks links first. */\nfunction resolveRepoDir(\n decl: RepositoryDeclaration,\n name: string,\n reposDir: string,\n projectDir?: string,\n): string | null {\n // Check links\n if (projectDir) {\n const links = readLinks(projectDir);\n if (links[name]) {\n return existsSync(links[name]) ? links[name] : null;\n }\n }\n\n if (decl.path) {\n const base = projectDir ?? resolve(reposDir, \"..\");\n const resolved = resolve(base, decl.path);\n return existsSync(resolved) ? resolved : null;\n }\n\n // Check project-local symlink or global cache\n const projectDest = join(reposDir, name);\n if (existsSync(projectDest)) return projectDest;\n\n const globalDest = join(getGlobalCacheDir(), name);\n if (existsSync(join(globalDest, \".git\"))) return globalDest;\n\n return null;\n}\n\n/**\n * Collision record: the same `kind:name` was found in more than one repository.\n * Produced by `resolveAll` when multiple repos contain the same asset.\n * @docLink packages/core/api-reference#asset-collision\n */\nexport interface AssetCollision {\n /** \"kind:name\" key. */\n key: string;\n /** Repository the asset was resolved from. */\n resolvedFrom: string;\n /** Other repositories that also contain this asset. */\n shadowedIn: string[];\n}\n\n/**\n * Result of a full transitive dependency resolution via `resolveAll`.\n * @docLink packages/core/api-reference#resolve-result\n */\nexport interface ResolveResult {\n /** All resolved assets in leaf-first (dependency) order. */\n resolved: CatalogEntry[];\n /** Refs that could not be found in any repo. */\n missing: string[];\n /** Maps \"kind:name\" → resolved_by (\"direct\" or \"kind:name\" of parent). */\n resolvedBy: Map<string, string>;\n /** Assets that exist in multiple repos (resolved entry shadows others). */\n collisions: AssetCollision[];\n}\n\n/**\n * Resolve all dependencies (including transitive) from a list of asset ref strings.\n * Returns resolved assets in leaf-first order (dependencies before dependents).\n *\n * Repo affinity: transitive deps inherit the parent entry's repository as a\n * search preference, so bundled assets are found in their own repo first.\n * Explicit `@repo` qualifiers always take precedence over affinity.\n *\n * @param deps - Top-level asset ref strings to resolve (e.g. `[\"skill:use-exa\", \"agent:pi\"]`)\n * @param repositories - Repository declarations from `skaile.yaml`\n * @param reposDir - Project-local repos directory\n * @param opts - Optional: `projectDir` for link lookup\n * @returns `ResolveResult` with resolved entries, missing refs, provenance map, and collisions\n * @docLink packages/core/api-reference#resolve-all\n */\nexport function resolveAll(\n deps: string[],\n repositories: Record<string, RepositoryDeclaration>,\n reposDir: string,\n opts?: { projectDir?: string },\n): ResolveResult {\n const resolved: CatalogEntry[] = [];\n const seen = new Set<string>();\n const missing: string[] = [];\n const resolvedBy = new Map<string, string>();\n\n function visit(refStr: string, parent: string, parentRepo?: string): void {\n const ref = parseAssetRef(refStr);\n const key = `${ref.kind}:${ref.name}`;\n if (seen.has(key)) return;\n seen.add(key);\n\n // Pass repo affinity: explicit @repo on the ref wins, then parent's repo\n const preferRepo = ref.repository ?? parentRepo;\n const entry = resolveAsset(ref, repositories, reposDir, {\n ...opts,\n preferRepo,\n });\n if (!entry) {\n missing.push(refStr);\n return;\n }\n\n resolvedBy.set(key, parent);\n\n // Propagate entry's repository to transitive deps\n const entryRepo = entry.repository;\n\n // Resolve transitive deps (from requires field)\n for (const req of entry.requires) {\n visit(`${req.kind}:${req.name}`, key, entryRepo);\n }\n\n // Resolve bundle dependencies\n for (const dep of entry.dependencies) {\n visit(dep, key, entryRepo);\n }\n\n resolved.push(entry);\n }\n\n for (const dep of deps) {\n visit(dep, \"direct\");\n }\n\n // Detect collisions: check each resolved asset against other repos\n const collisions = detectCollisions(resolved, repositories, reposDir, opts?.projectDir);\n\n return { resolved, missing, resolvedBy, collisions };\n}\n\n/**\n * For each resolved asset, check whether other repos also contain the same\n * kind:name pair. Returns only actual collisions (2+ repos).\n */\nfunction detectCollisions(\n resolved: CatalogEntry[],\n repositories: Record<string, RepositoryDeclaration>,\n reposDir: string,\n projectDir?: string,\n): AssetCollision[] {\n const repoNames = Object.keys(repositories);\n if (repoNames.length < 2) return [];\n\n // Build per-repo catalog caches (avoids re-scanning)\n const repoEntries = new Map<string, CatalogEntry[]>();\n for (const repoName of repoNames) {\n const decl = repositories[repoName];\n if (!decl) continue;\n const repoDir = resolveRepoDir(decl, repoName, reposDir, projectDir);\n if (!repoDir || !existsSync(repoDir)) continue;\n repoEntries.set(repoName, scanRepo(repoDir, repoName));\n }\n\n const collisions: AssetCollision[] = [];\n for (const entry of resolved) {\n const key = `${entry.kind}:${entry.name}`;\n const shadowedIn: string[] = [];\n for (const [repoName, entries] of repoEntries) {\n if (repoName === entry.repository) continue;\n if (entries.some((e) => e.kind === entry.kind && e.name === entry.name)) {\n shadowedIn.push(repoName);\n }\n }\n if (shadowedIn.length > 0 && entry.repository) {\n collisions.push({ key, resolvedFrom: entry.repository, shadowedIn });\n }\n }\n return collisions;\n}\n\n// ── Status ───────────────────────────────────────────────────────────────────\n\n/**\n * Status summary for a repository — local HEAD, remote HEAD, and how far behind.\n * @docLink packages/core/api-reference#repo-status\n */\nexport interface RepoStatus {\n /** Logical name of the repository. */\n name: string;\n /** Whether the repo is local, remote (cloned), or linked (dev override). */\n kind: \"local\" | \"remote\" | \"linked\";\n /** Current local HEAD commit SHA. */\n localHead: string;\n /** Remote HEAD commit SHA (fetched during status check). */\n remoteHead: string;\n /** Number of commits the local clone is behind the remote. */\n behind: number;\n /** `true` when `behind === 0`. */\n upToDate: boolean;\n /** Absolute path the link points to (linked repos only). */\n linkedTo?: string;\n /** Human-readable error string when the status check failed. */\n error?: string;\n}\n\n/**\n * Check whether a repository clone is up to date with its remote.\n * Fetches the last 50 commits to compare local HEAD with `origin/<branch>`.\n *\n * @param decl - Repository declaration from `skaile.yaml`\n * @param name - Logical repository name\n * @param reposDir - Project-local repos directory\n * @param projectDir - Optional project root for link lookup\n * @returns `RepoStatus` describing the current state\n * @docLink packages/core/api-reference#check-repo-status\n */\nexport function checkRepoStatus(\n decl: RepositoryDeclaration,\n name: string,\n reposDir: string,\n projectDir?: string,\n): RepoStatus {\n // Check for linked override\n if (projectDir) {\n const links = readLinks(projectDir);\n if (links[name]) {\n return {\n name,\n kind: \"linked\",\n localHead: \"\",\n remoteHead: \"\",\n behind: 0,\n upToDate: true,\n linkedTo: links[name],\n };\n }\n }\n\n const base: RepoStatus = {\n name,\n kind: decl.path ? \"local\" : \"remote\",\n localHead: \"\",\n remoteHead: \"\",\n behind: 0,\n upToDate: true,\n };\n\n if (decl.path) return base;\n\n // Check global cache first, then project-local\n let dest = join(getGlobalCacheDir(), name);\n if (!existsSync(join(dest, \".git\"))) {\n dest = join(reposDir, name);\n }\n if (!existsSync(join(dest, \".git\"))) {\n return { ...base, error: \"Not cloned yet\" };\n }\n\n const branch = decl.branch ?? \"main\";\n\n const localHead = getRepoCommit(dest);\n if (!localHead) return { ...base, error: \"Failed to read local HEAD\" };\n base.localHead = localHead;\n\n const fetchR = spawnSync(\"git\", [\"-C\", dest, \"fetch\", \"--depth=50\", \"origin\", branch], {\n encoding: \"utf8\",\n stdio: \"pipe\",\n env: GIT_ENV,\n });\n if (fetchR.status !== 0) return { ...base, error: \"Fetch failed\" };\n\n const remoteR = spawnSync(\"git\", [\"-C\", dest, \"rev-parse\", `origin/${branch}`], {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n if (remoteR.status !== 0) return { ...base, error: \"Failed to read remote HEAD\" };\n base.remoteHead = remoteR.stdout.trim();\n\n const countR = spawnSync(\n \"git\",\n [\"-C\", dest, \"rev-list\", \"--left-right\", \"--count\", `HEAD...origin/${branch}`],\n { encoding: \"utf8\", stdio: \"pipe\" },\n );\n if (countR.status === 0) {\n const parts = countR.stdout.trim().split(/\\s+/);\n base.behind = parseInt(parts[1] ?? \"0\", 10);\n }\n\n base.upToDate = base.behind === 0;\n return base;\n}\n","/**\n * Unified workspace configuration — `skaile.yaml` / `<name>.skaile.yaml`\n *\n * Single file combining AI resources, data connectors, agent behavior,\n * runtime defaults, and workspace layout.\n *\n * ── File naming ──────────────────────────────────────────────────────────\n *\n * skaile.yaml → canonical default workspace config\n * staging.skaile.yaml → alternative workspace config\n * *.skaile.yaml → glob pattern for named configs\n *\n * ── Stacking ─────────────────────────────────────────────────────────────\n *\n * Files stack across scope levels (same name must match):\n * ~/.skaile/skaile.yaml priority 10 (user)\n * /app/skaile.yaml priority 20 (app)\n * /project/skaile.yaml priority 30 (project)\n *\n * ── Relationship to other files ──────────────────────────────────────────\n *\n * .skaile/settings.json User-specific overrides (API keys, personal\n * model preferences). Gitignored. Overrides\n * workspace config defaults at runtime.\n *\n * workspace.yaml Scaffold template. Generates skaile.yaml\n * at `skaile init` time. Never read at runtime.\n *\n * agent.yaml Agent definition (identity). Referenced from\n * skaile.yaml via `agent.definition`.\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, parse as parsePath, resolve } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport { fromMcpServerMd } from \"./manifest.js\";\nimport { type CatalogEntry, parseAssetRef } from \"./models.js\";\nimport { getGlobalCacheDir, resolveAsset } from \"./repo-manager.js\";\n\n// ── Agent config ──────────────────────────────────────────────────────────────\n\n/**\n * Named agent configuration profile. The \"default\" profile is the active one.\n * Personal overrides (apiKeys, model preference) live in .skaile/settings.json.\n * @docLink packages/core/workspace-config#agent-config-profile\n */\nexport interface AgentConfigProfile {\n /** Bridge driver to use: \"claude-sdk\", \"codex\", or \"omp\". */\n driver?: string;\n /** Default LLM provider: \"anthropic\", \"openai\", \"google\", etc. */\n provider?: string;\n /** Default model identifier. */\n model?: string;\n /** Thinking mode for Claude models. */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level. */\n effort?: \"low\" | \"medium\" | \"high\" | string;\n /** Override framework install paths (rarely needed). */\n skills_dir?: string;\n agents_dir?: string;\n prompts_dir?: string;\n}\n\n// ── Startup ───────────────────────────────────────────────────────────────────\n\n/**\n * A startup directive — run on workspace launch.\n *\n * String form: \"agent:research-assistant\" — start the named agent\n * Object form: { \"system-prompt-override\": \"...\" } — replace system prompt\n * { \"system-prompt-append\": \"...\" } — append to system prompt\n * @docLink packages/core/workspace-config#startup-directive\n */\nexport type StartupDirective = string | Record<string, string>;\n\n// ── AI Resources ──────────────────────────────────────────────────────────────\n\n/**\n * An AI resource source with its own dependency list.\n * All declared dependencies are installed from this source's catalog.\n * @docLink packages/core/workspace-config#ai-resource-entry\n */\nexport interface AiResourceEntry {\n /** Source name (used as cache key and in CLI output). */\n name: string;\n /** Path to local directory or GitHub repo URL. */\n path: string;\n /** Git branch (default: main). */\n branch?: string;\n /** Skill/agent/package/flow refs to install from this source. Syntax: \"kind:name\". */\n dependencies?: string[];\n /** Auto-deploy to framework dirs on install. */\n auto_deploy?: boolean;\n}\n\n// ── Repository Declaration ────────────────────────────────────────────────────\n\n/**\n * Internal-only data shape used by the legacy asset install pipeline\n * (`repo-manager`, `lock`, `runtime-assets`). Carries the resolved URL or\n * path for an `ai_resources[]` entry. Not surfaced via the workspace config\n * schema — new sources are registered through `@skaile/library`.\n *\n * @docLink packages/core/workspace-config#repository-declaration\n */\nexport interface RepositoryDeclaration {\n /** GitHub or git URL (for remote repos). */\n url?: string;\n /** Local filesystem path (for local repos). */\n path?: string;\n /** Git branch (default: main). */\n branch?: string;\n /** Upstream URL for fork workflows. */\n upstream?: string;\n}\n\n// ── Source Entry ──────────────────────────────────────────────────────────────\n\n/**\n * A github source registered for this project — a third-party repo of AI\n * assets the project depends on. Bytes live under `~/.skaile/sources/<name>/`\n * (machine-global clone cache); this entry is the *per-project* declaration\n * that the project uses the source.\n *\n * Persisted under the `sources:` key in `skaile.yaml`.\n *\n * @docLink packages/core/workspace-config#source-entry\n */\nexport interface SourceEntry {\n /** Slug used as cache directory name (`~/.skaile/sources/<name>/`). */\n name: string;\n /** Git URL (ssh or https). */\n url: string;\n /** Git branch (default: main). */\n branch?: string;\n}\n\n// ── Mounts ──────────────────────────────────────────────────────────────────\n\n/**\n * A filesystem mount — projected storage backend.\n * @docLink packages/core/workspace-config#mount-declaration\n */\ninterface MountDeclaration {\n /** Unique identifier. Used as mount dir name. */\n id: string;\n /** Mount driver: \"local\", \"git\", \"s3\", \"webdav\", \"sharepoint\". */\n driver: string;\n /** What to mount: URL, bucket path, host filesystem path. */\n source: string;\n /** Workspace-relative mount point (default: .mounts/<id>). */\n target?: string;\n /** Access level enforced by the mount driver. */\n access?: \"read-only\" | \"read-write\";\n /** Credential reference: \"env:VAR_NAME\" or inline value. */\n auth?: string;\n /**\n * Whether to watch this mount for filesystem changes.\n * true = always watch, false = never watch, undefined = auto (watch if read-write).\n */\n watch?: boolean;\n /**\n * **Expert-only.** When `true`, the mount manager wires the resolved\n * credential into the workspace so the agent's interactive `git`/`curl`\n * tools can authenticate directly against the mount's host. Defaults to\n * `false` — agents have no credential exposure and rely on driver-managed\n * pulls/pushes. See `_devlog/specs/2026-05-05-git-credential-tiers.md`.\n */\n exposeAccessToken?: boolean;\n /**\n * Optional override for the access token TTL (seconds). When omitted, the\n * provider's natural TTL is used. Values above the provider's documented\n * maximum are silently capped.\n */\n accessTokenTTL?: number;\n /** Driver-specific configuration (branch, region, etc.). */\n options?: Record<string, unknown>;\n}\n\n// ── Connectors ────────────────────────────────────────────────────────────────\n\n/**\n * A data connector — tool-accessed backend the agent interacts with.\n * @docLink packages/core/workspace-config#connector-declaration\n */\nexport interface ConnectorDeclaration {\n /** Unique identifier. Used as tool namespace. */\n id: string;\n /** Connector adapter: \"postgres\", \"redis\", \"sqlite\", \"memory\", \"xstate\", \"xstate-store\", \"yjs\". */\n driver: string;\n /**\n * Access level enforced by ConnectorManager.\n * Optional in config — ConnectorManager defaults to \"read-only\" when absent.\n */\n access?: \"read-only\" | \"read-write\";\n /** Credential reference: \"env:VAR_NAME\" or inline value. */\n auth?: string;\n /** Adapter-specific configuration (dsn, host, etc.). */\n options?: Record<string, unknown>;\n\n // ── Extended fields (Plan A: first-level asset support) ──────────────────\n /** Semver range for future catalog versioning, e.g. \"^1.0.0\". */\n version?: string;\n /**\n * Run a health check (ping) when the connector is first connected.\n * Default: false. Set to true to surface connection errors early.\n */\n health_check?: boolean;\n /**\n * Inject this connector's skill description into the agent's system prompt.\n * Default: false.\n */\n expose_as_skill?: boolean;\n /** Tags for catalog browsing and skill routing. */\n tags?: string[];\n\n /**\n * Optional filesystem face — makes the connector \"mountable\".\n * When present, ConnectorManager allocates a mount directory and passes it\n * to the connector via `ConnectContext.mountTarget`.\n *\n * YAML key: `mount` (sub-block under a `connectors:` entry).\n * Replaces the legacy top-level `mounts:` key (hard cut — see Task 11).\n */\n mount?: {\n /** Source URL or path (repo URL, bucket name, host path). */\n source: string;\n /** Override mount target directory (default: `.mounts/<id>/`). */\n target?: string;\n /** Watch flag: omitted → watch read-write, skip read-only. */\n watch?: boolean;\n /** Expert-only: expose the resolved credential to the agent CLI. */\n exposeAccessToken?: boolean;\n /** Optional access-token TTL override (seconds). */\n accessTokenTTL?: number;\n };\n}\n\n// ── MCP Servers ──────────────────────────────────────────────────────────────\n\n/**\n * Reference to a Nix-built asset recipe.\n *\n * The `attr` field selects an attribute path in the platform's flake\n * (`/etc/skaile/flake/`), e.g. `mcps.excel`, `mcps.ppt`, `stacks.baseline`.\n * Resolution happens at session start (cold) and on `reconfigure_mcps`\n * (hot-add) via `nix path-info --offline`.\n *\n * @docLink packages/core/concepts#asset-recipe\n */\nexport interface AssetRecipe {\n /** Flake attribute path, e.g. `mcps.excel`. */\n attr: string;\n}\n\n/**\n * Validates an `AssetRecipe.attr` value against nix attribute path syntax.\n *\n * Nix attribute paths are dot-separated segments. Each segment must start with\n * a letter and contain only letters, digits, underscores, hyphens, and dots.\n * Characters like `#`, spaces, and nix expression fragments are explicitly\n * rejected — even though `spawnSync` array args prevent shell injection, nix\n * parses the combined `flakeRef#attr` string and invalid chars trigger\n * unintended evaluation paths.\n *\n * Deliberate restriction: leading digits per segment are not allowed even\n * though some nix attrs permit them, because they are rare in practice and\n * the restriction makes the validation straightforward to audit.\n *\n * @throws Error when `attr` is invalid\n */\nexport function validateAssetRecipeAttr(attr: string): void {\n if (typeof attr !== \"string\" || attr.length === 0) {\n throw new Error(\"AssetRecipe.attr must be a non-empty string\");\n }\n if (attr.length > 200) {\n throw new Error(`AssetRecipe.attr too long (${attr.length} chars, max 200)`);\n }\n const VALID_ATTR = /^[a-z][a-z0-9._-]*(?:\\.[a-z][a-z0-9._-]*)*$/i;\n if (!VALID_ATTR.test(attr)) {\n throw new Error(\n `AssetRecipe.attr \"${attr}\" contains invalid characters. ` +\n `Allowed: letters, digits, underscore, hyphen, dot. ` +\n `Each dot-segment must start with a letter.`,\n );\n }\n}\n\n/**\n * A declarative external MCP server — spawned or connected at session startup\n * and injected into the Claude SDK driver as a named `mcpServers` entry.\n *\n * Maps directly to the Claude Agent SDK's `McpServerConfig` union:\n * - `transport: \"stdio\"` (default) → `McpStdioServerConfig` — subprocess spawn\n * - `transport: \"sse\"` → `McpSSEServerConfig` — HTTP Server-Sent Events\n * - `transport: \"http\"` → `McpHttpServerConfig` — HTTP streaming\n *\n * The `id` becomes the key in the SDK's `mcpServers` record and also the MCP\n * tool prefix (e.g., `mcp__my-server__<tool-name>`).\n * @docLink packages/core/workspace-config#mcp-server-declaration\n */\nexport interface McpServerDeclaration {\n /** Unique identifier — used as the `mcpServers` record key and tool prefix. */\n id: string;\n /**\n * Transport type.\n * Default: `\"stdio\"` (subprocess).\n */\n transport?: \"stdio\" | \"sse\" | \"http\";\n /** For `\"stdio\"`: the command to execute (e.g. `\"npx\"`, `\"node\"`, `\"python\"`). */\n command?: string;\n /** For `\"stdio\"`: arguments passed to the command. */\n args?: string[];\n /** For `\"stdio\"`: environment variables injected into the subprocess. */\n env?: Record<string, string>;\n /** For `\"sse\"` and `\"http\"`: the server URL. */\n url?: string;\n /** For `\"sse\"` and `\"http\"`: HTTP headers (e.g. `Authorization`). */\n headers?: Record<string, string>;\n /** Short description of what this server provides (used in catalog). */\n description?: string;\n /** Tags for catalog browsing and discovery. */\n tags?: string[];\n /**\n * Optional Nix recipe binding. When present, the runner resolves the\n * recipe's `/nix/store` out-path before subprocess spawn and substitutes\n * `${recipe:<id>}` / `${recipe:<id>:<sub>}` / `${recipe:<id>:bin}` /\n * `${recipe:<id>:lib}` markers in `command`, `args`, and `env` values.\n * `<id>` matches this declaration's `id` field.\n */\n recipe?: AssetRecipe;\n}\n\n// ── Agent Configuration ──────────────────────────────────────────────────────\n\n/**\n * Platform-level context describing the environment the agent operates in.\n * Rendered by the runner into a \"## Platform\" section of the system prompt.\n */\nexport interface AgentContextConfig {\n /** Platform identifier (e.g. \"skaile\"). Controls the rendered header sentence. */\n platform?: string;\n /** Whether multiple users may interact in the same session. */\n multi_user?: boolean;\n /** Session persistence model. */\n session_model?: \"persistent\" | \"ephemeral\";\n}\n\nexport interface AgentConfig {\n /**\n * Agent definition reference. Resolved in order:\n * - Local path: \".skaile/agent\" or \"./my-agent\"\n * - Catalog reference: \"agent:<name>\" (resolved via asset manager catalog)\n * - Resource path: \"ai-assets://<domain>/agents/<name>\"\n */\n definition?: string;\n\n /**\n * Platform-level context (platform identifier, multi-user flag, session model).\n * Consumed by the runner to build the \"## Platform\" section of the system prompt.\n */\n context?: AgentContextConfig;\n\n /** Agent runtime constraints. */\n permissions?: AgentPermissions;\n\n /** Lifecycle hooks — shell commands run at specific points. */\n hooks?: AgentHooks;\n\n /** Named subagent definitions available for delegation. */\n subagents?: Record<string, SubagentConfig>;\n\n /**\n * Control which framework fragments are included in the rendered system prompt.\n * true (default) — include built-in fragment\n * false — omit this fragment\n * string — path to a custom markdown file (relative to project root)\n *\n * Fragment IDs: \"agent-mode\" | \"skill-discovery\" | \"connector-usage\" | \"handoff\"\n */\n fragments?: Record<string, boolean | string>;\n\n /**\n * Additional markdown files appended at the end of every rendered agent system\n * prompt in this workspace. Paths relative to the project root (skaile.yaml).\n *\n * YAML key: `prompt-extensions`\n */\n \"prompt-extensions\"?: string[];\n\n /**\n * Free-form user-authored agent prompt. Plain text or markdown — no length\n * cap, no template substitution. Prepended immediately after the platform\n * context section and before the environment section in the assembled\n * system prompt (see runner's {@link assembleSystemPrompt}).\n *\n * Written by the platform's wake-time yaml serializer from the combined\n * project-level + session-level prompts stored on `SkaileConfigData.agent.prompt`.\n * Standalone CLI / forge sessions may set this directly in `skaile.yaml`.\n *\n * Spec: `docs/superpowers/specs/2026-05-13-platform-agent-prompt-design.md`\n * @since 2026-05\n */\n prompt?: string;\n}\n\nexport interface AgentPermissions {\n /** Maximum agentic turns per query (default: 15). */\n max_turns?: number;\n /**\n * Permission mode for Claude SDK driver.\n * 'auto' = bypassPermissions (default for automated flows).\n * 'interactive' = prompt for each tool use.\n */\n permission_mode?: \"auto\" | \"interactive\";\n /** Glob patterns the agent may NOT write to. Stacking: union across scopes. */\n deny_write?: string[];\n /** Glob patterns the agent may NOT read. Stacking: union across scopes. */\n deny_read?: string[];\n}\n\nexport interface AgentHooks {\n /** Run before a flow starts (after resources are connected). */\n pre_flow?: HookEntry[];\n /** Run after a flow completes (before resources disconnect). */\n post_flow?: HookEntry[];\n /** Run before each flow node executes. */\n pre_node?: HookEntry[];\n /** Run after each flow node completes successfully. */\n post_node?: HookEntry[];\n}\n\nexport interface HookEntry {\n /** Human-readable hook name. */\n name: string;\n /** Shell command to execute. */\n run: string;\n /** Working directory relative to workspace root (default: workspace root). */\n cwd?: string;\n /** Timeout in seconds (default: 60). */\n timeout?: number;\n /** Continue flow if hook fails (default: false). */\n continue_on_error?: boolean;\n}\n\nexport interface SubagentConfig {\n /** What this subagent does. */\n description: string;\n /** System prompt for the subagent. */\n prompt: string;\n /** Tools this subagent may use (default: all). */\n tools?: string[];\n /** Tools this subagent may NOT use. */\n disallowed_tools?: string[];\n /** Model override. */\n model?: string;\n}\n\n// ── Workspace Layout ─────────────────────────────────────────────────────────\n\nexport interface WorkspaceLayoutConfig {\n /** Directories to ensure exist (created at scaffold time, verified at run time). */\n directories?: string[];\n\n /** Git configuration. */\n git?: GitConfig;\n\n /** Post-scaffold setup commands (run once after `skaile init`). */\n setup?: SetupEntry[];\n\n /** Container configuration (Docker). */\n container?: ContainerConfig;\n}\n\nexport interface GitConfig {\n /** Initialize a git repo at scaffold time (default: true). */\n init?: boolean;\n /** .gitignore entries. Stacking: concatenate + deduplicate. */\n ignore?: string[];\n}\n\nexport interface SetupEntry {\n /** Human-readable name. */\n name: string;\n /** Shell command to execute. */\n run: string;\n /** Working directory relative to workspace root. */\n cwd?: string;\n /** Continue if command fails (default: false). */\n continue_on_error?: boolean;\n}\n\nexport interface NixContainerConfig {\n /**\n * Nixpkgs package attribute names to include in the environment.\n * Example: [\"nodejs_22\", \"bun\", \"git\", \"python3\"]\n */\n packages?: string[];\n /**\n * Nixpkgs registry name used as a package prefix for `nix shell`.\n * MUST be a bare registry name like \"nixpkgs\" — not a channel path like\n * \"nixpkgs/nixos-24.11\" (which is not valid as a flake ref prefix).\n * Defaults to \"nixpkgs\".\n */\n channel?: string;\n /**\n * Path to a Nix file (shell.nix / flake.nix) relative to the project root.\n * When set, `packages` and `channel` are ignored — the file is the source of truth.\n */\n flake?: string;\n /**\n * Predefined named stack to resolve from the system stack registry (SKAILE_NIX_STACK_REGISTRY).\n * Overridden by `packages` if present.\n * Takes precedence over the parent `ContainerConfig.stack` field when nix mode is active.\n */\n stack?: string;\n}\n\nexport interface ContainerConfig {\n /** Enable Docker container generation. */\n enabled?: boolean;\n /** Base Docker image. */\n image?: string;\n /** System packages to install. */\n packages?: string[];\n /** Agent CLIs to install globally in the container. */\n agent_clis?: string[];\n /** Ports to expose. */\n ports?: string[];\n /** Environment variables to pass through. */\n env?: string[];\n /** Docker volume/bind mounts. */\n mounts?: Array<{ type: \"bind\" | \"volume\"; source: string; target: string }>;\n /** WebSocket port for IPC. */\n ws_port?: number;\n /**\n * Named system stack.\n * - Docker mode: resolved to an image tag via `dockerImageMap` (SKAILE_DOCKER_IMAGE_MAP).\n * - Nix mode: resolved to a package list via `nixStackRegistry` (SKAILE_NIX_STACK_REGISTRY).\n * Overridden by `nix.stack` if both are present.\n */\n stack?: string;\n /** Nix-specific environment configuration (nix session mode only). */\n nix?: NixContainerConfig;\n}\n\n// ── Top-level config ──────────────────────────────────────────────────────────\n\nexport interface SkWorkspaceConfig {\n /** Project name (defaults to directory basename). */\n name?: string;\n /** Project description. */\n description?: string;\n\n /**\n * Agent configuration profiles. The \"default\" profile provides runtime\n * defaults (framework, model, provider). Personal overrides live in\n * .skaile/settings.json and always take priority.\n *\n * YAML key: `agent-config` or `agent_config`\n */\n agent_config?: Record<string, AgentConfigProfile>;\n\n /**\n * Startup directives — executed when the workspace is launched.\n * Each item is either a string (\"agent:name\") or a map\n * ({ \"system-prompt-override\": \"...\" }).\n */\n startup?: StartupDirective[];\n\n /**\n * Internal-only — always `{}` on the merged config. Kept on the shape so\n * `repo-manager`, `lock`, and `runtime-assets` keep type-checking; their\n * `Record<string, RepositoryDeclaration>` arguments are built from\n * `ai_resources[]` entries inside the install pipeline.\n */\n repositories?: Record<string, RepositoryDeclaration>;\n\n /**\n * Asset dependencies using kind:name[@repo][#pin] syntax (new format).\n * Top-level flat list — repos and deps are separate concerns.\n *\n * YAML key: `dependencies`\n */\n dependencies?: string[];\n\n /**\n * Github sources this project depends on. Each entry names a clone under\n * `~/.skaile/sources/<name>/` (machine-global cache). `skaile init` and\n * `skaile install` clone any missing entries; `skaile source add/remove/sync`\n * are the CRUD surface.\n *\n * YAML key: `sources`\n */\n sources?: SourceEntry[];\n\n /**\n * Local patches applied during install (new format).\n * Maps \"kind:name\" → patch file path relative to project root.\n *\n * YAML key: `patches`\n */\n patches?: Record<string, string>;\n\n /**\n * AI resource sources, each with its own dependency list.\n * @deprecated Use `repositories` + `dependencies` instead.\n */\n ai_resources?: AiResourceEntry[];\n\n /**\n * @deprecated The top-level `mounts:` key is no longer supported as of Task 11.\n *\n * Move filesystem-projected storage backends under `connectors:` with a\n * `mount:` sub-block. See `docs/migration-mounts-to-connectors.md`.\n *\n * This field is kept on the type **only** so `config.ts` can detect a\n * present `mounts:` block and throw a migration error. It is never merged,\n * applied, or forwarded to any manager. `normalizeConfig` still populates it\n * when `mounts:` is present in the YAML so the detection check works.\n *\n * YAML key: `mounts` (rejected at runtime — do not use)\n */\n mounts?: MountDeclaration[];\n\n /**\n * Data connectors — tool-accessed backends.\n *\n * Each declaration's `driver` field is an *implicit* catalog ref\n * (`connector:<driver>`). The runtime resolves it through\n * `resolveRuntimeAssets()`, which scans every declared `repositories` entry\n * plus the implicit `@skaile/base-assets` repo for matching `CONNECTOR.md`\n * manifests. Drivers that do not match any catalog entry produce a\n * `missing_driver` warning at session startup.\n *\n * YAML key: `connectors`\n */\n connectors?: ConnectorDeclaration[];\n\n /**\n * External MCP servers — injected into the Claude SDK driver at session startup.\n * Supports stdio subprocess, SSE, and HTTP transports.\n *\n * YAML key: `mcp_servers`\n */\n mcp_servers?: McpServerDeclaration[];\n\n /** Agent behavior — definition reference, permissions, hooks, subagents. */\n agent?: AgentConfig;\n\n /** Workspace layout — directories, git, setup scripts, container. */\n workspace?: WorkspaceLayoutConfig;\n\n /**\n * Secret provisioning configuration.\n * Controls how connector credentials are resolved at runtime.\n *\n * YAML key: `secrets`\n */\n secrets?: SecretsConfig;\n\n /**\n * Telemetry configuration — passed through raw to the telemetry package.\n * Parsed by `resolveTelemetryConfig` in `@skaile/workspaces/telemetry`.\n *\n * YAML key: `telemetry`\n */\n telemetry?: Record<string, unknown>;\n\n /**\n * Session compaction settings -- controls when and how conversation\n * snapshots are created.\n *\n * YAML key: `compaction`\n */\n compaction?: CompactionConfig;\n\n /**\n * Plugin specs to load into pluginRegistry — npm specifiers like\n * \"@skaile/provider-fly@^0.1.0\". Opt-in; no auto-discovery. YAML key: `plugins`.\n */\n plugins?: string[];\n /** Deploy target selection. YAML key: `deploy`. */\n deploy?: DeployBlock;\n}\n\n/** Deploy target selection for `skaile deploy`. YAML key: `deploy`. Resolved through pluginRegistry at deploy time. */\nexport interface DeployBlock {\n /** Deploy target id (e.g. \"local\", \"docker\", \"fly\") — resolved against pluginRegistry at deploy time, not validated here. */\n target: string;\n /** Target-specific config; validated by the target's configSchema at resolve time. */\n config?: unknown;\n}\n\nexport interface SecretsConfig {\n /**\n * How secrets are provided to the container.\n * \"env\" — read from process.env (default, for CLI/standalone)\n * \"provisioned\" — wait for secrets over transport bridge (platform containers)\n */\n provider?: \"env\" | \"provisioned\";\n /** Timeout in ms for waiting for provisioned secrets (default: 30000). */\n timeoutMs?: number;\n}\n\n// ── Compaction config ────────────────────────────────────────────────────────\n\nexport interface CompactionConfig {\n /** Enable managed compaction (default: true). */\n enabled?: boolean;\n /** Context fill percentage that triggers compaction (default: 80). */\n thresholdPercent?: number;\n /** Compact before hibernation for cheap restores (default: true). */\n compactOnHibernate?: boolean;\n /** Minimum ms between compactions to prevent thrashing (default: 120000). */\n minCooldownMs?: number;\n /** Enable manual compact command in expert mode (default: false). */\n manualCompactEnabled?: boolean;\n}\n\nexport const COMPACTION_DEFAULTS: Required<CompactionConfig> = {\n enabled: true,\n thresholdPercent: 80,\n compactOnHibernate: true,\n minCooldownMs: 120_000,\n manualCompactEnabled: false,\n};\n\n// ── Deprecated type aliases ───────────────────────────────────────────────────\n\n/** @deprecated Use AgentConfigProfile */\nexport interface RuntimeDefaults {\n framework?: string;\n driver?: string;\n provider?: string;\n model?: string;\n skills_dir?: string;\n agents_dir?: string;\n prompts_dir?: string;\n}\n\n/** @deprecated Use AiResourceEntry[] */\nexport interface AiResourcesConfig {\n sources?: AiResourceSource[];\n requires?: string[];\n auto_deploy?: boolean;\n}\n\n/** @deprecated Use AiResourceEntry */\nexport interface AiResourceSource {\n name: string;\n path: string;\n branch?: string;\n}\n\n// ── Config file info ──────────────────────────────────────────────────────────\n\nexport interface SkWorkspaceConfigFile {\n /** Absolute path to the config file. */\n path: string;\n /** Workspace name (extracted from filename). */\n name: string;\n /** Parsed config. */\n config: SkWorkspaceConfig;\n /**\n * Diagnostics from decoding this file — legacy-shape warnings (camelCase keys,\n * flat agent-config, the old ai_resources object) and unrecognized\n * driver/provider/access values. Absent on configs synthesized in-memory.\n */\n diagnostics?: Diagnostic[];\n}\n\n// ── Constants ─────────────────────────────────────────────────────────────────\n\n/** Suffix for named workspace configs: `<name>.skaile.yaml` */\nexport const SKAILE_YAML_SUFFIX = \".skaile.yaml\";\n/** Filename for the default workspace config when no name is given. */\nexport const SKAILE_YAML_DEFAULT = \"skaile.yaml\";\n\n/** @deprecated Use SKAILE_YAML_SUFFIX */\nexport const SK_WORKSPACE_SUFFIX = SKAILE_YAML_SUFFIX;\n/** @deprecated Use SKAILE_YAML_DEFAULT */\nexport const SK_WORKSPACE_DEFAULT_NAME = \"default\";\n\n// ── Config I/O ────────────────────────────────────────────────────────────────\n\n/**\n * Return the canonical filename for a workspace config.\n * The default workspace resolves to `\"skaile.yaml\"`; named workspaces resolve to\n * `\"<name>.skaile.yaml\"`.\n *\n * @param name - Optional workspace name (omit or pass `\"default\"` for the primary config)\n * @returns Filename string (not a full path)\n * @docLink packages/core/workspace-config#workspace-config-filename\n */\nexport function workspaceConfigFilename(name?: string): string {\n if (!name || name === \"default\") return SKAILE_YAML_DEFAULT;\n return `${name}${SKAILE_YAML_SUFFIX}`;\n}\n\n/**\n * Return `true` if `filename` matches the workspace config naming convention\n * (`\"skaile.yaml\"` or any `\"*.skaile.yaml\"`).\n *\n * @param filename - Bare filename (no directory component)\n * @docLink packages/core/workspace-config#is-workspace-config-filename\n */\nexport function isWorkspaceConfigFilename(filename: string): boolean {\n return filename === SKAILE_YAML_DEFAULT || filename.endsWith(SKAILE_YAML_SUFFIX);\n}\n\n/**\n * Extract the workspace name from a config filename.\n * `\"skaile.yaml\"` → `\"default\"`, `\"staging.skaile.yaml\"` → `\"staging\"`.\n *\n * @param filename - Bare filename produced by `workspaceConfigFilename`\n * @returns Workspace name string\n * @docLink packages/core/workspace-config#workspace-name-from-filename\n */\nexport function workspaceNameFromFilename(filename: string): string {\n if (filename === SKAILE_YAML_DEFAULT) return \"default\";\n return filename.slice(0, -SKAILE_YAML_SUFFIX.length);\n}\n\n/**\n * Load a single workspace config file from `dir`.\n * When `name` is omitted and no `skaile.yaml` exists, falls back to the sole\n * `*.skaile.yaml` file in the directory if exactly one is present.\n *\n * @param dir - Directory to search for the config file\n * @param name - Optional workspace name (omit for the default `skaile.yaml`)\n * @returns Parsed config file info, or `null` if no matching file was found\n * @docLink packages/core/workspace-config#load-sk-workspace-config\n */\nexport function loadSkWorkspaceConfig(dir: string, name?: string): SkWorkspaceConfigFile | null {\n const resolvedDir = resolve(dir);\n const canonicalName = name && name !== \"default\" ? name : undefined;\n\n const filename = workspaceConfigFilename(canonicalName);\n const filePath = join(resolvedDir, filename);\n if (existsSync(filePath)) {\n return parseConfigFile(filePath, canonicalName ?? \"default\");\n }\n\n if (!canonicalName) {\n const found = listSkWorkspaceConfigs(resolvedDir);\n if (found.length === 1) return found[0]!;\n }\n\n return null;\n}\n\n/**\n * Serialize and write a workspace config to `dir`, creating the directory if needed.\n *\n * @param dir - Target directory (created recursively if absent)\n * @param config - Config object to serialize as YAML\n * @param name - Optional workspace name (omit for the default `skaile.yaml`)\n * @returns Absolute path of the written file\n * @docLink packages/core/workspace-config#save-sk-workspace-config\n */\nexport function saveSkWorkspaceConfig(\n dir: string,\n config: SkWorkspaceConfig,\n name?: string,\n): string {\n const resolvedDir = resolve(dir);\n const filename = workspaceConfigFilename(name);\n const filePath = join(resolvedDir, filename);\n\n if (!existsSync(resolvedDir)) {\n mkdirSync(resolvedDir, { recursive: true });\n }\n\n writeFileSync(filePath, encodeSkaileYaml(config));\n return filePath;\n}\n\n/**\n * List all workspace config files present in `dir`, sorted alphabetically by name.\n * Returns an empty array when `dir` does not exist or is unreadable.\n *\n * @param dir - Directory to scan for `skaile.yaml` and `*.skaile.yaml` files\n * @returns Array of parsed config file descriptors\n * @docLink packages/core/workspace-config#list-sk-workspace-configs\n */\nexport function listSkWorkspaceConfigs(dir: string): SkWorkspaceConfigFile[] {\n const resolvedDir = resolve(dir);\n if (!existsSync(resolvedDir)) return [];\n\n const configs: SkWorkspaceConfigFile[] = [];\n try {\n for (const entry of readdirSync(resolvedDir)) {\n if (isWorkspaceConfigFilename(entry)) {\n const wsName = workspaceNameFromFilename(entry);\n const parsed = parseConfigFile(join(resolvedDir, entry), wsName);\n if (parsed) configs.push(parsed);\n }\n }\n } catch {\n /* unreadable dir */\n }\n\n return configs.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Resolve the effective workspace config by stacking configs across three scope levels:\n * user (`~/.skaile/`) < app (`opts.appDir`) < project (`projectDir`).\n *\n * Each level's config is merged with `mergeSkWorkspaceConfigs`, with higher-priority\n * scopes winning for scalars and unions applied for arrays (deny lists, directories, etc.).\n * Returns an empty object `{}` when no config files are found.\n *\n * @param projectDir - Root directory of the current project\n * @param opts - Optional overrides: `name` selects a named workspace (default: `\"default\"`),\n * `appDir` inserts an app-level config between user and project scopes\n * @returns Merged effective `SkWorkspaceConfig`\n * @docLink packages/core/workspace-config#resolve-sk-workspace-config\n */\nexport function resolveSkWorkspaceConfig(\n projectDir: string,\n opts?: { name?: string; appDir?: string },\n): SkWorkspaceConfig {\n const name = opts?.name ?? SK_WORKSPACE_DEFAULT_NAME;\n const configs: SkWorkspaceConfig[] = [];\n\n const userConfig = loadSkWorkspaceConfig(join(homedir(), \".skaile\"), name);\n if (userConfig) configs.push(userConfig.config);\n\n if (opts?.appDir) {\n const appConfig = loadSkWorkspaceConfig(opts.appDir, name);\n if (appConfig) configs.push(appConfig.config);\n }\n\n const projectConfig = loadSkWorkspaceConfig(projectDir, name);\n if (projectConfig) configs.push(projectConfig.config);\n\n if (configs.length > 0) return configs.reduce(mergeSkWorkspaceConfigs);\n\n return {};\n}\n\n/**\n * Walk upward from `startDir` looking for a `skaile.yaml` (or `*.skaile.yaml`).\n * Returns the directory containing the first match, or `undefined` if none found.\n *\n * Stops after 20 levels to avoid scanning all the way to `/`.\n *\n * @param startDir - Directory to start searching from (usually `process.cwd()`)\n * @returns Absolute path to the workspace root, or `undefined`\n * @docLink packages/core/workspace-config#find-workspace-root\n */\nexport function findWorkspaceRoot(startDir: string): string | undefined {\n let dir = resolve(startDir);\n const root = parsePath(dir).root; // filesystem root (e.g. \"/\" or \"C:\\\\\")\n let depth = 0;\n\n while (depth < 20) {\n if (existsSync(join(dir, SKAILE_YAML_DEFAULT))) return dir;\n // Check for named workspace configs (*.skaile.yaml)\n try {\n for (const entry of readdirSync(dir)) {\n if (entry.endsWith(SKAILE_YAML_SUFFIX)) return dir;\n }\n } catch {\n /* unreadable */\n }\n\n if (dir === root) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n depth++;\n }\n return undefined;\n}\n\n// ── Merge logic ───────────────────────────────────────────────────────────────\n\n/**\n * Deep-merge two workspace configs according to stacking rules.\n * `overlay` takes priority over `base` for scalar fields.\n * Arrays use concatenation + deduplication; deny lists always union.\n * Mounts and connectors are merged by `id` (overlay entry wins for same id).\n * Hooks are concatenated in order (base first, overlay appended).\n *\n * @param base - Lower-priority config (e.g. user or app scope)\n * @param overlay - Higher-priority config (e.g. project scope)\n * @returns Merged `SkWorkspaceConfig`\n * @docLink packages/core/workspace-config#merge-sk-workspace-configs\n */\nexport function mergeSkWorkspaceConfigs(\n base: SkWorkspaceConfig,\n overlay: SkWorkspaceConfig,\n): SkWorkspaceConfig {\n return {\n name: overlay.name ?? base.name,\n description: overlay.description ?? base.description,\n\n // agent_config: per-profile key, overlay profile wins\n agent_config: {\n ...(base.agent_config ?? {}),\n ...(overlay.agent_config ?? {}),\n },\n\n // startup: overlay wins (project-level only)\n startup: overlay.startup ?? base.startup,\n\n // ai_resources: dedupe by source name — overlay entry wins for same name\n ai_resources: dedupeByKey(\n [...(base.ai_resources ?? []), ...(overlay.ai_resources ?? [])],\n \"name\",\n ),\n\n // mounts: by id — overlay wins\n mounts: mergeById(base.mounts ?? [], overlay.mounts ?? []),\n\n // connectors: by id — overlay wins\n connectors: mergeById(base.connectors ?? [], overlay.connectors ?? []),\n\n // mcp_servers: by id — overlay wins\n mcp_servers: mergeById(base.mcp_servers ?? [], overlay.mcp_servers ?? []),\n\n agent: {\n definition: overlay.agent?.definition ?? base.agent?.definition,\n context: overlay.agent?.context ?? base.agent?.context,\n permissions: {\n ...base.agent?.permissions,\n ...stripUndefined(overlay.agent?.permissions),\n deny_write: dedupe([\n ...(base.agent?.permissions?.deny_write ?? []),\n ...(overlay.agent?.permissions?.deny_write ?? []),\n ]),\n deny_read: dedupe([\n ...(base.agent?.permissions?.deny_read ?? []),\n ...(overlay.agent?.permissions?.deny_read ?? []),\n ]),\n },\n subagents: {\n ...(base.agent?.subagents ?? {}),\n ...(overlay.agent?.subagents ?? {}),\n },\n hooks: {\n pre_flow: [\n ...(base.agent?.hooks?.pre_flow ?? []),\n ...(overlay.agent?.hooks?.pre_flow ?? []),\n ],\n post_flow: [\n ...(base.agent?.hooks?.post_flow ?? []),\n ...(overlay.agent?.hooks?.post_flow ?? []),\n ],\n pre_node: [\n ...(base.agent?.hooks?.pre_node ?? []),\n ...(overlay.agent?.hooks?.pre_node ?? []),\n ],\n post_node: [\n ...(base.agent?.hooks?.post_node ?? []),\n ...(overlay.agent?.hooks?.post_node ?? []),\n ],\n },\n },\n\n workspace: {\n directories: dedupe([\n ...(base.workspace?.directories ?? []),\n ...(overlay.workspace?.directories ?? []),\n ]),\n git: {\n init: overlay.workspace?.git?.init ?? base.workspace?.git?.init,\n ignore: dedupe([\n ...(base.workspace?.git?.ignore ?? []),\n ...(overlay.workspace?.git?.ignore ?? []),\n ]),\n },\n setup: overlay.workspace?.setup ?? base.workspace?.setup,\n container: overlay.workspace?.container ?? base.workspace?.container,\n },\n\n // secrets: overlay wins entirely\n secrets: overlay.secrets ?? base.secrets,\n\n // telemetry: overlay wins entirely (raw pass-through)\n telemetry: overlay.telemetry ?? base.telemetry,\n\n // repositories: always empty in merged output; the schema no longer\n // accepts this key. The internal install pipeline builds its own map\n // from `ai_resources[]` entries.\n repositories: {},\n\n // dependencies: concatenate and dedupe\n dependencies: dedupe([...(base.dependencies ?? []), ...(overlay.dependencies ?? [])]),\n\n // sources: dedupe by name — overlay entry wins for the same name\n sources: dedupeByKey([...(base.sources ?? []), ...(overlay.sources ?? [])], \"name\"),\n\n // plugins: concatenate + dedupe (like dependencies)\n plugins: dedupe([...(base.plugins ?? []), ...(overlay.plugins ?? [])]),\n\n // deploy: overlay wins entirely (scalar-like selection)\n deploy: overlay.deploy ?? base.deploy,\n };\n}\n\n// ── Diagnostics ───────────────────────────────────────────────────────────────\n\n/** Severity of a {@link Diagnostic} produced by {@link decodeSkaileYaml}. */\nexport type DiagnosticSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A structured note about a decoded `skaile.yaml` — a syntax error, a tolerated\n * legacy/non-canonical shape that was normalized, or an unrecognized enum value.\n * {@link decodeSkaileYaml} never throws; it reports problems here so each caller\n * (platform editor, runner, CLI) decides how loud to be.\n */\nexport interface Diagnostic {\n /** Stable machine code, e.g. `\"legacy_key_camelcase\"` / `\"unknown_driver\"`. */\n code: string;\n severity: DiagnosticSeverity;\n /** Human-readable, actionable message. */\n message: string;\n /** Dotted path into the config the note refers to, when applicable. */\n path?: string;\n}\n\n/** Result of {@link decodeSkaileYaml}: the normalized config plus any notes. */\nexport interface DecodeResult {\n config: SkWorkspaceConfig;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Known runtime drivers — mirrors the keys of `DRIVER_DEFAULTS` (framework.ts).\n * Kept local to avoid a settings/framework ↔ workspace-config import cycle; a\n * drift test asserts parity.\n */\nconst KNOWN_DRIVERS = [\"omp\", \"claude-sdk\", \"codex\"] as const;\n\n/**\n * Known LLM/voice providers — mirrors `ALL_PROVIDERS` (settings.ts). Local for\n * the same cycle reason; a drift test asserts parity.\n */\nconst KNOWN_PROVIDERS = [\n \"anthropic\",\n \"openai\",\n \"google\",\n \"mistral\",\n \"groq\",\n \"openrouter\",\n \"deepseek\",\n \"xai\",\n \"together\",\n \"fireworks\",\n \"deepgram\",\n \"elevenlabs\",\n] as const;\n\nconst KNOWN_ACCESS = [\"read-only\", \"read-write\"] as const;\n\n// ── Raw → canonical normalization ─────────────────────────────────────────────\n\n/** Scalar fields that identify a flat (un-profiled) agent-config block. */\nconst AGENT_PROFILE_FIELDS = [\n \"driver\",\n \"provider\",\n \"model\",\n \"thinking\",\n \"effort\",\n \"skills_dir\",\n \"agents_dir\",\n \"prompts_dir\",\n] as const;\n\n/**\n * Coerce a raw agent-config block into the canonical profile-map shape\n * (`{ default: {...}, … }`).\n *\n * Accepts two authoring shapes:\n * - **Profile map** (canonical): `{ default: { driver, model }, staging: {…} }`\n * - **Flat profile**: `{ driver, model, provider }` — emitted by clients that\n * serialize a runtime config object straight to YAML. Wrapped as the\n * `default` profile so `settingsFromWorkspaceConfig` finds it.\n *\n * `wrappedFlat` reports whether a flat block was wrapped, so the caller can emit\n * a diagnostic. A block is flat when any known profile field is present as a\n * scalar; a profile named e.g. `driver` carries an object value, so the scalar\n * check disambiguates.\n */\nfunction normalizeAgentConfig(raw: Record<string, unknown>): {\n profiles: Record<string, AgentConfigProfile>;\n wrappedFlat: boolean;\n} {\n const looksFlat = AGENT_PROFILE_FIELDS.some((f) => typeof raw[f] === \"string\");\n return looksFlat\n ? { profiles: { default: raw as AgentConfigProfile }, wrappedFlat: true }\n : { profiles: raw as Record<string, AgentConfigProfile>, wrappedFlat: false };\n}\n\n/**\n * Normalize a raw parsed YAML object into the canonical SkWorkspaceConfig shape.\n * Pure structural pass; see {@link decodeSkaileYaml} for the diagnostics-aware\n * entry point. Tolerates backward-compatible fields:\n * - `agent-config` (hyphen) / `agent_config` (underscore) / `agentConfig` (camelCase) → `agent_config`\n * - flat agent-config (`{ driver, model }`) → `{ default: { driver, model } }`\n * - `aiResources` (camelCase) → `ai_resources`\n * - `ai_resources` as object (old {sources, requires}) → AiResourceEntry[]\n * @docLink packages/core/workspace-config#normalize-config\n */\nexport function normalizeConfig(raw: Record<string, unknown>): SkWorkspaceConfig {\n return normalizeConfigInternal(raw).config;\n}\n\n/** Diagnostics-collecting core of {@link normalizeConfig}. */\nfunction normalizeConfigInternal(raw: Record<string, unknown>): DecodeResult {\n const config: SkWorkspaceConfig = {};\n const diagnostics: Diagnostic[] = [];\n\n if (raw.name) config.name = String(raw.name);\n if (raw.description) config.description = String(raw.description);\n\n // agent_config: accept hyphen (canonical), underscore, or camelCase, plus a\n // flat single-profile block. Non-canonical shapes are normalized + flagged.\n let agentConfigRaw: unknown;\n let agentConfigKey: string | undefined;\n if (raw[\"agent-config\"] !== undefined) {\n agentConfigRaw = raw[\"agent-config\"];\n agentConfigKey = \"agent-config\";\n } else if (raw.agent_config !== undefined) {\n agentConfigRaw = raw.agent_config;\n agentConfigKey = \"agent_config\";\n } else if (raw.agentConfig !== undefined) {\n agentConfigRaw = raw.agentConfig;\n agentConfigKey = \"agentConfig\";\n }\n if (agentConfigRaw && typeof agentConfigRaw === \"object\" && !Array.isArray(agentConfigRaw)) {\n if (agentConfigKey === \"agentConfig\") {\n diagnostics.push({\n code: \"legacy_key_camelcase\",\n severity: \"warning\",\n message: 'Non-canonical key \"agentConfig\" — use \"agent-config\".',\n path: \"agentConfig\",\n });\n }\n const { profiles, wrappedFlat } = normalizeAgentConfig(\n agentConfigRaw as Record<string, unknown>,\n );\n if (wrappedFlat) {\n diagnostics.push({\n code: \"legacy_agent_config_flat\",\n severity: \"warning\",\n message:\n 'Flat agent-config block wrapped as the \"default\" profile — nest fields under \"default:\".',\n path: agentConfigKey,\n });\n }\n config.agent_config = profiles;\n }\n\n if (Array.isArray(raw.startup)) {\n config.startup = raw.startup as StartupDirective[];\n }\n\n // ai_resources: array (canonical) or old {sources, requires} object; accept\n // the camelCase `aiResources` alias.\n let aiResRaw: unknown;\n let aiResKey: string | undefined;\n if (raw.ai_resources !== undefined) {\n aiResRaw = raw.ai_resources;\n aiResKey = \"ai_resources\";\n } else if (raw.aiResources !== undefined) {\n aiResRaw = raw.aiResources;\n aiResKey = \"aiResources\";\n }\n if (aiResKey === \"aiResources\") {\n diagnostics.push({\n code: \"legacy_key_camelcase\",\n severity: \"warning\",\n message: 'Non-canonical key \"aiResources\" — use \"ai_resources\".',\n path: \"aiResources\",\n });\n }\n if (Array.isArray(aiResRaw)) {\n config.ai_resources = aiResRaw as AiResourceEntry[];\n } else if (aiResRaw && typeof aiResRaw === \"object\") {\n diagnostics.push({\n code: \"legacy_ai_resources_object\",\n severity: \"warning\",\n message:\n \"Legacy ai_resources object form ({sources, requires}) — use an array of {name, path, dependencies}.\",\n path: aiResKey,\n });\n const old = aiResRaw as Record<string, unknown>;\n const sources = Array.isArray(old.sources) ? (old.sources as Record<string, unknown>[]) : [];\n const requires = Array.isArray(old.requires) ? (old.requires as string[]).filter(Boolean) : [];\n const autoDeploy = Boolean(old.auto_deploy ?? false);\n\n config.ai_resources = sources.map((s, i) => {\n const entry: AiResourceEntry = {\n name: String(s.name ?? \"\"),\n path: String(s.path ?? s.url ?? \"\"),\n };\n if (s.branch) entry.branch = String(s.branch);\n if (autoDeploy) entry.auto_deploy = true;\n // Attach global requires to first source\n if (i === 0 && requires.length > 0) entry.dependencies = requires;\n return entry;\n });\n }\n\n // Structural validation deferred — these sections are accepted as raw\n // arrays/objects and cast; the runtime tolerates unexpected shapes.\n if (Array.isArray(raw.mounts)) {\n config.mounts = raw.mounts as MountDeclaration[];\n }\n // connectors: no data_resources fallback — clean break\n if (Array.isArray(raw.connectors)) {\n config.connectors = raw.connectors as ConnectorDeclaration[];\n }\n if (Array.isArray(raw.mcp_servers)) {\n config.mcp_servers = raw.mcp_servers as McpServerDeclaration[];\n }\n if (Array.isArray(raw.plugins)) {\n const specs = raw.plugins.filter((p): p is string => typeof p === \"string\" && p.length > 0);\n if (specs.length > 0) config.plugins = specs;\n }\n // deploy: structural only — the target id is resolved/validated against\n // pluginRegistry at deploy time, not here. A block missing a string target is\n // dropped silently (mirrors connectors' tolerant cast).\n if (raw.deploy && typeof raw.deploy === \"object\" && !Array.isArray(raw.deploy)) {\n const d = raw.deploy as Record<string, unknown>;\n if (typeof d.target === \"string\" && d.target.length > 0) {\n config.deploy = { target: d.target };\n if (d.config !== undefined) config.deploy.config = d.config;\n }\n }\n if (raw.agent) config.agent = raw.agent as AgentConfig;\n if (raw.workspace) config.workspace = raw.workspace as WorkspaceLayoutConfig;\n if (raw.secrets && typeof raw.secrets === \"object\") {\n config.secrets = raw.secrets as SecretsConfig;\n }\n if (raw.compaction && typeof raw.compaction === \"object\" && !Array.isArray(raw.compaction)) {\n config.compaction = raw.compaction as CompactionConfig;\n }\n if (raw.patches && typeof raw.patches === \"object\" && !Array.isArray(raw.patches)) {\n config.patches = raw.patches as Record<string, string>;\n }\n\n if (Array.isArray(raw.dependencies)) {\n config.dependencies = raw.dependencies.filter((d): d is string => typeof d === \"string\");\n }\n\n if (Array.isArray(raw.sources)) {\n const entries: SourceEntry[] = [];\n for (const item of raw.sources) {\n if (!item || typeof item !== \"object\") continue;\n const s = item as Record<string, unknown>;\n const name = typeof s.name === \"string\" ? s.name : \"\";\n const url = typeof s.url === \"string\" ? s.url : \"\";\n if (!name || !url) continue;\n const entry: SourceEntry = { name, url };\n if (typeof s.branch === \"string\" && s.branch.length > 0) entry.branch = s.branch;\n entries.push(entry);\n }\n if (entries.length > 0) config.sources = entries;\n }\n\n // telemetry: pass through raw — parsed by @skaile/workspaces/telemetry\n if (raw.telemetry && typeof raw.telemetry === \"object\" && !Array.isArray(raw.telemetry)) {\n config.telemetry = raw.telemetry as Record<string, unknown>;\n }\n\n return { config, diagnostics };\n}\n\n// ── Codec (decode / encode) ────────────────────────────────────────────────────\n\n/**\n * Decode `skaile.yaml` text into a normalized {@link SkWorkspaceConfig} plus\n * {@link Diagnostic}s. Total — never throws: a YAML syntax error or a non-object\n * root is reported as an `error`-severity diagnostic with an empty config.\n * Legacy/non-canonical shapes (camelCase keys, flat agent-config, the old\n * ai_resources object) are normalized and reported as `warning`s; unrecognized\n * driver/provider/access values are reported as `warning`s too.\n *\n * Pair with {@link encodeSkaileYaml} for round-tripping. The round-trip is\n * canonical-lossless on the typed model (`decode(encode(config)).config` deep-\n * equals `config`) but does not preserve comments or key order — use\n * `WorkspaceYamlEditor` for comment-preserving in-place edits.\n * @docLink packages/core/workspace-config#decode-skaile-yaml\n */\nexport function decodeSkaileYaml(text: string): DecodeResult {\n let parsed: unknown;\n try {\n parsed = parse(text) ?? {};\n } catch (err) {\n return {\n config: {},\n diagnostics: [\n {\n code: \"yaml_syntax\",\n severity: \"error\",\n message: `Invalid YAML: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n };\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return {\n config: {},\n diagnostics: [\n {\n code: \"non_object_root\",\n severity: \"error\",\n message: \"skaile.yaml must be a mapping at the top level.\",\n },\n ],\n };\n }\n const result = normalizeConfigInternal(parsed as Record<string, unknown>);\n validateConfigValues(result.config, result.diagnostics);\n return result;\n}\n\n/**\n * Encode a {@link SkWorkspaceConfig} to canonical `skaile.yaml` text:\n * deterministic key order, the hyphenated `agent-config` key, only defined\n * fields. This is the single sanctioned writer — clients should build a typed\n * config and encode it here rather than hand-serializing YAML.\n * @docLink packages/core/workspace-config#encode-skaile-yaml\n */\nexport function encodeSkaileYaml(config: SkWorkspaceConfig): string {\n return stringify(toCanonicalObject(config), { lineWidth: 120 });\n}\n\n/** Append `warning` diagnostics for unrecognized driver/provider/access values. */\nfunction validateConfigValues(config: SkWorkspaceConfig, diagnostics: Diagnostic[]): void {\n for (const [profile, p] of Object.entries(config.agent_config ?? {})) {\n if (p?.driver && !(KNOWN_DRIVERS as readonly string[]).includes(p.driver)) {\n diagnostics.push({\n code: \"unknown_driver\",\n severity: \"warning\",\n message: `Unknown driver \"${p.driver}\" — expected one of: ${KNOWN_DRIVERS.join(\", \")}.`,\n path: `agent-config.${profile}.driver`,\n });\n }\n if (p?.provider && !(KNOWN_PROVIDERS as readonly string[]).includes(p.provider)) {\n diagnostics.push({\n code: \"unknown_provider\",\n severity: \"warning\",\n message: `Unknown provider \"${p.provider}\" — expected one of: ${KNOWN_PROVIDERS.join(\", \")}.`,\n path: `agent-config.${profile}.provider`,\n });\n }\n }\n const checkAccess = (access: string | undefined, path: string) => {\n if (access && !(KNOWN_ACCESS as readonly string[]).includes(access)) {\n diagnostics.push({\n code: \"unknown_access\",\n severity: \"warning\",\n message: `Unknown access \"${access}\" — expected \"read-only\" or \"read-write\".`,\n path,\n });\n }\n };\n for (const c of config.connectors ?? []) checkAccess(c.access, `connectors.${c.id}.access`);\n for (const m of config.mounts ?? []) checkAccess(m.access, `mounts.${m.id}.access`);\n}\n\n/**\n * Canonical key order for encode. `agent_config` is emitted under the hyphenated\n * `agent-config` key (see {@link CONFIG_KEY_TO_YAML}); any field not listed here\n * is appended afterward so forward-compat keys survive a round-trip.\n */\nconst CANONICAL_KEY_ORDER: (keyof SkWorkspaceConfig)[] = [\n \"name\",\n \"description\",\n \"agent_config\",\n \"dependencies\",\n \"plugins\",\n \"sources\",\n \"startup\",\n \"ai_resources\",\n \"connectors\",\n \"mcp_servers\",\n \"deploy\",\n \"mounts\",\n \"agent\",\n \"workspace\",\n \"secrets\",\n \"telemetry\",\n \"compaction\",\n \"patches\",\n \"repositories\",\n];\n\n/** Internal field name → canonical YAML key, where they differ. */\nconst CONFIG_KEY_TO_YAML: Partial<Record<keyof SkWorkspaceConfig, string>> = {\n agent_config: \"agent-config\",\n};\n\nfunction toCanonicalObject(config: SkWorkspaceConfig): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const emit = (key: keyof SkWorkspaceConfig) => {\n const value = config[key];\n if (value === undefined) return;\n out[CONFIG_KEY_TO_YAML[key] ?? key] = value;\n };\n for (const key of CANONICAL_KEY_ORDER) emit(key);\n // Preserve any field not in the canonical order (forward-compat).\n for (const key of Object.keys(config) as (keyof SkWorkspaceConfig)[]) {\n if (CANONICAL_KEY_ORDER.includes(key)) continue;\n emit(key);\n }\n return out;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\nfunction parseConfigFile(filePath: string, name: string): SkWorkspaceConfigFile | null {\n let raw: string;\n try {\n raw = readFileSync(filePath, \"utf-8\");\n } catch {\n return null;\n }\n const { config, diagnostics } = decodeSkaileYaml(raw);\n // Preserve the legacy contract: an unparseable file reads as \"no config\".\n if (diagnostics.some((d) => d.code === \"yaml_syntax\")) return null;\n return { path: filePath, name, config, diagnostics };\n}\n\nfunction dedupe(arr: string[]): string[] {\n return [...new Set(arr)];\n}\n\nfunction dedupeByKey<T extends object>(arr: T[], key: string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (let i = arr.length - 1; i >= 0; i--) {\n const val = String((arr[i] as any)[key] ?? \"\");\n if (!seen.has(val)) {\n seen.add(val);\n result.unshift(arr[i]!);\n }\n }\n return result;\n}\n\nfunction mergeById<T extends { id: string }>(base: T[], overlay: T[]): T[] {\n const map = new Map<string, T>();\n for (const r of base) map.set(r.id, r);\n for (const r of overlay) map.set(r.id, r);\n return [...map.values()];\n}\n\nfunction stripUndefined<T extends object>(obj?: T): Partial<T> {\n if (!obj) return {};\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) result[k] = v;\n }\n return result as Partial<T>;\n}\n\n// ── MCP server loader ─────────────────────────────────────────────────────────\n\n/**\n * Build a `McpServerDeclaration` from a resolved `CatalogEntry` with `kind: \"mcp-server\"`.\n * Maps `metadata` fields (transport, command, args, env, url, headers) to declaration fields.\n * Returns `null` when the entry has no usable metadata (no command and no url).\n */\nfunction mcpDeclFromCatalogEntry(entry: CatalogEntry): McpServerDeclaration | null {\n const m = entry.metadata;\n if (!m) return null;\n\n const decl: McpServerDeclaration = { id: entry.name };\n if (m.transport) decl.transport = String(m.transport) as \"stdio\" | \"sse\" | \"http\";\n if (m.command) decl.command = String(m.command);\n if (Array.isArray(m.args)) decl.args = m.args.map(String);\n if (m.env && typeof m.env === \"object\") decl.env = m.env as Record<string, string>;\n if (m.url) decl.url = String(m.url);\n if (m.headers && typeof m.headers === \"object\") {\n decl.headers = m.headers as Record<string, string>;\n }\n if (entry.description) decl.description = entry.description;\n if (m.recipe && typeof m.recipe === \"object\" && !Array.isArray(m.recipe)) {\n const r = m.recipe as Record<string, unknown>;\n if (typeof r.attr === \"string\") {\n try {\n validateAssetRecipeAttr(r.attr);\n decl.recipe = { attr: r.attr };\n } catch (err) {\n // Invalid attr — skip the recipe field entirely (treat as if recipe was absent).\n // The MCP server may still be usable via a command/url without recipe substitution.\n console.warn(\n `[workspace-config] mcpDeclFromCatalogEntry: invalid recipe.attr for entry \"${entry.name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n }\n\n // Must have at least a command (stdio) or url (sse/http) to be useful\n if (!decl.command && !decl.url) return null;\n return decl;\n}\n\n/**\n * Merge two `McpServerDeclaration` objects field-by-field.\n * `overlay` values win for every non-undefined field; `base` provides defaults.\n */\nfunction mergeMcpDeclarations(\n base: McpServerDeclaration,\n overlay: McpServerDeclaration,\n): McpServerDeclaration {\n return {\n id: overlay.id,\n transport: overlay.transport ?? base.transport,\n command: overlay.command ?? base.command,\n args: overlay.args ?? base.args,\n env: overlay.env ? (base.env ? { ...base.env, ...overlay.env } : overlay.env) : base.env,\n url: overlay.url ?? base.url,\n headers: overlay.headers\n ? base.headers\n ? { ...base.headers, ...overlay.headers }\n : overlay.headers\n : base.headers,\n description: overlay.description ?? base.description,\n tags: overlay.tags ?? base.tags,\n recipe: overlay.recipe ?? base.recipe,\n };\n}\n\n/**\n * Scan `<projectDir>/.skaile/assets/mcp-server/<name>/MCP.md` for MCP servers\n * that the platform materializer has written to disk for a subscribed asset.\n *\n * For each immediate subdirectory containing an `MCP.md`, the manifest is parsed\n * via {@link fromMcpServerMd} and mapped to a declaration via\n * {@link mcpDeclFromCatalogEntry}. A sibling `.instance.json` (written by the\n * platform materializer) is folded into `decl.env`.\n *\n * **Env-fold precedence (lowest → highest):**\n * 1. `MCP.md` `env` defaults\n * 2. string-valued entries of `.instance.json` `config` (non-string config\n * values — objects/arrays/numbers — are skipped so env never contains\n * `[object Object]`)\n * 3. `.instance.json` `resolvedSecrets` (always folded, all keys)\n *\n * Folded secret *values* are never logged. A malformed `MCP.md` for one asset\n * is caught per-directory and skipped (warned without secret values) so one bad\n * asset never aborts the whole scan.\n *\n * @param projectDir - Workspace root containing `.skaile/assets/mcp-server/`\n * @returns Declarations for every materialized MCP asset (empty if the dir is absent)\n */\nfunction loadMaterializedMcpDeclarations(projectDir: string): McpServerDeclaration[] {\n const dir = join(projectDir, \".skaile/assets/mcp-server\");\n if (!existsSync(dir)) return [];\n\n const result: McpServerDeclaration[] = [];\n\n let subdirs: string[];\n try {\n subdirs = readdirSync(dir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n\n for (const name of subdirs) {\n const subDir = join(dir, name);\n const mdPath = join(subDir, \"MCP.md\");\n if (!existsSync(mdPath)) continue;\n\n try {\n const entry = fromMcpServerMd(mdPath, name);\n const decl = mcpDeclFromCatalogEntry(entry);\n if (!decl) continue;\n\n decl.id = entry.name || name;\n\n const instancePath = join(subDir, \".instance.json\");\n if (existsSync(instancePath)) {\n // A malformed transient .instance.json must not nuke a valid MCP server:\n // catch parse errors here so the decl survives with its MCP.md env.\n try {\n const instance = JSON.parse(readFileSync(instancePath, \"utf8\")) as {\n config?: Record<string, unknown>;\n resolvedSecrets?: Record<string, unknown>;\n };\n\n const env: Record<string, string> = { ...(decl.env ?? {}) };\n\n // string-config < resolvedSecrets (folded after, so secrets win)\n if (instance.config && typeof instance.config === \"object\") {\n for (const [k, v] of Object.entries(instance.config)) {\n if (typeof v === \"string\") env[k] = v;\n }\n }\n if (instance.resolvedSecrets && typeof instance.resolvedSecrets === \"object\") {\n for (const [k, v] of Object.entries(instance.resolvedSecrets)) {\n // Guard like the config fold above — a non-string secret (serializer\n // bug) must not land in subprocess env as \"[object Object]\"/\"null\".\n if (typeof v === \"string\") env[k] = v;\n }\n }\n\n if (Object.keys(env).length > 0) decl.env = env;\n } catch (err) {\n // Never include secret values in the warning — only the failing path + message.\n console.warn(\n `[workspace-config] loadMaterializedMcpDeclarations: ignoring malformed \".instance.json\" for \"${name}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n result.push(decl);\n } catch (err) {\n // Never include secret values in the warning — only the failing path + message.\n console.warn(\n `[workspace-config] loadMaterializedMcpDeclarations: failed to load \"${mdPath}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n return result;\n}\n\n/**\n * Load MCP server declarations by merging three sources:\n *\n * 1. **Catalog defaults** — `mcp-server:*` refs in the `dependencies` array\n * (or legacy `ai_resources[].dependencies`). Each ref is resolved from the\n * repository catalog; the `MCP.md` frontmatter provides default config\n * (transport, command, args, env, url, headers).\n *\n * 2. **Materialized assets** — MCP servers the platform materializer has written\n * to `<projectDir>/.skaile/assets/mcp-server/<name>/MCP.md` for subscribed\n * assets (see {@link loadMaterializedMcpDeclarations}). This scan ALWAYS runs,\n * so a subscribed asset on disk with no `dependencies:` and no `mcp_servers:`\n * entry is still picked up.\n *\n * 3. **Explicit declarations** — entries in the `mcp_servers` section of\n * `skaile.yaml`. These override the other two sources field-by-field when the\n * `id` matches.\n *\n * **Precedence (lowest → highest):** catalog-dep refs < materialized assets <\n * explicit `mcp_servers:`. A catalog-dep and a materialized asset with the same\n * id merge (materialized overlay onto catalog base) rather than double-counting.\n *\n * @param projectDir - Workspace root where `skaile.yaml` lives\n * @returns Unified array of `McpServerDeclaration` objects ready for the runner\n * @docLink packages/core/workspace-config#load-mcp-server-declarations\n */\nexport function loadMcpServerDeclarations(projectDir: string): McpServerDeclaration[] {\n const config = resolveSkWorkspaceConfig(projectDir);\n const explicit = config.mcp_servers ?? [];\n\n // Materialized scan always runs — the primary use case is a subscribed asset\n // on disk with no dependencies: and no mcp_servers: entry.\n const materialized = loadMaterializedMcpDeclarations(projectDir);\n\n // Collect all mcp-server refs from both dependency formats\n const mcpRefStrings: string[] = [];\n\n // New format: top-level dependencies\n for (const dep of config.dependencies ?? []) {\n const ref = parseAssetRef(dep);\n if (ref.kind === \"mcp-server\") mcpRefStrings.push(dep);\n }\n\n // Legacy format: ai_resources[].dependencies\n for (const res of config.ai_resources ?? []) {\n for (const dep of res.dependencies ?? []) {\n const ref = parseAssetRef(dep);\n if (ref.kind === \"mcp-server\") mcpRefStrings.push(dep);\n }\n }\n\n // Resolve catalog entries\n const repositories = config.repositories ?? {};\n\n // Also build repositories from legacy ai_resources for backward compat\n const allRepos = { ...repositories };\n for (const res of config.ai_resources ?? []) {\n if (res.name && res.path && !(res.name in allRepos)) {\n allRepos[res.name] = {\n url: res.path.startsWith(\"/\") ? undefined : res.path,\n path: res.path.startsWith(\"/\") ? res.path : undefined,\n branch: res.branch,\n };\n }\n }\n\n const reposDir = getGlobalCacheDir();\n // byId tracks the current merged decl per id so later, higher-precedence\n // sources overlay onto it instead of double-counting.\n const byId = new Map<string, McpServerDeclaration>();\n const order: string[] = [];\n\n const upsert = (decl: McpServerDeclaration) => {\n const existing = byId.get(decl.id);\n if (existing) {\n byId.set(decl.id, mergeMcpDeclarations(existing, decl));\n } else {\n byId.set(decl.id, decl);\n order.push(decl.id);\n }\n };\n\n // Source 1 (lowest): catalog-dep refs\n const seen = new Set<string>();\n for (const refStr of mcpRefStrings) {\n const ref = parseAssetRef(refStr);\n if (seen.has(ref.name)) continue;\n seen.add(ref.name);\n\n const entry = resolveAsset(ref, allRepos, reposDir, { projectDir });\n if (!entry) continue;\n\n const catalogDecl = mcpDeclFromCatalogEntry(entry);\n if (!catalogDecl) continue;\n\n upsert(catalogDecl);\n }\n\n // Source 2: materialized assets — overlay onto matching catalog base.\n for (const decl of materialized) {\n upsert(decl);\n }\n\n // Source 3 (highest): explicit mcp_servers: — overlay field-by-field.\n for (const decl of explicit) {\n upsert(decl);\n }\n\n return order.map((id) => byId.get(id) as McpServerDeclaration);\n}\n\n// ── Agent definition resolver ──────────────────────────────────────────────────\n\n/**\n * Walk upward from `from` (max 8 levels) until a directory containing\n * `ai-assets/` is found. Returns the absolute path to that `ai-assets/`\n * directory, or undefined if none found.\n */\nfunction findAiAssetsDir(from: string): string | undefined {\n let dir = resolve(from);\n for (let i = 0; i < 8; i++) {\n const candidate = join(dir, \"ai-assets\");\n if (existsSync(candidate)) return candidate;\n const resolved = resolve(dir, \"..\");\n if (resolved === dir) break;\n dir = resolved;\n }\n return undefined;\n}\n\n/**\n * Resolve the `agent.definition` field from `skaile.yaml` in `projectDir`\n * to an absolute filesystem path.\n *\n * Resolution rules:\n * - Absent or empty → undefined\n * - Relative/absolute local path → resolve(projectDir, definition)\n * - `ai-assets://<rest>` → walk up for ai-assets/, join with <rest>\n * - `agent:<name>` catalog refs → resolved via repository scanning\n *\n * Used by the runner to determine agentDir without requiring --agent-dir.\n * @docLink packages/core/workspace-config#resolve-agent-dir\n */\nexport function resolveAgentDir(projectDir: string): string | undefined {\n const config = resolveSkWorkspaceConfig(projectDir);\n const definition = config.agent?.definition;\n if (!definition) return undefined;\n\n // ai-assets:// URI\n if (definition.startsWith(\"ai-assets://\")) {\n const relPath = definition.slice(\"ai-assets://\".length);\n const aiAssetsDir = findAiAssetsDir(projectDir);\n if (!aiAssetsDir) return undefined;\n return join(aiAssetsDir, relPath);\n }\n\n // Catalog reference — resolve via repository scanning\n if (definition.startsWith(\"agent:\")) {\n const ref = parseAssetRef(definition);\n const repositories = config.repositories ?? {};\n const reposDir = getGlobalCacheDir();\n const entry = resolveAsset(ref, repositories, reposDir, { projectDir });\n if (!entry) return undefined;\n return dirname(entry.source);\n }\n\n // Local path (relative or absolute)\n return resolve(projectDir, definition);\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { resolveSkWorkspaceConfig, readLinks } from './chunk-VVS7MACX.js';
2
- import { scanDirectory } from './chunk-FRPKLIEZ.js';
1
+ import { resolveSkWorkspaceConfig, readLinks } from './chunk-TKOLD2O7.js';
2
+ import { scanDirectory } from './chunk-WIR34WMU.js';
3
3
  import { existsSync, readFileSync, lstatSync } from 'fs';
4
4
  import { resolve, join, dirname } from 'path';
5
5
  import { fileURLToPath } from 'url';
@@ -165,5 +165,5 @@ function findCatalogEntry(entries, query) {
165
165
  }
166
166
 
167
167
  export { BASE_ASSETS_REPO_NAME, resolveBaseAssetsRoot, resolveRuntimeAssets };
168
- //# sourceMappingURL=chunk-R4FRSB47.js.map
169
- //# sourceMappingURL=chunk-R4FRSB47.js.map
168
+ //# sourceMappingURL=chunk-TTY56FQQ.js.map
169
+ //# sourceMappingURL=chunk-TTY56FQQ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../core/src/runtime-assets.ts"],"names":["resolvePath","require"],"mappings":";;;;;;;AAuFO,IAAM,qBAAA,GAAwB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AA,EAGJ;AACA,EAAA,IAAI,KAAK,GAAA,EAAK;AACZ,IAAA,OAAO,CAAA,YAAA,EAAe,IAAI,CAAA,GAAA,EAAM,IAAA,CAAK,GAAG,CAAA,8EAAA,CAAA;AAAA,EAC1C;AACA,EAAA,IAAI,KAAK,IAAA,EAAM;AACb,IAAA,OAAO,CAAA,YAAA,EAAe,IAAI,CAAA,kBAAA,EAAqB,IAAA,CAAK,IAAI,CAAA,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,eAAe,IAAI,CAAA,2BAAA,CAAA;AAC5B;AAEA,SAAS,gBAAA,CACP,SACA,KAAA,EACiC;AACjC,EAAA,IAAI,MAAM,IAAA,EAAM;AACd,IAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,KAAA,CAAM,IAAA,IAAQ,CAAA,CAAE,IAAA,KAAS,KAAA,CAAM,IAAI,CAAA;AAAA,EAC3E;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,IAAA,KAAS,MAAM,IAAI,CAAA;AAC3D,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,QAAQ,CAAC,CAAA;AAE1C,EAAA,OAAO,MAAA;AACT","file":"chunk-R4FRSB47.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `base-assets/` directory as an implicit default), and\n * produce a unified view of connector catalog entries plus the implicit refs\n * that the `skaile.yaml` `connectors:` section adds to the dependency graph.\n *\n * This module is the single source of truth for \"which connectors does this\n * project see at runtime, and where do their implementations live on disk\".\n * Both the runner (serve, REPL, flow) and the platform's mid-session\n * `add_resource` flow consume `RuntimeAssetsResult.catalogEntries` and pass\n * it into `ConnectorManager` for catalog-based resolution.\n *\n * `base-assets/` is a subdirectory of the single published `@skaile/workspaces`\n * package — not a standalone package. Its on-disk path is resolved with this\n * precedence:\n * 1. `process.env.SKAILE_BASE_ASSETS_DIR` — set by the agent container at\n * runtime to point at `/app/base-assets/`.\n * 2. `require.resolve('@skaile/workspaces/package.json')` + `base-assets/` —\n * works when `@skaile/workspaces` is installed as a dependency.\n * 3. Walk upward from this module's location for the `@skaile/workspaces`\n * package root (a `package.json` whose `name` is `@skaile/workspaces`)\n * that contains a `base-assets/` subdirectory. This is the dev-workspace\n * fallback — it is bounded and works regardless of where the consumer\n * lives in the tree.\n */\n\nimport { existsSync, lstatSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { RepositoryDeclaration } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\nimport { readLinks } from \"./repo-manager.js\";\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/**\n * Catalog entry filtered to mount/connector kinds. Same shape as `CatalogEntry`.\n * @docLink packages/core/concepts#runtime-catalog-entry\n */\nexport type RuntimeCatalogEntry = CatalogEntry;\n\n/**\n * Implicit catalog reference derived from a `connectors:` declaration in `skaile.yaml`.\n * Each connector driver becomes an implicit ref that must be resolved in the catalog.\n * @docLink packages/core/concepts#runtime-asset-ref\n */\nexport interface RuntimeAssetRef {\n kind: \"connector\";\n /** Driver name — matches `RuntimeCatalogEntry.name`. */\n name: string;\n /** Source declaration id from `skaile.yaml`. */\n declarationId: string;\n}\n\n/**\n * Aggregated npm packages required by all resolved mount/connector adapters.\n * Populated from `metadata.npm_deps` in each matched catalog entry.\n * @docLink packages/core/concepts#runtime-npm-deps\n */\nexport interface RuntimeNpmDeps {\n required: string[];\n optional: string[];\n}\n\n/**\n * Non-fatal warning emitted during `resolveRuntimeAssets` when a repo is unavailable\n * or a driver is not found in any catalog.\n * @docLink packages/core/concepts#runtime-asset-warning\n */\nexport interface RuntimeAssetWarning {\n /** Stable code for filtering / structured logging. */\n code: \"missing_driver\" | \"repo_unavailable\" | \"invalid_repo_decl\";\n message: string;\n /** Declaration id when applicable. */\n declarationId?: string;\n /** Driver / repository name when applicable. */\n name?: string;\n}\n\n/**\n * Repository name used for the implicit `@skaile/base-assets` catalog entry.\n * Callers can override this repo by declaring `repositories: { base-assets: ... }` in `skaile.yaml`.\n * @docLink packages/core/concepts#base-assets-repo-name\n */\nexport const BASE_ASSETS_REPO_NAME = \"base-assets\";\n\n/**\n * Result of `resolveRuntimeAssets`.\n * The same object is mutated in place by `refresh()`, allowing callers to hold\n * a stable reference and observe updates after a new repository is cloned or\n * a driver is installed mid-session.\n * @docLink packages/core/concepts#runtime-assets-result\n */\nexport interface RuntimeAssetsResult {\n catalogEntries: RuntimeCatalogEntry[];\n implicitRefs: RuntimeAssetRef[];\n requiredNpmDeps: RuntimeNpmDeps;\n warnings: RuntimeAssetWarning[];\n /** Re-scan repositories and re-derive implicit refs. Mutates in place. */\n refresh(): Promise<void>;\n /**\n * Catalog lookup. When `kind` is omitted and multiple entries share the\n * `name`, returns `undefined` (caller must disambiguate).\n */\n findEntry(query: { kind?: \"connector\"; name: string }): RuntimeCatalogEntry | undefined;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Resolve all runtime assets visible to a project by scanning declared repositories.\n *\n * Reads `skaile.yaml`, scans every declared repository (plus the implicit\n * `@skaile/base-assets` repo), and derives implicit refs from `mounts:` /\n * `connectors:` declarations. Does not clone or install anything — purely a\n * read-only scan of what is already on disk. URL-only repositories that have\n * not been cloned yet are reported as `repo_unavailable` warnings.\n *\n * @param projectDir - Absolute path to the project workspace root\n * @returns `RuntimeAssetsResult` with catalog entries, implicit refs, npm deps, and warnings\n * @docLink packages/core/concepts#resolve-runtime-assets\n */\nexport async function resolveRuntimeAssets(projectDir: string): Promise<RuntimeAssetsResult> {\n const result: RuntimeAssetsResult = {\n catalogEntries: [],\n implicitRefs: [],\n requiredNpmDeps: { required: [], optional: [] },\n warnings: [],\n refresh: async () => {\n await populate(projectDir, result);\n },\n findEntry: (query) => findCatalogEntry(result.catalogEntries, query),\n };\n\n await populate(projectDir, result);\n return result;\n}\n\n/**\n * Resolve the on-disk root of `@skaile/base-assets`.\n *\n * Resolution tiers:\n * 1. `SKAILE_BASE_ASSETS_DIR` env var\n * 2. `require.resolve('@skaile/workspaces/base-assets/package.json')` (npm install / hoisted)\n * 3. Walk upward from this module looking for `base-assets/package.json` or\n * `ai-assets-skaile/package.json` (legacy shell-repo layout)\n *\n * @returns Absolute path to the `@skaile/base-assets` package directory\n * @throws When none of the three tiers can locate the package\n * @docLink packages/core/concepts#resolve-base-assets-root\n */\nexport function resolveBaseAssetsRoot(): string {\n const envDir = process.env.SKAILE_BASE_ASSETS_DIR;\n if (envDir && existsSync(envDir)) return resolvePath(envDir);\n\n try {\n const require = createRequire(import.meta.url);\n const pkgJson = require.resolve(\"@skaile/workspaces/package.json\");\n const candidate = join(dirname(pkgJson), \"base-assets\");\n if (existsSync(candidate)) return candidate;\n } catch {\n // Fall through to workspace walk.\n }\n\n const workspaceHit = findInWorkspace(import.meta.url);\n if (workspaceHit) return workspaceHit;\n\n throw new Error(\n `Cannot resolve the base-assets directory. ` +\n `Set SKAILE_BASE_ASSETS_DIR to the on-disk path, ` +\n `ensure @skaile/workspaces is installed, ` +\n `or run from within the @skaile/workspaces package tree.`,\n );\n}\n\n/**\n * Walk upward from `startUrl` looking for the `@skaile/workspaces` package\n * root — a directory whose `package.json` `name` is `@skaile/workspaces` and\n * which contains a `base-assets/` subdirectory. Bounded to 8 levels.\n */\nfunction findInWorkspace(startUrl: string): string | null {\n let dir: string;\n try {\n dir = dirname(fileURLToPath(startUrl));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n const baseAssets = join(dir, \"base-assets\");\n if (existsSync(pkgPath) && existsSync(baseAssets)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return baseAssets;\n } catch {\n // Ignore malformed package.json and keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\nasync function populate(projectDir: string, target: RuntimeAssetsResult): Promise<void> {\n target.catalogEntries = [];\n target.implicitRefs = [];\n target.requiredNpmDeps = { required: [], optional: [] };\n target.warnings = [];\n\n const config = resolveSkWorkspaceConfig(projectDir);\n const repositories = buildEffectiveRepositories(config.repositories);\n const links = readLinks(projectDir);\n\n // Scan each repository for connector entries.\n for (const [name, decl] of Object.entries(repositories)) {\n const repoDir = resolveRepoDir(name, decl, projectDir, links);\n if (!repoDir) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: repoUnavailableMessage(name, decl),\n });\n continue;\n }\n try {\n const entries = scanDirectory(repoDir, name).filter((e) => e.kind === \"connector\");\n target.catalogEntries.push(...entries);\n } catch (err) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: `Failed to scan repository \"${name}\" at ${repoDir}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n });\n }\n }\n\n // Derive implicit refs from skaile.yaml connectors.\n for (const c of config.connectors ?? []) {\n target.implicitRefs.push({ kind: \"connector\", name: c.driver, declarationId: c.id });\n }\n\n // Validate refs and aggregate npm deps.\n const requiredSet = new Set<string>();\n const optionalSet = new Set<string>();\n for (const ref of target.implicitRefs) {\n const entry = findCatalogEntry(target.catalogEntries, ref);\n if (!entry) {\n target.warnings.push({\n code: \"missing_driver\",\n declarationId: ref.declarationId,\n name: ref.name,\n message:\n `Unknown ${ref.kind} driver \"${ref.name}\" referenced by ${ref.kind} \"${ref.declarationId}\". ` +\n `Run \\`skaile ${ref.kind} catalog\\` to see available drivers, ` +\n `or declare a repository in skaile.yaml that provides this driver.`,\n });\n continue;\n }\n const npm = (entry.metadata?.npm_deps ?? {}) as { required?: string[]; optional?: string[] };\n for (const p of npm.required ?? []) requiredSet.add(p);\n for (const p of npm.optional ?? []) optionalSet.add(p);\n }\n target.requiredNpmDeps.required = [...requiredSet];\n target.requiredNpmDeps.optional = [...optionalSet];\n}\n\n/**\n * Build the effective `repositories` map: caller's declarations first, then\n * the implicit `base-assets` repo if absent. Caller's entries always win — an\n * org can override the default by declaring `repositories: { base-assets: {...} }`.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, RepositoryDeclaration> | undefined,\n): Record<string, RepositoryDeclaration> {\n const result: Record<string, RepositoryDeclaration> = { ...(declared ?? {}) };\n if (!result[BASE_ASSETS_REPO_NAME]) {\n try {\n const baseDir = resolveBaseAssetsRoot();\n result[BASE_ASSETS_REPO_NAME] = { path: baseDir };\n } catch (err) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether base-assets is required for this project.\n // We re-discover the failure in resolveRepoDir() and emit there.\n result[BASE_ASSETS_REPO_NAME] = { path: \"\" };\n }\n }\n return result;\n}\n\n/**\n * Resolve a repository declaration to an on-disk directory. Order:\n * 1. Linked override (`.skaile/links.yaml`).\n * 2. Local `path` — relative to `projectDir`.\n * 3. Cloned URL repo at `.skaile/repos/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n */\nfunction resolveRepoDir(\n name: string,\n decl: RepositoryDeclaration,\n projectDir: string,\n links: Record<string, string>,\n): string | null {\n // 1. Linked override\n const linked = links[name];\n if (linked && existsSync(linked)) return linked;\n\n // 2. Local path\n if (decl.path) {\n const resolved = resolvePath(projectDir, decl.path);\n return existsSync(resolved) ? resolved : null;\n }\n\n // 3. URL repo cloned to project's .skaile/repos/<name>\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"repos\", name);\n if (existsSync(projectDest)) {\n // Either a real directory or a symlink to the global cache.\n try {\n return lstatSync(projectDest).isSymbolicLink() ? projectDest : projectDest;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n return null;\n}\n\nfunction repoUnavailableMessage(name: string, decl: RepositoryDeclaration): string {\n if (name === BASE_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve @skaile/base-assets. ` +\n `Set SKAILE_BASE_ASSETS_DIR or ensure the package is installed.`\n );\n }\n if (decl.url) {\n return `Repository \"${name}\" (${decl.url}) is not available. Register it as a Library Source via \\`skaile source add\\`.`;\n }\n if (decl.path) {\n return `Repository \"${name}\" path not found: ${decl.path}`;\n }\n return `Repository \"${name}\" has neither url nor path.`;\n}\n\nfunction findCatalogEntry(\n entries: RuntimeCatalogEntry[],\n query: { kind?: \"connector\"; name: string },\n): RuntimeCatalogEntry | undefined {\n if (query.kind) {\n return entries.find((e) => e.kind === query.kind && e.name === query.name);\n }\n const matches = entries.filter((e) => e.name === query.name);\n if (matches.length === 1) return matches[0];\n // 0 or >1 with no kind — caller must disambiguate.\n return undefined;\n}\n"]}
1
+ {"version":3,"sources":["../core/src/runtime-assets.ts"],"names":["resolvePath","require"],"mappings":";;;;;;;AAuFO,IAAM,qBAAA,GAAwB;AAsCrC,eAAsB,qBAAqB,UAAA,EAAkD;AAC3F,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,gBAAgB,EAAC;AAAA,IACjB,cAAc,EAAC;AAAA,IACf,iBAAiB,EAAE,QAAA,EAAU,EAAC,EAAG,QAAA,EAAU,EAAC,EAAE;AAAA,IAC9C,UAAU,EAAC;AAAA,IACX,SAAS,YAAY;AACnB,MAAA,MAAM,QAAA,CAAS,YAAY,MAAM,CAAA;AAAA,IACnC,CAAA;AAAA,IACA,WAAW,CAAC,KAAA,KAAU,gBAAA,CAAiB,MAAA,CAAO,gBAAgB,KAAK;AAAA,GACrE;AAEA,EAAA,MAAM,QAAA,CAAS,YAAY,MAAM,CAAA;AACjC,EAAA,OAAO,MAAA;AACT;AAeO,SAAS,qBAAA,GAAgC;AAC9C,EAAA,MAAM,MAAA,GAAS,QAAQ,GAAA,CAAI,sBAAA;AAC3B,EAAA,IAAI,UAAU,UAAA,CAAW,MAAM,CAAA,EA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MAAM,OAAA,GAAU,QAAQ,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,IAAA,KAAS,MAAM,IAAI,CAAA;AAC3D,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,QAAQ,CAAC,CAAA;AAE1C,EAAA,OAAO,MAAA;AACT","file":"chunk-TTY56FQQ.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `base-assets/` directory as an implicit default), and\n * produce a unified view of connector catalog entries plus the implicit refs\n * that the `skaile.yaml` `connectors:` section adds to the dependency graph.\n *\n * This module is the single source of truth for \"which connectors does this\n * project see at runtime, and where do their implementations live on disk\".\n * Both the runner (serve, REPL, flow) and the platform's mid-session\n * `add_resource` flow consume `RuntimeAssetsResult.catalogEntries` and pass\n * it into `ConnectorManager` for catalog-based resolution.\n *\n * `base-assets/` is a subdirectory of the single published `@skaile/workspaces`\n * package — not a standalone package. Its on-disk path is resolved with this\n * precedence:\n * 1. `process.env.SKAILE_BASE_ASSETS_DIR` — set by the agent container at\n * runtime to point at `/app/base-assets/`.\n * 2. `require.resolve('@skaile/workspaces/package.json')` + `base-assets/` —\n * works when `@skaile/workspaces` is installed as a dependency.\n * 3. Walk upward from this module's location for the `@skaile/workspaces`\n * package root (a `package.json` whose `name` is `@skaile/workspaces`)\n * that contains a `base-assets/` subdirectory. This is the dev-workspace\n * fallback — it is bounded and works regardless of where the consumer\n * lives in the tree.\n */\n\nimport { existsSync, lstatSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { RepositoryDeclaration } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\nimport { readLinks } from \"./repo-manager.js\";\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/**\n * Catalog entry filtered to mount/connector kinds. Same shape as `CatalogEntry`.\n * @docLink packages/core/concepts#runtime-catalog-entry\n */\nexport type RuntimeCatalogEntry = CatalogEntry;\n\n/**\n * Implicit catalog reference derived from a `connectors:` declaration in `skaile.yaml`.\n * Each connector driver becomes an implicit ref that must be resolved in the catalog.\n * @docLink packages/core/concepts#runtime-asset-ref\n */\nexport interface RuntimeAssetRef {\n kind: \"connector\";\n /** Driver name — matches `RuntimeCatalogEntry.name`. */\n name: string;\n /** Source declaration id from `skaile.yaml`. */\n declarationId: string;\n}\n\n/**\n * Aggregated npm packages required by all resolved mount/connector adapters.\n * Populated from `metadata.npm_deps` in each matched catalog entry.\n * @docLink packages/core/concepts#runtime-npm-deps\n */\nexport interface RuntimeNpmDeps {\n required: string[];\n optional: string[];\n}\n\n/**\n * Non-fatal warning emitted during `resolveRuntimeAssets` when a repo is unavailable\n * or a driver is not found in any catalog.\n * @docLink packages/core/concepts#runtime-asset-warning\n */\nexport interface RuntimeAssetWarning {\n /** Stable code for filtering / structured logging. */\n code: \"missing_driver\" | \"repo_unavailable\" | \"invalid_repo_decl\";\n message: string;\n /** Declaration id when applicable. */\n declarationId?: string;\n /** Driver / repository name when applicable. */\n name?: string;\n}\n\n/**\n * Repository name used for the implicit `@skaile/base-assets` catalog entry.\n * Callers can override this repo by declaring `repositories: { base-assets: ... }` in `skaile.yaml`.\n * @docLink packages/core/concepts#base-assets-repo-name\n */\nexport const BASE_ASSETS_REPO_NAME = \"base-assets\";\n\n/**\n * Result of `resolveRuntimeAssets`.\n * The same object is mutated in place by `refresh()`, allowing callers to hold\n * a stable reference and observe updates after a new repository is cloned or\n * a driver is installed mid-session.\n * @docLink packages/core/concepts#runtime-assets-result\n */\nexport interface RuntimeAssetsResult {\n catalogEntries: RuntimeCatalogEntry[];\n implicitRefs: RuntimeAssetRef[];\n requiredNpmDeps: RuntimeNpmDeps;\n warnings: RuntimeAssetWarning[];\n /** Re-scan repositories and re-derive implicit refs. Mutates in place. */\n refresh(): Promise<void>;\n /**\n * Catalog lookup. When `kind` is omitted and multiple entries share the\n * `name`, returns `undefined` (caller must disambiguate).\n */\n findEntry(query: { kind?: \"connector\"; name: string }): RuntimeCatalogEntry | undefined;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Resolve all runtime assets visible to a project by scanning declared repositories.\n *\n * Reads `skaile.yaml`, scans every declared repository (plus the implicit\n * `@skaile/base-assets` repo), and derives implicit refs from `mounts:` /\n * `connectors:` declarations. Does not clone or install anything — purely a\n * read-only scan of what is already on disk. URL-only repositories that have\n * not been cloned yet are reported as `repo_unavailable` warnings.\n *\n * @param projectDir - Absolute path to the project workspace root\n * @returns `RuntimeAssetsResult` with catalog entries, implicit refs, npm deps, and warnings\n * @docLink packages/core/concepts#resolve-runtime-assets\n */\nexport async function resolveRuntimeAssets(projectDir: string): Promise<RuntimeAssetsResult> {\n const result: RuntimeAssetsResult = {\n catalogEntries: [],\n implicitRefs: [],\n requiredNpmDeps: { required: [], optional: [] },\n warnings: [],\n refresh: async () => {\n await populate(projectDir, result);\n },\n findEntry: (query) => findCatalogEntry(result.catalogEntries, query),\n };\n\n await populate(projectDir, result);\n return result;\n}\n\n/**\n * Resolve the on-disk root of `@skaile/base-assets`.\n *\n * Resolution tiers:\n * 1. `SKAILE_BASE_ASSETS_DIR` env var\n * 2. `require.resolve('@skaile/workspaces/base-assets/package.json')` (npm install / hoisted)\n * 3. Walk upward from this module looking for `base-assets/package.json` or\n * `ai-assets-skaile/package.json` (legacy shell-repo layout)\n *\n * @returns Absolute path to the `@skaile/base-assets` package directory\n * @throws When none of the three tiers can locate the package\n * @docLink packages/core/concepts#resolve-base-assets-root\n */\nexport function resolveBaseAssetsRoot(): string {\n const envDir = process.env.SKAILE_BASE_ASSETS_DIR;\n if (envDir && existsSync(envDir)) return resolvePath(envDir);\n\n try {\n const require = createRequire(import.meta.url);\n const pkgJson = require.resolve(\"@skaile/workspaces/package.json\");\n const candidate = join(dirname(pkgJson), \"base-assets\");\n if (existsSync(candidate)) return candidate;\n } catch {\n // Fall through to workspace walk.\n }\n\n const workspaceHit = findInWorkspace(import.meta.url);\n if (workspaceHit) return workspaceHit;\n\n throw new Error(\n `Cannot resolve the base-assets directory. ` +\n `Set SKAILE_BASE_ASSETS_DIR to the on-disk path, ` +\n `ensure @skaile/workspaces is installed, ` +\n `or run from within the @skaile/workspaces package tree.`,\n );\n}\n\n/**\n * Walk upward from `startUrl` looking for the `@skaile/workspaces` package\n * root — a directory whose `package.json` `name` is `@skaile/workspaces` and\n * which contains a `base-assets/` subdirectory. Bounded to 8 levels.\n */\nfunction findInWorkspace(startUrl: string): string | null {\n let dir: string;\n try {\n dir = dirname(fileURLToPath(startUrl));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n const baseAssets = join(dir, \"base-assets\");\n if (existsSync(pkgPath) && existsSync(baseAssets)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return baseAssets;\n } catch {\n // Ignore malformed package.json and keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\nasync function populate(projectDir: string, target: RuntimeAssetsResult): Promise<void> {\n target.catalogEntries = [];\n target.implicitRefs = [];\n target.requiredNpmDeps = { required: [], optional: [] };\n target.warnings = [];\n\n const config = resolveSkWorkspaceConfig(projectDir);\n const repositories = buildEffectiveRepositories(config.repositories);\n const links = readLinks(projectDir);\n\n // Scan each repository for connector entries.\n for (const [name, decl] of Object.entries(repositories)) {\n const repoDir = resolveRepoDir(name, decl, projectDir, links);\n if (!repoDir) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: repoUnavailableMessage(name, decl),\n });\n continue;\n }\n try {\n const entries = scanDirectory(repoDir, name).filter((e) => e.kind === \"connector\");\n target.catalogEntries.push(...entries);\n } catch (err) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: `Failed to scan repository \"${name}\" at ${repoDir}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n });\n }\n }\n\n // Derive implicit refs from skaile.yaml connectors.\n for (const c of config.connectors ?? []) {\n target.implicitRefs.push({ kind: \"connector\", name: c.driver, declarationId: c.id });\n }\n\n // Validate refs and aggregate npm deps.\n const requiredSet = new Set<string>();\n const optionalSet = new Set<string>();\n for (const ref of target.implicitRefs) {\n const entry = findCatalogEntry(target.catalogEntries, ref);\n if (!entry) {\n target.warnings.push({\n code: \"missing_driver\",\n declarationId: ref.declarationId,\n name: ref.name,\n message:\n `Unknown ${ref.kind} driver \"${ref.name}\" referenced by ${ref.kind} \"${ref.declarationId}\". ` +\n `Run \\`skaile ${ref.kind} catalog\\` to see available drivers, ` +\n `or declare a repository in skaile.yaml that provides this driver.`,\n });\n continue;\n }\n const npm = (entry.metadata?.npm_deps ?? {}) as { required?: string[]; optional?: string[] };\n for (const p of npm.required ?? []) requiredSet.add(p);\n for (const p of npm.optional ?? []) optionalSet.add(p);\n }\n target.requiredNpmDeps.required = [...requiredSet];\n target.requiredNpmDeps.optional = [...optionalSet];\n}\n\n/**\n * Build the effective `repositories` map: caller's declarations first, then\n * the implicit `base-assets` repo if absent. Caller's entries always win — an\n * org can override the default by declaring `repositories: { base-assets: {...} }`.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, RepositoryDeclaration> | undefined,\n): Record<string, RepositoryDeclaration> {\n const result: Record<string, RepositoryDeclaration> = { ...(declared ?? {}) };\n if (!result[BASE_ASSETS_REPO_NAME]) {\n try {\n const baseDir = resolveBaseAssetsRoot();\n result[BASE_ASSETS_REPO_NAME] = { path: baseDir };\n } catch (err) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether base-assets is required for this project.\n // We re-discover the failure in resolveRepoDir() and emit there.\n result[BASE_ASSETS_REPO_NAME] = { path: \"\" };\n }\n }\n return result;\n}\n\n/**\n * Resolve a repository declaration to an on-disk directory. Order:\n * 1. Linked override (`.skaile/links.yaml`).\n * 2. Local `path` — relative to `projectDir`.\n * 3. Cloned URL repo at `.skaile/repos/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n */\nfunction resolveRepoDir(\n name: string,\n decl: RepositoryDeclaration,\n projectDir: string,\n links: Record<string, string>,\n): string | null {\n // 1. Linked override\n const linked = links[name];\n if (linked && existsSync(linked)) return linked;\n\n // 2. Local path\n if (decl.path) {\n const resolved = resolvePath(projectDir, decl.path);\n return existsSync(resolved) ? resolved : null;\n }\n\n // 3. URL repo cloned to project's .skaile/repos/<name>\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"repos\", name);\n if (existsSync(projectDest)) {\n // Either a real directory or a symlink to the global cache.\n try {\n return lstatSync(projectDest).isSymbolicLink() ? projectDest : projectDest;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n return null;\n}\n\nfunction repoUnavailableMessage(name: string, decl: RepositoryDeclaration): string {\n if (name === BASE_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve @skaile/base-assets. ` +\n `Set SKAILE_BASE_ASSETS_DIR or ensure the package is installed.`\n );\n }\n if (decl.url) {\n return `Repository \"${name}\" (${decl.url}) is not available. Register it as a Library Source via \\`skaile source add\\`.`;\n }\n if (decl.path) {\n return `Repository \"${name}\" path not found: ${decl.path}`;\n }\n return `Repository \"${name}\" has neither url nor path.`;\n}\n\nfunction findCatalogEntry(\n entries: RuntimeCatalogEntry[],\n query: { kind?: \"connector\"; name: string },\n): RuntimeCatalogEntry | undefined {\n if (query.kind) {\n return entries.find((e) => e.kind === query.kind && e.name === query.name);\n }\n const matches = entries.filter((e) => e.name === query.name);\n if (matches.length === 1) return matches[0];\n // 0 or >1 with no kind — caller must disambiguate.\n return undefined;\n}\n"]}
@@ -0,0 +1,96 @@
1
+ // plugin-registry/src/errors.ts
2
+ var RegistrationError = class extends Error {
3
+ constructor(kind, id) {
4
+ super(`A "${kind}" target with id "${id}" is already registered.`);
5
+ this.name = "RegistrationError";
6
+ }
7
+ };
8
+ var MissingTargetError = class extends Error {
9
+ constructor(kind, id) {
10
+ super(`No "${kind}" target registered with id "${id}".`);
11
+ this.name = "MissingTargetError";
12
+ }
13
+ };
14
+ var ApiVersionMismatchError = class extends Error {
15
+ constructor(kind, id, got) {
16
+ super(
17
+ `Target "${id}" (kind "${kind}") declares apiVersion ${String(got)}; registry requires apiVersion 1.`
18
+ );
19
+ this.name = "ApiVersionMismatchError";
20
+ }
21
+ };
22
+ var DeployTargetNotFoundError = class extends Error {
23
+ constructor(id) {
24
+ super(`No deploy target registered with id "${id}".`);
25
+ this.name = "DeployTargetNotFoundError";
26
+ }
27
+ };
28
+
29
+ // plugin-registry/src/internal.ts
30
+ var MapPluginRegistry = class {
31
+ apiVersion = 1;
32
+ // One Map per kind keeps lookups kind-scoped — a driver and a connector may
33
+ // share an id without colliding.
34
+ stores = {
35
+ driver: /* @__PURE__ */ new Map(),
36
+ connector: /* @__PURE__ */ new Map(),
37
+ deployTarget: /* @__PURE__ */ new Map()
38
+ };
39
+ register(kind, target) {
40
+ const t = target;
41
+ if (t.apiVersion !== 1) {
42
+ throw new ApiVersionMismatchError(kind, t.id, t.apiVersion);
43
+ }
44
+ const store = this.stores[kind];
45
+ if (store.has(t.id)) {
46
+ throw new RegistrationError(kind, t.id);
47
+ }
48
+ store.set(t.id, t);
49
+ }
50
+ get(kind, id) {
51
+ return this.stores[kind].get(id);
52
+ }
53
+ list(kind) {
54
+ return [...this.stores[kind].values()].map((t) => ({
55
+ id: t.id,
56
+ displayName: t.displayName
57
+ }));
58
+ }
59
+ };
60
+ function createPluginRegistry() {
61
+ return new MapPluginRegistry();
62
+ }
63
+ var pluginRegistry = createPluginRegistry();
64
+
65
+ // plugin-registry/src/deploy-handle.ts
66
+ async function resolveDeployTarget(yaml, override, registry = pluginRegistry) {
67
+ if (override) {
68
+ const target2 = registry.get("deployTarget", override.target);
69
+ if (!target2) throw new DeployTargetNotFoundError(override.target);
70
+ return {
71
+ target: target2,
72
+ config: target2.configSchema.parse(override.config ?? {}),
73
+ provenance: { source: "override", reason: override.reason }
74
+ };
75
+ }
76
+ if (yaml.deploy) {
77
+ const target2 = registry.get("deployTarget", yaml.deploy.target);
78
+ if (!target2) throw new DeployTargetNotFoundError(yaml.deploy.target);
79
+ return {
80
+ target: target2,
81
+ config: target2.configSchema.parse(yaml.deploy.config ?? {}),
82
+ provenance: { source: "yaml" }
83
+ };
84
+ }
85
+ const target = registry.get("deployTarget", "local");
86
+ if (!target) throw new DeployTargetNotFoundError("local");
87
+ return {
88
+ target,
89
+ config: target.configSchema.parse({}),
90
+ provenance: { source: "default" }
91
+ };
92
+ }
93
+
94
+ export { ApiVersionMismatchError, DeployTargetNotFoundError, MissingTargetError, RegistrationError, createPluginRegistry, pluginRegistry, resolveDeployTarget };
95
+ //# sourceMappingURL=chunk-UZRY5UI2.js.map
96
+ //# sourceMappingURL=chunk-UZRY5UI2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../plugin-registry/src/errors.ts","../plugin-registry/src/internal.ts","../plugin-registry/src/deploy-handle.ts"],"names":["target"],"mappings":";AAQO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAC3C,WAAA,CAAY,MAAc,EAAA,EAAY;AACpC,IAAA,KAAA,CAAM,CAAA,GAAA,EAAM,IAAI,CAAA,kBAAA,EAAqB,EAAE,CAAA,wBAAA,CAA0B,CAAA;AACjE,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AAGO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EAC5C,WAAA,CAAY,MAAc,EAAA,EAAY;AACpC,IAAA,KAAA,CAAM,CAAA,IAAA,EAAO,IAAI,CAAA,6BAAA,EAAgC,EAAE,CAAA,EAAA,CAAI,CAAA;AACvD,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,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AM,IAAI,yBAAA,CAA0B,IAAA,CAAK,OAAO,MAAM,CAAA;AACnE,IAAA,OAAO;AAAA,MACL,MAAA,EAAAA,OAAAA;AAAA,MACA,MAAA,EAAQA,QAAO,YAAA,CAAa,KAAA,CAAM,KAAK,MAAA,CAAO,MAAA,IAAU,EAAE,CAAA;AAAA,MAC1D,UAAA,EAAY,EAAE,MAAA,EAAQ,MAAA;AAAO,KAC/B;AAAA,EACF;AACA,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,GAAA,CAAI,cAAA,EAAgB,OAAO,CAAA;AACnD,EAAA,IAAI,CAAC,MAAA,EAAQ,MAAM,IAAI,0BAA0B,OAAO,CAAA;AACxD,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,MAAA,EAAQ,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,EAAE,CAAA;AAAA,IACpC,UAAA,EAAY,EAAE,MAAA,EAAQ,SAAA;AAAU,GAClC;AACF","file":"chunk-UZRY5UI2.js","sourcesContent":["/**\n * Error types thrown by the plugin registry and deploy resolution.\n *\n * Each carries a stable `.name` so callers can branch on identity without\n * importing the class (cross-package / cross-bundle `instanceof` is unreliable).\n */\n\n/** Thrown by `register()` when a target id is already registered for its kind. */\nexport class RegistrationError extends Error {\n constructor(kind: string, id: string) {\n super(`A \"${kind}\" target with id \"${id}\" is already registered.`);\n this.name = \"RegistrationError\";\n }\n}\n\n/** Thrown when a lookup by id finds no registered target for the given kind. */\nexport class MissingTargetError extends Error {\n constructor(kind: string, id: string) {\n super(`No \"${kind}\" target registered with id \"${id}\".`);\n this.name = \"MissingTargetError\";\n }\n}\n\n/** Thrown by `register()` when a target declares an unsupported `apiVersion`. */\nexport class ApiVersionMismatchError extends Error {\n constructor(kind: string, id: string, got: unknown) {\n super(\n `Target \"${id}\" (kind \"${kind}\") declares apiVersion ${String(got)}; registry requires apiVersion 1.`,\n );\n this.name = \"ApiVersionMismatchError\";\n }\n}\n\n/** Thrown by `resolveDeployTarget()` when the requested deploy target id is unknown. */\nexport class DeployTargetNotFoundError extends Error {\n constructor(id: string) {\n super(`No deploy target registered with id \"${id}\".`);\n this.name = \"DeployTargetNotFoundError\";\n }\n}\n","/**\n * Map-backed `PluginRegistry` implementation + the process-wide singleton.\n *\n * Storage is one Map per kind. Registration rejects duplicate ids\n * (`RegistrationError`) and any target not on `apiVersion: 1`\n * (`ApiVersionMismatchError`).\n */\n\nimport { ApiVersionMismatchError, RegistrationError } from \"./errors.js\";\nimport type { PluginRegistry, Target, TargetKind, TargetMeta } from \"./registry.js\";\n\ntype AnyTarget = { id: string; displayName: string; apiVersion: unknown };\n\nclass MapPluginRegistry implements PluginRegistry {\n readonly apiVersion = 1 as const;\n\n // One Map per kind keeps lookups kind-scoped — a driver and a connector may\n // share an id without colliding.\n private readonly stores: Record<TargetKind, Map<string, AnyTarget>> = {\n driver: new Map(),\n connector: new Map(),\n deployTarget: new Map(),\n };\n\n register<K extends TargetKind>(kind: K, target: Target<K>): void {\n const t = target as unknown as AnyTarget;\n if (t.apiVersion !== 1) {\n throw new ApiVersionMismatchError(kind, t.id, t.apiVersion);\n }\n const store = this.stores[kind];\n if (store.has(t.id)) {\n throw new RegistrationError(kind, t.id);\n }\n store.set(t.id, t);\n }\n\n get<K extends TargetKind>(kind: K, id: string): Target<K> | undefined {\n return this.stores[kind].get(id) as Target<K> | undefined;\n }\n\n list<K extends TargetKind>(kind: K): readonly TargetMeta[] {\n return [...this.stores[kind].values()].map((t) => ({\n id: t.id,\n displayName: t.displayName,\n }));\n }\n}\n\n/** Create a fresh, isolated registry — used by tests so cases never share state. */\nexport function createPluginRegistry(): PluginRegistry {\n return new MapPluginRegistry();\n}\n\n/** Process-wide default registry. Built-ins and loaded plugins register here. */\nexport const pluginRegistry: PluginRegistry = createPluginRegistry();\n","/**\n * Deploy handle contract + the `resolveDeployTarget` precedence resolver.\n *\n * A `DeployHandle` is the live, restorable result of standing up a workspace on\n * a deploy target. `resolveDeployTarget` picks which target+config to use with\n * an explicit override > yaml > default chain.\n */\n\nimport { DeployTargetNotFoundError } from \"./errors.js\";\nimport { pluginRegistry } from \"./internal.js\";\nimport type { PluginRegistry } from \"./registry.js\";\nimport type { DeployTarget } from \"./targets.js\";\n\n/**\n * Live handle to a deployed workspace. `payload` is the target's own opaque\n * persistence slice (written to `.skaile/deploy/handle.json` and fed back into\n * `restore()`); the registry wrapper never inspects it.\n */\nexport interface DeployHandle<S = unknown> {\n readonly wsUrl: string;\n /** Redacted form of the auth token, safe to log. */\n readonly wsAuth?: string;\n readonly state: \"starting\" | \"ready\" | \"stopping\" | \"stopped\" | \"errored\";\n readonly payload: S;\n waitReady(timeoutMs?: number): Promise<void>;\n health(): Promise<{ healthy: boolean; detail?: string }>;\n logs?(opts?: { sinceMs?: number; follow?: boolean }): AsyncIterable<{ ts: number; line: string }>;\n stop(): Promise<void>;\n}\n\n/** Outcome of `resolveDeployTarget`: the chosen target, its parsed config, and where it came from. */\nexport interface DeployResolution {\n target: DeployTarget;\n config: unknown;\n provenance: { source: \"default\" | \"yaml\" | \"override\"; reason?: string };\n}\n\n/**\n * Resolve which deploy target + config to use, with explicit precedence:\n * CLI override > `skaile.yaml` `deploy:` block > the built-in `local` default.\n * Config is parsed through the chosen target's `configSchema`, so validation\n * failures propagate to the caller.\n */\nexport async function resolveDeployTarget(\n yaml: { deploy?: { target: string; config?: unknown } },\n override?: { target: string; config?: unknown; reason: string },\n registry: PluginRegistry = pluginRegistry,\n): Promise<DeployResolution> {\n if (override) {\n const target = registry.get(\"deployTarget\", override.target);\n if (!target) throw new DeployTargetNotFoundError(override.target);\n return {\n target,\n config: target.configSchema.parse(override.config ?? {}),\n provenance: { source: \"override\", reason: override.reason },\n };\n }\n if (yaml.deploy) {\n const target = registry.get(\"deployTarget\", yaml.deploy.target);\n if (!target) throw new DeployTargetNotFoundError(yaml.deploy.target);\n return {\n target,\n config: target.configSchema.parse(yaml.deploy.config ?? {}),\n provenance: { source: \"yaml\" },\n };\n }\n const target = registry.get(\"deployTarget\", \"local\");\n if (!target) throw new DeployTargetNotFoundError(\"local\");\n return {\n target,\n config: target.configSchema.parse({}),\n provenance: { source: \"default\" },\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { logErr } from './chunk-4NDWKA64.js';
2
- import { knowledgeKindProvider } from './chunk-BSY56QS7.js';
3
- import { createDefaultRegistry } from './chunk-4S4TZDCD.js';
2
+ import { knowledgeKindProvider } from './chunk-KA46DUM4.js';
3
+ import { createDefaultRegistry } from './chunk-SL6JVGRD.js';
4
4
  import { flowKindProvider } from './chunk-ICS76R4T.js';
5
5
 
6
6
  // cli/src/open-registry.ts
@@ -97,5 +97,5 @@ async function openLibraryManager() {
97
97
  }
98
98
 
99
99
  export { createFullRegistry, openCatalogSource, openLibrary, openLibraryManager, resolveCatalogSource };
100
- //# sourceMappingURL=chunk-NCUTHLRV.js.map
101
- //# sourceMappingURL=chunk-NCUTHLRV.js.map
100
+ //# sourceMappingURL=chunk-UZVHJ7LX.js.map
101
+ //# sourceMappingURL=chunk-UZVHJ7LX.js.map