@skaile/workspaces 3.16.2 → 3.18.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 (274) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/app-sdk/index.js +1 -1
  3. package/dist/{asset-feeds-FQT6GH24.js → asset-feeds-LT4GI576.js} +7 -7
  4. package/dist/{asset-feeds-FQT6GH24.js.map → asset-feeds-LT4GI576.js.map} +1 -1
  5. package/dist/asset-manager/catalog-deployer.js +3 -3
  6. package/dist/asset-manager/index.js +6 -6
  7. package/dist/asset-manager/installer.js +4 -4
  8. package/dist/bridge/codex-app-server.d.ts +2 -0
  9. package/dist/bridge/codex-app-server.js +5 -0
  10. package/dist/bridge/codex-app-server.js.map +1 -0
  11. package/dist/bridge/drivers/claude-sdk.js +5 -5
  12. package/dist/bridge/drivers/codex.js +1137 -4
  13. package/dist/bridge/drivers/codex.js.map +1 -1
  14. package/dist/bridge/drivers/continue.js +2 -2
  15. package/dist/bridge/drivers/echo.js +2 -2
  16. package/dist/bridge/drivers/gemini.js +3 -3
  17. package/dist/bridge/drivers/goose.js +2 -2
  18. package/dist/bridge/drivers/omp.js +1 -1
  19. package/dist/bridge/drivers/opencode.js +2 -2
  20. package/dist/bridge/drivers/qwen.js +3 -3
  21. package/dist/bridge/index.js +7 -6
  22. package/dist/bridge/src/capability-dispatch.d.ts +1 -1
  23. package/dist/bridge/src/capability-dispatch.d.ts.map +1 -1
  24. package/dist/bridge/src/codex/credentials.d.ts +12 -0
  25. package/dist/bridge/src/codex/credentials.d.ts.map +1 -0
  26. package/dist/bridge/src/codex/inputs.d.ts +8 -0
  27. package/dist/bridge/src/codex/inputs.d.ts.map +1 -0
  28. package/dist/bridge/src/codex/instance-state.d.ts +16 -0
  29. package/dist/bridge/src/codex/instance-state.d.ts.map +1 -0
  30. package/dist/bridge/src/codex/managed-driver.d.ts +71 -0
  31. package/dist/bridge/src/codex/managed-driver.d.ts.map +1 -0
  32. package/dist/bridge/src/codex/native-approvals.d.ts +22 -0
  33. package/dist/bridge/src/codex/native-approvals.d.ts.map +1 -0
  34. package/dist/bridge/src/codex/native-policy.d.ts +38 -0
  35. package/dist/bridge/src/codex/native-policy.d.ts.map +1 -0
  36. package/dist/bridge/src/codex/native-protocol.generated.d.ts +1411 -0
  37. package/dist/bridge/src/codex/native-protocol.generated.d.ts.map +1 -0
  38. package/dist/bridge/src/codex/native-state.d.ts +7 -0
  39. package/dist/bridge/src/codex/native-state.d.ts.map +1 -0
  40. package/dist/bridge/src/codex/questions.d.ts +19 -0
  41. package/dist/bridge/src/codex/questions.d.ts.map +1 -0
  42. package/dist/bridge/src/codex-app-server.d.ts +60 -0
  43. package/dist/bridge/src/codex-app-server.d.ts.map +1 -0
  44. package/dist/bridge/src/drivers/codex.d.ts +9 -1
  45. package/dist/bridge/src/drivers/codex.d.ts.map +1 -1
  46. package/dist/bridge/src/index.d.ts +1 -0
  47. package/dist/bridge/src/index.d.ts.map +1 -1
  48. package/dist/bridge/src/normalizer.d.ts.map +1 -1
  49. package/dist/bridge/src/runtime.d.ts +3 -2
  50. package/dist/bridge/src/runtime.d.ts.map +1 -1
  51. package/dist/bridge/src/types.d.ts +77 -4
  52. package/dist/bridge/src/types.d.ts.map +1 -1
  53. package/dist/{chunk-2KBA5OO2.js → chunk-23L3P7IB.js} +4 -4
  54. package/dist/{chunk-2KBA5OO2.js.map → chunk-23L3P7IB.js.map} +1 -1
  55. package/dist/{chunk-NC5YXVZF.js → chunk-2FDKUKDE.js} +3 -3
  56. package/dist/{chunk-NC5YXVZF.js.map → chunk-2FDKUKDE.js.map} +1 -1
  57. package/dist/{chunk-GRVSSAAQ.js → chunk-2IROGAS7.js} +2 -2
  58. package/dist/{chunk-GRVSSAAQ.js.map → chunk-2IROGAS7.js.map} +1 -1
  59. package/dist/{chunk-BUKPS4YL.js → chunk-4JDCKPTM.js} +2 -2
  60. package/dist/{chunk-BUKPS4YL.js.map → chunk-4JDCKPTM.js.map} +1 -1
  61. package/dist/{chunk-5KSIVLOX.js → chunk-5T7Y3AZU.js} +3 -3
  62. package/dist/{chunk-5KSIVLOX.js.map → chunk-5T7Y3AZU.js.map} +1 -1
  63. package/dist/{chunk-SWUVULBU.js → chunk-67KB2A77.js} +7 -7
  64. package/dist/{chunk-SWUVULBU.js.map → chunk-67KB2A77.js.map} +1 -1
  65. package/dist/{chunk-RRVQAE5D.js → chunk-7ZO3MUP3.js} +6 -5
  66. package/dist/chunk-7ZO3MUP3.js.map +1 -0
  67. package/dist/{chunk-EO7IJY3Q.js → chunk-AI2PZX4H.js} +3 -3
  68. package/dist/{chunk-EO7IJY3Q.js.map → chunk-AI2PZX4H.js.map} +1 -1
  69. package/dist/{chunk-CMGYUF5P.js → chunk-BJI7IGZF.js} +7 -7
  70. package/dist/{chunk-CMGYUF5P.js.map → chunk-BJI7IGZF.js.map} +1 -1
  71. package/dist/{chunk-HY6CIKFH.js → chunk-CP62G5PK.js} +8 -7
  72. package/dist/chunk-CP62G5PK.js.map +1 -0
  73. package/dist/{chunk-PBRMY64S.js → chunk-CQY7XKRV.js} +30 -9
  74. package/dist/chunk-CQY7XKRV.js.map +1 -0
  75. package/dist/{chunk-OIDFK7SG.js → chunk-DCG4UWJM.js} +3 -3
  76. package/dist/{chunk-OIDFK7SG.js.map → chunk-DCG4UWJM.js.map} +1 -1
  77. package/dist/{chunk-VT4MPCRK.js → chunk-FBD5SOIH.js} +3 -3
  78. package/dist/{chunk-VT4MPCRK.js.map → chunk-FBD5SOIH.js.map} +1 -1
  79. package/dist/{chunk-DUMD4AA2.js → chunk-FYVDBIZV.js} +6 -6
  80. package/dist/{chunk-DUMD4AA2.js.map → chunk-FYVDBIZV.js.map} +1 -1
  81. package/dist/{chunk-RTM4SFLA.js → chunk-GMKNGIIB.js} +7 -4
  82. package/dist/chunk-GMKNGIIB.js.map +1 -0
  83. package/dist/{chunk-NIQPSQFN.js → chunk-GMMACS5W.js} +4 -4
  84. package/dist/{chunk-NIQPSQFN.js.map → chunk-GMMACS5W.js.map} +1 -1
  85. package/dist/{chunk-QFYEDM63.js → chunk-GRA4BWCV.js} +5 -5
  86. package/dist/{chunk-QFYEDM63.js.map → chunk-GRA4BWCV.js.map} +1 -1
  87. package/dist/{chunk-CIPK5JMJ.js → chunk-H662SXKS.js} +4 -4
  88. package/dist/{chunk-CIPK5JMJ.js.map → chunk-H662SXKS.js.map} +1 -1
  89. package/dist/{chunk-4W2OOVN5.js → chunk-IST2V7RU.js} +3 -3
  90. package/dist/{chunk-4W2OOVN5.js.map → chunk-IST2V7RU.js.map} +1 -1
  91. package/dist/{chunk-L2UE4YJO.js → chunk-IT42ZT3T.js} +9 -9
  92. package/dist/{chunk-L2UE4YJO.js.map → chunk-IT42ZT3T.js.map} +1 -1
  93. package/dist/{chunk-FRER2PEN.js → chunk-J7VSUGGH.js} +16 -3
  94. package/dist/chunk-J7VSUGGH.js.map +1 -0
  95. package/dist/{chunk-ZNCZ7RUO.js → chunk-JVFZ5R7L.js} +3 -3
  96. package/dist/{chunk-ZNCZ7RUO.js.map → chunk-JVFZ5R7L.js.map} +1 -1
  97. package/dist/chunk-LOO5CB5M.js +12 -0
  98. package/dist/chunk-LOO5CB5M.js.map +1 -0
  99. package/dist/{chunk-AL6BU3SP.js → chunk-OJ4N4T4H.js} +12 -4
  100. package/dist/chunk-OJ4N4T4H.js.map +1 -0
  101. package/dist/chunk-QEZPFJX3.js +254 -0
  102. package/dist/chunk-QEZPFJX3.js.map +1 -0
  103. package/dist/{chunk-C4AP3XZB.js → chunk-QG2ZXU5W.js} +4 -4
  104. package/dist/{chunk-C4AP3XZB.js.map → chunk-QG2ZXU5W.js.map} +1 -1
  105. package/dist/{chunk-I3COVVFB.js → chunk-RJOGAEIY.js} +1024 -204
  106. package/dist/chunk-RJOGAEIY.js.map +1 -0
  107. package/dist/{chunk-OZ7UNMTK.js → chunk-RPVTPVGX.js} +7 -5
  108. package/dist/chunk-RPVTPVGX.js.map +1 -0
  109. package/dist/{chunk-S4UA244H.js → chunk-S635WMXH.js} +4 -4
  110. package/dist/{chunk-S4UA244H.js.map → chunk-S635WMXH.js.map} +1 -1
  111. package/dist/{chunk-BQMRUH7J.js → chunk-SFCVAEJ5.js} +4 -4
  112. package/dist/{chunk-BQMRUH7J.js.map → chunk-SFCVAEJ5.js.map} +1 -1
  113. package/dist/{chunk-EXT2LNST.js → chunk-SH7GXS7V.js} +125 -37
  114. package/dist/chunk-SH7GXS7V.js.map +1 -0
  115. package/dist/chunk-T3YLZQS4.js +336 -0
  116. package/dist/chunk-T3YLZQS4.js.map +1 -0
  117. package/dist/{chunk-X7FJ3ES3.js → chunk-X3LUB275.js} +4 -4
  118. package/dist/{chunk-X7FJ3ES3.js.map → chunk-X3LUB275.js.map} +1 -1
  119. package/dist/chunk-XKSGEYZC.js +244 -0
  120. package/dist/chunk-XKSGEYZC.js.map +1 -0
  121. package/dist/{chunk-SUPIVTLX.js → chunk-XL45U3C5.js} +3 -3
  122. package/dist/{chunk-SUPIVTLX.js.map → chunk-XL45U3C5.js.map} +1 -1
  123. package/dist/{chunk-AXEOG4B5.js → chunk-YCMHWNZA.js} +3 -3
  124. package/dist/{chunk-AXEOG4B5.js.map → chunk-YCMHWNZA.js.map} +1 -1
  125. package/dist/cli/index.js +75 -53
  126. package/dist/cli/index.js.map +1 -1
  127. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  128. package/dist/client/index.js +1 -1
  129. package/dist/client/src/client.d.ts +3 -2
  130. package/dist/client/src/client.d.ts.map +1 -1
  131. package/dist/connectors/config.js +4 -4
  132. package/dist/connectors/index.js +12 -11
  133. package/dist/connectors/src/connector-prompt.d.ts +11 -0
  134. package/dist/connectors/src/connector-prompt.d.ts.map +1 -1
  135. package/dist/core/index.js +3 -3
  136. package/dist/core/runtime-assets.js +2 -2
  137. package/dist/core/src/workspace-config.d.ts.map +1 -1
  138. package/dist/core/workspace-config.js +1 -1
  139. package/dist/deploy/index.js +3 -3
  140. package/dist/{ensure-sources-4GBXK6UR.js → ensure-sources-4BQ6GMYG.js} +9 -9
  141. package/dist/{ensure-sources-4GBXK6UR.js.map → ensure-sources-4BQ6GMYG.js.map} +1 -1
  142. package/dist/factory-assets/connectors/box.js +12 -11
  143. package/dist/factory-assets/connectors/deploy.js +12 -11
  144. package/dist/factory-assets/connectors/devserver.js +12 -11
  145. package/dist/factory-assets/connectors/flow/CONNECTOR.md +4 -5
  146. package/dist/factory-assets/connectors/flow/adapter.d.ts +8 -0
  147. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  148. package/dist/factory-assets/connectors/flow/adapter.js +12 -11
  149. package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
  150. package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
  151. package/dist/factory-assets/connectors/flow/contract/schema.d.ts +50 -17
  152. package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
  153. package/dist/factory-assets/connectors/flow/contract.js +3 -3
  154. package/dist/factory-assets/connectors/flow/engine/index.d.ts +1 -0
  155. package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
  156. package/dist/factory-assets/connectors/flow/engine.js +5 -5
  157. package/dist/factory-assets/connectors/flow/run-flow.js +13 -12
  158. package/dist/factory-assets/connectors/flow/subprompt-runner.d.ts +10 -1
  159. package/dist/factory-assets/connectors/flow/subprompt-runner.d.ts.map +1 -1
  160. package/dist/factory-assets/connectors/flow.js +12 -11
  161. package/dist/factory-assets/connectors/git.js +12 -11
  162. package/dist/factory-assets/connectors/gmail.js +12 -11
  163. package/dist/factory-assets/connectors/googledrive.js +12 -11
  164. package/dist/factory-assets/connectors/local.js +12 -11
  165. package/dist/factory-assets/connectors/mattermost.js +12 -11
  166. package/dist/factory-assets/connectors/memory.js +12 -11
  167. package/dist/factory-assets/connectors/minio.js +12 -11
  168. package/dist/factory-assets/connectors/postgres.js +12 -11
  169. package/dist/factory-assets/connectors/s3.js +12 -11
  170. package/dist/factory-assets/connectors/sharepoint.js +12 -11
  171. package/dist/factory-assets/connectors/sqlite.js +12 -11
  172. package/dist/factory-assets/connectors/static-server.js +12 -11
  173. package/dist/factory-assets/connectors/tunnel.js +12 -11
  174. package/dist/factory-assets/connectors/webdav.js +12 -11
  175. package/dist/factory-assets/connectors/xstate-store.js +12 -11
  176. package/dist/factory-assets/connectors/xstate.js +12 -11
  177. package/dist/{flows-2SUFOVVO.js → flows-COBS26MK.js} +6 -6
  178. package/dist/{flows-2SUFOVVO.js.map → flows-COBS26MK.js.map} +1 -1
  179. package/dist/{helpers-26LW4IXY.js → helpers-4UJMSN6T.js} +9 -9
  180. package/dist/{helpers-26LW4IXY.js.map → helpers-4UJMSN6T.js.map} +1 -1
  181. package/dist/library/index.js +4 -4
  182. package/dist/library/install.js +3 -3
  183. package/dist/{library-publish-IYGHOPEK.js → library-publish-QHQDN4IC.js} +14 -14
  184. package/dist/{library-publish-IYGHOPEK.js.map → library-publish-QHQDN4IC.js.map} +1 -1
  185. package/dist/{open-library-HH5LST7Z.js → open-library-ZDM6DUKJ.js} +12 -12
  186. package/dist/{open-library-HH5LST7Z.js.map → open-library-ZDM6DUKJ.js.map} +1 -1
  187. package/dist/{paths-4APA2PKT.js → paths-CZPCCBYX.js} +6 -6
  188. package/dist/{paths-4APA2PKT.js.map → paths-CZPCCBYX.js.map} +1 -1
  189. package/dist/{plugin-store-JQAIKR3R.js → plugin-store-ZEIBSNTO.js} +5 -5
  190. package/dist/{plugin-store-JQAIKR3R.js.map → plugin-store-ZEIBSNTO.js.map} +1 -1
  191. package/dist/{project-U5QRUCBN.js → project-JJUAAI7N.js} +10 -10
  192. package/dist/{project-U5QRUCBN.js.map → project-JJUAAI7N.js.map} +1 -1
  193. package/dist/resolver/index.js +3 -3
  194. package/dist/runner/index.js +25 -16
  195. package/dist/runner/src/capability-registry.d.ts +4 -0
  196. package/dist/runner/src/capability-registry.d.ts.map +1 -1
  197. package/dist/runner/src/codex-init.d.ts +5 -0
  198. package/dist/runner/src/codex-init.d.ts.map +1 -0
  199. package/dist/runner/src/codex-resource-tools.d.ts +16 -0
  200. package/dist/runner/src/codex-resource-tools.d.ts.map +1 -0
  201. package/dist/runner/src/codex-tools.d.ts +12 -0
  202. package/dist/runner/src/codex-tools.d.ts.map +1 -0
  203. package/dist/runner/src/define-capability.d.ts +2 -0
  204. package/dist/runner/src/define-capability.d.ts.map +1 -1
  205. package/dist/runner/src/external-mcp.d.ts +8 -3
  206. package/dist/runner/src/external-mcp.d.ts.map +1 -1
  207. package/dist/runner/src/index.d.ts +2 -0
  208. package/dist/runner/src/index.d.ts.map +1 -1
  209. package/dist/runner/src/managed-codex-bootstrap.d.ts +54 -0
  210. package/dist/runner/src/managed-codex-bootstrap.d.ts.map +1 -0
  211. package/dist/runner/src/resources.d.ts +1 -0
  212. package/dist/runner/src/resources.d.ts.map +1 -1
  213. package/dist/runner/src/serve.d.ts +5 -0
  214. package/dist/runner/src/serve.d.ts.map +1 -1
  215. package/dist/runner/src/session-builder.d.ts +18 -1
  216. package/dist/runner/src/session-builder.d.ts.map +1 -1
  217. package/dist/sdk/asset-manager.js +6 -6
  218. package/dist/sdk/bridge.js +7 -6
  219. package/dist/sdk/client.js +1 -1
  220. package/dist/sdk/core.js +3 -3
  221. package/dist/sdk/flow.js +5 -5
  222. package/dist/sdk/index.js +26 -17
  223. package/dist/sdk/index.js.map +1 -1
  224. package/dist/sdk/resolver.js +3 -3
  225. package/dist/sdk/runner.js +25 -16
  226. package/dist/sdk/session.js +2 -2
  227. package/dist/sdk/store.js +1 -1
  228. package/dist/sdk/types.js +1 -1
  229. package/dist/session/index.js +2 -2
  230. package/dist/{setup-XKTBHRWM.js → setup-PS6ZERZ5.js} +9 -8
  231. package/dist/setup-PS6ZERZ5.js.map +1 -0
  232. package/dist/{skills-Q7PJVB3W.js → skills-LG6IQSSN.js} +5 -5
  233. package/dist/{skills-Q7PJVB3W.js.map → skills-LG6IQSSN.js.map} +1 -1
  234. package/dist/{source-6PBVTACZ.js → source-QLDIZCI3.js} +13 -13
  235. package/dist/{source-6PBVTACZ.js.map → source-QLDIZCI3.js.map} +1 -1
  236. package/dist/{source-manifest-publish-VBVNW7KL.js → source-manifest-publish-J3AVCTLX.js} +15 -15
  237. package/dist/{source-manifest-publish-VBVNW7KL.js.map → source-manifest-publish-J3AVCTLX.js.map} +1 -1
  238. package/dist/store/index.js +1 -1
  239. package/dist/store/react.js +1 -1
  240. package/dist/store/react.js.map +1 -1
  241. package/dist/store/src/react.d.ts +1 -1
  242. package/dist/store/src/react.d.ts.map +1 -1
  243. package/dist/store/src/store.d.ts +2 -1
  244. package/dist/store/src/store.d.ts.map +1 -1
  245. package/dist/tui/index.js +25 -16
  246. package/dist/tui/index.js.map +1 -1
  247. package/dist/types/index.js +1 -1
  248. package/dist/types/src/events.d.ts +14 -1
  249. package/dist/types/src/events.d.ts.map +1 -1
  250. package/dist/types/src/index.d.ts +3 -3
  251. package/dist/types/src/index.d.ts.map +1 -1
  252. package/dist/types/src/lifecycle.d.ts +43 -0
  253. package/dist/types/src/lifecycle.d.ts.map +1 -1
  254. package/dist/types/src/protocol.d.ts +18 -0
  255. package/dist/types/src/protocol.d.ts.map +1 -1
  256. package/dist/types/src/runtime.d.ts +3 -1
  257. package/dist/types/src/runtime.d.ts.map +1 -1
  258. package/dist/types/src/version.d.ts +7 -1
  259. package/dist/types/src/version.d.ts.map +1 -1
  260. package/dist/workspace-plugin/adapters/mcp.js +9 -255
  261. package/dist/workspace-plugin/adapters/mcp.js.map +1 -1
  262. package/dist/workspace-plugin/adapters/omp.js +7 -7
  263. package/dist/workspace-plugin/index.js +1 -1
  264. package/package.json +10 -1
  265. package/dist/chunk-AL6BU3SP.js.map +0 -1
  266. package/dist/chunk-EXT2LNST.js.map +0 -1
  267. package/dist/chunk-FRER2PEN.js.map +0 -1
  268. package/dist/chunk-HY6CIKFH.js.map +0 -1
  269. package/dist/chunk-I3COVVFB.js.map +0 -1
  270. package/dist/chunk-OZ7UNMTK.js.map +0 -1
  271. package/dist/chunk-PBRMY64S.js.map +0 -1
  272. package/dist/chunk-RRVQAE5D.js.map +0 -1
  273. package/dist/chunk-RTM4SFLA.js.map +0 -1
  274. package/dist/setup-XKTBHRWM.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/commands/source-manifest.ts","../cli/src/commands/source.ts"],"names":["path2","existsSync","spawnSync"],"mappings":";;;;;;;;;;;;;;AA+CA,IAAM,aAAA,GACJ,2IAAA;AAGF,SAAS,SAAS,IAAA,EAAqB;AACrC,EAAA,MAAA,CAAO,CAAA,EAAG,aAAa,CAAA,wBAAA,EAA2B,IAAI,CAAA,CAAA,CAAG,CAAA;AACzD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB;AAkBO,SAAS,gBAAA,CACd,KACA,UAAA,EACmE;AACnE,EAAA,MAAM,IAAA,GAAO,kBAAkB,UAAU,CAAA;AACzC,EAAA,MAAM,UAAA,GAA4B,OAC9B,kBAAA,CAAwB,IAAA,CAAA,IAAA,CAAK,MAAM,uBAAA,EAAyB,CAAC,CAAA,GAC7D,EAAC;AACL,EAAA,MAAM,KAAA,GAAQ,WAAW,IAAA,CAAK,CAAC,MAAM,gBAAA,CAAiB,CAAA,EAAG,GAAG,CAAC,CAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,GAAQ,kBAAA,CAAmB,GAAG,CAAA,GAAI,MAAA;AAClD,EAAA,MAAM,MAAM,KAAA,GAAQ,KAAA,CAAM,MAAO,MAAA,EAAQ,GAAA,IAAO,mBAAmB,GAAG,CAAA;AACtE,EAAA,MAAM,IAAA,GAAO,gBAAgB,GAAG,CAAA;AAChC,EAAA,MAAM,IAAA,GAAO,eAAA,CAAgB,cAAA,CAAe,GAAG,CAAC,CAAA;AAChD,EAAA,OAAO,EAAE,KAAK,IAAA,EAAM,IAAA,EAAM,cAAc,MAAA,EAAQ,YAAA,IAAgB,iBAAA,CAAkB,GAAG,CAAA,EAAE;AACzF;AAQA,SAAS,mBAA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A,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB,CAAC,CAAA;AAGH,EAAA,yBAAA,CAA0B,GAAG,CAAA;AAE7B,EAAA,OAAO,GAAA;AACT","file":"chunk-L2UE4YJO.js","sourcesContent":["/**\n * `skaile source manifest …` — curated `skaile.manifest.yaml` lifecycle for a\n * source you do NOT own. `init` generates a curated manifest from a discovery\n * run and stores it OUTSIDE the source, under the local store catalog\n * (`~/.skaile/store/manifests/<slug>.yaml`); `edit` opens it in `$EDITOR` and\n * re-validates on save. `source add`/`sync` then apply it as a read overlay\n * (see `source.ts` `refreshManifestCache`).\n *\n * `rebuild` refreshes a curated manifest after an upstream change (merge by\n * default — curation is sacred; `--overwrite` re-scans). `verify` is a\n * read-only integrity check (paths, declared hashes, schema, dep refs).\n * `publish`/`propose`/`yank` remain stubs — they need the store publish\n * endpoint (`POST /sources/<id>/manifest`), which lands in a follow-up.\n *\n * @docLink cli/commands/source#manifest\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AssetEntry,\n decodeSkaileManifest,\n encodeSkaileManifest,\n findWorkspaceRoot,\n parseAssetRef,\n resolveSourcePublisher,\n type SkPublishManifest,\n type SourceEntry,\n sourceCacheKey,\n sourceShortName,\n storeManifestSlug,\n workspaceConfigFilename,\n} from \"@skaile/workspaces/core\";\nimport { computeDeterministicHash, discoverAssetsInTree } from \"@skaile/workspaces/discovery\";\nimport { getStoreManifestsDir, writeCuratedManifest } from \"@skaile/workspaces/library\";\nimport type { Command } from \"commander\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { createFullRegistry } from \"../open-registry.ts\";\nimport {\n ensureClone,\n normalizeSourceUrl,\n readProjectSources,\n sourceClonePath,\n sourceMatchesKey,\n} from \"./source.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 * Resolve a `source manifest` argument into a `{ url, slug, dest }` triple.\n *\n * Resolution order:\n * 1. A key matching an already-registered project source (stored URL, cache\n * key, or short slug).\n * 2. A collision-free **store slug** (`<host>__<owner>__<repo>`) whose\n * manifest already exists at `~/.skaile/store/manifests/<arg>.yaml`. This\n * MUST be tried before bare-name expansion: a bare name like `cli` would\n * otherwise expand (via `normalizeSourceUrl`) to the skaile-ai org and a\n * DIFFERENT slug than the one `init` wrote (e.g. `larksuite`). The slug is\n * the exact identifier `init`'s next-step hint prints back.\n * 3. Otherwise a git URL / `owner/repo` / bare name via `normalizeSourceUrl`.\n *\n * The clone dir is the same URL-keyed cache `source add` uses.\n */\nexport function resolveSourceArg(\n arg: string,\n projectDir: string,\n): { url: string; slug: string; dest: string; manifestFile: string } {\n const root = findWorkspaceRoot(projectDir);\n const registered: SourceEntry[] = root\n ? readProjectSources(path.join(root, workspaceConfigFilename()))\n : [];\n const match = registered.find((e) => sourceMatchesKey(e, arg));\n const bySlug = !match ? resolveByStoreSlug(arg) : undefined;\n const url = match ? match.url : (bySlug?.url ?? normalizeSourceUrl(arg));\n const slug = sourceShortName(url); // human-facing label\n const dest = sourceClonePath(sourceCacheKey(url));\n return { url, slug, dest, manifestFile: bySlug?.manifestFile ?? storeManifestPath(url) };\n}\n\n/**\n * When `arg` is a bare store slug (`<host>__<owner>__<repo>`) whose curated\n * manifest already exists on disk, recover the source URL from the slug and\n * point at that manifest file directly. Returns `undefined` when the arg isn't\n * a slug or has no manifest yet (fall back to URL normalization).\n */\nfunction resolveByStoreSlug(arg: string): { url: string; manifestFile: string } | undefined {\n // A slug is our own encoding — no path/URL sigils, at least the `<host>__…`\n // separator. Anything URL/owner-repo shaped is not a slug.\n if (!/^[\\w.-]+__[\\w.-]+/.test(arg) || /[/:\\\\]/.test(arg)) return undefined;\n const manifestFile = path.join(getStoreManifestsDir(), `${arg}.yaml`);\n if (!existsSync(manifestFile)) return undefined;\n // `<host>__<owner>__<repo>` → `https://<host>/<owner>/<repo>` — good enough to\n // key the clone dir + re-derive the same slug; the manifest file is what edit\n // actually opens.\n const [host, owner, repo] = arg.split(\"__\");\n const url = host && owner && repo ? `https://${host}/${owner}/${repo}` : arg;\n return { url, manifestFile };\n}\n\n/**\n * Absolute path to a source's curated store manifest. Keyed by the\n * collision-free {@link storeManifestSlug} (`<host>__<owner>__<repo>`) so\n * `orgA/cli` and `orgB/cli` don't share `cli.yaml`.\n */\nfunction storeManifestPath(url: string): string {\n return path.join(getStoreManifestsDir(), `${storeManifestSlug(url)}.yaml`);\n}\n\n/**\n * Directory-name segments that mark a test-fixture tree. `init`/`rebuild` drop\n * any asset whose repo-relative root contains one of these as an exact path\n * SEGMENT. Repos routinely ship fixture \"skills\" under such dirs (e.g.\n * `scripts/skill-format-check/tests`, `internal/qualitygate/skillscan/testdata/skills/lark-demo`)\n * that are not real, publishable assets.\n */\nconst TEST_FIXTURE_SEGMENTS = new Set([\n \"tests\",\n \"test\",\n \"__tests__\",\n \"testdata\",\n \"fixtures\",\n \"__fixtures__\",\n]);\n\n/**\n * True when an asset's repo-relative `root` sits under a test-fixture directory\n * (see {@link TEST_FIXTURE_SEGMENTS}). Conservative, not repo-specific — finer\n * curation (keeping a genuine fixture asset) stays the user's job via `edit`.\n * `init`/`rebuild`-path only; the general discovery walk (`source add`) is\n * untouched.\n */\nfunction isTestFixtureAsset(relativePath: string): boolean {\n const segments = relativePath.replace(/\\\\/g, \"/\").split(\"/\");\n return segments.some((s) => TEST_FIXTURE_SEGMENTS.has(s));\n}\n\n/**\n * `source manifest init <src>` — clone (if needed), run discovery, and write a\n * curated `skaile.manifest.yaml` to `~/.skaile/store/manifests/<slug>.yaml`.\n */\nasync function runInit(\n arg: string,\n opts: { projectDir: string; publisher?: string; dev?: boolean; force?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (existsSync(target) && !opts.force) {\n logWarn(\n `A curated manifest already exists at ${S.dim(target)}. ` +\n \"Edit it with `skaile source manifest edit`, refresh it after an upstream \" +\n \"change with `skaile source manifest rebuild`, or pass --force to regenerate.\",\n );\n return;\n }\n\n const entry: SourceEntry = { url };\n ensureClone(entry);\n\n const { assets, errors } = discoverCuratableAssets(dest, opts.dev ?? false);\n\n const publisher = opts.publisher ?? resolveSourcePublisher(dest) ?? sourceShortName(url);\n\n const written = writeCuratedManifest({\n manifestFile: target,\n publisher,\n assets,\n force: opts.force,\n // Init: every asset inherits the top-level repo `publisher`. Do NOT stamp a\n // per-asset publisher — on the glob path each DiscoveredAsset.publisher is\n // the bare first path segment (`scripts`/`skills`/…), which would clobber\n // the intended org/`--publisher` default with junk per-asset overrides.\n inheritPublisher: true,\n });\n\n if (!written.wrote) {\n logWarn(\n `Curated manifest already exists at ${S.dim(target)} — not overwritten. ` +\n \"Pass --force to regenerate.\",\n );\n return;\n }\n\n logOk(`Wrote curated manifest with ${written.assetCount} assets to ${S.dim(target)}.`);\n // Echo the EXACT <src> the user passed so the printed commands actually run.\n // A bare short name would mis-resolve through `normalizeSourceUrl` (→ the\n // skaile-ai org, wrong slug); the original arg is what `resolveSourceArg`\n // maps back to this same manifest.\n logInfo(\n `Edit it with \\`skaile source manifest edit ${arg}\\`, then ` +\n `\\`skaile source add ${arg}\\` to consume it.`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the manifest before consuming.`);\n }\n}\n\n/**\n * Run discovery over a clone and drop the test-fixture assets (see\n * {@link isTestFixtureAsset}). Shared by `init` and `rebuild` so both paths\n * produce an identical inventory from the same tree.\n */\nfunction discoverCuratableAssets(\n dest: string,\n includeDev: boolean,\n): { assets: ReturnType<typeof discoverAssetsInTree>[\"assets\"]; errors: string[] } {\n const result = discoverAssetsInTree(dest, {\n registry: createFullRegistry(),\n includeDev,\n });\n const assets = result.assets.filter((a) => !isTestFixtureAsset(a.relativePath));\n return { assets, errors: result.errors.map((e) => `${e.path}: ${e.error}`) };\n}\n\n/**\n * Best-effort `git pull --ff-only` on an existing clone. Never throws: a pull\n * failure (offline, diverged, detached) is warned and the caller continues with\n * the clone as-is.\n */\nfunction pullCloneFfOnly(dest: string): void {\n const res = spawnSync(\"git\", [\"-C\", dest, \"pull\", \"--ff-only\"], { stdio: \"pipe\" });\n if (res.status !== 0) {\n logWarn(\n \"git pull --ff-only failed — continuing with the existing clone \" +\n \"(it may be behind upstream).\",\n );\n }\n}\n\n/**\n * Repo-relative `root` path for a manifest asset entry — the merge match key\n * between an existing curated entry and a freshly-discovered asset. `root:`\n * entries use their declared path; a `files:`-only entry (rare for a curated\n * sidecar) falls back to the entry's dirname of the first file, else the name.\n */\nfunction entryRootKey(entry: AssetEntry): string {\n if (entry.root) return entry.root.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const files = entry.files;\n if (files && files.length > 0) {\n const first = typeof files[0] === \"string\" ? files[0] : files[0].path;\n const dir = path.posix.dirname(first.replace(/\\\\/g, \"/\"));\n return dir === \".\" ? entry.name : dir;\n }\n return entry.name;\n}\n\n/** Repo-relative `root` path a discovered asset maps to (matches init's writer). */\nfunction discoveredRootKey(relativePath: string): string {\n const dir = path.posix.dirname(relativePath.replace(/\\\\/g, \"/\"));\n return dir === \".\" ? path.posix.basename(relativePath.replace(/\\\\/g, \"/\")) : dir;\n}\n\n/** Human ref for reporting: `kind:name`. */\nfunction entryRef(entry: AssetEntry): string {\n return `${entry.kind}:${entry.name}`;\n}\n\n/**\n * `source manifest rebuild <src>` — refresh a curated manifest after the\n * upstream repo changed. MERGE is the default (curation is sacred); `--overwrite`\n * re-scans from scratch with `init --force` semantics.\n *\n * Merge algorithm (match by repo-relative `root` path):\n * - Existing entries whose root is STILL discovered → KEPT verbatim (all\n * hand-edits preserved).\n * - Existing entries whose root is GONE upstream → DROPPED (reported).\n * - Freshly-discovered assets not already in the manifest → NOT auto-added,\n * only REPORTED (a curated foreign sidecar must not silently absorb new\n * upstream skills). An asset the curator deliberately dropped stays dropped\n * because it is neither in the existing manifest nor re-added here.\n */\nasync function runRebuild(\n arg: string,\n opts: { projectDir: string; publisher?: string; dev?: boolean; overwrite?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(target)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n // Update the clone: clone if absent, else pull --ff-only (best-effort).\n const entry: SourceEntry = { url };\n const cloned = ensureClone(entry);\n if (!cloned) pullCloneFfOnly(dest);\n\n const { assets: freshAssets, errors } = discoverCuratableAssets(dest, opts.dev ?? false);\n\n if (opts.overwrite) {\n logWarn(\n \"--overwrite: replacing the curated manifest with a full fresh inventory. \" +\n \"All hand-curation (dropped assets, per-asset edits) is discarded.\",\n );\n const publisher = opts.publisher ?? resolveSourcePublisher(dest) ?? sourceShortName(url);\n const written = writeCuratedManifest({\n manifestFile: target,\n publisher,\n assets: freshAssets,\n force: true,\n inheritPublisher: true,\n });\n logOk(\n `Rebuilt curated manifest with ${written.assetCount} assets to ${S.dim(target)} (overwrite).`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the manifest before consuming.`);\n }\n return;\n }\n\n // MERGE (default). `--publisher` only applies to the full re-derive path.\n if (opts.publisher) {\n logWarn(\n \"--publisher is ignored in merge mode (the curated publisher is preserved). \" +\n \"Use --overwrite to re-derive the publisher from a full re-scan.\",\n );\n }\n\n // Read the existing curated manifest and keep it as the base.\n const { manifest: existing } = decodeSkaileManifest(readFileSync(target, \"utf-8\"));\n const existingEntries = existing.assets ?? [];\n\n // Index fresh discovery by repo-relative root path.\n const freshByRoot = new Map<string, (typeof freshAssets)[number]>();\n for (const a of freshAssets) freshByRoot.set(discoveredRootKey(a.relativePath), a);\n\n const kept: AssetEntry[] = [];\n const dropped: string[] = [];\n for (const e of existingEntries) {\n if (freshByRoot.has(entryRootKey(e))) kept.push(e);\n else dropped.push(entryRef(e));\n }\n\n // Fresh assets not already curated → report as available, do NOT add.\n const existingRoots = new Set(existingEntries.map(entryRootKey));\n const newlyAvailable: string[] = [];\n for (const a of freshAssets) {\n if (!existingRoots.has(discoveredRootKey(a.relativePath))) {\n newlyAvailable.push(`${a.kind}:${a.name}`);\n }\n }\n\n const changed = dropped.length > 0;\n if (dropped.length > 0) {\n logWarn(`removed (gone upstream): ${dropped.sort().join(\", \")}`);\n }\n if (newlyAvailable.length > 0) {\n logInfo(\n `${newlyAvailable.length} new upstream asset(s) available (not added): ` +\n `${newlyAvailable.sort().join(\", \")} — add with \\`skaile source manifest edit ${arg}\\` if wanted`,\n );\n }\n\n if (!changed) {\n logOk(\"already up to date\");\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the source before re-consuming.`);\n }\n return;\n }\n\n const merged: SkPublishManifest = { ...existing, assets: kept };\n writeFileSync(target, encodeSkaileManifest(merged), \"utf-8\");\n logOk(\n `Rebuilt curated manifest: kept ${kept.length}, dropped ${dropped.length} → ${S.dim(target)}.`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the source before re-consuming.`);\n }\n}\n\n/**\n * `source manifest verify <src>` — READ-ONLY integrity check of a curated\n * manifest against its clone. Writes nothing. Exit 0 when no errors; with\n * `--strict`, any warning also forces a nonzero exit.\n *\n * Per-asset checks:\n * - `root`/`files` paths still exist upstream (missing → error).\n * - A declared `sha256` recomputes to the same deterministic hash (mismatch → error).\n * - Schema decode diagnostics map to errors/warnings.\n * - Dependency refs parse via `parseAssetRef` (malformed → warning).\n */\nasync function runVerify(\n arg: string,\n opts: { projectDir: string; strict?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(target)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n // Ensure a clone exists to verify paths/hashes against (best-effort; no pull).\n ensureClone({ url });\n\n const text = readFileSync(target, \"utf-8\");\n const { manifest, diagnostics } = decodeSkaileManifest(text);\n\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Schema diagnostics from the decoder.\n for (const d of diagnostics) {\n const line = `${d.code}: ${d.message}`;\n if (d.severity === \"error\") errors.push(line);\n else warnings.push(line);\n }\n\n const assets = manifest.assets ?? [];\n for (const entry of assets) {\n const ref = entryRef(entry);\n\n // Path existence: `root` dir and/or each `files[]` path.\n const relPaths: string[] = [];\n if (entry.root) relPaths.push(entry.root);\n if (entry.files) {\n for (const f of entry.files) relPaths.push(typeof f === \"string\" ? f : f.path);\n }\n if (relPaths.length === 0) relPaths.push(entry.name);\n for (const rel of relPaths) {\n if (!existsSync(path.join(dest, rel))) {\n errors.push(`${ref}: path not found upstream: ${rel}`);\n }\n }\n\n // Declared sha256 → recompute + compare, but ONLY for granular `files:`\n // entries. Discovery (`discover-manifest.ts`) anchors a `files:`-only entry\n // at the REPO ROOT and hashes the files VERBATIM as repo-relative strings\n // (the path is folded into the digest), so verify must hash the same way:\n // `assetRoot = dest`, files kept repo-relative — NOT rebased onto the root.\n // A `root:` entry cannot be verified this way (discovery hashes only the\n // per-kind filtered set, not the whole-dir walk), and the writer never emits\n // sha256 for `root:` entries, so skip the hash check for them.\n if (entry.sha256) {\n if (entry.files && entry.files.length > 0) {\n const hashFiles = entry.files.map((f) =>\n (typeof f === \"string\" ? f : f.path).replace(/\\\\/g, \"/\"),\n );\n const actual = computeDeterministicHash(dest, hashFiles);\n if (actual !== entry.sha256) {\n errors.push(\n `${ref}: sha256 mismatch (declared ${entry.sha256.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n );\n }\n } else {\n warnings.push(\n `${ref}: declared sha256 on a root:-mode entry is not verifiable (discovery hashes only the per-kind filtered set) — skipped`,\n );\n }\n }\n\n // Dependency refs parse.\n for (const dep of entry.dependencies ?? []) {\n try {\n parseAssetRef(dep);\n } catch (err) {\n warnings.push(\n `${ref}: malformed dependency \"${dep}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n }\n\n for (const w of warnings) logWarn(w);\n for (const e of errors) logErr(e);\n\n if (errors.length === 0) {\n logOk(`verified ${assets.length} asset(s).`);\n } else {\n logErr(`${errors.length} issue(s).`);\n }\n\n const failStrict = opts.strict && warnings.length > 0;\n if (errors.length > 0 || failStrict) process.exit(1);\n}\n\n/**\n * Split a `$VISUAL`/`$EDITOR` value into `{ command, args }` and append the file\n * as the final arg. The env value is a full command line, not a bare binary —\n * `EDITOR=\"code --wait\"` must spawn `code` with `[\"--wait\", <file>]`, and\n * `EDITOR=code` (which returns before save) is the user's problem, not ours.\n * A whitespace split covers the common editors (`code --wait`, `code -w`,\n * `subl -w`, `vi`); paths with embedded spaces are not supported (rare for an\n * editor binary and out of scope). Falls back to `vi` when unset/empty.\n *\n * @docLink cli/commands/source#manifest-edit\n */\nexport function resolveEditorCommand(\n editorEnv: string | undefined,\n target: string,\n): { command: string; args: string[] } {\n const parts = (editorEnv ?? \"\").trim().split(/\\s+/).filter(Boolean);\n const [command, ...rest] = parts.length > 0 ? parts : [\"vi\"];\n return { command: command as string, args: [...rest, target] };\n}\n\n/** Minimal spawn contract runEdit needs — lets tests inject a fake. */\ntype SpawnLike = (\n command: string,\n args: string[],\n opts: { stdio: \"inherit\" },\n) => { status: number | null };\n\n/**\n * `source manifest edit <src>` — open the curated store manifest in `$EDITOR`\n * and re-validate on save. Warnings are surfaced but never hard-fail.\n *\n * `spawn` is injectable so tests can assert the argv without launching a real\n * editor; production passes the default `spawnSync`.\n */\nexport function runEdit(\n arg: string,\n opts: { projectDir: string },\n spawn: SpawnLike = spawnSync as unknown as SpawnLike,\n): void {\n const projectDir = path.resolve(opts.projectDir);\n const { slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${target}. ` +\n \"Run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { command, args } = resolveEditorCommand(process.env.VISUAL || process.env.EDITOR, target);\n const res = spawn(command, args, { stdio: \"inherit\" });\n if (res.status !== 0 && res.status !== null) {\n logErr(`Editor exited with status ${res.status}.`);\n process.exit(1);\n }\n\n // Re-validate the saved file; surface diagnostics as warnings, don't hard-fail.\n const { diagnostics } = decodeSkaileManifest(readFileSync(target, \"utf-8\"));\n const errors = diagnostics.filter((d) => d.severity === \"error\");\n const warnings = diagnostics.filter((d) => d.severity !== \"error\");\n if (errors.length > 0) {\n for (const d of errors) logErr(`${d.code}: ${d.message}`);\n logWarn(\"Manifest has errors — fix them before `skaile source add` will consume it.\");\n } else if (warnings.length > 0) {\n for (const d of warnings) logWarn(`${d.code}: ${d.message}`);\n logOk(\"Saved (with warnings).\");\n } else {\n logOk(\"Saved.\");\n }\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 // enablePositionalOptions so options on the leaf verb (`source manifest init\n // --publisher …`) route to that verb instead of being rejected by `manifest`.\n const manifest = src\n .command(\"manifest\")\n .description(\"Curated manifest lifecycle for a source\")\n .enablePositionalOptions();\n\n manifest\n .command(\"init <src>\")\n .description(\"Generate a curated manifest for a source (stored in the local store catalog)\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--publisher <name>\", \"Override the publisher (default: source's GitHub org)\")\n .option(\"--dev\", \"Include assets under the source's dev_paths\", false)\n .option(\"--force\", \"Overwrite an existing curated manifest\", false)\n .action((arg, opts) => runInit(arg, opts));\n\n manifest\n .command(\"edit <src>\")\n .description(\"Open the curated manifest in $EDITOR and re-validate on save\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .action((arg, opts) => runEdit(arg, opts));\n\n manifest\n .command(\"rebuild <src>\")\n .description(\n \"Refresh a curated manifest after an upstream change (merge by default: \" +\n \"keeps curation, drops assets gone upstream, reports new ones without adding)\",\n )\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--publisher <name>\", \"Override the publisher (--overwrite only)\")\n .option(\"--dev\", \"Include assets under the source's dev_paths\", false)\n .option(\"--overwrite\", \"Discard curation and re-scan the full inventory\", false)\n .action((arg, opts) => runRebuild(arg, opts));\n\n manifest\n .command(\"verify <src>\")\n .description(\"Verify hashes, deps, and schema (read-only)\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--strict\", \"Fail on advisory checks (warnings force a nonzero exit)\", false)\n .action((arg, opts) => runVerify(arg, opts));\n\n manifest\n .command(\"publish <src>\")\n .description(\"Push the curated sidecar manifest and publish it to the store\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--as <namespace>\", \"Publisher namespace (default: your store username)\")\n .option(\"--sidecar-repo <url>\", \"Public GitHub repo you own to hold the curated manifest\")\n .option(\"--ref <gitref>\", \"Foreign source ref to ingest (branch/sha; default: main)\")\n .option(\"--dry-run\", \"Print the publish plan without pushing or calling the store\", false)\n .action(async (arg, opts) => {\n const { runPublish } = await import(\"./source-manifest-publish.ts\");\n await runPublish(arg, opts);\n });\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 the source's published assets from the store\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--asset <ref>\", \"Yank only the asset matching this ref/name\")\n .action(async (arg, opts) => {\n const { runYank } = await import(\"./source-manifest-publish.ts\");\n await runYank(arg, opts);\n });\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 storeManifestSlug,\n WorkspaceYamlEditor,\n workspaceConfigFilename,\n} from \"@skaile/workspaces/core\";\nimport { getStoreManifestsDir, 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\nexport function 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 */\nexport function 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 advisories: 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 // Curated overlay: a `skaile source manifest init` writes a curated\n // manifest to the local store at `~/.skaile/store/manifests/<slug>.yaml`.\n // When present, route discovery through it so the curated publisher +\n // asset inventory win over the upstream repo's raw glob discovery. Keyed by\n // the collision-free `storeManifestSlug` (matches the init writer + resolver).\n const overlayFile = path.join(getStoreManifestsDir(), `${storeManifestSlug(entry.url)}.yaml`);\n const catalog = new LocalCatalogSource(library, lib.id, dest, createFullRegistry(), {\n sidecarManifestFile: existsSync(overlayFile) ? overlayFile : undefined,\n });\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 for (const advisory of result.advisories) logInfo(`${slug}: ${advisory}`);\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 for (const advisory of result.advisories) logInfo(advisory);\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/ — pass --purge to remove it, or run \\`skaile cache clean\\`).`,\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 for (const advisory of result.advisories) logInfo(`${slug}: ${advisory}`);\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
+ {"version":3,"sources":["../cli/src/commands/source-manifest.ts","../cli/src/commands/source.ts"],"names":["path2","existsSync","spawnSync"],"mappings":";;;;;;;;;;;;;;AA+CA,IAAM,aAAA,GACJ,2IAAA;AAGF,SAAS,SAAS,IAAA,EAAqB;AACrC,EAAA,MAAA,CAAO,CAAA,EAAG,aAAa,CAAA,wBAAA,EAA2B,IAAI,CAAA,CAAA,CAAG,CAAA;AACzD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB;AAkBO,SAAS,gBAAA,CACd,KACA,UAAA,EACmE;AACnE,EAAA,MAAM,IAAA,GAAO,kBAAkB,UAAU,CAAA;AACzC,EAAA,MAAM,UAAA,GAA4B,OAC9B,kBAAA,CAAwB,IAAA,CA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,IAAI,CAAA,EAAA,EAAK,QAAQ,CAAA,CAAE,CAAA;AACxE,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-IT42ZT3T.js","sourcesContent":["/**\n * `skaile source manifest …` — curated `skaile.manifest.yaml` lifecycle for a\n * source you do NOT own. `init` generates a curated manifest from a discovery\n * run and stores it OUTSIDE the source, under the local store catalog\n * (`~/.skaile/store/manifests/<slug>.yaml`); `edit` opens it in `$EDITOR` and\n * re-validates on save. `source add`/`sync` then apply it as a read overlay\n * (see `source.ts` `refreshManifestCache`).\n *\n * `rebuild` refreshes a curated manifest after an upstream change (merge by\n * default — curation is sacred; `--overwrite` re-scans). `verify` is a\n * read-only integrity check (paths, declared hashes, schema, dep refs).\n * `publish`/`propose`/`yank` remain stubs — they need the store publish\n * endpoint (`POST /sources/<id>/manifest`), which lands in a follow-up.\n *\n * @docLink cli/commands/source#manifest\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AssetEntry,\n decodeSkaileManifest,\n encodeSkaileManifest,\n findWorkspaceRoot,\n parseAssetRef,\n resolveSourcePublisher,\n type SkPublishManifest,\n type SourceEntry,\n sourceCacheKey,\n sourceShortName,\n storeManifestSlug,\n workspaceConfigFilename,\n} from \"@skaile/workspaces/core\";\nimport { computeDeterministicHash, discoverAssetsInTree } from \"@skaile/workspaces/discovery\";\nimport { getStoreManifestsDir, writeCuratedManifest } from \"@skaile/workspaces/library\";\nimport type { Command } from \"commander\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { createFullRegistry } from \"../open-registry.ts\";\nimport {\n ensureClone,\n normalizeSourceUrl,\n readProjectSources,\n sourceClonePath,\n sourceMatchesKey,\n} from \"./source.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 * Resolve a `source manifest` argument into a `{ url, slug, dest }` triple.\n *\n * Resolution order:\n * 1. A key matching an already-registered project source (stored URL, cache\n * key, or short slug).\n * 2. A collision-free **store slug** (`<host>__<owner>__<repo>`) whose\n * manifest already exists at `~/.skaile/store/manifests/<arg>.yaml`. This\n * MUST be tried before bare-name expansion: a bare name like `cli` would\n * otherwise expand (via `normalizeSourceUrl`) to the skaile-ai org and a\n * DIFFERENT slug than the one `init` wrote (e.g. `larksuite`). The slug is\n * the exact identifier `init`'s next-step hint prints back.\n * 3. Otherwise a git URL / `owner/repo` / bare name via `normalizeSourceUrl`.\n *\n * The clone dir is the same URL-keyed cache `source add` uses.\n */\nexport function resolveSourceArg(\n arg: string,\n projectDir: string,\n): { url: string; slug: string; dest: string; manifestFile: string } {\n const root = findWorkspaceRoot(projectDir);\n const registered: SourceEntry[] = root\n ? readProjectSources(path.join(root, workspaceConfigFilename()))\n : [];\n const match = registered.find((e) => sourceMatchesKey(e, arg));\n const bySlug = !match ? resolveByStoreSlug(arg) : undefined;\n const url = match ? match.url : (bySlug?.url ?? normalizeSourceUrl(arg));\n const slug = sourceShortName(url); // human-facing label\n const dest = sourceClonePath(sourceCacheKey(url));\n return { url, slug, dest, manifestFile: bySlug?.manifestFile ?? storeManifestPath(url) };\n}\n\n/**\n * When `arg` is a bare store slug (`<host>__<owner>__<repo>`) whose curated\n * manifest already exists on disk, recover the source URL from the slug and\n * point at that manifest file directly. Returns `undefined` when the arg isn't\n * a slug or has no manifest yet (fall back to URL normalization).\n */\nfunction resolveByStoreSlug(arg: string): { url: string; manifestFile: string } | undefined {\n // A slug is our own encoding — no path/URL sigils, at least the `<host>__…`\n // separator. Anything URL/owner-repo shaped is not a slug.\n if (!/^[\\w.-]+__[\\w.-]+/.test(arg) || /[/:\\\\]/.test(arg)) return undefined;\n const manifestFile = path.join(getStoreManifestsDir(), `${arg}.yaml`);\n if (!existsSync(manifestFile)) return undefined;\n // `<host>__<owner>__<repo>` → `https://<host>/<owner>/<repo>` — good enough to\n // key the clone dir + re-derive the same slug; the manifest file is what edit\n // actually opens.\n const [host, owner, repo] = arg.split(\"__\");\n const url = host && owner && repo ? `https://${host}/${owner}/${repo}` : arg;\n return { url, manifestFile };\n}\n\n/**\n * Absolute path to a source's curated store manifest. Keyed by the\n * collision-free {@link storeManifestSlug} (`<host>__<owner>__<repo>`) so\n * `orgA/cli` and `orgB/cli` don't share `cli.yaml`.\n */\nfunction storeManifestPath(url: string): string {\n return path.join(getStoreManifestsDir(), `${storeManifestSlug(url)}.yaml`);\n}\n\n/**\n * Directory-name segments that mark a test-fixture tree. `init`/`rebuild` drop\n * any asset whose repo-relative root contains one of these as an exact path\n * SEGMENT. Repos routinely ship fixture \"skills\" under such dirs (e.g.\n * `scripts/skill-format-check/tests`, `internal/qualitygate/skillscan/testdata/skills/lark-demo`)\n * that are not real, publishable assets.\n */\nconst TEST_FIXTURE_SEGMENTS = new Set([\n \"tests\",\n \"test\",\n \"__tests__\",\n \"testdata\",\n \"fixtures\",\n \"__fixtures__\",\n]);\n\n/**\n * True when an asset's repo-relative `root` sits under a test-fixture directory\n * (see {@link TEST_FIXTURE_SEGMENTS}). Conservative, not repo-specific — finer\n * curation (keeping a genuine fixture asset) stays the user's job via `edit`.\n * `init`/`rebuild`-path only; the general discovery walk (`source add`) is\n * untouched.\n */\nfunction isTestFixtureAsset(relativePath: string): boolean {\n const segments = relativePath.replace(/\\\\/g, \"/\").split(\"/\");\n return segments.some((s) => TEST_FIXTURE_SEGMENTS.has(s));\n}\n\n/**\n * `source manifest init <src>` — clone (if needed), run discovery, and write a\n * curated `skaile.manifest.yaml` to `~/.skaile/store/manifests/<slug>.yaml`.\n */\nasync function runInit(\n arg: string,\n opts: { projectDir: string; publisher?: string; dev?: boolean; force?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (existsSync(target) && !opts.force) {\n logWarn(\n `A curated manifest already exists at ${S.dim(target)}. ` +\n \"Edit it with `skaile source manifest edit`, refresh it after an upstream \" +\n \"change with `skaile source manifest rebuild`, or pass --force to regenerate.\",\n );\n return;\n }\n\n const entry: SourceEntry = { url };\n ensureClone(entry);\n\n const { assets, errors } = discoverCuratableAssets(dest, opts.dev ?? false);\n\n const publisher = opts.publisher ?? resolveSourcePublisher(dest) ?? sourceShortName(url);\n\n const written = writeCuratedManifest({\n manifestFile: target,\n publisher,\n assets,\n force: opts.force,\n // Init: every asset inherits the top-level repo `publisher`. Do NOT stamp a\n // per-asset publisher — on the glob path each DiscoveredAsset.publisher is\n // the bare first path segment (`scripts`/`skills`/…), which would clobber\n // the intended org/`--publisher` default with junk per-asset overrides.\n inheritPublisher: true,\n });\n\n if (!written.wrote) {\n logWarn(\n `Curated manifest already exists at ${S.dim(target)} — not overwritten. ` +\n \"Pass --force to regenerate.\",\n );\n return;\n }\n\n logOk(`Wrote curated manifest with ${written.assetCount} assets to ${S.dim(target)}.`);\n // Echo the EXACT <src> the user passed so the printed commands actually run.\n // A bare short name would mis-resolve through `normalizeSourceUrl` (→ the\n // skaile-ai org, wrong slug); the original arg is what `resolveSourceArg`\n // maps back to this same manifest.\n logInfo(\n `Edit it with \\`skaile source manifest edit ${arg}\\`, then ` +\n `\\`skaile source add ${arg}\\` to consume it.`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the manifest before consuming.`);\n }\n}\n\n/**\n * Run discovery over a clone and drop the test-fixture assets (see\n * {@link isTestFixtureAsset}). Shared by `init` and `rebuild` so both paths\n * produce an identical inventory from the same tree.\n */\nfunction discoverCuratableAssets(\n dest: string,\n includeDev: boolean,\n): { assets: ReturnType<typeof discoverAssetsInTree>[\"assets\"]; errors: string[] } {\n const result = discoverAssetsInTree(dest, {\n registry: createFullRegistry(),\n includeDev,\n });\n const assets = result.assets.filter((a) => !isTestFixtureAsset(a.relativePath));\n return { assets, errors: result.errors.map((e) => `${e.path}: ${e.error}`) };\n}\n\n/**\n * Best-effort `git pull --ff-only` on an existing clone. Never throws: a pull\n * failure (offline, diverged, detached) is warned and the caller continues with\n * the clone as-is.\n */\nfunction pullCloneFfOnly(dest: string): void {\n const res = spawnSync(\"git\", [\"-C\", dest, \"pull\", \"--ff-only\"], { stdio: \"pipe\" });\n if (res.status !== 0) {\n logWarn(\n \"git pull --ff-only failed — continuing with the existing clone \" +\n \"(it may be behind upstream).\",\n );\n }\n}\n\n/**\n * Repo-relative `root` path for a manifest asset entry — the merge match key\n * between an existing curated entry and a freshly-discovered asset. `root:`\n * entries use their declared path; a `files:`-only entry (rare for a curated\n * sidecar) falls back to the entry's dirname of the first file, else the name.\n */\nfunction entryRootKey(entry: AssetEntry): string {\n if (entry.root) return entry.root.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const files = entry.files;\n if (files && files.length > 0) {\n const first = typeof files[0] === \"string\" ? files[0] : files[0].path;\n const dir = path.posix.dirname(first.replace(/\\\\/g, \"/\"));\n return dir === \".\" ? entry.name : dir;\n }\n return entry.name;\n}\n\n/** Repo-relative `root` path a discovered asset maps to (matches init's writer). */\nfunction discoveredRootKey(relativePath: string): string {\n const dir = path.posix.dirname(relativePath.replace(/\\\\/g, \"/\"));\n return dir === \".\" ? path.posix.basename(relativePath.replace(/\\\\/g, \"/\")) : dir;\n}\n\n/** Human ref for reporting: `kind:name`. */\nfunction entryRef(entry: AssetEntry): string {\n return `${entry.kind}:${entry.name}`;\n}\n\n/**\n * `source manifest rebuild <src>` — refresh a curated manifest after the\n * upstream repo changed. MERGE is the default (curation is sacred); `--overwrite`\n * re-scans from scratch with `init --force` semantics.\n *\n * Merge algorithm (match by repo-relative `root` path):\n * - Existing entries whose root is STILL discovered → KEPT verbatim (all\n * hand-edits preserved).\n * - Existing entries whose root is GONE upstream → DROPPED (reported).\n * - Freshly-discovered assets not already in the manifest → NOT auto-added,\n * only REPORTED (a curated foreign sidecar must not silently absorb new\n * upstream skills). An asset the curator deliberately dropped stays dropped\n * because it is neither in the existing manifest nor re-added here.\n */\nasync function runRebuild(\n arg: string,\n opts: { projectDir: string; publisher?: string; dev?: boolean; overwrite?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(target)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n // Update the clone: clone if absent, else pull --ff-only (best-effort).\n const entry: SourceEntry = { url };\n const cloned = ensureClone(entry);\n if (!cloned) pullCloneFfOnly(dest);\n\n const { assets: freshAssets, errors } = discoverCuratableAssets(dest, opts.dev ?? false);\n\n if (opts.overwrite) {\n logWarn(\n \"--overwrite: replacing the curated manifest with a full fresh inventory. \" +\n \"All hand-curation (dropped assets, per-asset edits) is discarded.\",\n );\n const publisher = opts.publisher ?? resolveSourcePublisher(dest) ?? sourceShortName(url);\n const written = writeCuratedManifest({\n manifestFile: target,\n publisher,\n assets: freshAssets,\n force: true,\n inheritPublisher: true,\n });\n logOk(\n `Rebuilt curated manifest with ${written.assetCount} assets to ${S.dim(target)} (overwrite).`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the manifest before consuming.`);\n }\n return;\n }\n\n // MERGE (default). `--publisher` only applies to the full re-derive path.\n if (opts.publisher) {\n logWarn(\n \"--publisher is ignored in merge mode (the curated publisher is preserved). \" +\n \"Use --overwrite to re-derive the publisher from a full re-scan.\",\n );\n }\n\n // Read the existing curated manifest and keep it as the base.\n const { manifest: existing } = decodeSkaileManifest(readFileSync(target, \"utf-8\"));\n const existingEntries = existing.assets ?? [];\n\n // Index fresh discovery by repo-relative root path.\n const freshByRoot = new Map<string, (typeof freshAssets)[number]>();\n for (const a of freshAssets) freshByRoot.set(discoveredRootKey(a.relativePath), a);\n\n const kept: AssetEntry[] = [];\n const dropped: string[] = [];\n for (const e of existingEntries) {\n if (freshByRoot.has(entryRootKey(e))) kept.push(e);\n else dropped.push(entryRef(e));\n }\n\n // Fresh assets not already curated → report as available, do NOT add.\n const existingRoots = new Set(existingEntries.map(entryRootKey));\n const newlyAvailable: string[] = [];\n for (const a of freshAssets) {\n if (!existingRoots.has(discoveredRootKey(a.relativePath))) {\n newlyAvailable.push(`${a.kind}:${a.name}`);\n }\n }\n\n const changed = dropped.length > 0;\n if (dropped.length > 0) {\n logWarn(`removed (gone upstream): ${dropped.sort().join(\", \")}`);\n }\n if (newlyAvailable.length > 0) {\n logInfo(\n `${newlyAvailable.length} new upstream asset(s) available (not added): ` +\n `${newlyAvailable.sort().join(\", \")} — add with \\`skaile source manifest edit ${arg}\\` if wanted`,\n );\n }\n\n if (!changed) {\n logOk(\"already up to date\");\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the source before re-consuming.`);\n }\n return;\n }\n\n const merged: SkPublishManifest = { ...existing, assets: kept };\n writeFileSync(target, encodeSkaileManifest(merged), \"utf-8\");\n logOk(\n `Rebuilt curated manifest: kept ${kept.length}, dropped ${dropped.length} → ${S.dim(target)}.`,\n );\n if (errors.length > 0) {\n logWarn(`${errors.length} discovery error(s) — inspect the source before re-consuming.`);\n }\n}\n\n/**\n * `source manifest verify <src>` — READ-ONLY integrity check of a curated\n * manifest against its clone. Writes nothing. Exit 0 when no errors; with\n * `--strict`, any warning also forces a nonzero exit.\n *\n * Per-asset checks:\n * - `root`/`files` paths still exist upstream (missing → error).\n * - A declared `sha256` recomputes to the same deterministic hash (mismatch → error).\n * - Schema decode diagnostics map to errors/warnings.\n * - Dependency refs parse via `parseAssetRef` (malformed → warning).\n */\nasync function runVerify(\n arg: string,\n opts: { projectDir: string; strict?: boolean },\n): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n const { url, dest, slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(target)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n // Ensure a clone exists to verify paths/hashes against (best-effort; no pull).\n ensureClone({ url });\n\n const text = readFileSync(target, \"utf-8\");\n const { manifest, diagnostics } = decodeSkaileManifest(text);\n\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Schema diagnostics from the decoder.\n for (const d of diagnostics) {\n const line = `${d.code}: ${d.message}`;\n if (d.severity === \"error\") errors.push(line);\n else warnings.push(line);\n }\n\n const assets = manifest.assets ?? [];\n for (const entry of assets) {\n const ref = entryRef(entry);\n\n // Path existence: `root` dir and/or each `files[]` path.\n const relPaths: string[] = [];\n if (entry.root) relPaths.push(entry.root);\n if (entry.files) {\n for (const f of entry.files) relPaths.push(typeof f === \"string\" ? f : f.path);\n }\n if (relPaths.length === 0) relPaths.push(entry.name);\n for (const rel of relPaths) {\n if (!existsSync(path.join(dest, rel))) {\n errors.push(`${ref}: path not found upstream: ${rel}`);\n }\n }\n\n // Declared sha256 → recompute + compare, but ONLY for granular `files:`\n // entries. Discovery (`discover-manifest.ts`) anchors a `files:`-only entry\n // at the REPO ROOT and hashes the files VERBATIM as repo-relative strings\n // (the path is folded into the digest), so verify must hash the same way:\n // `assetRoot = dest`, files kept repo-relative — NOT rebased onto the root.\n // A `root:` entry cannot be verified this way (discovery hashes only the\n // per-kind filtered set, not the whole-dir walk), and the writer never emits\n // sha256 for `root:` entries, so skip the hash check for them.\n if (entry.sha256) {\n if (entry.files && entry.files.length > 0) {\n const hashFiles = entry.files.map((f) =>\n (typeof f === \"string\" ? f : f.path).replace(/\\\\/g, \"/\"),\n );\n const actual = computeDeterministicHash(dest, hashFiles);\n if (actual !== entry.sha256) {\n errors.push(\n `${ref}: sha256 mismatch (declared ${entry.sha256.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n );\n }\n } else {\n warnings.push(\n `${ref}: declared sha256 on a root:-mode entry is not verifiable (discovery hashes only the per-kind filtered set) — skipped`,\n );\n }\n }\n\n // Dependency refs parse.\n for (const dep of entry.dependencies ?? []) {\n try {\n parseAssetRef(dep);\n } catch (err) {\n warnings.push(\n `${ref}: malformed dependency \"${dep}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n }\n\n for (const w of warnings) logWarn(w);\n for (const e of errors) logErr(e);\n\n if (errors.length === 0) {\n logOk(`verified ${assets.length} asset(s).`);\n } else {\n logErr(`${errors.length} issue(s).`);\n }\n\n const failStrict = opts.strict && warnings.length > 0;\n if (errors.length > 0 || failStrict) process.exit(1);\n}\n\n/**\n * Split a `$VISUAL`/`$EDITOR` value into `{ command, args }` and append the file\n * as the final arg. The env value is a full command line, not a bare binary —\n * `EDITOR=\"code --wait\"` must spawn `code` with `[\"--wait\", <file>]`, and\n * `EDITOR=code` (which returns before save) is the user's problem, not ours.\n * A whitespace split covers the common editors (`code --wait`, `code -w`,\n * `subl -w`, `vi`); paths with embedded spaces are not supported (rare for an\n * editor binary and out of scope). Falls back to `vi` when unset/empty.\n *\n * @docLink cli/commands/source#manifest-edit\n */\nexport function resolveEditorCommand(\n editorEnv: string | undefined,\n target: string,\n): { command: string; args: string[] } {\n const parts = (editorEnv ?? \"\").trim().split(/\\s+/).filter(Boolean);\n const [command, ...rest] = parts.length > 0 ? parts : [\"vi\"];\n return { command: command as string, args: [...rest, target] };\n}\n\n/** Minimal spawn contract runEdit needs — lets tests inject a fake. */\ntype SpawnLike = (\n command: string,\n args: string[],\n opts: { stdio: \"inherit\" },\n) => { status: number | null };\n\n/**\n * `source manifest edit <src>` — open the curated store manifest in `$EDITOR`\n * and re-validate on save. Warnings are surfaced but never hard-fail.\n *\n * `spawn` is injectable so tests can assert the argv without launching a real\n * editor; production passes the default `spawnSync`.\n */\nexport function runEdit(\n arg: string,\n opts: { projectDir: string },\n spawn: SpawnLike = spawnSync as unknown as SpawnLike,\n): void {\n const projectDir = path.resolve(opts.projectDir);\n const { slug, manifestFile: target } = resolveSourceArg(arg, projectDir);\n\n if (!existsSync(target)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${target}. ` +\n \"Run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { command, args } = resolveEditorCommand(process.env.VISUAL || process.env.EDITOR, target);\n const res = spawn(command, args, { stdio: \"inherit\" });\n if (res.status !== 0 && res.status !== null) {\n logErr(`Editor exited with status ${res.status}.`);\n process.exit(1);\n }\n\n // Re-validate the saved file; surface diagnostics as warnings, don't hard-fail.\n const { diagnostics } = decodeSkaileManifest(readFileSync(target, \"utf-8\"));\n const errors = diagnostics.filter((d) => d.severity === \"error\");\n const warnings = diagnostics.filter((d) => d.severity !== \"error\");\n if (errors.length > 0) {\n for (const d of errors) logErr(`${d.code}: ${d.message}`);\n logWarn(\"Manifest has errors — fix them before `skaile source add` will consume it.\");\n } else if (warnings.length > 0) {\n for (const d of warnings) logWarn(`${d.code}: ${d.message}`);\n logOk(\"Saved (with warnings).\");\n } else {\n logOk(\"Saved.\");\n }\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 // enablePositionalOptions so options on the leaf verb (`source manifest init\n // --publisher …`) route to that verb instead of being rejected by `manifest`.\n const manifest = src\n .command(\"manifest\")\n .description(\"Curated manifest lifecycle for a source\")\n .enablePositionalOptions();\n\n manifest\n .command(\"init <src>\")\n .description(\"Generate a curated manifest for a source (stored in the local store catalog)\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--publisher <name>\", \"Override the publisher (default: source's GitHub org)\")\n .option(\"--dev\", \"Include assets under the source's dev_paths\", false)\n .option(\"--force\", \"Overwrite an existing curated manifest\", false)\n .action((arg, opts) => runInit(arg, opts));\n\n manifest\n .command(\"edit <src>\")\n .description(\"Open the curated manifest in $EDITOR and re-validate on save\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .action((arg, opts) => runEdit(arg, opts));\n\n manifest\n .command(\"rebuild <src>\")\n .description(\n \"Refresh a curated manifest after an upstream change (merge by default: \" +\n \"keeps curation, drops assets gone upstream, reports new ones without adding)\",\n )\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--publisher <name>\", \"Override the publisher (--overwrite only)\")\n .option(\"--dev\", \"Include assets under the source's dev_paths\", false)\n .option(\"--overwrite\", \"Discard curation and re-scan the full inventory\", false)\n .action((arg, opts) => runRebuild(arg, opts));\n\n manifest\n .command(\"verify <src>\")\n .description(\"Verify hashes, deps, and schema (read-only)\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--strict\", \"Fail on advisory checks (warnings force a nonzero exit)\", false)\n .action((arg, opts) => runVerify(arg, opts));\n\n manifest\n .command(\"publish <src>\")\n .description(\"Push the curated sidecar manifest and publish it to the store\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--as <namespace>\", \"Publisher namespace (default: your store username)\")\n .option(\"--sidecar-repo <url>\", \"Public GitHub repo you own to hold the curated manifest\")\n .option(\"--ref <gitref>\", \"Foreign source ref to ingest (branch/sha; default: main)\")\n .option(\"--dry-run\", \"Print the publish plan without pushing or calling the store\", false)\n .action(async (arg, opts) => {\n const { runPublish } = await import(\"./source-manifest-publish.ts\");\n await runPublish(arg, opts);\n });\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 the source's published assets from the store\")\n .option(\"-C, --project-dir <dir>\", \"Project directory\", process.cwd())\n .option(\"--asset <ref>\", \"Yank only the asset matching this ref/name\")\n .action(async (arg, opts) => {\n const { runYank } = await import(\"./source-manifest-publish.ts\");\n await runYank(arg, opts);\n });\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 storeManifestSlug,\n WorkspaceYamlEditor,\n workspaceConfigFilename,\n} from \"@skaile/workspaces/core\";\nimport { getStoreManifestsDir, 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\nexport function 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 */\nexport function 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 advisories: 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 // Curated overlay: a `skaile source manifest init` writes a curated\n // manifest to the local store at `~/.skaile/store/manifests/<slug>.yaml`.\n // When present, route discovery through it so the curated publisher +\n // asset inventory win over the upstream repo's raw glob discovery. Keyed by\n // the collision-free `storeManifestSlug` (matches the init writer + resolver).\n const overlayFile = path.join(getStoreManifestsDir(), `${storeManifestSlug(entry.url)}.yaml`);\n const catalog = new LocalCatalogSource(library, lib.id, dest, createFullRegistry(), {\n sidecarManifestFile: existsSync(overlayFile) ? overlayFile : undefined,\n });\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 for (const advisory of result.advisories) logInfo(`${slug}: ${advisory}`);\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 for (const advisory of result.advisories) logInfo(advisory);\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/ — pass --purge to remove it, or run \\`skaile cache clean\\`).`,\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 for (const advisory of result.advisories) logInfo(`${slug}: ${advisory}`);\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"]}
@@ -7,6 +7,19 @@ function getBridgeLogger(subkind) {
7
7
  return createLogger({ kind: "bridge", subkind });
8
8
  }
9
9
  var AgentDriver = class extends EventEmitter {
10
+ /** Preserve text-only callers; drivers must explicitly support attachments. */
11
+ promptInput(input) {
12
+ if (input.attachments?.length) return Promise.reject(new Error("Structured input unsupported"));
13
+ return this.prompt(input.text);
14
+ }
15
+ /** Managed replies never fall back to a new prompt after a request has settled. */
16
+ get acceptsReplyAsPrompt() {
17
+ return true;
18
+ }
19
+ /** Stop the driver and await owned process/state cleanup when the backend supports it. */
20
+ async dispose() {
21
+ this.kill();
22
+ }
10
23
  /** Optional provider-native session/thread identifier for resume support. */
11
24
  get runtimeSessionId() {
12
25
  return void 0;
@@ -41,7 +54,7 @@ var AgentDriver = class extends EventEmitter {
41
54
  * @returns `true` when the answer was consumed by a pending question; `false`
42
55
  * when no question was pending (caller should treat the reply as a prompt).
43
56
  */
44
- answerQuestion(answer, question) {
57
+ answerQuestion(answer, question, requestId) {
45
58
  return false;
46
59
  }
47
60
  // ── Live reconfiguration ────────────────────────────────────────────────
@@ -307,5 +320,5 @@ async function listModelsForDriver(driverId, apiKeys) {
307
320
  }
308
321
 
309
322
  export { AgentDriver, BUILTIN_DRIVER_CATALOG, DRIVER_CATALOG, createDriver, getBridgeLogger, listDrivers, listModelsForDriver, registerBuiltinDrivers };
310
- //# sourceMappingURL=chunk-FRER2PEN.js.map
311
- //# sourceMappingURL=chunk-FRER2PEN.js.map
323
+ //# sourceMappingURL=chunk-J7VSUGGH.js.map
324
+ //# sourceMappingURL=chunk-J7VSUGGH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../bridge/src/logger.ts","../bridge/src/types.ts","../bridge/src/registry.ts"],"names":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ACF;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-J7VSUGGH.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 AgentPromptInput,\n Capability,\n CredentialMint,\n CodexCredentialDelivery,\n CodexSubscriptionRefreshInput,\n CodexSubscriptionRefreshResult,\n FlowExecution,\n ModelTokenUsage,\n RenderInvokedEvent,\n TokenUsage,\n} from \"@skaile/workspaces/types\";\nimport type { CodexServerRequestHandlers } from \"./codex-app-server.js\";\nexport type { AgentPromptInput } from \"@skaile/workspaces/types\";\nimport type { ModelEntry } from \"./models.js\";\n\n/**\n * Test-only hook injected by the runner so a no-LLM driver (the echo driver's\n * scripted-flow mode) can read flow state and drive flow-adapter mutations\n * without an SDK/MCP round-trip. The runner wires this in `createActiveFlow`\n * from the active FlowAdapter + handle.\n *\n * This is an internal runner↔driver interface — NOT part of any wire\n * protocol or flow contract. Production drivers ignore it.\n *\n * @see packages/bridge/drivers/echo — scripted-flow mode\n * @since 3.6.0\n */\nexport interface FlowTestDriverHook {\n /** Current flow execution snapshot, or `null` when no flow is active. */\n getState(): FlowExecution | null;\n /**\n * Execute a flow-adapter operation (`start_node`, `request_approval`,\n * `complete_node`, `request_input`, `skip_node`, `fail_node`, …). Returns\n * the adapter's JSON string result (or rejects on an illegal transition).\n */\n execute(op: string, args: Record<string, unknown>): Promise<string>;\n /**\n * Node IDs marked as mandatory approval gates. The scripted policy resolves\n * `auto` to `request_approval` for these even in autonomous mode, so hosts\n * can drive a mandatory gate deterministically. Optional — absent hooks\n * behave as if no node is mandatory.\n */\n mandatoryGates?(): string[];\n}\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, signal?: AbortSignal): Promise<unknown>;\n /** Subscribe to registry changes; callback carries no credentials or tool payloads. */\n onToolsChanged?(listener: () => void): () => void;\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/** Closed, passive managed-MCP observations. Counts saturate at 512. */\nexport interface CodexNativeMcpDiagnostics {\n startupBeforeTurn: \"unknown\" | \"starting\" | \"ready\" | \"failed\" | \"cancelled\";\n startupAtEnd: CodexNativeMcpDiagnostics[\"startupBeforeTurn\"];\n toolsListBeforeTurn: number;\n toolsListTotal: number;\n toolsCallTotal: number;\n nativeMcpToolItemCount: number;\n}\n\n/** Trusted session-local tool transport; fulfilled only after required tools are ready. */\nexport interface CodexToolTransport {\n mcpServers: Record<string, Record<string, unknown>>;\n onServerRequest?: CodexServerRequestHandlers;\n /** Revalidate the required live inventory before starting each turn. */\n validate?(): Promise<void>;\n /** Rebuild the native generation at idle when its advertised inventory is stale. */\n needsReload?(): boolean;\n instructions?: string;\n /** Restrict model calls to the active turn and abort outstanding calls when it ends. */\n beginTurn?(signal: AbortSignal): void;\n /** Trusted private server binding and passive request-handler counters; never performs I/O. */\n diagnostics?: {\n serverName: string;\n requestCounts(): { toolsListTotal: number; toolsCallTotal: number };\n };\n dispose(): Promise<void>;\n}\n\n/** Explicit managed instance inputs; none are inferred from ambient developer state. */\nexport interface CodexManagedRuntimeOptions {\n executable: string;\n /** Optional launcher arguments, for the caller-owned executable wrapper. */\n executableArgs?: string[];\n /** Private local filesystem state; the host must fence old native processes before reuse. */\n privateDirectory: string;\n /** Host-owned private mount containing every parent/child instance; denied to native tools. */\n privateRoot: string;\n environment: Record<string, string>;\n credential: CodexCredentialDelivery;\n instructionFiles?: string[];\n skillsDirectory?: string;\n prepareTools(signal: AbortSignal): Promise<CodexToolTransport>;\n /** Optional passive observation sink. Failures never affect native execution or cleanup. */\n onNativeMcpDiagnostics?(value: Readonly<CodexNativeMcpDiagnostics>): void | Promise<void>;\n refreshCredential?: (\n input: CodexSubscriptionRefreshInput,\n signal: AbortSignal,\n ) => Promise<CodexSubscriptionRefreshResult>;\n requestTimeoutMs?: number;\n turnTimeoutMs?: number;\n /** Maximum native turns admitted by this instance; reserved for disposable one-turn children. */\n nativeTurnBudget?: 1;\n /** Human interaction deadline, bounded separately from ordinary RPCs. */\n interactionTimeoutMs?: number;\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 /** Omission retains the standalone SDK path; managed mode always requires App Server inputs. */\n authSource?: \"local\" | \"managed\";\n managedRuntime?: CodexManagedRuntimeOptions;\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 * What the driver tells the host about a turn blocked by an upstream usage\n * limit. Everything but `configId` is best-effort: the SDK reports the limit\n * window only on its structured telemetry, not on the error result text.\n *\n * @see AgentConfig.onLimitBlocked\n * @category Configuration\n * @since 3.9.0\n */\nexport interface LimitBlockedContext {\n /** The AI provider config the blocked turn ran on (`\"\"` when unmediated). */\n configId: string;\n /** Upstream limit window (`five_hour`, `seven_day`, …) when reported. */\n limitType?: string;\n /** Epoch seconds at which the limit window resets, when reported. */\n resetsAt?: number;\n /** Fraction of the limit window consumed (0–1) when reported. */\n utilization?: number;\n}\n\n/**\n * The host's verdict on a limit-blocked turn. `switched: true` is a promise\n * that a different seat's credential is already on disk — the driver acts on it\n * by respawning the CLI and replaying the prompt, so returning it without\n * having rewritten the credential file would just replay onto the dead seat.\n *\n * @see AgentConfig.onLimitBlocked\n * @category Configuration\n * @since 3.9.0\n */\nexport interface LimitFailoverResult {\n /** Whether the session was repointed at a different AI provider config. */\n switched: boolean;\n /** The config id now in effect. Informational — used for logs. */\n configId?: string;\n /**\n * Why no switch happened: `same-config`, `standalone`,\n * `platform-omitted-config-id` (the mint succeeded but named no seat, so a\n * re-resolution is indistinguishable from none), or a `CredentialMint`\n * failure code. Diagnostic only — the driver branches on `switched`.\n */\n reason?: string;\n}\n\n/**\n * One observed AI-provider rejection, reported to the host for per-seat health\n * attribution. Fire-and-forget — see {@link AgentConfig.onProviderResponse}.\n *\n * @category Configuration\n * @since 3.9.0\n */\nexport interface ProviderResponseObservation {\n /** 401 — the credential was rejected. 429 — an upstream rate/session limit. */\n status: 401 | 429;\n /** The AI provider config the observation is attributed to, when known. */\n configId?: string;\n /** Upstream limit window (`five_hour`, `seven_day`, …) when reported. */\n limitType?: string;\n /** Fraction of the limit window consumed (0–1) when reported. */\n utilization?: number;\n /** Epoch seconds at which the limit window resets, when reported. */\n resetsAt?: number;\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 * Optional callback invoked by the driver when a turn is blocked by an\n * upstream **usage limit** rather than a bad credential — the subscription\n * five-hour / seven-day ceiling, or any `rate_limit` the classifier\n * recognises. Called at most once per logical turn, and only after the\n * blocked attempt has already failed, so it never runs mid-turn.\n *\n * The runner implements it by asking the platform to re-resolve the seat:\n *\n * - `switched: true` — the session was repointed at a DIFFERENT AI\n * provider config and `.credentials.json` was rewritten. The driver\n * drops its query (forcing a fresh CLI spawn, which is what clears a\n * resident CLI's cached \"blocked until <reset>\" state — a hot file\n * rewrite alone does not) and replays the prompt once.\n * - `switched: false` — no alternative seat was available. The driver\n * surfaces the original limit error unchanged.\n *\n * Left unset by standalone runners (CLI / forge / Claude plugin): there is\n * no platform mediator to re-resolve a seat, so the limit error surfaces\n * exactly as it does today.\n *\n * Companion to {@link onAuthError}: that one covers 401s, this one covers\n * the rejection path, which previously reached no failover at all\n * (skaile-ai/workspaces#567, skaile-ai/platform#2976).\n *\n * @since 3.9.0\n */\n onLimitBlocked?: (ctx: LimitBlockedContext) => Promise<LimitFailoverResult>;\n /**\n * Optional fire-and-forget hook invoked when the driver observes a 401 or a\n * 429 / subscription-limit rejection from the AI provider. The runner\n * forwards it to the platform as a `provider_response_seen` event so the\n * owning `AIProviderConfig`'s live health counters can be bumped — the cron\n * health probe only samples auth, never capacity\n * (skaile-ai/workspaces#368, skaile-ai/platform#3539).\n *\n * Never awaited and never retried; the driver swallows a throwing\n * implementation so telemetry can never fail a turn.\n *\n * @since 3.9.0\n */\n onProviderResponse?: (observation: ProviderResponseObservation) => void;\n /**\n * Test-only flow driver hook. When present, the echo driver's scripted-flow\n * mode uses it to advance flow nodes deterministically (no LLM). The runner\n * injects it in `createActiveFlow`; every other driver ignores it.\n *\n * @see FlowTestDriverHook\n * @since 3.6.0\n */\n flowTestDriver?: FlowTestDriverHook;\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 /** Per-turn usage keyed by model, subagent calls included. Added in 3.11.0. */\n modelUsage?: Record<string, ModelTokenUsage>;\n /** Prompt size of the turn's last main-thread API call. Added in 3.11.0. */\n contextTokens?: number;\n /** Context window of the main model, in tokens. Added in 3.11.0. */\n contextWindow?: number;\n errors?: string[];\n [k: string]: any;\n }\n | {\n type: \"error\";\n error: string;\n detail?: AgentError;\n fatal?: boolean;\n /** Usage of a failed provider turn, when reported. */\n tokens?: TokenUsage;\n /** Failed-turn usage keyed by the actual model. */\n modelUsage?: Record<string, ModelTokenUsage>;\n contextTokens?: number;\n contextWindow?: number;\n [k: string]: any;\n }\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:\n | \"signature_mismatch\"\n | \"model_mismatch\"\n | \"jsonl_lost\"\n | \"jsonl_poisoned\"\n | \"native_state_unavailable\";\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 /** Preserve text-only callers; drivers must explicitly support attachments. */\n promptInput(input: AgentPromptInput): Promise<void> {\n if (input.attachments?.length) return Promise.reject(new Error(\"Structured input unsupported\"));\n return this.prompt(input.text);\n }\n\n /** Managed replies never fall back to a new prompt after a request has settled. */\n get acceptsReplyAsPrompt(): boolean {\n return true;\n }\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 /** Stop the driver and await owned process/state cleanup when the backend supports it. */\n async dispose(): Promise<void> {\n this.kill();\n }\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, the driver resolves the underlying\n * call only once every 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 * @param question - The sub-question this answers, verbatim from the\n * `question` event that asked it. Supply it whenever the host lets the user\n * answer out of order — without it the answer fills the next unanswered\n * slot in order, which silently mismatches a non-sequential reply.\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, question?: string, requestId?: string): boolean {\n void requestId;\n void answer;\n void question;\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 * Prompt tokens occupying the context window as of the most recent API\n * request — i.e. how full the context actually is right now.\n *\n * Deliberately NOT the same number as {@link getTokenUsage}, whose usage is\n * cumulative over every API call in the turn and therefore overstates the\n * context by 10-40x on any multi-tool turn. Callers measuring context fill\n * (compaction thresholds) must prefer this; callers billing a turn\n * (usage ledgers, the `finished` event) must keep using `getTokenUsage()`.\n *\n * Returns `null` both when the driver cannot report a per-call figure at all\n * and when it can but has no reading yet. Falling back to `getTokenUsage()`\n * is safe in either case only because a driver clears the two in lockstep: no\n * reading means no API call landed, so there is no cumulative usage to\n * overstate. A driver implementing this must preserve that invariant.\n */\n getContextTokens(): number | 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"]}