@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 +0,0 @@
1
- {"version":3,"sources":["../bridge/src/logger.ts","../bridge/src/provider-registry-derive.ts","../bridge/src/types.ts"],"names":[],"mappings":";;;;;;AAuBO,SAAS,gBAAgB,OAAA,EAAyB;AACvD,EAAA,OAAO,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,CAAA;AACjD;;;ACFO,SAAS,gBAAA,CACd,QAAA,EACA,KAAA,GAA2B,SAAA,EACD;AAC1B,EAAA,IAAI,KAAA,CAAM,OAAA,CAAS,QAAA,CAAsC,KAAK,CAAA,EAAG;AAC/D,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,OAAO,gBAAgB,CAAC,EAAE,OAAO,SAAA,EAAW,QAAA,EAAgC,CAAC,CAAA;AAC/E;AAYO,SAAS,oBAAA,CACd,QAAA,EACA,OAAA,GAAqC,EAAC,EACkD;AACxF,EAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,QAAA,EAAU,SAAS,CAAA;AACnD,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,MAAA;AAAA,IACV,GAAA,EAAK,qBAAA,CAAsB,MAAA,EAAQ,OAAO,CAAA;AAAA,IAC1C,GAAI,QAAQ,UAAA,GAAa,EAAE,UAAU,OAAA,CAAQ,UAAA,KAAe;AAAC,GAC/D;AACF;AC+UO,IAAM,sBAAsB,CAAC,KAAA,EAAO,QAAA,EAAU,MAAA,EAAQ,SAAS,KAAK;AAQpE,SAAS,cAAc,KAAA,EAAyC;AACrE,EAAA,OAAO,aAAA,CAAc,KAAK,CAAA,GAAI,KAAA,GAAQ,MAAA;AACxC;AAEA,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAQ,mBAAA,CAA2C,SAAS,KAAK,CAAA;AACnE;AAydO,IAAM,0BAAA,GAA6B;A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A,EAAU,QAAQ,QAAA,IAAY,SAAA;AAAA,QAC9B,aAAa,MAAA,CAAO,WAAA;AAAA,QACpB,cAAc,MAAA,CAAO,YAAA;AAAA,QACrB,UAAA;AAAA,QACA,YAAY,MAAA,CAAO;AAAA,OACpB,CAAA;AAAA,IACH;AAEA,IAAA,IAAA,CAAK,UAAA,CAAW,OAAA,CAAQ,IAAA,CAAK,eAAA,EAAiB;AAAA,MAC5C,MAAA,EAAQ,MAAA,EAAQ,KAAA,GAAQ,OAAA,GAAU,IAAA;AAAA,MAClC,OAAO,MAAA,EAAQ,KAAA;AAAA,MACf,UAAA,EAAY,EAAE,yBAAA,EAA2B,UAAA;AAAW,KACrD,CAAA;AAED,IAAA,IAAA,CAAK,eAAA,GAAkB,MAAA;AACvB,IAAA,IAAA,CAAK,cAAA,GAAiB,MAAA;AAAA,EACxB;AACF","file":"chunk-4AKR4XPQ.js","sourcesContent":["/**\n * Bridge-layer logger factory.\n *\n * Each driver creates its own Logger via `getBridgeLogger(subkind)` at\n * construction time. Falls back to an off-mode Logger (stdout only) when\n * no LogStore is registered — see @skaile/workspaces/core/logging for details.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * Construct a bridge-scoped Logger for a given driver subkind.\n *\n * Creates a `Logger` with `kind: \"bridge\"` and the specified `subkind`. Falls back to\n * an off-mode Logger (stdout only) when no `LogStore` is registered — see\n * `@skaile/workspaces/core/logging` for details. Each driver calls this once at construction\n * time; never re-construct per call.\n *\n * @param subkind - Driver id, e.g. `\"claude-sdk\"`, `\"omp\"`, `\"echo\"`, `\"codex\"`.\n * @returns A `Logger` scoped to `bridge:<subkind>`.\n * @docLink packages/bridge/api-reference#logger\n */\nexport function getBridgeLogger(subkind: string): Logger {\n return createLogger({ kind: \"bridge\", subkind });\n}\n","/**\n * The two shaping helpers every registry consumer needs.\n *\n * The legacy provider axis — `provider` / `cloud` / `cloud_config` /\n * `cloudSecrets` — is gone from the runtime, and so is the user-local\n * `settings.json` `apiKeys{}` map: a session carries an AI provider registry\n * and a model selector, nothing else. Credentials are named by a\n * `credential.ref` and resolved into the child environment; no literal secret\n * ever enters an entry.\n */\n\nimport {\n type AIProviderLayerId,\n type AIProviderRegistry,\n type MergedAIProviderRegistry,\n mergeRegistries,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport {\n type RegistryCredentialOptions,\n registryCredentialEnv,\n} from \"./provider-materialize/credential-env.js\";\n\n/** Turn any registry shape into the merged view, without re-merging one. */\nexport function toMergedRegistry(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n layer: AIProviderLayerId = \"session\",\n): MergedAIProviderRegistry {\n if (Array.isArray((registry as MergedAIProviderRegistry).order)) {\n return registry as MergedAIProviderRegistry;\n }\n return mergeRegistries([{ layer, providers: registry as AIProviderRegistry }]);\n}\n\n/**\n * The `AgentConfig` slice a `DriverTarget.listModels` closure builds its\n * throwaway driver from: the registry, the selector when the caller named one\n * entry, and the credentials as a child-environment fragment.\n *\n * The credentials have to ride `env`, not a side channel: a `platform:` or\n * `cmd:` reference resolves where the *caller* stands, and this process's own\n * environment cannot see it. `registryCredentialEnv` writes each one under\n * `SKAILE_AIP_<ID>_KEY`, which is the carrier every driver already consults.\n */\nexport function registryDriverConfig(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: RegistryCredentialOptions = {},\n): { registry: MergedAIProviderRegistry; env: Record<string, string>; modelRef?: string } {\n const merged = toMergedRegistry(registry, \"runtime\");\n return {\n registry: merged,\n env: registryCredentialEnv(merged, options),\n ...(options.providerId ? { modelRef: options.providerId } : {}),\n };\n}\n","import { EventEmitter } from \"node:events\";\nimport type { Span, TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type {\n AgentPromptInput,\n Capability,\n CredentialMint,\n CodexCredentialDelivery,\n ContextUsageDetail,\n DriverContextReport,\n DriverInfo,\n ErrorRetryReason,\n CodexSubscriptionRefreshInput,\n CodexSubscriptionRefreshResult,\n FlowExecution,\n ModelTokenUsage,\n RenderInvokedEvent,\n TokenUsage,\n} from \"@skaile/workspaces/types\";\nimport type { CodexServerRequestHandlers } from \"./codex-app-server.js\";\nexport type { AgentPromptInput } from \"@skaile/workspaces/types\";\nimport type { MergedAIProviderRegistry } from \"@skaile/workspaces/core/provider-registry\";\nimport type { ModelEntry } from \"./models.js\";\n\n/**\n * Test-only hook injected by the runner so a no-LLM driver (the echo driver's\n * scripted-flow mode) can read flow state and drive flow-adapter mutations\n * without an SDK/MCP round-trip. The runner wires this in `createActiveFlow`\n * from the active FlowAdapter + handle.\n *\n * This is an internal runner↔driver interface — NOT part of any wire\n * protocol or flow contract. Production drivers ignore it.\n *\n * @see packages/bridge/drivers/echo — scripted-flow mode\n * @since 3.6.0\n */\nexport interface FlowTestDriverHook {\n /** Current flow execution snapshot, or `null` when no flow is active. */\n getState(): FlowExecution | null;\n /**\n * Execute a flow-adapter operation (`start_node`, `request_approval`,\n * `complete_node`, `request_input`, `skip_node`, `fail_node`, …). Returns\n * the adapter's JSON string result (or rejects on an illegal transition).\n */\n execute(op: string, args: Record<string, unknown>): Promise<string>;\n /**\n * Node IDs marked as mandatory approval gates. The scripted policy resolves\n * `auto` to `request_approval` for these even in autonomous mode, so hosts\n * can drive a mandatory gate deterministically. Optional — absent hooks\n * behave as if no node is mandatory.\n */\n mandatoryGates?(): string[];\n}\n\n/**\n * Minimal LLM tool descriptor used by the capability dispatch path. Mirrors\n * the runner's `LLMTool` shape so drivers can consume registry output without\n * importing `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-tool\n */\nexport interface BridgeCapabilityTool {\n /** Capability name; used as the LLM-visible tool name. */\n name: string;\n /** Human/LLM-readable description. */\n description: string;\n /** JSON Schema for the tool's input parameters. */\n parameters: Record<string, unknown>;\n}\n\n/**\n * Render-cap event emission callback used by the bridge when the LLM invokes\n * a capability that carries a `render` spec. The runner provides the actual\n * sink (transport.send / sendEvent); the bridge only emits.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-render-emit\n */\nexport type BridgeRenderEmit = (event: RenderInvokedEvent) => void;\n\n/**\n * Text-event emission callback for render-capability fallbacks. When a\n * `RenderCapability` carries `render.fallback` and the LLM invokes it, the\n * bridge substitutes `{{prop}}` placeholders (top-level keys of `props`,\n * optional dotted-path traversal `{{user.name}}`) and pushes the rendered\n * string through this callback so clients without a render layer still see\n * a textual representation. No-op when `fallback` is absent.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-text-emit\n */\nexport type BridgeTextEmit = (text: string) => void;\n\n/**\n * Bundle of capability dispatch hooks. Registered into the driver via\n * `AgentConfig.capabilities`; the driver routes registered LLM tool calls\n * back into `invoke()` instead of using its native dispatch path.\n *\n * The runner constructs this from a `CapabilityRegistry` instance and threads\n * it through `createAgentSession()`. Drivers that don't yet implement\n * capability dispatch ignore the field — legacy v1 paths stay intact.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-hooks\n */\nexport interface BridgeCapabilityHooks {\n /** Build the LLM tool descriptor list from the registry. Called per turn so registration changes take effect. */\n composeTools(): BridgeCapabilityTool[];\n /** Resolve a wire-format Capability descriptor by name. Used by the bridge to inspect `fireAndForget` / `render`. */\n resolve(name: string): Capability | null;\n /**\n * Validate input + dispatch through the registry. Logging is wired by the\n * registry.\n *\n * `callId` is the per-dispatch id minted by `dispatchCapability`. It MUST be\n * unique per process (never a driver/provider tool-call id, which only the\n * model backend keeps unique): it is the `render_invoked.callId`, the\n * registry's log correlation id, the handler's `ctx.callId` and — for client\n * capabilities — the `capability_invoked.callId` keying the runner's pending\n * map, so a reused id would let a late `capability_result` for a timed-out\n * call resolve a later call. Callers without one omit it and the registry\n * generates a fresh id.\n */\n invoke(name: string, input: unknown, signal?: AbortSignal, callId?: string): Promise<unknown>;\n /** Subscribe to registry changes; callback carries no credentials or tool payloads. */\n onToolsChanged?(listener: () => void): () => void;\n /** Emit a render-invoked event. The runner forwards via the WebSocket transport. */\n emitRender?: BridgeRenderEmit;\n /** Emit a text fallback for render capabilities with `render.fallback`. */\n emitText?: BridgeTextEmit;\n /** Session id passed through to the runner's per-handler logger. */\n sessionId: string;\n}\n\n/**\n * Static metadata for a registered agent driver (the harness it drives).\n *\n * Declared once in `@skaile/workspaces/types` — it is protocol surface (the\n * platform reads `surfaces` to decide which AI provider registry entries a\n * driver can serve) and was previously duplicated here field-for-field.\n *\n * Returned by {@link listDrivers} and exposed on every {@link AgentDriver}\n * instance via `driverInfo`.\n *\n * @docLink packages/bridge/concepts#driver-info\n */\nexport type { DriverInfo };\n\n/** Closed, passive managed-MCP observations. Counts saturate at 512. */\nexport interface CodexNativeMcpDiagnostics {\n startupBeforeTurn: \"unknown\" | \"starting\" | \"ready\" | \"failed\" | \"cancelled\";\n startupAtEnd: CodexNativeMcpDiagnostics[\"startupBeforeTurn\"];\n toolsListBeforeTurn: number;\n toolsListTotal: number;\n toolsCallTotal: number;\n nativeMcpToolItemCount: number;\n}\n\n/** Trusted session-local tool transport; fulfilled only after required tools are ready. */\nexport interface CodexToolTransport {\n mcpServers: Record<string, Record<string, unknown>>;\n /** Trusted runner server eligible for human native consent; must name its configured entry. */\n approvalServerName?: string;\n onServerRequest?: CodexServerRequestHandlers;\n /** Revalidate the required live inventory before starting each turn. */\n validate?(): Promise<void>;\n /** Rebuild the native generation at idle when its advertised inventory is stale. */\n needsReload?(): boolean;\n instructions?: string;\n /** Restrict model calls to the active turn and abort outstanding calls when it ends. */\n beginTurn?(signal: AbortSignal): void;\n /** Trusted private server binding and passive request-handler counters; never performs I/O. */\n diagnostics?: {\n serverName: string;\n requestCounts(): { toolsListTotal: number; toolsCallTotal: number };\n };\n dispose(): Promise<void>;\n}\n\n/** Explicit managed instance inputs; none are inferred from ambient developer state. */\nexport interface CodexManagedRuntimeOptions {\n executable: string;\n /** Optional launcher arguments, for the caller-owned executable wrapper. */\n executableArgs?: string[];\n /** Private local filesystem state; the host must fence old native processes before reuse. */\n privateDirectory: string;\n /** Host-owned private mount containing every parent/child instance; denied to native tools. */\n privateRoot: string;\n environment: Record<string, string>;\n credential: CodexCredentialDelivery;\n instructionFiles?: string[];\n skillsDirectory?: string;\n prepareTools(signal: AbortSignal): Promise<CodexToolTransport>;\n /**\n * Passive snapshots before/after turns, plus final local counts after successful transport closure.\n * No final snapshot is emitted on uncertain cleanup or a failed final counter read. Earlier snapshots\n * are not proof of completed cleanup. Sink failures never affect native execution or cleanup.\n */\n onNativeMcpDiagnostics?(value: Readonly<CodexNativeMcpDiagnostics>): void | Promise<void>;\n refreshCredential?: (\n input: CodexSubscriptionRefreshInput,\n signal: AbortSignal,\n ) => Promise<CodexSubscriptionRefreshResult>;\n requestTimeoutMs?: number;\n turnTimeoutMs?: number;\n /** Maximum native turns admitted by this instance; reserved for disposable one-turn children. */\n nativeTurnBudget?: 1;\n /** Human interaction deadline, bounded separately from ordinary RPCs. */\n interactionTimeoutMs?: number;\n}\n\n/**\n * Codex-specific tuning options passed through `DriverOptions.codex`.\n *\n * @remarks These are forwarded verbatim to the Codex driver and have no effect on other drivers.\n * @docLink packages/bridge/concepts#codex-driver-options\n */\nexport interface CodexDriverOptions {\n /** Omission retains the standalone SDK path; managed mode always requires App Server inputs. */\n authSource?: \"local\" | \"managed\";\n managedRuntime?: CodexManagedRuntimeOptions;\n /** Controls whether Codex may auto-apply edits without user approval. */\n approvalPolicy?: \"never\" | \"on-request\" | \"on-failure\" | \"untrusted\";\n /** Filesystem sandbox level for the Codex process. */\n sandboxMode?: \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n /** Reasoning budget passed to the model. */\n reasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** When `true`, the Codex sandbox is allowed to make outbound network requests. */\n networkAccessEnabled?: boolean;\n /** Extra directories made accessible to the Codex sandbox in addition to `cwd`. */\n additionalDirectories?: string[];\n}\n\n/**\n * omp-specific options passed through `DriverOptions.omp`.\n *\n * They govern the session-private agent directory the omp adapter renders the\n * provider registry into (`omp-models-yml.ts`); every one of them has a\n * working default, so a caller that sets none still gets a correct session.\n *\n * @remarks Forwarded verbatim to the omp driver; no effect on other drivers.\n * @see PROVIDER-CONFIG-PLAN.md §2.3\n */\nexport interface OmpDriverOptions {\n /**\n * Explicit session-private agent directory for `PI_CODING_AGENT_DIR`.\n * Defaults to `<cwd>/.omp/agent-home/<sessionId>`.\n */\n agentHome?: string;\n /**\n * Inherit the developer's own omp state (auth store, blobs, extensions) by\n * symlinking {@link OmpDriverOptions.userAgentDir} into the session\n * directory. Defaults to *on when that directory exists*, which is exactly\n * the standalone case: a platform container has none, so its session starts\n * empty. Set `false` to force an empty session directory regardless.\n */\n seedUserAgentDir?: boolean;\n /** Seed source. Defaults to `~/.omp/agent`. */\n userAgentDir?: string;\n}\n\n/**\n * Driver-specific configuration bag.\n *\n * Fields are keyed by driver ID so that callers can pass driver-specific options\n * through the common {@link AgentConfig} without breaking other drivers.\n *\n * @docLink packages/bridge/concepts#driver-options\n */\nexport interface DriverOptions {\n /** Codex-specific options. Ignored by all other drivers. */\n codex?: CodexDriverOptions;\n /** omp-specific options. Ignored by all other drivers. */\n omp?: OmpDriverOptions;\n}\n\n/**\n * What the driver tells the host about a turn blocked by an upstream usage\n * limit. Everything but `configId` is best-effort: the SDK reports the limit\n * window only on its structured telemetry, not on the error result text.\n *\n * @see AgentConfig.onLimitBlocked\n * @category Configuration\n * @since 3.9.0\n */\nexport interface LimitBlockedContext {\n /** The AI provider config the blocked turn ran on (`\"\"` when unmediated). */\n configId: string;\n /** Upstream limit window (`five_hour`, `seven_day`, …) when reported. */\n limitType?: string;\n /** Epoch seconds at which the limit window resets, when reported. */\n resetsAt?: number;\n /** Fraction of the limit window consumed (0–1) when reported. */\n utilization?: number;\n}\n\n/**\n * The host's verdict on a limit-blocked turn. `switched: true` is a promise\n * that a different seat's credential is already on disk — the driver acts on it\n * by respawning the CLI and replaying the prompt, so returning it without\n * having rewritten the credential file would just replay onto the dead seat.\n *\n * @see AgentConfig.onLimitBlocked\n * @category Configuration\n * @since 3.9.0\n */\nexport interface LimitFailoverResult {\n /** Whether the session was repointed at a different AI provider config. */\n switched: boolean;\n /** The config id now in effect. Informational — used for logs. */\n configId?: string;\n /**\n * Why no switch happened: `same-config`, `standalone`,\n * `platform-omitted-config-id` (the mint succeeded but named no seat, so a\n * re-resolution is indistinguishable from none), or a `CredentialMint`\n * failure code. Diagnostic only — the driver branches on `switched`.\n */\n reason?: string;\n}\n\n/**\n * One observed AI-provider rejection, reported to the host for per-seat health\n * attribution. Fire-and-forget — see {@link AgentConfig.onProviderResponse}.\n *\n * @category Configuration\n * @since 3.9.0\n */\nexport interface ProviderResponseObservation {\n /** 401 — the credential was rejected. 429 — an upstream rate/session limit. */\n status: 401 | 429;\n /** The AI provider config the observation is attributed to, when known. */\n configId?: string;\n /** Upstream limit window (`five_hour`, `seven_day`, …) when reported. */\n limitType?: string;\n /** Fraction of the limit window consumed (0–1) when reported. */\n utilization?: number;\n /** Epoch seconds at which the limit window resets, when reported. */\n resetsAt?: number;\n /**\n * What the 429 was, when the driver recognised something narrower than a\n * usage limit. `long-context-entitlement`: the account may not use a long\n * (1M) context window; the seat is not out of quota. Diagnostic only — the\n * driver still treats the rejection as before.\n */\n cause?: ProviderResponseCause;\n}\n\n/**\n * Why a 429 {@link ProviderResponseObservation} was rejected, when the driver\n * recognised it. Consumers must tolerate values they do not know.\n *\n * @category Configuration\n * @since 4.11.0\n */\nexport type ProviderResponseCause = \"long-context-entitlement\";\n\n/**\n * One upstream quota-window reading, reported to the host for every SDK\n * `rate_limit_event` — allowed, warning or rejected alike. Fire-and-forget —\n * see {@link AgentConfig.onProviderQuota}.\n *\n * @category Configuration\n * @since 4.1.0\n */\nexport interface ProviderQuotaObservation {\n /** The AI provider config the reading is attributed to, when known. */\n configId?: string;\n /** Upstream window, verbatim (`five_hour`, `seven_day`, or a future value). */\n window: string;\n /** Upstream status, verbatim (`allowed`, `allowed_warning`, `rejected`, …). */\n status: string;\n /** Fraction of the window consumed (0–1); the SDK reports it on warnings and rejections only. */\n utilization?: number;\n /** Epoch seconds at which the window resets, when reported. */\n resetsAt?: number;\n}\n\n/**\n * Reasoning effort levels a host may set. The platform sends all five, the\n * Agent SDK accepts all five, omp has a same-named thinking level for each, and\n * managed codex passes the value to its app server.\n *\n * @since 4.22.0\n */\nexport const AGENT_EFFORT_LEVELS = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport type AgentEffort = (typeof AGENT_EFFORT_LEVELS)[number];\n\n/**\n * Narrow a free-form effort (the wire `agentConfig.effort`, a `skaile.yaml`\n * default) to an {@link AgentEffort}; anything else gives `undefined`, so an\n * unknown value never reaches a driver.\n */\nexport function toAgentEffort(value: unknown): AgentEffort | undefined {\n return isAgentEffort(value) ? value : undefined;\n}\n\nfunction isAgentEffort(value: unknown): value is AgentEffort {\n return (AGENT_EFFORT_LEVELS as readonly unknown[]).includes(value);\n}\n\n/**\n * Configuration passed to a driver when it is created via {@link createDriver}.\n *\n * All fields are shared across drivers; driver-specific behaviour is documented\n * per field. Fields that are silently ignored by a driver are marked accordingly.\n *\n * @docLink packages/bridge/concepts#agent-config\n */\nexport interface AgentConfig {\n /** Absolute path to the working directory the agent operates in. */\n cwd: string;\n /**\n * LLM model identifier (e.g. `\"claude-sonnet-4-5\"`, `\"gpt-4o\"`).\n *\n * The unscoped fallback: {@link AgentConfig.modelRef} is what a session\n * normally carries, and this is what a driver falls back to when no\n * registry entry resolved one.\n */\n model?: string;\n /**\n * The AI provider registry for this session — every endpoint the driver may\n * address, already merged across the catalog / user / workspace / runtime /\n * control-plane layers and in registry order.\n *\n * This is the *only* provider surface a driver reads. Entries reference\n * their credential (`credential.ref`) and never carry the secret itself;\n * the value reaches the child under `SKAILE_AIP_<ID>_KEY`\n * (`provider-materialize/credential-env.ts`), which the session boundary\n * puts in {@link AgentConfig.env}.\n *\n * Absent (or empty) means no endpoint was configured at all — the driver\n * then falls back to whatever native auth it can discover on its own (a\n * `claude` OAuth login, `codex login`, an ambient vendor key).\n */\n registry?: MergedAIProviderRegistry;\n /**\n * Model selector resolved against {@link AgentConfig.registry}:\n * `\"<providerId>/<modelId>\"`, a bare `\"<modelId>\"` (first registry entry\n * that maps it wins), or `\"@role\"`. Absent when no model was configured at\n * all — the driver then applies its own default, exactly as it does for an\n * absent `model`.\n */\n modelRef?: string;\n /**\n * The `skaile.yaml` `roles` table — role name → model selector\n * (`{default: \"anthropic/opus\", smol: \"groq/llama-3.1-8b\"}`, §9.8). It is\n * what `\"@role\"` in {@link AgentConfig.modelRef} expands through, and what\n * a driver that supports per-role models materializes natively: omp renders\n * it as `modelRoles` in its session-private `config.yml`, so `@smol` inside\n * the session reaches a different provider than `@default`.\n *\n * Resolution is lenient: a role naming an entry this registry does not have\n * is a warning, never a failure.\n */\n roles?: Record<string, string>;\n /**\n * Additional environment variables merged into the child process\n * environment. The session boundary delivers resolved registry credentials\n * here as `SKAILE_AIP_<ID>_KEY` entries; anything else the caller sets is\n * merged over the driver's own allowlist, never instead of it.\n */\n env?: Record<string, string>;\n /** Inline system prompt — written to .omp/system.md and passed via --append-system-prompt (omp driver) */\n systemPrompt?: string;\n /** Path to project .omp/ directory (PI_CODING_AGENT_DIR for omp driver) */\n agentDir?: string;\n /** SSH key path — injected as GIT_SSH_COMMAND */\n sshKeyPath?: string;\n /** Pre-assign a UUID as the session ID for a new session (claude-sdk: passed as sessionId option) */\n sessionId?: string;\n /** Resume this specific past session by UUID instead of starting fresh (claude-sdk: passed as resume option) */\n resumeSessionId?: string;\n /** Maximum agentic turns per query (claude-sdk: passed as maxTurns option) */\n maxTurns?: number;\n /** Agent name — selects a deployed sub-agent definition as the main agent identity.\n * claude-sdk: passed as `agent` option to query() → reads .claude/agents/<name>.md natively.\n * omp: ignored (omp uses agentDir/PI_CODING_AGENT_DIR instead). */\n agentName?: string;\n /** In-process SDK MCP servers for custom tool injection (Claude SDK only, ignored by other drivers) */\n mcpServers?: Record<string, unknown>;\n /** Tool restrictions from agent.yaml — applied to the main agent session */\n tools?: {\n /** Tool names that the agent is allowed to invoke. An empty array means no restriction. */\n allowed?: string[];\n /** Tool names that the agent is explicitly forbidden from invoking. */\n denied?: string[];\n };\n /** Thinking mode for Claude models: adaptive (Claude decides), enabled (always think), disabled (no thinking). */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level; each driver maps it to its own scale (see {@link AgentEffort}). */\n effort?: AgentEffort;\n /** Driver-specific configuration bag. */\n driverOptions?: DriverOptions;\n /**\n * Protocol v2 capability dispatch hooks. When present, the driver uses the\n * registry as the source of LLM tool definitions and routes invocations\n * through `capabilities.invoke()`. Absent → legacy v1 path (existing\n * mcpServers / native dispatch).\n *\n * @since 2.0.0\n */\n capabilities?: BridgeCapabilityHooks;\n /**\n * The platform's `AIProviderConfig.id` for the AI credential currently\n * provisioned into this driver. The runner reads this off `AgentConfig`\n * during 401 mediation and passes it as `configId` in\n * `request_access_token { kind: 'ai-credentials' }`. The driver itself\n * does not consume this field — only the runner uses it.\n *\n * Set by the platform agent-gateway in `ConfigureCommandV2` for mediated\n * sessions. Standalone runners (CLI / forge / Claude plugin) leave it\n * undefined; the runner falls back to surfacing the auth error to the\n * user without mediating.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Wire `aiProviderConfigId` end-to-end\".\n *\n * @since 3.3.0\n */\n aiProviderConfigId?: string;\n /**\n * Optional callback invoked by the driver when the underlying agent\n * surfaces an `authentication_error`. In Protocol v3 the runner mediates\n * the refresh via the `host.refresh_credential` capability and returns a\n * typed {@link CredentialMint}. The driver inspects the discriminator:\n *\n * - `mint.ok === true`: a fresh credential is now provisioned. The\n * driver re-attempts the in-flight prompt once.\n * - `mint.ok === false`: refresh failed (`code` carries a stable reason\n * such as `revoked`, `not-configured`, `provider-error`,\n * `backend-error`). The driver surfaces the original `AuthError` to\n * the caller.\n *\n * `args.configId` carries the platform `AIProviderConfig.id` the driver\n * was provisioned with (mirrors {@link AgentConfig.aiProviderConfigId}).\n * The runner uses it to scope the refresh to the correct AI credential.\n *\n * When omitted, the driver throws `AuthError` immediately as before\n * (standalone CLI / forge mode — there is no platform mediator to ask).\n *\n * Centralising auth-retry inside the driver means every consumer of\n * `driver.prompt(...)` (serve handler, compaction orchestrator, flow\n * orchestrator, …) gets self-healing for free — there is no per-call-site\n * wrapping.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"host.refresh_credential capability\".\n *\n * @since 3.4.0\n */\n onAuthError?: (args: { configId: string }) => Promise<CredentialMint>;\n /**\n * Optional callback invoked by the driver when a turn is blocked by an\n * upstream **usage limit** rather than a bad credential — the subscription\n * five-hour / seven-day ceiling, or any `rate_limit` the classifier\n * recognises. Called at most once per logical turn, and only after the\n * blocked attempt has already failed, so it never runs mid-turn.\n *\n * The runner implements it by asking the platform to re-resolve the seat:\n *\n * - `switched: true` — the session was repointed at a DIFFERENT AI\n * provider config and `.credentials.json` was rewritten. The driver\n * drops its query (forcing a fresh CLI spawn, which is what clears a\n * resident CLI's cached \"blocked until <reset>\" state — a hot file\n * rewrite alone does not) and replays the prompt once.\n * - `switched: false` — no alternative seat was available. The driver\n * surfaces the original limit error unchanged.\n *\n * Left unset by standalone runners (CLI / forge / Claude plugin): there is\n * no platform mediator to re-resolve a seat, so the limit error surfaces\n * exactly as it does today.\n *\n * Companion to {@link onAuthError}: that one covers 401s, this one covers\n * the rejection path, which previously reached no failover at all\n * (skaile-ai/workspaces#567, skaile-ai/platform#2976).\n *\n * @since 3.9.0\n */\n onLimitBlocked?: (ctx: LimitBlockedContext) => Promise<LimitFailoverResult>;\n /**\n * Optional fire-and-forget hook invoked when the driver observes a 401 or a\n * 429 / subscription-limit rejection from the AI provider. The runner\n * forwards it to the platform as a `provider_response_seen` event so the\n * owning `AIProviderConfig`'s live health counters can be bumped — the cron\n * health probe only samples auth, never capacity\n * (skaile-ai/workspaces#368, skaile-ai/platform#3539).\n *\n * Never awaited and never retried; the driver swallows a throwing\n * implementation so telemetry can never fail a turn.\n *\n * @since 3.9.0\n */\n onProviderResponse?: (observation: ProviderResponseObservation) => void;\n /**\n * Optional fire-and-forget hook invoked for every upstream quota-window\n * reading (claude-sdk `rate_limit_event`), not only rejections. The runner\n * forwards it as `provider_quota_observed`, which is the only quota signal\n * the platform has for a seat whose token cannot read the OAuth usage\n * endpoint (a `claude setup-token` seat).\n *\n * Never awaited and never retried; the driver swallows a throwing\n * implementation so telemetry can never fail a turn. Unlike\n * {@link onProviderResponse} it fires on every event, so dedupe at the host.\n *\n * @since 4.1.0\n */\n onProviderQuota?: (observation: ProviderQuotaObservation) => void;\n /**\n * Test-only flow driver hook. When present, the echo driver's scripted-flow\n * mode uses it to advance flow nodes deterministically (no LLM). The runner\n * injects it in `createActiveFlow`; every other driver ignores it.\n *\n * @see FlowTestDriverHook\n * @since 3.6.0\n */\n flowTestDriver?: FlowTestDriverHook;\n}\n\n/**\n * A single message in an agent conversation.\n *\n * Emitted as part of {@link AgentEvent} variants (`message_start`, `message_update`, `message_end`).\n *\n * @docLink packages/bridge/concepts#agent-message\n */\nexport interface AgentMessage {\n /** Originator of the message. */\n role: \"user\" | \"assistant\" | \"tool\";\n /** Message body — either a plain string or a list of typed content blocks. */\n content: string | ContentBlock[];\n /** Tool invocations made by the assistant in this message. */\n toolCalls?: ToolCall[];\n /** For `role === \"tool\"`: the name of the tool whose result this message carries. */\n toolName?: string;\n /** For `role === \"tool\"`: `true` when the tool returned an error. */\n isError?: boolean;\n /** Optional structured payload for tool results. */\n data?: unknown;\n /**\n * Set when a subagent produced this message: the id of the tool use that\n * runs the subagent. Absent on main-thread messages.\n */\n parentToolUseId?: string;\n}\n\n/**\n * A typed block within an {@link AgentMessage}'s content array.\n *\n * Mirrors the Anthropic content block schema but is driver-agnostic.\n *\n * @docLink packages/bridge/concepts#content-block\n */\nexport interface ContentBlock {\n /** Block discriminant. */\n type: \"text\" | \"tool_use\" | \"tool_result\" | \"thinking\";\n /** Present for `text` and `thinking` blocks. */\n text?: string;\n /** Tool use / tool result correlation ID. */\n id?: string;\n /** Tool name (present on `tool_use` blocks). */\n name?: string;\n /** Tool input arguments (present on `tool_use` blocks). */\n input?: any;\n /** Serialised tool result content (present on `tool_result` blocks). */\n content?: string;\n}\n\n/**\n * A single tool invocation made by the agent within a message.\n *\n * @docLink packages/bridge/concepts#tool-call\n */\nexport interface ToolCall {\n /** Correlation ID used to match the call with its result. */\n id: string;\n /** Name of the tool being invoked. */\n name: string;\n /** Arguments passed to the tool. */\n input: any;\n}\n\n/**\n * Error classification for agent failures.\n *\n * Used to determine whether a failure is retryable and to surface actionable\n * hints to the user. See `bridge/CLAUDE.md` for the full category-to-behaviour matrix.\n *\n * @see AgentError\n * @docLink packages/bridge/concepts#error-category\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"account\"\n | \"rate_limit\"\n | \"model\"\n | \"network\"\n | \"config\"\n | \"process\"\n | \"validation\"\n | \"unknown\";\n\n/**\n * Structured error payload emitted inside the `error` {@link AgentEvent}.\n *\n * Consumers should inspect `retryable` before deciding to surface a retry button,\n * and `hint` to provide an actionable message to the user.\n *\n * @docLink packages/bridge/concepts#agent-error\n */\nexport interface AgentError {\n /** Human-readable error description. */\n message: string;\n /** Coarse failure classification used for retry logic and telemetry. */\n category: ErrorCategory;\n /** HTTP status code if the error originated from an API response. */\n statusCode?: number;\n /** `true` when the caller may safely retry the same operation. */\n retryable: boolean;\n /** Short actionable advice suitable for display in the UI. */\n hint?: string;\n}\n\n/**\n * Metadata for a slash command exposed by the active agent runtime.\n *\n * @docLink packages/bridge/concepts#slash-command-info\n */\nexport interface SlashCommandInfo {\n /** Command name without the leading slash (e.g. `\"compact\"`). */\n name: string;\n /** One-line description shown in command pickers. */\n description: string;\n /** Placeholder text describing what argument the command expects. */\n argumentHint?: string;\n}\n\n/**\n * Discriminated union of all events emitted by a driver on the `'agent-event'` channel.\n *\n * @remarks\n * Consumers listen via `driver.on('agent-event', (event: AgentEvent) => ...)`.\n * The `[k: string]: any` index signature on most variants allows drivers to attach\n * driver-specific fields (e.g. `_textDelta`) without breaking the union.\n *\n * @docLink packages/bridge/concepts#agent-event\n */\nexport type AgentEvent =\n | { type: \"message_start\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_update\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_end\"; message: AgentMessage; [k: string]: any }\n /**\n * Takes back `text`, the unfinished tail of streamed `_textDelta`s, before the\n * driver replays an abandoned attempt. Always a suffix of what was streamed\n * since the last completed assistant message; see `TextRetractEvent` in the types package.\n */\n | { type: \"message_retract\"; text: string; [k: string]: any }\n | { type: \"turn_end\"; toolResults?: AgentMessage[]; [k: string]: any }\n | { type: \"agent_end\"; [k: string]: any }\n /** A background task started in the running turn; see `BackgroundTaskStartedEvent`. */\n | { type: \"background_task_started\"; taskId: string; [k: string]: any }\n /** A turn the driver was not prompted for began; see `SelfTurnStartedEvent`. */\n | { type: \"self_turn_started\"; taskIds: string[]; [k: string]: any }\n | {\n type: \"result\";\n subtype: string;\n summary?: string;\n costUsd?: number;\n /** Per-turn token usage when the driver tracks it. Added in 3.1.0. */\n tokens?: TokenUsage;\n /** Per-turn usage keyed by model, subagent calls included. Added in 3.11.0. */\n modelUsage?: Record<string, ModelTokenUsage>;\n /** Prompt size of the turn's last main-thread API call. Added in 3.11.0. */\n contextTokens?: number;\n /** Context window of the main model, in tokens. Added in 3.11.0. */\n contextWindow?: number;\n errors?: string[];\n [k: string]: any;\n }\n | {\n type: \"error\";\n error: string;\n detail?: AgentError;\n fatal?: boolean;\n /** Set (with `fatal: false`) when the driver replays the prompt in place; see `ErrorEvent.retrying`. */\n retrying?: boolean;\n retryReason?: ErrorRetryReason;\n /** Usage of a failed provider turn, when reported. */\n tokens?: TokenUsage;\n /** Failed-turn usage keyed by the actual model. */\n modelUsage?: Record<string, ModelTokenUsage>;\n contextTokens?: number;\n contextWindow?: number;\n [k: string]: any;\n }\n | {\n type: \"tool_call\";\n name?: string;\n tool?: { name: string };\n /** Set when a subagent made the call. */\n parentToolUseId?: string;\n [k: string]: any;\n }\n | { type: \"tool_execution_end\"; toolName?: string; parentToolUseId?: string; [k: string]: any }\n | { type: \"commands_available\"; commands: SlashCommandInfo[] }\n | { type: \"session_info\"; driverSessionId: string; sessionFile?: string }\n | { type: \"ui_render\"; [k: string]: any }\n | { type: \"ui_render_update\"; [k: string]: any }\n | { type: \"ui_clear\"; [k: string]: any }\n // Phase 3 (resume cascade) — driver-emitted resume outcome.\n | {\n type: \"resume_failed\";\n resumeSessionId: string;\n reason:\n | \"signature_mismatch\"\n | \"model_mismatch\"\n | \"jsonl_lost\"\n | \"jsonl_poisoned\"\n | \"native_state_unavailable\";\n [k: string]: any;\n };\n\n/** The settings a live reconfigure may change. */\nexport type ReconfigurePatch = Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>;\n\n/**\n * What a driver now holds for the fields of an accepted reconfigure. `modelRef`\n * is the registry selector the model was scoped to; it is absent when the\n * session has none. A host remembers exactly this, never the raw patch.\n */\nexport interface ReconfigureApplied {\n model?: string;\n modelRef?: string;\n thinking?: AgentConfig[\"thinking\"];\n effort?: AgentConfig[\"effort\"];\n}\n\n/**\n * Result of `AgentDriver.reconfigure()`. `ok: true` means effective from the\n * next turn (live switch, query recycle or respawn); a driver that cannot\n * promise that answers `ok: false` instead.\n *\n * - `not_supported`: the driver cannot change settings live.\n * - `model_not_on_provider`: the session's AI provider entry does not list the\n * model (`providerId` names the entry).\n * - `rejected`: the running process refused the change; the driver config is\n * unchanged.\n *\n * @category Bridge\n */\nexport type ReconfigureOutcome =\n | { ok: true; applied: ReconfigureApplied }\n | {\n ok: false;\n code: \"not_supported\" | \"model_not_on_provider\" | \"rejected\";\n message: string;\n providerId?: string;\n };\n\n/**\n * A reconfigure the driver answered `ok` (it landed mid-turn) and then refused\n * at the next turn boundary. The driver already rolled its config back;\n * `requested` is what was asked, `restored` what it holds again. Emitted as the\n * driver event `'reconfigure-rollback'`.\n */\nexport interface ReconfigureRollback {\n message: string;\n requested: ReconfigureApplied;\n restored: ReconfigureApplied;\n}\n\n/** Rejection message of a driver asked to run a turn under a tool allowlist it cannot enforce. */\nexport const TOOL_ALLOWLIST_UNSUPPORTED = \"This agent harness cannot enforce a tool allowlist\";\n\n/**\n * Abstract base class for agent drivers.\n *\n * Wraps an LLM coding agent behind a single `prompt()` interface.\n * All drivers emit `'agent-event'` with {@link AgentEvent} payloads.\n *\n * @remarks\n * Subclasses must implement `start`, `prompt`, `abort`, `kill`, and `isRunning`.\n * Implementations should never emit an event name other than `'agent-event'` as\n * the public streaming channel — internal events (`'ready'`, `'exit'`, etc.) are\n * driver-private. The one other public event is `'reconfigure-rollback'` (a\n * {@link ReconfigureRollback}): a live reconfigure the driver had accepted and\n * then refused at the turn boundary, already rolled back in the driver.\n *\n * @example\n * ```ts\n * const driver = createDriver('omp', config);\n * driver.on('agent-event', (event) => console.log(event.type));\n * await driver.start();\n * await driver.prompt('Refactor the auth module');\n * driver.kill();\n * ```\n *\n * @docLink packages/bridge/concepts#agent-driver\n */\nexport abstract class AgentDriver extends EventEmitter {\n /** Static metadata describing this driver's capabilities. */\n abstract readonly driverInfo: DriverInfo;\n\n /**\n * Initialises the driver's harness — spawns the child process (omp) or loads\n * the SDK module (claude-sdk). Resolves when the harness is ready to accept\n * prompts. Idempotent: calling `start()` on an already-running driver is a no-op.\n *\n * @throws {Error} When the harness binary is missing or the SDK cannot be loaded.\n */\n abstract start(): Promise<void>;\n\n /**\n * Sends a user message to the agent and resolves when the agent's turn completes\n * (i.e. after the `agent_end` event has been emitted).\n *\n * @param message - Plain-text user prompt to send to the agent.\n * @throws {Error} When the driver is not running or the underlying harness reports a fatal error.\n */\n abstract prompt(message: string): Promise<void>;\n\n /**\n * Preserve text-only callers; drivers must explicitly support attachments.\n * A `toolAllowlist` is refused here: only a driver that overrides\n * {@link enforcesToolAllowlist} may run a restricted turn.\n */\n promptInput(input: AgentPromptInput): Promise<void> {\n if (input.toolAllowlist !== undefined)\n return Promise.reject(new Error(TOOL_ALLOWLIST_UNSUPPORTED));\n if (input.attachments?.length) return Promise.reject(new Error(\"Structured input unsupported\"));\n return this.prompt(input.text);\n }\n\n /**\n * Whether {@link promptInput} enforces `AgentPromptInput.toolAllowlist` for\n * the whole turn, subagents included. A driver that answers `false` must\n * reject an input carrying one; the runner refuses such a prompt before it\n * reaches the driver.\n */\n get enforcesToolAllowlist(): boolean {\n return false;\n }\n\n /**\n * The names in `allowlist` this driver does not recognize as a tool it could\n * offer. The runner refuses a prompt whose allowlist names any, rather than\n * guess. A driver that does not enforce allowlists recognizes none.\n */\n unknownAllowlistedTools(allowlist: readonly string[]): string[] {\n return [...allowlist];\n }\n\n /** Managed replies never fall back to a new prompt after a request has settled. */\n get acceptsReplyAsPrompt(): boolean {\n return true;\n }\n\n /**\n * Sends an in-band abort signal to the agent, requesting it to stop the current\n * turn without terminating the process. The driver remains usable after `abort()`.\n *\n * @remarks Only meaningful when `driverInfo.supportsInBandAbort` is `true`.\n * For other drivers, prefer `kill()` followed by creating a new driver instance.\n */\n abstract abort(): Promise<void>;\n\n /**\n * Terminates the agent harness immediately (SIGTERM for subprocess drivers,\n * `close()` for in-process drivers). The driver instance must not be reused\n * after `kill()`.\n */\n abstract kill(): void;\n\n /** Stop the driver and await owned process/state cleanup when the harness supports it. */\n async dispose(): Promise<void> {\n this.kill();\n }\n\n /** `true` when the harness is alive and able to accept new prompts. */\n abstract get isRunning(): boolean;\n\n /** Optional provider-native session/thread identifier for resume support. */\n get runtimeSessionId(): string | undefined {\n return undefined;\n }\n\n /** Slash commands discovered from the agent runtime. Override in drivers that support introspection. */\n getSlashCommands(): SlashCommandInfo[] {\n return [];\n }\n\n // ── Interactive questions (AskUserQuestion) ──────────────────────────────\n\n /**\n * `true` while the driver is paused on an interactive question and waiting\n * for the user's answer rather than a new prompt. The runner routes a\n * `reply` command to {@link answerQuestion} instead of {@link prompt} when\n * this returns `true`. Drivers without interactive-question support return\n * `false` (the default), so a `reply` falls back to `prompt`.\n */\n hasPendingQuestion(): boolean {\n return false;\n }\n\n /**\n * Deliver the user's answer to the question the driver is currently paused\n * on. This resumes the in-flight turn — it does NOT start a new one. When a\n * single tool call asks several questions, the driver resolves the underlying\n * call only once every sub-question has an answer.\n *\n * @param answer - The user's reply text (an option label, free text, or for\n * multi-select a comma-joined list).\n * @param question - The sub-question this answers, verbatim from the\n * `question` event that asked it. Supply it whenever the host lets the user\n * answer out of order — without it the answer fills the next unanswered\n * slot in order, which silently mismatches a non-sequential reply.\n * @returns `true` when the answer was consumed by a pending question; `false`\n * when no question was pending (caller should treat the reply as a prompt).\n */\n answerQuestion(answer: string, question?: string, requestId?: string): boolean {\n void requestId;\n void answer;\n void question;\n return false;\n }\n\n /**\n * Apply this driver's rule for a new prompt that meets a pending question,\n * ahead of the prompt itself. The runner queues a prompt behind the turn in\n * flight, so a turn paused on a question would otherwise hold that prompt\n * until the user answered. Drivers whose `prompt()` cancels the question\n * (claude-sdk, omp) do the same here; the default keeps the question.\n */\n supersedePendingQuestion(): void {\n // No-op: a driver without this rule keeps the question pending.\n }\n\n // ── Live reconfiguration ────────────────────────────────────────────────\n\n /**\n * Live-update driver configuration. `ok: true` means effective from the next\n * turn: the next turn runs on the new settings, by live switch, query recycle\n * or respawn, and the host needs no restart. A turn in progress finishes on\n * the old settings. Only model/thinking/effort are reconfigurable mid-session.\n *\n * Drivers that can honour that promise build a `ReconfigureLedger` and\n * delegate to it; it owns the model scope rule, ordering, drift and rollback.\n * The base implementation answers `not_supported`.\n */\n reconfigure(patch: ReconfigurePatch): Promise<ReconfigureOutcome> {\n const fields = Object.keys(patch).join(\", \");\n return Promise.resolve({\n ok: false,\n code: \"not_supported\",\n message: `The ${this.driverInfo.id} driver cannot change ${fields} live; the change applies when the session next starts.`,\n });\n }\n\n /**\n * Returns the model identifier currently configured on this driver.\n * Subclasses that store config locally should override this.\n */\n getModel(): string | undefined {\n return undefined;\n }\n\n // ── Compaction support ──────────────────────────────────────────────────\n\n /**\n * `Date.now()` of the harness's most recent sign of life, counting messages\n * that emit no `agent-event` (thinking deltas, rate-limit telemetry, API\n * retries). A stall check reads it alongside the events it sees. `null` when\n * the driver does not track it.\n */\n lastActivityAt(): number | null {\n return null;\n }\n\n /**\n * Returns the token usage from the most recent completed turn.\n * Returns `null` if usage data is unavailable (e.g. driver doesn't track it).\n *\n * Widened in 3.1.0 to return the full `TokenUsage` shape (input / output /\n * cache-read / cache-creation / reasoning). All fields are optional so\n * drivers can populate just what their provider reports. Existing callers\n * that read only `inputTokens` / `outputTokens` keep working — those fields\n * are still present and carry the same semantics as before.\n */\n getTokenUsage(): TokenUsage | null {\n return null;\n }\n\n /**\n * Prompt tokens occupying the context window as of the most recent API\n * request — i.e. how full the context actually is right now.\n *\n * Deliberately NOT the same number as {@link getTokenUsage}, whose usage is\n * cumulative over every API call in the turn and therefore overstates the\n * context by 10-40x on any multi-tool turn. Callers measuring context fill\n * (compaction thresholds) must prefer this; callers billing a turn\n * (usage ledgers, the `finished` event) must keep using `getTokenUsage()`.\n *\n * Returns `null` both when the driver cannot report a per-call figure at all\n * and when it can but has no reading yet. Falling back to `getTokenUsage()`\n * is safe in either case only because a driver clears the two in lockstep: no\n * reading means no API call landed, so there is no cumulative usage to\n * overstate. A driver implementing this must preserve that invariant.\n */\n getContextTokens(): number | null {\n return null;\n }\n\n /**\n * Returns the model's context window size in tokens.\n * Returns `null` if unknown.\n */\n getContextWindow(): number | null {\n return null;\n }\n\n /**\n * What the driver can measure natively about its context window, in the\n * neutral {@link DriverContextReport} shape, or `null` when it measures\n * nothing beyond {@link getContextTokens} / {@link getContextWindow}.\n *\n * `detail: \"full\"` (the default) may be expensive — claude-sdk issues\n * `count_tokens` requests — so the runner asks for it only when a host\n * requests a measured breakdown; `\"summary\"` must make no provider call and\n * is what the per-turn snapshot uses. Implementations must not throw for\n * \"unsupported\"; a rejection means the measurement itself failed and the\n * runner falls back to estimates.\n */\n async getContextUsageReport(_opts?: {\n detail?: ContextUsageDetail;\n }): Promise<DriverContextReport | null> {\n return null;\n }\n\n /**\n * Returns the list of models available to this driver without starting a session.\n * Drivers that can enumerate their own models override this method.\n * Returns an empty array by default.\n */\n async listModels(): Promise<ModelEntry[]> {\n return [];\n }\n\n /**\n * Closes the current conversation session and prepares for a fresh start.\n * The next `prompt()` call will begin a new session without prior history.\n * The driver remains usable after `resetSession()`.\n */\n abstract resetSession(): Promise<void>;\n\n // ── Telemetry ─────────────────────────────────────────────────────────────\n\n protected _telemetry?: TelemetryProvider;\n protected _activeTrace?: Trace;\n protected _activeTurnSpan?: Span;\n private _turnStartTime?: number;\n\n /**\n * Attach a telemetry provider and active trace to this driver.\n * Called by the runner after creating the driver but before start().\n */\n setTelemetry(provider: TelemetryProvider, trace: Trace): void {\n this._telemetry = provider;\n this._activeTrace = trace;\n }\n\n /**\n * Begin a turn span. Called by the runner before prompt().\n * Pass a parent span (e.g. the turn span from the orchestrator) for nesting.\n * Returns the span so the runner can annotate it further.\n */\n beginTurnSpan(\n parent?: Trace | Span,\n attrs?: Record<string, string | number | boolean>,\n ): Span | undefined {\n if (!this._telemetry || !this._activeTrace) return undefined;\n this._turnStartTime = Date.now();\n this._activeTurnSpan = this._telemetry.startSpan(parent ?? this._activeTrace, {\n name: \"llm_generation\",\n kind: \"llm_generation\",\n attributes: attrs,\n });\n return this._activeTurnSpan;\n }\n\n /**\n * End the current turn span with generation data.\n * Called by the runner after agent_end. Model and provider are passed\n * explicitly — the driver base class does not access config directly.\n */\n endTurnSpan(result?: {\n model?: string;\n provider?: string;\n inputTokens?: number;\n outputTokens?: number;\n stopReason?: string;\n error?: string;\n }): void {\n if (!this._telemetry || !this._activeTurnSpan) return;\n const durationMs = this._turnStartTime ? Date.now() - this._turnStartTime : 0;\n\n if (result?.inputTokens !== undefined || result?.outputTokens !== undefined) {\n this._telemetry.logGeneration(this._activeTurnSpan, {\n model: result?.model ?? \"unknown\",\n provider: result?.provider ?? \"unknown\",\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n durationMs,\n stopReason: result.stopReason,\n });\n }\n\n this._telemetry.endSpan(this._activeTurnSpan, {\n status: result?.error ? \"error\" : \"ok\",\n error: result?.error,\n attributes: { \"skaile.turn.duration_ms\": durationMs },\n });\n\n this._activeTurnSpan = undefined;\n this._turnStartTime = undefined;\n }\n}\n\n/**\n * Factory function signature registered in the driver registry.\n *\n * @param config - Configuration for the new driver instance.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @docLink packages/bridge/concepts#driver-factory\n */\nexport type DriverFactory = (config: AgentConfig) => AgentDriver;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../core/src/asset-roots.ts","../core/src/lock.ts","../core/src/manifest-yaml-editor.ts","../core/src/conformance.ts","../core/src/patch.ts","../core/src/provider-registry-files.ts","../core/src/settings.ts","../core/src/package-manager.ts","../core/src/driver-sdk.ts","../core/src/agent-prompt-sections.ts","../core/src/workspace-yaml-editor.ts"],"names":["existsSync","join","path","readFileSync","writeFileSync","dirname","resolve","parse","mkdirSync","stringify","SKAILE_DIR","fileURLToPath","parseDocument","Document","isMap","isSeq"],"mappings":";;;;;;;;;;;;;;;;;AA2BO,SAAS,iBAAA,GAA4B;AAC1C,EAAA,OAAO,IAAA,CAAK,eAAA,EAAgB,EAAG,WAAW,CAAA;AAC5C;AAUO,SAAS,iBAAA,GAA4B;AAC1C,EAAA,IAAI,QAAQ,GAAA,CAAI,oBAAA,SAA6B,OAAA,CAAQ,OAAA,CAAQ,IAAI,oBAAoB,CAAA;AACrF,EAAA,OAAO,iBAAA,EAAkB;AAC3B;AAGO,IAAM,uBAAA,GAA0B;AAOhC,SAAS,gBAAA,GAA2B;AACzC,EAAA,OAAO,IAAA,CAAK,iBAAA,EAAkB,EAAG,uBAAuB,CAAA;AAC1D;AAWA,SAAS,YAAA,CAAa,eAAwB,UAAA,EAA8B;AAC1E,EAA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AAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AACzB,MAAA,IAAID,KAAAA,CAAM,IAAI,CAAA,IAAM,IAAA,CAAiB,IAAI,KAAK,CAAA,KAAM,MAAM,GAAA,EAAK;AAC7D,QAAA,IAAA,CAAK,IAAI,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AACtC,QAAA,KAAA,GAAQ,IAAA;AACR,QAAA;AAAA,MACF;AAAA,IACF;AACA,IAAA,IAAI,CAAC,OAAO,IAAA,CAAK,GAAA,CAAI,KAAK,GAAA,CAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,EACjD;AAAA;AAAA,EAGA,eAAe,GAAA,EAAsB;AACnC,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,aAAa,IAAI,CAAA;AAC3C,IAAA,IAAI,CAAC,IAAA,IAAQ,CAACC,KAAAA,CAAM,IAAI,GAAG,OAAO,KAAA;AAClC,IAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AAC1C,MAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AACzB,MAAA,IAAID,MAAM,IAAI,CAAA,IAAM,KAAiB,GAAA,CAAI,KAAK,MAAM,GAAA,EAAK;AACvD,QAAA,IAAA,CAAK,OAAO,CAAC,CAAA;AACb,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA;AAAA,EAKA,IAAI,QAAA,GAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,EACd;AACF","file":"chunk-4QINFQ27.js","sourcesContent":["/**\n * asset-roots.ts — the single definition of *where* skaile-owned content lives.\n *\n * The policy sits in `core/` rather than next to either of its callers because\n * both layers that need it already depend on `core/`: the CLI's discovery\n * surfaces (`flow list`, completions, skill walking) and the flow connector's\n * resolution surfaces under `factory-assets/` (`resume`, sub-flow targets,\n * `serve`). Keeping it in `cli/` instead would force a `factory-assets → cli`\n * import, which is a real module cycle — and duplicating it there is exactly\n * how the two lists drifted apart in the first place.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { globalSkaileDir } from \"./cache-paths.js\";\nimport { SUPPORTED_DRIVER_TARGETS } from \"./driver-targets.js\";\nimport { factoryAssetRoots } from \"./runtime-assets.js\";\nimport { deployedBase } from \"./store.js\";\n\n/**\n * The library checkouts directory before any environment override — the value\n * `getConfigDefaults()` reports as the *default*, which must stay independent of\n * `SKAILE_LIBRARIES_DIR` so a config file can still be seen to override it.\n * Callers that want the effective directory want {@link resolveLibraryDir}.\n *\n * @docLink packages/core/concepts#discovery\n */\nexport function defaultLibraryDir(): string {\n return join(globalSkaileDir(), \"libraries\");\n}\n\n/**\n * Resolve the active library checkouts directory.\n *\n * `SKAILE_LIBRARIES_DIR` overrides the default `$SKAILE_HOME/libraries`\n * (`~/.skaile/libraries` when `SKAILE_HOME` is unset).\n *\n * @docLink packages/core/concepts#discovery\n */\nexport function resolveLibraryDir(): string {\n if (process.env.SKAILE_LIBRARIES_DIR) return resolve(process.env.SKAILE_LIBRARIES_DIR);\n return defaultLibraryDir();\n}\n\n/** Folder name, under the library checkouts directory, that `skaile install` fills. */\nexport const GLOBAL_INSTALL_DIR_NAME = \"installed\";\n\n/**\n * The folder a global pointer-only install (`skaile install kind:@pub/name#ver`)\n * writes asset bytes into: `<libraries dir>/installed`. It holds store assets,\n * not authored ones, so it must never be adopted as an owner library.\n */\nexport function globalInstallDir(): string {\n return join(resolveLibraryDir(), GLOBAL_INSTALL_DIR_NAME);\n}\n\n/**\n * The skaile-owned install roots for one scope — the parent of the directory\n * `skaile install` / `skaile add` deploy flows into.\n *\n * Derived through `deployedBase`, the same function the installer calls, so\n * discovery cannot drift from where the bytes land. Every driver target maps\n * `flow` to the same `.skaile/flows`, so the three results collapse in the\n * caller's `Set`.\n */\nfunction installRoots(globalInstall: boolean, projectDir: string): string[] {\n return SUPPORTED_DRIVER_TARGETS.map((target) =>\n dirname(deployedBase(\"flow\", target, globalInstall, projectDir)),\n );\n}\n\n/**\n * All content roots that skill / flow discovery should walk, in priority order,\n * filtered to those that exist on disk and de-duplicated.\n *\n * Four layers, in this order:\n * 1. The project-local install root `<projectDir>/.skaile/`, where\n * `skaile install` / `skaile add` deploy flows.\n * 2. The first-party `factory-assets/` roots from the shared `factoryAssetRoots()`\n * helper — the `SKAILE_FACTORY_ASSETS_DIR` override layer (when set) ahead of\n * the bundled tree (in-repo source in dev, `dist/factory-assets/` after\n * install). No monorepo special-case.\n * 3. The user-library dir `~/.skaile/libraries/`.\n * 4. The user-global install root `~/.skaile/`.\n *\n * Order is significant: `findSkills` / flow discovery dedupe first-root-wins, so\n * the env override shadows the bundled tree on a name clash. The project-local\n * install root leads because `deployAll` applies `patches:` to the deployed copy\n * — that copy, not the factory original, is the project's effective flow.\n *\n * Only `flow` installs into skaile's own `.skaile/` tree; every other asset kind\n * installs into the driver's directory (`.claude/`, `.omp/`, `.codex/`), which\n * the driver reads natively and skaile deliberately does not enumerate. So the\n * roots below are exactly the skaile-owned ones — an invariant asserted by\n * `cli/tests/installed-asset-roots.test.ts`.\n *\n * This is the discovery surface used by `findSkills`, flow discovery, and the\n * completion resolvers; flow *resolution* walks these same roots behind\n * `flowLookupRoots`, which only prepends the project's own `ai-assets/` tree.\n *\n * @param projectDir - Project directory whose local install root to include\n * (default: `process.cwd()`).\n * @docLink packages/core/concepts#discovery\n */\nexport function aiResourceRoots(projectDir: string = process.cwd()): string[] {\n const roots: string[] = [\n ...installRoots(false, projectDir),\n ...factoryAssetRoots(),\n // resolveLibraryDir honors SKAILE_LIBRARIES_DIR (the authoring side does too),\n // so a custom-dir library is visible to discovery instead of being missed.\n resolveLibraryDir(),\n ...installRoots(true, projectDir),\n ];\n return [...new Set(roots)].filter((r) => existsSync(r));\n}\n","/**\n * Lock file I/O and integrity verification (schema v4).\n *\n * The lock file (skaile.lock.yaml) captures the complete resolved state: every\n * asset keyed by its canonical ref `<kind>:@<publisher>/<name>#<version>`, the\n * upstream source + commit it resolved from, a per-file + composite content\n * hash for drift detection, and whether an `overrides[]` entry pinned it. A\n * top-level `sources:` block records every contributing source URL at its\n * resolved commit.\n *\n * Old v1 lockfiles (`lockfile_version: 1`, `repositories:`) are rejected with a\n * clear regenerate-from-scratch error.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport type {\n LockEntry,\n LockFile,\n LockLibraryOrigin,\n LockPluginEntry,\n LockSourceEntry,\n} from \"./models.js\";\nimport { parseAssetRefLoose } from \"./models.js\";\nimport { compositeSha256, sha256Hex } from \"./publish-manifest.js\";\nimport type { ProvenanceCandidate } from \"./walker.js\";\n\n/**\n * The `schema_version` every lock is written with, whatever origins it holds. A lock read with\n * the older `3` loads unchanged and is rewritten as `4` by the next `add` / `install` / `update`.\n */\nexport const LOCK_SCHEMA_VERSION = 4;\n\n// ── Lock file I/O ────────────────────────────────────────────────────────────\n\n/**\n * Deep copy of `value` with every object's keys in sorted order (arrays keep their order: a\n * `files` list or a `sources` list is sorted by the code that builds it). Equal content then\n * serializes to equal bytes, whichever code path (`add`, `install`, `update`) built the lock.\n */\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n const v = (value as Record<string, unknown>)[key];\n if (v !== undefined) out[key] = canonicalize(v);\n }\n return out;\n }\n return value;\n}\n\n/** Lock YAML in canonical order: the version and timestamp first, then every key sorted. */\nfunction stringifyLock(data: LockFile | Record<string, unknown>): string {\n const { schema_version, locked_at, ...rest } = data as Record<string, unknown>;\n const head: Record<string, unknown> = {};\n if (schema_version !== undefined) head.schema_version = schema_version;\n if (locked_at !== undefined) head.locked_at = locked_at;\n return stringify(\n { ...head, ...(canonicalize(rest) as Record<string, unknown>) },\n { lineWidth: 120 },\n );\n}\n\n/**\n * Serialize a `LockFile` to YAML (keys in canonical sorted order) and write it to disk, unless\n * the file already holds the same content apart from `locked_at` and key order. An unchanged\n * lock keeps its bytes (and its `locked_at`), so a no-op `install`, also the first one after\n * `add`, does not dirty a committed lock.\n *\n * @param lockPath - Absolute path to write the lock file (e.g. `skaile.lock.yaml`)\n * @param data - Lock file data to serialize\n * @returns `true` when the file was written, `false` when it already matched\n * @docLink packages/core/api-reference#write-lock\n */\nexport function writeLock(lockPath: string, data: LockFile): boolean {\n const next = stringifyLock(data);\n if (existsSync(lockPath)) {\n try {\n const prev = parse(readFileSync(lockPath, \"utf8\"));\n if (prev && typeof prev === \"object\" && typeof prev.locked_at === \"string\") {\n const same = stringifyLock({ ...prev, locked_at: data.locked_at });\n if (same === next) return false;\n }\n } catch {\n // Unreadable lock: rewrite it.\n }\n }\n writeFileSync(lockPath, next);\n return true;\n}\n\n/**\n * Read and parse a lock file from disk.\n *\n * @param lockPath - Absolute path to the lock file\n * @returns Parsed `LockFile`, or `null` if the file is missing or unparseable\n * @throws When the file is a legacy v1 lock — the shape changed and it must be regenerated.\n * @docLink packages/core/api-reference#read-lock\n */\nexport function readLock(lockPath: string): LockFile | null {\n if (!existsSync(lockPath)) return null;\n let raw: unknown;\n try {\n raw = parse(readFileSync(lockPath, \"utf8\"));\n } catch {\n return null;\n }\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n if (r.schema_version !== 3 && r.schema_version !== 4) {\n throw new Error(\n \"outdated lockfile schema detected — the lockfile shape changed. \" +\n \"Regenerate: `rm skaile.lock.yaml && skaile install`.\",\n );\n }\n return r as unknown as LockFile;\n}\n\n// ── Hashing ──────────────────────────────────────────────────────────────────\n\n/**\n * Compute the SHA-256 hash of a file's content (hex digest, no prefix).\n *\n * @param filePath - Absolute path to the file\n * @returns Hex-encoded SHA-256 hash string\n * @docLink packages/core/api-reference#compute-hash\n */\nexport function computeHash(filePath: string): string {\n return sha256Hex(readFileSync(filePath));\n}\n\n// ── Lock file construction ───────────────────────────────────────────────────\n\n/** One asset resolved from a registered library, as input to {@link buildLibraryLockEntries}. */\nexport interface LibraryLockInput {\n kind: string;\n /** Bare publisher (no `@` scope sigil). */\n publisher: string;\n name: string;\n /** Library-side origin: library name, version and (when indexed) content hash. */\n library: LockLibraryOrigin;\n}\n\n/**\n * Build library-origin lock entries keyed by canonical ref\n * `<kind>:@<publisher>/<name>#<library version>`.\n *\n * A library is a local authoring place, not a git source: the entry carries no\n * `source` / `files`, only the `library` marker `installLocked` restores from.\n *\n * @param inputs - Assets resolved from libraries.\n * @returns Lock entries ready to merge into a `LockFile.assets` map.\n */\nexport function buildLibraryLockEntries(inputs: LibraryLockInput[]): Record<string, LockEntry> {\n const assets: Record<string, LockEntry> = {};\n for (const i of inputs) {\n const key = `${i.kind}:@${i.publisher}/${i.name}#${i.library.version}`;\n const library: LockLibraryOrigin = { name: i.library.name, version: i.library.version };\n if (i.library.sha256) library.sha256 = i.library.sha256;\n if (i.library.url) library.url = i.library.url;\n if (i.library.installed) library.installed = i.library.installed;\n assets[key] = {\n sha256: i.library.sha256 ?? \"\",\n files: [],\n override_applied: false,\n library,\n };\n }\n return assets;\n}\n\n/**\n * Build a v4 `LockFile` from the resolver's output.\n *\n * Assets are keyed by canonical ref `<kind>:@<publisher>/<name>#<version>`; the\n * top-level `sources:` block lists every contributing source URL pinned to its\n * resolved commit. Library-origin assets (see {@link buildLibraryLockEntries})\n * are merged into `assets` but never contribute a `sources:` row.\n *\n * @param resolved - Resolved provenance candidates (the resolver's `resolved` array).\n * @param overridesApplied - Canonical refs that an `overrides[]` entry pinned.\n * @param libraryAssets - Library-origin entries to merge in (optional).\n * @returns Complete `LockFile` ready for serialization (always `schema_version` 4).\n * @docLink packages/core/api-reference#build-lock-file\n */\nexport function buildLockFile(\n resolved: ProvenanceCandidate[],\n overridesApplied: Set<string>,\n libraryAssets: Record<string, LockEntry> = {},\n): LockFile {\n const assets: Record<string, LockEntry> = {};\n\n for (const c of resolved) {\n const canonicalRef = `${c.kind}:@${c.publisher}/${c.name}#${c.version}`;\n assets[canonicalRef] = {\n sha256: c.sha256,\n source: { url: c.sourceUrl, commit: c.commit },\n files: c.files,\n override_applied: overridesApplied.has(canonicalRef),\n ...lockRequires(c),\n };\n }\n return {\n // One schema version whatever the origins: a source-only lock used to flip between 3 and 4\n // when a library-origin entry came or went. CLIs that predate library origin gate on `=== 3`\n // and reject a 4 with the regenerate hint instead of crashing on `entry.source.url`.\n schema_version: LOCK_SCHEMA_VERSION,\n locked_at: new Date().toISOString(),\n assets: { ...assets, ...libraryAssets },\n sources: sourcesOfAssets(assets),\n };\n}\n\n/**\n * The `requires:` of the lock entry of a store candidate: its catalog row's requirements as\n * sorted, version-less `kind:@publisher/name` (a requirement without a publisher takes the\n * candidate's). `{}` when the store listed none.\n */\nfunction lockRequires(c: ProvenanceCandidate): Pick<LockEntry, \"requires\"> {\n const refs = new Set<string>();\n for (const dep of c.storeRequires ?? []) {\n // A bare `kind:name` inherits the declaring asset's publisher.\n const bare = /^([^:@#/\\s]+):([^@#/\\s][^#\\s]*)(#.*)?$/.exec(dep);\n const ref = parseAssetRefLoose(\n bare ? `${bare[1]}:@${c.publisher}/${bare[2]}${bare[3] ?? \"\"}` : dep,\n );\n if (!ref) continue;\n refs.add(`${ref.kind}:@${(ref.publisher ?? c.publisher).replace(/^@/, \"\")}/${ref.name}`);\n }\n return refs.size > 0 ? { requires: [...refs].sort() } : {};\n}\n\n/**\n * The top-level `sources:` list for a set of locked assets: one row per source URL, sorted by\n * URL. When assets of one URL are locked at different commits (store assets added one by one\n * from several commits of one repo), the row carries the commit of the asset whose canonical\n * ref sorts first, so `add` (which merges into the previous lock) and `install` (which rebuilds\n * the lock from every declared asset) write the same row whatever order the assets arrived in.\n */\nfunction sourcesOfAssets(assets: Record<string, LockEntry>): LockSourceEntry[] {\n const byUrl = new Map<string, LockSourceEntry>();\n for (const key of Object.keys(assets).sort()) {\n const source = assets[key]?.source;\n if (source && !byUrl.has(source.url)) {\n byUrl.set(source.url, { url: source.url, commit: source.commit });\n }\n }\n return [...byUrl.values()].sort((a, b) => a.url.localeCompare(b.url));\n}\n\n/**\n * Merge a freshly built lock into the previous one: a superset write that never\n * drops existing entries or the reconciler's `plugins` slice.\n *\n * A fresh entry (any origin: source, store or library) supersedes older entries\n * of the same kind/publisher/name (a different pinned version or commit), else\n * both versions would stay locked.\n *\n * @param prev - The lock currently on disk, or `null` when there is none.\n * @param fresh - The lock built for this install.\n */\nexport function mergeLockFile(prev: LockFile | null, fresh: LockFile): LockFile {\n if (!prev) return fresh;\n const sources = new Map(prev.sources.map((s) => [s.url, s]));\n for (const s of fresh.sources) sources.set(s.url, s);\n const assets = { ...prev.assets };\n for (const key of Object.keys(fresh.assets)) {\n const freshId = identityOfLockKey(key);\n if (!freshId) continue;\n for (const old of Object.keys(assets)) {\n if (identityOfLockKey(old) === freshId) delete assets[old];\n }\n }\n const presets = mergePresetRefs(prev.presets, fresh.presets);\n const mergedAssets = { ...assets, ...fresh.assets };\n // A source an asset still points at gets the one commit `buildLockFile` picks for it; a\n // source no asset points at keeps its previous row.\n for (const s of sourcesOfAssets(mergedAssets)) sources.set(s.url, s);\n return {\n ...fresh,\n assets: mergedAssets,\n sources: [...sources.values()].sort((a, b) => a.url.localeCompare(b.url)),\n // buildLockFile never emits a plugins slice — preserve the reconciler's.\n plugins: prev.plugins,\n presets,\n };\n}\n\n/**\n * Union of two `LockFile.presets` lists, one entry per preset identity (a fresh ref\n * supersedes an older version of the same preset), sorted; `undefined` when empty.\n */\nfunction mergePresetRefs(\n prev: string[] | undefined,\n fresh: string[] | undefined,\n): string[] | undefined {\n const byIdentity = new Map<string, string>();\n for (const ref of [...(prev ?? []), ...(fresh ?? [])]) {\n byIdentity.set(identityOfLockKey(ref) ?? ref, ref);\n }\n return byIdentity.size > 0 ? [...byIdentity.values()].sort() : undefined;\n}\n\n/** `kind:publisher/name` of a canonical lock key, or `undefined` when it does not parse. */\nfunction identityOfLockKey(key: string): string | undefined {\n const ref = parseAssetRefLoose(key);\n return ref ? `${ref.kind}:${ref.publisher}/${ref.name}` : undefined;\n}\n\n// ── Plugins slice ────────────────────────────────────────────────────────────\n\n/** Absolute path to a project's lock file. */\nfunction lockPathFor(projectDir: string): string {\n return join(projectDir, \"skaile.lock.yaml\");\n}\n\n/**\n * Read the `plugins` slice from a project's `skaile.lock.yaml`.\n *\n * Total — never throws on a missing/unparseable/legacy lock file (returns\n * `undefined`). The plugin-store reconciler folds this into its reconcile-hash\n * so a lock edit invalidates the hash even without a manifest change.\n *\n * @param projectDir - Project root containing `skaile.lock.yaml`\n * @returns The `plugins` record, or `undefined` when absent\n */\nexport function readPluginsLockSlice(\n projectDir: string,\n): Record<string, LockPluginEntry> | undefined {\n try {\n return readLock(lockPathFor(projectDir))?.plugins;\n } catch {\n // Legacy v1 lock — no usable plugins slice.\n return undefined;\n }\n}\n\n/**\n * Merge a `plugins` slice into a project's `skaile.lock.yaml`, preserving all\n * other fields. Creates a minimal v3 lock file when none exists (or the\n * existing one is an outdated schema that can't be read).\n *\n * @param projectDir - Project root containing `skaile.lock.yaml`\n * @param slice - The `plugins` record to persist\n */\nexport function writePluginsLockSlice(\n projectDir: string,\n slice: Record<string, LockPluginEntry>,\n): void {\n const lockPath = lockPathFor(projectDir);\n let existing: LockFile | null = null;\n try {\n existing = readLock(lockPath);\n } catch {\n existing = null; // outdated schema — overwrite with a fresh v3 shell\n }\n const next: LockFile = existing ?? {\n schema_version: 3,\n locked_at: new Date().toISOString(),\n assets: {},\n sources: [],\n };\n next.plugins = slice;\n writeLock(lockPath, next);\n}\n\n// ── Verification ─────────────────────────────────────────────────────────────\n\n/**\n * Result of verifying a lock file against the current repository state.\n * @docLink packages/core/api-reference#verify-result\n */\nexport interface VerifyResult {\n /** `true` when no drift or missing assets were found. */\n ok: boolean;\n /** Canonical refs whose content hash no longer matches. */\n drifted: string[];\n /** Canonical refs whose files cannot be found on disk. */\n missing: string[];\n}\n\n/**\n * Verify a v2 lock file against the current on-disk source clones.\n *\n * For each locked asset, resolve its source clone directory via `resolveCloneDir`\n * (URL → on-disk path), re-hash the recorded files, and compare the recomputed\n * composite against the locked `sha256`. Reports assets whose hash changed\n * (`drifted`) and assets whose files are missing (`missing`).\n *\n * @param lock - Previously generated v2 `LockFile`.\n * @param resolveCloneDir - Maps a source URL to its on-disk clone root (or null).\n * @returns `VerifyResult` indicating drift and missing assets.\n * @docLink packages/core/api-reference#verify-lock\n */\nexport function verifyLock(\n lock: LockFile,\n resolveCloneDir: (sourceUrl: string, entry: LockEntry) => string | null,\n): VerifyResult {\n const drifted: string[] = [];\n const missing: string[] = [];\n\n for (const [ref, entry] of Object.entries(lock.assets)) {\n // Library-origin entries have no clone to re-hash; installLocked verifies them\n // against the library itself.\n if (!entry.source) continue;\n const state = verifyLockEntry(entry, resolveCloneDir(entry.source.url, entry));\n if (state === \"missing\") missing.push(ref);\n else if (state === \"drifted\") drifted.push(ref);\n }\n\n return { ok: drifted.length === 0 && missing.length === 0, drifted, missing };\n}\n\n/**\n * Whether `cloneDir` (a source clone, a bundled tree, or `null` when there is none) holds the\n * files a source-origin lock entry lists with the bytes it recorded: `missing` when the\n * directory is absent or a listed file is, `drifted` when the rolled-up hash differs.\n */\nexport function verifyLockEntry(\n entry: LockEntry,\n cloneDir: string | null,\n): \"ok\" | \"drifted\" | \"missing\" {\n if (!cloneDir) return \"missing\";\n const recomputed: Array<{ path: string; sha256: string }> = [];\n for (const f of entry.files) {\n const abs = join(cloneDir, f.path);\n if (!existsSync(abs)) return \"missing\";\n recomputed.push({ path: f.path, sha256: computeHash(abs) });\n }\n return compositeSha256(recomputed) === entry.sha256 ? \"ok\" : \"drifted\";\n}\n","/**\n * Comment-preserving editor for `skaile.manifest.yaml` files.\n *\n * The publication counterpart to {@link WorkspaceYamlEditor}: it owns the\n * `publisher` / `version` / `assets[]` accessors that used to sit on the\n * workspace editor before the 2026-06-03 manifest/workspace file split. Uses the\n * `yaml` library's Document AST so untouched sections stay byte-identical.\n *\n * Usage:\n *\n * import { ManifestYamlEditor } from '@skaile/workspaces/core'\n *\n * const editor = ManifestYamlEditor.load('/project/skaile.manifest.yaml')\n * editor.setPublisher('skaile-ai')\n * editor.setAsset({ kind: 'skill', name: 'audit', root: 'skills/audit' })\n * editor.save()\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { Document, isMap, isScalar, isSeq, parseDocument, type YAMLMap } from \"yaml\";\nimport { ASSET_KEY_ORDER, type AssetEntry, orderedAsset } from \"./publish-manifest.js\";\n\n/** Matches `encodeSkaileManifest`, so editor-written files wrap like encoded ones. */\nconst STRINGIFY_OPTIONS = { lineWidth: 120 };\n\n/**\n * Comment-preserving editor for `skaile.manifest.yaml` files.\n * Create with `ManifestYamlEditor.load(filePath)` or `ManifestYamlEditor.create(filePath)`.\n * @docLink packages/core/publish-manifest#manifest-yaml-editor\n */\nexport class ManifestYamlEditor {\n readonly path: string;\n private doc: Document;\n\n private constructor(path: string, doc: Document) {\n this.path = path;\n this.doc = doc;\n }\n\n /** Load an existing skaile.manifest.yaml file. */\n static load(filePath: string): ManifestYamlEditor {\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n const raw = readFileSync(filePath, \"utf-8\");\n return new ManifestYamlEditor(filePath, parseDocument(raw));\n }\n\n /** Create a new empty document (for use when no file exists yet). */\n static create(filePath: string): ManifestYamlEditor {\n return new ManifestYamlEditor(filePath, new Document({}));\n }\n\n /**\n * Why this document cannot be edited safely, or `undefined` when it can. Editing\n * a document that failed to parse would clobber what the author wrote.\n */\n problem(): string | undefined {\n const { errors, contents } = this.doc;\n if (errors.length > 0) return errors[0]?.message;\n if (contents != null && !isMap(contents)) return \"the root must be a mapping\";\n return undefined;\n }\n\n /** Write the document back to disk, preserving comments and formatting. */\n save(): void {\n writeFileSync(this.path, this.toString());\n }\n\n /** Return the serialized YAML string without writing to disk. */\n toString(): string {\n return this.doc.toString(STRINGIFY_OPTIONS);\n }\n\n // ── Publisher / version / repo-level defaults ───────────────────────────────\n\n /** Get the `publisher:` field. */\n getPublisher(): string | undefined {\n const v = this.doc.get(\"publisher\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the `publisher:` field. A newly added key goes first, where the canonical encoding puts it. */\n setPublisher(p: string): void {\n if (!this.doc.has(\"publisher\") && isMap(this.doc.contents)) {\n this.doc.contents.items.unshift(this.doc.createPair(\"publisher\", p));\n return;\n }\n this.doc.set(\"publisher\", p);\n }\n\n /** Get the `version:` field. */\n getVersion(): string | undefined {\n const v = this.doc.get(\"version\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the `version:` field. */\n setVersion(v: string): void {\n this.doc.set(\"version\", v);\n }\n\n /** Get the repo-level `license:` default. */\n getLicense(): string | undefined {\n const v = this.doc.get(\"license\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the repo-level `license:` default. */\n setLicense(v: string): void {\n this.doc.set(\"license\", v);\n }\n\n /** Get the repo-level `homepage:` default. */\n getHomepage(): string | undefined {\n const v = this.doc.get(\"homepage\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the repo-level `homepage:` default. */\n setHomepage(v: string): void {\n this.doc.set(\"homepage\", v);\n }\n\n // ── Assets ──────────────────────────────────────────────────────────────────\n\n /** Get all `assets:` entries. */\n getAssets(): AssetEntry[] {\n const node = this.doc.get(\"assets\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as AssetEntry[];\n }\n\n /** Declare an empty `assets:` inventory when the document has none. */\n ensureAssets(): void {\n if (!this.doc.has(\"assets\")) this.doc.set(\"assets\", this.doc.createNode([]));\n }\n\n /**\n * Add or update an asset entry, matched by `kind` + `name`. An update rewrites\n * only the fields that changed, so comments on the entry survive; a new field\n * lands at its canonical position, where `encodeSkaileManifest` would put it.\n */\n setAsset(entry: AssetEntry): void {\n const node = this.doc.get(\"assets\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"assets\", this.doc.createNode([orderedAsset(entry)]));\n return;\n }\n for (const item of node.items) {\n if (!isMap(item) || item.get(\"kind\") !== entry.kind || item.get(\"name\") !== entry.name) {\n continue;\n }\n const current = item.toJSON() as Record<string, unknown>;\n const next = orderedAsset(entry);\n for (const key of Object.keys(current)) {\n if (!(key in next)) item.delete(key);\n }\n for (const [key, value] of Object.entries(next)) {\n if (isDeepStrictEqual(current[key], value)) continue;\n if (item.has(key)) item.set(key, this.doc.createNode(value));\n else insertAtCanonicalPosition(item, this.doc.createPair(key, value));\n }\n return;\n }\n // An empty `assets: []` would otherwise force every entry into flow style.\n if (node.items.length === 0) node.flow = false;\n node.add(this.doc.createNode(orderedAsset(entry)));\n }\n\n /** Remove an asset entry by kind + name. Returns true when removed. */\n removeAsset(kind: string, name: string): boolean {\n const node = this.doc.get(\"assets\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (\n isMap(item) &&\n (item as YAMLMap).get(\"kind\") === kind &&\n (item as YAMLMap).get(\"name\") === name\n ) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Rename the entry `kind` + `from` to `to` in place (position, comments and every other\n * field stay). Returns true when renamed.\n */\n renameAsset(kind: string, from: string, to: string): boolean {\n const node = this.doc.get(\"assets\", true);\n if (!node || !isSeq(node)) return false;\n for (const item of node.items) {\n if (isMap(item) && item.get(\"kind\") === kind && item.get(\"name\") === from) {\n item.set(\"name\", to);\n return true;\n }\n }\n return false;\n }\n}\n\n/** Position of `key` in the canonical asset key order; unknown keys sort last. */\nfunction assetKeyRank(key: unknown): number {\n const i = ASSET_KEY_ORDER.indexOf(String(isScalar(key) ? key.value : key) as never);\n return i < 0 ? ASSET_KEY_ORDER.length : i;\n}\n\n/** Insert `pair` before the first existing key that sorts after it. */\nfunction insertAtCanonicalPosition(item: YAMLMap, pair: YAMLMap[\"items\"][number]): void {\n const rank = assetKeyRank(pair.key);\n const at = item.items.findIndex((p) => assetKeyRank(p.key) > rank);\n if (at < 0) item.items.push(pair);\n else item.items.splice(at, 0, pair);\n}\n","/**\n * Agent Skills (agentskills.io) open-standard conformance lint for SKILL.md\n * frontmatter — pure, advisory, never a hard gate.\n * See devlog: 2026-06-21-agentskills-conformance-shipped.\n * @docLink core/conformance\n */\n\n/** A single agentskills.io conformance finding. */\nexport interface ConformanceFinding {\n /** `error` = hard standard violation; `warn` = portability risk. */\n level: \"error\" | \"warn\";\n /** Frontmatter field the finding concerns (e.g. \"name\", \"metadata.tags\"). */\n field: string;\n /** Human-readable, ready to print after a file path. */\n message: string;\n}\n\n/** Options for {@link checkAgentSkillConformance}. */\nexport interface ConformanceOptions {\n /**\n * Parent directory name, for the standard's `name === <dir>` rule.\n * Omit to skip that check (e.g. when validating a detached frontmatter blob).\n */\n dirName?: string;\n}\n\n// Standard limits — see https://agentskills.io/specification.\nconst NAME_MAX = 64;\nconst DESCRIPTION_MAX = 1024;\nconst COMPATIBILITY_MAX = 500;\n\n/**\n * Check a SKILL.md frontmatter object against the Agent Skills open standard.\n * Returns findings only — the caller maps severity to exit codes.\n *\n * @param frontmatter Parsed SKILL.md YAML frontmatter.\n * @param opts Optional context (`dirName` enables the name==dir rule).\n * @returns Zero or more {@link ConformanceFinding}s.\n */\nexport function checkAgentSkillConformance(\n frontmatter: Record<string, unknown>,\n opts: ConformanceOptions = {},\n): ConformanceFinding[] {\n const out: ConformanceFinding[] = [];\n const name = frontmatter.name;\n\n if (typeof name === \"string\") {\n if (name.length > NAME_MAX) {\n out.push({\n level: \"error\",\n field: \"name\",\n message: `name is ${name.length} chars (standard max ${NAME_MAX})`,\n });\n }\n if (opts.dirName !== undefined && name !== opts.dirName) {\n out.push({\n level: \"warn\",\n field: \"name\",\n message: `name \"${name}\" does not match parent directory \"${opts.dirName}\" (standard requires equality)`,\n });\n }\n }\n\n const description = frontmatter.description;\n if (typeof description === \"string\" && description.length > DESCRIPTION_MAX) {\n out.push({\n level: \"error\",\n field: \"description\",\n message: `description is ${description.length} chars (standard max ${DESCRIPTION_MAX})`,\n });\n }\n\n const compatibility = frontmatter.compatibility;\n if (typeof compatibility === \"string\" && compatibility.length > COMPATIBILITY_MAX) {\n out.push({\n level: \"error\",\n field: \"compatibility\",\n message: `compatibility is ${compatibility.length} chars (standard max ${COMPATIBILITY_MAX})`,\n });\n }\n\n // The standard defines metadata as a string→string map. skaile nests objects\n // here by design — report as a portability WARN, never an error, never rewrite.\n const metadata = frontmatter.metadata;\n if (metadata !== undefined && typeof metadata === \"object\" && metadata !== null) {\n for (const [k, v] of Object.entries(metadata as Record<string, unknown>)) {\n if (typeof v !== \"string\") {\n out.push({\n level: \"warn\",\n field: `metadata.${k}`,\n message: `metadata.${k} is ${Array.isArray(v) ? \"an array\" : typeof v}, not a string — non-portable to strict skills-ref consumers`,\n });\n }\n }\n }\n\n const allowedTools = frontmatter[\"allowed-tools\"];\n if (allowedTools !== undefined && typeof allowedTools !== \"string\") {\n out.push({\n level: \"warn\",\n field: \"allowed-tools\",\n message: \"allowed-tools must be a space-separated string\",\n });\n }\n\n return out;\n}\n","/**\n * Patch operations — extract, generate, apply patches for skill improvement.\n *\n * Patches allow editing deployed assets from remote repos and contributing\n * changes back upstream via PR.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { CatalogEntry } from \"./models.js\";\n\n/**\n * Copy an asset's source directory into a patch working directory for editing.\n *\n * @param entry - The catalog entry to extract\n * @param patchDir - Base directory where extracted copies are placed\n * @returns Absolute path to the extracted copy (`<patchDir>/<kind>-<name>`)\n * @docLink packages/core/api-reference#extract-for-patch\n */\nexport function extractForPatch(entry: CatalogEntry, patchDir: string): string {\n const ref = `${entry.kind}-${entry.name}`;\n const dest = join(patchDir, ref);\n mkdirSync(dest, { recursive: true });\n\n // Copy the asset's source directory (or file) to the patch dir\n const sourceDir = dirname(entry.source);\n const sourceName = basename(entry.source);\n\n // If source is a file in a directory (e.g., skills/overview/SKILL.md), copy the whole dir\n if (existsSync(sourceDir)) {\n cpSync(sourceDir, dest, { recursive: true });\n }\n\n return dest;\n}\n\n/**\n * Generate a unified diff between an original and patched directory using `diff -ruN`.\n *\n * @param originalDir - Unmodified copy of the asset directory\n * @param patchedDir - Modified copy of the asset directory\n * @returns Patch content string, or `null` if there are no differences (or on error)\n * @docLink packages/core/api-reference#generate-patch\n */\nexport function generatePatch(originalDir: string, patchedDir: string): string | null {\n const r = spawnSync(\"diff\", [\"-ruN\", originalDir, patchedDir], {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n\n // diff returns 0 if no differences, 1 if differences, 2 on error\n if (r.status === 0) return null; // no differences\n if (r.status === 1) return r.stdout;\n return null; // error\n}\n\n/**\n * Apply a unified diff patch file to a directory using `patch -p1`.\n *\n * @param targetDir - Directory to apply the patch to\n * @param patchFile - Path to the `.patch` file\n * @returns `true` on success, `false` if the patch file is missing or the command fails\n * @docLink packages/core/api-reference#apply-patch\n */\nexport function applyPatch(targetDir: string, patchFile: string): boolean {\n if (!existsSync(patchFile)) return false;\n const r = spawnSync(\"patch\", [\"-p1\", \"-d\", targetDir, \"-i\", patchFile], {\n stdio: \"pipe\",\n });\n return r.status === 0;\n}\n\n/**\n * Return the paths of all `.patch` files in a directory.\n *\n * @param patchDir - Directory to scan for `.patch` files\n * @returns Array of absolute paths; empty array when `patchDir` does not exist\n * @docLink packages/core/api-reference#list-patches\n */\nexport function listPatches(patchDir: string): string[] {\n if (!existsSync(patchDir)) return [];\n return readdirSync(patchDir)\n .filter((f) => f.endsWith(\".patch\"))\n .map((f) => join(patchDir, f));\n}\n\n/**\n * Write patch content to a file, creating parent directories as needed.\n *\n * @param patchPath - Destination file path (including `.patch` extension)\n * @param content - Unified diff content to write\n * @docLink packages/core/api-reference#save-patch\n */\nexport function savePatch(patchPath: string, content: string): void {\n mkdirSync(dirname(patchPath), { recursive: true });\n writeFileSync(patchPath, content, \"utf8\");\n}\n\n/**\n * Read the content of a patch file.\n *\n * @param patchPath - Path to the `.patch` file\n * @returns File content as a string, or `null` if the file does not exist\n * @docLink packages/core/api-reference#read-patch\n */\nexport function readPatch(patchPath: string): string | null {\n if (!existsSync(patchPath)) return null;\n return readFileSync(patchPath, \"utf8\");\n}\n","/**\n * Reading and writing `providers.yml` — the two on-disk layers of the AI\n * provider registry (§1.5).\n *\n * `~/.skaile/providers.yml` is the default home for endpoint definitions;\n * `<workspace>/.skaile/providers.yml` overrides it per project and is\n * gitignored by `skaile init`. Higher layers (CLI/runtime overrides and the\n * control-plane session layer) never touch disk — callers pass them to\n * {@link loadProviderRegistry} as extra layers.\n *\n * @see PROVIDER-CONFIG-PLAN.md §1.5, §2.1\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport { globalSkaileDir } from \"./cache-paths.js\";\nimport {\n type AIProviderDiagnostic,\n type AIProviderRegistryDocument,\n type AIProviderRegistryLayer,\n type AIProviderRegistryPatch,\n type AIProviderRegistrySource,\n type MergedAIProviderRegistry,\n mergeRegistries,\n validateMergedRegistry,\n validateRegistry,\n} from \"./provider-registry.js\";\n\n/** The registry filename in both layers. */\nexport const PROVIDERS_FILENAME = \"providers.yml\";\n\nconst SKAILE_DIR = \".skaile\";\n\n/** `~/.skaile/providers.yml` — honours `$SKAILE_HOME`. */\nexport function userProviderRegistryPath(): string {\n return join(globalSkaileDir(), PROVIDERS_FILENAME);\n}\n\n/** `<projectDir>/.skaile/providers.yml`. */\nexport function workspaceProviderRegistryPath(projectDir: string): string {\n return join(resolve(projectDir), SKAILE_DIR, PROVIDERS_FILENAME);\n}\n\n/** One loaded registry file. */\nexport interface ProviderRegistryFile {\n /** Layer the file feeds. */\n layer: \"user\" | \"workspace\";\n path: string;\n exists: boolean;\n /**\n * The layer this file contributes. Entries may be partial: a file that names\n * `base_url` alone overrides that one field (§1.5). Empty when the file is\n * absent or every entry was malformed.\n */\n document: AIProviderRegistryDocument;\n diagnostics: AIProviderDiagnostic[];\n}\n\n/**\n * Read one registry file as **one layer** of the §1.5 stack. A missing file is\n * not an error — it is an empty layer. A malformed one yields diagnostics,\n * never an exception.\n *\n * Only the checks that stand on their own run here (types, URLs, the\n * credential grammar, literal secrets); whether an entry is *complete* is\n * decided on the merged registry by {@link loadProviderRegistry}, because the\n * layer below may be the one that names its `kind`.\n */\nexport function loadProviderRegistryFile(\n filePath: string,\n layer: \"user\" | \"workspace\",\n): ProviderRegistryFile {\n const empty: AIProviderRegistryDocument = { version: 1, providers: {} };\n if (!existsSync(filePath)) {\n return { layer, path: filePath, exists: false, document: empty, diagnostics: [] };\n }\n let raw: unknown;\n try {\n raw = parse(readFileSync(filePath, \"utf-8\"));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n layer,\n path: filePath,\n exists: true,\n document: empty,\n diagnostics: [\n {\n code: \"yaml_parse_error\",\n severity: \"error\",\n path: \"\",\n message: `${filePath}: ${message}`,\n },\n ],\n };\n }\n const { document, diagnostics } = validateRegistry(raw, { source: filePath, layer });\n return { layer, path: filePath, exists: true, document, diagnostics };\n}\n\n/**\n * Write a registry document, creating `.skaile/` when needed.\n *\n * The document is serialized verbatim: the file holds references, never\n * secrets, so there is nothing to redact — and {@link validateRegistry} is the\n * gate that keeps it that way. Callers validate before writing.\n *\n * @returns the path written.\n */\nexport function saveProviderRegistryFile(\n filePath: string,\n document: AIProviderRegistryDocument,\n): string {\n const dir = dirname(filePath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n writeFileSync(filePath, stringify({ version: 1, providers: document.providers }));\n return filePath;\n}\n\n/** Options for {@link loadProviderRegistry}. */\nexport interface LoadProviderRegistryOptions {\n /** Workspace whose `.skaile/providers.yml` is layered on top of the user file. */\n projectDir?: string;\n /**\n * Layers that do not come from these two files — the catalog layer from\n * `bridge/src/provider-catalog.ts`, CLI/runtime overrides, and the\n * control-plane session layer. Precedence follows each layer's id, not this\n * array's order.\n */\n extraLayers?: AIProviderRegistryLayer[];\n}\n\n/** The merged registry plus the files it came from. */\nexport interface LoadedProviderRegistry {\n /** Merged and gated: every entry here is complete. */\n registry: MergedAIProviderRegistry;\n /**\n * The same merge **before** the gate: every configured entry, complete or\n * not, as the layers left it. This is what a caller that has to see the\n * configured entries in order to build another layer reads — the catalog\n * layer expands the presets these entries name, and an entry whose `kind`\n * comes from its preset is still incomplete here, so it is absent from\n * `registry`.\n */\n patches: AIProviderRegistryPatch;\n files: ProviderRegistryFile[];\n /**\n * Every file's diagnostics in layer order, then the merge's own — an entry\n * no layer completed is reported here, naming the files that fed it.\n */\n diagnostics: AIProviderDiagnostic[];\n}\n\n/**\n * Load `~/.skaile/providers.yml` and, when a project directory is given,\n * `<projectDir>/.skaile/providers.yml`, then merge them with any extra layers\n * per §1.5 and gate the result.\n *\n * Merge *then* validate: each file is read as a patch, so a workspace entry\n * that sets one field of an entry the user file defines is applied over it\n * rather than dropped for being incomplete on its own.\n */\nexport function loadProviderRegistry(\n options: LoadProviderRegistryOptions = {},\n): LoadedProviderRegistry {\n const files: ProviderRegistryFile[] = [\n loadProviderRegistryFile(userProviderRegistryPath(), \"user\"),\n ];\n if (options.projectDir) {\n files.push(\n loadProviderRegistryFile(workspaceProviderRegistryPath(options.projectDir), \"workspace\"),\n );\n }\n\n const layers: AIProviderRegistryLayer[] = files.map((file) => ({\n layer: file.layer,\n providers: file.document.providers,\n }));\n const extraLayers = options.extraLayers ?? [];\n const merged = mergeRegistries([...layers, ...extraLayers]);\n const sources: AIProviderRegistrySource[] = [\n ...files.map((file) => ({ label: file.path, providers: file.document.providers })),\n ...extraLayers.map((layer) => ({ label: `${layer.layer} layer`, providers: layer.providers })),\n ];\n const { registry, diagnostics } = validateMergedRegistry(merged, { sources });\n\n return {\n registry,\n patches: merged.providers,\n files,\n diagnostics: [...files.flatMap((file) => file.diagnostics), ...diagnostics],\n };\n}\n","/**\n * User-layer runtime settings.\n *\n * SkaileSettings represents the personal, machine-specific overrides stored in\n * .skaile/settings.json (gitignored). Project-level defaults (framework, agent\n * definition, resource connections, hooks) belong in skaile.yaml via SkWorkspaceConfig.\n *\n * Resolution order (highest priority first):\n * 1. CLI flags / API overrides\n * 2. `PREFERRED_MODEL`\n * 3. .skaile/settings.json (project-local, walking upward)\n * 4. ~/.skaile/settings.json (user global)\n * 5. skaile.yaml defaults: (via resolveSkWorkspaceConfig — no duplicate YAML parser)\n * 6. Built-in SETTINGS_DEFAULTS\n *\n * `driver` is the exception: `skaile.yaml` alone owns the harness of a project,\n * so a settings file's `driver` applies only when `skaile.yaml` names none.\n *\n * Endpoints and credentials are NOT here: they are AI provider registry\n * entries in `~/.skaile/providers.yml` (`provider-registry-files.ts`). A\n * settings file that still carries the old `apiKeys{}` map is rejected on\n * load with the `skaile providers add` command that replaces it.\n */\n\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { globalSkaileDir } from \"./cache-paths.js\";\nimport { DEFAULT_DRIVER_ID } from \"./framework.js\";\nimport { type DriverTarget, driverTargetForDriver } from \"./driver-targets.js\";\nimport { resolveSkWorkspaceConfig, type SkWorkspaceConfig } from \"./workspace-config.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\n/**\n * Personal runtime settings — stored in .skaile/settings.json (gitignored).\n * Contains only user-specific overrides: credentials, preferred model/driver.\n *\n * Project-level config (framework, resources, hooks, agent definition) lives\n * in skaile.yaml as SkWorkspaceConfig. App-specific fields (e.g. voice)\n * are added by forge-common-backend via AppSettings.\n * @docLink packages/core/settings#skaile-settings\n */\nexport interface SkaileSettings {\n /** Active model selector — `\"<providerId>/<modelId>\"`, a bare model id, or `\"@role\"`. */\n model?: string;\n /** Bridge driver to use: \"omp\", \"claude-sdk\", or \"codex\". */\n driver?: string;\n /**\n * Model role aliases (§9.8), sourced from `skaile.yaml` `roles:`. Consumed\n * by `parseModelRef` when a selector is `@role`.\n */\n roles?: Record<string, string>;\n /** Framework install path overrides. Normally derived from skaile.yaml defaults. */\n skillsDir?: string;\n /** Override for the agents directory. Normally derived from skaile.yaml defaults. */\n agentsDir?: string;\n /** Override for the prompts directory. Normally derived from skaile.yaml defaults. */\n promptsDir?: string;\n /** AI Asset Store API URL (default: https://store.skaile.ai) */\n storeUrl?: string;\n /** JWT access token for the AI Asset Store */\n storeJwt?: string;\n /** Refresh token for JWT renewal */\n storeRefreshToken?: string;\n}\n\n/**\n * Built-in default settings. Lowest-priority layer in resolveSettings().\n * Override via .skaile/settings.json, ~/.skaile/settings.json, or env vars.\n *\n * `model` is deliberately absent. A hardcoded default here is not a floor a\n * consumer can opt out of: because `loadSettings` and `resolveSettings` spread\n * these defaults *under* every other layer, deleting `model` from a settings\n * file does not unset it — the built-in comes back. A caller therefore cannot\n * express \"no model configured\" and cannot route an unconfigured session to its\n * own per-harness default; it silently inherits whichever id was pinned here,\n * however stale. Leaving it unset lets each driver apply its own current\n * default (omp omits `--model`; claude-sdk falls back to the `sonnet` rolling\n * alias), which is the one that ages correctly.\n *\n * @docLink packages/core/settings#settings-defaults\n */\nexport const SETTINGS_DEFAULTS: SkaileSettings = {\n driver: DEFAULT_DRIVER_ID,\n};\n\n// ── Legacy field mapping ───────────────────────────────────────────────────\n\nconst LEGACY_FIELD_MAP: Record<string, keyof SkaileSettings> = {\n defaultModel: \"model\",\n defaultAgentType: \"driver\",\n};\n\n/**\n * The one settings.json field that is neither renamed nor carried: `apiKeys{}`\n * put literal secrets in a file the runtime cannot rotate, scope or audit.\n * Registry entries reference a credential (`credential.ref: env:NAME`), and a\n * file that still has the field is rejected — silently dropping it would start\n * the session without the keys the operator believes are configured.\n */\nconst APIKEYS_REJECTION =\n \"settings.json: `apiKeys` is no longer read — endpoints and credentials are AI provider \" +\n \"registry entries in ~/.skaile/providers.yml. Run `skaile providers add <id> --preset \" +\n \"<preset> --credential env:NAME` for each provider, then delete the field.\";\n\n/**\n * Rename legacy field names in a raw parsed settings object to their current equivalents.\n * Maps `defaultModel` → `model`, `defaultAgentType` → `driver`. A present\n * `apiKeys` key (even an empty map) throws with the command that replaces it.\n *\n * @param raw - Raw object from JSON.parse of a settings file\n * @returns Settings with legacy keys renamed to current ones\n * @docLink packages/core/settings#map-legacy-fields\n */\nexport function mapLegacyFields(raw: Record<string, unknown>): SkaileSettings {\n if (\"apiKeys\" in raw) throw new Error(APIKEYS_REJECTION);\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(raw)) {\n const mapped = LEGACY_FIELD_MAP[key];\n if (mapped) {\n if (!(mapped in result) || result[mapped] == null) result[mapped] = value;\n } else {\n result[key] = value;\n }\n }\n return result as SkaileSettings;\n}\n\n// ── Paths ──────────────────────────────────────────────────────────────────\n\nconst SKAILE_DIR = \".skaile\";\nconst SETTINGS_FILE = \"settings.json\";\n\n/**\n * Return the path to the user-global settings file: `$SKAILE_HOME/settings.json`\n * (`~/.skaile/settings.json` when `SKAILE_HOME` is unset).\n * @docLink packages/core/settings#global-settings-path\n */\nexport function globalSettingsPath(): string {\n return path.join(globalSkaileDir(), SETTINGS_FILE);\n}\n\n/**\n * Return the path to the project-local settings file: `<projectDir>/.skaile/settings.json`.\n *\n * @param projectDir - Absolute path to the project root\n * @returns Absolute path to the project settings file\n * @docLink packages/core/settings#project-settings-path\n */\nexport function projectSettingsPath(projectDir: string): string {\n return path.join(projectDir, SKAILE_DIR, SETTINGS_FILE);\n}\n\n// ── I/O ────────────────────────────────────────────────────────────────────\n\n/**\n * Read and parse one settings JSON file. `undefined` when the file is missing\n * or not JSON — those are the cases a layer may skip. What it must not skip is\n * a rejected field, which `mapLegacyFields` throws for outside this guard.\n */\nfunction readSettingsJson(filePath: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Load and parse one settings JSON file — exactly the keys it holds, no\n * built-in defaults merged in. Returns `{}` if the file does not exist or\n * cannot be parsed; throws when it carries a rejected field (`apiKeys`).\n *\n * A caller that reads a file in order to write it back (`config set`, the\n * setup wizard) must not persist a default the user never typed: a `driver`\n * merged in here once landed in `.skaile/settings.json` and pinned the harness\n * of the project. {@link resolveSettings} is the reader that adds defaults.\n *\n * @param filePath - Absolute path to a settings.json file\n * @returns The settings the file holds\n * @docLink packages/core/settings#load-settings\n */\nexport async function loadSettings(filePath: string): Promise<SkaileSettings> {\n let raw: Record<string, unknown>;\n try {\n raw = JSON.parse(await fsp.readFile(filePath, \"utf-8\"));\n } catch {\n return {};\n }\n return mapLegacyFields(raw);\n}\n\n/**\n * Persist settings to a JSON file, creating parent directories as needed.\n *\n * @param settings - Settings object to serialize\n * @param filePath - Absolute path to write the settings.json file\n * @docLink packages/core/settings#save-settings\n */\nexport async function saveSettings(settings: SkaileSettings, filePath: string): Promise<void> {\n await fsp.mkdir(path.dirname(filePath), { recursive: true });\n await fsp.writeFile(filePath, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n/**\n * Walk upward from `projectDir` (max 10 levels) and collect all\n * `.skaile/settings.json` paths found along the way.\n * Results are ordered nearest-to-root first.\n *\n * @param projectDir - Starting directory for the upward walk\n * @returns Array of absolute paths to settings files found\n * @docLink packages/core/settings#walk-for-settings\n */\nexport function walkForSettings(projectDir: string): string[] {\n const found: string[] = [];\n let dir = path.resolve(projectDir);\n const root = path.parse(dir).root;\n for (let i = 0; i < 10; i++) {\n const candidate = path.join(dir, SKAILE_DIR, SETTINGS_FILE);\n if (fs.existsSync(candidate)) found.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir || parent === root) break;\n dir = parent;\n }\n return found;\n}\n\n// ── Resolution ─────────────────────────────────────────────────────────────\n\nfunction mergeSettings(base: SkaileSettings, source: Partial<SkaileSettings>): SkaileSettings {\n const result: SkaileSettings = { ...base };\n for (const [key, value] of Object.entries(source) as [keyof SkaileSettings, unknown][]) {\n if (value === undefined || value === null || value === \"\") continue;\n if (key === \"roles\" && typeof value === \"object\") {\n // Per-key merge: a project that redefines `smol` must not have to\n // restate the roles its user-scope config already provides.\n result[key] = { ...result[key], ...(value as Record<string, string>) };\n } else {\n Object.assign(result, { [key]: value });\n }\n }\n return result;\n}\n\n/**\n * Derive a SkaileSettings-compatible layer from `skaile.yaml` — the default\n * profile's selection plus the workspace `roles:` table.\n *\n * A `skaile.yaml` that still defines a provider or an endpoint is a parse\n * error, and that one error is re-thrown rather than swallowed: silently\n * resolving an empty layer would start the session against the wrong model\n * instead of printing the command that fixes the file.\n */\nfunction settingsFromWorkspaceConfig(projectDir: string): SkaileSettings {\n let ws: SkWorkspaceConfig;\n try {\n ws = resolveSkWorkspaceConfig(projectDir);\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"skaile migrate providers\")) throw error;\n return {};\n }\n const result: SkaileSettings = {};\n if (ws.roles && Object.keys(ws.roles).length > 0) result.roles = ws.roles;\n const p = ws.agent_config?.default;\n if (!p) return result;\n if (p.driver) result.driver = p.driver;\n if (p.model) result.model = p.model;\n if (p.skills_dir) result.skillsDir = p.skills_dir;\n if (p.agents_dir) result.agentsDir = p.agents_dir;\n if (p.prompts_dir) result.promptsDir = p.prompts_dir;\n return result;\n}\n\n// ── Migration ──────────────────────────────────────────────────────────────\n\nconst _migrated = new Set<string>();\n\n/**\n * One-time migration from old config locations to .skaile/settings.json.\n * Does not delete old files — user can do that manually.\n * @docLink packages/core/settings#migrate-settings\n */\nexport async function migrateSettings(projectDir: string): Promise<void> {\n const resolved = path.resolve(projectDir);\n if (_migrated.has(resolved)) return;\n\n const targetPath = projectSettingsPath(resolved);\n if (fs.existsSync(targetPath)) {\n _migrated.add(resolved);\n return;\n }\n\n // Old locations: data/settings.json (forge-project), .cf/settings.json\n // (forge-concept), .skaile/config.json (old SkailConfig).\n const sources = [\n path.join(resolved, \"data\", \"settings.json\"),\n path.join(resolved, \".cf\", \"settings.json\"),\n path.join(resolved, \".skaile\", \"config.json\"),\n ]\n .map(readSettingsJson)\n .filter((raw): raw is Record<string, unknown> => raw !== undefined);\n\n if (sources.length > 0) {\n let merged: SkaileSettings = {};\n for (const source of sources) {\n merged = mergeSettings(merged, mapLegacyFields(source));\n }\n await saveSettings(merged, targetPath);\n }\n\n _migrated.add(resolved);\n}\n\n/** Where an effective setting came from: a file path, `PREFERRED_MODEL`, or `built-in default`. */\nexport type SettingsSources = Partial<Record<keyof SkaileSettings, string>>;\n\n/** Fold `source` into `acc`, recording `origin` for each scalar key it sets. */\nfunction foldLayer(\n acc: { settings: SkaileSettings; sources: SettingsSources },\n source: Partial<SkaileSettings>,\n origin: string,\n): void {\n for (const [key, value] of Object.entries(source) as [keyof SkaileSettings, unknown][]) {\n if (value === undefined || value === null || value === \"\") continue;\n if (key !== \"roles\") acc.sources[key] = origin;\n }\n acc.settings = mergeSettings(acc.settings, source);\n}\n\n/**\n * Merge the layers a user or project actually configured — `skaile.yaml`\n * agent_config defaults < `~/.skaile/settings.json` < `.skaile/settings.json`\n * (walking upward, farthest first) — without {@link SETTINGS_DEFAULTS}, so a\n * field is present only when something set it. `sources` names the file that\n * set each key.\n *\n * `driver` is the exception to that order: `skaile.yaml` alone owns the\n * harness a project runs on. A personal settings file names a driver only for\n * a project whose `skaile.yaml` names none, so a `driver` in\n * `.skaile/settings.json` never moves the project to another harness.\n */\nfunction configuredSettingsLayers(projectDir: string): {\n settings: SkaileSettings;\n sources: SettingsSources;\n} {\n const acc = { settings: {} as SkaileSettings, sources: {} as SettingsSources };\n\n // Layer: workspace config defaults (skaile.yaml via resolveSkWorkspaceConfig)\n const yamlLayer = settingsFromWorkspaceConfig(projectDir);\n foldLayer(acc, yamlLayer, path.join(path.resolve(projectDir), \"skaile.yaml\"));\n const projectDriver = yamlLayer.driver;\n\n // Layer: user global settings\n const globalPath = globalSettingsPath();\n const globalRaw = readSettingsJson(globalPath);\n if (globalRaw) foldLayer(acc, mapLegacyFields(globalRaw), globalPath);\n\n // Layer: project-local .skaile/settings.json (walking upward, farthest first)\n const settingsFiles = walkForSettings(projectDir);\n for (const filePath of settingsFiles.reverse()) {\n if (path.resolve(filePath) === path.resolve(globalPath)) continue;\n const raw = readSettingsJson(filePath);\n if (raw) foldLayer(acc, mapLegacyFields(raw), filePath);\n }\n\n if (projectDriver) {\n acc.settings.driver = projectDriver;\n acc.sources.driver = path.join(path.resolve(projectDir), \"skaile.yaml\");\n }\n return acc;\n}\n\n/**\n * The {@link DriverTarget} the project is configured for — the harness whose\n * install dirs `skaile config show` reports under \"Resolved Paths\". Resolves\n * `driver` through the same layers as {@link resolveSettings}, but without the\n * built-in `omp` default: `undefined` means nothing configured a (known)\n * driver, and the caller picks its own fallback.\n *\n * @param projectDir - Root directory of the project being operated on\n * @returns The configured target, or `undefined` when none is configured\n * @docLink packages/core/settings#resolve-configured-driver-target\n */\nexport function resolveConfiguredDriverTarget(projectDir: string): DriverTarget | undefined {\n return driverTargetForDriver(configuredSettingsLayers(projectDir).settings.driver);\n}\n\n/**\n * Resolve effective settings through the priority chain:\n * overrides > env vars (PREFERRED_MODEL) >\n * .skaile/settings.json (walks upward) > ~/.skaile/settings.json >\n * skaile.yaml agent_config defaults > SETTINGS_DEFAULTS. `driver` is the\n * exception: a `skaile.yaml` driver beats both settings files.\n *\n * @param projectDir - Root directory of the project being operated on\n * @param overrides - Optional top-priority overrides (CLI flags, API body)\n * @returns Merged effective settings\n * @docLink packages/core/settings#resolve-settings\n */\nexport async function resolveSettings(\n projectDir: string,\n overrides?: Partial<SkaileSettings>,\n): Promise<SkaileSettings> {\n return (await resolveSettingsWithSources(projectDir, overrides)).settings;\n}\n\n/**\n * {@link resolveSettings} plus the origin of every scalar key: the file path\n * that set it, `PREFERRED_MODEL`, `command line`, or `built-in default`.\n * Backs `skaile config show`.\n */\nexport async function resolveSettingsWithSources(\n projectDir: string,\n overrides?: Partial<SkaileSettings>,\n): Promise<{ settings: SkaileSettings; sources: SettingsSources }> {\n await migrateSettings(projectDir);\n\n const layers = configuredSettingsLayers(projectDir);\n // Base: built-in defaults under every configured layer\n const acc = {\n settings: { ...SETTINGS_DEFAULTS } as SkaileSettings,\n sources: {} as SettingsSources,\n };\n for (const key of Object.keys(SETTINGS_DEFAULTS) as (keyof SkaileSettings)[]) {\n acc.sources[key] = \"built-in default\";\n }\n foldLayer(acc, layers.settings, \"\");\n Object.assign(acc.sources, layers.sources);\n\n // Layer: environment variable model override\n if (process.env.PREFERRED_MODEL) {\n acc.settings.model = process.env.PREFERRED_MODEL;\n acc.sources.model = \"PREFERRED_MODEL\";\n }\n\n // Layer: explicit overrides\n if (overrides) foldLayer(acc, overrides, \"command line\");\n\n return acc;\n}\n\n// ── API key helpers ────────────────────────────────────────────────────────\n\n/**\n * Return a masked version of an API key for safe logging.\n * Shows only the last four characters (e.g. `'****abc1'`).\n *\n * @param key - Raw API key to mask\n * @returns Masked key string, or empty string if key is falsy\n * @docLink packages/core/settings#mask-api-key\n */\nexport function maskApiKey(key: string): string {\n return key ? `****${key.slice(-4)}` : \"\";\n}\n","/**\n * Which package manager a project (or this skaile install) uses, and the\n * command that adds a package with it. Messages that tell a user to install an\n * optional SDK print this command, so an npm user is never told to run `bun add`.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Package managers whose lockfile marks a project. */\nexport type PackageManager = \"bun\" | \"npm\" | \"pnpm\" | \"yarn\";\n\nconst LOCKFILES: [file: string, manager: PackageManager][] = [\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n];\n\n/** The manager named by `npm_config_user_agent` (set by `npx`, `bunx`, `pnpm dlx`, scripts). */\nfunction managerFromUserAgent(): PackageManager | undefined {\n const name = process.env.npm_config_user_agent?.split(\"/\")[0];\n return name === \"bun\" || name === \"npm\" || name === \"pnpm\" || name === \"yarn\" ? name : undefined;\n}\n\n/** The manager whose global store holds this skaile install, judged by its path. */\nfunction managerFromInstallPath(): PackageManager | undefined {\n let here: string;\n try {\n here = fileURLToPath(import.meta.url);\n } catch {\n return undefined;\n }\n if (/[\\\\/]\\.bun[\\\\/]/.test(here)) return \"bun\";\n if (/[\\\\/]pnpm[\\\\/]/.test(here) || /[\\\\/]\\.pnpm[\\\\/]/.test(here)) return \"pnpm\";\n if (/[\\\\/]\\.?yarn[\\\\/]/.test(here)) return \"yarn\";\n return undefined;\n}\n\n/**\n * The package manager of the project at `projectDir`: the one whose lockfile is\n * there, else the one that launched this process (`npx`/`bunx`), else the one\n * whose global store holds skaile, else Bun when this process runs under Bun,\n * else npm.\n */\nexport function detectPackageManager(projectDir: string): PackageManager {\n for (const [file, manager] of LOCKFILES) {\n if (existsSync(join(projectDir, file))) return manager;\n }\n return (\n managerFromUserAgent() ??\n managerFromInstallPath() ??\n ((globalThis as { Bun?: unknown }).Bun !== undefined ? \"bun\" : \"npm\")\n );\n}\n\n/** The command that adds `pkg` to a project managed by `manager`. */\nexport function installCommand(manager: PackageManager, pkg: string): string {\n switch (manager) {\n case \"bun\":\n return `bun add ${pkg}`;\n case \"pnpm\":\n return `pnpm add ${pkg}`;\n case \"yarn\":\n return `yarn add ${pkg}`;\n default:\n return `npm i ${pkg}`;\n }\n}\n\n/** The add command for `pkg` in the project at `projectDir` (default: the current directory). */\nexport function installCommandFor(pkg: string, projectDir: string = process.cwd()): string {\n return installCommand(detectPackageManager(projectDir), pkg);\n}\n","/**\n * Where a harness driver finds its optional SDK (`@anthropic-ai/claude-agent-sdk`,\n * `@openai/codex-sdk`). The project's `node_modules` comes first, so the\n * `npm i <sdk>` a tutorial tells the user to run in the project is enough; the SDK\n * next to the skaile install itself is the fallback. A failure names both places.\n */\n\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { installCommandFor } from \"./package-manager.js\";\n\n/** Conditions tried, in order, when a package's `exports` map has nested objects. */\nconst EXPORT_CONDITIONS = [\"import\", \"node\", \"default\"];\n\n/**\n * The package directory `skaile` runs from (the nearest ancestor of this file with a\n * `package.json`), or `null` when it cannot be told (a compiled binary).\n */\nexport function skaileInstallDir(): string | null {\n try {\n let dir = path.dirname(realpathSync(fileURLToPath(import.meta.url)));\n for (;;) {\n if (existsSync(path.join(dir, \"package.json\"))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n } catch {\n return null;\n }\n}\n\n/** The package directory of `pkg` in the nearest `node_modules` at or above `startDir`, or `null`. */\nexport function findProjectPackageDir(pkg: string, startDir: string): string | null {\n let dir = path.resolve(startDir);\n for (;;) {\n const candidate = path.join(dir, \"node_modules\", pkg);\n if (existsSync(path.join(candidate, \"package.json\"))) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction pickCondition(target: unknown): string | null {\n if (typeof target === \"string\") return target;\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = pickCondition(item);\n if (found) return found;\n }\n return null;\n }\n if (target && typeof target === \"object\") {\n for (const condition of EXPORT_CONDITIONS) {\n const found = pickCondition((target as Record<string, unknown>)[condition]);\n if (found) return found;\n }\n }\n return null;\n}\n\n/** The file `import(\"<pkg>\")` loads from the package at `pkgDir`, or `null` when none can be told. */\nexport function packageEntry(pkgDir: string): string | null {\n let manifest: { exports?: unknown; module?: string; main?: string };\n try {\n manifest = JSON.parse(readFileSync(path.join(pkgDir, \"package.json\"), \"utf8\"));\n } catch {\n return null;\n }\n const exp = manifest.exports;\n let rel: string | null = null;\n if (exp !== undefined) {\n const root =\n exp && typeof exp === \"object\" && !Array.isArray(exp) && \".\" in exp\n ? (exp as Record<string, unknown>)[\".\"]\n : exp;\n rel = pickCondition(root);\n } else {\n rel = manifest.module ?? manifest.main ?? \"index.js\";\n }\n if (!rel) return null;\n const file = path.resolve(pkgDir, rel);\n return existsSync(file) ? file : null;\n}\n\nconst loaded = new Map<string, Promise<unknown>>();\n\n/** One-line description of where the SDK was looked for. */\nexport function sdkLookupPlaces(projectDir: string): string {\n const home = skaileInstallDir();\n const project = path.join(path.resolve(projectDir), \"node_modules\");\n return home ? `${project} and next to skaile (${home})` : `${project} and next to skaile`;\n}\n\n/** The error a driver throws when its SDK is in neither place. One line, names both places. */\nexport function driverSdkMissingError(\n label: string,\n pkg: string,\n projectDir: string,\n cause?: unknown,\n): Error {\n const detail =\n cause instanceof Error && cause.message ? ` (load failed: ${firstLine(cause.message)})` : \"\";\n return new Error(\n `${label} not installed${detail}. Looked in ${sdkLookupPlaces(projectDir)}. Run: ${installCommandFor(pkg, projectDir)}`,\n );\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\", 1)[0]?.trim() ?? \"\";\n}\n\n/**\n * Load a driver SDK: from the project's `node_modules` first, then through `fallback`\n * (the literal `import(\"<pkg>\")` at the call site, which resolves next to the skaile\n * install and keeps the SDK visible to bundlers).\n *\n * @param pkg - npm name of the SDK.\n * @param projectDir - Project directory the driver runs for.\n * @param fallback - The `import(\"<pkg>\")` that resolves from the skaile install.\n * @throws {Error} One line naming both places the SDK was looked for.\n */\nexport async function loadDriverSdk<T>(\n pkg: string,\n projectDir: string,\n fallback: () => Promise<T>,\n label: string = pkg,\n): Promise<T> {\n let cause: unknown;\n const dir = findProjectPackageDir(pkg, projectDir);\n const entry = dir ? packageEntry(dir) : null;\n if (entry) {\n let pending = loaded.get(entry);\n if (!pending) {\n pending = import(/* @vite-ignore */ pathToFileURL(entry).href);\n loaded.set(entry, pending);\n }\n try {\n return (await pending) as T;\n } catch (err) {\n loaded.delete(entry);\n cause = err;\n }\n }\n try {\n return await fallback();\n } catch (err) {\n throw driverSdkMissingError(label, pkg, projectDir, cause ?? (dir ? err : undefined));\n }\n}\n","/**\n * The one system-prompt section builder for an agent definition. The install\n * renderers (`asset-manager`, bake the prompt into `.claude/agents/<name>.md`\n * and friends) and the runner (`createAgentSession`, assembles the live\n * system prompt) both build the agent part of the prompt through\n * {@link buildAgentPromptSections}, so the two can never disagree on order.\n *\n * Order — fixed here and nowhere else:\n *\n * 1. soul — identity and values\n * 2. memory — `<MEMORY>` block, one framed `<block>` per memory block\n * 3. fragments — framework fragments (agent-mode, handoff, …)\n * 4. constraints — `## Constraints` (RULES)\n * 5. duties — `## Duties`\n * 6. abilities — `## Installed Abilities`\n * 7. contracts — `## Contracts`\n * 8. composed — inline blocks from `composes:`\n * 9. extensions — per-project prompt-extensions\n *\n * Pure: no I/O. Callers hand in text they already loaded.\n */\n\n/** Section ids in the order the builder emits them. */\nexport const AGENT_PROMPT_SECTION_ORDER = [\n \"soul\",\n \"memory\",\n \"fragments\",\n \"constraints\",\n \"duties\",\n \"abilities\",\n \"contracts\",\n \"composed\",\n \"extensions\",\n] as const;\n\nexport type AgentPromptSectionId = (typeof AGENT_PROMPT_SECTION_ORDER)[number];\n\n/** A piece of prompt text, optionally with a label for breakdowns (`source`). */\nexport type AgentPromptPart = string | { text: string; source?: string };\n\n/** One memory block as rendered in `<MEMORY>`. */\nexport interface AgentPromptMemoryBlock {\n name: string;\n /** `instance` | `user` | `workspace`. */\n scope: string;\n /** Hard cap on the rendered content (characters). */\n maxChars: number;\n /** Current block content: what the host holds, or the seed when the host holds nothing. */\n content: string;\n}\n\nexport interface AgentPromptAbility {\n /** Slash-command name. */\n name: string;\n description: string;\n}\n\nexport interface AgentPromptContract {\n name: string;\n /** Path relative to the workspace root. */\n relativePath: string;\n}\n\n/** Everything the builder can place; every part is optional. */\nexport interface AgentPromptSectionsInput {\n soul?: string | null;\n memory?: readonly AgentPromptMemoryBlock[];\n frameworkFragments?: readonly AgentPromptPart[];\n /** RULES text; rendered under `## Constraints`. */\n constraints?: string | null;\n /** DUTIES text; rendered under `## Duties`. */\n duties?: string | null;\n abilities?: readonly AgentPromptAbility[];\n contracts?: readonly AgentPromptContract[];\n /** Inline blocks composed through `composes:`. */\n composed?: readonly AgentPromptPart[];\n promptExtensions?: readonly AgentPromptPart[];\n}\n\n/** One rendered, non-empty section. Multi-entry ids (fragments, composed, extensions) repeat. */\nexport interface AgentPromptSection {\n id: AgentPromptSectionId;\n text: string;\n /** Label of the contributing part, when it had one. */\n source?: string;\n}\n\n/**\n * Render one memory block's content, capped at `maxChars` (the cap bounds the\n * content; the frame is extra). Exported so hosts that edit blocks can preview\n * exactly what the agent will see.\n */\nexport function capMemoryContent(content: string, maxChars: number): string {\n const text = content.trim();\n return text.length > maxChars ? text.slice(0, maxChars).trimEnd() : text;\n}\n\n/**\n * The `<MEMORY>` block for the given memory blocks, or `undefined` when none\n * has content. Each block is framed `<block name=… scope=…>` and capped at its\n * own `maxChars`.\n */\nexport function renderMemorySection(blocks: readonly AgentPromptMemoryBlock[]): string | undefined {\n const framed: string[] = [];\n for (const block of blocks) {\n const content = capMemoryContent(block.content, block.maxChars);\n if (!content) continue;\n framed.push(`<block name=\"${block.name}\" scope=\"${block.scope}\">\\n${content}\\n</block>`);\n }\n if (framed.length === 0) return undefined;\n return `<MEMORY>\\n${framed.join(\"\\n\")}\\n</MEMORY>`;\n}\n\nconst partText = (part: AgentPromptPart): string => (typeof part === \"string\" ? part : part.text);\nconst partSource = (part: AgentPromptPart): string | undefined =>\n typeof part === \"string\" ? undefined : part.source;\n\n/**\n * Build the agent part of a system prompt as an ordered list of sections.\n * Empty parts are dropped. Join `section.text` with the caller's separator\n * (`\\n\\n` in the install renderers, the `---` rule in the runner).\n */\nexport function buildAgentPromptSections(input: AgentPromptSectionsInput): AgentPromptSection[] {\n const sections: AgentPromptSection[] = [];\n const push = (id: AgentPromptSectionId, text: string | undefined, source?: string): void => {\n if (!text) return;\n sections.push(source ? { id, text, source } : { id, text });\n };\n const pushParts = (id: AgentPromptSectionId, parts: readonly AgentPromptPart[] | undefined) => {\n for (const part of parts ?? []) {\n const text = partText(part);\n if (text.trim()) push(id, text, partSource(part));\n }\n };\n\n push(\"soul\", input.soul?.trim());\n push(\"memory\", renderMemorySection(input.memory ?? []));\n pushParts(\"fragments\", input.frameworkFragments);\n if (input.constraints?.trim())\n push(\"constraints\", `## Constraints\\n\\n${input.constraints.trim()}`);\n if (input.duties?.trim()) push(\"duties\", `## Duties\\n\\n${input.duties.trim()}`);\n\n if (input.abilities && input.abilities.length > 0) {\n const lines = [\"## Installed Abilities\", \"\"];\n for (const a of input.abilities) lines.push(`- \\`/${a.name}\\` — ${a.description}`);\n push(\"abilities\", lines.join(\"\\n\"));\n }\n\n if (input.contracts && input.contracts.length > 0) {\n const lines = [\n \"## Contracts\",\n \"\",\n \"Read the relevant contract before acting on constrained tasks:\",\n \"\",\n ];\n for (const c of input.contracts) lines.push(`- \\`${c.relativePath}\\``);\n push(\"contracts\", lines.join(\"\\n\"));\n }\n\n pushParts(\"composed\", input.composed);\n pushParts(\"extensions\", input.promptExtensions);\n return sections;\n}\n","/**\n * Comment-preserving editor for skaile.yaml files.\n *\n * Uses the `yaml` library's Document API to parse into an AST that retains\n * comments, blank lines, and formatting. Mutations are applied to the AST\n * and serialized back — untouched sections remain byte-identical.\n *\n * Usage:\n *\n * import { WorkspaceYamlEditor } from '@skaile/workspaces/core'\n *\n * const editor = WorkspaceYamlEditor.load('/project/skaile.yaml')\n * editor.setAgentConfig('default', { driver: 'claude-sdk', model: 'claude-sonnet-4-6' })\n * editor.setSource({ url: 'https://github.com/skaile-ai/ai-assets' })\n * editor.save()\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { Document, isMap, isSeq, parseDocument, type YAMLMap } from \"yaml\";\nimport type {\n AgentConfigProfile,\n ConnectorDeclaration,\n McpServerDeclaration,\n OverrideEntry,\n SourceEntry,\n StoreEntry,\n} from \"./workspace-config.js\";\nimport { parseSourceEntries } from \"./workspace-config.js\";\n\n/**\n * Comment-preserving editor for `skaile.yaml` files.\n * Uses the `yaml` library's Document AST so untouched sections remain byte-identical.\n * Create with `WorkspaceYamlEditor.load(filePath)` or `WorkspaceYamlEditor.create(filePath)`.\n * @docLink packages/core/workspace-config#workspace-yaml-editor\n */\nexport class WorkspaceYamlEditor {\n readonly path: string;\n private doc: Document;\n\n private constructor(path: string, doc: Document) {\n this.path = path;\n this.doc = doc;\n }\n\n /** Load an existing skaile.yaml file. */\n static load(filePath: string): WorkspaceYamlEditor {\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n const raw = readFileSync(filePath, \"utf-8\");\n const doc = parseDocument(raw);\n return new WorkspaceYamlEditor(filePath, doc);\n }\n\n /** Create a new empty document (for use when no file exists yet). */\n static create(filePath: string): WorkspaceYamlEditor {\n const doc = new Document({});\n return new WorkspaceYamlEditor(filePath, doc);\n }\n\n /** Write the document back to disk, preserving comments and formatting. */\n save(): void {\n writeFileSync(this.path, this.doc.toString());\n }\n\n /** Return the serialized YAML string without writing to disk. */\n toString(): string {\n return this.doc.toString();\n }\n\n // ── Scalar fields ──────────────────────────────────────────────────────────\n\n /** Get a top-level scalar field (name, description). */\n get(key: \"name\" | \"description\"): string | undefined {\n const val = this.doc.get(key);\n return val != null ? String(val) : undefined;\n }\n\n /** Set a top-level scalar field. */\n set(key: \"name\" | \"description\", value: string): void {\n this.doc.set(key, value);\n }\n\n // ── Agent config ──────────────────────────────────────────────────────────\n\n /**\n * Get an agent config profile by name (usually \"default\").\n * Reads from `agent-config` (canonical YAML key).\n */\n getAgentConfig(profile = \"default\"): AgentConfigProfile | undefined {\n const section = this._getAgentConfigSection();\n if (!section) return undefined;\n const node = section.get(profile, true);\n // `.toJSON()` — a YAMLMap's own properties are AST internals, not the\n // profile's fields, so returning the node would make every read undefined.\n return isMap(node) ? (node.toJSON() as AgentConfigProfile) : undefined;\n }\n\n /**\n * Set fields on an agent config profile. Merges with existing values —\n * only the provided fields are overwritten.\n */\n setAgentConfig(profile: string, values: Partial<AgentConfigProfile>): void {\n let section = this._getAgentConfigSection();\n if (!section) {\n // `createNode` — `doc.set(key, plainObject)` stores the object itself,\n // which is not a YAMLMap, and every later `section.get`/`set` would\n // throw on it.\n this.doc.set(\"agent-config\", this.doc.createNode({ [profile]: {} }));\n section = this._getAgentConfigSection();\n if (!section) throw new Error(\"failed to create the agent-config section\");\n }\n\n const existing = section.get(profile, true);\n if (!existing || !isMap(existing)) {\n section.set(profile, { ...values });\n return;\n }\n\n for (const [k, v] of Object.entries(values)) {\n if (v === undefined) continue;\n existing.set(k, v);\n }\n }\n\n /**\n * Delete a field from an agent config profile.\n */\n deleteAgentConfigField(profile: string, field: string): void {\n const section = this._getAgentConfigSection();\n if (!section) return;\n const profileNode = section.get(profile, true);\n if (isMap(profileNode)) {\n profileNode.delete(field);\n }\n }\n\n private _getAgentConfigSection(): YAMLMap | undefined {\n // Try canonical 'agent-config' first, then 'agent_config'\n const node = this.doc.get(\"agent-config\", true) ?? this.doc.get(\"agent_config\", true);\n return isMap(node) ? (node as YAMLMap) : undefined;\n }\n\n // ── Connectors ─────────────────────────────────────────────────────────────\n\n /** Get all connectors. */\n getConnectors(): ConnectorDeclaration[] {\n const node = this.doc.get(\"connectors\", true) ?? this.doc.get(\"data_resources\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as ConnectorDeclaration[];\n }\n\n /** Add or update a connector by id. */\n setConnector(connector: ConnectorDeclaration): void {\n const key = \"connectors\";\n const node = this.doc.get(key, true);\n\n if (!node || !isSeq(node)) {\n this.doc.set(key, this.doc.createNode([connector]));\n return;\n }\n\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === connector.id) {\n node.set(i, this.doc.createNode(connector));\n found = true;\n break;\n }\n }\n\n if (!found) {\n node.add(this.doc.createNode(connector));\n }\n }\n\n /** Remove a connector by id. */\n removeConnector(id: string): boolean {\n const key = this.doc.has(\"connectors\") ? \"connectors\" : \"data_resources\";\n const node = this.doc.get(key, true);\n if (!node || !isSeq(node)) return false;\n\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === id) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── MCP servers ────────────────────────────────────────────────────────────\n\n /**\n * Add or replace an mcp server entry, matched by `id`.\n * Mirrors {@link setConnector}: an existing entry with the same `id` is\n * replaced in place; otherwise the declaration is appended.\n */\n setMcpServer(mcp: McpServerDeclaration): void {\n const key = \"mcp_servers\";\n const node = this.doc.get(key, true);\n\n if (!node || !isSeq(node)) {\n this.doc.set(key, this.doc.createNode([mcp]));\n return;\n }\n\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === mcp.id) {\n node.set(i, this.doc.createNode(mcp));\n found = true;\n break;\n }\n }\n\n if (!found) {\n node.add(this.doc.createNode(mcp));\n }\n }\n\n // ── Dependencies ───────────────────────────────────────────────────────────\n\n /**\n * Append a dependency ref to `dependencies:`, deduped by exact ref string.\n *\n * @param ref - Canonical dependency ref (e.g. `skill:@skaile/foo#1.0.0`).\n * @returns `true` when the ref was newly added, `false` when it was already present.\n */\n addDependency(ref: string): boolean {\n const node = this.doc.get(\"dependencies\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"dependencies\", this.doc.createNode([ref]));\n return true;\n }\n for (const item of node.items) {\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (cur === ref) return false;\n }\n node.add(this.doc.createNode(ref));\n return true;\n }\n\n // ── Plugins ────────────────────────────────────────────────────────────────\n\n /** Get all `plugins:` specifiers. */\n getPlugins(): string[] {\n const node = this.doc.get(\"plugins\", true);\n if (!isSeq(node)) return [];\n const out: string[] = [];\n for (const item of node.items) {\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\") out.push(cur);\n }\n return out;\n }\n\n /**\n * Add a plugin specifier to `plugins:`, deduped by package name.\n * If an entry with the same package name exists it is replaced (so a version\n * bump re-pins in place); otherwise the spec is appended.\n *\n * @param spec - npm specifier, e.g. `\"@skaile/provider-fly@^0.1.0\"`.\n * @param nameOf - Extracts the package name from a spec (caller passes `parseSpec`-derived names).\n * @returns `true` when an existing entry was replaced, `false` when appended.\n */\n addPlugin(spec: string, nameOf: (s: string) => string): boolean {\n const node = this.doc.get(\"plugins\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"plugins\", this.doc.createNode([spec]));\n return false;\n }\n\n const wantName = nameOf(spec);\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\" && nameOf(cur) === wantName) {\n node.set(i, this.doc.createNode(spec));\n return true;\n }\n }\n node.add(this.doc.createNode(spec));\n return false;\n }\n\n /**\n * Remove the `plugins:` entry whose package name matches `name`.\n *\n * @param name - Package name to remove (e.g. `\"@skaile/provider-fly\"`).\n * @param nameOf - Extracts the package name from a spec.\n * @returns `true` when an entry was removed.\n */\n removePlugin(name: string, nameOf: (s: string) => string): boolean {\n const node = this.doc.get(\"plugins\", true);\n if (!node || !isSeq(node)) return false;\n\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\" && nameOf(cur) === name) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Sources ────────────────────────────────────────────────────────────────\n\n /**\n * Get all source entries (`{url, pin?}`).\n * @throws {SourceEntryError} When an item has no `url:` (see {@link parseSourceEntries}).\n */\n getSources(): SourceEntry[] {\n const node = this.doc.get(\"sources\", true);\n if (!isSeq(node)) return [];\n const raw = node.toJSON() as unknown[];\n parseSourceEntries(raw);\n return raw as SourceEntry[];\n }\n\n /**\n * Add or update a source entry, matched by `url`.\n * If an entry with the same url exists, it is replaced.\n */\n setSource(entry: SourceEntry): void {\n const node = this.doc.get(\"sources\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"sources\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === entry.url) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove a source entry by url. Returns true when an entry was removed. */\n removeSource(url: string): boolean {\n const node = this.doc.get(\"sources\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === url) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Stores ─────────────────────────────────────────────────────────────────\n\n /** Get all store entries (`{url}`). */\n getStores(): StoreEntry[] {\n const node = this.doc.get(\"stores\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as StoreEntry[];\n }\n\n /** Add or update a store entry, matched by `url`. */\n setStore(entry: StoreEntry): void {\n const node = this.doc.get(\"stores\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"stores\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === entry.url) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove a store entry by url. Returns true when an entry was removed. */\n removeStore(url: string): boolean {\n const node = this.doc.get(\"stores\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === url) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Overrides ────────────────────────────────────────────────────────────────\n\n /** Get all override entries (`{ref, source, reason}`). */\n getOverrides(): OverrideEntry[] {\n const node = this.doc.get(\"overrides\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as OverrideEntry[];\n }\n\n /** Add or update an override entry, matched by `ref`. */\n setOverride(entry: OverrideEntry): void {\n const node = this.doc.get(\"overrides\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"overrides\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"ref\") === entry.ref) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove an override entry by ref. Returns true when an entry was removed. */\n removeOverride(ref: string): boolean {\n const node = this.doc.get(\"overrides\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"ref\") === ref) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Raw access (escape hatch) ─────────────────────────────────────────────\n\n /** Get the underlying yaml Document for advanced manipulation. */\n get document(): Document {\n return this.doc;\n }\n}\n"]}