@skaile/workspaces 5.15.1 → 5.16.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 (367) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/{asset-feeds-FVDNQ2FM.js → asset-feeds-BELBSJEE.js} +18 -18
  3. package/dist/{asset-feeds-FVDNQ2FM.js.map → asset-feeds-BELBSJEE.js.map} +1 -1
  4. package/dist/asset-manager/catalog-deployer.js +7 -7
  5. package/dist/asset-manager/index.js +13 -13
  6. package/dist/asset-manager/installer.js +9 -9
  7. package/dist/asset-manager/renderers.js +8 -8
  8. package/dist/asset-manager/src/index.d.ts +105 -6
  9. package/dist/asset-manager/src/index.d.ts.map +1 -1
  10. package/dist/asset-manager/src/installer.d.ts +11 -2
  11. package/dist/asset-manager/src/installer.d.ts.map +1 -1
  12. package/dist/asset-manager/src/mcp-config.d.ts.map +1 -1
  13. package/dist/bridge/drivers/claude-sdk.js +150 -19
  14. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  15. package/dist/bridge/drivers/codex.js +15 -128
  16. package/dist/bridge/drivers/codex.js.map +1 -1
  17. package/dist/bridge/drivers/continue.js +10 -10
  18. package/dist/bridge/drivers/echo.js +2 -2
  19. package/dist/bridge/drivers/gemini.js +7 -7
  20. package/dist/bridge/drivers/goose.js +10 -10
  21. package/dist/bridge/drivers/omp.js +61 -5
  22. package/dist/bridge/drivers/omp.js.map +1 -1
  23. package/dist/bridge/drivers/opencode.js +10 -10
  24. package/dist/bridge/drivers/qwen.js +7 -7
  25. package/dist/bridge/index.js +13 -12
  26. package/dist/bridge/src/approval-card.d.ts +24 -0
  27. package/dist/bridge/src/approval-card.d.ts.map +1 -0
  28. package/dist/bridge/src/driver-model-check.d.ts +21 -0
  29. package/dist/bridge/src/driver-model-check.d.ts.map +1 -0
  30. package/dist/bridge/src/drivers/claude-sdk.d.ts +22 -0
  31. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  32. package/dist/bridge/src/drivers/omp-models-yml.d.ts.map +1 -1
  33. package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
  34. package/dist/bridge/src/index.d.ts +2 -0
  35. package/dist/bridge/src/index.d.ts.map +1 -1
  36. package/dist/bridge/src/types.d.ts +23 -0
  37. package/dist/bridge/src/types.d.ts.map +1 -1
  38. package/dist/{chunk-YUURCZWY.js → chunk-2SKPPIV7.js} +5 -5
  39. package/dist/{chunk-YUURCZWY.js.map → chunk-2SKPPIV7.js.map} +1 -1
  40. package/dist/{chunk-PK5XQBOC.js → chunk-46IRZJV4.js} +4 -4
  41. package/dist/{chunk-PK5XQBOC.js.map → chunk-46IRZJV4.js.map} +1 -1
  42. package/dist/{chunk-NVBN3YOH.js → chunk-5CE6J4DB.js} +46 -67
  43. package/dist/chunk-5CE6J4DB.js.map +1 -0
  44. package/dist/{chunk-54TVXZP3.js → chunk-5DCOG5B5.js} +3 -3
  45. package/dist/{chunk-54TVXZP3.js.map → chunk-5DCOG5B5.js.map} +1 -1
  46. package/dist/{chunk-X7DIT65W.js → chunk-5RDZ5JHH.js} +4 -4
  47. package/dist/{chunk-X7DIT65W.js.map → chunk-5RDZ5JHH.js.map} +1 -1
  48. package/dist/{chunk-BV7NLPI6.js → chunk-6GSE63K2.js} +4 -4
  49. package/dist/{chunk-BV7NLPI6.js.map → chunk-6GSE63K2.js.map} +1 -1
  50. package/dist/{chunk-GQ5OYFVD.js → chunk-6Q7NKTDG.js} +47 -47
  51. package/dist/chunk-6Q7NKTDG.js.map +1 -0
  52. package/dist/chunk-6RTEUWXX.js +125 -0
  53. package/dist/chunk-6RTEUWXX.js.map +1 -0
  54. package/dist/{chunk-RTYDYSUV.js → chunk-72KZJE3G.js} +82 -22
  55. package/dist/chunk-72KZJE3G.js.map +1 -0
  56. package/dist/{chunk-SAKVAG23.js → chunk-A26MUUN7.js} +7 -7
  57. package/dist/{chunk-SAKVAG23.js.map → chunk-A26MUUN7.js.map} +1 -1
  58. package/dist/{chunk-NHH3MRSC.js → chunk-A7AZ3RL5.js} +6 -6
  59. package/dist/{chunk-NHH3MRSC.js.map → chunk-A7AZ3RL5.js.map} +1 -1
  60. package/dist/{chunk-LEOXPIC6.js → chunk-AP24HESN.js} +3 -3
  61. package/dist/{chunk-LEOXPIC6.js.map → chunk-AP24HESN.js.map} +1 -1
  62. package/dist/{chunk-JJLH4TX4.js → chunk-CQFVKN6S.js} +230 -62
  63. package/dist/chunk-CQFVKN6S.js.map +1 -0
  64. package/dist/{chunk-OOQ5Q75W.js → chunk-D3PU3C6F.js} +41 -16
  65. package/dist/chunk-D3PU3C6F.js.map +1 -0
  66. package/dist/{chunk-WXKNM2JJ.js → chunk-D5REDKVU.js} +3 -3
  67. package/dist/{chunk-WXKNM2JJ.js.map → chunk-D5REDKVU.js.map} +1 -1
  68. package/dist/{chunk-R37L4BNR.js → chunk-DADAZLFW.js} +648 -76
  69. package/dist/chunk-DADAZLFW.js.map +1 -0
  70. package/dist/{chunk-U7YMGW7M.js → chunk-DQOAPR4M.js} +2 -2
  71. package/dist/{chunk-U7YMGW7M.js.map → chunk-DQOAPR4M.js.map} +1 -1
  72. package/dist/{chunk-7Y7UYNGL.js → chunk-E634MBP6.js} +12 -9
  73. package/dist/chunk-E634MBP6.js.map +1 -0
  74. package/dist/{chunk-NKDSU4Q7.js → chunk-ES6ARJPQ.js} +21 -7
  75. package/dist/chunk-ES6ARJPQ.js.map +1 -0
  76. package/dist/{chunk-WWUWMOX2.js → chunk-FSLVMZXR.js} +37 -17
  77. package/dist/chunk-FSLVMZXR.js.map +1 -0
  78. package/dist/{chunk-MKTJZLQM.js → chunk-FSSRBWYL.js} +4 -4
  79. package/dist/{chunk-MKTJZLQM.js.map → chunk-FSSRBWYL.js.map} +1 -1
  80. package/dist/{chunk-VY6NTFE7.js → chunk-FT4ZHLYR.js} +3 -2
  81. package/dist/chunk-FT4ZHLYR.js.map +1 -0
  82. package/dist/chunk-FWAJUWXQ.js +1016 -0
  83. package/dist/chunk-FWAJUWXQ.js.map +1 -0
  84. package/dist/{chunk-ANSZULXH.js → chunk-H7R7R5BN.js} +21 -6
  85. package/dist/chunk-H7R7R5BN.js.map +1 -0
  86. package/dist/{chunk-4AKR4XPQ.js → chunk-HG52NGAV.js} +3 -3
  87. package/dist/chunk-HG52NGAV.js.map +1 -0
  88. package/dist/{plugin-store-BIITCNOZ.js → chunk-HUKUYWBJ.js} +32 -23
  89. package/dist/chunk-HUKUYWBJ.js.map +1 -0
  90. package/dist/{chunk-JUHDED6J.js → chunk-ISSYT5AZ.js} +3 -3
  91. package/dist/{chunk-JUHDED6J.js.map → chunk-ISSYT5AZ.js.map} +1 -1
  92. package/dist/{chunk-GR7TV4XC.js → chunk-J4RRH2NP.js} +4 -4
  93. package/dist/{chunk-GR7TV4XC.js.map → chunk-J4RRH2NP.js.map} +1 -1
  94. package/dist/{chunk-NOF73BUH.js → chunk-L6UMSKDF.js} +10 -2
  95. package/dist/chunk-L6UMSKDF.js.map +1 -0
  96. package/dist/{chunk-TCWECSEB.js → chunk-NSNM2ZXF.js} +28 -4
  97. package/dist/chunk-NSNM2ZXF.js.map +1 -0
  98. package/dist/{chunk-B6I7SF2X.js → chunk-OHNNCXMB.js} +114 -81
  99. package/dist/chunk-OHNNCXMB.js.map +1 -0
  100. package/dist/{chunk-MUOSKYI2.js → chunk-OJHPG6HK.js} +10 -10
  101. package/dist/{chunk-MUOSKYI2.js.map → chunk-OJHPG6HK.js.map} +1 -1
  102. package/dist/{chunk-SZPE55SB.js → chunk-PGZDSDOB.js} +3 -3
  103. package/dist/{chunk-SZPE55SB.js.map → chunk-PGZDSDOB.js.map} +1 -1
  104. package/dist/{chunk-4QINFQ27.js → chunk-PIC23DDE.js} +59 -17
  105. package/dist/chunk-PIC23DDE.js.map +1 -0
  106. package/dist/{chunk-GLMKS6V6.js → chunk-RTNWU2UD.js} +4 -4
  107. package/dist/{chunk-GLMKS6V6.js.map → chunk-RTNWU2UD.js.map} +1 -1
  108. package/dist/{chunk-354JIEIE.js → chunk-SAGBVBY2.js} +5 -5
  109. package/dist/{chunk-354JIEIE.js.map → chunk-SAGBVBY2.js.map} +1 -1
  110. package/dist/{chunk-55VKZUQY.js → chunk-SMUIYYCH.js} +70 -34
  111. package/dist/chunk-SMUIYYCH.js.map +1 -0
  112. package/dist/{chunk-N36S36OZ.js → chunk-SPV2CXJ3.js} +3 -3
  113. package/dist/{chunk-N36S36OZ.js.map → chunk-SPV2CXJ3.js.map} +1 -1
  114. package/dist/{chunk-KRRHADE7.js → chunk-SXWGLW23.js} +4 -4
  115. package/dist/{chunk-KRRHADE7.js.map → chunk-SXWGLW23.js.map} +1 -1
  116. package/dist/{chunk-RNFHJUK7.js → chunk-TADJCATD.js} +3 -3
  117. package/dist/{chunk-RNFHJUK7.js.map → chunk-TADJCATD.js.map} +1 -1
  118. package/dist/{chunk-PQF5QHVS.js → chunk-TKI7YDWE.js} +19 -5
  119. package/dist/chunk-TKI7YDWE.js.map +1 -0
  120. package/dist/{chunk-O673TBWJ.js → chunk-TXGVG7VH.js} +3 -3
  121. package/dist/{chunk-O673TBWJ.js.map → chunk-TXGVG7VH.js.map} +1 -1
  122. package/dist/{chunk-GV3MFKDV.js → chunk-VJ2DZLDM.js} +62 -6
  123. package/dist/chunk-VJ2DZLDM.js.map +1 -0
  124. package/dist/{chunk-PV47EEHD.js → chunk-WKEBNB5S.js} +4 -4
  125. package/dist/{chunk-PV47EEHD.js.map → chunk-WKEBNB5S.js.map} +1 -1
  126. package/dist/{chunk-ESXZJP4M.js → chunk-WXWQNJCT.js} +3 -3
  127. package/dist/{chunk-ESXZJP4M.js.map → chunk-WXWQNJCT.js.map} +1 -1
  128. package/dist/{chunk-DPCEQOIZ.js → chunk-XGR7IDTY.js} +3 -3
  129. package/dist/{chunk-DPCEQOIZ.js.map → chunk-XGR7IDTY.js.map} +1 -1
  130. package/dist/{chunk-VQQCA7BD.js → chunk-Y25V2MW2.js} +4 -4
  131. package/dist/{chunk-VQQCA7BD.js.map → chunk-Y25V2MW2.js.map} +1 -1
  132. package/dist/{chunk-MGM5EJQQ.js → chunk-YK3XLEQJ.js} +40 -26
  133. package/dist/chunk-YK3XLEQJ.js.map +1 -0
  134. package/dist/{chunk-SP5NGNBV.js → chunk-YW2BNDSE.js} +11 -4
  135. package/dist/chunk-YW2BNDSE.js.map +1 -0
  136. package/dist/{chunk-J76LDUDS.js → chunk-ZVZTCDUN.js} +26 -10
  137. package/dist/chunk-ZVZTCDUN.js.map +1 -0
  138. package/dist/cli/index.js +899 -1617
  139. package/dist/cli/index.js.map +1 -1
  140. package/dist/cli/src/agent-checks.d.ts +22 -10
  141. package/dist/cli/src/agent-checks.d.ts.map +1 -1
  142. package/dist/cli/src/commands/catalog.d.ts.map +1 -1
  143. package/dist/cli/src/commands/config.d.ts.map +1 -1
  144. package/dist/cli/src/commands/integration.d.ts.map +1 -1
  145. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  146. package/dist/cli/src/commands/library-index.d.ts +6 -0
  147. package/dist/cli/src/commands/library-index.d.ts.map +1 -1
  148. package/dist/cli/src/commands/library-publish.d.ts.map +1 -1
  149. package/dist/cli/src/commands/outdated.d.ts.map +1 -1
  150. package/dist/cli/src/commands/plugin/codex.d.ts +10 -0
  151. package/dist/cli/src/commands/plugin/codex.d.ts.map +1 -1
  152. package/dist/cli/src/commands/plugin/types.d.ts +5 -2
  153. package/dist/cli/src/commands/plugin/types.d.ts.map +1 -1
  154. package/dist/cli/src/commands/preset-export.d.ts.map +1 -1
  155. package/dist/cli/src/commands/project.d.ts +6 -0
  156. package/dist/cli/src/commands/project.d.ts.map +1 -1
  157. package/dist/cli/src/commands/rebuild.d.ts.map +1 -1
  158. package/dist/cli/src/commands/run.d.ts.map +1 -1
  159. package/dist/cli/src/commands/serve-preflight.d.ts +13 -0
  160. package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
  161. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  162. package/dist/cli/src/commands/show.d.ts.map +1 -1
  163. package/dist/cli/src/commands/source.d.ts +2 -1
  164. package/dist/cli/src/commands/source.d.ts.map +1 -1
  165. package/dist/cli/src/commands/store.d.ts.map +1 -1
  166. package/dist/cli/src/commands/update.d.ts.map +1 -1
  167. package/dist/cli/src/commands/validate.d.ts +6 -1
  168. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  169. package/dist/cli/src/commands/verify.d.ts.map +1 -1
  170. package/dist/cli/src/helpers.d.ts +23 -0
  171. package/dist/cli/src/helpers.d.ts.map +1 -1
  172. package/dist/cli/src/plugin-store/index.d.ts +8 -0
  173. package/dist/cli/src/plugin-store/index.d.ts.map +1 -1
  174. package/dist/cli/src/plugin-store/load.d.ts +1 -0
  175. package/dist/cli/src/plugin-store/load.d.ts.map +1 -1
  176. package/dist/cli/src/skill-checks.d.ts +9 -21
  177. package/dist/cli/src/skill-checks.d.ts.map +1 -1
  178. package/dist/connectors/config.js +5 -5
  179. package/dist/connectors/index.js +16 -15
  180. package/dist/{connectors-TVFFE5H4.js → connectors-44RE2QEM.js} +19 -18
  181. package/dist/{connectors-TVFFE5H4.js.map → connectors-44RE2QEM.js.map} +1 -1
  182. package/dist/core/index.js +6 -6
  183. package/dist/core/manifest.js +2 -2
  184. package/dist/core/models.js +1 -1
  185. package/dist/core/publish-manifest.js +3 -3
  186. package/dist/core/ref.js +1 -1
  187. package/dist/core/runtime-assets.js +5 -5
  188. package/dist/core/src/conformance.d.ts.map +1 -1
  189. package/dist/core/src/driver-sdk.d.ts +12 -2
  190. package/dist/core/src/driver-sdk.d.ts.map +1 -1
  191. package/dist/core/src/index.d.ts +4 -4
  192. package/dist/core/src/index.d.ts.map +1 -1
  193. package/dist/core/src/lock.d.ts +7 -0
  194. package/dist/core/src/lock.d.ts.map +1 -1
  195. package/dist/core/src/manifest.d.ts +9 -0
  196. package/dist/core/src/manifest.d.ts.map +1 -1
  197. package/dist/core/src/models.d.ts.map +1 -1
  198. package/dist/core/src/publish-manifest.d.ts +5 -2
  199. package/dist/core/src/publish-manifest.d.ts.map +1 -1
  200. package/dist/core/src/repo-manager.d.ts +14 -0
  201. package/dist/core/src/repo-manager.d.ts.map +1 -1
  202. package/dist/core/workspace-config.js +4 -4
  203. package/dist/deploy/index.js +6 -6
  204. package/dist/discovery/index.js +5 -5
  205. package/dist/discovery/src/index.d.ts +2 -2
  206. package/dist/discovery/src/index.d.ts.map +1 -1
  207. package/dist/discovery/src/parse-manifest.d.ts +7 -0
  208. package/dist/discovery/src/parse-manifest.d.ts.map +1 -1
  209. package/dist/discovery/src/source-config.d.ts +6 -0
  210. package/dist/discovery/src/source-config.d.ts.map +1 -1
  211. package/dist/{ensure-sources-N4E5EDGC.js → ensure-sources-R6AHZ7RV.js} +16 -16
  212. package/dist/{ensure-sources-N4E5EDGC.js.map → ensure-sources-R6AHZ7RV.js.map} +1 -1
  213. package/dist/factory-assets/README.md +1 -1
  214. package/dist/factory-assets/connectors/box.js +16 -15
  215. package/dist/factory-assets/connectors/deploy.js +16 -15
  216. package/dist/factory-assets/connectors/devserver.js +16 -15
  217. package/dist/factory-assets/connectors/flow/adapter.js +16 -15
  218. package/dist/factory-assets/connectors/flow/engine.js +7 -7
  219. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  220. package/dist/factory-assets/connectors/flow/run-flow.js +18 -17
  221. package/dist/factory-assets/connectors/flow.js +16 -15
  222. package/dist/factory-assets/connectors/git.js +16 -15
  223. package/dist/factory-assets/connectors/gmail.js +16 -15
  224. package/dist/factory-assets/connectors/googledrive.js +16 -15
  225. package/dist/factory-assets/connectors/local.js +16 -15
  226. package/dist/factory-assets/connectors/mattermost.js +16 -15
  227. package/dist/factory-assets/connectors/memory.js +16 -15
  228. package/dist/factory-assets/connectors/minio.js +16 -15
  229. package/dist/factory-assets/connectors/postgres.js +16 -15
  230. package/dist/factory-assets/connectors/s3.js +16 -15
  231. package/dist/factory-assets/connectors/sharepoint.js +16 -15
  232. package/dist/factory-assets/connectors/sqlite.js +16 -15
  233. package/dist/factory-assets/connectors/static-server.js +16 -15
  234. package/dist/factory-assets/connectors/tunnel.js +16 -15
  235. package/dist/factory-assets/connectors/webdav.js +16 -15
  236. package/dist/factory-assets/connectors/xstate-store.js +16 -15
  237. package/dist/factory-assets/connectors/xstate.js +16 -15
  238. package/dist/factory-assets/skills/authoring-skaile-assets/SKILL.md +12 -11
  239. package/dist/factory-assets/skills/authoring-skaile-manifests/SKILL.md +11 -7
  240. package/dist/factory-assets/skills/skailify/SKILL.md +3 -3
  241. package/dist/{flows-CYJI3URW.js → flows-YKC53LDP.js} +11 -11
  242. package/dist/{flows-CYJI3URW.js.map → flows-YKC53LDP.js.map} +1 -1
  243. package/dist/{helpers-PPVGVYIZ.js → helpers-FNQL5PI7.js} +16 -16
  244. package/dist/{helpers-PPVGVYIZ.js.map → helpers-FNQL5PI7.js.map} +1 -1
  245. package/dist/library/index.js +10 -10
  246. package/dist/library/install.js +4 -4
  247. package/dist/library/src/index.d.ts +1 -1
  248. package/dist/library/src/index.d.ts.map +1 -1
  249. package/dist/library/src/local/store-paths.d.ts +8 -0
  250. package/dist/library/src/local/store-paths.d.ts.map +1 -1
  251. package/dist/library/src/manifest-writer.d.ts +5 -1
  252. package/dist/library/src/manifest-writer.d.ts.map +1 -1
  253. package/dist/library/src/remote/remote-catalog-source.d.ts +3 -2
  254. package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
  255. package/dist/{library-publish-EQFYHJ6G.js → library-publish-GHPVY42Y.js} +56 -48
  256. package/dist/library-publish-GHPVY42Y.js.map +1 -0
  257. package/dist/model-endpoint/index.js +19 -3
  258. package/dist/model-endpoint/src/index.d.ts +1 -1
  259. package/dist/model-endpoint/src/index.d.ts.map +1 -1
  260. package/dist/model-endpoint/src/resolve.d.ts +5 -0
  261. package/dist/model-endpoint/src/resolve.d.ts.map +1 -1
  262. package/dist/model-endpoint/src/server.d.ts +7 -0
  263. package/dist/model-endpoint/src/server.d.ts.map +1 -1
  264. package/dist/model-endpoint/src/types.d.ts +41 -7
  265. package/dist/model-endpoint/src/types.d.ts.map +1 -1
  266. package/dist/{open-library-JJGDEYYT.js → open-library-YSUGNP36.js} +19 -19
  267. package/dist/{open-library-JJGDEYYT.js.map → open-library-YSUGNP36.js.map} +1 -1
  268. package/dist/{open-registry-X6YQVP7V.js → open-registry-YPRQDUMK.js} +14 -14
  269. package/dist/{open-registry-X6YQVP7V.js.map → open-registry-YPRQDUMK.js.map} +1 -1
  270. package/dist/{paths-NXWIBZCX.js → paths-P55DTBEK.js} +9 -9
  271. package/dist/{paths-NXWIBZCX.js.map → paths-P55DTBEK.js.map} +1 -1
  272. package/dist/plugin-store-IPIBZRBX.js +23 -0
  273. package/dist/plugin-store-IPIBZRBX.js.map +1 -0
  274. package/dist/project-NDSLXERO.js +83 -0
  275. package/dist/{project-5HW3XSOE.js.map → project-NDSLXERO.js.map} +1 -1
  276. package/dist/resolver/index.js +7 -7
  277. package/dist/resolver/src/types.d.ts +1 -0
  278. package/dist/resolver/src/types.d.ts.map +1 -1
  279. package/dist/resolver/src/validator.d.ts +1 -1
  280. package/dist/runner/index.js +32 -31
  281. package/dist/runner/src/agent.d.ts +9 -1
  282. package/dist/runner/src/agent.d.ts.map +1 -1
  283. package/dist/runner/src/agents/in-process-host.d.ts.map +1 -1
  284. package/dist/runner/src/composition/content-source.d.ts.map +1 -1
  285. package/dist/runner/src/composition/index.d.ts +1 -1
  286. package/dist/runner/src/composition/index.d.ts.map +1 -1
  287. package/dist/runner/src/composition/resolve-instance.d.ts +20 -0
  288. package/dist/runner/src/composition/resolve-instance.d.ts.map +1 -1
  289. package/dist/runner/src/model-endpoint-discovery.d.ts.map +1 -1
  290. package/dist/runner/src/resource-handler.d.ts.map +1 -1
  291. package/dist/runner/src/runner-capabilities.d.ts +9 -3
  292. package/dist/runner/src/runner-capabilities.d.ts.map +1 -1
  293. package/dist/runner/src/serve.d.ts +10 -0
  294. package/dist/runner/src/serve.d.ts.map +1 -1
  295. package/dist/runner/src/session-builder.d.ts +20 -1
  296. package/dist/runner/src/session-builder.d.ts.map +1 -1
  297. package/dist/runner/src/session-capability-wiring.d.ts +5 -0
  298. package/dist/runner/src/session-capability-wiring.d.ts.map +1 -1
  299. package/dist/sdk/asset-manager.js +13 -13
  300. package/dist/sdk/bridge.js +13 -12
  301. package/dist/sdk/core.js +6 -6
  302. package/dist/sdk/flow.js +7 -7
  303. package/dist/sdk/index.js +32 -31
  304. package/dist/sdk/index.js.map +1 -1
  305. package/dist/sdk/resolver.js +7 -7
  306. package/dist/sdk/runner.js +32 -31
  307. package/dist/sdk/transport/ws/server.js +1 -1
  308. package/dist/sdk/transport/ws.js +1 -1
  309. package/dist/sdk/transport.js +1 -1
  310. package/dist/{serve-preflight-GD7IQFA3.js → serve-preflight-ON2LS3SD.js} +15 -9
  311. package/dist/serve-preflight-ON2LS3SD.js.map +1 -0
  312. package/dist/{setup-52NDDR7C.js → setup-MFPEQS2I.js} +23 -22
  313. package/dist/setup-MFPEQS2I.js.map +1 -0
  314. package/dist/{skills-XVHOXOOH.js → skills-7G6QCDEM.js} +12 -12
  315. package/dist/{skills-XVHOXOOH.js.map → skills-7G6QCDEM.js.map} +1 -1
  316. package/dist/{source-WKV4QFGS.js → source-4QVRD5NV.js} +42 -41
  317. package/dist/{source-WKV4QFGS.js.map → source-4QVRD5NV.js.map} +1 -1
  318. package/dist/{source-manifest-publish-3HAX6DPN.js → source-manifest-publish-ZIO24GUM.js} +44 -43
  319. package/dist/source-manifest-publish-ZIO24GUM.js.map +1 -0
  320. package/dist/transport/index.js +1 -1
  321. package/dist/transport/src/ws/server.d.ts +9 -0
  322. package/dist/transport/src/ws/server.d.ts.map +1 -1
  323. package/dist/transport/ws/server.js +1 -1
  324. package/dist/transport/ws.js +1 -1
  325. package/dist/tui/index.js +107 -41
  326. package/dist/tui/index.js.map +1 -1
  327. package/dist/tui/src/repl-session.d.ts +7 -0
  328. package/dist/tui/src/repl-session.d.ts.map +1 -1
  329. package/dist/tui/src/repl.d.ts +16 -0
  330. package/dist/tui/src/repl.d.ts.map +1 -1
  331. package/dist/types/manifests.js +1 -1
  332. package/dist/types/src/manifests/index.d.ts +1 -0
  333. package/dist/types/src/manifests/index.d.ts.map +1 -1
  334. package/dist/types/src/manifests/scaffold-body.d.ts +8 -0
  335. package/dist/types/src/manifests/scaffold-body.d.ts.map +1 -0
  336. package/dist/workspace-plugin/adapters/mcp.js +23 -22
  337. package/dist/workspace-plugin/adapters/omp.js +14 -14
  338. package/dist/workspace-plugin/index.js +1 -1
  339. package/package.json +1 -1
  340. package/dist/chunk-4AKR4XPQ.js.map +0 -1
  341. package/dist/chunk-4QINFQ27.js.map +0 -1
  342. package/dist/chunk-55VKZUQY.js.map +0 -1
  343. package/dist/chunk-7Y7UYNGL.js.map +0 -1
  344. package/dist/chunk-ANSZULXH.js.map +0 -1
  345. package/dist/chunk-B6I7SF2X.js.map +0 -1
  346. package/dist/chunk-GQ5OYFVD.js.map +0 -1
  347. package/dist/chunk-GV3MFKDV.js.map +0 -1
  348. package/dist/chunk-J76LDUDS.js.map +0 -1
  349. package/dist/chunk-JJLH4TX4.js.map +0 -1
  350. package/dist/chunk-MGM5EJQQ.js.map +0 -1
  351. package/dist/chunk-NKDSU4Q7.js.map +0 -1
  352. package/dist/chunk-NOF73BUH.js.map +0 -1
  353. package/dist/chunk-NVBN3YOH.js.map +0 -1
  354. package/dist/chunk-OOQ5Q75W.js.map +0 -1
  355. package/dist/chunk-PQF5QHVS.js.map +0 -1
  356. package/dist/chunk-R37L4BNR.js.map +0 -1
  357. package/dist/chunk-RTYDYSUV.js.map +0 -1
  358. package/dist/chunk-SP5NGNBV.js.map +0 -1
  359. package/dist/chunk-TCWECSEB.js.map +0 -1
  360. package/dist/chunk-VY6NTFE7.js.map +0 -1
  361. package/dist/chunk-WWUWMOX2.js.map +0 -1
  362. package/dist/library-publish-EQFYHJ6G.js.map +0 -1
  363. package/dist/plugin-store-BIITCNOZ.js.map +0 -1
  364. package/dist/project-5HW3XSOE.js +0 -82
  365. package/dist/serve-preflight-GD7IQFA3.js.map +0 -1
  366. package/dist/setup-52NDDR7C.js.map +0 -1
  367. package/dist/source-manifest-publish-3HAX6DPN.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { compositeSha256 } from './chunk-ANSZULXH.js';
