@skaile/workspaces 1.2.0 → 1.4.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 (224) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +1 -1
  3. package/dist/app-sdk/index.d.ts +2 -0
  4. package/dist/app-sdk/index.js +295 -0
  5. package/dist/app-sdk/index.js.map +1 -0
  6. package/dist/app-sdk/src/app.d.ts +101 -0
  7. package/dist/app-sdk/src/app.d.ts.map +1 -0
  8. package/dist/app-sdk/src/define-app-capability.d.ts +139 -0
  9. package/dist/app-sdk/src/define-app-capability.d.ts.map +1 -0
  10. package/dist/app-sdk/src/index.d.ts +16 -0
  11. package/dist/app-sdk/src/index.d.ts.map +1 -0
  12. package/dist/app-sdk/src/logger.d.ts +26 -0
  13. package/dist/app-sdk/src/logger.d.ts.map +1 -0
  14. package/dist/app-sdk/src/transport.d.ts +84 -0
  15. package/dist/app-sdk/src/transport.d.ts.map +1 -0
  16. package/dist/app-sdk/src/ws-transport.d.ts +63 -0
  17. package/dist/app-sdk/src/ws-transport.d.ts.map +1 -0
  18. package/dist/{asset-feeds-OBPWVUDL.js → asset-feeds-NG5TKB3V.js} +10 -10
  19. package/dist/{asset-feeds-OBPWVUDL.js.map → asset-feeds-NG5TKB3V.js.map} +1 -1
  20. package/dist/asset-manager/index.js +9 -9
  21. package/dist/asset-manager/installer.js +8 -8
  22. package/dist/asset-manager/renderers.js +2 -2
  23. package/dist/asset-manager/src/index.d.ts +42 -6
  24. package/dist/asset-manager/src/index.d.ts.map +1 -1
  25. package/dist/bridge/drivers/claude-sdk.js +41 -6
  26. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  27. package/dist/bridge/drivers/codex.js +1 -1
  28. package/dist/bridge/drivers/continue.js +2 -2
  29. package/dist/bridge/drivers/echo.js +1 -1
  30. package/dist/bridge/drivers/gemini.js +3 -3
  31. package/dist/bridge/drivers/goose.js +2 -2
  32. package/dist/bridge/drivers/omp.js +1 -1
  33. package/dist/bridge/drivers/opencode.js +2 -2
  34. package/dist/bridge/drivers/qwen.js +3 -3
  35. package/dist/bridge/index.js +4 -3
  36. package/dist/bridge/src/cloud.d.ts +89 -0
  37. package/dist/bridge/src/cloud.d.ts.map +1 -0
  38. package/dist/bridge/src/drivers/claude-sdk.d.ts +12 -1
  39. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  40. package/dist/bridge/src/index.d.ts +1 -0
  41. package/dist/bridge/src/index.d.ts.map +1 -1
  42. package/dist/bridge/src/types.d.ts +31 -0
  43. package/dist/bridge/src/types.d.ts.map +1 -1
  44. package/dist/{chunk-MG6UIS7G.js → chunk-26YCXWCU.js} +52 -3
  45. package/dist/chunk-26YCXWCU.js.map +1 -0
  46. package/dist/{chunk-SKADPHAM.js → chunk-4N5XR5DQ.js} +2 -2
  47. package/dist/chunk-4N5XR5DQ.js.map +1 -0
  48. package/dist/{chunk-CLUJLV7Z.js → chunk-77OXU44H.js} +6 -6
  49. package/dist/{chunk-CLUJLV7Z.js.map → chunk-77OXU44H.js.map} +1 -1
  50. package/dist/{chunk-TTTLCSEQ.js → chunk-AAGD2J4H.js} +121 -41
  51. package/dist/chunk-AAGD2J4H.js.map +1 -0
  52. package/dist/{chunk-KVZ6XKVN.js → chunk-B6SSXVF2.js} +4 -4
  53. package/dist/chunk-B6SSXVF2.js.map +1 -0
  54. package/dist/{chunk-BCJL2UNH.js → chunk-BDUANIAR.js} +3 -3
  55. package/dist/{chunk-BCJL2UNH.js.map → chunk-BDUANIAR.js.map} +1 -1
  56. package/dist/{chunk-YI5OZ7QO.js → chunk-BE5KTS2L.js} +3 -3
  57. package/dist/{chunk-YI5OZ7QO.js.map → chunk-BE5KTS2L.js.map} +1 -1
  58. package/dist/{chunk-ZUE2PIJ5.js → chunk-BJHZHNKR.js} +3 -3
  59. package/dist/{chunk-ZUE2PIJ5.js.map → chunk-BJHZHNKR.js.map} +1 -1
  60. package/dist/{chunk-MQEZE6TU.js → chunk-DNFIKRO6.js} +3 -3
  61. package/dist/{chunk-MQEZE6TU.js.map → chunk-DNFIKRO6.js.map} +1 -1
  62. package/dist/{chunk-VCBLXF7D.js → chunk-GWDZW44L.js} +5 -5
  63. package/dist/{chunk-VCBLXF7D.js.map → chunk-GWDZW44L.js.map} +1 -1
  64. package/dist/{chunk-UY5Q2NZH.js → chunk-HKX5VSWQ.js} +3 -3
  65. package/dist/{chunk-UY5Q2NZH.js.map → chunk-HKX5VSWQ.js.map} +1 -1
  66. package/dist/{chunk-NUS5L5ZJ.js → chunk-HWTQ6HPO.js} +5 -5
  67. package/dist/{chunk-NUS5L5ZJ.js.map → chunk-HWTQ6HPO.js.map} +1 -1
  68. package/dist/{chunk-WRBF34YE.js → chunk-IEX5YV4R.js} +3 -3
  69. package/dist/{chunk-WRBF34YE.js.map → chunk-IEX5YV4R.js.map} +1 -1
  70. package/dist/{chunk-CU5Z7GH3.js → chunk-IRORTHGA.js} +20 -6
  71. package/dist/chunk-IRORTHGA.js.map +1 -0
  72. package/dist/chunk-ISQWMBKD.js +74 -0
  73. package/dist/chunk-ISQWMBKD.js.map +1 -0
  74. package/dist/{chunk-W65IK4MH.js → chunk-JZPEEMIM.js} +6 -6
  75. package/dist/{chunk-W65IK4MH.js.map → chunk-JZPEEMIM.js.map} +1 -1
  76. package/dist/{chunk-35TLBMHX.js → chunk-LCTRCWBK.js} +6 -6
  77. package/dist/{chunk-35TLBMHX.js.map → chunk-LCTRCWBK.js.map} +1 -1
  78. package/dist/{chunk-U5J77IIZ.js → chunk-NKTFEV7Q.js} +4 -4
  79. package/dist/{chunk-U5J77IIZ.js.map → chunk-NKTFEV7Q.js.map} +1 -1
  80. package/dist/{chunk-EPLYVB3L.js → chunk-OSCJRUKM.js} +2 -2
  81. package/dist/{chunk-EPLYVB3L.js.map → chunk-OSCJRUKM.js.map} +1 -1
  82. package/dist/{chunk-5AGARSQT.js → chunk-OUWNTFDG.js} +31 -3
  83. package/dist/chunk-OUWNTFDG.js.map +1 -0
  84. package/dist/{chunk-EVZKWY5J.js → chunk-PK7Q7MC7.js} +5 -4
  85. package/dist/chunk-PK7Q7MC7.js.map +1 -0
  86. package/dist/{chunk-XWLVIEWD.js → chunk-QM2TT2PJ.js} +20 -12
  87. package/dist/chunk-QM2TT2PJ.js.map +1 -0
  88. package/dist/{chunk-BM37QD6U.js → chunk-TJRWGMD2.js} +3 -3
  89. package/dist/{chunk-BM37QD6U.js.map → chunk-TJRWGMD2.js.map} +1 -1
  90. package/dist/{chunk-QVE3ILCY.js → chunk-TNSCHS4I.js} +2 -2
  91. package/dist/chunk-TNSCHS4I.js.map +1 -0
  92. package/dist/{chunk-Z5Z3MYDL.js → chunk-UPZGQZEJ.js} +3 -3
  93. package/dist/{chunk-Z5Z3MYDL.js.map → chunk-UPZGQZEJ.js.map} +1 -1
  94. package/dist/{chunk-52XHXSBN.js → chunk-UQ5FK2AB.js} +3 -3
  95. package/dist/{chunk-52XHXSBN.js.map → chunk-UQ5FK2AB.js.map} +1 -1
  96. package/dist/{chunk-KAWKKMU4.js → chunk-X57AMTAH.js} +74 -11
  97. package/dist/chunk-X57AMTAH.js.map +1 -0
  98. package/dist/{chunk-OIGYDVCM.js → chunk-XBG2YDQQ.js} +3 -3
  99. package/dist/{chunk-OIGYDVCM.js.map → chunk-XBG2YDQQ.js.map} +1 -1
  100. package/dist/cli/index.js +770 -188
  101. package/dist/cli/index.js.map +1 -1
  102. package/dist/cli/src/commands/preset-apply.d.ts +59 -0
  103. package/dist/cli/src/commands/preset-apply.d.ts.map +1 -0
  104. package/dist/cli/src/commands/preset-cmd.d.ts +2 -2
  105. package/dist/cli/src/commands/preset-cmd.d.ts.map +1 -1
  106. package/dist/cli/src/commands/preset-export.d.ts +93 -0
  107. package/dist/cli/src/commands/preset-export.d.ts.map +1 -0
  108. package/dist/cli/src/commands/source.d.ts.map +1 -1
  109. package/dist/cli/src/commands/why.d.ts +18 -0
  110. package/dist/cli/src/commands/why.d.ts.map +1 -1
  111. package/dist/connectors/config.js +5 -5
  112. package/dist/connectors/index.js +7 -7
  113. package/dist/core/index.js +4 -4
  114. package/dist/core/runtime-assets.js +2 -2
  115. package/dist/core/src/index.d.ts +2 -2
  116. package/dist/core/src/index.d.ts.map +1 -1
  117. package/dist/core/src/settings.d.ts +18 -0
  118. package/dist/core/src/settings.d.ts.map +1 -1
  119. package/dist/core/src/workspace-config.d.ts +45 -0
  120. package/dist/core/src/workspace-config.d.ts.map +1 -1
  121. package/dist/core/src/workspace-yaml-editor.d.ts +14 -1
  122. package/dist/core/src/workspace-yaml-editor.d.ts.map +1 -1
  123. package/dist/core/workspace-config.js +1 -1
  124. package/dist/deploy/index.js +4 -4
  125. package/dist/discovery/index.js +2 -2
  126. package/dist/{ensure-sources-BQI2TOZZ.js → ensure-sources-CHC7X7AJ.js} +12 -12
  127. package/dist/{ensure-sources-BQI2TOZZ.js.map → ensure-sources-CHC7X7AJ.js.map} +1 -1
  128. package/dist/factory-assets/connectors/box.js +7 -7
  129. package/dist/factory-assets/connectors/deploy.js +7 -7
  130. package/dist/factory-assets/connectors/devserver.js +7 -7
  131. package/dist/factory-assets/connectors/flow/adapter.js +7 -7
  132. package/dist/factory-assets/connectors/flow/engine/engine.d.ts +4 -1
  133. package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
  134. package/dist/factory-assets/connectors/flow/engine/types.d.ts +41 -6
  135. package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
  136. package/dist/factory-assets/connectors/flow/engine.js +5 -5
  137. package/dist/factory-assets/connectors/flow/run-flow.js +8 -8
  138. package/dist/factory-assets/connectors/flow.js +7 -7
  139. package/dist/factory-assets/connectors/git.js +7 -7
  140. package/dist/factory-assets/connectors/gmail.js +7 -7
  141. package/dist/factory-assets/connectors/googledrive.js +7 -7
  142. package/dist/factory-assets/connectors/local.js +7 -7
  143. package/dist/factory-assets/connectors/mattermost.js +7 -7
  144. package/dist/factory-assets/connectors/memory.js +7 -7
  145. package/dist/factory-assets/connectors/minio.js +7 -7
  146. package/dist/factory-assets/connectors/postgres.js +7 -7
  147. package/dist/factory-assets/connectors/s3.js +7 -7
  148. package/dist/factory-assets/connectors/sharepoint.js +7 -7
  149. package/dist/factory-assets/connectors/sqlite.js +7 -7
  150. package/dist/factory-assets/connectors/static-server.js +7 -7
  151. package/dist/factory-assets/connectors/tunnel.js +7 -7
  152. package/dist/factory-assets/connectors/webdav.js +7 -7
  153. package/dist/factory-assets/connectors/xstate-store.js +7 -7
  154. package/dist/factory-assets/connectors/xstate.js +7 -7
  155. package/dist/factory-assets/skills/skaile-author-asset/SKILL.md +1 -1
  156. package/dist/factory-assets/skills/skaile-manage-workspace/SKILL.md +1 -1
  157. package/dist/{flows-4Z74KY2H.js → flows-CGOCUNO6.js} +4 -4
  158. package/dist/{flows-4Z74KY2H.js.map → flows-CGOCUNO6.js.map} +1 -1
  159. package/dist/{helpers-SC4PWN2F.js → helpers-GWG4CYYC.js} +12 -12
  160. package/dist/{helpers-SC4PWN2F.js.map → helpers-GWG4CYYC.js.map} +1 -1
  161. package/dist/library/index.js +8 -8
  162. package/dist/library/install.js +4 -4
  163. package/dist/{open-library-ZNYIND7N.js → open-library-37PXN6MK.js} +17 -17
  164. package/dist/{open-library-ZNYIND7N.js.map → open-library-37PXN6MK.js.map} +1 -1
  165. package/dist/{paths-S7QNXYMB.js → paths-UVOHWUPY.js} +7 -7
  166. package/dist/{paths-S7QNXYMB.js.map → paths-UVOHWUPY.js.map} +1 -1
  167. package/dist/{plugin-store-3DAVGKHN.js → plugin-store-EIMVEH3O.js} +6 -6
  168. package/dist/{plugin-store-3DAVGKHN.js.map → plugin-store-EIMVEH3O.js.map} +1 -1
  169. package/dist/runner/index.js +14 -13
  170. package/dist/runner/src/capability-registry.d.ts +15 -4
  171. package/dist/runner/src/capability-registry.d.ts.map +1 -1
  172. package/dist/runner/src/cloud-bundle.d.ts +36 -0
  173. package/dist/runner/src/cloud-bundle.d.ts.map +1 -0
  174. package/dist/runner/src/serve.d.ts.map +1 -1
  175. package/dist/runner/src/session-builder.d.ts +32 -0
  176. package/dist/runner/src/session-builder.d.ts.map +1 -1
  177. package/dist/sdk/asset-manager.js +9 -9
  178. package/dist/sdk/bridge.js +4 -3
  179. package/dist/sdk/core.js +4 -4
  180. package/dist/sdk/flow.js +5 -5
  181. package/dist/sdk/index.js +14 -13
  182. package/dist/sdk/index.js.map +1 -1
  183. package/dist/sdk/runner.js +14 -13
  184. package/dist/sdk/session.js +2 -2
  185. package/dist/sdk/types.js +1 -1
  186. package/dist/session/index.js +2 -2
  187. package/dist/{setup-WBGDT2WY.js → setup-DINVR6ZQ.js} +10 -9
  188. package/dist/setup-DINVR6ZQ.js.map +1 -0
  189. package/dist/{source-SBFVULTG.js → source-RXAHIGMD.js} +18 -18
  190. package/dist/{source-SBFVULTG.js.map → source-RXAHIGMD.js.map} +1 -1
  191. package/dist/{store-client-YGDN4L2G.js → store-client-T3F663YG.js} +7 -7
  192. package/dist/{store-client-YGDN4L2G.js.map → store-client-T3F663YG.js.map} +1 -1
  193. package/dist/tui/index.js +14 -13
  194. package/dist/tui/index.js.map +1 -1
  195. package/dist/types/index.js +1 -1
  196. package/dist/types/manifests.js +1 -1
  197. package/dist/types/src/capabilities.d.ts +8 -2
  198. package/dist/types/src/capabilities.d.ts.map +1 -1
  199. package/dist/types/src/logging.d.ts +3 -2
  200. package/dist/types/src/logging.d.ts.map +1 -1
  201. package/dist/types/src/manifests/_shared.d.ts +4 -4
  202. package/dist/types/src/manifests/agent.d.ts +47 -8
  203. package/dist/types/src/manifests/agent.d.ts.map +1 -1
  204. package/dist/types/src/manifests/index.d.ts +3 -3
  205. package/dist/types/src/manifests/index.d.ts.map +1 -1
  206. package/dist/types/src/manifests/preset.d.ts +10 -0
  207. package/dist/types/src/manifests/preset.d.ts.map +1 -1
  208. package/dist/types/src/version.d.ts +11 -1
  209. package/dist/types/src/version.d.ts.map +1 -1
  210. package/dist/workspace-plugin/adapters/mcp.js +2 -2
  211. package/dist/workspace-plugin/adapters/omp.js +3 -3
  212. package/dist/workspace-plugin/index.js +1 -1
  213. package/package.json +7 -1
  214. package/dist/chunk-5AGARSQT.js.map +0 -1
  215. package/dist/chunk-CU5Z7GH3.js.map +0 -1
  216. package/dist/chunk-EVZKWY5J.js.map +0 -1
  217. package/dist/chunk-KAWKKMU4.js.map +0 -1
  218. package/dist/chunk-KVZ6XKVN.js.map +0 -1
  219. package/dist/chunk-MG6UIS7G.js.map +0 -1
  220. package/dist/chunk-QVE3ILCY.js.map +0 -1
  221. package/dist/chunk-SKADPHAM.js.map +0 -1
  222. package/dist/chunk-TTTLCSEQ.js.map +0 -1
  223. package/dist/chunk-XWLVIEWD.js.map +0 -1
  224. package/dist/setup-WBGDT2WY.js.map +0 -1