2
- import { parseAssetRef } from './chunk-VY6NTFE7.js';
1
+ import { compositeSha256 } from './chunk-H7R7R5BN.js';
2
+ import { parseAssetRef } from './chunk-FT4ZHLYR.js';
3
3
  import { createHash } from 'crypto';
4
4
  import { rm, mkdir, writeFile } from 'fs/promises';
5
5
  import { isAbsolute, resolve, sep, join, dirname } from 'path';
@@ -123,5 +123,5 @@ async function installFlat(manifest, targetDir, fetcher) {
123
123
  }
124
124
 
125
125
  export { assertSafeManifestPath, installFromManifest, longestCommonDirPrefix };
126
- //# sourceMappingURL=chunk-KRRHADE7.js.map
127
- //# sourceMappingURL=chunk-KRRHADE7.js.map
126
+ //# sourceMappingURL=chunk-SXWGLW23.js.map
127
+ //# sourceMappingURL=chunk-SXWGLW23.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../library/src/install/install-from-manifest.ts"],"names":[],"mappings":";;;;;;AAgDO,SAAS,sBAAA,CAAuB,aAAqB,CAAA,EAAiB;AAC3E,EAAA,MAAM,MAAM,MAAa;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,CAAC,CAAA,CAAE,CAAA;AAAA,EACjD,CAAA;AACA,EAAA,IAAI,CAAC,CAAA,IAAK,CAAA,CAAE,MAAA,KAAW,GAAG,GAAA,EAAI;AAC9B,EAAA,IAAI,UAAA,CAAW,CAAC,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,EAAG,GAAA,EAAI;AAClE,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,KAAA,CAAM,OAAO,CAAA;AAChC,EAAA,IAAI,SAAS,IAAA,CAAK,CAAC,MAAM,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O,IAAA,CAAK,MAAA,EAAQ,OAAO,CAAA;AACjC,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,SAAA,CAAU,MAAM,GAAG,CAAA;AAAA,EAC3B;AAEA,EAAA,OAAO,EAAE,aAAa,MAAA,EAAO;AAC/B","file":"chunk-KRRHADE7.js","sourcesContent":["/**\n * Pointer-only install path.\n *\n * Given an {@link InstallManifest} (the Pointer Triple the Catalog hands\n * clients), this:\n *\n * 1. fetches the asset bytes directly from the upstream repo at the pinned\n * commit (via an injectable fetcher, default {@link fetchAssetFilesFromGitHub});\n * 2. verifies EVERY per-file SHA256 against `manifest.files[].sha256`;\n * 3. verifies the composite SHA256 rollup over the sorted\n * `<path>:<sha256>\\n` lines against `manifest.sha256`;\n * 4. writes the verified bytes under `<libraryRoot>/@<publisher>/<name>/<version>`.\n *\n * Any hash mismatch is a hard failure — bytes are not written if per-file\n * verification fails, and the composite check is the second gate.\n *\n * @docLink packages/library/concepts#install\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve, sep } from \"node:path\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { parseAssetRef } from \"../../../core/src/models.js\";\nimport { compositeSha256 } from \"../../../core/src/publish-manifest.js\";\n\n/**\n * Validate a single manifest-supplied file path against path traversal.\n *\n * `manifest.files[].path` comes off the network — the attacker controls the\n * entire manifest (and therefore every hash in it), so hash verification can\n * NEVER mitigate a malicious *destination*. A path like\n * `../../../../home/user/.bashrc` or an absolute path would escape\n * `installPath` and yield an arbitrary file write. Every path is checked\n * BEFORE any fetch or write happens; the first bad path aborts the entire\n * install with a hard throw.\n *\n * A path is rejected if ANY of:\n * - it is empty;\n * - it is absolute (`path.isAbsolute`) or has a leading slash;\n * - it contains a `..` segment;\n * - `path.resolve(installPath, p)` is not `installPath` itself and does not\n * start with `installPath + path.sep` (escapes the install dir).\n *\n * @throws An error matching `/unsafe path in manifest/` on the first bad path.\n */\nexport function assertSafeManifestPath(installPath: string, p: string): void {\n const bad = (): never => {\n throw new Error(`unsafe path in manifest: ${p}`);\n };\n if (!p || p.length === 0) bad();\n if (isAbsolute(p) || p.startsWith(\"/\") || p.startsWith(\"\\\\\")) bad();\n const segments = p.split(/[/\\\\]/);\n if (segments.some((s) => s === \"..\")) bad();\n const resolved = resolve(installPath, p);\n if (resolved !== installPath && !resolved.startsWith(installPath + sep)) bad();\n}\n\n/**\n * Validate one component (publisher / name / version) of the attacker-controlled\n * `manifest.ref`.\n *\n * `installPath` is built by joining these components onto `libraryRoot`. A\n * component containing a path separator or a `..` / leading-dot segment would\n * let `installPath` itself escape `libraryRoot` — yielding an arbitrary file\n * write AND, via the pre-write `rm(installPath, { recursive })`, an arbitrary\n * recursive delete. The per-file `assertSafeManifestPath` guard cannot catch\n * this: it only validates each `f.path` *relative to* `installPath`, never\n * `installPath` itself. Components must be plain identifier-like strings.\n *\n * @throws An error matching `/unsafe ref/` on a bad component.\n */\nfunction assertSafeRefComponent(kind: string, value: string): void {\n // Reject empty, leading-dot (covers `.` and `..`), path separators, and\n // ASCII control characters (NUL et al.) — fails a malformed segment fast\n // with a domain-specific error rather than a raw EINVAL deeper in.\n const hasControlChar = [...value].some((c) => c.charCodeAt(0) < 0x20);\n if (!value || value.startsWith(\".\") || /[/\\\\]/.test(value) || hasControlChar) {\n throw new Error(`unsafe ref ${kind} component in manifest: '${value}'`);\n }\n}\n\n/**\n * Longest common **directory** prefix across manifest paths, compared by whole\n * slash-delimited segments (never raw-string — so `app/` and `app-data/` never\n * collide). Each path's basename is excluded, so the result is always a\n * directory prefix and every path keeps a non-empty remainder after stripping.\n *\n * Used by flat mode to reproduce the platform pointer-installer's asset-rooting:\n * the store persists repo-root-relative paths (e.g. `skaile-platform/mcpo/xls/MCP.md`)\n * but the runner scans `.skaile/assets/<kind>/<name>/` for immediate-child files,\n * so this prefix is stripped from the WRITE path while the fetch keeps the full\n * repo path. Returns `''` when there is no common directory (a no-op strip).\n */\nexport function longestCommonDirPrefix(paths: readonly string[]): string {\n if (paths.length === 0) return \"\";\n const dirSegments = paths.map((p) => p.split(\"/\").slice(0, -1));\n let common = dirSegments[0]!;\n for (let i = 1; i < dirSegments.length && common.length > 0; i++) {\n const segs = dirSegments[i]!;\n let n = 0;\n while (n < common.length && n < segs.length && common[n] === segs[n]) n++;\n common = common.slice(0, n);\n }\n return common.join(\"/\");\n}\n\n/**\n * Fetcher signature — fetches `{ path → Buffer }` for the requested paths at\n * a pinned upstream commit. {@link fetchAssetFilesFromGitHub} is the default\n * production implementation; tests inject a mock.\n */\nexport type AssetFetcher = (opts: {\n url: string;\n commitSha: string;\n paths: string[];\n}) => Promise<Record<string, Buffer>>;\n\n/**\n * Options for {@link installFromManifest}.\n */\nexport interface InstallOpts {\n /** The pointer-only install manifest from the Catalog. */\n manifest: InstallManifest;\n /** Filesystem root the asset is installed under (ref-derived mode). */\n libraryRoot: string;\n /**\n * Pluggable fetcher so tests can inject mock data. Defaults to\n * {@link fetchAssetFilesFromGitHub} in production.\n */\n fetcher?: AssetFetcher;\n /**\n * Flat-layout mode. When set, install-core reproduces the platform\n * pointer-installer's behavior: it ignores `libraryRoot`/ref-derivation, does\n * NOT parse `manifest.ref` and does NOT verify the composite sha256, strips\n * the longest-common-dir prefix from each path, per-file sha256-verifies, and\n * writes the stripped paths as immediate children of `targetDir` (what the\n * runner's `.skaile/assets/<kind>/<name>/` scan requires). `installPath` is\n * `targetDir`. Absent → unchanged ref-derived `@<pub>/name/version/<path>`\n * layout with composite verify.\n */\n targetDir?: string;\n}\n\n/**\n * Result of a successful {@link installFromManifest} call.\n */\nexport interface InstallResult {\n /** Absolute path the asset files were written to. */\n installPath: string;\n}\n\n/**\n * Fetch, verify, and write an asset's files per its {@link InstallManifest}.\n *\n * @throws An error matching `/hash mismatch/i` if any per-file SHA256 differs.\n * @throws An error matching `/composite hash mismatch/i` if the rollup differs.\n * @throws An error if the ref is malformed or the fetcher omits a file.\n */\nexport async function installFromManifest(opts: InstallOpts): Promise<InstallResult> {\n const { manifest, libraryRoot } = opts;\n const fetcher =\n opts.fetcher ?? (await import(\"./source-fetch-github.js\")).fetchAssetFilesFromGitHub;\n\n // Flat mode: reproduce the platform pointer-installer's asset-rooted layout.\n // No ref parse, no composite verify — the platform store may not satisfy a\n // ref-grammar or composite, and the runner only needs immediate-child files.\n if (opts.targetDir !== undefined) {\n return installFlat(manifest, opts.targetDir, fetcher);\n }\n\n // 1. Parse ref into install path: `skill:@x/git#1.0.0` → `<root>/@x/git/1.0.0`.\n // Done first so the C1 path-traversal guard can resolve against installPath\n // BEFORE any network fetch happens. The ref is attacker-controlled, so each\n // segment is further validated as a safe path component (H1) after parsing.\n // `parseAssetRef` is the single canonical grammar (`kind:@publisher/name#version`);\n // the legacy trailing-`@version` shape was removed in core and is rejected here.\n let parsed: ReturnType<typeof parseAssetRef>;\n try {\n parsed = parseAssetRef(manifest.ref);\n } catch (e) {\n throw new Error(`invalid ref: ${manifest.ref}: ${e instanceof Error ? e.message : String(e)}`);\n }\n const publisher = parsed.publisher;\n const name = parsed.name;\n const version = parsed.pin;\n if (!publisher) throw new Error(`invalid ref: ${manifest.ref} (missing publisher)`);\n if (!version) throw new Error(`invalid ref: ${manifest.ref} (missing version pin)`);\n assertSafeRefComponent(\"publisher\", publisher);\n assertSafeRefComponent(\"name\", name);\n assertSafeRefComponent(\"version\", version);\n const root = resolve(libraryRoot);\n const installPath = resolve(join(root, `@${publisher}`, name, version));\n // Defense in depth: even with the segment guards above, assert the built\n // installPath stays strictly inside libraryRoot before any write or `rm`.\n if (installPath !== root && !installPath.startsWith(root + sep)) {\n throw new Error(`unsafe install path: ref '${manifest.ref}' resolves outside the library root`);\n }\n\n // 2. [C1] Validate EVERY manifest path against traversal BEFORE fetching.\n // The attacker controls the manifest (and thus all hashes) — hashes verify\n // content, never destination. Reject the whole install on the first bad path.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n }\n\n // 3. Fetch all files at the pinned commit.\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // 4. Verify per-file SHA256 — hard fail before writing anything. The path\n // key used to read from the fetcher result is re-guarded as defense in depth.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n }\n\n // 5. Verify composite SHA256 over the sorted `<path>:<sha256>\\n` lines.\n const actualComposite = compositeSha256(manifest.files);\n if (actualComposite !== manifest.sha256) {\n throw new Error(`composite hash mismatch: expected ${manifest.sha256}, got ${actualComposite}`);\n }\n\n // 6. [M1] Write all verified files. A failed install must leave NO partial\n // directory: any prior `installPath` is removed first (clean overwrite), and\n // a mid-loop write failure removes the partially-written tree before\n // rethrowing.\n await rm(installPath, { recursive: true, force: true });\n try {\n for (const f of manifest.files) {\n const target = join(installPath, f.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, bytes[f.path]!);\n }\n } catch (e) {\n await rm(installPath, { recursive: true, force: true }).catch(() => {});\n throw e;\n }\n\n return { installPath };\n}\n\n/**\n * Flat-layout install — the platform pointer-installer's behavior, made canonical\n * in install-core. Validates every path, fetches with the FULL repo paths, per-file\n * sha256-verifies, then strips the longest-common-dir prefix and writes each file\n * as `join(targetDir, path.slice(assetRoot.length + 1))` — immediate children of\n * `targetDir`. No ref parse, no composite check.\n */\nasync function installFlat(\n manifest: InstallManifest,\n targetDir: string,\n fetcher: AssetFetcher,\n): Promise<InstallResult> {\n const target = resolve(targetDir);\n\n // Gate every path before any fetch — the attacker controls the whole manifest.\n for (const f of manifest.files) {\n assertSafeManifestPath(target, f.path);\n }\n\n // Fetch keys off the FULL repo path (matches the upstream tree).\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // Strip the asset-root dir prefix from the WRITE path only — the fetch above\n // still keyed off the full repo path. Stripping removes leading whole segments\n // (never the basename), so a non-empty remainder always survives.\n const assetRoot = longestCommonDirPrefix(paths);\n\n for (const f of manifest.files) {\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n const relPath = assetRoot ? f.path.slice(assetRoot.length + 1) : f.path;\n // Re-guard the post-strip destination — it is what we actually write.\n assertSafeManifestPath(target, relPath);\n const dest = join(target, relPath);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, buf);\n }\n\n return { installPath: target };\n}\n"]}
1
+ {"version":3,"sources":["../library/src/install/install-from-manifest.ts"],"names":[],"mappings":";;;;;;AAgDO,SAAS,sBAAA,CAAuB,aAAqB,CAAA,EAAiB;AAC3E,EAAA,MAAM,MAAM,MAAa;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,CAAC,CAAA,CAAE,CAAA;AAAA,EACjD,CAAA;AACA,EAAA,IAAI,CAAC,CAAA,IAAK,CAAA,CAAE,MAAA,KAAW,GAAG,GAAA,EAAI;AAC9B,EAAA,IAAI,UAAA,CAAW,CAAC,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,EAAG,GAAA,EAAI;AAClE,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,KAAA,CAAM,OAAO,CAAA;AAChC,EA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OAAO,CAAA;AACtC,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,MAAA,EAAQ,OAAO,CAAA;AACjC,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,SAAA,CAAU,MAAM,GAAG,CAAA;AAAA,EAC3B;AAEA,EAAA,OAAO,EAAE,aAAa,MAAA,EAAO;AAC/B","file":"chunk-SXWGLW23.js","sourcesContent":["/**\n * Pointer-only install path.\n *\n * Given an {@link InstallManifest} (the Pointer Triple the Catalog hands\n * clients), this:\n *\n * 1. fetches the asset bytes directly from the upstream repo at the pinned\n * commit (via an injectable fetcher, default {@link fetchAssetFilesFromGitHub});\n * 2. verifies EVERY per-file SHA256 against `manifest.files[].sha256`;\n * 3. verifies the composite SHA256 rollup over the sorted\n * `<path>:<sha256>\\n` lines against `manifest.sha256`;\n * 4. writes the verified bytes under `<libraryRoot>/@<publisher>/<name>/<version>`.\n *\n * Any hash mismatch is a hard failure — bytes are not written if per-file\n * verification fails, and the composite check is the second gate.\n *\n * @docLink packages/library/concepts#install\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve, sep } from \"node:path\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { parseAssetRef } from \"../../../core/src/models.js\";\nimport { compositeSha256 } from \"../../../core/src/publish-manifest.js\";\n\n/**\n * Validate a single manifest-supplied file path against path traversal.\n *\n * `manifest.files[].path` comes off the network — the attacker controls the\n * entire manifest (and therefore every hash in it), so hash verification can\n * NEVER mitigate a malicious *destination*. A path like\n * `../../../../home/user/.bashrc` or an absolute path would escape\n * `installPath` and yield an arbitrary file write. Every path is checked\n * BEFORE any fetch or write happens; the first bad path aborts the entire\n * install with a hard throw.\n *\n * A path is rejected if ANY of:\n * - it is empty;\n * - it is absolute (`path.isAbsolute`) or has a leading slash;\n * - it contains a `..` segment;\n * - `path.resolve(installPath, p)` is not `installPath` itself and does not\n * start with `installPath + path.sep` (escapes the install dir).\n *\n * @throws An error matching `/unsafe path in manifest/` on the first bad path.\n */\nexport function assertSafeManifestPath(installPath: string, p: string): void {\n const bad = (): never => {\n throw new Error(`unsafe path in manifest: ${p}`);\n };\n if (!p || p.length === 0) bad();\n if (isAbsolute(p) || p.startsWith(\"/\") || p.startsWith(\"\\\\\")) bad();\n const segments = p.split(/[/\\\\]/);\n if (segments.some((s) => s === \"..\")) bad();\n const resolved = resolve(installPath, p);\n if (resolved !== installPath && !resolved.startsWith(installPath + sep)) bad();\n}\n\n/**\n * Validate one component (publisher / name / version) of the attacker-controlled\n * `manifest.ref`.\n *\n * `installPath` is built by joining these components onto `libraryRoot`. A\n * component containing a path separator or a `..` / leading-dot segment would\n * let `installPath` itself escape `libraryRoot` — yielding an arbitrary file\n * write AND, via the pre-write `rm(installPath, { recursive })`, an arbitrary\n * recursive delete. The per-file `assertSafeManifestPath` guard cannot catch\n * this: it only validates each `f.path` *relative to* `installPath`, never\n * `installPath` itself. Components must be plain identifier-like strings.\n *\n * @throws An error matching `/unsafe ref/` on a bad component.\n */\nfunction assertSafeRefComponent(kind: string, value: string): void {\n // Reject empty, leading-dot (covers `.` and `..`), path separators, and\n // ASCII control characters (NUL et al.) — fails a malformed segment fast\n // with a domain-specific error rather than a raw EINVAL deeper in.\n const hasControlChar = [...value].some((c) => c.charCodeAt(0) < 0x20);\n if (!value || value.startsWith(\".\") || /[/\\\\]/.test(value) || hasControlChar) {\n throw new Error(`unsafe ref ${kind} component in manifest: '${value}'`);\n }\n}\n\n/**\n * Longest common **directory** prefix across manifest paths, compared by whole\n * slash-delimited segments (never raw-string — so `app/` and `app-data/` never\n * collide). Each path's basename is excluded, so the result is always a\n * directory prefix and every path keeps a non-empty remainder after stripping.\n *\n * Used by flat mode to reproduce the platform pointer-installer's asset-rooting:\n * the store persists repo-root-relative paths (e.g. `skaile-platform/mcpo/xls/MCP.md`)\n * but the runner scans `.skaile/assets/<kind>/<name>/` for immediate-child files,\n * so this prefix is stripped from the WRITE path while the fetch keeps the full\n * repo path. Returns `''` when there is no common directory (a no-op strip).\n */\nexport function longestCommonDirPrefix(paths: readonly string[]): string {\n if (paths.length === 0) return \"\";\n const dirSegments = paths.map((p) => p.split(\"/\").slice(0, -1));\n let common = dirSegments[0]!;\n for (let i = 1; i < dirSegments.length && common.length > 0; i++) {\n const segs = dirSegments[i]!;\n let n = 0;\n while (n < common.length && n < segs.length && common[n] === segs[n]) n++;\n common = common.slice(0, n);\n }\n return common.join(\"/\");\n}\n\n/**\n * Fetcher signature — fetches `{ path → Buffer }` for the requested paths at\n * a pinned upstream commit. {@link fetchAssetFilesFromGitHub} is the default\n * production implementation; tests inject a mock.\n */\nexport type AssetFetcher = (opts: {\n url: string;\n commitSha: string;\n paths: string[];\n}) => Promise<Record<string, Buffer>>;\n\n/**\n * Options for {@link installFromManifest}.\n */\nexport interface InstallOpts {\n /** The pointer-only install manifest from the Catalog. */\n manifest: InstallManifest;\n /** Filesystem root the asset is installed under (ref-derived mode). */\n libraryRoot: string;\n /**\n * Pluggable fetcher so tests can inject mock data. Defaults to\n * {@link fetchAssetFilesFromGitHub} in production.\n */\n fetcher?: AssetFetcher;\n /**\n * Flat-layout mode. When set, install-core reproduces the platform\n * pointer-installer's behavior: it ignores `libraryRoot`/ref-derivation, does\n * NOT parse `manifest.ref` and does NOT verify the composite sha256, strips\n * the longest-common-dir prefix from each path, per-file sha256-verifies, and\n * writes the stripped paths as immediate children of `targetDir` (what the\n * runner's `.skaile/assets/<kind>/<name>/` scan requires). `installPath` is\n * `targetDir`. Absent → unchanged ref-derived `@<pub>/name/version/<path>`\n * layout with composite verify.\n */\n targetDir?: string;\n}\n\n/**\n * Result of a successful {@link installFromManifest} call.\n */\nexport interface InstallResult {\n /** Absolute path the asset files were written to. */\n installPath: string;\n}\n\n/**\n * Fetch, verify, and write an asset's files per its {@link InstallManifest}.\n *\n * @throws An error matching `/hash mismatch/i` if any per-file SHA256 differs.\n * @throws An error matching `/composite hash mismatch/i` if the rollup differs.\n * @throws An error if the ref is malformed or the fetcher omits a file.\n */\nexport async function installFromManifest(opts: InstallOpts): Promise<InstallResult> {\n const { manifest, libraryRoot } = opts;\n const fetcher =\n opts.fetcher ?? (await import(\"./source-fetch-github.js\")).fetchAssetFilesFromGitHub;\n\n // Flat mode: reproduce the platform pointer-installer's asset-rooted layout.\n // No ref parse, no composite verify — the platform store may not satisfy a\n // ref-grammar or composite, and the runner only needs immediate-child files.\n if (opts.targetDir !== undefined) {\n return installFlat(manifest, opts.targetDir, fetcher);\n }\n\n // 1. Parse ref into install path: `skill:@x/git#1.0.0` → `<root>/@x/git/1.0.0`.\n // Done first so the C1 path-traversal guard can resolve against installPath\n // BEFORE any network fetch happens. The ref is attacker-controlled, so each\n // segment is further validated as a safe path component (H1) after parsing.\n // `parseAssetRef` is the single canonical grammar (`kind:@publisher/name#version`);\n // the legacy trailing-`@version` shape was removed in core and is rejected here.\n let parsed: ReturnType<typeof parseAssetRef>;\n try {\n parsed = parseAssetRef(manifest.ref);\n } catch (e) {\n throw new Error(`invalid ref: ${manifest.ref}: ${e instanceof Error ? e.message : String(e)}`);\n }\n const publisher = parsed.publisher;\n const name = parsed.name;\n const version = parsed.pin;\n if (!publisher) throw new Error(`invalid ref: ${manifest.ref} (missing publisher)`);\n if (!version) throw new Error(`invalid ref: ${manifest.ref} (missing version pin)`);\n assertSafeRefComponent(\"publisher\", publisher);\n assertSafeRefComponent(\"name\", name);\n assertSafeRefComponent(\"version\", version);\n const root = resolve(libraryRoot);\n const installPath = resolve(join(root, `@${publisher}`, name, version));\n // Defense in depth: even with the segment guards above, assert the built\n // installPath stays strictly inside libraryRoot before any write or `rm`.\n if (installPath !== root && !installPath.startsWith(root + sep)) {\n throw new Error(`unsafe install path: ref '${manifest.ref}' resolves outside the library root`);\n }\n\n // 2. [C1] Validate EVERY manifest path against traversal BEFORE fetching.\n // The attacker controls the manifest (and thus all hashes) — hashes verify\n // content, never destination. Reject the whole install on the first bad path.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n }\n\n // 3. Fetch all files at the pinned commit.\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // 4. Verify per-file SHA256 — hard fail before writing anything. The path\n // key used to read from the fetcher result is re-guarded as defense in depth.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n }\n\n // 5. Verify composite SHA256 over the sorted `<path>:<sha256>\\n` lines.\n const actualComposite = compositeSha256(manifest.files);\n if (actualComposite !== manifest.sha256) {\n throw new Error(`composite hash mismatch: expected ${manifest.sha256}, got ${actualComposite}`);\n }\n\n // 6. [M1] Write all verified files. A failed install must leave NO partial\n // directory: any prior `installPath` is removed first (clean overwrite), and\n // a mid-loop write failure removes the partially-written tree before\n // rethrowing.\n await rm(installPath, { recursive: true, force: true });\n try {\n for (const f of manifest.files) {\n const target = join(installPath, f.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, bytes[f.path]!);\n }\n } catch (e) {\n await rm(installPath, { recursive: true, force: true }).catch(() => {});\n throw e;\n }\n\n return { installPath };\n}\n\n/**\n * Flat-layout install — the platform pointer-installer's behavior, made canonical\n * in install-core. Validates every path, fetches with the FULL repo paths, per-file\n * sha256-verifies, then strips the longest-common-dir prefix and writes each file\n * as `join(targetDir, path.slice(assetRoot.length + 1))` — immediate children of\n * `targetDir`. No ref parse, no composite check.\n */\nasync function installFlat(\n manifest: InstallManifest,\n targetDir: string,\n fetcher: AssetFetcher,\n): Promise<InstallResult> {\n const target = resolve(targetDir);\n\n // Gate every path before any fetch — the attacker controls the whole manifest.\n for (const f of manifest.files) {\n assertSafeManifestPath(target, f.path);\n }\n\n // Fetch keys off the FULL repo path (matches the upstream tree).\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // Strip the asset-root dir prefix from the WRITE path only — the fetch above\n // still keyed off the full repo path. Stripping removes leading whole segments\n // (never the basename), so a non-empty remainder always survives.\n const assetRoot = longestCommonDirPrefix(paths);\n\n for (const f of manifest.files) {\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n const relPath = assetRoot ? f.path.slice(assetRoot.length + 1) : f.path;\n // Re-guard the post-strip destination — it is what we actually write.\n assertSafeManifestPath(target, relPath);\n const dest = join(target, relPath);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, buf);\n }\n\n return { installPath: target };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { err, okJson, ok } from './chunk-X5YPJV4N.js';
2
- import { buildConnectorListPayload } from './chunk-MUOSKYI2.js';
2
+ import { buildConnectorListPayload } from './chunk-OJHPG6HK.js';
3
3
  import { readFile } from 'fs/promises';
4
4
  import { join } from 'path';
5
5
 
@@ -117,5 +117,5 @@ async function connectorDescribe(manager, id) {
117
117
  }
118
118
 
119
119
  export { connectorDescribe, connectorExec, connectorList, connectorLoadSkill, connectorRead, connectorSearch, connectorWrite, mountList, mountRead, mountStatus, mountSync };
120
- //# sourceMappingURL=chunk-RNFHJUK7.js.map
121
- //# sourceMappingURL=chunk-RNFHJUK7.js.map
120
+ //# sourceMappingURL=chunk-TADJCATD.js.map
121
+ //# sourceMappingURL=chunk-TADJCATD.js.map
@@ -1 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C,OAAA,EAAS,OAAO,GAAA,CAAI,yCAAyC,CAAA;AAClE,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,SAAA,CAAU,EAAE,CAAA;AAClC,IAAA,OAAO,GAAG,KAAK,CAAA;AAAA,EACjB,SAAS,CAAA,EAAY;AACnB,IAAA,OAAO,IAAI,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF;AAcA,eAAsB,iBAAA,CACpB,SACA,EAAA,EACqB;AACrB,EAAA,IAAI,CAAC,OAAA,EAAS,OAAO,GAAA,CAAI,yCAAyC,CAAA;AAClE,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,QAAQ,UAAA,EAAW;AAClC,IAAA,MAAM,aAAa,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAO,EAAE,CAAA;AACjD,IAAA,IAAI,CAAC,UAAA,EAAY,OAAO,GAAA,CAAI,CAAA,mCAAA,EAAsC,EAAE,CAAA,CAAA,CAAG,CAAA;AACvE,IAAA,OAAO,OAAO,UAAU,CAAA;AAAA,EAC1B,SAAS,CAAA,EAAY;AACnB,IAAA,OAAO,IAAI,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF","file":"chunk-RNFHJUK7.js","sourcesContent":["// src/tools/connectors.ts\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { buildConnectorListPayload, type ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport type { ToolResult } from \"../types.js\";\nimport { err, ok, okJson } from \"../types.js\";\n\n// ── Mountable-connector helpers ──────────────────────────────────────────────\n//\n// The unified ConnectorManager owns mountable (filesystem-face) connectors too.\n// A connector is mountable when its `listConnectors()` summary carries a\n// `mountPath`. The `mount*` helpers below project that subset for the legacy\n// `mount_*` tool surface.\n\n/**\n * A connector summary that carries a projected filesystem path. Unlike the raw\n * `listConnectors()` summary, `mountPath` is non-optional here — `listMountable()`\n * runtime-filters to exactly those entries before narrowing to this type.\n */\ntype MountableConnector = ReturnType<ConnectorManager[\"listConnectors\"]>[number] & {\n mountPath: string;\n};\n\n/** Return the mountable (filesystem-face) connectors from a manager. */\nfunction listMountable(manager: ConnectorManager): MountableConnector[] {\n return manager\n .listConnectors()\n .filter((c): c is MountableConnector => typeof c.mountPath === \"string\");\n}\n\n/**\n * A mountable connector as reported to the agent, with an optional `reason`.\n *\n * A fleet-managed mount whose path is gone reports `status: \"error\"` plus a\n * `reason`, even though the connector handle still reads `connected`. One whose\n * probe timed out keeps its cached status and gains a `reason` saying it is\n * unverified: a slow cloud mount is not reported dead.\n */\ntype MountView = MountableConnector & { reason?: string };\n\n/** Overlay a live re-check on the cached connect-time status where one applies. */\nasync function withLiveness(\n manager: ConnectorManager,\n mount: MountableConnector,\n): Promise<MountView> {\n // Optional call: the tool tests' manager doubles omit the method.\n const liveness = await manager.checkMountLiveness?.(mount.id);\n if (!liveness || liveness.state === \"live\") return mount;\n if (liveness.state === \"dead\") return { ...mount, status: \"error\", reason: liveness.reason };\n return { ...mount, reason: liveness.reason };\n}\n\n/**\n * List all mountable (filesystem-face) connectors declared in `skaile.yaml`\n * with their current mount status.\n *\n * @param manager - Active `ConnectorManager` or `null` when not configured.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountList(manager: ConnectorManager | null): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n return okJson(await Promise.all(listMountable(manager).map((m) => withLiveness(manager, m))));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Sync a mountable connector — pull the latest content from its remote source.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountSync(\n manager: ConnectorManager | null,\n mountId: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const result = await manager.sync(mountId);\n return okJson(result);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Get the current status and metadata for a single mountable connector.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountStatus(\n manager: ConnectorManager | null,\n mountId: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const mount = listMountable(manager).find((v) => v.id === mountId);\n if (!mount) return err(`Mount not found: \"${mountId}\"`);\n return okJson(await withLiveness(manager, mount));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Read a file from within a mountable connector's projected directory by its\n * relative path.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n * @param filePath - Relative path within the projected mount directory.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountRead(\n manager: ConnectorManager | null,\n mountId: string,\n filePath: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const mount = listMountable(manager).find((v) => v.id === mountId);\n if (!mount) return err(`Mount not found: \"${mountId}\"`);\n const content = await readFile(join(mount.mountPath, filePath), \"utf-8\");\n return ok(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * List all connectors registered with the `ConnectorManager`.\n *\n * Returns `{ connected, failed }` — `connected` from `manager.listConnectors()`,\n * `failed` from `manager.listFailedConnectors()`. A connector that threw during\n * `connect()` never enters the active map, so it is absent from the first list\n * entirely; without the second one an agent driven through MCP or OMP has no\n * way to learn that a mount it is about to write into is dead. Returns an error\n * result when no manager is configured (i.e. `skaile.yaml` has no `connectors`\n * section).\n *\n * @param manager - Active `ConnectorManager` or `null` when not configured.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorList(manager: ConnectorManager | null): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n // Same payload as the Claude SDK tool: per-mount health and a notice when one is not ok.\n return okJson(await buildConnectorListPayload(manager));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Read content from a connector at the given path.\n *\n * Delegates to `manager.read(id, path)`. Returns an error result when the\n * path yields `null` (not found) or the manager is absent.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param path - Resource path within the connector (connector-specific format).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorRead(\n manager: ConnectorManager | null,\n id: string,\n path: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const content = await manager.read(id, path);\n if (content === null) return err(`No content at path \"${path}\" in connector \"${id}\"`);\n return okJson(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Write string content to a connector at the given path.\n *\n * Delegates to `manager.write(id, path, { data: content })`.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param path - Destination path within the connector.\n * @param content - String payload to write.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorWrite(\n manager: ConnectorManager | null,\n id: string,\n path: string,\n content: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n await manager.write(id, path, { data: content });\n return ok(`Written to \"${path}\" in connector \"${id}\"`);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Search a connector's data using a query string.\n *\n * Delegates to `manager.search(id, query)` and returns the result set as JSON.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param query - Free-text or structured query (connector-specific format).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorSearch(\n manager: ConnectorManager | null,\n id: string,\n query: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const results = await manager.search(id, query);\n return okJson(results);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Execute a named operation on a connector.\n *\n * Delegates to `manager.executeOp(id, operation, args)`. Operations and\n * their argument shapes are connector-specific; use {@link connectorDescribe}\n * to discover what operations a connector supports.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param operation - Operation name (from the connector's `RuntimeSkillDescriptor`).\n * @param args - Named arguments for the operation.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorExec(\n manager: ConnectorManager | null,\n id: string,\n operation: string,\n args: Record<string, unknown>,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const result = await manager.executeOp(id, operation, args);\n return ok(result);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Load the rendered skill body for a connector.\n *\n * Delegates to `manager.loadSkill(id)` and returns the skill content as\n * plain text. Useful when the agent needs the connector's operations and\n * usage instructions injected as prompt context.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorLoadSkill(\n manager: ConnectorManager | null,\n id: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const skill = manager.loadSkill(id);\n return ok(skill);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Describe a connector's capabilities via its `RuntimeSkillDescriptor`.\n *\n * Finds the matching skill descriptor from `manager.listSkills()` and returns\n * it as JSON. The descriptor includes the connector's operations, argument\n * shapes, and usage instructions.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorDescribe(\n manager: ConnectorManager | null,\n id: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const skills = manager.listSkills();\n const descriptor = skills.find((s) => s.id === id);\n if (!descriptor) return err(`No skill descriptor for connector \"${id}\"`);\n return okJson(descriptor);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n"]}
1
+ {"version":3,"sources":["../workspace-plugin/src/tools/connectors.ts"],"names":[],"mappings":";;;;;AAwBA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,OAAO,OAAA,CACJ,gBAAe,CACf,MAAA,CAAO,CAAC,CAAA,KAA+B,OAAO,CAAA,CAAE,SAAA,KAAc,QAAQ,CAAA;AAC3E;AAaA,eAAe,YAAA,CACb,SACA,KAAA,EACoB;AAEpB,EAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,kBAAA,GAAqB,MAAM,EAAE,CAAA;AAC5D,EAAA,IAAI,CAAC,QAAA,IAAY,QAAA,CAAS,KAAA,KAAU,QAAQ,OAAO,KAAA;AACnD,EAAA,IAAI,QAAA,CAAS,KAAA,KAAU,MAAA,EAAQ,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAO;AAC3F,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,MAAA,EAAQ,SAAS,MAAA,EAAO;AAC7C;AAUA,eAAsB,UAAU,OAAA,EAAuD;AACrF,EAAA,IAAI,CAAC,OAAA,EAAS,OAAO,GAAA,CAAI,yCAAyC,CAAA;AAClE,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,MAAM,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E,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF","file":"chunk-TADJCATD.js","sourcesContent":["// src/tools/connectors.ts\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { buildConnectorListPayload, type ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport type { ToolResult } from \"../types.js\";\nimport { err, ok, okJson } from \"../types.js\";\n\n// ── Mountable-connector helpers ──────────────────────────────────────────────\n//\n// The unified ConnectorManager owns mountable (filesystem-face) connectors too.\n// A connector is mountable when its `listConnectors()` summary carries a\n// `mountPath`. The `mount*` helpers below project that subset for the legacy\n// `mount_*` tool surface.\n\n/**\n * A connector summary that carries a projected filesystem path. Unlike the raw\n * `listConnectors()` summary, `mountPath` is non-optional here — `listMountable()`\n * runtime-filters to exactly those entries before narrowing to this type.\n */\ntype MountableConnector = ReturnType<ConnectorManager[\"listConnectors\"]>[number] & {\n mountPath: string;\n};\n\n/** Return the mountable (filesystem-face) connectors from a manager. */\nfunction listMountable(manager: ConnectorManager): MountableConnector[] {\n return manager\n .listConnectors()\n .filter((c): c is MountableConnector => typeof c.mountPath === \"string\");\n}\n\n/**\n * A mountable connector as reported to the agent, with an optional `reason`.\n *\n * A fleet-managed mount whose path is gone reports `status: \"error\"` plus a\n * `reason`, even though the connector handle still reads `connected`. One whose\n * probe timed out keeps its cached status and gains a `reason` saying it is\n * unverified: a slow cloud mount is not reported dead.\n */\ntype MountView = MountableConnector & { reason?: string };\n\n/** Overlay a live re-check on the cached connect-time status where one applies. */\nasync function withLiveness(\n manager: ConnectorManager,\n mount: MountableConnector,\n): Promise<MountView> {\n // Optional call: the tool tests' manager doubles omit the method.\n const liveness = await manager.checkMountLiveness?.(mount.id);\n if (!liveness || liveness.state === \"live\") return mount;\n if (liveness.state === \"dead\") return { ...mount, status: \"error\", reason: liveness.reason };\n return { ...mount, reason: liveness.reason };\n}\n\n/**\n * List all mountable (filesystem-face) connectors declared in `skaile.yaml`\n * with their current mount status.\n *\n * @param manager - Active `ConnectorManager` or `null` when not configured.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountList(manager: ConnectorManager | null): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n return okJson(await Promise.all(listMountable(manager).map((m) => withLiveness(manager, m))));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Sync a mountable connector — pull the latest content from its remote source.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountSync(\n manager: ConnectorManager | null,\n mountId: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const result = await manager.sync(mountId);\n return okJson(result);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Get the current status and metadata for a single mountable connector.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountStatus(\n manager: ConnectorManager | null,\n mountId: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const mount = listMountable(manager).find((v) => v.id === mountId);\n if (!mount) return err(`Mount not found: \"${mountId}\"`);\n return okJson(await withLiveness(manager, mount));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Read a file from within a mountable connector's projected directory by its\n * relative path.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param mountId - Connector ID declared in `skaile.yaml`.\n * @param filePath - Relative path within the projected mount directory.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function mountRead(\n manager: ConnectorManager | null,\n mountId: string,\n filePath: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const mount = listMountable(manager).find((v) => v.id === mountId);\n if (!mount) return err(`Mount not found: \"${mountId}\"`);\n const content = await readFile(join(mount.mountPath, filePath), \"utf-8\");\n return ok(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * List all connectors registered with the `ConnectorManager`.\n *\n * Returns `{ connected, failed }` — `connected` from `manager.listConnectors()`,\n * `failed` from `manager.listFailedConnectors()`. A connector that threw during\n * `connect()` never enters the active map, so it is absent from the first list\n * entirely; without the second one an agent driven through MCP or OMP has no\n * way to learn that a mount it is about to write into is dead. Returns an error\n * result when no manager is configured (i.e. `skaile.yaml` has no `connectors`\n * section).\n *\n * @param manager - Active `ConnectorManager` or `null` when not configured.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorList(manager: ConnectorManager | null): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n // Same payload as the Claude SDK tool: per-mount health and a notice when one is not ok.\n return okJson(await buildConnectorListPayload(manager));\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Read content from a connector at the given path.\n *\n * Delegates to `manager.read(id, path)`. Returns an error result when the\n * path yields `null` (not found) or the manager is absent.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param path - Resource path within the connector (connector-specific format).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorRead(\n manager: ConnectorManager | null,\n id: string,\n path: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const content = await manager.read(id, path);\n if (content === null) return err(`No content at path \"${path}\" in connector \"${id}\"`);\n return okJson(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Write string content to a connector at the given path.\n *\n * Delegates to `manager.write(id, path, { data: content })`.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param path - Destination path within the connector.\n * @param content - String payload to write.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorWrite(\n manager: ConnectorManager | null,\n id: string,\n path: string,\n content: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n await manager.write(id, path, { data: content });\n return ok(`Written to \"${path}\" in connector \"${id}\"`);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Search a connector's data using a query string.\n *\n * Delegates to `manager.search(id, query)` and returns the result set as JSON.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param query - Free-text or structured query (connector-specific format).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorSearch(\n manager: ConnectorManager | null,\n id: string,\n query: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const results = await manager.search(id, query);\n return okJson(results);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Execute a named operation on a connector.\n *\n * Delegates to `manager.executeOp(id, operation, args)`. Operations and\n * their argument shapes are connector-specific; use {@link connectorDescribe}\n * to discover what operations a connector supports.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n * @param operation - Operation name (from the connector's `RuntimeSkillDescriptor`).\n * @param args - Named arguments for the operation.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorExec(\n manager: ConnectorManager | null,\n id: string,\n operation: string,\n args: Record<string, unknown>,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const result = await manager.executeOp(id, operation, args);\n return ok(result);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Load the rendered skill body for a connector.\n *\n * Delegates to `manager.loadSkill(id)` and returns the skill content as\n * plain text. Useful when the agent needs the connector's operations and\n * usage instructions injected as prompt context.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorLoadSkill(\n manager: ConnectorManager | null,\n id: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const skill = manager.loadSkill(id);\n return ok(skill);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Describe a connector's capabilities via its `RuntimeSkillDescriptor`.\n *\n * Finds the matching skill descriptor from `manager.listSkills()` and returns\n * it as JSON. The descriptor includes the connector's operations, argument\n * shapes, and usage instructions.\n *\n * @param manager - Active `ConnectorManager` or `null`.\n * @param id - Connector ID declared in `skaile.yaml`.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function connectorDescribe(\n manager: ConnectorManager | null,\n id: string,\n): Promise<ToolResult> {\n if (!manager) return err(\"No connectors configured in skaile.yaml\");\n try {\n const skills = manager.listSkills();\n const descriptor = skills.find((s) => s.id === id);\n if (!descriptor) return err(`No skill descriptor for connector \"${id}\"`);\n return okJson(descriptor);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n"]}
@@ -1,8 +1,22 @@
1
+ import { buildCodexConfigDocument } from './chunk-6RTEUWXX.js';
1
2
  import { classifyClaudeSdkError } from './chunk-B4X2N7JQ.js';
2
- import { toMergedRegistry } from './chunk-4AKR4XPQ.js';
3
- import { createDriver, getProviderPreset, resolvePresetBaseUrl, expandPreset, resolveProbeUrl, buildCredentialHeaders } from './chunk-GQ5OYFVD.js';
3
+ import { toMergedRegistry } from './chunk-HG52NGAV.js';
4
+ import { createDriver, getProviderPreset, resolvePresetBaseUrl, expandPreset, resolveProbeUrl, buildCredentialHeaders } from './chunk-6Q7NKTDG.js';
4
5
  import { stripActivityLabel, TOOL_ACTIVITY_LABEL_PARAM, TOOL_ACTIVITY_LABEL_MAX_CHARS } from './chunk-D5WTOVLG.js';
5
6
 
7
+ // bridge/src/driver-model-check.ts
8
+ function checkDriverModel(driverId, input) {
9
+ if (driverId !== "codex") return void 0;
10
+ const build = buildCodexConfigDocument({
11
+ registry: input.registry,
12
+ ...input.model ? { modelRef: input.model, model: input.model } : {},
13
+ ...input.roles ? { roles: input.roles } : {}
14
+ });
15
+ if (!build.unaddressable) return void 0;
16
+ const { id, reason } = build.unaddressable;
17
+ return `AI provider '${id}' cannot be used with the codex driver: ${reason}. Pick a model of another provider.`;
18
+ }
19
+
6
20
  // bridge/src/normalizer.ts
7
21
  function resultUsageFields(event) {
8
22
  return {
@@ -640,6 +654,6 @@ async function validateApiKey(provider, key, options = {}) {
640
654
  }
641
655
  }
642
656
 
643
- export { BridgeRuntime, EventNormalizer, createRuntime, detectFileChange, detectFileChanges, labelToolCall, summarizeToolCall, summarizeToolResult, validateApiKey };
644
- //# sourceMappingURL=chunk-PQF5QHVS.js.map
645
- //# sourceMappingURL=chunk-PQF5QHVS.js.map
657
+ export { BridgeRuntime, EventNormalizer, checkDriverModel, createRuntime, detectFileChange, detectFileChanges, labelToolCall, summarizeToolCall, summarizeToolResult, validateApiKey };
658
+ //# sourceMappingURL=chunk-TKI7YDWE.js.map
659
+ //# sourceMappingURL=chunk-TKI7YDWE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../bridge/src/driver-model-check.ts","../bridge/src/normalizer.ts","../bridge/src/runtime.ts","../bridge/src/validation.ts"],"names":[],"mappings":";;;;;;;AAyBO,SAAS,gBAAA,CACd,UACA,KAAA,EACoB;AACpB,EAAA,IAAI,QAAA,KAAa,SAAS,OAAO,MAAA;AACjC,EAAA,MAAM,QAAQ,wBAAA,CAAyB;AAAA,IACrC,UAAU,KAAA,CAAM,QAAA;AAAA,IAChB,GAAI,KAAA,CAAM,KAAA,GAAQ,EAAE,QAAA,EAAU,KAAA,C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,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,yCAAA,EAA0C;AAAA,IACvE;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAA,EAAG;AAAA,EAC3D,SAAS,GAAA,EAAU;AACjB,IAAA,IAAI,GAAA,CAAI,SAAS,YAAA,EAAc,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,wBAAA,EAAyB;AACnF,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,CAAI,WAAW,eAAA,EAAgB;AAAA,EAC5D;AACF","file":"chunk-TKI7YDWE.js","sourcesContent":["/**\n * Pre-flight model check: would the driver refuse the selected model before it starts a turn?\n *\n * `skaile run --dry-run` uses it so a setup check learns about a refusal that a real run would\n * print. Only the codex driver refuses a selection up front (it cannot address every AI\n * provider surface); every other driver answers `undefined`.\n */\nimport type {\n AIProviderRegistry,\n MergedAIProviderRegistry,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { buildCodexConfigDocument } from \"./codex/config-toml.js\";\n\n/** What {@link checkDriverModel} reads. */\nexport interface DriverModelCheckInput {\n registry?: AIProviderRegistry | MergedAIProviderRegistry;\n /** The model selector: `<providerId>/<modelId>`, a bare id or `@role`. */\n model?: string;\n roles?: Record<string, string>;\n}\n\n/**\n * The refusal message the driver prints for this model, or `undefined` when it takes it.\n * The text matches the one the driver throws at start.\n */\nexport function checkDriverModel(\n driverId: string,\n input: DriverModelCheckInput,\n): string | undefined {\n if (driverId !== \"codex\") return undefined;\n const build = buildCodexConfigDocument({\n registry: input.registry,\n ...(input.model ? { modelRef: input.model, model: input.model } : {}),\n ...(input.roles ? { roles: input.roles } : {}),\n });\n if (!build.unaddressable) return undefined;\n const { id, reason } = build.unaddressable;\n return `AI provider '${id}' cannot be used with the codex driver: ${reason}. Pick a model of another provider.`;\n}\n","/**\n * EventNormalizer — converts bridge-level AgentEvent (raw driver events) to\n * skaile-agent-types AgentEvent (normalized, human-readable events).\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call reset() between sessions.\n */\n\nimport {\n type AgentEvent as NormalizedEvent,\n type NativeApprovalDescription,\n stripActivityLabel,\n TOOL_ACTIVITY_LABEL_MAX_CHARS,\n TOOL_ACTIVITY_LABEL_PARAM,\n} from \"@skaile/workspaces/types\";\nimport { classifyClaudeSdkError } from \"./error-classifier.js\";\nimport type { AgentMessage, AgentEvent as BridgeEvent, ContentBlock } from \"./types.js\";\n\n/**\n * The optional usage keys a `result` event carries, in the shape both\n * `finished` and a result-sourced `error` emit them. Absent keys stay absent.\n */\nfunction resultUsageFields(\n event: Pick<\n Extract<BridgeEvent, { type: \"result\" | \"error\" }>,\n \"tokens\" | \"modelUsage\" | \"contextTokens\" | \"contextWindow\"\n >,\n) {\n return {\n ...(event.tokens ? { tokens: event.tokens } : {}),\n ...(event.modelUsage ? { modelUsage: event.modelUsage } : {}),\n ...(typeof event.contextTokens === \"number\" ? { contextTokens: event.contextTokens } : {}),\n ...(typeof event.contextWindow === \"number\" ? { contextWindow: event.contextWindow } : {}),\n };\n}\n\n/**\n * The tool a driver uses to park a turn on a human answer. Both branches that\n * recognise it must use this constant: `message_start` turns it into a\n * `question`, and `tool_call` must then stay silent about it.\n */\nconst QUESTION_TOOL = \"AskUserQuestion\";\n\nconst MAX_ANNOUNCED_TOOL_USES = 64;\n\n/**\n * Bridge `tool_call` inputs are loosely typed: Codex MCP arguments may arrive\n * as a JSON string, and the echo driver passes a bare path.\n */\nfunction toolInputRecord(input: unknown): Record<string, unknown> {\n let value = input;\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch {\n return { input };\n }\n }\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n return value === undefined ? {} : { input };\n}\n\n/**\n * Converts raw bridge-level {@link BridgeEvent} payloads into normalized\n * `@skaile/workspaces/types` `AgentEvent` payloads consumed by the runner and transport.\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call {@link EventNormalizer.reset} between sessions to clear accumulated state.\n *\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport class EventNormalizer {\n private activeSubagents = new Map<string, string>();\n private devServerStartingEmitted = false;\n private devServerReadyEmitted = false;\n /** True when message_update deltas have been emitted for the current message. */\n private hasStreamedText = false;\n /**\n * True once a `_thinkingDelta` run has been reported as `status: thinking`;\n * cleared by the next text delta or assistant message, so a run reports once.\n */\n private thinkingAnnounced = false;\n /**\n * tool_use blocks `message_start` already reported, awaiting the driver's\n * matching bridge `tool_call` — which must then not report the call again.\n */\n private announcedToolUses: Array<{ id?: string; name: string }> = [];\n\n /**\n * Convert a single bridge event into zero or more normalized events.\n * One bridge event can produce multiple normalized events (e.g., a message_start\n * with text + tool_use blocks produces both text and tool_call events).\n */\n normalize(event: BridgeEvent): NormalizedEvent[] {\n switch (event.type) {\n case \"message_start\":\n return this.handleMessageStart(event.message);\n\n case \"message_update\":\n return this.handleMessageUpdate(event);\n\n case \"message_end\":\n return [];\n\n case \"message_retract\":\n // The replay streams its reply afresh, so its deltas (or, failing\n // those, its message_start text) must count as a new message.\n this.hasStreamedText = false;\n return event.text ? [{ type: \"text_retract\", content: event.text }] : [];\n\n case \"turn_end\":\n return this.handleTurnEnd(event.toolResults);\n\n case \"result\":\n return this.handleResult(event);\n\n case \"error\":\n this.announcedToolUses = [];\n return [\n {\n type: \"error\",\n message: event.error,\n fatal: event.fatal ?? true,\n category: event.detail?.category,\n ...(event.detail?.hint ? { hint: event.detail.hint } : {}),\n ...resultUsageFields(event),\n ...(event.retrying === true\n ? { retrying: true, ...(event.retryReason ? { retryReason: event.retryReason } : {}) }\n : {}),\n ...(event.selfStarted === true ? { selfStarted: true as const } : {}),\n },\n ];\n\n case \"background_task_started\":\n return [{ type: \"background_task_started\", taskId: event.taskId }];\n\n case \"self_turn_started\":\n return [{ type: \"self_turn_started\", taskIds: [...event.taskIds] }];\n\n case \"tool_call\": {\n // The question tool parks the turn on the user's answer, so reporting\n // work here would undo the idle its `question` event just set, and\n // nothing follows to correct it while the user reads the prompt.\n const toolName = event.name ?? event.tool?.name;\n if (toolName === QUESTION_TOOL) return [];\n // A driver that also sent the call as a `message_start` tool_use block\n // (Claude) was already reported there; the rest only ever send this.\n if (!toolName || this.consumeAnnouncedToolUse(toolName, event.toolCallId)) {\n return [{ type: \"status\", phase: \"working\" }];\n }\n return this.handleToolUse(\n {\n type: \"tool_use\",\n id: typeof event.toolCallId === \"string\" ? event.toolCallId : undefined,\n name: toolName,\n input: toolInputRecord(event.input),\n },\n typeof event.parentToolUseId === \"string\" ? event.parentToolUseId : undefined,\n );\n }\n\n case \"tool_execution_end\":\n return [];\n\n case \"agent_end\":\n this.announcedToolUses = [];\n return [{ type: \"status\", phase: \"idle\" }];\n\n case \"commands_available\":\n // Pass through to transport — the gateway caches this event\n return [event as unknown as NormalizedEvent];\n\n case \"session_info\":\n // Pass through to transport — the forge layer stores the OMP session ID\n return [event as unknown as NormalizedEvent];\n\n case \"ui_render\":\n case \"ui_render_update\":\n case \"ui_clear\":\n // Pass through verbatim — drivers that implement the Agent UI Protocol emit these directly\n return [event as unknown as NormalizedEvent];\n\n default:\n return [];\n }\n }\n\n /** Clear all stateful tracking between sessions. */\n reset(): void {\n this.activeSubagents.clear();\n this.devServerStartingEmitted = false;\n this.devServerReadyEmitted = false;\n this.hasStreamedText = false;\n this.thinkingAnnounced = false;\n this.announcedToolUses = [];\n }\n\n private consumeAnnouncedToolUse(name: string, id: unknown): boolean {\n const callId = typeof id === \"string\" ? id : undefined;\n const index = this.announcedToolUses.findIndex(\n (entry) => entry.name === name && (!callId || !entry.id || entry.id === callId),\n );\n if (index === -1) return false;\n this.announcedToolUses.splice(index, 1);\n return true;\n }\n\n // ---------------------------------------------------------------------------\n // message_start → text, tool_call, question, subagent\n // ---------------------------------------------------------------------------\n\n private handleMessageStart(message: AgentMessage): NormalizedEvent[] {\n // Only process assistant messages. Drivers (e.g. omp) may echo the user's\n // message as a message_start with role:\"user\" before streaming the response.\n // Emitting a text event for that echo would prepend the user's input to the\n // assistant bubble on the frontend.\n if (message.role !== \"assistant\") return [];\n\n // A subagent's message is not the main reply: its text belongs to the\n // subagent's own result, and it must not reset the main stream's state.\n const parentToolUseId = message.parentToolUseId;\n const events: NormalizedEvent[] = [];\n const blocks = this.getContentBlocks(message);\n\n for (const block of blocks) {\n if (block.type === \"text\" && block.text) {\n if (parentToolUseId) continue;\n // Skip full text if we already streamed it via message_update deltas\n if (!this.hasStreamedText) {\n events.push({ type: \"text\", content: block.text });\n }\n } else if (block.type === \"tool_use\" && block.name) {\n if (block.name !== QUESTION_TOOL) {\n this.announcedToolUses.push({ id: block.id, name: block.name });\n // Bounded in case a driver never echoes a block as a tool_call.\n if (this.announcedToolUses.length > MAX_ANNOUNCED_TOOL_USES) {\n this.announcedToolUses.shift();\n }\n }\n events.push(...this.handleToolUse(block, parentToolUseId));\n }\n }\n\n if (!parentToolUseId) this.hasStreamedText = false;\n if (!parentToolUseId) this.thinkingAnnounced = false;\n return events;\n }\n\n private handleToolUse(block: ContentBlock, parentToolUseId?: string): NormalizedEvent[] {\n const name = block.name!;\n const input = (block.input ?? {}) as Record<string, unknown>;\n\n if (name === QUESTION_TOOL) {\n return this.handleAskUserQuestion(input);\n }\n if (name === \"Agent\") {\n return this.handleAgentToolUse(block, input);\n }\n return this.handleGenericToolUse(name, input, parentToolUseId);\n }\n\n private handleAskUserQuestion(input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const candidate = input.approval as Partial<NativeApprovalDescription> | undefined;\n const approval =\n candidate &&\n [\"command\", \"file\", \"permissions\", \"mcp\"].includes(candidate.kind ?? \"\") &&\n Array.isArray(candidate.details) &&\n candidate.details.length > 0 &&\n candidate.details.length <= 64 &&\n candidate.details.every((detail) => typeof detail === \"string\" && detail.length <= 8192) &&\n candidate.details.reduce((total, detail) => total + detail.length, 0) <= 65536\n ? (candidate as NativeApprovalDescription)\n : undefined;\n if (Object.hasOwn(input, \"approval\") && !approval) return [];\n // Claude SDK sends { questions: [{ question, header, options: [{ label, description }] }] }\n // Legacy/simple format sends { question: string, options?: string[] }\n const questions = input.questions;\n if (Array.isArray(questions)) {\n for (const q of questions) {\n const qObj = q as Record<string, unknown>;\n const question = String(qObj.question ?? \"\");\n const rawOpts = qObj.options;\n const options = Array.isArray(rawOpts)\n ? rawOpts.map((o: any) => (typeof o === \"string\" ? o : String(o.label ?? o)))\n : undefined;\n events.push({\n type: \"question\",\n question,\n options,\n ...(typeof input.requestId === \"string\" ? { requestId: input.requestId } : {}),\n ...(approval ? { approval } : {}),\n });\n }\n } else {\n const question = String(input.question ?? input.text ?? \"\");\n const rawOptions = input.options;\n const options = Array.isArray(rawOptions) ? rawOptions.map(String) : undefined;\n events.push({\n type: \"question\",\n question,\n options,\n ...(typeof input.requestId === \"string\" ? { requestId: input.requestId } : {}),\n ...(approval ? { approval } : {}),\n });\n }\n return events;\n }\n\n private handleAgentToolUse(\n block: ContentBlock,\n input: Record<string, unknown>,\n ): NormalizedEvent[] {\n const agentName = String(input.subagent_type ?? input.description ?? \"unknown\");\n const description = String(input.description ?? input.prompt ?? \"\").slice(0, 200);\n if (block.id) {\n this.activeSubagents.set(block.id, agentName);\n }\n return [\n { type: \"subagent\", name: agentName, status: \"started\", description },\n { type: \"status\", phase: \"working\" },\n ];\n }\n\n private handleGenericToolUse(\n name: string,\n input: Record<string, unknown>,\n parentToolUseId?: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const label = labelToolCall(name, input);\n events.push({\n type: \"tool_call\",\n tool: name,\n input,\n // Summarize without the label: it would eat the default branch's\n // 100-char argument budget and push the real args out.\n summary: summarizeToolCall(name, stripActivityLabel(input)),\n ...(label ? { label } : {}),\n ...(parentToolUseId ? { parentToolUseId } : {}),\n });\n events.push({ type: \"status\", phase: \"working\" });\n\n if (name === \"Bash\" && typeof input.command === \"string\") {\n const devEvent = this.detectDevServerStarting(input.command);\n if (devEvent) events.push(devEvent);\n }\n\n return events;\n }\n\n // ---------------------------------------------------------------------------\n // message_update → streaming text\n // ---------------------------------------------------------------------------\n\n private handleMessageUpdate(event: BridgeEvent): NormalizedEvent[] {\n // Bridge deltas carry no subagent tag: a driver must drop a subagent's\n // partials itself (claude-sdk does in handleStreamEvent), or they read as main text.\n const delta = (event as any)._textDelta as string | undefined;\n if (delta) {\n this.hasStreamedText = true;\n this.thinkingAnnounced = false;\n return [{ type: \"text\", content: delta }];\n }\n // The protocol has no thinking-content event, so reasoning surfaces as the\n // existing `thinking` phase, once per run. The text is never forwarded as\n // `text`; a driver keeps it out of `_textDelta`.\n const thinking: unknown = \"_thinkingDelta\" in event ? event._thinkingDelta : undefined;\n if (typeof thinking === \"string\" && thinking && !this.thinkingAnnounced) {\n this.thinkingAnnounced = true;\n return [{ type: \"status\", phase: \"thinking\" }];\n }\n return [];\n }\n\n // ---------------------------------------------------------------------------\n // turn_end → tool_result, subagent finished, file_changed, dev_server\n // ---------------------------------------------------------------------------\n\n private handleTurnEnd(toolResults?: AgentMessage[]): NormalizedEvent[] {\n if (!toolResults?.length) return [];\n\n const events: NormalizedEvent[] = [];\n\n for (const result of toolResults) {\n const toolName = result.toolName ?? \"unknown\";\n const outputData = result.data ?? result.content;\n const output = typeof outputData === \"string\" ? outputData : JSON.stringify(outputData);\n\n // Check if this is a subagent result\n if (toolName === \"Agent\" || this.isSubagentResult(result)) {\n events.push(...this.handleSubagentResult(result, output));\n } else {\n events.push(...this.handleToolResult(toolName, outputData, output, result.parentToolUseId));\n }\n }\n\n return events;\n }\n\n private handleSubagentResult(result: AgentMessage, output: string): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const agentName = this.resolveSubagentName(result);\n const description = output.slice(0, 200);\n events.push({ type: \"subagent\", name: agentName, status: \"finished\", description });\n\n if (agentName === \"dev-server\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private handleToolResult(\n toolName: string,\n outputData: unknown,\n output: string,\n parentToolUseId?: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_result\",\n tool: toolName,\n output: outputData,\n summary: summarizeToolResult(toolName, outputData),\n ...(parentToolUseId ? { parentToolUseId } : {}),\n });\n\n // Detect file changes from Write/Edit results\n const fileEvents = detectFileChanges(toolName, outputData);\n if (fileEvents.length > 0) events.push(...fileEvents);\n\n // Detect dev server from Bash output\n if (toolName === \"Bash\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private isSubagentResult(result: AgentMessage): boolean {\n // Check if the tool result's id maps to a tracked subagent\n if (result.toolName && this.activeSubagents.has(result.toolName)) return true;\n return false;\n }\n\n private resolveSubagentName(result: AgentMessage): string {\n // toolName on bridge AgentMessage is resolved from toolIdToName in the driver\n const name = result.toolName ? this.activeSubagents.get(result.toolName) : undefined;\n if (name) {\n this.activeSubagents.delete(result.toolName!);\n return name;\n }\n return result.toolName ?? \"unknown\";\n }\n\n // ---------------------------------------------------------------------------\n // result → finished or error\n // ---------------------------------------------------------------------------\n\n private handleResult(event: BridgeEvent & { type: \"result\" }): NormalizedEvent[] {\n const usage = resultUsageFields(event);\n if (event.subtype === \"success\") {\n return [\n {\n type: \"finished\",\n summary: event.summary ?? \"Task completed\",\n costUsd: event.costUsd ?? 0,\n ...usage,\n ...(event.selfStarted === true ? { selfStarted: true as const } : {}),\n },\n ];\n }\n\n const errors = event.errors ?? [];\n // Run the same classifier the claude-sdk driver uses on its `error`\n // event so the result-error path also surfaces a category and hint\n // (drivers other than claude-sdk emit `result` without a paired\n // `error`, so this is the only place they get classified).\n const detail = classifyClaudeSdkError({ errors, subtype: event.subtype });\n // The turn billed even though it failed: carry its usage so a ledger\n // that only writes on `finished` can write here too. Unlike the finished\n // branch, no `costUsd: 0` fallback — an absent figure stays absent.\n return [\n {\n type: \"error\",\n message: `Agent stopped: ${event.subtype}${errors.length ? ` — ${errors.join(\"; \")}` : \"\"}`,\n fatal: event.subtype === \"error_during_execution\",\n category: detail.category,\n ...(detail.hint ? { hint: detail.hint } : {}),\n ...(typeof event.costUsd === \"number\" ? { costUsd: event.costUsd } : {}),\n ...usage,\n ...(event.selfStarted === true ? { selfStarted: true as const } : {}),\n },\n ];\n }\n\n // ---------------------------------------------------------------------------\n // Dev server detection\n // ---------------------------------------------------------------------------\n\n private detectDevServerStarting(command: string): NormalizedEvent | null {\n if (this.devServerStartingEmitted) return null;\n const cmd = command.toLowerCase();\n const isFrontendStart =\n (cmd.includes(\"pnpm run dev\") || cmd.includes(\"pnpm dev\") || cmd.includes(\"vite\")) &&\n (cmd.includes(\"frontend\") || cmd.includes(\"dev:preview\"));\n if (isFrontendStart) {\n this.devServerStartingEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"starting\" };\n }\n return null;\n }\n\n private detectDevServerReady(text: string): NormalizedEvent | null {\n if (this.devServerReadyEmitted) return null;\n\n const explicitMatch = text.match(/DEVSERVER_READY:(https?:\\/\\/[^\\s\"\\\\]+)/);\n if (explicitMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: explicitMatch[1]!, status: \"ready\" };\n }\n\n const viteMatch = text.match(/Local:\\s+(https?:\\/\\/localhost:\\d+)/);\n if (viteMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: viteMatch[1]!, status: \"ready\" };\n }\n\n if (text.includes(\"FRONTEND_READY\")) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"ready\" };\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private getContentBlocks(message: AgentMessage): ContentBlock[] {\n if (Array.isArray(message.content)) return message.content;\n if (typeof message.content === \"string\" && message.content) {\n return [{ type: \"text\", text: message.content }];\n }\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helper functions (exported for reuse)\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a human-readable one-line summary of a tool call for the activity log.\n *\n * Returns a string like `$ git status` for Bash, `Read src/index.ts` for Read, etc.\n * Falls back to `ToolName({...input...})` for unrecognised tools.\n *\n * @param tool - Tool name (e.g. `\"Bash\"`, `\"Write\"`, `\"Grep\"`).\n * @param input - Tool input record passed to the call.\n * @returns A short display string suitable for the activity feed.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolCall(tool: string, input: Record<string, unknown>): string {\n // A driver that sent a bare value instead of named args has it under `input`.\n const arg = (key: string) => String(input[key] ?? input.input);\n switch (tool) {\n case \"Bash\":\n return `$ ${String(input.command ?? input.input ?? \"\").slice(0, 200)}`;\n case \"Write\":\n return `Create ${arg(\"file_path\")}`;\n case \"Edit\":\n return `Edit ${arg(\"file_path\")}`;\n case \"Read\":\n return `Read ${arg(\"file_path\")}`;\n case \"Glob\":\n return `Find ${arg(\"pattern\")}`;\n case \"Grep\":\n return `Search for ${arg(\"pattern\")}`;\n case \"ApplyPatch\": {\n // Paths only: stringifying the input would serialize every full diff.\n const changes = Array.isArray(input.changes) ? input.changes : [];\n const paths = changes\n .map((change) => (change as { path?: unknown } | null)?.path)\n .filter((path): path is string => typeof path === \"string\");\n return `Edit ${paths.join(\", \").slice(0, 200) || \"files\"}`;\n }\n default:\n return `${tool}(${JSON.stringify(input).slice(0, 100)})`;\n }\n}\n\n/**\n * Produce the plain-language label shown to non-technical users while a tool\n * call runs: the agent's own `activity_label`, Bash's `description`, else a\n * derived phrase for Claude Code built-ins. `undefined` for any other tool —\n * the UI then falls back to a generic \"working\" line rather than raw input.\n *\n * @param tool - Tool name as the model called it.\n * @param input - Tool input record, still carrying `activity_label`.\n * @returns A trimmed label capped at `TOOL_ACTIVITY_LABEL_MAX_CHARS`, or `undefined`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function labelToolCall(tool: string, input: Record<string, unknown>): string | undefined {\n const authored =\n nonEmpty(input[TOOL_ACTIVITY_LABEL_PARAM]) ??\n (tool === \"Bash\" ? nonEmpty(input.description) : undefined);\n const label = authored ?? builtinToolLabel(tool, input);\n if (!label) return undefined;\n return label.length > TOOL_ACTIVITY_LABEL_MAX_CHARS\n ? `${label.slice(0, TOOL_ACTIVITY_LABEL_MAX_CHARS - 1).trimEnd()}…`\n : label;\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.replace(/\\s+/g, \" \").trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction builtinToolLabel(tool: string, input: Record<string, unknown>): string | undefined {\n switch (tool) {\n case \"Read\":\n return withTarget(\"Reading\", baseName(input.file_path));\n case \"Edit\":\n case \"MultiEdit\":\n case \"NotebookEdit\":\n return withTarget(\"Editing\", baseName(input.file_path ?? input.notebook_path));\n case \"Write\":\n return withTarget(\"Creating\", baseName(input.file_path));\n case \"Grep\":\n case \"Glob\":\n return \"Searching files\";\n case \"WebSearch\":\n return \"Searching the web\";\n case \"WebFetch\":\n return withTarget(\"Fetching\", hostOf(input.url), \"a web page\");\n case \"TodoWrite\":\n return \"Updating the task list\";\n case \"ApplyPatch\":\n return \"Editing files\";\n default:\n return undefined;\n }\n}\n\nfunction withTarget(verb: string, target: string | undefined, fallback = \"a file\"): string {\n return `${verb} ${target ?? fallback}`;\n}\n\nfunction baseName(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n return value.split(/[\\\\/]/).filter(Boolean).pop();\n}\n\nfunction hostOf(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n try {\n return new URL(value).host || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Extract plain text from an Anthropic content-block array (e.g. tool results returned by Claude SDK). */\nfunction extractContentBlockText(blocks: unknown[]): string | null {\n const textBlocks = blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n typeof b === \"object\" &&\n b !== null &&\n (b as Record<string, unknown>).type === \"text\" &&\n typeof (b as Record<string, unknown>).text === \"string\",\n );\n if (textBlocks.length === 0) return null;\n return textBlocks.map((b) => b.text).join(\"\\n\");\n}\n\n/**\n * Produce a human-readable one-line summary of a tool result for the activity log.\n *\n * Handles Bash stdout/stderr, Write/Edit file paths, ApplyPatch change counts, and\n * Anthropic content-block arrays. Falls back to `JSON.stringify` for unknown shapes.\n *\n * @param tool - Tool name.\n * @param result - Raw tool result payload.\n * @returns A short display string, truncated to 200 characters.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolResult(tool: string, result: unknown): string {\n // Handle Anthropic content-block arrays: [{ type: \"text\", text: \"...\" }, ...]\n if (Array.isArray(result)) {\n const text = extractContentBlockText(result);\n return (text ?? JSON.stringify(result)).slice(0, 200);\n }\n if (typeof result !== \"object\" || !result) {\n return String(result).slice(0, 200);\n }\n const r = result as Record<string, unknown>;\n switch (tool) {\n case \"Bash\": {\n const stderr = String(r.stderr ?? \"\").trim();\n if (stderr) return `stderr: ${stderr.slice(0, 200)}`;\n return (\n String(r.stdout ?? \"\")\n .trim()\n .slice(0, 200) || \"(no output)\"\n );\n }\n case \"Write\":\n return `${String(r.type)}: ${String(r.filePath)}`;\n case \"Edit\":\n return `Edited ${String(r.filePath)}`;\n case \"ApplyPatch\":\n return `${Array.isArray(r.changes) ? r.changes.length : 0} file changes`;\n default:\n return JSON.stringify(result).slice(0, 200);\n }\n}\n\n/**\n * Detect file-change events from a tool result, returning zero or more `file_changed` events.\n *\n * Handles `Write` (single create/edit), `Edit` (single edit), and `ApplyPatch` (multi-file\n * patch with per-change `kind` classification). Returns an empty array for all other tools.\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns Array of `file_changed` normalized events.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChanges(toolName: string, result: unknown): NormalizedEvent[] {\n if (typeof result !== \"object\" || !result) return [];\n const r = result as Record<string, unknown>;\n\n if (toolName === \"Write\" && r.filePath) {\n return [\n {\n type: \"file_changed\",\n path: String(r.filePath),\n action: r.type === \"create\" ? \"create\" : \"edit\",\n },\n ];\n }\n if (toolName === \"Edit\" && r.filePath) {\n return [{ type: \"file_changed\", path: String(r.filePath), action: \"edit\" }];\n }\n if (toolName === \"ApplyPatch\" && Array.isArray(r.changes)) {\n return r.changes\n .filter(\n (change): change is { path: string; kind: \"add\" | \"delete\" | \"update\" } =>\n typeof change === \"object\" &&\n change !== null &&\n typeof (change as Record<string, unknown>).path === \"string\" &&\n typeof (change as Record<string, unknown>).kind === \"string\",\n )\n .map((change) => ({\n type: \"file_changed\" as const,\n path: change.path,\n action: change.kind === \"add\" ? \"create\" : change.kind === \"delete\" ? \"delete\" : \"edit\",\n }));\n }\n\n return [];\n}\n\n/**\n * Backward-compatible single-event helper; returns the first `file_changed` event or `null`.\n *\n * Prefer {@link detectFileChanges} for multi-file patches (e.g. `ApplyPatch`).\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns First detected `file_changed` event, or `null`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChange(toolName: string, result: unknown): NormalizedEvent | null {\n return detectFileChanges(toolName, result)[0] ?? null;\n}\n","/**\n * BridgeRuntime — implements IAgentRuntime from @skaile/workspaces/types by wrapping\n * an AgentDriver + EventNormalizer. This is the primary integration point for\n * consumers that want normalized events from any driver.\n */\n\nimport type {\n AgentEvent,\n AgentPromptInput,\n AgentReconfigureOptions,\n AgentRuntimeConfig,\n IAgentRuntime,\n} from \"@skaile/workspaces/types\";\n\nimport { EventNormalizer } from \"./normalizer.js\";\nimport { toMergedRegistry } from \"./provider-registry-derive.js\";\nimport { createDriver } from \"./registry.js\";\nimport type { AgentConfig, AgentDriver } from \"./types.js\";\n\n/**\n * Implements `IAgentRuntime` from `@skaile/workspaces/types` by wrapping an {@link AgentDriver}\n * and an {@link EventNormalizer}.\n *\n * This is the primary integration point for consumers that want normalized `AgentEvent`\n * payloads from any driver without managing the driver lifecycle directly. Create via\n * {@link createRuntime} to avoid coupling to `BridgeRuntime` directly.\n *\n * @docLink packages/bridge/api-reference#runtime\n */\nexport class BridgeRuntime implements IAgentRuntime {\n private driver: AgentDriver | null = null;\n private normalizer = new EventNormalizer();\n private handlers = new Set<(event: AgentEvent) => void>();\n private boundEventHandler: ((event: any) => void) | null = null;\n private driverId: string;\n\n constructor(driverId: string = \"claude-sdk\") {\n this.driverId = driverId;\n }\n\n async start(config: AgentRuntimeConfig): Promise<void> {\n // Dispose previous driver if any\n if (this.driver) {\n await this.dispose();\n }\n\n this.normalizer.reset();\n\n const bridgeConfig: AgentConfig = {\n cwd: config.cwd,\n model: config.model,\n systemPrompt: config.systemPrompt,\n env: config.env,\n agentDir: config.agentDir,\n sessionId: config.sessionId,\n resumeSessionId: config.resumeSessionId,\n maxTurns: config.maxTurns,\n ...(config.registry ? { registry: toMergedRegistry(config.registry, \"runtime\") } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n };\n\n this.driver = await createDriver(this.driverId, bridgeConfig);\n\n // Wire bridge events through normalizer to handlers\n this.boundEventHandler = (bridgeEvent: any) => {\n const normalized = this.normalizer.normalize(bridgeEvent);\n for (const event of normalized) {\n for (const handler of this.handlers) {\n handler(event);\n }\n }\n };\n this.driver.on(\"agent-event\", this.boundEventHandler);\n\n await this.driver.start();\n }\n\n async configure(_config: AgentReconfigureOptions): Promise<void> {\n // Runtime reconfiguration for BridgeRuntime is a no-op for now.\n // Future: reconnect connectors, reload ai-assets, update subagents.\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.prompt(message);\n }\n\n async promptInput(input: AgentPromptInput): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.promptInput(input);\n }\n\n async reply(answer: string, question?: string, requestId?: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n // Mirror serve.ts handleReply: an answer must resume the paused turn. Falling through to\n // prompt() would deny the question as superseded and drop the structured answer.\n if (\n this.driver?.hasPendingQuestion() &&\n this.driver.answerQuestion(answer, question, requestId)\n )\n return;\n if (this.driver?.acceptsReplyAsPrompt) await this.prompt(answer);\n }\n\n async abort(): Promise<void> {\n if (this.driver) {\n await this.driver.abort();\n }\n }\n\n async dispose(): Promise<void> {\n if (this.driver) {\n if (this.boundEventHandler) {\n this.driver.off(\"agent-event\", this.boundEventHandler);\n this.boundEventHandler = null;\n }\n this.driver.kill();\n this.driver = null;\n }\n this.normalizer.reset();\n }\n\n onEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.add(handler);\n }\n\n offEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.delete(handler);\n }\n\n get isRunning(): boolean {\n return this.driver?.isRunning ?? false;\n }\n}\n\n/**\n * Factory function to create a {@link BridgeRuntime} with the specified driver.\n *\n * @param driverId - Registered driver id (default: `\"claude-sdk\"`).\n * @returns A new `IAgentRuntime` wrapping the selected driver with event normalization.\n * @docLink packages/bridge/api-reference#runtime\n */\nexport function createRuntime(driverId: string = \"claude-sdk\"): IAgentRuntime {\n return new BridgeRuntime(driverId);\n}\n","/** Provider API key validation — hits each provider's models endpoint to verify the key works. */\n\nimport {\n buildCredentialHeaders,\n expandPreset,\n getProviderPreset,\n resolvePresetBaseUrl,\n resolveProbeUrl,\n} from \"./provider-catalog.js\";\n\n/**\n * Result of an API key validation check performed by {@link validateApiKey}.\n *\n * @docLink packages/bridge/api-reference#validation\n */\nexport interface ValidationResult {\n /** `true` when the API key was accepted by the provider's models endpoint. */\n ok: boolean;\n /** Human-readable error description when `ok` is `false`. */\n error?: string;\n}\n\n/**\n * Validate an API key by sending a lightweight GET request to the provider's models endpoint.\n *\n * Returns `{ ok: true }` when the provider accepts the key (HTTP 2xx). Returns\n * `{ ok: false, error }` on 401/403 (invalid key), other HTTP errors, network failures,\n * or unsupported providers. Requests time out after 8 seconds.\n *\n * @param provider - Catalog preset id (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * @param key - API key to validate.\n * @param options - Optional base-URL / environment overrides; defaults to the\n * provider's own API, or its `base_url_env` value when one is set.\n * @returns Validation result with optional error description.\n * @docLink packages/bridge/api-reference#validation\n */\nexport async function validateApiKey(\n provider: string,\n key: string,\n options: { baseUrl?: string; env?: Record<string, string | undefined> } = {},\n): Promise<ValidationResult> {\n const preset = getProviderPreset(provider);\n if (!preset) return { ok: false, error: `Unknown provider: ${provider}` };\n\n // Validate against the same endpoint discovery/dispatch use: behind a gateway\n // the key is the gateway's, and the provider's public API would reject it.\n const baseUrl = resolvePresetBaseUrl(preset, {\n ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),\n env: options.env ?? process.env,\n });\n const entry = expandPreset(preset, baseUrl ? { baseUrl } : {});\n const url = resolveProbeUrl(entry);\n if (!url) return { ok: false, error: `Provider ${provider} exposes no models endpoint` };\n // Static non-secret headers (Anthropic's `anthropic-version`) plus the\n // credential carrier the preset's `auth_header` names.\n const headers = { ...entry.headers, ...buildCredentialHeaders(entry, key) };\n\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8000);\n\n const response = await fetch(url, {\n method: \"GET\",\n headers,\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (response.ok) return { ok: true };\n\n const status = response.status;\n if (status === 401 || status === 403) {\n return { ok: false, error: \"Invalid API key (authentication failed)\" };\n }\n return { ok: false, error: `API returned HTTP ${status}` };\n } catch (err: any) {\n if (err.name === \"AbortError\") return { ok: false, error: \"Request timed out (8s)\" };\n return { ok: false, error: err.message ?? \"Network error\" };\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getProviderPreset, registryCredentialEnv, providerCredentialEnvName, BUILTIN_DRIVER_CATALOG } from './chunk-GQ5OYFVD.js';
1
+ import { getProviderPreset, registryCredentialEnv, providerCredentialEnvName, BUILTIN_DRIVER_CATALOG } from './chunk-6Q7NKTDG.js';
2
2
  import { mergeRegistries, resolveEntryBaseUrl, normalizeEntryBaseUrl, registryEntries, isEntryEnabled, parseModelRef } from './chunk-MJHSLODD.js';
3
3
 
4
4
  // bridge/src/provider-materialize/env-drivers.ts
@@ -137,5 +137,5 @@ function continueRoleBinding(session) {
137
137
  }
138
138
 
139
139
  export { bindSingleProviderEntry, continueRoleBinding, credentialsForEveryProvider, entryBaseUrl, entryModelIds, entrySurface, harnessModelSelector, harnessProviderName, isStockCatalogEndpoint, registryModelEntries, resolveEnvDriverSession, resolveRegistryBinding, selectableEntries, versionedAnthropicBaseUrl };
140
- //# sourceMappingURL=chunk-O673TBWJ.js.map
141
- //# sourceMappingURL=chunk-O673TBWJ.js.map
140
+ //# sourceMappingURL=chunk-TXGVG7VH.js.map
141
+ //# sourceMappingURL=chunk-TXGVG7VH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/provider-materialize/env-drivers.ts"],"names":[],"mappings":";;;;AAyEO,SAAS,uBAAA,CACd,MAAA,EACA,UAAA,GAAiD,OAAA,CAAQ,GAAA,EACvC;AAClB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,MAAA,CAAO,QAAA,IAAY,eAAA,CAAgB,EAAE,CAAA;AAAA,IAC/C,WAAW,EAAE,GAAG,UAAA,EAAY,GAAG,OAAO,GAAA,EAAI;AAAA,IAC1C,GAAI,OAAO,QAAA,GAAW,EAAE,UAAU,MAAA,CAAO,QAAA,KAAa,EAAC;AAAA,IACvD,GAAI,OAAO,KAAA,GAAQ,EAAE,OAAO,MAAA,CAAO,KAAA,KAAU;AAAC,GAChD;AACF;AA2BO,SAAS,aAAa,KAAA,EAA0D;AACrF,EAAA,IAAI,KAAA,CAAM,OAAA,EAAS,OAAO,KAAA,CAAM,OAAA;AAChC,EAAA,OAAO,MAAM,MAAA,GAAS,iBAAA,CAAkB,KAAA,CAAM,MAAM,GAAG,OAAA,GAAU,MAAA;AACnE;AAcO,SAAS,aAA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":"chunk-O673TBWJ.js","sourcesContent":["/**\n * Registry adapter for the **env-shaped CLI drivers** — Gemini, Qwen, OpenCode,\n * Goose and Continue (§2.3).\n *\n * These harnesses take their endpoint from the environment rather than from a\n * config file, so the adapter's job is three things: resolve which registry\n * entry the session's model selector names, refuse at start when that entry\n * speaks a wire surface the harness cannot, and hand the driver the\n * provider-side model id it must put on the command line.\n *\n * Two pluralities meet here (`BUILTIN_DRIVER_CATALOG.providerPlurality`):\n *\n * - `single` — Gemini and Qwen address exactly one endpoint. The bound entry\n * supplies the credential *and* the base URL, and a surface mismatch is\n * fatal: a Gemini CLI pointed at an `openai-completions` endpoint cannot\n * work, and failing at start names the surface instead of leaving the user\n * with an opaque error mid-turn.\n * - `credentials-n` — OpenCode, Goose and Continue accept every enabled\n * entry's credential at once and select one active model. The credential\n * fan-out is `registryCredentialEnv`; the active model is this module's\n * `<provider>/<model>` binding.\n *\n * Writing the per-endpoint config files those three need for *custom*\n * endpoints (`opencode.json`, Goose `custom_providers/*.json`, Continue\n * `config.yaml`) is the file half, and is deliberately not here.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3\n */\n\nimport {\n type AIProviderLlmEntry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n mergeRegistries,\n normalizeEntryBaseUrl,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport type { ModelEntry } from \"../models.js\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport type { AgentConfig } from \"../types.js\";\nimport { providerCredentialEnvName, registryCredentialEnv } from \"./credential-env.js\";\n\n/**\n * Everything a CLI driver needs to know about this session's AI providers,\n * resolved once from its {@link AgentConfig}.\n */\nexport interface EnvDriverSession {\n /** The merged registry this session may address. Empty when none was configured. */\n registry: MergedAIProviderRegistry;\n /**\n * Environment `credential.ref` lookups resolve against — the process\n * environment widened with `config.env`, which is where the session\n * boundary delivered every resolved `SKAILE_AIP_<ID>_KEY`.\n */\n lookupEnv: Record<string, string | undefined>;\n /** Model selector: `<providerId>/<modelId>`, a bare id, or `@role`. */\n modelRef?: string;\n /** Roles table an `@role` selector resolves through. */\n roles?: Record<string, string>;\n}\n\n/**\n * Resolve the session's providers once, from its {@link AgentConfig}.\n *\n * `config.env` is folded into `lookupEnv` rather than kept apart: it is part\n * of the session's environment, not an extra, and a credential or\n * `*_BASE_URL` delivered there must be visible exactly as the child will see\n * it.\n */\nexport function resolveEnvDriverSession(\n config: AgentConfig,\n processEnv: Record<string, string | undefined> = process.env,\n): EnvDriverSession {\n return {\n registry: config.registry ?? mergeRegistries([]),\n lookupEnv: { ...processEnv, ...config.env },\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n };\n}\n\n/** One resolved endpoint + model — everything a driver needs to spawn. */\nexport interface RegistryModelBinding {\n /** Registry id of the selected entry. */\n providerId: string;\n /** The selected entry itself. */\n entry: AIProviderLlmEntry;\n /** Logical model id, after `@role` expansion and before `model_map`. */\n modelId?: string;\n /** Provider-side model id — what goes on the wire / command line. */\n providerModelId?: string;\n /** Wire protocol, from the entry or its preset. */\n surface?: AIProviderSurface;\n /** Resolved endpoint, from the entry, its transport params, or its preset. */\n baseUrl?: string;\n /**\n * The provider name the *harness* knows this endpoint by — a catalog preset\n * id for a stock endpoint, the registry id for anything custom. See\n * {@link harnessProviderName}.\n */\n harnessProviderId: string;\n /** Non-fatal notes from `parseModelRef` (dangling role, disabled provider). */\n warnings: string[];\n}\n\n/** The entry's wire surface: its own, else its preset's. */\nexport function entrySurface(entry: AIProviderLlmEntry): AIProviderSurface | undefined {\n if (entry.surface) return entry.surface;\n return entry.preset ? getProviderPreset(entry.preset)?.surface : undefined;\n}\n\n/**\n * The entry's endpoint: its literal or transport-derived URL, else its\n * preset's literal, in the canonical spelling for its surface\n * (`normalizeEntryBaseUrl`: an `anthropic-messages` endpoint is its host root,\n * so `https://api.anthropic.com/v1` reads as `https://api.anthropic.com`).\n * Transport templates that still carry `{param}` placeholders never come\n * back — `resolveEntryBaseUrl` withholds those, and a preset's template is not\n * a URL.\n *\n * Every adapter reads the endpoint here and only re-spells it for a client\n * that wants something else ({@link versionedAnthropicBaseUrl}).\n */\nexport function entryBaseUrl(entry: AIProviderLlmEntry): string | undefined {\n const resolved =\n resolveEntryBaseUrl(entry) ??\n (entry.preset ? getProviderPreset(entry.preset)?.base_url : undefined);\n return normalizeEntryBaseUrl(resolved, entrySurface(entry));\n}\n\n/**\n * An `anthropic-messages` endpoint spelled for a client that appends only\n * `/messages` — `@ai-sdk/anthropic` (OpenCode) and Continue — rather than\n * `/v1/messages` like the Claude CLI, the Anthropic SDK and Goose. `baseUrl`\n * must already be canonical ({@link entryBaseUrl}); every other surface passes\n * through unchanged.\n */\nexport function versionedAnthropicBaseUrl(\n baseUrl: string,\n surface: AIProviderSurface | undefined,\n): string {\n if (surface !== \"anthropic-messages\") return baseUrl;\n // Append to the path, not the string: a query or fragment stays at the end.\n try {\n const url = new URL(baseUrl);\n url.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/v1`;\n return url.toString();\n } catch {\n return `${baseUrl}/v1`;\n }\n}\n\n/**\n * True when a `credentials-n` harness already knows this endpoint under its\n * own catalog name — the entry names a preset and did not move it somewhere\n * else. Both sides are compared canonically, so `https://api.anthropic.com/v1`\n * is still the `anthropic` preset's endpoint.\n *\n * The one rule both halves of §2.3 read: it decides the name the env half\n * puts on the command line ({@link harnessProviderName}) *and* whether the\n * file half has to describe the endpoint at all. Reading it twice is what\n * keeps `-m <name>/<model>` and the generated provider file talking about the\n * same thing.\n */\nexport function isStockCatalogEndpoint(entry: AIProviderLlmEntry): boolean {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset) return false;\n return entryBaseUrl(entry) === normalizeEntryBaseUrl(preset.base_url, entrySurface(entry));\n}\n\n/**\n * The provider name to give a `credentials-n` harness (`-m <name>/<model>`,\n * `GOOSE_PROVIDER`).\n *\n * A stock catalog endpoint is named by its preset, because that is the name\n * OpenCode's models.dev list and Goose's built-in provider table already use —\n * `prod-claude: {preset: anthropic}` is still Anthropic to them. An entry with\n * an endpoint of its own is named by its registry id: no built-in table knows\n * it, so the id is what its generated provider file is keyed by (the file half\n * of §2.3).\n */\nexport function harnessProviderName(providerId: string, entry: AIProviderLlmEntry): string {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset || !isStockCatalogEndpoint(entry)) return providerId;\n return preset.id;\n}\n\n/**\n * Enabled `llm`/`embed` entries, in registry order. Also the set the file\n * adapters render (`opencode-config.ts`, `goose-custom-providers.ts`,\n * `continue-config-yaml.ts`): the env half and the file half must agree on\n * which entries exist before they can agree on what to call them.\n */\nexport function selectableEntries(\n registry: MergedAIProviderRegistry,\n): Array<[string, AIProviderLlmEntry]> {\n return registryEntries(registry).filter(\n (pair): pair is [string, AIProviderLlmEntry] =>\n (pair[1].kind === \"llm\" || pair[1].kind === \"embed\") && isEntryEnabled(pair[1]),\n );\n}\n\n/**\n * The provider-side model ids an entry declares, as `[logicalId, providerId]`\n * pairs in declaration order: every `model_map` entry, plus every\n * `capabilities` key the map does not rename.\n */\nexport function entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logicalIds = [\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}).filter((id) => !(id in (entry.model_map ?? {}))),\n ];\n return logicalIds.map((id) => [id, entry.model_map?.[id] ?? id]);\n}\n\nfunction describeBinding(\n providerId: string,\n entry: AIProviderLlmEntry,\n modelId: string | undefined,\n providerModelId: string | undefined,\n warnings: string[],\n): RegistryModelBinding {\n const surface = entrySurface(entry);\n const baseUrl = entryBaseUrl(entry);\n return {\n providerId,\n entry,\n ...(modelId === undefined ? {} : { modelId }),\n ...(providerModelId === undefined ? {} : { providerModelId }),\n ...(surface ? { surface } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n harnessProviderId: harnessProviderName(providerId, entry),\n warnings,\n };\n}\n\n/**\n * Resolve the session's endpoint + model.\n *\n * With no selector the first entry in registry order wins and the harness\n * keeps its own default model — exactly what an absent `model` meant before\n * the registry existed. Returns `undefined` when no entry can serve a model\n * (an empty, fully-disabled or voice-only registry).\n */\nexport function resolveRegistryBinding(\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const entries = selectableEntries(session.registry);\n if (entries.length === 0) return undefined;\n\n const selector = session.modelRef?.trim();\n if (!selector) {\n const [providerId, entry] = entries[0];\n return describeBinding(providerId, entry, undefined, undefined, []);\n }\n\n // A selector that is exactly an entry id names the endpoint and nothing\n // else: the harness keeps its own default model. `parseModelRef` would read\n // it as a bare *model* id and fall back to registry order.\n const named = entries.find(([id]) => id === selector);\n if (named) return describeBinding(named[0], named[1], undefined, undefined, []);\n\n const resolved = parseModelRef(selector, session.registry, session.roles);\n if (!resolved) return undefined;\n const match = entries.find(([id]) => id === resolved.providerId);\n if (!match) return undefined;\n return describeBinding(\n match[0],\n match[1],\n resolved.modelId,\n resolved.providerModelId,\n resolved.warnings,\n );\n}\n\n/**\n * Every credential a `credentials-n` harness may use: one variable per\n * enabled registry entry. OpenCode, Goose and Continue have always received\n * *all* of them, not just the selected endpoint's, because they route across\n * providers inside a single session.\n */\nexport function credentialsForEveryProvider(session: EnvDriverSession): Record<string, string> {\n return registryCredentialEnv(session.registry, { env: session.lookupEnv });\n}\n\n/**\n * Throw when the bound entry speaks a wire surface this driver cannot.\n *\n * The message names the offending surface and lists the ones the harness does\n * speak (`BUILTIN_DRIVER_CATALOG[driverId].surfaces`). An entry that declares\n * no surface and names no preset is not judged — there is nothing to compare.\n */\nexport function assertDriverSpeaksSurface(\n driverId: string,\n productName: string,\n binding: RegistryModelBinding,\n): void {\n const supported = BUILTIN_DRIVER_CATALOG[driverId]?.surfaces;\n if (!supported || supported.length === 0) return;\n const surface = binding.surface;\n if (!surface || supported.includes(surface)) return;\n throw new Error(\n `${productName} cannot speak the '${surface}' surface of AI provider entry ` +\n `'${binding.providerId}'. ${productName} speaks: ${supported.join(\", \")}. ` +\n `Point this session's model at an entry with one of those surfaces, ` +\n `or run it on a driver that speaks '${surface}'.`,\n );\n}\n\n/**\n * The models a `credentials-n` harness can be pointed at, straight from the\n * registry: every enabled entry's mapped ids, namespaced the way the harness\n * takes them (`-m <provider>/<model>`).\n *\n * These harnesses have no model-list endpoint of their own — OpenCode reads\n * models.dev, Goose and Continue read their config — so the registry is the\n * only list that describes *this* session's reachable models, and it needs no\n * network call to produce.\n */\nexport function registryModelEntries(session: EnvDriverSession): ModelEntry[] {\n const out: ModelEntry[] = [];\n const seen = new Set<string>();\n for (const [providerId, entry] of selectableEntries(session.registry)) {\n const harnessId = harnessProviderName(providerId, entry);\n const label = entry.label ?? providerId;\n for (const [logicalId, providerModelId] of entryModelIds(entry)) {\n const id = `${harnessId}/${providerModelId}`;\n if (seen.has(id)) continue;\n seen.add(id);\n out.push({ id, name: `${label} ${logicalId}` });\n }\n }\n return out;\n}\n\n/**\n * Resolve the binding and enforce the surface — what a `single`-plurality\n * driver does at start.\n *\n * The registry is authoritative: pointing the driver at an entry it cannot\n * speak throws rather than silently running somewhere else. `undefined` when\n * the session configured no endpoint at all, which leaves the driver on its\n * own native auth.\n */\nexport function bindSingleProviderEntry(\n driverId: string,\n productName: string,\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n assertDriverSpeaksSurface(driverId, productName, binding);\n return binding;\n}\n\n/**\n * The `<provider>/<model>` selector a `credentials-n` harness takes on its\n * command line (`opencode -m`). `undefined` when no model was selected — the\n * harness then uses its own default rather than being handed a bare provider.\n */\nexport function harnessModelSelector(binding: RegistryModelBinding): string | undefined {\n if (!binding.providerModelId) return undefined;\n return `${binding.harnessProviderId}/${binding.providerModelId}`;\n}\n\n/**\n * Continue's model selection is a **role binding**, not a flag: `cn` has no\n * `--model` option (only `--config <slug>`), and its `config.yaml` binds each\n * model to roles (`chat`, `edit`, `apply`, …). This is the binding for the\n * role a headless `cn -p` turn runs as, and the shape its generated\n * `config.yaml` is rendered from.\n *\n * `apiKeyEnv` is a variable *name*: the secret travels in the child\n * environment, never in a rendered config.\n */\nexport interface ContinueRoleBinding {\n /** Continue role this model serves. A headless prompt is a `chat` turn. */\n role: \"chat\";\n /** Registry id of the entry. */\n providerId: string;\n /** Provider name Continue knows the endpoint by. */\n provider: string;\n /** Provider-side model id. */\n model?: string;\n /** Endpoint, when the entry states one, spelled the way Continue's `apiBase` wants it. */\n apiBase?: string;\n /** Env var holding the credential — the name, never the value. */\n apiKeyEnv: string;\n}\n\n/**\n * Map the session's chosen endpoint onto the Continue role a headless turn\n * runs as. `undefined` when the session configured no endpoint — `cn` then\n * runs against whatever its own `config.yaml` / Hub login provides.\n */\nexport function continueRoleBinding(session: EnvDriverSession): ContinueRoleBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n return {\n role: \"chat\",\n providerId: binding.providerId,\n provider: binding.harnessProviderId,\n ...(binding.providerModelId ? { model: binding.providerModelId } : {}),\n ...(binding.baseUrl\n ? { apiBase: versionedAnthropicBaseUrl(binding.baseUrl, binding.surface) }\n : {}),\n apiKeyEnv: providerCredentialEnvName(binding.providerId),\n };\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/provider-materialize/env-drivers.ts"],"names":[],"mappings":";;;;AAyEO,SAAS,uBAAA,CACd,MAAA,EACA,UAAA,GAAiD,OAAA,CAAQ,GAAA,EACvC;AAClB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,MAAA,CAAO,QAAA,IAAY,eAAA,CAAgB,EAAE,CAAA;AAAA,IAC/C,WAAW,EAAE,GAAG,UAAA,EAAY,GAAG,OAAO,GAAA,EAAI;AAAA,IAC1C,GAAI,OAAO,QAAA,GAAW,EAAE,UAAU,MAAA,CAAO,QAAA,KAAa,EAAC;AAAA,IACvD,GAAI,OAAO,KAAA,GAAQ,EAAE,OA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,OAAO,OAAA,CAAQ,eAAA,KAAoB,EAAC;AAAA,IACpE,GAAI,OAAA,CAAQ,OAAA,GACR,EAAE,OAAA,EAAS,yBAAA,CAA0B,OAAA,CAAQ,OAAA,EAAS,OAAA,CAAQ,OAAO,CAAA,EAAE,GACvE,EAAC;AAAA,IACL,SAAA,EAAW,yBAAA,CAA0B,OAAA,CAAQ,UAAU;AAAA,GACzD;AACF","file":"chunk-TXGVG7VH.js","sourcesContent":["/**\n * Registry adapter for the **env-shaped CLI drivers** — Gemini, Qwen, OpenCode,\n * Goose and Continue (§2.3).\n *\n * These harnesses take their endpoint from the environment rather than from a\n * config file, so the adapter's job is three things: resolve which registry\n * entry the session's model selector names, refuse at start when that entry\n * speaks a wire surface the harness cannot, and hand the driver the\n * provider-side model id it must put on the command line.\n *\n * Two pluralities meet here (`BUILTIN_DRIVER_CATALOG.providerPlurality`):\n *\n * - `single` — Gemini and Qwen address exactly one endpoint. The bound entry\n * supplies the credential *and* the base URL, and a surface mismatch is\n * fatal: a Gemini CLI pointed at an `openai-completions` endpoint cannot\n * work, and failing at start names the surface instead of leaving the user\n * with an opaque error mid-turn.\n * - `credentials-n` — OpenCode, Goose and Continue accept every enabled\n * entry's credential at once and select one active model. The credential\n * fan-out is `registryCredentialEnv`; the active model is this module's\n * `<provider>/<model>` binding.\n *\n * Writing the per-endpoint config files those three need for *custom*\n * endpoints (`opencode.json`, Goose `custom_providers/*.json`, Continue\n * `config.yaml`) is the file half, and is deliberately not here.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3\n */\n\nimport {\n type AIProviderLlmEntry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n mergeRegistries,\n normalizeEntryBaseUrl,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport type { ModelEntry } from \"../models.js\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport type { AgentConfig } from \"../types.js\";\nimport { providerCredentialEnvName, registryCredentialEnv } from \"./credential-env.js\";\n\n/**\n * Everything a CLI driver needs to know about this session's AI providers,\n * resolved once from its {@link AgentConfig}.\n */\nexport interface EnvDriverSession {\n /** The merged registry this session may address. Empty when none was configured. */\n registry: MergedAIProviderRegistry;\n /**\n * Environment `credential.ref` lookups resolve against — the process\n * environment widened with `config.env`, which is where the session\n * boundary delivered every resolved `SKAILE_AIP_<ID>_KEY`.\n */\n lookupEnv: Record<string, string | undefined>;\n /** Model selector: `<providerId>/<modelId>`, a bare id, or `@role`. */\n modelRef?: string;\n /** Roles table an `@role` selector resolves through. */\n roles?: Record<string, string>;\n}\n\n/**\n * Resolve the session's providers once, from its {@link AgentConfig}.\n *\n * `config.env` is folded into `lookupEnv` rather than kept apart: it is part\n * of the session's environment, not an extra, and a credential or\n * `*_BASE_URL` delivered there must be visible exactly as the child will see\n * it.\n */\nexport function resolveEnvDriverSession(\n config: AgentConfig,\n processEnv: Record<string, string | undefined> = process.env,\n): EnvDriverSession {\n return {\n registry: config.registry ?? mergeRegistries([]),\n lookupEnv: { ...processEnv, ...config.env },\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n };\n}\n\n/** One resolved endpoint + model — everything a driver needs to spawn. */\nexport interface RegistryModelBinding {\n /** Registry id of the selected entry. */\n providerId: string;\n /** The selected entry itself. */\n entry: AIProviderLlmEntry;\n /** Logical model id, after `@role` expansion and before `model_map`. */\n modelId?: string;\n /** Provider-side model id — what goes on the wire / command line. */\n providerModelId?: string;\n /** Wire protocol, from the entry or its preset. */\n surface?: AIProviderSurface;\n /** Resolved endpoint, from the entry, its transport params, or its preset. */\n baseUrl?: string;\n /**\n * The provider name the *harness* knows this endpoint by — a catalog preset\n * id for a stock endpoint, the registry id for anything custom. See\n * {@link harnessProviderName}.\n */\n harnessProviderId: string;\n /** Non-fatal notes from `parseModelRef` (dangling role, disabled provider). */\n warnings: string[];\n}\n\n/** The entry's wire surface: its own, else its preset's. */\nexport function entrySurface(entry: AIProviderLlmEntry): AIProviderSurface | undefined {\n if (entry.surface) return entry.surface;\n return entry.preset ? getProviderPreset(entry.preset)?.surface : undefined;\n}\n\n/**\n * The entry's endpoint: its literal or transport-derived URL, else its\n * preset's literal, in the canonical spelling for its surface\n * (`normalizeEntryBaseUrl`: an `anthropic-messages` endpoint is its host root,\n * so `https://api.anthropic.com/v1` reads as `https://api.anthropic.com`).\n * Transport templates that still carry `{param}` placeholders never come\n * back — `resolveEntryBaseUrl` withholds those, and a preset's template is not\n * a URL.\n *\n * Every adapter reads the endpoint here and only re-spells it for a client\n * that wants something else ({@link versionedAnthropicBaseUrl}).\n */\nexport function entryBaseUrl(entry: AIProviderLlmEntry): string | undefined {\n const resolved =\n resolveEntryBaseUrl(entry) ??\n (entry.preset ? getProviderPreset(entry.preset)?.base_url : undefined);\n return normalizeEntryBaseUrl(resolved, entrySurface(entry));\n}\n\n/**\n * An `anthropic-messages` endpoint spelled for a client that appends only\n * `/messages` — `@ai-sdk/anthropic` (OpenCode) and Continue — rather than\n * `/v1/messages` like the Claude CLI, the Anthropic SDK and Goose. `baseUrl`\n * must already be canonical ({@link entryBaseUrl}); every other surface passes\n * through unchanged.\n */\nexport function versionedAnthropicBaseUrl(\n baseUrl: string,\n surface: AIProviderSurface | undefined,\n): string {\n if (surface !== \"anthropic-messages\") return baseUrl;\n // Append to the path, not the string: a query or fragment stays at the end.\n try {\n const url = new URL(baseUrl);\n url.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/v1`;\n return url.toString();\n } catch {\n return `${baseUrl}/v1`;\n }\n}\n\n/**\n * True when a `credentials-n` harness already knows this endpoint under its\n * own catalog name — the entry names a preset and did not move it somewhere\n * else. Both sides are compared canonically, so `https://api.anthropic.com/v1`\n * is still the `anthropic` preset's endpoint.\n *\n * The one rule both halves of §2.3 read: it decides the name the env half\n * puts on the command line ({@link harnessProviderName}) *and* whether the\n * file half has to describe the endpoint at all. Reading it twice is what\n * keeps `-m <name>/<model>` and the generated provider file talking about the\n * same thing.\n */\nexport function isStockCatalogEndpoint(entry: AIProviderLlmEntry): boolean {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset) return false;\n return entryBaseUrl(entry) === normalizeEntryBaseUrl(preset.base_url, entrySurface(entry));\n}\n\n/**\n * The provider name to give a `credentials-n` harness (`-m <name>/<model>`,\n * `GOOSE_PROVIDER`).\n *\n * A stock catalog endpoint is named by its preset, because that is the name\n * OpenCode's models.dev list and Goose's built-in provider table already use —\n * `prod-claude: {preset: anthropic}` is still Anthropic to them. An entry with\n * an endpoint of its own is named by its registry id: no built-in table knows\n * it, so the id is what its generated provider file is keyed by (the file half\n * of §2.3).\n */\nexport function harnessProviderName(providerId: string, entry: AIProviderLlmEntry): string {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset || !isStockCatalogEndpoint(entry)) return providerId;\n return preset.id;\n}\n\n/**\n * Enabled `llm`/`embed` entries, in registry order. Also the set the file\n * adapters render (`opencode-config.ts`, `goose-custom-providers.ts`,\n * `continue-config-yaml.ts`): the env half and the file half must agree on\n * which entries exist before they can agree on what to call them.\n */\nexport function selectableEntries(\n registry: MergedAIProviderRegistry,\n): Array<[string, AIProviderLlmEntry]> {\n return registryEntries(registry).filter(\n (pair): pair is [string, AIProviderLlmEntry] =>\n (pair[1].kind === \"llm\" || pair[1].kind === \"embed\") && isEntryEnabled(pair[1]),\n );\n}\n\n/**\n * The provider-side model ids an entry declares, as `[logicalId, providerId]`\n * pairs in declaration order: every `model_map` entry, plus every\n * `capabilities` key the map does not rename.\n */\nexport function entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logicalIds = [\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}).filter((id) => !(id in (entry.model_map ?? {}))),\n ];\n return logicalIds.map((id) => [id, entry.model_map?.[id] ?? id]);\n}\n\nfunction describeBinding(\n providerId: string,\n entry: AIProviderLlmEntry,\n modelId: string | undefined,\n providerModelId: string | undefined,\n warnings: string[],\n): RegistryModelBinding {\n const surface = entrySurface(entry);\n const baseUrl = entryBaseUrl(entry);\n return {\n providerId,\n entry,\n ...(modelId === undefined ? {} : { modelId }),\n ...(providerModelId === undefined ? {} : { providerModelId }),\n ...(surface ? { surface } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n harnessProviderId: harnessProviderName(providerId, entry),\n warnings,\n };\n}\n\n/**\n * Resolve the session's endpoint + model.\n *\n * With no selector the first entry in registry order wins and the harness\n * keeps its own default model — exactly what an absent `model` meant before\n * the registry existed. Returns `undefined` when no entry can serve a model\n * (an empty, fully-disabled or voice-only registry).\n */\nexport function resolveRegistryBinding(\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const entries = selectableEntries(session.registry);\n if (entries.length === 0) return undefined;\n\n const selector = session.modelRef?.trim();\n if (!selector) {\n const [providerId, entry] = entries[0];\n return describeBinding(providerId, entry, undefined, undefined, []);\n }\n\n // A selector that is exactly an entry id names the endpoint and nothing\n // else: the harness keeps its own default model. `parseModelRef` would read\n // it as a bare *model* id and fall back to registry order.\n const named = entries.find(([id]) => id === selector);\n if (named) return describeBinding(named[0], named[1], undefined, undefined, []);\n\n const resolved = parseModelRef(selector, session.registry, session.roles);\n if (!resolved) return undefined;\n const match = entries.find(([id]) => id === resolved.providerId);\n if (!match) return undefined;\n return describeBinding(\n match[0],\n match[1],\n resolved.modelId,\n resolved.providerModelId,\n resolved.warnings,\n );\n}\n\n/**\n * Every credential a `credentials-n` harness may use: one variable per\n * enabled registry entry. OpenCode, Goose and Continue have always received\n * *all* of them, not just the selected endpoint's, because they route across\n * providers inside a single session.\n */\nexport function credentialsForEveryProvider(session: EnvDriverSession): Record<string, string> {\n return registryCredentialEnv(session.registry, { env: session.lookupEnv });\n}\n\n/**\n * Throw when the bound entry speaks a wire surface this driver cannot.\n *\n * The message names the offending surface and lists the ones the harness does\n * speak (`BUILTIN_DRIVER_CATALOG[driverId].surfaces`). An entry that declares\n * no surface and names no preset is not judged — there is nothing to compare.\n */\nexport function assertDriverSpeaksSurface(\n driverId: string,\n productName: string,\n binding: RegistryModelBinding,\n): void {\n const supported = BUILTIN_DRIVER_CATALOG[driverId]?.surfaces;\n if (!supported || supported.length === 0) return;\n const surface = binding.surface;\n if (!surface || supported.includes(surface)) return;\n throw new Error(\n `${productName} cannot speak the '${surface}' surface of AI provider entry ` +\n `'${binding.providerId}'. ${productName} speaks: ${supported.join(\", \")}. ` +\n `Point this session's model at an entry with one of those surfaces, ` +\n `or run it on a driver that speaks '${surface}'.`,\n );\n}\n\n/**\n * The models a `credentials-n` harness can be pointed at, straight from the\n * registry: every enabled entry's mapped ids, namespaced the way the harness\n * takes them (`-m <provider>/<model>`).\n *\n * These harnesses have no model-list endpoint of their own — OpenCode reads\n * models.dev, Goose and Continue read their config — so the registry is the\n * only list that describes *this* session's reachable models, and it needs no\n * network call to produce.\n */\nexport function registryModelEntries(session: EnvDriverSession): ModelEntry[] {\n const out: ModelEntry[] = [];\n const seen = new Set<string>();\n for (const [providerId, entry] of selectableEntries(session.registry)) {\n const harnessId = harnessProviderName(providerId, entry);\n const label = entry.label ?? providerId;\n for (const [logicalId, providerModelId] of entryModelIds(entry)) {\n const id = `${harnessId}/${providerModelId}`;\n if (seen.has(id)) continue;\n seen.add(id);\n out.push({ id, name: `${label} ${logicalId}` });\n }\n }\n return out;\n}\n\n/**\n * Resolve the binding and enforce the surface — what a `single`-plurality\n * driver does at start.\n *\n * The registry is authoritative: pointing the driver at an entry it cannot\n * speak throws rather than silently running somewhere else. `undefined` when\n * the session configured no endpoint at all, which leaves the driver on its\n * own native auth.\n */\nexport function bindSingleProviderEntry(\n driverId: string,\n productName: string,\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n assertDriverSpeaksSurface(driverId, productName, binding);\n return binding;\n}\n\n/**\n * The `<provider>/<model>` selector a `credentials-n` harness takes on its\n * command line (`opencode -m`). `undefined` when no model was selected — the\n * harness then uses its own default rather than being handed a bare provider.\n */\nexport function harnessModelSelector(binding: RegistryModelBinding): string | undefined {\n if (!binding.providerModelId) return undefined;\n return `${binding.harnessProviderId}/${binding.providerModelId}`;\n}\n\n/**\n * Continue's model selection is a **role binding**, not a flag: `cn` has no\n * `--model` option (only `--config <slug>`), and its `config.yaml` binds each\n * model to roles (`chat`, `edit`, `apply`, …). This is the binding for the\n * role a headless `cn -p` turn runs as, and the shape its generated\n * `config.yaml` is rendered from.\n *\n * `apiKeyEnv` is a variable *name*: the secret travels in the child\n * environment, never in a rendered config.\n */\nexport interface ContinueRoleBinding {\n /** Continue role this model serves. A headless prompt is a `chat` turn. */\n role: \"chat\";\n /** Registry id of the entry. */\n providerId: string;\n /** Provider name Continue knows the endpoint by. */\n provider: string;\n /** Provider-side model id. */\n model?: string;\n /** Endpoint, when the entry states one, spelled the way Continue's `apiBase` wants it. */\n apiBase?: string;\n /** Env var holding the credential — the name, never the value. */\n apiKeyEnv: string;\n}\n\n/**\n * Map the session's chosen endpoint onto the Continue role a headless turn\n * runs as. `undefined` when the session configured no endpoint — `cn` then\n * runs against whatever its own `config.yaml` / Hub login provides.\n */\nexport function continueRoleBinding(session: EnvDriverSession): ContinueRoleBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n return {\n role: \"chat\",\n providerId: binding.providerId,\n provider: binding.harnessProviderId,\n ...(binding.providerModelId ? { model: binding.providerModelId } : {}),\n ...(binding.baseUrl\n ? { apiBase: versionedAnthropicBaseUrl(binding.baseUrl, binding.surface) }\n : {}),\n apiKeyEnv: providerCredentialEnvName(binding.providerId),\n };\n}\n"]}