@@ -31,6 +31,7 @@ function isUserInvokable(cap) {
31
31
  case "flow":
32
32
  case "connector":
33
33
  case "mount":
34
+ case "app":
34
35
  return false;
35
36
  case "mcp":
36
37
  return cap.kind === "effect";
@@ -42,8 +43,8 @@ function isUserInvokable(cap) {
42
43
  }
43
44
 
44
45
  // types/src/version.ts
45
- var PROTOCOL_VERSION = { major: 3, minor: 3, patch: 0 };
46
- var PROTOCOL_VERSION_STRING = "3.3.0";
46
+ var PROTOCOL_VERSION = { major: 3, minor: 4, patch: 0 };
47
+ var PROTOCOL_VERSION_STRING = "3.4.0";
47
48
  function parseVersion(s) {
48
49
  const parts = s.split(".");
49
50
  if (parts.length !== 3) {
@@ -63,5 +64,5 @@ function formatVersion(v) {
63
64
  }
64
65
 
65
66
  export { MENTION_GROUPS, PROTOCOL_VERSION, PROTOCOL_VERSION_STRING, QUICK_REACTIONS, formatVersion, isRenderCapability, isUserInvokable, parseVersion };
66
- //# sourceMappingURL=chunk-EVZKWY5J.js.map
67
- //# sourceMappingURL=chunk-EVZKWY5J.js.map
67
+ //# sourceMappingURL=chunk-PK7Q7MC7.js.map
68
+ //# sourceMappingURL=chunk-PK7Q7MC7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../types/src/mentions.ts","../types/src/reactions.ts","../types/src/capabilities.ts","../types/src/version.ts"],"names":[],"mappings":";AAmBO,IAAM,iBAAiB,CAAC,OAAA,EAAS,QAAA,EAAU,aAAA,EAAe,QAAQ,KAAK;;;ACevE,IAAM,eAAA,GAAkB;AAAA,EAC7B,WAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,cAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;;;AC8LO,SAAS,mBAAmB,GAAA,EAA0C;AAC3E,EAAA,OAAO,IAAI,MAAA,KAAW,MAAA;AACxB;AAsCO,SAAS,gBAAgB,GAAA,EAA0B;AACxD,EAAA,IAAI,GAAA,CAAI,aAAa,MAAA,EAAW;AAC9B,IAAA,OAAO,GAAA,CAAI,QAAA,CAAS,QAAA,CAAS,MAAM,CAAA;AAAA,EACrC;AACA,EAAA,IAAI,GAAA,CAAI,kBAAkB,MAAA,EAAW;AACnC,IAAA,OAAO,GAAA,CAAI,aAAA;AAAA,EACb;AACA,EAAA,QAAQ,GAAA,CAAI,OAAO,IAAA;AAAM,IACvB,KAAK,WAAA;AAAA,IACL,KAAK,QAAA;AAAA,IACL,KAAK,OAAA;AAAA,IACL,KAAK,MAAA;AAAA,IACL,KAAK,WAAA;AAAA,IACL,KAAK,OAAA;AAAA,IACL,KAAK,KAAA;AACH,MAAA,OAAO,KAAA;AAAA,IACT,KAAK,KAAA;AACH,MAAA,OAAO,IAAI,IAAA,KAAS,QAAA;AAAA,IACtB,KAAK,OAAA;AACH,MAAA,OAAO,GAAA,CAAI,IAAA,KAAS,QAAA,IAAY,GAAA,CAAI,IAAA,KAAS,QAAA;AAAA,IAC/C;AACE,MAAA,OAAO,KAAA;AAAA;AAEb;;;ACtLO,IAAM,mBAAoC,EAAE,KAAA,EAAO,GAAG,KAAA,EAAO,CAAA,EAAG,OAAO,CAAA;AAUvE,IAAM,uBAAA,GAA0B;AAmBhC,SAAS,aAAa,CAAA,EAA4B;AACvD,EAAA,MAAM,KAAA,GAAQ,CAAA,CAAE,KAAA,CAAM,GAAG,CAAA;AACzB,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,gCAAA,CAAkC,CAAA;AAAA,EAClF;AACA,EAAA,MAAM,CAAC,GAAA,EAAK,GAAA,EAAK,GAAG,CAAA,GAAI,KAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,EAAA,IACE,CAAC,OAAO,SAAA,CAAU,KAAK,KACvB,CAAC,MAAA,CAAO,UAAU,KAAK,CAAA,IACvB,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IACvB,KAAA,GAAQ,KACR,KAAA,GAAQ,CAAA,IACR,QAAQ,CAAA,EACR;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,4CAAA,CAA8C,CAAA;AAAA,EAC9F;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAM;AAC/B;AAiBO,SAAS,cAAc,CAAA,EAA4B;AACxD,EAAA,OAAO,CAAA,EAAG,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA;AACzC","file":"chunk-PK7Q7MC7.js","sourcesContent":["/**\n * Mentions — types for @-mention support in session messages.\n *\n * A Mention records who was addressed in a message, whether a specific user\n * or a well-known group. Group mentions carry a resolved array of user IDs\n * so consumers can perform membership checks without the resolver.\n */\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\n/**\n * Well-known group mention targets as a `const` array.\n *\n * Use this for validation or exhaustive checks against `MentionGroup`.\n *\n * @docLink packages/types/messages#mention\n */\nexport const MENTION_GROUPS = [\"agent\", \"humans\", \"humans_here\", \"here\", \"all\"] as const;\n\n/**\n * A well-known group that can be `@`-mentioned: `'agent' | 'humans' | 'humans_here' | 'here' | 'all'`.\n *\n * @docLink packages/types/messages#mention\n */\nexport type MentionGroup = (typeof MENTION_GROUPS)[number];\n\n// ---------------------------------------------------------------------------\n// Mention discriminated union\n// ---------------------------------------------------------------------------\n\n/**\n * A parsed `@`-mention in a session message. Records who was addressed — either a\n * specific user or a well-known group — along with the source text position.\n *\n * Group mentions carry a resolved array of user IDs so consumers can perform\n * membership checks without needing the resolver.\n *\n * @docLink packages/types/messages#mention\n */\nexport type Mention =\n | {\n type: \"user\";\n userId: string;\n name: string;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"group\";\n group: MentionGroup;\n /** User IDs resolved at parse time (e.g. all online users for `@here`). */\n resolved: string[];\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"custom\";\n /** Consumer-defined mention kind, e.g. \"assistant\". */\n kind: string;\n /** User IDs this mention resolves to (so isMentioned works); may be empty. */\n resolved: string[];\n /** Optional consumer payload, e.g. { sessionId, ownerId }. */\n data?: Record<string, unknown>;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n };\n","/**\n * Reactions -- emoji reactions on session messages.\n *\n * Any session participant (user or agent) can react to any message.\n * Reactions are persisted in a dedicated DB model and broadcast as\n * transient events for real-time updates.\n */\n\n/**\n * A single emoji reaction on a message, set by any session participant (user or agent).\n *\n * Reactions are persisted in a dedicated DB model and broadcast as transient events\n * for real-time updates.\n *\n * @docLink packages/types/messages#reaction\n */\nexport type Reaction = {\n /** Unicode emoji character (e.g. \"thumbs up\", not \":thumbsup:\"). */\n emoji: string;\n /** ID of the user (or \"agent\" for agent reactions). */\n userId: string;\n /** Display name at reaction time (avoids extra lookups for tooltip rendering). */\n userName: string;\n /** Unix epoch milliseconds. */\n timestamp: number;\n};\n\n/**\n * Quick-access emojis shown in the reaction bar picker.\n *\n * An `as const` array of eight Unicode emoji characters in display order.\n *\n * @docLink packages/types/messages#reaction\n */\nexport const QUICK_REACTIONS = [\n \"\\u{1F44D}\",\n \"\\u{1F440}\",\n \"\\u2705\",\n \"\\u2764\\uFE0F\",\n \"\\u{1F914}\",\n \"\\u{1FAE1}\",\n \"\\u{1F44F}\",\n \"\\u{1F389}\",\n] as const;\n","/**\n * Capability layer — Protocol v2's unified registry of LLM-invokable entry points.\n *\n * A {@link Capability} is a named, schema-typed entry point that the LLM can call\n * during a session. Capabilities are registered into a per-session\n * registry by either side (host platform via `side: 'client'` or runtime via\n * `side: 'agent'`) and routed by the bridge at invocation time.\n *\n * This module defines the wire types only; the runtime registry, the\n * `defineCapability` helper, and the per-handler logger live in\n * `@skaile/workspaces/runner`.\n *\n * @see {@link MessageV2} envelope that carries capability commands and events\n * @see {@link ProtocolVersion} for the version contract\n *\n * @category Capabilities\n * @since 2.0.0\n */\n\n// ---------------------------------------------------------------------------\n// Capability shape\n// ---------------------------------------------------------------------------\n\n/**\n * Visibility scope for a capability. Determines which surfaces the capability\n * appears on and which callers can invoke it.\n *\n * - `'llm'`: registered as an LLM tool, surfaced in the `<CAPABILITIES>` system\n * prompt section. The agent driver can invoke it.\n * - `'user'`: appears in user-facing surfaces — the command palette (cmdK),\n * debug menus, capability lists.\n * - `'runtime'`: invocable only by trusted runner / platform code paths. Never\n * reaches the LLM tool list. Never reaches the command palette. Used for\n * host RPCs (`host.refresh_credential`, `host.audit`, `host.notify_user`,\n * `host.persist_compaction_attempt`) and runner RPCs (`runner.add_mount`,\n * `runner.set_log_level`, `runner.lifecycle`, ...).\n *\n * Multiple audiences are allowed (e.g. `['llm', 'user']`). The default when\n * {@link Capability.audience} is omitted is `['llm', 'user']`, preserving the\n * v2.x default visibility for capabilities that haven't migrated yet.\n *\n * @category Capabilities\n * @since 3.0.0\n * @docLink packages/types/capabilities#capability-audience\n */\nexport type CapabilityAudience = \"llm\" | \"user\" | \"runtime\";\n\n/**\n * Source of truth for who registered a capability. Used for trust enforcement\n * (the bridge rejects mismatches between registering side and origin kind)\n * and for the `capability:<origin>:<name>` log taxonomy.\n *\n * Variants:\n * - `framework`: built-in (e.g. `__capabilities.list`)\n * - `client`: host platform (e.g. `platform.react`)\n * - `agent`: self-registered by the agent runtime\n * - `flow`: injected by an active flow execution\n * - `skill`: from a skill's MCP surface\n * - `mcp`: from a generic MCP server\n * - `connector`: from a connector (e.g. `postgres.query`)\n * - `mount`: surfaced by a filesystem mount\n * - `app`: from an embedded, agent-controllable app (carries the originating\n * `appId`). Handlers run in the app itself — see {@link Capability.side} `'app'`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-origin\n */\nexport type CapabilityOrigin =\n | { kind: \"framework\" }\n | { kind: \"client\" }\n | { kind: \"agent\" }\n | { kind: \"flow\"; flowId: string }\n | { kind: \"skill\"; skillId: string }\n | { kind: \"mcp\"; serverId: string }\n | { kind: \"connector\"; connectorId: string }\n | { kind: \"mount\"; mountId: string }\n | { kind: \"app\"; appId: string };\n\n/**\n * Render contract for a capability that produces a UI surface when invoked.\n *\n * When the LLM invokes a capability whose `render` is set, the bridge emits\n * a {@link RenderInvokedEvent} carrying the capability name and props. The\n * client renders the configured `source` at the chosen `target`. Clients\n * without a render layer can fall back to the markdown `fallback` template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-spec\n */\nexport type RenderSpec = {\n /** Where the rendered component lives. */\n source: { kind: \"web-component\"; url: string; tagName: string } | { kind: \"iframe\"; url: string };\n /** Render placements supported by the component. */\n targets: (\"chat\" | \"preview\" | \"modal\" | \"input-extension\")[];\n /** Markdown template with `{{prop}}` placeholders for clients without a render layer. */\n fallback?: string;\n /** True when props may be partial during streaming. */\n streaming?: boolean;\n /** Interaction names the rendered component may fire back as state events. */\n interactions?: string[];\n};\n\n/**\n * A named, schema-typed entry point that the LLM can invoke during a session.\n *\n * Capabilities can be declared statically (via `ConfigureCommand.capabilities`)\n * or dynamically (via {@link CapabilityRegisterCommand} /\n * {@link CapabilityRegisterEvent}). They are cached for replay across\n * subscriber reconnects and session hibernation.\n *\n * @example Defining a client-side fire-and-forget tool (uses the runner's\n * `defineCapability` helper, which serializes a {@link Capability} to the wire):\n * ```ts\n * const reactTool = defineCapability({\n * name: 'platform.react',\n * description: 'Acknowledge a user message with a Unicode emoji.',\n * side: 'client',\n * origin: { kind: 'client' },\n * fireAndForget: true,\n * input: z.object({ emoji: z.string(), targetSeq: z.number().optional() }),\n * handler: async ({ emoji, targetSeq }, ctx) => { ... },\n * });\n * ```\n *\n * @see {@link RenderCapability} for capabilities that render UI components\n * @see {@link CapabilityOrigin} for who-registered-it metadata\n * @see {@link isRenderCapability} for the type-guard\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability\n */\nexport type Capability = {\n /** Unique within a session. Convention: namespaced as `<origin>.<name>` (e.g. `platform.react`, `ui.gif`). */\n name: string;\n /**\n * Human-readable label for user-facing surfaces (cmdK action palette,\n * capability menus, debug panels). Falls back to {@link Capability.name}\n * when omitted. Pure presentation — the LLM sees `name`, not `displayName`.\n */\n displayName?: string;\n /** Human/LLM-readable summary. Shown to the LLM as part of tool registration. */\n description: string;\n /** JSON Schema validating the invocation arguments. Authored as Zod, converted at register time. */\n inputSchema: Record<string, unknown>;\n /** Optional return shape. Omit for fire-and-forget effects. */\n outputSchema?: Record<string, unknown>;\n /** Where the handler runs. `client` = host platform, `agent` = runtime/skill/connector, `app` = embedded app. */\n side: \"client\" | \"agent\" | \"app\";\n /** Discriminated tag identifying who registered the capability. Used for trust enforcement and audit. */\n origin: CapabilityOrigin;\n /** Lifetime: `session` survives the whole session, `turn` is dropped at end-of-turn. */\n scope?: \"session\" | \"turn\";\n /** When true, the bridge auto-resolves with `{}` immediately and runs the handler in the background. */\n fireAndForget?: boolean;\n /** When true, the platform shows a confirm UI before dispatch and waits for {@link CapabilityApproveCommand}. */\n requiresApproval?: boolean;\n /** Documentation hint (not enforced) describing whether this is a side-effect, render, or pure query. */\n kind?: \"effect\" | \"render\" | \"query\";\n /**\n * Whether this capability should be exposed in user-facing surfaces (cmdK\n * action palette, capability menus). When omitted, the consumer applies a\n * default per-origin via {@link isUserInvokable}.\n *\n * - `true`: surface in cmdK and capability menus.\n * - `false`: hide from user surfaces (LLM-only or low-level).\n * - `undefined`: defer to {@link isUserInvokable}'s inference rules.\n *\n * @deprecated Set {@link Capability.audience} instead. `userInvokable` is\n * kept as a read-only shim for v2.x consumers and is honoured by\n * {@link isUserInvokable} when {@link Capability.audience} is absent.\n */\n userInvokable?: boolean;\n /**\n * Audience scoping for this capability. See {@link CapabilityAudience} for\n * the meaning of each value and combinations.\n *\n * When omitted, consumers treat the capability as `['llm', 'user']` (the\n * v2.x default). Host RPCs and runner RPCs MUST set this to `['runtime']`\n * so they never leak to the LLM tool list or the user-facing surfaces.\n *\n * @category Capabilities\n * @since 3.0.0\n */\n audience?: CapabilityAudience[];\n /** Appended to the system prompt's `<CAPABILITIES>` section. Use for usage hints the LLM should always see. */\n promptFragment?: string;\n /**\n * Per-capability override for how long the runner waits on the\n * `capability_result` round-trip before timing out. When omitted the\n * runner applies its default (`DEFAULT_CAPABILITY_CALL_TIMEOUT_MS`, 60s).\n *\n * Set this for capabilities that legitimately block far longer than a\n * normal tool call — e.g. `platform.ask_session` suspends the caller's\n * turn until a peer session answers, which can take minutes.\n *\n * @category Capabilities\n * @since 3.3.0\n */\n callTimeoutMs?: number;\n /** Present iff this is a render capability — see {@link RenderCapability}. */\n render?: RenderSpec;\n};\n\n/**\n * A {@link Capability} that produces a UI surface when invoked. The narrowed\n * type guarantees `render` is set, which simplifies frontend lookup.\n *\n * @see {@link isRenderCapability}\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-capability\n */\nexport type RenderCapability = Capability & { render: NonNullable<Capability[\"render\"]> };\n\n/**\n * Type-guard for {@link RenderCapability}. Use after {@link Capability}\n * lookup to narrow the type before reading `render`.\n *\n * @example\n * ```ts\n * for (const cap of registry.list()) {\n * if (isRenderCapability(cap)) console.log(cap.render.targets);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#is-render-capability\n */\nexport function isRenderCapability(cap: Capability): cap is RenderCapability {\n return cap.render !== undefined;\n}\n\n/**\n * Decide whether a capability should be surfaced in user-facing actions\n * (cmdK action palette, capability menus).\n *\n * Resolution order (first match wins):\n *\n * 1. {@link Capability.audience} is set — return `audience.includes('user')`.\n * Capabilities scoped to `'runtime'` only never appear in user surfaces.\n * 2. {@link Capability.userInvokable} is set (v2.x shim) — return that value.\n * 3. Default per-origin inference table below.\n *\n * Default-inference rules (when both `audience` and `userInvokable` are\n * omitted):\n * | Origin | Default |\n * | ------------ | ---------------------------------------------------------------------- |\n * | `framework` | `false` (LLM discovery surfaces, e.g. `__capabilities.list`) |\n * | `client` | `false` (platform ack tools — `platform.react`, `platform.pass`) |\n * | `agent` | `false` (agent-defined; assume internal unless flagged) |\n * | `flow` | `false` (per-cap opt-in) |\n * | `connector` | `false` (low-level FS / data ops) |\n * | `mount` | `false` (low-level FS ops) |\n * | `app` | `false` (LLM-only; app authors opt in via `audience: ['llm','user']`) |\n * | `mcp` | `true` if `kind === 'effect'`, else `false` |\n * | `skill` | `true` if `kind` ∈ {`effect`, `render`}, else `false` |\n *\n * @example\n * ```ts\n * for (const cap of capabilities.values()) {\n * if (isUserInvokable(cap)) registerCommandPaletteAction(cap);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.1.0\n * @docLink packages/types/capabilities#is-user-invokable\n */\nexport function isUserInvokable(cap: Capability): boolean {\n if (cap.audience !== undefined) {\n return cap.audience.includes(\"user\");\n }\n if (cap.userInvokable !== undefined) {\n return cap.userInvokable;\n }\n switch (cap.origin.kind) {\n case \"framework\":\n case \"client\":\n case \"agent\":\n case \"flow\":\n case \"connector\":\n case \"mount\":\n case \"app\":\n return false;\n case \"mcp\":\n return cap.kind === \"effect\";\n case \"skill\":\n return cap.kind === \"effect\" || cap.kind === \"render\";\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Capability commands (client → agent)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (client → agent).\n *\n * The platform sends this when a new client-side tool becomes available\n * after `configure` has already returned (e.g. a user installs a new\n * extension during the session).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-command\n */\nexport type CapabilityRegisterCommand = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (client → agent). Names that are not\n * currently registered are ignored silently.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-command\n */\nexport type CapabilityDeregisterCommand = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Return the result of a previously {@link CapabilityInvokedEvent | invoked} client-side\n * capability (client → agent). Bridges that registered the capability with\n * `fireAndForget: true` MAY skip this command; the bridge auto-resolves with `{}`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-result-command\n */\nexport type CapabilityResultCommand = {\n type: \"capability_result\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** Successful result payload, or an error envelope. */\n result: unknown | { error: string };\n};\n\n/**\n * Approve or reject a capability call that was invoked with\n * `requiresApproval: true` (client → agent). The platform shows a confirm\n * UI and forwards the user's decision via this command.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-approve-command\n */\nexport type CapabilityApproveCommand = {\n type: \"capability_approve\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** User's decision. */\n decision: \"approved\" | \"rejected\";\n /** Optional rationale stored alongside the decision for audit. */\n feedback?: string;\n /** User ID of the decider (informational — framework enforces no policy). */\n decidedBy: string;\n};\n\n// ---------------------------------------------------------------------------\n// Capability events (agent → client)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (agent → client). Mirrors\n * {@link CapabilityRegisterCommand} for the agent-initiated direction; used\n * when the runtime adds a capability after `configure` (e.g. when a flow\n * starts and injects flow-scoped tools).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-event\n */\nexport type CapabilityRegisterEvent = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (agent → client).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-event\n */\nexport type CapabilityDeregisterEvent = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Notify the client that a capability has been invoked by the LLM (agent →\n * client). For client-side capabilities the platform's handler runs in\n * response to this event and replies with {@link CapabilityResultCommand}.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-invoked-event\n */\nexport type CapabilityInvokedEvent = {\n type: \"capability_invoked\";\n /** Correlation token for the eventual {@link CapabilityResultCommand}. */\n callId: string;\n /** Name of the invoked {@link Capability}. */\n name: string;\n /** Validated input payload (already conforms to the capability's `inputSchema`). */\n input: unknown;\n /** In v2.0.0 the LLM is the only invoker. */\n invokedBy: \"agent\";\n};\n\n/**\n * Notify the client that a render capability should be drawn (agent →\n * client). Emitted alongside {@link CapabilityInvokedEvent} when the\n * invoked capability's `render` block is populated.\n *\n * Clients without a render layer can fall back to the capability's\n * `render.fallback` markdown template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-invoked-event\n */\nexport type RenderInvokedEvent = {\n type: \"render_invoked\";\n /** Name of the invoked render capability. */\n capabilityName: string;\n /** Props passed to the rendered component (already conforms to `inputSchema`). */\n props: unknown;\n /** Correlation token shared with the matching {@link CapabilityInvokedEvent}. */\n callId: string;\n};\n","/**\n * Protocol versioning primitives for Skaile Agent Protocol v2.\n *\n * The protocol is versioned by a structured {@link ProtocolVersion} record\n * (`major.minor.patch`). The compatibility rule applied at handshake is\n * **major-equality**: a runner emits {@link IncompatibleProtocolEvent} and\n * shuts down when its declared major does not match the platform's announced\n * major. Minor and patch differences ride through transparently because\n * unknown fields are preserved on round-trip (see `MessageMeta` round-trip\n * contract in `messaging.ts`).\n *\n * @category Protocol\n * @since 2.0.0\n */\n\n/**\n * Structured semantic version triple for the agent protocol.\n *\n * @example\n * ```ts\n * const v: ProtocolVersion = { major: 2, minor: 0, patch: 0 };\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#protocol-version\n */\nexport type ProtocolVersion = {\n /** Incremented on breaking wire-format changes (field removed, semantics changed, required field added). */\n major: number;\n /** Incremented on additive wire-format changes (new optional fields, new event types). */\n minor: number;\n /** Incremented on bug-fix or doc-only changes that do not affect the wire. */\n patch: number;\n};\n\n/**\n * The protocol version the framework currently speaks. Runners and platforms\n * compare this against the peer's announced version at session boot via\n * `SessionInitCommand.protocolVersion`.\n *\n * @example\n * ```ts\n * import { PROTOCOL_VERSION } from '@skaile/workspaces/types';\n * if (cmd.protocolVersion.major !== PROTOCOL_VERSION.major) {\n * emit({ type: 'incompatible_protocol', agentVersion: PROTOCOL_VERSION, platformVersion: cmd.protocolVersion });\n * }\n * ```\n *\n * @category Protocol\n * @since 3.0.0\n *\n * Changed in 3.4.0:\n * Additive embedded-app capability source. `CapabilityOrigin` gains a\n * `{ kind: 'app'; appId: string }` variant and `Capability.side` gains `'app'`\n * (\"the handler runs in the embedded app\"). Both are additive: a peer that does\n * not understand `origin:'app'` / `side:'app'` never produces or routes them, so\n * they ride through transparently under the major-equality rule. No new message\n * types — `capability_register` / `capability_invoked` / `capability_result` /\n * `capability_approve` / `render_invoked` are reused verbatim. Spec:\n * `_devlog/specs/2026-07-07-app-capability-source.md`.\n *\n * Changed in 3.3.0:\n * Additive agent-to-agent (session-to-session) communication extension.\n * `AgentEvent` gains an `a2a_message` variant carrying cross-session messages\n * (`direction`, `peerSessionId`, `peerName`, `exchangeId`, `text`). `Capability`\n * gains an optional `callTimeoutMs?: number` so a long-running capability call\n * (e.g. a 5-minute `platform.ask_session`) can exceed the default capability-call\n * timeout. Both are additive: a peer that does not understand them ignores the\n * event / falls back to the default timeout, so they ride through transparently\n * under the major-equality rule.\n *\n * Changed in 3.2.0:\n * Additive wake-time resume cascade. `AgentReconfigureOptions` gains optional\n * `resumeSessionId` and `expectedCapabilitySignature` fields driving the tier-1\n * native SDK resume path; `AgentEvent` gains `ResumeAttemptedEvent` and\n * `ResumeFailedEvent`. `FinishedEvent` gains optional `customType` /\n * `customData` for capability-routed custom payloads. All additive — clients\n * that omit the resume hint or ignore the new events keep working unchanged.\n *\n * Changed in 3.1.0:\n * Additive cost / token usage extension. `FinishedEvent` gains an optional\n * `tokens?: TokenUsage` field carrying per-turn input / output / cache-read /\n * cache-creation / reasoning token counts. `AgentDriver.getTokenUsage()` is\n * widened to return the same `TokenUsage` shape (existing consumers reading\n * `inputTokens` / `outputTokens` keep working unchanged). Drivers that do not\n * surface token usage continue to return `null` / omit the field.\n *\n * Changed in 3.0.0:\n * Major bump for the deterministic session bootstrap rewrite. `ConfigureCommandV2`,\n * `provision_secrets`, `request_access_token`, `add_resource`, `remove_resource`,\n * `set_log_level`, `state_action`, `lifecycle`, `remount_mount`, `compact`, and\n * `reconfigure_agent` are removed from the `AgentCommand` union. Their semantics\n * are reachable through:\n * - `session_init` (one deterministic envelope at session start that delivers\n * identity, resolved config, pre-minted credentials, secrets, capabilities,\n * shared state, active flows, resume hints, and logging config),\n * - `host.refresh_credential` (capability invocation that replaces the\n * refresh-on-401 path of `request_access_token`), and\n * - `runner.*` capabilities (`runner.add_mount`, `runner.add_connector`,\n * `runner.remove_resource`, `runner.update_credential`, `runner.set_log_level`,\n * `runner.set_state`, `runner.lifecycle`) invoked by the platform via the\n * bidirectional capability registry.\n *\n * Capabilities gain an `audience: ('llm' | 'user' | 'runtime')[]` field that\n * scopes visibility: host RPCs (`host.*`) and runner RPCs (`runner.*`) are\n * `['runtime']` and never reach the LLM tool list or the user-facing command\n * palette. v2.x capabilities without an explicit `audience` default to\n * `['llm', 'user']`, preserving prior behaviour.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 3, minor: 4, patch: 0 };\n\n/**\n * String form of {@link PROTOCOL_VERSION}, kept in lock-step. Useful for\n * `package.json` version fields and HTTP `User-Agent` strings.\n *\n * @category Protocol\n * @since 3.0.0\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION_STRING = \"3.4.0\";\n\n/**\n * Parse a `\"major.minor.patch\"` string into a {@link ProtocolVersion}.\n *\n * @param s - the version string to parse, exactly three dot-separated non-negative integers\n * @returns the parsed protocol version\n * @throws {Error} if the string is not exactly three dot-separated non-negative integers\n *\n * @example\n * ```ts\n * parseVersion('2.0.0'); // { major: 2, minor: 0, patch: 0 }\n * parseVersion('2.1'); // throws\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#parse-version\n */\nexport function parseVersion(s: string): ProtocolVersion {\n const parts = s.split(\".\");\n if (parts.length !== 3) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (expected \"major.minor.patch\")`);\n }\n const [maj, min, pat] = parts;\n const major = Number(maj);\n const minor = Number(min);\n const patch = Number(pat);\n if (\n !Number.isInteger(major) ||\n !Number.isInteger(minor) ||\n !Number.isInteger(patch) ||\n major < 0 ||\n minor < 0 ||\n patch < 0\n ) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (each part must be a non-negative integer)`);\n }\n return { major, minor, patch };\n}\n\n/**\n * Format a {@link ProtocolVersion} record into its `\"major.minor.patch\"` string form.\n *\n * @param v - the protocol version to format\n * @returns the dot-joined string form\n *\n * @example\n * ```ts\n * formatVersion({ major: 2, minor: 0, patch: 0 }); // '2.0.0'\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#format-version\n */\nexport function formatVersion(v: ProtocolVersion): string {\n return `${v.major}.${v.minor}.${v.patch}`;\n}\n"]}
@@ -1,10 +1,10 @@
1
- import { openLibraryManager, createFullRegistry } from './chunk-CLUJLV7Z.js';
2
- import { logInfo, logWarn, logErr, logOk, S } from './chunk-MQEZE6TU.js';
3
- import { LocalCatalogSource } from './chunk-NUS5L5ZJ.js';
4
- import { WorkspaceYamlEditor } from './chunk-MG6UIS7G.js';
5
- import { getGlobalCacheDir, sourceCacheKey, sourceShortName, findWorkspaceRoot, workspaceConfigFilename } from './chunk-5AGARSQT.js';
1
+ import { openLibraryManager, createFullRegistry } from './chunk-77OXU44H.js';
2
+ import { logInfo, logWarn, logErr, logOk, S } from './chunk-DNFIKRO6.js';
3
+ import { LocalCatalogSource } from './chunk-HWTQ6HPO.js';
4
+ import { WorkspaceYamlEditor } from './chunk-26YCXWCU.js';
5
+ import { getGlobalCacheDir, sourceCacheKey, sourceShortName, findWorkspaceRoot, workspaceConfigFilename } from './chunk-OUWNTFDG.js';
6
6
  import { spawnSync } from 'child_process';
7
- import { existsSync, mkdirSync, rmSync } from 'fs';
7
+ import { existsSync, mkdirSync, rmSync, renameSync } from 'fs';
8
8
  import * as path from 'path';
9
9
  import * as p from '@clack/prompts';
10
10
  import { Command } from 'commander';
@@ -81,18 +81,26 @@ function readProjectSources(yamlPath) {
81
81
  }
82
82
  function ensureClone(entry, opts = {}) {
83
83
  const dest = sourceClonePath(sourceCacheKey(entry.url));
84
+ let backup;
84
85
  if (existsSync(dest)) {
85
86
  if (!opts.force) return false;
86
- rmSync(dest, { recursive: true, force: true });
87
+ backup = `${dest}.bak`;
88
+ rmSync(backup, { recursive: true, force: true });
89
+ renameSync(dest, backup);
87
90
  }
88
91
  mkdirSync(path.dirname(dest), { recursive: true });
89
92
  const args = ["clone", entry.url, dest];
90
93
  if (entry.pin) args.splice(1, 0, "--branch", entry.pin);
91
94
  const clone = spawnSync("git", args, { stdio: "inherit" });
92
95
  if (clone.status !== 0) {
96
+ if (backup) {
97
+ rmSync(dest, { recursive: true, force: true });
98
+ renameSync(backup, dest);
99
+ }
93
100
  logErr(`git clone failed for ${entry.url}`);
94
101
  process.exit(1);
95
102
  }
103
+ if (backup) rmSync(backup, { recursive: true, force: true });
96
104
  return true;
97
105
  }
98
106
  async function refreshManifestCache(entry, includeDev = false) {
@@ -204,9 +212,6 @@ function makeSourceCommand() {
204
212
  const slug = sourceShortName(url);
205
213
  const entry = { url };
206
214
  if (pin) entry.pin = pin;
207
- const editor = WorkspaceYamlEditor.load(yamlPath);
208
- editor.setSource(entry);
209
- editor.save();
210
215
  const dest = sourceClonePath(sourceCacheKey(url));
211
216
  const preexisting = existsSync(dest);
212
217
  const cloned = ensureClone(entry, { force: opts.force });
@@ -217,6 +222,9 @@ function makeSourceCommand() {
217
222
  } else {
218
223
  logOk(`Cloned ${url} \u2192 ${dest}`);
219
224
  }
225
+ const editor = WorkspaceYamlEditor.load(yamlPath);
226
+ editor.setSource(entry);
227
+ editor.save();
220
228
  const result = await refreshManifestCache(entry, opts.dev);
221
229
  const failed = indexingHadFailures(result);
222
230
  const indexedMsg = `Indexed ${result.assetsUpdated} of ${result.assetsFound} asset(s) from "${slug}".`;
@@ -373,5 +381,5 @@ function makeSourceCommand() {
373
381
  }
374
382
 
375
383
  export { autoSyncForSearch, findCacheKeyCollision, indexingHadFailures, legacySourceConfigHint, makeSourceCommand, normalizeSourceUrl, sourceClonePath, sourceMatchesKey, syncProjectSources };
376
- //# sourceMappingURL=chunk-XWLVIEWD.js.map
377
- //# sourceMappingURL=chunk-XWLVIEWD.js.map
384
+ //# sourceMappingURL=chunk-QM2TT2PJ.js.map
385
+ //# sourceMappingURL=chunk-QM2TT2PJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources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,MAAA,MAAM,UAAA,GAAa,uBAAuB,IAAI,CAAA;AAC9C,MAAA,IAAI,YAAY,OAAA,CAAQ,CAAA,EAAG,IAAI,CAAA,EAAA,EAAK,UAAU,CAAA,CAAE,CAAA;AAAA,IAClD;AAAA,EACF,CAAC,CAAA;AAGH,EAAA,GAAA,CACG,OAAA,CAAQ,aAAa,CAAA,CACrB,WAAA,CAAY,iDAAiD,CAAA,CAC7D,MAAA,CAAO,CAAC,IAAA,KAAiB;AACxB,IAAA,MAAA;AAAA,MACE;AAAA,KAEF;AACA,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB,CAAC,CAAA;AAEH,EAAA,GAAA,CACG,OAAA,CAAQ,eAAe,CAAA,CACvB,WAAA,CAAY,sDAAsD,CAAA,CAClE,MAAA,CAAO,CAAC,IAAA,KAAiB;AACxB,IAAA,MAAA;AAAA,MACE;AAAA,KAEF;AACA,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB,CAAC,CAAA;AAGH,EAAA,yBAAA,CAA0B,GAAG,CAAA;AAE7B,EAAA,OAAO,GAAA;AACT","file":"chunk-QM2TT2PJ.js","sourcesContent":["/**\n * `skaile source manifest …` — sidecar manifest lifecycle, refactored under\n * the `source` noun (was `source sidecar …`).\n *\n * The verbs are stubs for now — the real wiring lands when the publish path\n * through `POST /sources/<id>/manifest` is finalised on the store backend.\n * Each subcommand exits with code 2 plus a clear \"not yet wired\" hint so\n * smoke tests can verify the surface without depending on the server.\n *\n * @docLink cli/commands/source#manifest\n */\n\nimport type { Command } from \"commander\";\nimport { logErr } from \"../helpers.ts\";\n\nconst NOT_WIRED_MSG =\n \"`skaile source manifest *` is scaffolded but not yet wired. \" +\n \"Server-side endpoint (`POST /sources/<id>/manifest`) lands in a follow-up PR.\";\n\nfunction notWired(verb: string): never {\n logErr(`${NOT_WIRED_MSG} (verb: source manifest ${verb})`);\n process.exit(2);\n}\n\n/**\n * Append the `manifest` sub-tree to a `source` command.\n *\n * Called from `makeSourceCommand()` in `source.ts`.\n */\nexport function addSourceManifestCommands(src: Command): void {\n const manifest = src.command(\"manifest\").description(\"Sidecar manifest lifecycle for a source\");\n\n manifest\n .command(\"init <src>\")\n .description(\"Start a sidecar manifest for a source\")\n .action(() => notWired(\"init\"));\n\n manifest\n .command(\"edit <src>\")\n .description(\"Open the sidecar manifest in $EDITOR\")\n .action(() => notWired(\"edit\"));\n\n manifest\n .command(\"rebuild <src>\")\n .description(\"Re-derive the manifest after an upstream change\")\n .option(\"--merge\", \"Merge with existing entries instead of overwriting\", false)\n .action(() => notWired(\"rebuild\"));\n\n manifest\n .command(\"verify <src>\")\n .description(\"Verify hashes, deps, and schema\")\n .option(\"--strict\", \"Fail on advisory checks\", false)\n .action(() => notWired(\"verify\"));\n\n manifest\n .command(\"publish <src>\")\n .description(\"Register the manifest in the store (provenance=curator)\")\n .action(() => notWired(\"publish\"));\n\n manifest\n .command(\"propose <src>\")\n .description(\"Open a PR to upstream with the sidecar manifest\")\n .action(() => notWired(\"propose\"));\n\n manifest\n .command(\"yank <src>\")\n .description(\"Retract a published manifest from the remote store\")\n .option(\"--version <v>\", \"Version to yank\")\n .action(() => notWired(\"yank\"));\n}\n","/**\n * `skaile source …` — manage github sources for the current project.\n *\n * A *source* is a third-party github repo of AI assets. The project's\n * `skaile.yaml` `sources:` array is the source of truth for which sources\n * this project uses. The clone itself lives at\n * `~/.skaile/cache/sources/<host>/<owner>/<repo>/` (machine-global cache, shared\n * across projects, URL-keyed so cross-org repos never collide), and the manifest is\n * mirrored into `~/.skaile/index.db` (machine-global manifest cache).\n *\n * @docLink cli/commands/source\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n findWorkspaceRoot,\n getGlobalCacheDir,\n type SourceEntry,\n sourceCacheKey,\n sourceShortName,\n WorkspaceYamlEditor,\n workspaceConfigFilename,\n} from \"@skaile/workspaces/core\";\nimport { LocalCatalogSource } from \"@skaile/workspaces/library\";\nimport * as p from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { openLibraryManager } from \"../open-library.ts\";\nimport { createFullRegistry } from \"../open-registry.ts\";\nimport { addSourceManifestCommands } from \"./source-manifest.ts\";\n\n/**\n * Clone dir for one source cache key (`<host>/<owner>/<repo>`). Exported for the\n * cache-path regression test. Callers pass `sourceCacheKey(url)`.\n */\nexport function sourceClonePath(key: string): string {\n return path.join(getGlobalCacheDir(), key);\n}\n\nconst SKAILE_MANIFEST_FILENAME = \"skaile.manifest.yaml\";\nconst LEGACY_SOURCE_CONFIG_FILENAME = \".skaile-source.yaml\";\n\n/**\n * Whether a manifest-cache refresh actually failed to index something. Keyed on\n * `errors`, NOT on `assetsUpdated < assetsFound`: the discovery walk counts\n * presets (and other intentionally-not-cataloged kinds) toward `assetsFound` but\n * never upserts them, so a source shipping a `.preset.yaml` would otherwise read\n * as a partial failure — false `! N asset(s) failed to index` + exit 1 — with\n * zero real errors.\n */\nexport function indexingHadFailures(result: { errors: string[] }): boolean {\n return result.errors.length > 0;\n}\n\n/**\n * A clone that ships only the legacy `.skaile-source.yaml` (no\n * `skaile.manifest.yaml`) has its declared `publisher_default` silently ignored\n * — discovery only reads `skaile.manifest.yaml`, so publisher resolution falls\n * back to the first path segment. Surface a hint so the author can fix it.\n */\nexport function legacySourceConfigHint(dest: string): string | undefined {\n const hasLegacy = existsSync(path.join(dest, LEGACY_SOURCE_CONFIG_FILENAME));\n const hasManifest = existsSync(path.join(dest, SKAILE_MANIFEST_FILENAME));\n if (hasLegacy && !hasManifest) {\n return (\n `This source ships a legacy ${LEGACY_SOURCE_CONFIG_FILENAME} but no ` +\n `${SKAILE_MANIFEST_FILENAME}; its declared publisher is ignored and assets ` +\n `are published under their first path segment. Add a ${SKAILE_MANIFEST_FILENAME} ` +\n `(\\`skaile source manifest init\\`) to set the publisher and asset inventory.`\n );\n }\n return undefined;\n}\n\n/**\n * Normalize a `source add` argument into a clonable git URL. Full URLs and\n * scp-style (`git@host:…`) specs pass through unchanged; an `owner/repo`\n * shorthand and a bare repo name expand to GitHub over SSH — a bare name\n * defaults to the `skaile-ai` org (`git@github.com:skaile-ai/<name>.git`).\n */\nexport function normalizeSourceUrl(input: string): string {\n const s = input.trim();\n if (/^(?:https?|git|ssh|file):\\/\\//.test(s) || /^git@/.test(s)) return s;\n const repo = s.replace(/\\.git$/, \"\");\n if (/^[\\w.-]+\\/[\\w.-]+$/.test(repo)) return `git@github.com:${repo}.git`;\n if (/^[\\w.-]+$/.test(repo)) return `git@github.com:skaile-ai/${repo}.git`;\n return s;\n}\n\n/**\n * Match a stored source against a user-supplied key. Mirrors the shortcut\n * expansion `source add` applies (`normalizeSourceUrl`) so any form that `add`\n * accepted — bare name, `owner/repo`, `.git`-suffixed, full URL — also resolves\n * at `sync`/`show`/`remove` time, not just the raw stored URL or derived slug.\n */\nexport function sourceMatchesKey(entry: SourceEntry, key: string): boolean {\n if (entry.url === key) return true;\n if (sourceCacheKey(entry.url) === key || sourceShortName(entry.url) === key) return true;\n return entry.url === normalizeSourceUrl(key);\n}\n\n/**\n * Find an already-registered source that maps to the same cache key as `url`\n * but is stored under a *different* URL string (e.g. the `.git`-suffixed or\n * scp form of the same remote). Two such entries would fight over one clone\n * dir, so `source add` rejects the ambiguity. Returns the colliding entry, or\n * `undefined` when the URL is unique or only matches an exact-string duplicate\n * (which `setSource` updates in place).\n */\nexport function findCacheKeyCollision(\n sources: SourceEntry[],\n url: string,\n): SourceEntry | undefined {\n const key = sourceCacheKey(url);\n return sources.find((s) => s.url !== url && sourceCacheKey(s.url) === key);\n}\n\nfunction requireProjectYamlPath(): string {\n const root = findWorkspaceRoot(process.cwd());\n if (!root) {\n logErr(\n \"No skaile.yaml found in the current directory or any parent. \" + \"Run `skaile init` first.\",\n );\n process.exit(1);\n }\n return path.join(root, workspaceConfigFilename());\n}\n\nfunction readProjectSources(yamlPath: string): SourceEntry[] {\n if (!existsSync(yamlPath)) return [];\n try {\n return WorkspaceYamlEditor.load(yamlPath).getSources();\n } catch (err) {\n logErr(`Could not read ${yamlPath}: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n}\n\n/**\n * Clone the source if its clone directory does not yet exist. When `force` is\n * set, the existing clone is replaced by a fresh checkout. Returns true when a\n * clone happened. The cache slug is derived from the URL.\n *\n * A `--force` re-clone moves the old clone aside first and only deletes it once\n * the fresh clone succeeds — so a failed re-clone restores the previous clone\n * rather than leaving the source registered with no cache behind it.\n */\nfunction ensureClone(entry: SourceEntry, opts: { force?: boolean } = {}): boolean {\n const dest = sourceClonePath(sourceCacheKey(entry.url));\n let backup: string | undefined;\n if (existsSync(dest)) {\n if (!opts.force) return false;\n backup = `${dest}.bak`;\n rmSync(backup, { recursive: true, force: true });\n renameSync(dest, backup);\n }\n mkdirSync(path.dirname(dest), { recursive: true });\n const args = [\"clone\", entry.url, dest];\n // `pin` may be a branch/tag; pass it as the clone branch when present.\n if (entry.pin) args.splice(1, 0, \"--branch\", entry.pin);\n const clone = spawnSync(\"git\", args, { stdio: \"inherit\" });\n if (clone.status !== 0) {\n if (backup) {\n rmSync(dest, { recursive: true, force: true });\n renameSync(backup, dest);\n }\n logErr(`git clone failed for ${entry.url}`);\n process.exit(1);\n }\n if (backup) rmSync(backup, { recursive: true, force: true });\n return true;\n}\n\n/**\n * Refresh the machine-global manifest cache for `entry` by running discovery\n * and upserting AssetDefinitions into `~/.skaile/index.db`. Creates the\n * libraries-table cache row if missing (ownership: reader = cache state).\n */\nasync function refreshManifestCache(\n entry: SourceEntry,\n includeDev = false,\n): Promise<{\n assetsFound: number;\n assetsUpdated: number;\n errors: string[];\n}> {\n const { manager, library, close } = await openLibraryManager();\n try {\n const name = sourceShortName(entry.url);\n const dest = sourceClonePath(sourceCacheKey(entry.url));\n const existing = (await manager.listLibraries()).find((l) => l.name === name);\n const lib =\n existing ??\n (await manager.addLibrary({\n name,\n path: dest,\n backend: \"git\",\n backendConfig: { url: entry.url, branch: entry.pin ?? \"main\", authHint: \"ssh\" },\n ownership: \"reader\",\n }));\n const catalog = new LocalCatalogSource(library, lib.id, dest, createFullRegistry());\n const result = await catalog.sync({ includeDev });\n await library.syncSource(lib.id);\n return result;\n } finally {\n close();\n }\n}\n\n/**\n * Auto-sync hook for `skaile search` on an unsynced workspace. Clones/pulls and\n * re-indexes every source declared in the project's `skaile.yaml`, then returns\n * whether the manifest cache may have changed (caller re-queries on `true`).\n *\n * Unlike `source sync`, this degrades gracefully — a clone/pull/index failure is\n * logged and skipped (never `process.exit`) so a failed auto-sync falls back to\n * the \"run sync first\" hint rather than killing the search. Returns `false`\n * (silently, no announce) when no sources are declared. Callers must guard\n * air-gapped mode themselves — this always touches the network.\n */\nexport async function autoSyncForSearch(projectDir: string): Promise<boolean> {\n const root = findWorkspaceRoot(projectDir);\n if (!root) return false;\n if (readProjectSources(path.join(root, workspaceConfigFilename())).length === 0) return false;\n\n logInfo(\"sources not synced — syncing now…\");\n const { synced } = await syncProjectSources(projectDir);\n return synced > 0;\n}\n\n/**\n * Clone-or-pull every source declared in the project's `skaile.yaml`, then\n * refresh its manifest cache. Shared by `autoSyncForSearch` and `skaile update`\n * (the latter offers it behind a confirm) so a re-deploy can see upstream\n * commits — `update` re-deploys against the local source cache, which is\n * otherwise frozen at the commit captured when the source was first cloned.\n *\n * Graceful by design: a clone/pull/index failure for one source is logged and\n * skipped (never `process.exit`), so a single bad remote can't abort the run.\n * Existing clones are advanced with `git pull --ff-only` (no `--depth=1`, unlike\n * the installer's `pullRepo`, so it fast-forwards instead of tripping the\n * shallow-divergence path). Returns a count summary for the caller to report.\n */\nexport async function syncProjectSources(\n projectDir: string,\n opts: { dev?: boolean } = {},\n): Promise<{ total: number; synced: number; failed: number }> {\n const root = findWorkspaceRoot(projectDir) ?? projectDir;\n const sources = readProjectSources(path.join(root, workspaceConfigFilename()));\n let synced = 0;\n let failed = 0;\n for (const entry of sources) {\n const slug = sourceShortName(entry.url);\n const dest = sourceClonePath(sourceCacheKey(entry.url));\n try {\n // Quiet git — the sync is a preparatory step; keep progress bars out of\n // the foreground output (spinner / install result).\n if (!existsSync(dest)) {\n mkdirSync(path.dirname(dest), { recursive: true });\n const args = [\"clone\", entry.url, dest];\n if (entry.pin) args.splice(1, 0, \"--branch\", entry.pin);\n const clone = spawnSync(\"git\", args, { stdio: \"ignore\" });\n if (clone.status !== 0) {\n logWarn(`${slug}: git clone failed, skipping.`);\n failed++;\n continue;\n }\n } else {\n const pull = spawnSync(\"git\", [\"pull\", \"--ff-only\"], { cwd: dest, stdio: \"ignore\" });\n if (pull.status !== 0) {\n logWarn(`${slug}: git pull failed, skipping manifest refresh.`);\n failed++;\n continue;\n }\n }\n const result = await refreshManifestCache(entry, opts.dev);\n for (const err of result.errors) logWarn(`${slug}: ${err}`);\n synced++;\n } catch (err) {\n logWarn(`${slug}: sync failed — ${err instanceof Error ? err.message : String(err)}`);\n failed++;\n }\n }\n return { total: sources.length, synced, failed };\n}\n\n/** Remove the libraries-table cache row and (optionally) the clone bytes. */\nasync function dropManifestCache(url: string, purgeClone: boolean): Promise<void> {\n const name = sourceShortName(url);\n const { manager, close } = await openLibraryManager();\n try {\n const existing = (await manager.listLibraries()).find((l) => l.name === name);\n if (existing) {\n await manager.removeLibrary(name, { purge: false });\n }\n } finally {\n close();\n }\n if (purgeClone) {\n const dest = sourceClonePath(sourceCacheKey(url));\n if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });\n }\n}\n\nexport function makeSourceCommand(): Command {\n const cmd = new Command(\"source\").description(\n \"Manage github sources for the current project (recorded in skaile.yaml)\",\n );\n\n // ── source add ──────────────────────────────────────────────────────────\n cmd\n .command(\"add <source>\")\n .description(\n \"Clone a github repo and register it in this project's skaile.yaml. \" +\n \"<source> may be a full git URL, an owner/repo shorthand, or a bare \" +\n \"name (→ git@github.com:skaile-ai/<name>.git).\",\n )\n .option(\"--name <slug>\", \"[deprecated] no-op — the source entry stores only the URL\")\n .option(\"--pin <ref>\", \"Pin a branch, tag, or 40-char SHA\")\n .option(\"--branch <branch>\", \"[deprecated] alias for --pin\")\n .option(\"--force\", \"Remove an existing clone and re-clone\", false)\n .option(\"--dev\", \"Also index dev-only assets under the source's dev_paths\", false)\n .action(\n async (\n source: string,\n opts: {\n name?: string;\n pin?: string;\n branch?: string;\n force?: boolean;\n dev?: boolean;\n },\n ) => {\n const url = normalizeSourceUrl(source);\n const yamlPath = requireProjectYamlPath();\n\n // A different URL string that maps to the same cache key (e.g. the\n // `.git`-suffixed or scp form of an already-registered remote) would\n // fight over one clone dir. setSource only dedupes exact strings, so\n // reject the ambiguous collision here instead of silently shadowing.\n const collision = findCacheKeyCollision(readProjectSources(yamlPath), url);\n if (collision) {\n logErr(\n `\"${url}\" maps to the same cache key (${sourceCacheKey(url)}) as ` +\n `already-registered \"${collision.url}\". Remove that source first ` +\n `(skaile source remove) or re-use its exact URL to update it.`,\n );\n process.exitCode = 1;\n return;\n }\n\n if (opts.name) {\n logWarn(\n \"the --name flag is deprecated; the source entry now stores only the URL \" +\n \"(the cache slug is derived from it).\",\n );\n }\n const pin = opts.pin ?? opts.branch;\n const slug = sourceShortName(url);\n const entry: SourceEntry = { url };\n if (pin) entry.pin = pin;\n\n const dest = sourceClonePath(sourceCacheKey(url));\n const preexisting = existsSync(dest);\n // Clone/validate the repo BEFORE touching skaile.yaml — a failed clone\n // (repo not found, bad URL, network error) hard-exits in ensureClone, so\n // the entry is only ever recorded once the source is known-good.\n const cloned = ensureClone(entry, { force: opts.force });\n if (!cloned) {\n logOk(`Reusing cached clone at ${dest}`);\n } else if (preexisting) {\n logOk(`Re-cloned ${url} → ${dest}`);\n } else {\n logOk(`Cloned ${url} → ${dest}`);\n }\n\n const editor = WorkspaceYamlEditor.load(yamlPath);\n editor.setSource(entry);\n editor.save();\n\n const result = await refreshManifestCache(entry, opts.dev);\n const failed = indexingHadFailures(result);\n const indexedMsg = `Indexed ${result.assetsUpdated} of ${result.assetsFound} asset(s) from \"${slug}\".`;\n if (failed) {\n logWarn(indexedMsg);\n } else {\n logOk(indexedMsg);\n }\n for (const err of result.errors) logWarn(err);\n\n const legacyHint = legacySourceConfigHint(dest);\n if (legacyHint) logWarn(legacyHint);\n\n const where = path.relative(process.cwd(), yamlPath);\n if (failed) {\n // The entry IS recorded in skaile.yaml, but indexing did not fully\n // succeed — don't present it as a clean success.\n logWarn(\n `Source \"${slug}\" registered in ${where}, but ${result.errors.length} ` +\n `asset(s) failed to index (see above). Fix the cause, then re-run ` +\n `\\`skaile source sync ${slug}\\`.`,\n );\n process.exitCode = 1;\n } else {\n logOk(`Source \"${slug}\" registered in ${where}.`);\n }\n },\n );\n\n // ── source list ─────────────────────────────────────────────────────────\n cmd\n .command(\"list\")\n .description(\"List sources registered in this project's skaile.yaml\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (opts: { json?: boolean }) => {\n const yamlPath = requireProjectYamlPath();\n const sources = readProjectSources(yamlPath);\n if (opts.json) return console.log(JSON.stringify(sources, null, 2));\n if (sources.length === 0) {\n logInfo(\"No sources in skaile.yaml. Run `skaile source add <git-url>` to register one.\");\n return;\n }\n console.log();\n console.log(S.heading(\" Sources\"));\n for (const s of sources) {\n const slug = sourceShortName(s.url);\n const cached = existsSync(sourceClonePath(sourceCacheKey(s.url)))\n ? \"\"\n : S.warn(\" (not cached)\");\n console.log(` ${S.cmd(slug.padEnd(24))} ${S.dim(s.url)}${cached}`);\n }\n console.log(`\\n ${S.dim(`${sources.length} source(s)`)}\\n`);\n });\n\n // ── source show ─────────────────────────────────────────────────────────\n cmd\n .command(\"show <name-or-url>\")\n .description(\"Show details for a source (matched by URL or derived slug)\")\n .action(async (key: string) => {\n const yamlPath = requireProjectYamlPath();\n const entry = readProjectSources(yamlPath).find((s) => sourceMatchesKey(s, key));\n if (!entry) {\n logErr(`No source matching \"${key}\" in ${yamlPath}.`);\n process.exit(1);\n }\n const slug = sourceShortName(entry.url);\n const clonePath = sourceClonePath(sourceCacheKey(entry.url));\n console.log(\n JSON.stringify(\n {\n ...entry,\n slug,\n clonePath,\n cached: existsSync(clonePath),\n },\n null,\n 2,\n ),\n );\n });\n\n // ── source remove ───────────────────────────────────────────────────────\n cmd\n .command(\"remove <name-or-url>\")\n .description(\"Remove a source from this project's skaile.yaml (matched by URL or slug)\")\n .option(\"--purge\", \"Also delete the cached clone from ~/.skaile/cache/sources/\", false)\n .action(async (key: string, opts: { purge: boolean }) => {\n const yamlPath = requireProjectYamlPath();\n const editor = WorkspaceYamlEditor.load(yamlPath);\n // Resolve to the stored URL (entries are keyed by url in the editor).\n const match = editor.getSources().find((s) => sourceMatchesKey(s, key));\n if (!match) {\n logErr(`No source matching \"${key}\" in ${yamlPath}.`);\n process.exit(1);\n }\n const slug = sourceShortName(match.url);\n editor.removeSource(match.url);\n editor.save();\n await dropManifestCache(match.url, opts.purge);\n logOk(\n opts.purge\n ? `Removed source \"${slug}\" and purged its clone.`\n : `Removed source \"${slug}\" from skaile.yaml (clone left in ~/.skaile/cache/sources/).`,\n );\n });\n\n // ── source sync ─────────────────────────────────────────────────────────\n cmd\n .command(\"sync [name]\")\n .description(\"Pull upstream changes and refresh the manifest cache\")\n .option(\"--dev\", \"Also index dev-only assets under each source's dev_paths\", false)\n .option(\"--all\", \"Sync every source without prompting\", false)\n .action(async (key: string | undefined, opts: { dev?: boolean; all?: boolean }) => {\n const yamlPath = requireProjectYamlPath();\n const sources = readProjectSources(yamlPath);\n if (sources.length === 0) {\n logInfo(\"No sources in skaile.yaml.\");\n return;\n }\n\n let targets: SourceEntry[];\n if (key) {\n targets = sources.filter((s) => sourceMatchesKey(s, key));\n if (targets.length === 0) {\n logInfo(`No source matching \"${key}\".`);\n return;\n }\n } else if (opts.all || sources.length === 1 || !process.stdin.isTTY) {\n // --all, a single source, or a non-interactive shell: sync everything.\n targets = sources;\n } else {\n const selected = await p.multiselect({\n message: \"Select sources to sync\",\n options: sources.map((s) => ({\n value: s.url,\n label: sourceShortName(s.url),\n hint: s.url,\n })),\n required: true,\n });\n if (p.isCancel(selected)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n const picked = new Set(selected as string[]);\n targets = sources.filter((s) => picked.has(s.url));\n }\n for (const entry of targets) {\n const slug = sourceShortName(entry.url);\n const dest = sourceClonePath(sourceCacheKey(entry.url));\n if (!existsSync(dest)) {\n ensureClone(entry);\n logOk(`${slug}: cloned to ${dest}.`);\n } else {\n const pull = spawnSync(\"git\", [\"pull\", \"--ff-only\"], { cwd: dest, stdio: \"inherit\" });\n if (pull.status !== 0) {\n logWarn(`${slug}: git pull failed, skipping manifest refresh.`);\n continue;\n }\n }\n const result = await refreshManifestCache(entry, opts.dev);\n const failed = indexingHadFailures(result);\n const indexedMsg = `${slug}: indexed ${result.assetsUpdated} of ${result.assetsFound} asset(s).`;\n if (failed) {\n logWarn(indexedMsg);\n process.exitCode = 1;\n } else {\n logOk(indexedMsg);\n }\n for (const err of result.errors) logWarn(`${slug}: ${err}`);\n const legacyHint = legacySourceConfigHint(dest);\n if (legacyHint) logWarn(`${slug}: ${legacyHint}`);\n }\n });\n\n // ── source patch / propose (stubs) ──────────────────────────────────────\n cmd\n .command(\"patch <ref>\")\n .description(\"Extract an asset for editing against the source\")\n .action((_ref: string) => {\n logErr(\n \"`skaile source patch` is scaffolded but not yet wired. \" +\n \"The patch flow lands in a follow-up PR.\",\n );\n process.exit(2);\n });\n\n cmd\n .command(\"propose <ref>\")\n .description(\"Open a PR with the patch against the source upstream\")\n .action((_ref: string) => {\n logErr(\n \"`skaile source propose` is scaffolded but not yet wired. \" +\n \"The propose flow lands in a follow-up PR.\",\n );\n process.exit(2);\n });\n\n // ── source manifest * ───────────────────────────────────────────────────\n addSourceManifestCommands(cmd);\n\n return cmd;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveSkWorkspaceConfig, readLinks, getGlobalCacheDir, sourceCacheKey } from './chunk-5AGARSQT.js';
1
+ import { resolveSkWorkspaceConfig, readLinks, getGlobalCacheDir, sourceCacheKey } from './chunk-OUWNTFDG.js';
2
2
  import { scanDirectory } from './chunk-BQCGFPHW.js';
3
3
  import { existsSync, readFileSync, lstatSync } from 'fs';
4
4
  import { createRequire } from 'module';
@@ -207,5 +207,5 @@ function findCatalogEntry(entries, query) {
207
207
  }
208
208
 
209
209
  export { FACTORY_ASSETS_REPO_NAME, factoryAssetRoots, resolveFactoryAssetsRoot, resolveFactoryAssetsRootOrNull, resolvePackagedAssetsDir, resolveRuntimeAssets, resolveWorkspacesPackageRoot };
210
- //# sourceMappingURL=chunk-BM37QD6U.js.map
211
- //# sourceMappingURL=chunk-BM37QD6U.js.map
210
+ //# sourceMappingURL=chunk-TJRWGMD2.js.map
211
+ //# sourceMappingURL=chunk-TJRWGMD2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../core/src/runtime-assets.ts"],"names":["resolvePath","require"],"mappings":";;;;;;;AAoDA,SAAS,sBACP,OAAA,EACmC;AACnC,EAAA,MAAM,aAAa,iBAAA,EAAkB;AACrC,EAAA,MAAM,MAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,CAAA,IAAK,OAAA,IAAW,EAAC,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,cAAA,CAAe,CAAA,CAAE,GAAG,CAAA;AAChC,IAAA,IAAI,GAAA,CAAI,GAAG,CAAA,EAAG;AACd,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,EAAE,IAAA,EAAM,IAAA,CAAK,UAAA,EAAY,GAAG,CAAA,EAAG,GAAA,EAAK,CAAA,CAAE,GAAA,EAAK,MAAA,EAAQ,EAAE,GAAA,EAAI;AAAA,EACtE;AACA,EAAA,OAAO,GAAA;AACT;AAqDO,IAAM,wBAAA,GAA2B;AAMxC,IAAM,iCAAA,GAAoC,yBAAA;AAsC1C,eAAsB,qBAAqB,UAAA,EAAkD;AAC3F,EAAA,MAAM,MAAA,GAA8B;AAAA,IAClC,gBAAgB,EAAC;AAAA,IACjB,cAAc,EAAC;AAA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EAAA,IAAI,SAAS,wBAAA,IAA4B,CAAC,KAAK,IAAA,IAAQ,CAAC,KAAK,GAAA,EAAK;AAChE,IAAA,OACE,CAAA,oHAAA,CAAA;AAAA,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-BM37QD6U.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `factory-assets/` directory as an implicit default),\n * and 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 * `factory-assets/` is the single first-party content tree (built-in connectors\n * + first-party skills + bundles) shipped inside the `@skaile/workspaces`\n * package — not a standalone package.\n *\n * It resolves to an **ordered list of roots** ({@link factoryAssetRoots}), not a\n * single dir. The bundled tree is always the baseline; an optional\n * `SKAILE_FACTORY_ASSETS_DIR` (legacy: `SKAILE_BASE_ASSETS_DIR`) is layered\n * **in front** as an additive override source — the agent container points it at\n * `/app/factory-assets/` (or a bind-mounted host dir) to ship updated skills /\n * flows / bundles / connector manifests without rebuilding the image. The two\n * roots resolve uniformly across every consumer (connector catalog scan, skill /\n * flow / completion discovery, the asset-manager factory source):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir, when set and existing (override layer).\n * 2. the bundled tree via {@link resolvePackagedAssetsDir} — the in-repo source\n * `packages/workspaces/factory-assets/` during dev, else the published\n * `dist/factory-assets/` after install (always-present baseline).\n *\n * Override semantics are **env-first**: on a name conflict the env root wins and\n * the bundled root fills the rest. Connector *code* still loads via the package's\n * static `exports` map, so the env root can override/add skills, flows, bundles,\n * and connector **manifests/metadata**, but cannot ship a new executable\n * connector — its `.js` is not on the package's import graph.\n */\n\nimport { existsSync, lstatSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { getGlobalCacheDir, readLinks, sourceCacheKey } from \"./repo-manager.js\";\nimport type { SourceDeclaration, SourceEntry } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\n\n/**\n * Map declared `sources[]` to internal `SourceDeclaration`s keyed by the\n * collision-free {@link sourceCacheKey} (`<host>/<owner>/<repo>`), pointing at\n * the unified machine-cache clone path (`getGlobalCacheDir()/<key>/`). Keyed by\n * the same function every other cache writer/reader uses so the path resolves.\n */\nfunction sourcesToDeclarations(\n sources: SourceEntry[] | undefined,\n): Record<string, SourceDeclaration> {\n const sourcesDir = getGlobalCacheDir();\n const out: Record<string, SourceDeclaration> = {};\n for (const s of sources ?? []) {\n const key = sourceCacheKey(s.url);\n if (out[key]) continue;\n out[key] = { path: join(sourcesDir, key), url: s.url, branch: s.pin };\n }\n return out;\n}\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 built-in `factory-assets` catalog entry\n * (the in-package connector tree).\n * @docLink packages/core/concepts#factory-assets-repo-name\n */\nexport const FACTORY_ASSETS_REPO_NAME = \"factory-assets\";\n\n/**\n * Repository name for the optional `SKAILE_FACTORY_ASSETS_DIR` override layer,\n * scanned ahead of (and overriding) the bundled {@link FACTORY_ASSETS_REPO_NAME}.\n */\nconst FACTORY_ASSETS_OVERRIDE_REPO_NAME = \"factory-assets:override\";\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 * built-in `factory-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 ordered list of on-disk roots for the built-in `factory-assets`\n * tree (built-in connectors + first-party skills + bundles). This is the single\n * shared resolver every consumer goes through, so the env override and the\n * bundled baseline are honoured uniformly.\n *\n * Order (env-first = override-wins):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir (legacy: `SKAILE_BASE_ASSETS_DIR`),\n * when set and existing — an additive override layer.\n * 2. {@link resolvePackagedAssetsDir} — the bundled tree (in-repo source in dev,\n * `dist/factory-assets/` after install). Always-present baseline.\n *\n * Returns `[]` only when the package cannot be located at all. De-duplicated, so\n * pointing the env var at the bundled dir collapses to one root.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function factoryAssetRoots(): string[] {\n const roots: string[] = [];\n const envDir = process.env.SKAILE_FACTORY_ASSETS_DIR ?? process.env.SKAILE_BASE_ASSETS_DIR;\n if (envDir && existsSync(envDir)) roots.push(resolvePath(envDir));\n const bundled = resolvePackagedAssetsDir(\"factory-assets\");\n if (bundled) roots.push(bundled);\n return [...new Set(roots)];\n}\n\n/**\n * Resolve the primary on-disk root of the `factory-assets` tree — the first of\n * {@link factoryAssetRoots} (the env override when set, else the bundled tree).\n * Prefer {@link factoryAssetRoots} when you need to scan every layer; this\n * single-dir form is for callers that want one canonical path.\n *\n * @returns Absolute path to the highest-precedence `factory-assets` directory\n * @throws When no root can be located\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolveFactoryAssetsRoot(): string {\n const hit = resolveFactoryAssetsRootOrNull();\n if (hit) return hit;\n\n throw new Error(\n `Cannot resolve the factory-assets directory. ` +\n `Set SKAILE_FACTORY_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 * Non-throwing variant of {@link resolveFactoryAssetsRoot}: the same\n * env-then-packaged resolution tiers, returning `null` instead of throwing when\n * none locate the directory. Callers that treat a missing factory tree as a\n * soft \"not present\" (e.g. the asset-manager's implicit-source injection) MUST\n * use this so they honour the `SKAILE_FACTORY_ASSETS_DIR` container override\n * identically to the runtime path.\n */\nexport function resolveFactoryAssetsRootOrNull(): string | null {\n return factoryAssetRoots()[0] ?? null;\n}\n\n/**\n * Resolve the `@skaile/workspaces` package root — the directory containing its\n * `package.json`. Tries `require.resolve` first (works when installed as a\n * dependency *and* in-repo via the self-reference), then walks upward from this\n * module looking for a `package.json` whose `name` is `@skaile/workspaces`\n * (bounded to 8 levels). Returns `null` when neither locates it.\n *\n * The single source of truth for finding content shipped inside the package —\n * the unified `factory-assets/` tree (built-in connectors + first-party skills\n * + bundles) resolves through {@link resolvePackagedAssetsDir} on top of this.\n *\n * Memoized: the package location is immutable for the process lifetime, but\n * this sits on the CLI hot path (every `findSkills` / flow / completion call\n * funnels through here), so the `require.resolve` + upward `package.json` walk\n * runs once. `undefined` = not yet computed.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nlet workspacesPackageRootCache: string | null | undefined;\n\nexport function resolveWorkspacesPackageRoot(): string | null {\n if (workspacesPackageRootCache !== undefined) return workspacesPackageRootCache;\n workspacesPackageRootCache = computeWorkspacesPackageRoot();\n return workspacesPackageRootCache;\n}\n\nfunction computeWorkspacesPackageRoot(): string | null {\n try {\n const require = createRequire(import.meta.url);\n return dirname(require.resolve(\"@skaile/workspaces/package.json\"));\n } catch {\n // Fall through to the workspace walk.\n }\n let dir: string;\n try {\n dir = dirname(fileURLToPath(import.meta.url));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return dir;\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/**\n * Locate a content-asset directory inside the package. Prefers the in-repo\n * **source** dir `<pkgRoot>/<subdir>` when present — in a dev checkout it is the\n * full tree (e.g. `factory-assets/` keeps the connector `.ts` entry files that\n * `dist/` does not) — then the published `dist/<subdir>` copy (what\n * `files: [\"dist\"]` ships, the only one present after `npm i`). Returns `null`\n * when neither exists.\n *\n * `factory-assets/` resolves to the source tree in dev (code + skills + bundles)\n * and to `dist/factory-assets` post-install (compiled connectors + copied\n * manifests/skills/bundles).\n *\n * @param subdir - `\"factory-assets\"` | …\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolvePackagedAssetsDir(subdir: string): string | null {\n const root = resolveWorkspacesPackageRoot();\n if (!root) return null;\n for (const cand of [join(root, subdir), join(root, \"dist\", subdir)]) {\n if (existsSync(cand)) return cand;\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 // Connector catalog scan runs over the project's declared sources[] (resolved\n // to their machine-cache clone paths) plus the implicit factory-assets repo.\n const repositories = buildEffectiveRepositories(sourcesToDeclarations(config.sources));\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 // Both factory layers carry the same `factory-assets` provenance — the\n // override repo is an internal scan-order device, not a distinct source.\n const repoName = name === FACTORY_ASSETS_OVERRIDE_REPO_NAME ? FACTORY_ASSETS_REPO_NAME : name;\n const entries = scanDirectory(repoDir, repoName).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 // De-duplicate by (kind, name), keeping the first occurrence. Scan order is\n // declared sources → env override → bundled baseline, so an env-supplied\n // connector manifest overrides the bundled one and the bundled one fills the\n // rest (the override layer can refresh built-in manifests in place).\n const seen = new Set<string>();\n target.catalogEntries = target.catalogEntries.filter((e) => {\n const key = `${e.kind}:${e.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\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 the\n * implicit built-in `factory-assets` repos. Each {@link factoryAssetRoots} layer\n * becomes its own repo, the env override inserted **before** the bundled\n * baseline so its connector entries win on the first-match dedup downstream.\n * When the package cannot be located at all, a path-less sentinel under\n * {@link FACTORY_ASSETS_REPO_NAME} drives the `repo_unavailable` warning.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, SourceDeclaration> | undefined,\n): Record<string, SourceDeclaration> {\n const result: Record<string, SourceDeclaration> = { ...(declared ?? {}) };\n const roots = factoryAssetRoots();\n if (roots.length === 0) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether factory-assets is required. resolveRepoDir() /\n // repoUnavailableMessage re-discover the failure and emit it.\n if (!result[FACTORY_ASSETS_REPO_NAME]) result[FACTORY_ASSETS_REPO_NAME] = { path: \"\" };\n return result;\n }\n // override-first when both layers exist, so the env root's entries are scanned\n // (and matched) ahead of the bundled baseline.\n const keys =\n roots.length > 1\n ? [FACTORY_ASSETS_OVERRIDE_REPO_NAME, FACTORY_ASSETS_REPO_NAME]\n : [FACTORY_ASSETS_REPO_NAME];\n roots.forEach((dir, i) => {\n const key = keys[i] ?? `${FACTORY_ASSETS_REPO_NAME}:${i}`;\n if (!result[key]) result[key] = { path: dir };\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/cache/sources/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n */\nfunction resolveRepoDir(\n name: string,\n decl: SourceDeclaration,\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/cache/sources/<name> — the\n // project-local clone dir (often a symlink into the global cache, which\n // lives at getGlobalCacheDir()); NOT the global clone root itself.\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"cache\", \"sources\", name);\n if (existsSync(projectDest)) {\n // Either a real directory or a symlink to the global cache.\n try {\n lstatSync(projectDest);\n return projectDest;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n return null;\n}\n\nfunction repoUnavailableMessage(name: string, decl: SourceDeclaration): string {\n if (name === FACTORY_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve the built-in factory-assets. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR or ensure @skaile/workspaces 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":";;;;;;;AAoDA,SAAS,sBACP,OAAA,EACmC;AACnC,EAAA,MAAM,aAAa,iBAAA,EAAkB;AACrC,EAAA,MAAM,MAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,CAAA,IAAK,OAAA,IAAW,EAAC,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,cAAA,CAAe,CAAA,CAAE,GAAG,CAAA;AAChC,IAAA,IAAI,GAAA,CAAI,GAAG,CAAA,EAAG;AACd,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,EAAE,IAAA,EAAM,IAAA,CAAK,UAAA,EAAY,GAAG,CAAA,EAAG,GAAA,EAAK,CAAA,CAAE,GAAA,EAAK,MAAA,EAAQ,EAAE,GAAA,EAAI;AAAA,EACtE;AACA,EAAA,OAAO,GAAA;AACT;AAqDO,IAAM,wBAAA,GAA2B;AAMxC,IAAM,iCAAA,GAAoC,yBAAA;AAsC1C,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,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;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-TJRWGMD2.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `factory-assets/` directory as an implicit default),\n * and 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 * `factory-assets/` is the single first-party content tree (built-in connectors\n * + first-party skills + bundles) shipped inside the `@skaile/workspaces`\n * package — not a standalone package.\n *\n * It resolves to an **ordered list of roots** ({@link factoryAssetRoots}), not a\n * single dir. The bundled tree is always the baseline; an optional\n * `SKAILE_FACTORY_ASSETS_DIR` (legacy: `SKAILE_BASE_ASSETS_DIR`) is layered\n * **in front** as an additive override source — the agent container points it at\n * `/app/factory-assets/` (or a bind-mounted host dir) to ship updated skills /\n * flows / bundles / connector manifests without rebuilding the image. The two\n * roots resolve uniformly across every consumer (connector catalog scan, skill /\n * flow / completion discovery, the asset-manager factory source):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir, when set and existing (override layer).\n * 2. the bundled tree via {@link resolvePackagedAssetsDir} — the in-repo source\n * `packages/workspaces/factory-assets/` during dev, else the published\n * `dist/factory-assets/` after install (always-present baseline).\n *\n * Override semantics are **env-first**: on a name conflict the env root wins and\n * the bundled root fills the rest. Connector *code* still loads via the package's\n * static `exports` map, so the env root can override/add skills, flows, bundles,\n * and connector **manifests/metadata**, but cannot ship a new executable\n * connector — its `.js` is not on the package's import graph.\n */\n\nimport { existsSync, lstatSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { getGlobalCacheDir, readLinks, sourceCacheKey } from \"./repo-manager.js\";\nimport type { SourceDeclaration, SourceEntry } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\n\n/**\n * Map declared `sources[]` to internal `SourceDeclaration`s keyed by the\n * collision-free {@link sourceCacheKey} (`<host>/<owner>/<repo>`), pointing at\n * the unified machine-cache clone path (`getGlobalCacheDir()/<key>/`). Keyed by\n * the same function every other cache writer/reader uses so the path resolves.\n */\nfunction sourcesToDeclarations(\n sources: SourceEntry[] | undefined,\n): Record<string, SourceDeclaration> {\n const sourcesDir = getGlobalCacheDir();\n const out: Record<string, SourceDeclaration> = {};\n for (const s of sources ?? []) {\n const key = sourceCacheKey(s.url);\n if (out[key]) continue;\n out[key] = { path: join(sourcesDir, key), url: s.url, branch: s.pin };\n }\n return out;\n}\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 built-in `factory-assets` catalog entry\n * (the in-package connector tree).\n * @docLink packages/core/concepts#factory-assets-repo-name\n */\nexport const FACTORY_ASSETS_REPO_NAME = \"factory-assets\";\n\n/**\n * Repository name for the optional `SKAILE_FACTORY_ASSETS_DIR` override layer,\n * scanned ahead of (and overriding) the bundled {@link FACTORY_ASSETS_REPO_NAME}.\n */\nconst FACTORY_ASSETS_OVERRIDE_REPO_NAME = \"factory-assets:override\";\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 * built-in `factory-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 ordered list of on-disk roots for the built-in `factory-assets`\n * tree (built-in connectors + first-party skills + bundles). This is the single\n * shared resolver every consumer goes through, so the env override and the\n * bundled baseline are honoured uniformly.\n *\n * Order (env-first = override-wins):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir (legacy: `SKAILE_BASE_ASSETS_DIR`),\n * when set and existing — an additive override layer.\n * 2. {@link resolvePackagedAssetsDir} — the bundled tree (in-repo source in dev,\n * `dist/factory-assets/` after install). Always-present baseline.\n *\n * Returns `[]` only when the package cannot be located at all. De-duplicated, so\n * pointing the env var at the bundled dir collapses to one root.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function factoryAssetRoots(): string[] {\n const roots: string[] = [];\n const envDir = process.env.SKAILE_FACTORY_ASSETS_DIR ?? process.env.SKAILE_BASE_ASSETS_DIR;\n if (envDir && existsSync(envDir)) roots.push(resolvePath(envDir));\n const bundled = resolvePackagedAssetsDir(\"factory-assets\");\n if (bundled) roots.push(bundled);\n return [...new Set(roots)];\n}\n\n/**\n * Resolve the primary on-disk root of the `factory-assets` tree — the first of\n * {@link factoryAssetRoots} (the env override when set, else the bundled tree).\n * Prefer {@link factoryAssetRoots} when you need to scan every layer; this\n * single-dir form is for callers that want one canonical path.\n *\n * @returns Absolute path to the highest-precedence `factory-assets` directory\n * @throws When no root can be located\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolveFactoryAssetsRoot(): string {\n const hit = resolveFactoryAssetsRootOrNull();\n if (hit) return hit;\n\n throw new Error(\n `Cannot resolve the factory-assets directory. ` +\n `Set SKAILE_FACTORY_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 * Non-throwing variant of {@link resolveFactoryAssetsRoot}: the same\n * env-then-packaged resolution tiers, returning `null` instead of throwing when\n * none locate the directory. Callers that treat a missing factory tree as a\n * soft \"not present\" (e.g. the asset-manager's implicit-source injection) MUST\n * use this so they honour the `SKAILE_FACTORY_ASSETS_DIR` container override\n * identically to the runtime path.\n */\nexport function resolveFactoryAssetsRootOrNull(): string | null {\n return factoryAssetRoots()[0] ?? null;\n}\n\n/**\n * Resolve the `@skaile/workspaces` package root — the directory containing its\n * `package.json`. Tries `require.resolve` first (works when installed as a\n * dependency *and* in-repo via the self-reference), then walks upward from this\n * module looking for a `package.json` whose `name` is `@skaile/workspaces`\n * (bounded to 8 levels). Returns `null` when neither locates it.\n *\n * The single source of truth for finding content shipped inside the package —\n * the unified `factory-assets/` tree (built-in connectors + first-party skills\n * + bundles) resolves through {@link resolvePackagedAssetsDir} on top of this.\n *\n * Memoized: the package location is immutable for the process lifetime, but\n * this sits on the CLI hot path (every `findSkills` / flow / completion call\n * funnels through here), so the `require.resolve` + upward `package.json` walk\n * runs once. `undefined` = not yet computed.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nlet workspacesPackageRootCache: string | null | undefined;\n\nexport function resolveWorkspacesPackageRoot(): string | null {\n if (workspacesPackageRootCache !== undefined) return workspacesPackageRootCache;\n workspacesPackageRootCache = computeWorkspacesPackageRoot();\n return workspacesPackageRootCache;\n}\n\nfunction computeWorkspacesPackageRoot(): string | null {\n try {\n const require = createRequire(import.meta.url);\n return dirname(require.resolve(\"@skaile/workspaces/package.json\"));\n } catch {\n // Fall through to the workspace walk.\n }\n let dir: string;\n try {\n dir = dirname(fileURLToPath(import.meta.url));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return dir;\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/**\n * Locate a content-asset directory inside the package. Prefers the in-repo\n * **source** dir `<pkgRoot>/<subdir>` when present — in a dev checkout it is the\n * full tree (e.g. `factory-assets/` keeps the connector `.ts` entry files that\n * `dist/` does not) — then the published `dist/<subdir>` copy (what\n * `files: [\"dist\"]` ships, the only one present after `npm i`). Returns `null`\n * when neither exists.\n *\n * `factory-assets/` resolves to the source tree in dev (code + skills + bundles)\n * and to `dist/factory-assets` post-install (compiled connectors + copied\n * manifests/skills/bundles).\n *\n * @param subdir - `\"factory-assets\"` | …\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolvePackagedAssetsDir(subdir: string): string | null {\n const root = resolveWorkspacesPackageRoot();\n if (!root) return null;\n for (const cand of [join(root, subdir), join(root, \"dist\", subdir)]) {\n if (existsSync(cand)) return cand;\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 // Connector catalog scan runs over the project's declared sources[] (resolved\n // to their machine-cache clone paths) plus the implicit factory-assets repo.\n const repositories = buildEffectiveRepositories(sourcesToDeclarations(config.sources));\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 // Both factory layers carry the same `factory-assets` provenance — the\n // override repo is an internal scan-order device, not a distinct source.\n const repoName = name === FACTORY_ASSETS_OVERRIDE_REPO_NAME ? FACTORY_ASSETS_REPO_NAME : name;\n const entries = scanDirectory(repoDir, repoName).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 // De-duplicate by (kind, name), keeping the first occurrence. Scan order is\n // declared sources → env override → bundled baseline, so an env-supplied\n // connector manifest overrides the bundled one and the bundled one fills the\n // rest (the override layer can refresh built-in manifests in place).\n const seen = new Set<string>();\n target.catalogEntries = target.catalogEntries.filter((e) => {\n const key = `${e.kind}:${e.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\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 the\n * implicit built-in `factory-assets` repos. Each {@link factoryAssetRoots} layer\n * becomes its own repo, the env override inserted **before** the bundled\n * baseline so its connector entries win on the first-match dedup downstream.\n * When the package cannot be located at all, a path-less sentinel under\n * {@link FACTORY_ASSETS_REPO_NAME} drives the `repo_unavailable` warning.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, SourceDeclaration> | undefined,\n): Record<string, SourceDeclaration> {\n const result: Record<string, SourceDeclaration> = { ...(declared ?? {}) };\n const roots = factoryAssetRoots();\n if (roots.length === 0) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether factory-assets is required. resolveRepoDir() /\n // repoUnavailableMessage re-discover the failure and emit it.\n if (!result[FACTORY_ASSETS_REPO_NAME]) result[FACTORY_ASSETS_REPO_NAME] = { path: \"\" };\n return result;\n }\n // override-first when both layers exist, so the env root's entries are scanned\n // (and matched) ahead of the bundled baseline.\n const keys =\n roots.length > 1\n ? [FACTORY_ASSETS_OVERRIDE_REPO_NAME, FACTORY_ASSETS_REPO_NAME]\n : [FACTORY_ASSETS_REPO_NAME];\n roots.forEach((dir, i) => {\n const key = keys[i] ?? `${FACTORY_ASSETS_REPO_NAME}:${i}`;\n if (!result[key]) result[key] = { path: dir };\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/cache/sources/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n */\nfunction resolveRepoDir(\n name: string,\n decl: SourceDeclaration,\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/cache/sources/<name> — the\n // project-local clone dir (often a symlink into the global cache, which\n // lives at getGlobalCacheDir()); NOT the global clone root itself.\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"cache\", \"sources\", name);\n if (existsSync(projectDest)) {\n // Either a real directory or a symlink to the global cache.\n try {\n lstatSync(projectDest);\n return projectDest;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n return null;\n}\n\nfunction repoUnavailableMessage(name: string, decl: SourceDeclaration): string {\n if (name === FACTORY_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve the built-in factory-assets. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR or ensure @skaile/workspaces 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"]}
@@ -285,5 +285,5 @@ async function listModelsForDriver(driverId, apiKeys) {
285
285
  }
286
286
 
287
287
  export { AgentDriver, BUILTIN_DRIVER_CATALOG, DRIVER_CATALOG, createDriver, getBridgeLogger, listDrivers, listModelsForDriver, registerBuiltinDrivers };
288
- //# sourceMappingURL=chunk-QVE3ILCY.js.map
289
- //# sourceMappingURL=chunk-QVE3ILCY.js.map
288
+ //# sourceMappingURL=chunk-TNSCHS4I.js.map
289
+ //# sourceMappingURL=chunk-TNSCHS4I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../bridge/src/logger.ts","../bridge/src/types.ts","../bridge/src/registry.ts"],"names":[],"mappings":";;;;;AAuBO,SAAS,gBAAgB,OAAA,EAAyB;AACvD,EAAA,OAAO,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,CAAA;AACjD;ACubO,IAAe,WAAA,GAAf,cAAmC,YAAA,CAAa;AAAA;AAAA,EA0CrD,IAAI,gBAAA,GAAuC;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,gBAAA,GAAuC;AACrC,IAAA,OAAO,EAAC;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,kBAAA,GAA8B;AAC5B,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,eAAe,MAAA,EAAyB;AAEtC,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA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AA,OACrD,CAAA;AAAA,IACH;AAAA,EACF;AACA,EAAA,OAAO,CAAC,GAAG,MAAA,CAAO,MAAA,EAAQ,CAAA;AAC5B;AAiBA,eAAsB,mBAAA,CACpB,UACA,OAAA,EACuB;AACvB,EAAA,MAAM,MAAA,GAAS,MAAM,mBAAA,CAAoB,QAAQ,CAAA;AACjD,EAAA,OAAQ,MAAM,MAAA,CAAO,UAAA,GAAa,OAAO,KAAM,EAAC;AAClD","file":"chunk-TNSCHS4I.js","sourcesContent":["/**\n * Bridge-layer logger factory.\n *\n * Each driver creates its own Logger via `getBridgeLogger(subkind)` at\n * construction time. Falls back to an off-mode Logger (stdout only) when\n * no LogStore is registered — see @skaile/workspaces/core/logging for details.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * Construct a bridge-scoped Logger for a given driver subkind.\n *\n * Creates a `Logger` with `kind: \"bridge\"` and the specified `subkind`. Falls back to\n * an off-mode Logger (stdout only) when no `LogStore` is registered — see\n * `@skaile/workspaces/core/logging` for details. Each driver calls this once at construction\n * time; never re-construct per call.\n *\n * @param subkind - Driver id, e.g. `\"claude-sdk\"`, `\"omp\"`, `\"echo\"`, `\"codex\"`.\n * @returns A `Logger` scoped to `bridge:<subkind>`.\n * @docLink packages/bridge/api-reference#logger\n */\nexport function getBridgeLogger(subkind: string): Logger {\n return createLogger({ kind: \"bridge\", subkind });\n}\n","import { EventEmitter } from \"node:events\";\nimport type { Span, TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type {\n Capability,\n CredentialMint,\n RenderInvokedEvent,\n TokenUsage,\n} from \"@skaile/workspaces/types\";\nimport type { ModelEntry } from \"./models.js\";\n\n/**\n * Minimal LLM tool descriptor used by the capability dispatch path. Mirrors\n * the runner's `LLMTool` shape so drivers can consume registry output without\n * importing `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-tool\n */\nexport interface BridgeCapabilityTool {\n /** Capability name; used as the LLM-visible tool name. */\n name: string;\n /** Human/LLM-readable description. */\n description: string;\n /** JSON Schema for the tool's input parameters. */\n parameters: Record<string, unknown>;\n}\n\n/**\n * Render-cap event emission callback used by the bridge when the LLM invokes\n * a capability that carries a `render` spec. The runner provides the actual\n * sink (transport.send / sendEvent); the bridge only emits.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-render-emit\n */\nexport type BridgeRenderEmit = (event: RenderInvokedEvent) => void;\n\n/**\n * Text-event emission callback for render-capability fallbacks. When a\n * `RenderCapability` carries `render.fallback` and the LLM invokes it, the\n * bridge substitutes `{{prop}}` placeholders (top-level keys of `props`,\n * optional dotted-path traversal `{{user.name}}`) and pushes the rendered\n * string through this callback so clients without a render layer still see\n * a textual representation. No-op when `fallback` is absent.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-text-emit\n */\nexport type BridgeTextEmit = (text: string) => void;\n\n/**\n * Bundle of capability dispatch hooks. Registered into the driver via\n * `AgentConfig.capabilities`; the driver routes registered LLM tool calls\n * back into `invoke()` instead of using its native dispatch path.\n *\n * The runner constructs this from a `CapabilityRegistry` instance and threads\n * it through `createAgentSession()`. Drivers that don't yet implement\n * capability dispatch ignore the field — legacy v1 paths stay intact.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-hooks\n */\nexport interface BridgeCapabilityHooks {\n /** Build the LLM tool descriptor list from the registry. Called per turn so registration changes take effect. */\n composeTools(): BridgeCapabilityTool[];\n /** Resolve a wire-format Capability descriptor by name. Used by the bridge to inspect `fireAndForget` / `render`. */\n resolve(name: string): Capability | null;\n /** Validate input + dispatch through the registry. Logging is wired by the registry. */\n invoke(name: string, input: unknown): Promise<unknown>;\n /** Emit a render-invoked event. The runner forwards via the WebSocket transport. */\n emitRender?: BridgeRenderEmit;\n /** Emit a text fallback for render capabilities with `render.fallback`. */\n emitText?: BridgeTextEmit;\n /** Session id passed through to the runner's per-handler logger. */\n sessionId: string;\n}\n\n/**\n * Static metadata for a registered agent driver backend.\n *\n * Returned by {@link listDrivers} and exposed on every {@link AgentDriver} instance\n * via `driverInfo`.\n *\n * @docLink packages/bridge/concepts#driver-info\n */\nexport interface DriverInfo {\n /** Stable machine identifier used to look up the driver in the registry (e.g. `\"omp\"`, `\"claude-sdk\"`). */\n id: string;\n /** Human-readable display name shown in UIs and logs. */\n name: string;\n /** `true` when the driver can target any LLM provider; `false` for Anthropic-only drivers. */\n modelAgnostic: boolean;\n /**\n * `true` when the driver supports mid-stream abort via `abort()` without killing the process.\n * Drivers that return `false` can only be stopped via `kill()`.\n */\n supportsInBandAbort: boolean;\n}\n\n/**\n * Codex-specific tuning options passed through `DriverOptions.codex`.\n *\n * @remarks These are forwarded verbatim to the Codex driver and have no effect on other drivers.\n * @docLink packages/bridge/concepts#codex-driver-options\n */\nexport interface CodexDriverOptions {\n /** Controls whether Codex may auto-apply edits without user approval. */\n approvalPolicy?: \"never\" | \"on-request\" | \"on-failure\" | \"untrusted\";\n /** Filesystem sandbox level for the Codex process. */\n sandboxMode?: \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n /** Reasoning budget passed to the model. */\n reasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** When `true`, the Codex sandbox is allowed to make outbound network requests. */\n networkAccessEnabled?: boolean;\n /** Extra directories made accessible to the Codex sandbox in addition to `cwd`. */\n additionalDirectories?: string[];\n}\n\n/**\n * Driver-specific configuration bag.\n *\n * Fields are keyed by driver ID so that callers can pass driver-specific options\n * through the common {@link AgentConfig} without breaking other drivers.\n *\n * @docLink packages/bridge/concepts#driver-options\n */\nexport interface DriverOptions {\n /** Codex-specific options. Ignored by all other drivers. */\n codex?: CodexDriverOptions;\n}\n\n/**\n * Configuration passed to a driver when it is created via {@link createDriver}.\n *\n * All fields are shared across drivers; driver-specific behaviour is documented\n * per field. Fields that are silently ignored by a driver are marked accordingly.\n *\n * @docLink packages/bridge/concepts#agent-config\n */\nexport interface AgentConfig {\n /** Absolute path to the working directory the agent operates in. */\n cwd: string;\n /**\n * LLM provider name (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * Combined with `model` as `provider/model` for omp's `--model` flag.\n * Ignored by claude-sdk (always Anthropic).\n */\n provider?: string;\n /**\n * LLM model identifier (e.g. `\"claude-sonnet-4-5\"`, `\"gpt-4o\"`).\n * For omp: passed as `--model [provider/]model`.\n * For claude-sdk: passed as the `model` query option.\n */\n model?: string;\n /**\n * Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Drivers inject the relevant key into the environment or SDK options.\n */\n apiKeys?: Record<string, string>;\n /**\n * Additional environment variables merged into the child process environment.\n * For omp: merged with `process.env` before spawn. For claude-sdk: accessed\n * via `env.ANTHROPIC_API_KEY` as an alternative to `apiKeys.anthropic`.\n */\n env?: Record<string, string>;\n /**\n * AI cloud transport for claude-sdk: `default | bedrock | vertex | azure |\n * gateway`. Absent (or `\"default\"`) preserves today's behavior — the\n * provider's native API. Typed as `string` for forward compatibility; the\n * driver falls back to `default` on unrecognized values (with a warning).\n * Ignored by all other drivers.\n *\n * @since 1.3.0\n */\n cloud?: string;\n /**\n * Non-secret transport settings for the selected `cloud` (camelCase — the\n * skaile.yaml `cloud_config` wire shape is snake_case and converted once at\n * the settings/serve boundary). Ignored when `cloud` is absent/default.\n *\n * @since 1.3.0\n */\n cloudConfig?: { region?: string; projectId?: string; resource?: string; baseUrl?: string };\n /**\n * Resolved credential env bundle for the selected `cloud` — runner-provided\n * (platform `session_init` secrets, or runner-materialized file paths such\n * as the Vertex service-account file). Values are secrets: never logged.\n *\n * @since 1.3.0\n */\n cloudSecrets?: Record<string, string>;\n /** Inline system prompt — written to .omp/system.md and passed via --append-system-prompt (omp driver) */\n systemPrompt?: string;\n /** Path to project .omp/ directory (PI_CODING_AGENT_DIR for omp driver) */\n agentDir?: string;\n /** SSH key path — injected as GIT_SSH_COMMAND */\n sshKeyPath?: string;\n /** Pre-assign a UUID as the session ID for a new session (claude-sdk: passed as sessionId option) */\n sessionId?: string;\n /** Resume this specific past session by UUID instead of starting fresh (claude-sdk: passed as resume option) */\n resumeSessionId?: string;\n /** Maximum agentic turns per query (claude-sdk: passed as maxTurns option) */\n maxTurns?: number;\n /** Agent name — selects a deployed sub-agent definition as the main agent identity.\n * claude-sdk: passed as `agent` option to query() → reads .claude/agents/<name>.md natively.\n * omp: ignored (omp uses agentDir/PI_CODING_AGENT_DIR instead). */\n agentName?: string;\n /** In-process SDK MCP servers for custom tool injection (Claude SDK only, ignored by other drivers) */\n mcpServers?: Record<string, unknown>;\n /** Tool restrictions from agent.yaml — applied to the main agent session */\n tools?: {\n /** Tool names that the agent is allowed to invoke. An empty array means no restriction. */\n allowed?: string[];\n /** Tool names that the agent is explicitly forbidden from invoking. */\n denied?: string[];\n };\n /** Thinking mode for Claude models: adaptive (Claude decides), enabled (always think), disabled (no thinking). */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level for Claude models. */\n effort?: \"low\" | \"medium\" | \"high\" | \"max\";\n /** Driver-specific configuration bag. */\n driverOptions?: DriverOptions;\n /**\n * Protocol v2 capability dispatch hooks. When present, the driver uses the\n * registry as the source of LLM tool definitions and routes invocations\n * through `capabilities.invoke()`. Absent → legacy v1 path (existing\n * mcpServers / native dispatch).\n *\n * @since 2.0.0\n */\n capabilities?: BridgeCapabilityHooks;\n /**\n * The platform's `AIProviderConfig.id` for the AI credential currently\n * provisioned into this driver. The runner reads this off `AgentConfig`\n * during 401 mediation and passes it as `configId` in\n * `request_access_token { kind: 'ai-credentials' }`. The driver itself\n * does not consume this field — only the runner uses it.\n *\n * Set by the platform agent-gateway in `ConfigureCommandV2` for mediated\n * sessions. Standalone runners (CLI / forge / Claude plugin) leave it\n * undefined; the runner falls back to surfacing the auth error to the\n * user without mediating.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Wire `aiProviderConfigId` end-to-end\".\n *\n * @since 3.3.0\n */\n aiProviderConfigId?: string;\n /**\n * Optional callback invoked by the driver when the underlying agent\n * surfaces an `authentication_error`. In Protocol v3 the runner mediates\n * the refresh via the `host.refresh_credential` capability and returns a\n * typed {@link CredentialMint}. The driver inspects the discriminator:\n *\n * - `mint.ok === true`: a fresh credential is now provisioned. The\n * driver re-attempts the in-flight prompt once.\n * - `mint.ok === false`: refresh failed (`code` carries a stable reason\n * such as `revoked`, `not-configured`, `provider-error`,\n * `backend-error`). The driver surfaces the original `AuthError` to\n * the caller.\n *\n * `args.configId` carries the platform `AIProviderConfig.id` the driver\n * was provisioned with (mirrors {@link AgentConfig.aiProviderConfigId}).\n * The runner uses it to scope the refresh to the correct AI credential.\n *\n * When omitted, the driver throws `AuthError` immediately as before\n * (standalone CLI / forge mode — there is no platform mediator to ask).\n *\n * Centralising auth-retry inside the driver means every consumer of\n * `driver.prompt(...)` (serve handler, compaction orchestrator, flow\n * orchestrator, …) gets self-healing for free — there is no per-call-site\n * wrapping.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"host.refresh_credential capability\".\n *\n * @since 3.4.0\n */\n onAuthError?: (args: { configId: string }) => Promise<CredentialMint>;\n}\n\n/**\n * A single message in an agent conversation.\n *\n * Emitted as part of {@link AgentEvent} variants (`message_start`, `message_update`, `message_end`).\n *\n * @docLink packages/bridge/concepts#agent-message\n */\nexport interface AgentMessage {\n /** Originator of the message. */\n role: \"user\" | \"assistant\" | \"tool\";\n /** Message body — either a plain string or a list of typed content blocks. */\n content: string | ContentBlock[];\n /** Tool invocations made by the assistant in this message. */\n toolCalls?: ToolCall[];\n /** For `role === \"tool\"`: the name of the tool whose result this message carries. */\n toolName?: string;\n /** For `role === \"tool\"`: `true` when the tool returned an error. */\n isError?: boolean;\n /** Optional structured payload for tool results. */\n data?: unknown;\n}\n\n/**\n * A typed block within an {@link AgentMessage}'s content array.\n *\n * Mirrors the Anthropic content block schema but is driver-agnostic.\n *\n * @docLink packages/bridge/concepts#content-block\n */\nexport interface ContentBlock {\n /** Block discriminant. */\n type: \"text\" | \"tool_use\" | \"tool_result\" | \"thinking\";\n /** Present for `text` and `thinking` blocks. */\n text?: string;\n /** Tool use / tool result correlation ID. */\n id?: string;\n /** Tool name (present on `tool_use` blocks). */\n name?: string;\n /** Tool input arguments (present on `tool_use` blocks). */\n input?: any;\n /** Serialised tool result content (present on `tool_result` blocks). */\n content?: string;\n}\n\n/**\n * A single tool invocation made by the agent within a message.\n *\n * @docLink packages/bridge/concepts#tool-call\n */\nexport interface ToolCall {\n /** Correlation ID used to match the call with its result. */\n id: string;\n /** Name of the tool being invoked. */\n name: string;\n /** Arguments passed to the tool. */\n input: any;\n}\n\n/**\n * Error classification for agent failures.\n *\n * Used to determine whether a failure is retryable and to surface actionable\n * hints to the user. See `bridge/CLAUDE.md` for the full category-to-behaviour matrix.\n *\n * @see AgentError\n * @docLink packages/bridge/concepts#error-category\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"account\"\n | \"rate_limit\"\n | \"model\"\n | \"network\"\n | \"config\"\n | \"process\"\n | \"validation\"\n | \"unknown\";\n\n/**\n * Structured error payload emitted inside the `error` {@link AgentEvent}.\n *\n * Consumers should inspect `retryable` before deciding to surface a retry button,\n * and `hint` to provide an actionable message to the user.\n *\n * @docLink packages/bridge/concepts#agent-error\n */\nexport interface AgentError {\n /** Human-readable error description. */\n message: string;\n /** Coarse failure classification used for retry logic and telemetry. */\n category: ErrorCategory;\n /** HTTP status code if the error originated from an API response. */\n statusCode?: number;\n /** `true` when the caller may safely retry the same operation. */\n retryable: boolean;\n /** Short actionable advice suitable for display in the UI. */\n hint?: string;\n}\n\n/**\n * Metadata for a slash command exposed by the active agent runtime.\n *\n * @docLink packages/bridge/concepts#slash-command-info\n */\nexport interface SlashCommandInfo {\n /** Command name without the leading slash (e.g. `\"compact\"`). */\n name: string;\n /** One-line description shown in command pickers. */\n description: string;\n /** Placeholder text describing what argument the command expects. */\n argumentHint?: string;\n}\n\n/**\n * Discriminated union of all events emitted by a driver on the `'agent-event'` channel.\n *\n * @remarks\n * Consumers listen via `driver.on('agent-event', (event: AgentEvent) => ...)`.\n * The `[k: string]: any` index signature on most variants allows drivers to attach\n * driver-specific fields (e.g. `_textDelta`) without breaking the union.\n *\n * @docLink packages/bridge/concepts#agent-event\n */\nexport type AgentEvent =\n | { type: \"message_start\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_update\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_end\"; message: AgentMessage; [k: string]: any }\n | { type: \"turn_end\"; toolResults?: AgentMessage[]; [k: string]: any }\n | { type: \"agent_end\"; [k: string]: any }\n | {\n type: \"result\";\n subtype: string;\n summary?: string;\n costUsd?: number;\n /** Per-turn token usage when the driver tracks it. Added in 3.1.0. */\n tokens?: TokenUsage;\n errors?: string[];\n [k: string]: any;\n }\n | { type: \"error\"; error: string; detail?: AgentError; fatal?: boolean; [k: string]: any }\n | { type: \"tool_call\"; name?: string; tool?: { name: string }; [k: string]: any }\n | { type: \"tool_execution_end\"; toolName?: string; [k: string]: any }\n | { type: \"commands_available\"; commands: SlashCommandInfo[] }\n | { type: \"session_info\"; driverSessionId: string; sessionFile?: string }\n | { type: \"ui_render\"; [k: string]: any }\n | { type: \"ui_render_update\"; [k: string]: any }\n | { type: \"ui_clear\"; [k: string]: any }\n // Phase 3 (resume cascade) — driver-emitted resume outcome.\n | {\n type: \"resume_failed\";\n resumeSessionId: string;\n reason: \"signature_mismatch\" | \"model_mismatch\" | \"jsonl_lost\" | \"jsonl_poisoned\";\n [k: string]: any;\n };\n\n/**\n * Abstract base class for agent driver backends.\n *\n * Wraps an LLM coding agent behind a single `prompt()` interface.\n * All drivers emit `'agent-event'` with {@link AgentEvent} payloads.\n *\n * @remarks\n * Subclasses must implement `start`, `prompt`, `abort`, `kill`, and `isRunning`.\n * Implementations should never emit an event name other than `'agent-event'` as\n * the public streaming channel — internal events (`'ready'`, `'exit'`, etc.) are\n * driver-private.\n *\n * @example\n * ```ts\n * const driver = createDriver('omp', config);\n * driver.on('agent-event', (event) => console.log(event.type));\n * await driver.start();\n * await driver.prompt('Refactor the auth module');\n * driver.kill();\n * ```\n *\n * @docLink packages/bridge/concepts#agent-driver\n */\nexport abstract class AgentDriver extends EventEmitter {\n /** Static metadata describing this driver's capabilities. */\n abstract readonly driverInfo: DriverInfo;\n\n /**\n * Initialises the driver backend — spawns the child process (omp) or loads\n * the SDK module (claude-sdk). Resolves when the backend is ready to accept\n * prompts. Idempotent: calling `start()` on an already-running driver is a no-op.\n *\n * @throws {Error} When the backend binary is missing or the SDK cannot be loaded.\n */\n abstract start(): Promise<void>;\n\n /**\n * Sends a user message to the agent and resolves when the agent's turn completes\n * (i.e. after the `agent_end` event has been emitted).\n *\n * @param message - Plain-text user prompt to send to the agent.\n * @throws {Error} When the driver is not running or the underlying backend reports a fatal error.\n */\n abstract prompt(message: string): Promise<void>;\n\n /**\n * Sends an in-band abort signal to the agent, requesting it to stop the current\n * turn without terminating the process. The driver remains usable after `abort()`.\n *\n * @remarks Only meaningful when `driverInfo.supportsInBandAbort` is `true`.\n * For other drivers, prefer `kill()` followed by creating a new driver instance.\n */\n abstract abort(): Promise<void>;\n\n /**\n * Terminates the agent backend immediately (SIGTERM for subprocess drivers,\n * `close()` for in-process drivers). The driver instance must not be reused\n * after `kill()`.\n */\n abstract kill(): void;\n\n /** `true` when the backend is alive and able to accept new prompts. */\n abstract get isRunning(): boolean;\n\n /** Optional provider-native session/thread identifier for resume support. */\n get runtimeSessionId(): string | undefined {\n return undefined;\n }\n\n /** Slash commands discovered from the agent runtime. Override in drivers that support introspection. */\n getSlashCommands(): SlashCommandInfo[] {\n return [];\n }\n\n // ── Interactive questions (AskUserQuestion) ──────────────────────────────\n\n /**\n * `true` while the driver is paused on an interactive question and waiting\n * for the user's answer rather than a new prompt. The runner routes a\n * `reply` command to {@link answerQuestion} instead of {@link prompt} when\n * this returns `true`. Drivers without interactive-question support return\n * `false` (the default), so a `reply` falls back to `prompt`.\n */\n hasPendingQuestion(): boolean {\n return false;\n }\n\n /**\n * Deliver the user's answer to the question the driver is currently paused\n * on. This resumes the in-flight turn — it does NOT start a new one. When a\n * single tool call asks several questions, replies arrive one per `question`\n * event in order and the driver resolves the underlying call only once every\n * sub-question has an answer.\n *\n * @param answer - The user's reply text (an option label, free text, or for\n * multi-select a comma-joined list).\n * @returns `true` when the answer was consumed by a pending question; `false`\n * when no question was pending (caller should treat the reply as a prompt).\n */\n answerQuestion(answer: string): boolean {\n void answer;\n return false;\n }\n\n // ── Live reconfiguration ────────────────────────────────────────────────\n\n /**\n * Live-update driver configuration. The new values take effect on the next\n * prompt() call. Only model/thinking/effort are reconfigurable mid-session.\n *\n * Subclasses that store config locally should override this to apply the\n * patch to their own config field. The base implementation is a no-op.\n */\n reconfigure(patch: Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>): void {\n // No-op — subclasses override to apply to their own config.\n void patch;\n }\n\n /**\n * Returns the model identifier currently configured on this driver.\n * Subclasses that store config locally should override this.\n */\n getModel(): string | undefined {\n return undefined;\n }\n\n // ── Compaction support ──────────────────────────────────────────────────\n\n /**\n * Returns the token usage from the most recent completed turn.\n * Returns `null` if usage data is unavailable (e.g. driver doesn't track it).\n *\n * Widened in 3.1.0 to return the full `TokenUsage` shape (input / output /\n * cache-read / cache-creation / reasoning). All fields are optional so\n * drivers can populate just what their provider reports. Existing callers\n * that read only `inputTokens` / `outputTokens` keep working — those fields\n * are still present and carry the same semantics as before.\n */\n getTokenUsage(): TokenUsage | null {\n return null;\n }\n\n /**\n * Returns the model's context window size in tokens.\n * Returns `null` if unknown.\n */\n getContextWindow(): number | null {\n return null;\n }\n\n /**\n * Returns the list of models available to this driver without starting a session.\n * Drivers that can enumerate their own models override this method.\n * Returns an empty array by default.\n */\n async listModels(): Promise<ModelEntry[]> {\n return [];\n }\n\n /**\n * Closes the current conversation session and prepares for a fresh start.\n * The next `prompt()` call will begin a new session without prior history.\n * The driver remains usable after `resetSession()`.\n */\n abstract resetSession(): Promise<void>;\n\n // ── Telemetry ─────────────────────────────────────────────────────────────\n\n protected _telemetry?: TelemetryProvider;\n protected _activeTrace?: Trace;\n protected _activeTurnSpan?: Span;\n private _turnStartTime?: number;\n\n /**\n * Attach a telemetry provider and active trace to this driver.\n * Called by the runner after creating the driver but before start().\n */\n setTelemetry(provider: TelemetryProvider, trace: Trace): void {\n this._telemetry = provider;\n this._activeTrace = trace;\n }\n\n /**\n * Begin a turn span. Called by the runner before prompt().\n * Pass a parent span (e.g. the turn span from the orchestrator) for nesting.\n * Returns the span so the runner can annotate it further.\n */\n beginTurnSpan(\n parent?: Trace | Span,\n attrs?: Record<string, string | number | boolean>,\n ): Span | undefined {\n if (!this._telemetry || !this._activeTrace) return undefined;\n this._turnStartTime = Date.now();\n this._activeTurnSpan = this._telemetry.startSpan(parent ?? this._activeTrace, {\n name: \"llm_generation\",\n kind: \"llm_generation\",\n attributes: attrs,\n });\n return this._activeTurnSpan;\n }\n\n /**\n * End the current turn span with generation data.\n * Called by the runner after agent_end. Model and provider are passed\n * explicitly — the driver base class does not access config directly.\n */\n endTurnSpan(result?: {\n model?: string;\n provider?: string;\n inputTokens?: number;\n outputTokens?: number;\n stopReason?: string;\n error?: string;\n }): void {\n if (!this._telemetry || !this._activeTurnSpan) return;\n const durationMs = this._turnStartTime ? Date.now() - this._turnStartTime : 0;\n\n if (result?.inputTokens !== undefined || result?.outputTokens !== undefined) {\n this._telemetry.logGeneration(this._activeTurnSpan, {\n model: result?.model ?? \"unknown\",\n provider: result?.provider ?? \"unknown\",\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n durationMs,\n stopReason: result.stopReason,\n });\n }\n\n this._telemetry.endSpan(this._activeTurnSpan, {\n status: result?.error ? \"error\" : \"ok\",\n error: result?.error,\n attributes: { \"skaile.turn.duration_ms\": durationMs },\n });\n\n this._activeTurnSpan = undefined;\n this._turnStartTime = undefined;\n }\n}\n\n/**\n * Factory function signature registered in the driver registry.\n *\n * @param config - Configuration for the new driver instance.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @docLink packages/bridge/concepts#driver-factory\n */\nexport type DriverFactory = (config: AgentConfig) => AgentDriver;\n","import type { DriverContext } from \"@skaile/workspaces/plugin-registry\";\nimport { type PluginRegistry, pluginRegistry } from \"@skaile/workspaces/plugin-registry\";\nimport type { ModelEntry } from \"./models.js\";\nimport type { AgentConfig, AgentDriver, DriverInfo } from \"./types.js\";\n\n// Build-time backend gating. `bun build --compile --define:__INCLUDE_*__=...`\n// folds these to literal booleans so an excluded backend's driver module and\n// its SDK are dead-code-stripped from the binary. Under tsup / vitest / bun\n// run-on-source no `--define` runs and the `typeof` guard defaults to `true` —\n// every backend is available (the SDKs stay optional peers).\ndeclare const __INCLUDE_CLAUDE_SDK__: boolean;\ndeclare const __INCLUDE_CODEX__: boolean;\nconst INCLUDE_CLAUDE_SDK =\n typeof __INCLUDE_CLAUDE_SDK__ === \"undefined\" ? true : __INCLUDE_CLAUDE_SDK__;\nconst INCLUDE_CODEX = typeof __INCLUDE_CODEX__ === \"undefined\" ? true : __INCLUDE_CODEX__;\n\n/**\n * Static capability metadata for every built-in backend.\n *\n * Pure data — this object imports no driver module and references no backend\n * SDK. {@link listDrivers} returns it (merged with any third-party drivers)\n * so selection UIs can enumerate every backend without loading a single\n * driver module. The matching driver module's `DriverTarget` is registered\n * into the plugin registry by {@link registerBuiltinDrivers}.\n *\n * @docLink packages/bridge/api-reference#registry\n */\nexport const BUILTIN_DRIVER_CATALOG: Record<string, DriverInfo> = {\n omp: {\n id: \"omp\",\n name: \"omp (oh-my-pi)\",\n modelAgnostic: true,\n supportsInBandAbort: true,\n },\n \"claude-sdk\": {\n id: \"claude-sdk\",\n name: \"Claude Agent SDK\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n codex: {\n id: \"codex\",\n name: \"OpenAI Codex\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n echo: {\n id: \"echo\",\n name: \"Echo (E2E mock)\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n gemini: {\n id: \"gemini\",\n name: \"Gemini CLI\",\n modelAgnostic: false,\n supportsInBandAbort: false,\n },\n qwen: {\n id: \"qwen\",\n name: \"Qwen Code\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n opencode: {\n id: \"opencode\",\n name: \"OpenCode\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n goose: {\n id: \"goose\",\n name: \"Goose\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n continue: {\n id: \"continue\",\n name: \"Continue CLI\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n};\n\n/**\n * Back-compat alias for {@link BUILTIN_DRIVER_CATALOG}. Consumers and tests that\n * predate the plugin-registry refactor still import `DRIVER_CATALOG`.\n *\n * @docLink packages/bridge/api-reference#registry\n */\nexport const DRIVER_CATALOG = BUILTIN_DRIVER_CATALOG;\n\nlet _driversRegistered = false;\n\n/**\n * Register every built-in driver's `DriverTarget` into the plugin registry.\n *\n * This is the single id → module map in bridge core. Every specifier is a\n * literal string so `bun --compile` can statically bundle the driver module\n * (and, transitively, its SDK). The in-process-SDK backends (`claude-sdk`,\n * `codex`) are wrapped in build-constant guards so an excluded backend's\n * `await import` folds to dead code in the compiled binary. `omp` and `echo`\n * carry no SDK weight and are always available.\n *\n * **Static import discipline.** Every `import()` specifier below must be a\n * string literal — never aliased through a variable. Indirection defeats\n * `bun --compile`'s static analysis and silently drops the module from the\n * binary.\n *\n * Idempotent: guarded by a module flag so a second call is a no-op (a duplicate\n * `register` would otherwise throw `RegistrationError`).\n *\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function registerBuiltinDrivers(\n registry: PluginRegistry = pluginRegistry,\n): Promise<void> {\n if (registry === pluginRegistry && _driversRegistered) return;\n\n if (!registry.get(\"driver\", \"omp\")) {\n const m = await import(\"@skaile/workspaces/drivers/omp\");\n registry.register(\"driver\", m.ompDriverTarget);\n }\n if (!registry.get(\"driver\", \"echo\")) {\n const m = await import(\"@skaile/workspaces/drivers/echo\");\n registry.register(\"driver\", m.echoDriverTarget);\n }\n if (INCLUDE_CLAUDE_SDK && !registry.get(\"driver\", \"claude-sdk\")) {\n const m = await import(\"@skaile/workspaces/drivers/claude-sdk\");\n registry.register(\"driver\", m.claudeSdkDriverTarget);\n }\n if (INCLUDE_CODEX && !registry.get(\"driver\", \"codex\")) {\n const m = await import(\"@skaile/workspaces/drivers/codex\");\n registry.register(\"driver\", m.codexDriverTarget);\n }\n // Subprocess CLI backends spawn an external binary the user installs\n // separately — no bundled SDK to dead-code-strip, so (like omp/echo) they\n // carry no build constant and are always registered.\n if (!registry.get(\"driver\", \"gemini\")) {\n const m = await import(\"@skaile/workspaces/drivers/gemini\");\n registry.register(\"driver\", m.geminiDriverTarget);\n }\n if (!registry.get(\"driver\", \"qwen\")) {\n const m = await import(\"@skaile/workspaces/drivers/qwen\");\n registry.register(\"driver\", m.qwenDriverTarget);\n }\n if (!registry.get(\"driver\", \"opencode\")) {\n const m = await import(\"@skaile/workspaces/drivers/opencode\");\n registry.register(\"driver\", m.opencodeDriverTarget);\n }\n if (!registry.get(\"driver\", \"goose\")) {\n const m = await import(\"@skaile/workspaces/drivers/goose\");\n registry.register(\"driver\", m.gooseDriverTarget);\n }\n if (!registry.get(\"driver\", \"continue\")) {\n const m = await import(\"@skaile/workspaces/drivers/continue\");\n registry.register(\"driver\", m.continueDriverTarget);\n }\n\n if (registry === pluginRegistry) _driversRegistered = true;\n}\n\n/**\n * Creates a new driver instance for the given backend id.\n *\n * Ensures the built-in driver targets are registered (idempotent), then looks\n * up the target in the plugin registry and calls its `create()`. The returned\n * driver has not been started yet — call `driver.start()` before sending\n * prompts.\n *\n * @param id - Registered driver identifier (e.g. `\"omp\"`, `\"claude-sdk\"`).\n * @param config - Configuration forwarded to the driver constructor.\n * @param ctx - Optional driver context (logger / abort signal). Defaults to `{}`.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @throws {Error} When `id` is a known backend excluded from this build, or\n * when `id` does not match any registered driver at all.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function createDriver(\n id: string,\n config: AgentConfig,\n ctx?: DriverContext,\n): Promise<AgentDriver> {\n const target = await resolveDriverTarget(id);\n return target.create(config, ctx ?? {});\n}\n\n/**\n * Resolve a registered driver target by id, ensuring the built-ins are\n * registered first. Throws the canonical \"not bundled\" / \"unknown driver\"\n * errors so every caller (`createDriver`, `listModelsForDriver`) reports an\n * unrecognized id the same way instead of silently degrading.\n *\n * @throws {Error} When `id` is a known backend excluded from this build, or\n * when `id` does not match any registered driver at all.\n */\nasync function resolveDriverTarget(id: string) {\n await registerBuiltinDrivers();\n const target = pluginRegistry.get(\"driver\", id);\n if (!target) {\n if (id in BUILTIN_DRIVER_CATALOG) {\n throw new Error(`Agent driver \"${id}\" is not bundled in this build.`);\n }\n throw new Error(\n `Unknown agent driver: \"${id}\". Available: ${listDrivers()\n .map((d) => d.id)\n .join(\", \")}`,\n );\n }\n return target;\n}\n\n/**\n * Returns the capability metadata for every available driver.\n *\n * Enumerates every built-in backend from {@link BUILTIN_DRIVER_CATALOG} without\n * loading a single driver module or backend SDK, then merges in any third-party\n * driver targets registered into the plugin registry that are not already in\n * the catalog. Use this to populate driver selection UIs.\n *\n * @returns Array of {@link DriverInfo} objects, one per available driver.\n * @docLink packages/bridge/api-reference#registry\n */\nexport function listDrivers(): DriverInfo[] {\n const merged = new Map<string, DriverInfo>();\n for (const info of Object.values(BUILTIN_DRIVER_CATALOG)) {\n merged.set(info.id, info);\n }\n for (const meta of pluginRegistry.list(\"driver\")) {\n if (!merged.has(meta.id)) {\n // Third-party drivers carry no DriverInfo row; read the capability flags\n // off the registered target (defaulting to conservative false) so a\n // model-agnostic / in-band-abort backend can still advertise them.\n const target = pluginRegistry.get(\"driver\", meta.id);\n merged.set(meta.id, {\n id: meta.id,\n name: meta.displayName,\n modelAgnostic: target?.modelAgnostic ?? false,\n supportsInBandAbort: target?.supportsInBandAbort ?? false,\n });\n }\n }\n return [...merged.values()];\n}\n\n/**\n * List models available to a specific driver without starting a full agent session.\n *\n * Ensures the built-in driver targets are registered (idempotent), then\n * delegates to the target's optional `listModels()`. API keys are forwarded so\n * drivers can authenticate against provider REST APIs if needed. Throws on an\n * unknown / not-bundled id (same contract as {@link createDriver}); returns `[]`\n * only when the target exists but exposes no `listModels`.\n *\n * @param driverId - Registered driver id (e.g. `\"omp\"`, `\"claude-sdk\"`, `\"codex\"`).\n * @param apiKeys - Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Pass `settings.apiKeys ?? {}` from forge-assistant's resolved settings.\n * @throws {Error} When `driverId` is unknown or excluded from this build.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function listModelsForDriver(\n driverId: string,\n apiKeys: Record<string, string>,\n): Promise<ModelEntry[]> {\n const target = await resolveDriverTarget(driverId);\n return (await target.listModels?.(apiKeys)) ?? [];\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { MENTION_GROUPS } from './chunk-EVZKWY5J.js';
1
+ import { MENTION_GROUPS } from './chunk-PK7Q7MC7.js';
2
2
 
3
3
  // session/src/dispatcher.ts
4
4
  var TRANSIENT_TYPES = /* @__PURE__ */ new Set([
@@ -516,5 +516,5 @@ function isAgentAddressed(mentions) {
516
516
  }
517
517
 
518
518
  export { SessionDispatcher, isAddressedByKind, isAgentAddressed, isMentioned, parseMentions };
519
- //# sourceMappingURL=chunk-Z5Z3MYDL.js.map
520
- //# sourceMappingURL=chunk-Z5Z3MYDL.js.map
519
+ //# sourceMappingURL=chunk-UPZGQZEJ.js.map
520
+ //# sourceMappingURL=chunk-UPZGQZEJ.js.map