@skaile/workspaces 6.1.0 → 6.2.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 (381) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/{asset-feeds-HJFV7UPW.js → asset-feeds-KPKCE64E.js} +26 -26
  3. package/dist/{asset-feeds-HJFV7UPW.js.map → asset-feeds-KPKCE64E.js.map} +1 -1
  4. package/dist/asset-manager/catalog-deployer.js +10 -10
  5. package/dist/asset-manager/fragments.js +1 -1
  6. package/dist/asset-manager/index.js +18 -18
  7. package/dist/asset-manager/installer.js +13 -13
  8. package/dist/asset-manager/renderers.js +11 -11
  9. package/dist/asset-manager/src/index.d.ts +149 -16
  10. package/dist/asset-manager/src/index.d.ts.map +1 -1
  11. package/dist/asset-manager/src/installer.d.ts +9 -0
  12. package/dist/asset-manager/src/installer.d.ts.map +1 -1
  13. package/dist/asset-manager/src/renderers.d.ts +7 -0
  14. package/dist/asset-manager/src/renderers.d.ts.map +1 -1
  15. package/dist/bridge/harnesses/claude-sdk.js +15 -15
  16. package/dist/bridge/harnesses/codex.js +24 -17
  17. package/dist/bridge/harnesses/codex.js.map +1 -1
  18. package/dist/bridge/harnesses/continue.js +14 -14
  19. package/dist/bridge/harnesses/echo.js +4 -4
  20. package/dist/bridge/harnesses/gemini.js +10 -10
  21. package/dist/bridge/harnesses/goose.js +14 -14
  22. package/dist/bridge/harnesses/omp.js +15 -8
  23. package/dist/bridge/harnesses/omp.js.map +1 -1
  24. package/dist/bridge/harnesses/opencode.js +14 -14
  25. package/dist/bridge/harnesses/qwen.js +10 -10
  26. package/dist/bridge/index.js +19 -19
  27. package/dist/bridge/src/harness-model-check.d.ts +15 -0
  28. package/dist/bridge/src/harness-model-check.d.ts.map +1 -1
  29. package/dist/bridge/src/harnesses/_subprocess-cli.d.ts.map +1 -1
  30. package/dist/bridge/src/harnesses/codex.d.ts.map +1 -1
  31. package/dist/bridge/src/harnesses/omp.d.ts.map +1 -1
  32. package/dist/bridge/src/index.d.ts +1 -1
  33. package/dist/bridge/src/index.d.ts.map +1 -1
  34. package/dist/bridge/src/runner-private-env.d.ts +7 -0
  35. package/dist/bridge/src/runner-private-env.d.ts.map +1 -1
  36. package/dist/{chunk-DIGFA7Z5.js → chunk-27SXN33H.js} +13 -5
  37. package/dist/chunk-27SXN33H.js.map +1 -0
  38. package/dist/{chunk-AITJ7ELM.js → chunk-2XM3ZH36.js} +59 -23
  39. package/dist/chunk-2XM3ZH36.js.map +1 -0
  40. package/dist/{chunk-KUQAJVYT.js → chunk-3HACK2Z7.js} +142 -28
  41. package/dist/chunk-3HACK2Z7.js.map +1 -0
  42. package/dist/{chunk-J72MO2WA.js → chunk-5JPW27BI.js} +10 -9
  43. package/dist/chunk-5JPW27BI.js.map +1 -0
  44. package/dist/{chunk-AATHJRKL.js → chunk-5LQ62LNT.js} +4 -4
  45. package/dist/{chunk-AATHJRKL.js.map → chunk-5LQ62LNT.js.map} +1 -1
  46. package/dist/{chunk-S2XHGWQC.js → chunk-6CYKTHNT.js} +44 -15
  47. package/dist/chunk-6CYKTHNT.js.map +1 -0
  48. package/dist/{chunk-XFIEVEU7.js → chunk-6OHZUUR7.js} +5 -4
  49. package/dist/chunk-6OHZUUR7.js.map +1 -0
  50. package/dist/{chunk-E572OHGY.js → chunk-76FLBODK.js} +4 -3
  51. package/dist/chunk-76FLBODK.js.map +1 -0
  52. package/dist/{chunk-HPMQRAIF.js → chunk-7DRFKAJZ.js} +7 -7
  53. package/dist/{chunk-HPMQRAIF.js.map → chunk-7DRFKAJZ.js.map} +1 -1
  54. package/dist/{chunk-EX3GLAL6.js → chunk-7H6XRCPG.js} +5 -5
  55. package/dist/{chunk-EX3GLAL6.js.map → chunk-7H6XRCPG.js.map} +1 -1
  56. package/dist/{chunk-4FVIT5DI.js → chunk-7Y6S4XLL.js} +3 -3
  57. package/dist/{chunk-4FVIT5DI.js.map → chunk-7Y6S4XLL.js.map} +1 -1
  58. package/dist/{chunk-RDTLPOPD.js → chunk-BEYNH2LS.js} +4 -4
  59. package/dist/{chunk-RDTLPOPD.js.map → chunk-BEYNH2LS.js.map} +1 -1
  60. package/dist/{chunk-GNZBFSRB.js → chunk-BOT64P3U.js} +4 -4
  61. package/dist/{chunk-GNZBFSRB.js.map → chunk-BOT64P3U.js.map} +1 -1
  62. package/dist/{chunk-VMVDAZLA.js → chunk-BRK5QZKI.js} +108 -19
  63. package/dist/chunk-BRK5QZKI.js.map +1 -0
  64. package/dist/{chunk-QSYQOTWN.js → chunk-BY5WIRCU.js} +58 -5
  65. package/dist/chunk-BY5WIRCU.js.map +1 -0
  66. package/dist/{chunk-Z7ZEZZB6.js → chunk-C5HFK34M.js} +3 -3
  67. package/dist/chunk-C5HFK34M.js.map +1 -0
  68. package/dist/{chunk-ABFPSVIS.js → chunk-COAFAYBS.js} +31 -7
  69. package/dist/chunk-COAFAYBS.js.map +1 -0
  70. package/dist/{chunk-YLLVSR2U.js → chunk-E5NQRHEB.js} +30 -7
  71. package/dist/chunk-E5NQRHEB.js.map +1 -0
  72. package/dist/{chunk-BFMYYNDT.js → chunk-F3D25RGM.js} +11 -3
  73. package/dist/chunk-F3D25RGM.js.map +1 -0
  74. package/dist/{chunk-QAKUD6QN.js → chunk-GF5JXQIZ.js} +3 -3
  75. package/dist/{chunk-QAKUD6QN.js.map → chunk-GF5JXQIZ.js.map} +1 -1
  76. package/dist/{chunk-ZFUZ5AKM.js → chunk-I7LC5TDY.js} +3 -3
  77. package/dist/{chunk-ZFUZ5AKM.js.map → chunk-I7LC5TDY.js.map} +1 -1
  78. package/dist/{chunk-NB7SYQYP.js → chunk-ICSGNT5P.js} +7 -7
  79. package/dist/{chunk-NB7SYQYP.js.map → chunk-ICSGNT5P.js.map} +1 -1
  80. package/dist/{chunk-CEKW3KXP.js → chunk-ITFCWMOY.js} +18 -15
  81. package/dist/chunk-ITFCWMOY.js.map +1 -0
  82. package/dist/{chunk-LSSYC5IC.js → chunk-IZQOO6MN.js} +2 -2
  83. package/dist/{chunk-LSSYC5IC.js.map → chunk-IZQOO6MN.js.map} +1 -1
  84. package/dist/{chunk-7LP7RCZI.js → chunk-JFLQICIU.js} +5 -5
  85. package/dist/{chunk-7LP7RCZI.js.map → chunk-JFLQICIU.js.map} +1 -1
  86. package/dist/{chunk-COYF6IG2.js → chunk-JJJ2G4K2.js} +5 -5
  87. package/dist/{chunk-COYF6IG2.js.map → chunk-JJJ2G4K2.js.map} +1 -1
  88. package/dist/{chunk-RHN5MRQO.js → chunk-JMIKGAUA.js} +27 -5
  89. package/dist/chunk-JMIKGAUA.js.map +1 -0
  90. package/dist/{chunk-DGTI65OC.js → chunk-K3R2UKG7.js} +17 -11
  91. package/dist/chunk-K3R2UKG7.js.map +1 -0
  92. package/dist/{chunk-3GMOPFWH.js → chunk-KB56WBQ3.js} +4 -4
  93. package/dist/{chunk-3GMOPFWH.js.map → chunk-KB56WBQ3.js.map} +1 -1
  94. package/dist/{chunk-ZHGKAZJ7.js → chunk-KJSC2ZD6.js} +56 -8
  95. package/dist/chunk-KJSC2ZD6.js.map +1 -0
  96. package/dist/{chunk-ZBHZLWV3.js → chunk-KPKGWXUJ.js} +4 -4
  97. package/dist/{chunk-ZBHZLWV3.js.map → chunk-KPKGWXUJ.js.map} +1 -1
  98. package/dist/{chunk-EJPMNDTP.js → chunk-KXJMQTOU.js} +3 -3
  99. package/dist/{chunk-EJPMNDTP.js.map → chunk-KXJMQTOU.js.map} +1 -1
  100. package/dist/{chunk-7HX6FNKL.js → chunk-LRBP3234.js} +41 -56
  101. package/dist/chunk-LRBP3234.js.map +1 -0
  102. package/dist/{chunk-FKQNBCDW.js → chunk-M4OG2YN4.js} +4 -4
  103. package/dist/{chunk-FKQNBCDW.js.map → chunk-M4OG2YN4.js.map} +1 -1
  104. package/dist/{chunk-UI745XC3.js → chunk-MAZ3UXJK.js} +13 -7
  105. package/dist/chunk-MAZ3UXJK.js.map +1 -0
  106. package/dist/{chunk-ASWTQQ7E.js → chunk-MM4YO3EL.js} +3 -3
  107. package/dist/{chunk-ASWTQQ7E.js.map → chunk-MM4YO3EL.js.map} +1 -1
  108. package/dist/{chunk-6YR4ALVX.js → chunk-OCQNUV4T.js} +7 -7
  109. package/dist/{chunk-6YR4ALVX.js.map → chunk-OCQNUV4T.js.map} +1 -1
  110. package/dist/{chunk-4MUDQCBP.js → chunk-PJJSBZZP.js} +3 -3
  111. package/dist/{chunk-4MUDQCBP.js.map → chunk-PJJSBZZP.js.map} +1 -1
  112. package/dist/{chunk-HWNK3F3X.js → chunk-PKBLJI23.js} +588 -76
  113. package/dist/chunk-PKBLJI23.js.map +1 -0
  114. package/dist/{chunk-NOA6EJXE.js → chunk-PKE3PXOK.js} +3 -3
  115. package/dist/{chunk-NOA6EJXE.js.map → chunk-PKE3PXOK.js.map} +1 -1
  116. package/dist/{chunk-AZ2H6R5I.js → chunk-PMWRM4EJ.js} +74 -39
  117. package/dist/chunk-PMWRM4EJ.js.map +1 -0
  118. package/dist/{chunk-VYVTEMAW.js → chunk-PNUM7GUY.js} +3 -3
  119. package/dist/{chunk-VYVTEMAW.js.map → chunk-PNUM7GUY.js.map} +1 -1
  120. package/dist/{chunk-X3YGUKCG.js → chunk-Q5RN4PWV.js} +3 -3
  121. package/dist/{chunk-X3YGUKCG.js.map → chunk-Q5RN4PWV.js.map} +1 -1
  122. package/dist/{chunk-BBBCJSSU.js → chunk-QIHL3YPL.js} +4 -4
  123. package/dist/{chunk-BBBCJSSU.js.map → chunk-QIHL3YPL.js.map} +1 -1
  124. package/dist/{chunk-HMISULVD.js → chunk-QK7AG5AV.js} +4 -4
  125. package/dist/{chunk-HMISULVD.js.map → chunk-QK7AG5AV.js.map} +1 -1
  126. package/dist/{chunk-ZDLUQLI6.js → chunk-QPWR3YMY.js} +15 -5
  127. package/dist/chunk-QPWR3YMY.js.map +1 -0
  128. package/dist/{chunk-SVTMNSPI.js → chunk-QXKUFROW.js} +5 -5
  129. package/dist/{chunk-SVTMNSPI.js.map → chunk-QXKUFROW.js.map} +1 -1
  130. package/dist/{chunk-5Y2KGB4H.js → chunk-RQMIZONH.js} +34 -9
  131. package/dist/chunk-RQMIZONH.js.map +1 -0
  132. package/dist/{chunk-LSI2IVFT.js → chunk-RXGPFAMN.js} +4 -3
  133. package/dist/chunk-RXGPFAMN.js.map +1 -0
  134. package/dist/{chunk-NUA33BYO.js → chunk-S2H3RBK7.js} +42 -15
  135. package/dist/chunk-S2H3RBK7.js.map +1 -0
  136. package/dist/{chunk-2LAPHLDH.js → chunk-SJNZ4WPA.js} +44 -35
  137. package/dist/chunk-SJNZ4WPA.js.map +1 -0
  138. package/dist/{chunk-QEULL4Q3.js → chunk-T2VBPVWZ.js} +77 -18
  139. package/dist/chunk-T2VBPVWZ.js.map +1 -0
  140. package/dist/{chunk-Z3VKUWAX.js → chunk-TSTRH4SM.js} +3 -3
  141. package/dist/{chunk-Z3VKUWAX.js.map → chunk-TSTRH4SM.js.map} +1 -1
  142. package/dist/{chunk-5J4NPGFM.js → chunk-TZERN27L.js} +5 -5
  143. package/dist/{chunk-5J4NPGFM.js.map → chunk-TZERN27L.js.map} +1 -1
  144. package/dist/{chunk-XGULGQA3.js → chunk-U673DB5U.js} +4 -4
  145. package/dist/{chunk-XGULGQA3.js.map → chunk-U673DB5U.js.map} +1 -1
  146. package/dist/{chunk-IRYKRKVQ.js → chunk-URCJIV7T.js} +3 -3
  147. package/dist/{chunk-IRYKRKVQ.js.map → chunk-URCJIV7T.js.map} +1 -1
  148. package/dist/{chunk-ADPM6AYF.js → chunk-VSX2G7LA.js} +3 -3
  149. package/dist/{chunk-ADPM6AYF.js.map → chunk-VSX2G7LA.js.map} +1 -1
  150. package/dist/{chunk-ILLTBKDJ.js → chunk-X37JUNEW.js} +4 -4
  151. package/dist/{chunk-ILLTBKDJ.js.map → chunk-X37JUNEW.js.map} +1 -1
  152. package/dist/{chunk-IHFGPHCT.js → chunk-Z3IRZBXB.js} +49 -25
  153. package/dist/chunk-Z3IRZBXB.js.map +1 -0
  154. package/dist/{chunk-ZAELRYKS.js → chunk-ZWJCRHP3.js} +3 -3
  155. package/dist/{chunk-ZAELRYKS.js.map → chunk-ZWJCRHP3.js.map} +1 -1
  156. package/dist/{claude-code-RE46FJXI.js → claude-code-BBMNVH2J.js} +5 -5
  157. package/dist/{claude-code-RE46FJXI.js.map → claude-code-BBMNVH2J.js.map} +1 -1
  158. package/dist/cli/index.js +348 -141
  159. package/dist/cli/index.js.map +1 -1
  160. package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
  161. package/dist/cli/src/commands/catalog.d.ts.map +1 -1
  162. package/dist/cli/src/commands/config.d.ts.map +1 -1
  163. package/dist/cli/src/commands/diff.d.ts.map +1 -1
  164. package/dist/cli/src/commands/harness.d.ts.map +1 -1
  165. package/dist/cli/src/commands/integration.d.ts.map +1 -1
  166. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  167. package/dist/cli/src/commands/library-index.d.ts +8 -1
  168. package/dist/cli/src/commands/library-index.d.ts.map +1 -1
  169. package/dist/cli/src/commands/migrate-assets.d.ts.map +1 -1
  170. package/dist/cli/src/commands/outdated.d.ts.map +1 -1
  171. package/dist/cli/src/commands/plugin-registry-cmd.d.ts.map +1 -1
  172. package/dist/cli/src/commands/project.d.ts.map +1 -1
  173. package/dist/cli/src/commands/rebuild.d.ts.map +1 -1
  174. package/dist/cli/src/commands/run.d.ts.map +1 -1
  175. package/dist/cli/src/commands/serve-preflight.d.ts +31 -1
  176. package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
  177. package/dist/cli/src/commands/serve.d.ts +10 -0
  178. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  179. package/dist/cli/src/commands/source-manifest-publish.d.ts.map +1 -1
  180. package/dist/cli/src/commands/source-manifest.d.ts +19 -7
  181. package/dist/cli/src/commands/source-manifest.d.ts.map +1 -1
  182. package/dist/cli/src/commands/validate-instances.d.ts.map +1 -1
  183. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  184. package/dist/cli/src/commands/why.d.ts.map +1 -1
  185. package/dist/cli/src/config-checks.d.ts +23 -5
  186. package/dist/cli/src/config-checks.d.ts.map +1 -1
  187. package/dist/cli/src/harness-error.d.ts +12 -1
  188. package/dist/cli/src/harness-error.d.ts.map +1 -1
  189. package/dist/cli/src/helpers.d.ts +18 -8
  190. package/dist/cli/src/helpers.d.ts.map +1 -1
  191. package/dist/cli/src/plugin-store/index.d.ts +10 -1
  192. package/dist/cli/src/plugin-store/index.d.ts.map +1 -1
  193. package/dist/cli/src/plugin-store/spec.d.ts +8 -0
  194. package/dist/cli/src/plugin-store/spec.d.ts.map +1 -1
  195. package/dist/cli/src/skill-checks.d.ts +2 -2
  196. package/dist/cli/src/skill-checks.d.ts.map +1 -1
  197. package/dist/connectors/config.js +5 -5
  198. package/dist/connectors/index.js +22 -22
  199. package/dist/connectors/src/connector-manager.d.ts.map +1 -1
  200. package/dist/connectors-47EM6C2P.js +48 -0
  201. package/dist/{connectors-7THEF7YA.js.map → connectors-47EM6C2P.js.map} +1 -1
  202. package/dist/core/framework.js +1 -1
  203. package/dist/core/index.js +9 -9
  204. package/dist/core/manifest.js +2 -2
  205. package/dist/core/models.js +1 -1
  206. package/dist/core/provider-registry-credentials.js +2 -2
  207. package/dist/core/provider-registry.js +1 -1
  208. package/dist/core/publish-manifest.js +3 -3
  209. package/dist/core/ref.js +1 -1
  210. package/dist/core/runtime-assets.js +5 -5
  211. package/dist/core/src/framework.d.ts +5 -3
  212. package/dist/core/src/framework.d.ts.map +1 -1
  213. package/dist/core/src/index.d.ts +2 -1
  214. package/dist/core/src/index.d.ts.map +1 -1
  215. package/dist/core/src/lock.d.ts +12 -0
  216. package/dist/core/src/lock.d.ts.map +1 -1
  217. package/dist/core/src/manifest.d.ts +15 -0
  218. package/dist/core/src/manifest.d.ts.map +1 -1
  219. package/dist/core/src/models.d.ts +7 -0
  220. package/dist/core/src/models.d.ts.map +1 -1
  221. package/dist/core/src/provider-registry.d.ts +6 -0
  222. package/dist/core/src/provider-registry.d.ts.map +1 -1
  223. package/dist/core/src/workspace-config.d.ts +10 -1
  224. package/dist/core/src/workspace-config.d.ts.map +1 -1
  225. package/dist/core/src/workspace-yaml-editor.d.ts.map +1 -1
  226. package/dist/core/workspace-config.js +4 -4
  227. package/dist/deploy/index.js +9 -9
  228. package/dist/discovery/index.js +5 -5
  229. package/dist/discovery/src/parse-manifest.d.ts.map +1 -1
  230. package/dist/{ensure-sources-IH7CHSJF.js → ensure-sources-K5EFNC3L.js} +35 -21
  231. package/dist/ensure-sources-K5EFNC3L.js.map +1 -0
  232. package/dist/factory-assets/connectors/box.js +22 -22
  233. package/dist/factory-assets/connectors/deploy.js +22 -22
  234. package/dist/factory-assets/connectors/devserver.js +22 -22
  235. package/dist/factory-assets/connectors/flow/adapter.js +22 -22
  236. package/dist/factory-assets/connectors/flow/engine.js +10 -10
  237. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  238. package/dist/factory-assets/connectors/flow/run-flow.js +24 -24
  239. package/dist/factory-assets/connectors/flow.js +22 -22
  240. package/dist/factory-assets/connectors/git.js +22 -22
  241. package/dist/factory-assets/connectors/gmail.js +22 -22
  242. package/dist/factory-assets/connectors/googledrive.js +22 -22
  243. package/dist/factory-assets/connectors/local.js +22 -22
  244. package/dist/factory-assets/connectors/mattermost.js +22 -22
  245. package/dist/factory-assets/connectors/memory.js +22 -22
  246. package/dist/factory-assets/connectors/minio.js +22 -22
  247. package/dist/factory-assets/connectors/postgres.js +22 -22
  248. package/dist/factory-assets/connectors/s3.js +22 -22
  249. package/dist/factory-assets/connectors/sharepoint.js +22 -22
  250. package/dist/factory-assets/connectors/sqlite.js +22 -22
  251. package/dist/factory-assets/connectors/static-server.js +22 -22
  252. package/dist/factory-assets/connectors/tunnel.js +22 -22
  253. package/dist/factory-assets/connectors/webdav.js +22 -22
  254. package/dist/factory-assets/connectors/xstate-store.js +22 -22
  255. package/dist/factory-assets/connectors/xstate.js +22 -22
  256. package/dist/flows-KLBNSKLO.js +26 -0
  257. package/dist/{flows-4JZQ3XFK.js.map → flows-KLBNSKLO.js.map} +1 -1
  258. package/dist/helpers-LUSV2ICC.js +52 -0
  259. package/dist/{helpers-JNMK3FC2.js.map → helpers-LUSV2ICC.js.map} +1 -1
  260. package/dist/library/index.js +14 -14
  261. package/dist/library/install.js +5 -5
  262. package/dist/library/src/index.d.ts +1 -1
  263. package/dist/library/src/index.d.ts.map +1 -1
  264. package/dist/library/src/install/index.d.ts +1 -1
  265. package/dist/library/src/install/index.d.ts.map +1 -1
  266. package/dist/library/src/install/install-from-manifest.d.ts +13 -0
  267. package/dist/library/src/install/install-from-manifest.d.ts.map +1 -1
  268. package/dist/library/src/install/source-fetch-github.d.ts.map +1 -1
  269. package/dist/library/src/manifest-writer.d.ts.map +1 -1
  270. package/dist/library/src/remote/remote-catalog-source.d.ts +3 -1
  271. package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
  272. package/dist/library/src/remote/rest-catalog-source.d.ts +3 -2
  273. package/dist/library/src/remote/rest-catalog-source.d.ts.map +1 -1
  274. package/dist/{library-publish-I3UWXAHI.js → library-publish-XMRCKRNR.js} +54 -55
  275. package/dist/library-publish-XMRCKRNR.js.map +1 -0
  276. package/dist/model-endpoint/index.js +12 -12
  277. package/dist/model-endpoint/src/openai-chat.d.ts +7 -2
  278. package/dist/model-endpoint/src/openai-chat.d.ts.map +1 -1
  279. package/dist/model-endpoint/src/openai-shared.d.ts +8 -0
  280. package/dist/model-endpoint/src/openai-shared.d.ts.map +1 -1
  281. package/dist/model-endpoint/src/server.d.ts.map +1 -1
  282. package/dist/model-endpoint/src/types.d.ts +1 -1
  283. package/dist/model-endpoint/src/types.d.ts.map +1 -1
  284. package/dist/model-endpoint/src/usage-cost.d.ts +23 -0
  285. package/dist/model-endpoint/src/usage-cost.d.ts.map +1 -0
  286. package/dist/open-library-XBR46DJL.js +56 -0
  287. package/dist/{open-library-NKKUJLWA.js.map → open-library-XBR46DJL.js.map} +1 -1
  288. package/dist/open-registry-W562DCDL.js +32 -0
  289. package/dist/{open-registry-BYAXSHUI.js.map → open-registry-W562DCDL.js.map} +1 -1
  290. package/dist/paths-2AZXB3QL.js +22 -0
  291. package/dist/{paths-UKWE35XS.js.map → paths-2AZXB3QL.js.map} +1 -1
  292. package/dist/plugin-store-36SIL4TV.js +23 -0
  293. package/dist/{plugin-store-ABE35NRX.js.map → plugin-store-36SIL4TV.js.map} +1 -1
  294. package/dist/project-D7GN7WLS.js +86 -0
  295. package/dist/{project-BIPK47JK.js.map → project-D7GN7WLS.js.map} +1 -1
  296. package/dist/resolver/index.js +10 -10
  297. package/dist/runner/index.js +39 -39
  298. package/dist/runner/src/capability-roundtrip.d.ts +7 -6
  299. package/dist/runner/src/capability-roundtrip.d.ts.map +1 -1
  300. package/dist/runner/src/serve.d.ts +6 -5
  301. package/dist/runner/src/serve.d.ts.map +1 -1
  302. package/dist/sdk/asset-manager.js +18 -18
  303. package/dist/sdk/bridge.js +19 -19
  304. package/dist/sdk/core.js +9 -9
  305. package/dist/sdk/flow.js +10 -10
  306. package/dist/sdk/index.js +39 -39
  307. package/dist/sdk/resolver.js +10 -10
  308. package/dist/sdk/runner.js +39 -39
  309. package/dist/sdk/transport/ws/server.js +10 -10
  310. package/dist/sdk/transport/ws.js +10 -10
  311. package/dist/sdk/transport.js +10 -10
  312. package/dist/{serve-preflight-FLTIBTEX.js → serve-preflight-CGA5G3AE.js} +63 -35
  313. package/dist/serve-preflight-CGA5G3AE.js.map +1 -0
  314. package/dist/{setup-AG6NFHSN.js → setup-IBDNJAOU.js} +31 -31
  315. package/dist/{setup-AG6NFHSN.js.map → setup-IBDNJAOU.js.map} +1 -1
  316. package/dist/skills-CTTO7SZK.js +26 -0
  317. package/dist/{skills-UQYUHVKO.js.map → skills-CTTO7SZK.js.map} +1 -1
  318. package/dist/source-2DJ5KNOI.js +85 -0
  319. package/dist/{source-ASEHI2XS.js.map → source-2DJ5KNOI.js.map} +1 -1
  320. package/dist/source-fetch-github-RWHV4I5Z.js +4 -0
  321. package/dist/{source-fetch-github-ST4MFL3D.js.map → source-fetch-github-RWHV4I5Z.js.map} +1 -1
  322. package/dist/{source-manifest-publish-IEVV3W6J.js → source-manifest-publish-IYWUMUCY.js} +54 -56
  323. package/dist/source-manifest-publish-IYWUMUCY.js.map +1 -0
  324. package/dist/transport/index.js +10 -10
  325. package/dist/transport/ws/server.js +10 -10
  326. package/dist/transport/ws.js +10 -10
  327. package/dist/tui/index.js +47 -40
  328. package/dist/tui/index.js.map +1 -1
  329. package/dist/tui/src/repl.d.ts.map +1 -1
  330. package/dist/types/manifests.js +1 -1
  331. package/dist/types/src/manifests/index.d.ts +1 -1
  332. package/dist/types/src/manifests/index.d.ts.map +1 -1
  333. package/dist/types/src/manifests/scaffold-body.d.ts +2 -0
  334. package/dist/types/src/manifests/scaffold-body.d.ts.map +1 -1
  335. package/dist/workspace-plugin/adapters/mcp.js +29 -29
  336. package/dist/workspace-plugin/adapters/omp.js +15 -15
  337. package/dist/workspace-plugin/index.js +2 -2
  338. package/package.json +1 -1
  339. package/dist/chunk-2LAPHLDH.js.map +0 -1
  340. package/dist/chunk-5Y2KGB4H.js.map +0 -1
  341. package/dist/chunk-7HX6FNKL.js.map +0 -1
  342. package/dist/chunk-ABFPSVIS.js.map +0 -1
  343. package/dist/chunk-AITJ7ELM.js.map +0 -1
  344. package/dist/chunk-AZ2H6R5I.js.map +0 -1
  345. package/dist/chunk-BFMYYNDT.js.map +0 -1
  346. package/dist/chunk-CEKW3KXP.js.map +0 -1
  347. package/dist/chunk-DGTI65OC.js.map +0 -1
  348. package/dist/chunk-DIGFA7Z5.js.map +0 -1
  349. package/dist/chunk-E572OHGY.js.map +0 -1
  350. package/dist/chunk-HWNK3F3X.js.map +0 -1
  351. package/dist/chunk-IHFGPHCT.js.map +0 -1
  352. package/dist/chunk-J72MO2WA.js.map +0 -1
  353. package/dist/chunk-KUQAJVYT.js.map +0 -1
  354. package/dist/chunk-LSI2IVFT.js.map +0 -1
  355. package/dist/chunk-NUA33BYO.js.map +0 -1
  356. package/dist/chunk-QEULL4Q3.js.map +0 -1
  357. package/dist/chunk-QSYQOTWN.js.map +0 -1
  358. package/dist/chunk-RHN5MRQO.js.map +0 -1
  359. package/dist/chunk-S2XHGWQC.js.map +0 -1
  360. package/dist/chunk-UI745XC3.js.map +0 -1
  361. package/dist/chunk-VMVDAZLA.js.map +0 -1
  362. package/dist/chunk-XFIEVEU7.js.map +0 -1
  363. package/dist/chunk-YLLVSR2U.js.map +0 -1
  364. package/dist/chunk-Z7ZEZZB6.js.map +0 -1
  365. package/dist/chunk-ZDLUQLI6.js.map +0 -1
  366. package/dist/chunk-ZHGKAZJ7.js.map +0 -1
  367. package/dist/connectors-7THEF7YA.js +0 -48
  368. package/dist/ensure-sources-IH7CHSJF.js.map +0 -1
  369. package/dist/flows-4JZQ3XFK.js +0 -26
  370. package/dist/helpers-JNMK3FC2.js +0 -38
  371. package/dist/library-publish-I3UWXAHI.js.map +0 -1
  372. package/dist/open-library-NKKUJLWA.js +0 -42
  373. package/dist/open-registry-BYAXSHUI.js +0 -32
  374. package/dist/paths-UKWE35XS.js +0 -22
  375. package/dist/plugin-store-ABE35NRX.js +0 -23
  376. package/dist/project-BIPK47JK.js +0 -86
  377. package/dist/serve-preflight-FLTIBTEX.js.map +0 -1
  378. package/dist/skills-UQYUHVKO.js +0 -26
  379. package/dist/source-ASEHI2XS.js +0 -85
  380. package/dist/source-fetch-github-ST4MFL3D.js +0 -4
  381. package/dist/source-manifest-publish-IEVV3W6J.js.map +0 -1
@@ -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/harness-sdk.ts","../core/src/bind.ts","../core/src/agent-prompt-sections.ts","../core/src/workspace-yaml-editor.ts"],"names":["existsSync","join","path","readF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AA,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-VMVDAZLA.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_HARNESSES } from \"./harness-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 harness 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_HARNESSES.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 harness's directory (`.claude/`, `.omp/`, `.codex/`), which\n * the harness 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/**\n * The content roots of what one project has: the flows `skaile install` / `skaile add` deployed\n * into `<projectDir>/.skaile/`, plus the first-party `factory-assets/` layers the product ships\n * (the `SKAILE_FACTORY_ASSETS_DIR` override and the bundled tree). Filtered to those that exist.\n *\n * Unlike {@link aiResourceRoots} it leaves out `~/.skaile/libraries/` and the user-global\n * `~/.skaile/` root. The global root holds `cache/` (every source clone on the machine), so\n * walking it listed flows no project declared. `flow list` and `skaile run <id>` read this\n * set, so a flow that runs for you also runs for a teammate with the same `skaile.yaml` (p1353).\n *\n * @param projectDir - Project directory whose local install root to include\n * (default: `process.cwd()`).\n */\nexport function projectAssetRoots(projectDir: string = process.cwd()): string[] {\n const roots: string[] = [...installRoots(false, projectDir), ...factoryAssetRoots()];\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 { isScalar, parseDocument, stringify, visit } 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 * Parse lock YAML with every `commit` and `sha256` value read as the text written in the file.\n * A sha made only of digits (`0000…0001`, `1111…`) parses as a YAML number, which loses its\n * leading zeros and digits and later fails with an error about `slice`; `stringify` quotes\n * such a string on write, a hand edit or another tool may not (p1295).\n */\nfunction parseLockYaml(text: string): unknown {\n const doc = parseDocument(text);\n // `parseDocument` collects errors instead of throwing: a lock with git conflict markers or a\n // duplicate key must fail like `parse` did, so `readLock` returns null.\n if (doc.errors.length > 0) throw doc.errors[0];\n visit(doc, {\n Pair(_key, pair) {\n // `commit` (a git sha) and `sha256` (a hex digest) are always text, never a number.\n if (!isScalar(pair.key) || (pair.key.value !== \"commit\" && pair.key.value !== \"sha256\"))\n return;\n const value = pair.value;\n if (!isScalar(value) || typeof value.value === \"string\" || value.value === null) return;\n if (typeof value.source === \"string\") value.value = value.source;\n },\n });\n return doc.toJS();\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 = parseLockYaml(readFileSync(lockPath, \"utf8\")) as Record<string, unknown> | null;\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 = parseLockYaml(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/**\n * Refuse a lock whose `commit` or `sha256` is not hex text (a hand edit, a merge gone wrong):\n * one line naming the entry, instead of a failure deep in the restore. An empty entry\n * `sha256` is a library entry without a recorded hash and passes.\n *\n * @throws `skaile.lock.yaml: commit of <ref> is not a git sha` (or the `sha256` form).\n */\nexport function assertLockHashes(lock: LockFile): void {\n const isHex = (value: unknown): boolean =>\n typeof value === \"string\" && /^[0-9a-f]+$/i.test(value);\n // A path source has no commit: an absent or empty one is not a hand-edited value.\n const badCommit = (value: unknown): boolean =>\n value !== undefined && value !== \"\" && !isHex(value);\n for (const [ref, entry] of Object.entries(lock.assets)) {\n if (entry.source && badCommit(entry.source.commit)) {\n throw new Error(`skaile.lock.yaml: commit of ${ref} is not a git sha`);\n }\n const files = entry.files ?? [];\n const hasHash = entry.sha256 !== undefined && entry.sha256 !== \"\";\n if ((hasHash && !isHex(entry.sha256)) || files.some((f) => !isHex(f.sha256))) {\n throw new Error(`skaile.lock.yaml: sha256 of ${ref} is not a hex digest`);\n }\n }\n for (const source of lock.sources ?? []) {\n if (badCommit(source.commit)) {\n throw new Error(`skaile.lock.yaml: commit of ${source.url} is not a git sha`);\n }\n }\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 * What the asset requires, as sorted, version-less `kind:@publisher/name`, as the library\n * lists it (`metadata.requires` and manifest `dependencies:`). The deployed copy cannot say\n * a manifest `dependencies:` entry, so `remove` reads it here once the library is gone.\n */\n requires?: string[];\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 ...(i.requires && i.requires.length > 0 ? { requires: i.requires } : {}),\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 * `lock` with the `sources:` row of every source URL an asset still points at re-derived from\n * the assets that remain, the way {@link buildLockFile} does. Call after dropping assets: a row\n * that kept the commit of a removed asset would differ from the one the next `install` builds,\n * and that `install` would rewrite a clean lock (p790). A source no asset points at keeps its\n * row, except the URLs in `droppedUrls` (the sources the removed assets pointed at): `install`\n * builds no row for a repo none of its assets uses, so `remove` of the last asset of a repo\n * drops it too.\n */\nexport function resyncLockSources(lock: LockFile, droppedUrls: Iterable<string> = []): LockFile {\n const sources = new Map(lock.sources.map((s) => [s.url, s]));\n const live = sourcesOfAssets(lock.assets);\n const liveUrls = new Set(live.map((s) => s.url));\n for (const url of droppedUrls) if (!liveUrls.has(url)) sources.delete(url);\n for (const s of live) sources.set(s.url, s);\n return {\n ...lock,\n sources: [...sources.values()].sort((a, b) => a.url.localeCompare(b.url)),\n };\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/** True for the structured `metadata` values the skaile manifest schema itself defines. */\nfunction isSkaileMetadataShape(key: string, value: unknown): boolean {\n if (key === \"tags\" || key === \"requires\") {\n return Array.isArray(value) && value.every((v) => typeof v === \"string\");\n }\n if (key === \"prerequisites\") {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n return false;\n}\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 values here by design:\n // `tags` and `requires` are arrays of strings and `prerequisites` is an object (the resolver\n // format), as the manifest schema requires (p1027). Those are not findings; any other\n // non-string value is a portability WARN, never an error, never rewritten.\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\" || isSkaileMetadataShape(k, v)) continue;\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 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 * `harness` is the exception: `skaile.yaml` alone owns the harness of a project,\n * so a settings file's `harness` 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_HARNESS_ID } from \"./framework.js\";\nimport { type HarnessName, harnessNameForHarnessId } from \"./harness-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/harness.\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 harness to use: \"omp\", \"claude-sdk\", or \"codex\". */\n harness?: 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 harness 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 harness: DEFAULT_HARNESS_ID,\n};\n\n// ── Legacy field mapping ───────────────────────────────────────────────────\n\nconst LEGACY_FIELD_MAP: Record<string, keyof SkaileSettings> = {\n defaultModel: \"model\",\n defaultAgentType: \"harness\",\n // Pre-6.0 spelling of `harness`; read for one major, then removed.\n driver: \"harness\",\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` → `harness` and the pre-6.0\n * `driver` → `harness` (an explicit `harness` in the same file wins). 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 `harness`\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.harness) result.harness = p.harness;\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 * `harness` is the exception to that order: `skaile.yaml` alone owns the\n * harness a project runs on. A personal settings file names a harness only for\n * a project whose `skaile.yaml` names none, so a `harness` 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 projectHarness = yamlLayer.harness;\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 (projectHarness) {\n acc.settings.harness = projectHarness;\n acc.sources.harness = path.join(path.resolve(projectDir), \"skaile.yaml\");\n }\n return acc;\n}\n\n/**\n * The {@link HarnessName} the project is configured for — the harness whose\n * install dirs `skaile config show` reports under \"Resolved Paths\". Resolves\n * `harness` through the same layers as {@link resolveSettings}, but without the\n * built-in `omp` default: `undefined` means nothing configured a (known)\n * harness, 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-harness-target\n */\nexport function resolveConfiguredHarnessName(projectDir: string): HarnessName | undefined {\n return harnessNameForHarnessId(configuredSettingsLayers(projectDir).settings.harness);\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. `harness` is the\n * exception: a `skaile.yaml` harness 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 harness 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/**\n * The file `import(\"<pkg>\")` (or `import(\"<pkg>/<subpath>\")`) loads from the package at\n * `pkgDir`, or `null` when none can be told. A subpath is matched against the `exports`\n * map: an exact key (`./api/x`) first, then a single-`*` pattern (`./api/*`).\n */\nexport function packageEntry(pkgDir: string, subpath?: 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 (subpath !== undefined) {\n if (!exp || typeof exp !== \"object\" || Array.isArray(exp)) return null;\n const map = exp as Record<string, unknown>;\n const key = `./${subpath}`;\n if (key in map) {\n rel = pickCondition(map[key]);\n } else {\n for (const [pattern, target] of Object.entries(map)) {\n const star = pattern.indexOf(\"*\");\n if (star === -1) continue;\n const head = pattern.slice(0, star);\n const tail = pattern.slice(star + 1);\n if (key.length < head.length + tail.length) continue;\n if (!key.startsWith(head) || !key.endsWith(tail)) continue;\n const matched = key.slice(head.length, key.length - tail.length);\n const picked = pickCondition(target);\n rel = picked ? picked.replaceAll(\"*\", matched) : null;\n break;\n }\n }\n } else 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 harness throws when its SDK is in neither place. One line, names both places. */\nexport function harnessSdkMissingError(\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 harness 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 harness 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 loadHarnessSdk<T>(\n pkg: string,\n projectDir: string,\n fallback: () => Promise<T>,\n label: string = pkg,\n): Promise<T> {\n return loadFromProject(pkg, undefined, projectDir, fallback, label);\n}\n\n/**\n * Like {@link loadHarnessSdk}, for a subpath export of the SDK (`import(\"<pkg>/<subpath>\")`).\n *\n * @param subpath - Subpath without the leading `./` (for example `api/anthropic-messages`).\n */\nexport async function loadHarnessSdkSubpath<T>(\n pkg: string,\n subpath: string,\n projectDir: string,\n fallback: () => Promise<T>,\n label: string = pkg,\n): Promise<T> {\n return loadFromProject(pkg, subpath, projectDir, fallback, label);\n}\n\nasync function loadFromProject<T>(\n pkg: string,\n subpath: string | undefined,\n projectDir: string,\n fallback: () => Promise<T>,\n label: string,\n): Promise<T> {\n let cause: unknown;\n const dir = findProjectPackageDir(pkg, projectDir);\n const entry = dir ? packageEntry(dir, subpath) : 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 harnessSdkMissingError(label, pkg, projectDir, cause ?? (dir ? err : undefined));\n }\n}\n","/**\n * One bind helper for every TCP server skaile starts (the WebSocket server and the model\n * endpoint). A port rule fixed in one server only came back twice (p842, p1006), so the busy-port\n * probe and the \"already in use\" error live here.\n */\n\nimport { connect, type Server } from \"node:net\";\n\nconst WILDCARD_HOSTS = [\"0.0.0.0\", \"::\", \"::0\", \"0:0:0:0:0:0:0:0\"];\n\n/** How long one connect probe waits before the address counts as free. */\nconst PROBE_TIMEOUT_MS = 1000;\n\n/**\n * The addresses a client may dial for a server bound to `host:port`: both loopback addresses\n * (a client on this machine uses either) plus the chosen host unless it is a wildcard. A bind to\n * a specific address can succeed next to a listener on another address or on a wildcard (macOS\n * allows it; Linux allows it across address families), while the other process keeps answering\n * clients on the address we think is ours (p842, p1006).\n */\nexport function probeHosts(host: string | undefined): string[] {\n const hosts = [\"127.0.0.1\", \"::1\"];\n if (host && !WILDCARD_HOSTS.includes(host) && !hosts.includes(host)) hosts.push(host);\n return hosts;\n}\n\n/**\n * Whether something accepts a TCP connection on `host:port`. Only a completed connect counts;\n * a refusal, an address this machine lacks (no IPv6), a timeout or any other error means nobody\n * listens there, and the real bind decides.\n */\nexport function connectProbe(\n port: number,\n host: string,\n timeoutMs = PROBE_TIMEOUT_MS,\n): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n const socket = connect({ port, host });\n const done = (held: boolean) => {\n socket.destroy();\n resolve(held);\n };\n socket.setTimeout(timeoutMs, () => done(false));\n socket.once(\"connect\", () => done(true));\n socket.once(\"error\", () => done(false));\n });\n}\n\n/**\n * Whether another process holds `port` on 127.0.0.1, on ::1 or on `host`. A fixed port only: port\n * 0 asks the OS for a free one and needs no probe.\n */\nexport async function portIsHeld(port: number, host?: string): Promise<boolean> {\n if (port === 0) return false;\n const results = await Promise.all(probeHosts(host).map((h) => connectProbe(port, h)));\n return results.some(Boolean);\n}\n\n/**\n * Whether a bind to `host:port` needed the old wildcard probe.\n *\n * @deprecated Kept for 5.18.x callers. {@link listenWithProbe} now always connect-probes\n * (`127.0.0.1`, `::1` and the host) on every platform; use {@link portIsHeld}.\n */\nexport function needsWildcardProbe(\n host: string | undefined,\n port: number,\n platform: NodeJS.Platform,\n): boolean {\n if (!host || port === 0 || platform !== \"darwin\") return false;\n return !WILDCARD_HOSTS.includes(host);\n}\n\n/**\n * Whether another process holds `port`.\n *\n * @deprecated Kept for 5.18.x callers. It connect-probes `127.0.0.1` and `::1` (a listener on\n * `::`, `0.0.0.0` or a loopback address answers there); use {@link portIsHeld}.\n */\nexport function holdsWildcard(port: number): Promise<boolean> {\n return portIsHeld(port);\n}\n\n/**\n * Bind `server` to `port` (on `host` when given) after probing the port by connect. Resolves once\n * listening. Rejects with the server's own error, or with an `EADDRINUSE` error when another\n * process holds the port, also when only the probe saw it.\n *\n * @param server - Any `net.Server` (an `http.Server` included), not yet listening.\n * @param _platform - Ignored (5.18.x took the platform for the wildcard probe); the probe runs everywhere.\n */\nexport async function listenWithProbe(\n server: Server,\n port: number,\n host?: string,\n _platform?: NodeJS.Platform,\n): Promise<void> {\n if (await portIsHeld(port, host)) {\n throw Object.assign(new Error(\"port probe\"), { code: \"EADDRINUSE\" });\n }\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n const onBound = () => {\n server.off(\"error\", reject);\n resolve();\n };\n if (host) server.listen(port, host, onBound);\n else server.listen(port, onBound);\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', { harness: '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 { basename } from \"node:path\";\nimport { Document, isMap, isScalar, isSeq, parseDocument, type Scalar, 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 /**\n * Load an existing skaile.yaml file.\n *\n * @throws {Error} `<file> — parse error: <reason>` (one line, the one every other command\n * prints) when the file does not parse. A document with errors cannot be written back, so\n * it is never handed out: `source add` used to crash in `save()` and `source list` read it\n * as empty (p1421).\n */\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 const first = doc.errors[0];\n if (first) {\n const reason = (first.message.split(\"\\n\")[0] ?? \"\").replace(/:$/, \"\");\n throw new Error(`${basename(filePath)} — parse error: ${reason}`);\n }\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 if (!isMap(node)) return undefined;\n const profileJson = node.toJSON() as AgentConfigProfile & { driver?: unknown };\n // Pre-6.0 `driver` key: surface it as `harness` (the file is only\n // rewritten by `setAgentConfig` / `skaile migrate harness`).\n const { driver, ...rest } = profileJson;\n if (driver === undefined) return profileJson;\n return rest.harness === undefined && typeof driver === \"string\"\n ? { ...rest, harness: driver }\n : rest;\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 // Editing a profile migrates its pre-6.0 `driver` key in place: the value moves to\n // `harness` (keeping position and comments), or is dropped when `harness` already exists.\n const driverPair = existing.items.find((p) => isScalar(p.key) && p.key.value === \"driver\");\n if (driverPair) {\n if (existing.has(\"harness\")) existing.delete(\"driver\");\n else (driverPair.key as Scalar).value = \"harness\";\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-ai/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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../bridge/src/error-classifier.ts","../bridge/src/reconfigure-model-ref.ts","../bridge/src/reconfigure-ledger.ts","../bridge/src/runner-private-env.ts"],"names":[],"mappings":";;;AAkDO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,MAAA;AAAA,EACT,YAAY,MAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,OAAO,OAAO,CAAA;AACpB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAaO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACxC,MAAA;AAAA,EACT,YAAY,MAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,OAAO,OAAO,CAAA;AACpB,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAQO,SAAS,mCAAmC,MAAA,EAAgC;AACjF,EAAA,OAAO;AAAA,IACL,GAAG,MAAA;AAAA,IACH,QAAA,EAAU,SAAA;AAAA,IACV,UAAA,EAAY,OAAO,UAAA,IAAc,GAAA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AAA,EAAG;AACjB,QAAA,MAAA,CAAO,MAAA,CAAO,WAAW,EAAE,CAAC,GAAG,GAAG,KAAA,CAAM,GAAG,CAAA,EAAG,CAAA;AAC9C,QAAA,MAAA,CAAO,MAAA,CAAO,UAAU,EAAE,CAAC,GAAG,GAAG,QAAA,CAAS,GAAG,CAAA,EAAG,CAAA;AAAA,MAClD;AAAA,IACF;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,GAAA,EAAK,IAAA,CAAK,8CAAA,EAAgD;AAAA,MACrE,QAAQ,MAAA,CAAO,QAAA;AAAA,MACf,MAAA,EAAQ,MAAA,CAAO,IAAA,CAAK,KAAK;AAAA,KAC1B,CAAA;AACD,IAAA,IAAI,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA,CAAE,SAAS,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAA,CAAQ,kBAAkB,EAAE,OAAA,EAAS,OAAO,QAAA,EAAU,SAAA,EAAW,UAAU,CAAA;AAAA,IAClF;AACA,IAAA,OAAO,MAAA,CAAO,QAAA;AAAA,EAChB;AACF;;;AChQO,IAAM,uBAAA,GAA6C;AAAA,EACxD,sBAAA;AAAA,EACA;AACF;AAMO,SAAS,sBAAoE,GAAA,EAAW;AAC7F,EAAA,KAAA,MAAW,GAAA,IAAO,uBAAA,EAAyB,OAAO,GAAA,CAAI,GAAG,CAAA;AACzD,EAAA,OAAO,GAAA;AACT","file":"chunk-XFIEVEU7.js","sourcesContent":["/**\n * Error classification for the Claude Agent SDK harness.\n *\n * Wraps the Anthropic API error patterns surfaced through the bundled\n * `claude-cli.js`. The CLI flattens upstream HTTP errors into terse strings\n * like:\n *\n * `Claude Code returned an error result: Failed to authenticate. API Error:\n * 401 {\"type\":\"error\",\"error\":{\"type\":\"authentication_error\",\"message\":\n * \"Invalid authentication credentials\"}}`\n *\n * Word-for-word that reads as an auth failure, but in practice it also\n * fires when a Claude Max OAuth subscription has exhausted its current\n * quota window — Anthropic returns a non-200 that the CLI relabels as\n * \"Failed to authenticate\" without preserving the original error type.\n *\n * The classifier here:\n * 1. Parses an embedded JSON body when the upstream included one\n * (e.g. `{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",...}}`)\n * so we believe the structured `error.type` over the surrounding\n * free-text wrapper.\n * 2. Honours the SDK's `terminal_reason` when it explicitly indicates\n * a blocking-limit / rapid-refill / model-error condition — those\n * are authoritative even if the textual error reads as auth.\n * 3. Falls back to keyword heuristics on the message text.\n * 4. For OAuth-style credentials (Claude Code subscriptions), adds a\n * hint that bounces user attention to quota rather than credentials,\n * because that's overwhelmingly the cause when a CredentialsFile\n * provider that worked yesterday now returns \"Invalid authentication\n * credentials\" without anyone touching the file.\n */\n\nimport type { AgentError } from \"./types.js\";\n\n/**\n * Error thrown by harnesses when the upstream provider rejects the credential\n * with an authentication-shaped failure (HTTP 401 / `authentication_error`\n * structured body). Carries the structured {@link AgentError} produced by\n * {@link classifyClaudeSdkError} so the runner can mediate without\n * re-classifying string text.\n *\n * The runner's 401-mediation handler `instanceof`-discriminates on this\n * subclass so the auth-vs-rate_limit fork stays in one place.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Runner-side handling on 401\".\n *\n * @category Errors\n * @since 3.3.0\n */\nexport class AuthError extends Error {\n readonly detail: AgentError;\n constructor(detail: AgentError) {\n super(detail.message);\n this.name = \"AuthError\";\n this.detail = detail;\n }\n}\n\n/**\n * Error thrown when an auth-shaped failure persists *after* a successful\n * credential self-heal — the refresh worked, yet the immediate retry still\n * returned 401. That combination rules out the credential and points at the\n * account itself: a hidden-tier rate limit, a billing block, or anti-abuse\n * throttling on OAuth tokens used at scale (Anthropic mislabels all three as\n * `authentication_error`). It deliberately does **not** extend {@link AuthError}\n * so the harness's auth self-heal does not fire again on it.\n *\n * @category Errors\n */\nexport class AccountUnavailableError extends Error {\n readonly detail: AgentError;\n constructor(detail: AgentError) {\n super(detail.message);\n this.name = \"AccountUnavailableError\";\n this.detail = detail;\n }\n}\n\n/**\n * Re-label an auth-shaped {@link AgentError} as an `account` failure. Called\n * when a 401 recurs after a successful credential refresh: the credential is\n * fine, so the user needs an account-state hint, not \"check your API key\".\n * Pure function.\n */\nexport function reclassifyAuthAsAccountUnavailable(detail: AgentError): AgentError {\n return {\n ...detail,\n category: \"account\",\n statusCode: detail.statusCode ?? 401,\n retryable: false,\n hint: \"The credential was refreshed successfully but Anthropic still rejected the request. This is an account-state issue, not an invalid credential — usually a rate limit at a hidden tier, a billing block, or anti-abuse throttling. Wait a few minutes and retry; if it persists, check the account's billing and usage limits at https://console.anthropic.com/.\",\n };\n}\n\n/**\n * `terminal_reason` values from the Claude Agent SDK that imply the failure\n * is a rate / quota / blocking condition rather than a credential problem.\n */\nconst RATE_LIMIT_TERMINAL_REASONS = new Set<string>([\"blocking_limit\", \"rapid_refill_breaker\"]);\n\n/**\n * `terminal_reason` values that indicate a generic, retryable model failure.\n * `prompt_too_long` is handled separately (not retryable, different hint).\n */\nconst MODEL_TERMINAL_REASONS = new Set<string>([\"model_error\", \"image_error\"]);\n\n/**\n * Input shape for {@link classifyClaudeSdkError} when decoding an `SDKResultError`.\n *\n * All fields are optional; `classifyClaudeSdkError` also accepts a plain `string`\n * (a thrown exception message) for the common non-SDK code paths.\n *\n * @docLink packages/bridge/api-reference#error-classifier\n */\nexport interface ClaudeSdkResultErrorInput {\n /** `errors` array from `SDKResultError`. Empty when not provided. */\n errors?: string[];\n /**\n * `terminal_reason` from `SDKResultError`. Authoritative when set to a\n * blocking/rapid-refill value, regardless of message text.\n */\n terminalReason?: string;\n /** `subtype` from `SDKResultError` — `error_max_turns` etc. */\n subtype?: string;\n /**\n * `true` when the configured Anthropic credential is a Claude Code\n * subscription (`CredentialsFile` provider) rather than a raw API key.\n * Changes the hint copy because `Invalid authentication credentials`\n * on an OAuth subscription almost always means quota.\n */\n oauthCredential?: boolean;\n}\n\n/**\n * The `apiError` tag the Claude Agent SDK (0.3.289) puts on the assistant\n * message it renders for a long-context entitlement 429.\n */\nexport const LONG_CONTEXT_CREDITS_API_ERROR = \"long_context_credits_required\";\n\n/**\n * Upstream and SDK-rendered wordings of the long-context entitlement 429:\n * \"Extra usage is required for long context\", \"Usage credits are required for\n * long context requests\", and the CLI's \"Usage credits required for 1M context\".\n */\nconst LONG_CONTEXT_ENTITLEMENT_PATTERN =\n /\\b(?:extra usage is|usage credits(?: are)?) required for (?:long|1m) context\\b/i;\n\n/**\n * Whether any of `texts` is the 429 Anthropic returns when the account may not\n * use a long (1M) context window: the seat is not out of quota, it cannot serve\n * a context over 200k. Matches only that wording, never a usage-limit 429.\n *\n * @docLink packages/bridge/api-reference#error-classifier\n */\nexport function isLongContextEntitlementRejection(\n texts: ReadonlyArray<string | null | undefined>,\n): boolean {\n return texts.some(\n (text) => typeof text === \"string\" && LONG_CONTEXT_ENTITLEMENT_PATTERN.test(text),\n );\n}\n\n/**\n * Classify a Claude SDK result-error or thrown error into a structured\n * {@link AgentError}. Pure function — safe to call from any layer.\n *\n * @param input - Either a free-text error message (from a thrown exception)\n * or a partially-decoded `SDKResultError` shape with `errors[]`,\n * `terminal_reason`, and `subtype`.\n * @returns A category, retryable flag, and human-readable hint.\n * @docLink packages/bridge/api-reference#error-classifier\n */\nexport function classifyClaudeSdkError(input: string | ClaudeSdkResultErrorInput): AgentError {\n const opts: ClaudeSdkResultErrorInput = typeof input === \"string\" ? { errors: [input] } : input;\n\n const message = (opts.errors ?? []).join(\"; \") || \"Unknown agent error\";\n\n // ── 1. Honour authoritative `terminal_reason` ──────────────────────────\n const byTerminalReason = classifyByTerminalReason(message, opts);\n if (byTerminalReason) {\n return byTerminalReason;\n }\n\n // ── 2. Inspect embedded JSON body for a structured error.type ──────────\n const structured = tryParseEmbeddedAnthropicError(message);\n if (structured) {\n const byStructured = classifyByStructuredError(message, structured, opts);\n if (byStructured) {\n return byStructured;\n }\n }\n\n // ── 3. Heuristic keyword classification on the wrapper text ────────────\n const lower = message.toLowerCase();\n\n const byKeyword = classifyByKeyword(message, lower, opts);\n if (byKeyword) {\n return byKeyword;\n }\n\n // ── 4. SDK result subtypes ─────────────────────────────────────────────\n const bySubtype = classifyBySubtype(message, opts);\n if (bySubtype) {\n return bySubtype;\n }\n\n return {\n message,\n category: \"unknown\",\n retryable: true,\n };\n}\n\n/**\n * Phase 1: classify on the SDK's authoritative `terminal_reason`. Returns\n * `null` when the reason is unset or not one of the recognised values.\n */\nfunction classifyByTerminalReason(\n message: string,\n opts: ClaudeSdkResultErrorInput,\n): AgentError | null {\n if (opts.terminalReason && RATE_LIMIT_TERMINAL_REASONS.has(opts.terminalReason)) {\n return {\n message,\n category: \"rate_limit\",\n retryable: true,\n hint: oauthQuotaHint(opts.oauthCredential),\n };\n }\n if (opts.terminalReason === \"prompt_too_long\") {\n return {\n message,\n category: \"model\",\n retryable: false,\n hint: \"The conversation is too long for the configured model. Start a new session or compact the existing one.\",\n };\n }\n if (opts.terminalReason && MODEL_TERMINAL_REASONS.has(opts.terminalReason)) {\n return {\n message,\n category: \"model\",\n retryable: true,\n hint: \"The model rejected this turn. Try again or switch models.\",\n };\n }\n return null;\n}\n\n/**\n * Phase 2: classify on the structured `error.type` parsed from an embedded\n * Anthropic JSON body. Returns `null` for an unrecognised `errorType`.\n */\nfunction classifyByStructuredError(\n message: string,\n structured: { errorType: string; statusCode?: number },\n opts: ClaudeSdkResultErrorInput,\n): AgentError | null {\n if (structured.errorType === \"rate_limit_error\") {\n return {\n message,\n category: \"rate_limit\",\n statusCode: structured.statusCode ?? 429,\n retryable: true,\n hint: oauthQuotaHint(opts.oauthCredential),\n };\n }\n if (structured.errorType === \"overloaded_error\") {\n return {\n message,\n category: \"rate_limit\",\n statusCode: structured.statusCode ?? 529,\n retryable: true,\n hint: \"Anthropic is overloaded. Try again in a moment.\",\n };\n }\n if (structured.errorType === \"authentication_error\") {\n // Anthropic genuinely says it's an auth failure. But for OAuth\n // credentials with the `oauth-2025-04-20` beta flow, this still\n // overwhelmingly correlates with quota. Surface both possibilities\n // in the hint so the user does not first re-upload a perfectly\n // good credentials file.\n return {\n message,\n category: \"auth\",\n statusCode: structured.statusCode ?? 401,\n retryable: false,\n hint: opts.oauthCredential\n ? \"Anthropic rejected the OAuth credential. With Claude Code subscriptions this is usually a quota or rate-limit issue rather than an invalid token — wait a few minutes before re-uploading the credentials file. If it persists, re-export `~/.claude/.credentials.json` from a working Claude Code install.\"\n : \"Anthropic rejected the API key. Check it in Settings -> AI Providers.\",\n };\n }\n if (structured.errorType === \"permission_error\") {\n return {\n message,\n category: \"auth\",\n statusCode: structured.statusCode ?? 403,\n retryable: false,\n hint: \"The configured credential does not have access to the requested model.\",\n };\n }\n if (structured.errorType === \"invalid_request_error\") {\n return {\n message,\n category: \"validation\",\n statusCode: structured.statusCode ?? 400,\n retryable: false,\n hint: \"Anthropic rejected the request shape. This is likely a bug — please report it.\",\n };\n }\n return null;\n}\n\n/**\n * Phase 3: heuristic keyword classification on the lowercased wrapper text.\n * `lower` is the pre-lowercased `message`. Returns `null` when no bucket hits.\n */\nfunction classifyByKeyword(\n message: string,\n lower: string,\n opts: ClaudeSdkResultErrorInput,\n): AgentError | null {\n if (\n lower.includes(\"rate limit\") ||\n lower.includes(\"rate_limit\") ||\n lower.includes(\"too many requests\") ||\n lower.includes(\"429\") ||\n lower.includes(\"quota\") ||\n lower.includes(\"blocking_limit\") ||\n lower.includes(\"rapid_refill\")\n ) {\n return {\n message,\n category: \"rate_limit\",\n retryable: true,\n hint: oauthQuotaHint(opts.oauthCredential),\n };\n }\n\n if (\n lower.includes(\"credit balance\") ||\n lower.includes(\"insufficient credit\") ||\n lower.includes(\"out of credits\")\n ) {\n return {\n message,\n category: \"rate_limit\",\n retryable: false,\n hint: \"The configured Anthropic account is out of credits. Top up at https://console.anthropic.com/ or switch providers.\",\n };\n }\n\n if (lower.includes(\"oauth authentication is currently not supported\")) {\n return {\n message,\n category: \"auth\",\n statusCode: 401,\n retryable: false,\n hint: \"The Claude Code CLI did not send the OAuth beta header. The bundled CLI in this image is too old — rebuild the agent image.\",\n };\n }\n\n // The Claude Code CLI emits this terse, JSON-less string when it finds no\n // usable credential — most commonly because the OAuth access token in\n // `~/.claude/.credentials.json` expired and the file carries no refresh token\n // (the platform provisions access-token-only files by design). It MUST be\n // classified as `auth` so the harness promotes it to `AuthError` and the\n // `onAuthError` self-heal re-mints the credential. Without this branch the\n // message falls through to `unknown`, the self-heal never fires, and every\n // subsequent turn dead-ends on \"please /login\". The check sits ahead of the\n // generic auth keywords because the string contains none of them.\n if (lower.includes(\"not logged in\") || lower.includes(\"please run /login\")) {\n return {\n message,\n category: \"auth\",\n statusCode: 401,\n retryable: false,\n hint: opts.oauthCredential\n ? \"The Claude Code OAuth credential expired and could not be auto-refreshed in-container. The runner will re-mint it — retry the prompt. If it persists, re-export `~/.claude/.credentials.json` from a working Claude Code install.\"\n : \"No Anthropic credential is configured for this provider. Add one in Settings -> AI Providers.\",\n };\n }\n\n if (\n lower.includes(\"api key\") ||\n lower.includes(\"authentication\") ||\n lower.includes(\"invalid authentication\") ||\n lower.includes(\"unauthorized\") ||\n lower.includes(\"401\") ||\n lower.includes(\"403\")\n ) {\n return {\n message,\n category: \"auth\",\n retryable: false,\n hint: opts.oauthCredential\n ? \"Anthropic rejected the OAuth credential. With Claude Code subscriptions this is usually a quota or rate-limit issue rather than an invalid token — wait a few minutes before re-uploading the credentials file.\"\n : \"Check the API key configured for this AI provider in Settings.\",\n };\n }\n\n if (\n lower.includes(\"model\") &&\n (lower.includes(\"not found\") ||\n lower.includes(\"not available\") ||\n lower.includes(\"does not exist\"))\n ) {\n return {\n message,\n category: \"model\",\n retryable: false,\n hint: \"The selected model is not available for this credential. Change the model in the AI provider config.\",\n };\n }\n\n if (\n lower.includes(\"context length\") ||\n lower.includes(\"token limit\") ||\n lower.includes(\"max_tokens\") ||\n lower.includes(\"prompt is too long\") ||\n lower.includes(\"prompt_too_long\")\n ) {\n return {\n message,\n category: \"model\",\n retryable: false,\n hint: \"The conversation is too long for the model. Start a new session or compact this one.\",\n };\n }\n\n if (\n lower.includes(\"timeout\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"enotfound\") ||\n lower.includes(\"fetch failed\") ||\n lower.includes(\"network\")\n ) {\n return {\n message,\n category: \"network\",\n retryable: true,\n hint: \"Network error reaching Anthropic. The runner will retry — try again if it persists.\",\n };\n }\n\n return null;\n}\n\n/**\n * Phase 4: classify on the SDK result `subtype` (`error_max_turns` etc).\n * Returns `null` when the subtype is unset or unrecognised.\n */\nfunction classifyBySubtype(message: string, opts: ClaudeSdkResultErrorInput): AgentError | null {\n if (opts.subtype === \"error_max_turns\") {\n return {\n message,\n category: \"unknown\",\n retryable: true,\n hint: \"The agent stopped after reaching `max_turns`. Resume the session or raise `max_turns` in the agent config.\",\n };\n }\n if (opts.subtype === \"error_max_budget_usd\") {\n return {\n message,\n category: \"rate_limit\",\n retryable: false,\n hint: \"The agent stopped because it hit the configured per-turn budget. Raise the budget or split the work.\",\n };\n }\n return null;\n}\n\n/**\n * The shared keyword buckets matched by {@link classifyGenericErrorMessage}.\n * Harnesses layer a provider-specific `hint` on top of the returned category.\n */\nexport type GenericErrorCategory = \"auth\" | \"rate_limit\" | \"model\" | \"network\";\n\n/**\n * Classify a free-text harness error against the keyword buckets common to the\n * subprocess/SDK harnesses (omp, codex). Returns the matched `category` +\n * `retryable` flag, or `null` when no shared bucket matches so the caller can\n * fall through to its own provider-specific buckets (e.g. codex sandbox) and\n * `unknown` default. The harness supplies the user-facing `hint` — only the\n * bucketing logic is shared, not the copy.\n */\nexport function classifyGenericErrorMessage(\n msg: string,\n): { category: GenericErrorCategory; retryable: boolean } | null {\n const lower = msg.toLowerCase();\n if (\n lower.includes(\"api key\") ||\n lower.includes(\"unauthorized\") ||\n lower.includes(\"authentication\") ||\n lower.includes(\"401\")\n ) {\n return { category: \"auth\", retryable: false };\n }\n if (\n lower.includes(\"rate limit\") ||\n lower.includes(\"429\") ||\n lower.includes(\"too many requests\") ||\n lower.includes(\"quota\")\n ) {\n return { category: \"rate_limit\", retryable: true };\n }\n if (\n lower.includes(\"model\") &&\n (lower.includes(\"not found\") ||\n lower.includes(\"not available\") ||\n lower.includes(\"does not exist\"))\n ) {\n return { category: \"model\", retryable: false };\n }\n if (\n lower.includes(\"context length\") ||\n lower.includes(\"too long\") ||\n lower.includes(\"token limit\") ||\n lower.includes(\"max_tokens\")\n ) {\n return { category: \"model\", retryable: false };\n }\n if (\n lower.includes(\"timeout\") ||\n lower.includes(\"econnrefused\") ||\n lower.includes(\"enotfound\") ||\n lower.includes(\"network\") ||\n lower.includes(\"fetch failed\") ||\n lower.includes(\"fetch\") ||\n lower.includes(\"connection\")\n ) {\n return { category: \"network\", retryable: true };\n }\n return null;\n}\n\n/**\n * Returns the rate-limit hint copy, branched on whether the active\n * credential is a Claude Code OAuth subscription.\n */\nfunction oauthQuotaHint(oauthCredential?: boolean): string {\n if (oauthCredential) {\n return \"Quota exhausted on this Claude Code subscription. Wait for the rate-limit window to reset (typically a few minutes for short windows, longer for daily/weekly limits) before retrying. The credential itself is fine.\";\n }\n return \"The Anthropic account hit a rate limit. Wait a moment and try again.\";\n}\n\n/**\n * Try to extract a structured Anthropic error body from a free-text wrapper.\n * The bundled `claude-cli.js` typically formats failures as\n * `... API Error: <status> {\"type\":\"error\",\"error\":{\"type\":\"<errorType>\",...}}`\n * with optional trailing garbage after the JSON.\n *\n * Strategy: find the first `{`, then forward-scan tracking brace depth (with\n * string-literal awareness so braces inside quoted values do not throw the\n * count). The substring from `braceStart` to the matching `}` is the JSON\n * candidate; one `JSON.parse` does the rest. O(n) in the input length.\n *\n * Returns `null` when nothing parseable is found.\n */\nfunction tryParseEmbeddedAnthropicError(\n text: string,\n): { errorType: string; statusCode?: number } | null {\n const braceStart = text.indexOf(\"{\");\n if (braceStart < 0) {\n return null;\n }\n\n const braceEnd = findMatchingCloseBrace(text, braceStart);\n if (braceEnd < 0) {\n return null;\n }\n\n let parsed: { type?: string; error?: { type?: string; message?: string } };\n try {\n parsed = JSON.parse(text.slice(braceStart, braceEnd));\n } catch {\n return null;\n }\n const errorType = parsed?.error?.type;\n if (typeof errorType !== \"string\") {\n return null;\n }\n const statusMatch = text.match(/API Error:\\s*(\\d{3})/i);\n const statusCode = statusMatch ? Number(statusMatch[1]) : undefined;\n return { errorType, statusCode };\n}\n\n/**\n * Forward-scan `text` from `braceStart` (a `{`) with brace counting, returning\n * the index just past the matching close brace, or `-1` if unbalanced.\n * String-literal awareness: skip braces between unescaped double quotes.\n */\nfunction findMatchingCloseBrace(text: string, braceStart: number): number {\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = braceStart; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === 92 /* \\ */) {\n escaped = true;\n } else if (ch === 34 /* \" */) {\n inString = false;\n }\n continue;\n }\n if (ch === 34 /* \" */) {\n inString = true;\n } else if (ch === 123 /* { */) {\n depth++;\n } else if (ch === 125 /* } */) {\n depth--;\n if (depth === 0) {\n return i + 1;\n }\n }\n }\n return -1;\n}\n","// The registry selector a live model change (`reconfigure({ model })`) leaves a\n// session on. Shared by the runner's `runner.reconfigure` handler and every\n// harness whose `reconfigure()` rewrites `modelRef`, so both pick the same entry.\nimport {\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n parseModelRef,\n registryEntries,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/** What a model-only reconfigure does to the session's registry selector. */\nexport type ReconfigureModelScope =\n | {\n ok: true;\n /** The selector to run from now on; `undefined` leaves `modelRef` unset. */\n modelRef: string | undefined;\n }\n | {\n ok: false;\n code: \"model_not_on_provider\";\n /** The entry the session runs on, or the one the patch named. */\n providerId: string;\n message: string;\n };\n\nexport interface ReconfigureModelScopeInput {\n /** The model the patch names: bare, `<providerId>/<modelId>` or `@role`. */\n model: string;\n /** The session's current selector (`AgentConfig.modelRef`). */\n modelRef: string | undefined;\n registry: AIProviderRegistry | MergedAIProviderRegistry | undefined;\n roles?: Record<string, string>;\n}\n\nfunction selectable(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n): Array<[string, AIProviderLlmEntry]> {\n return registryEntries(registry).filter(\n (pair): pair is [string, AIProviderLlmEntry] =>\n (pair[1].kind === \"llm\" || pair[1].kind === \"embed\") && isEntryEnabled(pair[1]),\n );\n}\n\n/**\n * Whether an entry serves a model id. An entry that declares no model at all\n * (no `model_map`, no `capabilities`) passes any id through, as the wake does.\n * Otherwise the id must be a declared logical id or a `model_map` target: the\n * platform sends the provider-side id the wake translated to.\n */\nfunction entryServes(entry: AIProviderLlmEntry, modelId: string): boolean {\n const map = entry.model_map ?? {};\n const caps = entry.capabilities ?? {};\n if (Object.keys(map).length === 0 && Object.keys(caps).length === 0) return true;\n return modelId in map || modelId in caps || Object.values(map).includes(modelId);\n}\n\n/** The entry a selector runs on, resolved the way the harnesses resolve it. */\nfunction currentProviderId(\n modelRef: string | undefined,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n entries: Array<[string, AIProviderLlmEntry]>,\n roles: Record<string, string> | undefined,\n): string | undefined {\n const named = modelRef?.trim();\n if (!named) return entries[0]?.[0];\n // A selector that is exactly an entry id names the endpoint and no model.\n if (entries.some(([id]) => id === named)) return named;\n return parseModelRef(named, registry, roles)?.providerId;\n}\n\n/**\n * Decide the selector a live model change leaves the session on.\n *\n * A bare model id keeps the provider the session already runs on\n * (`<currentProvider>/<model>`): re-resolving it by id alone could move the\n * session to another entry that lists the same id, which changes billing and\n * data residency without a sign. Only a patch that names a provider\n * (`<providerId>/<model>` or `@role`) moves it. When the target entry declares\n * its models and this one is not among them, the patch is refused so the host\n * applies it at the next wake instead.\n *\n * A registry with at most one usable entry has nowhere to move to and keeps the\n * old behaviour: the selector becomes the patch's model when one was set.\n */\nexport function scopeReconfigureModel(input: ReconfigureModelScopeInput): ReconfigureModelScope {\n const { model, modelRef, registry, roles } = input;\n const legacy: ReconfigureModelScope = {\n ok: true,\n modelRef: modelRef === undefined ? undefined : model,\n };\n if (!registry) return legacy;\n const entries = selectable(registry);\n if (entries.length <= 1) return legacy;\n\n const selector = model.trim();\n if (selector.startsWith(\"@\")) return { ok: true, modelRef: selector };\n\n const slash = selector.indexOf(\"/\");\n if (slash > 0) {\n const head = selector.slice(0, slash);\n const tail = selector.slice(slash + 1);\n const named = entries.find(([id]) => id === head);\n if (named && tail !== \"\") {\n if (entryServes(named[1], tail)) return { ok: true, modelRef: selector };\n return refuse(head, tail);\n }\n }\n\n const providerId = currentProviderId(modelRef, registry, entries, roles);\n const current = entries.find(([id]) => id === providerId);\n if (!current) return legacy;\n if (!entryServes(current[1], selector)) return refuse(current[0], selector);\n return { ok: true, modelRef: `${current[0]}/${selector}` };\n}\n\nfunction refuse(providerId: string, modelId: string): ReconfigureModelScope {\n return {\n ok: false,\n code: \"model_not_on_provider\",\n providerId,\n message: `AI provider entry \"${providerId}\" does not list model \"${modelId}\"; the change applies when the session next starts.`,\n };\n}\n","// One owner for a live reconfigure (`AgentHarness.reconfigure()`): the desired\n// config, the snapshot the running process was last given, drift between them,\n// serial ordering of patches, the provider-entry scope rule, rollback on a\n// refusal and the typed outcome. A harness supplies one `applyLive` hook that\n// pushes a delta into its process; everything else lives here.\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { scopeReconfigureModel } from \"./reconfigure-model-ref.js\";\nimport type {\n AgentConfig,\n ReconfigureApplied,\n ReconfigureOutcome,\n ReconfigurePatch,\n ReconfigureRollback,\n} from \"./types.js\";\n\n/** The config fields a live reconfigure reads and writes (the harness's own config object). */\nexport type ReconfigureConfig = Pick<\n AgentConfig,\n \"model\" | \"modelRef\" | \"thinking\" | \"effort\" | \"registry\" | \"roles\"\n>;\n\n/** What the running process holds: the settings it spawned with or was last switched to. */\nexport interface ReconfigureSnapshot {\n model?: string;\n modelRef?: string;\n thinking?: AgentConfig[\"thinking\"];\n effort?: AgentConfig[\"effort\"];\n}\n\n/**\n * What an {@link ReconfigureLedgerOptions.applyLive} hook answers:\n *\n * - `\"applied\"`: the process now runs the delta.\n * - `\"respawn\"`: the process cannot take it live; the harness replaces it before\n * the next turn and the new process reads the desired config.\n * - `{ rejected }`: the process refuses it; the ledger rolls the config back to\n * the snapshot.\n */\nexport type ReconfigureApplyResult = \"applied\" | \"respawn\" | { rejected: string };\n\n/**\n * What an {@link ReconfigureLedgerOptions.applyLive} hook is told about a push.\n * `late` is true when the whole delta was answered `ok` earlier (it landed\n * mid-turn): a refusal then reaches the host only through\n * {@link ReconfigureLedgerOptions.onLateRejection}, so the hook must not also\n * report it on another channel (an `error` event).\n */\nexport interface ReconfigurePushContext {\n late: boolean;\n}\n\nconst FIELDS = [\"model\", \"modelRef\", \"thinking\", \"effort\"] as const;\n\nexport interface ReconfigureLedgerOptions<S extends ReconfigureSnapshot> {\n /**\n * The desired config. A getter, because a harness may replace its config object;\n * the ledger writes accepted patches into whatever it returns.\n */\n config: () => ReconfigureConfig;\n /**\n * Push a delta (the fields whose desired value differs from the snapshot) into\n * the running process. Called with the process up and idle, or at a turn\n * boundary through {@link ReconfigureLedger.flushBeforeTurn}. The hook receives\n * the live snapshot and may refine it (a harness that keeps extra fields on `S`\n * updates them here); on `\"applied\"` the ledger copies the delta into it.\n * A hook that throws counts as a rejection. Its `context.late` says whether a\n * refusal is reported elsewhere (see {@link ReconfigurePushContext}). Absent: the process reads the\n * desired config at its next spawn and there is nothing to push.\n */\n applyLive?: (\n delta: ReconfigureApplied,\n snapshot: S,\n context: ReconfigurePushContext,\n ) => ReconfigureApplyResult | Promise<ReconfigureApplyResult>;\n /** Whether the process is up and can take a push. Default: true. */\n isLive?: () => boolean;\n /** Whether no turn is in flight. Default: true. */\n isIdle?: () => boolean;\n /**\n * Called synchronously once a patch is written to the desired config, before\n * any live push. For harnesses that must refresh a derived cache on a change.\n */\n onDesired?: (applied: ReconfigureApplied) => void;\n /**\n * A refusal that arrives after the patch was already answered `ok` (it landed\n * mid-turn and flushed at the turn boundary). The config is already rolled back\n * when this runs, and an idle-time refusal never calls it (the capability call\n * answers that one). A harness emits the harness event `reconfigure-rollback`.\n */\n onLateRejection?: (rollback: ReconfigureRollback) => void;\n log?: Pick<Logger, \"warn\" | \"info\">;\n}\n\n/**\n * Serialised live reconfigure for one harness.\n *\n * `ok: true` means effective from the next turn: the next turn runs on the new\n * settings by live switch, query recycle or respawn. A patch that lands while a\n * turn is in flight (or before the process is ready) stays desired, is answered\n * `ok`, and is pushed by {@link flushBeforeTurn}.\n *\n * @category Bridge\n */\nexport class ReconfigureLedger<S extends ReconfigureSnapshot = ReconfigureSnapshot> {\n private snapshot: S | null = null;\n private respawn = false;\n private tail: Promise<unknown> | null = null;\n\n constructor(private readonly options: ReconfigureLedgerOptions<S>) {}\n\n /**\n * Record what a freshly spawned process runs. Call at every spawn: the\n * desired config is what that spawn read, so drift is computed against this.\n * `null` forgets the process (nothing left to push to).\n */\n setSnapshot(snapshot: S | null): void {\n this.snapshot = snapshot;\n this.respawn = false;\n }\n\n /**\n * The process cannot take the desired config live and the harness must replace\n * it before the next turn. Cleared by the next {@link setSnapshot}.\n */\n get needsRespawn(): boolean {\n return this.respawn;\n }\n\n /**\n * Apply a patch: scope the model to the session's provider entry, write it to\n * the desired config, and push it when the process is up and idle. Patches run\n * one at a time in arrival order.\n */\n reconfigure(patch: ReconfigurePatch): Promise<ReconfigureOutcome> {\n return this.enqueue(() => this.runPatch(patch));\n }\n\n /**\n * Push any drift to the process at a turn boundary. Await it before the turn\n * is sent, so the turn runs on the desired settings. Never rejects.\n */\n flushBeforeTurn(): Promise<void> {\n return this.enqueue(async () => {\n const snapshot = this.snapshot;\n if (!snapshot || this.respawn || !(this.options.isLive?.() ?? true)) return;\n await this.flush(snapshot, new Set());\n });\n }\n\n private enqueue<T>(job: () => Promise<T>): Promise<T> {\n // With nothing in flight the job's synchronous prefix (scope + write) runs now.\n const run = this.tail ? this.tail.then(job) : job();\n const settled = run.then(\n () => undefined,\n () => undefined,\n );\n this.tail = settled;\n void settled.then(() => {\n if (this.tail === settled) this.tail = null;\n });\n return run;\n }\n\n private async runPatch(patch: ReconfigurePatch): Promise<ReconfigureOutcome> {\n const config = this.options.config();\n const applied: ReconfigureApplied = {};\n if (patch.model !== undefined) {\n // In registry mode the spawned model derives from `modelRef`, so it moves\n // too: scoped to the current entry unless the patch names another one.\n const scope = scopeReconfigureModel({\n model: patch.model,\n modelRef: config.modelRef,\n registry: config.registry,\n roles: config.roles,\n });\n if (!scope.ok) {\n this.options.log?.warn(\"model change refused; keeping the current model\", {\n model: patch.model,\n providerId: scope.providerId,\n });\n return {\n ok: false,\n code: scope.code,\n message: scope.message,\n providerId: scope.providerId,\n };\n }\n config.model = applied.model = patch.model;\n if (scope.modelRef !== undefined) config.modelRef = applied.modelRef = scope.modelRef;\n }\n if (patch.thinking !== undefined) config.thinking = applied.thinking = patch.thinking;\n if (patch.effort !== undefined) config.effort = applied.effort = patch.effort;\n this.options.onDesired?.(applied);\n\n const snapshot = this.snapshot;\n // No process: the next spawn reads the desired config.\n if (!snapshot || this.respawn) return { ok: true, applied };\n const live = this.options.isLive?.() ?? true;\n const idle = this.options.isIdle?.() ?? true;\n // Mid-turn or before ready: stays desired, flushed at the turn boundary.\n if (!live || !idle) return { ok: true, applied };\n\n const own = new Set(Object.keys(applied) as Array<keyof ReconfigureApplied>);\n const rejected = await this.flush(snapshot, own);\n return rejected === null\n ? { ok: true, applied }\n : { ok: false, code: \"rejected\", message: rejected };\n }\n\n /**\n * Push the drift to the process. Returns the refusal message, or `null` when\n * the process took it (or will, by respawn). On a refusal the config rolls back\n * to the snapshot; fields outside `own` were answered `ok` earlier, so they are\n * reported through `onLateRejection`.\n */\n private async flush(\n snapshot: S,\n own: ReadonlySet<keyof ReconfigureApplied>,\n ): Promise<string | null> {\n const hook = this.options.applyLive;\n if (!hook) return null;\n const config = this.options.config();\n const delta: ReconfigureApplied = {};\n for (const key of FIELDS) {\n const value = config[key];\n if (value !== undefined && value !== snapshot[key]) Object.assign(delta, { [key]: value });\n }\n if (Object.keys(delta).length === 0) return null;\n\n // Nothing in the delta was answered to a caller of this push: it is all late.\n const context: ReconfigurePushContext = { late: own.size === 0 };\n let result: ReconfigureApplyResult;\n try {\n result = await hook(delta, snapshot, context);\n } catch (err) {\n result = { rejected: err instanceof Error ? err.message : String(err) };\n }\n // The process was replaced meanwhile; the new one read the desired config.\n if (this.snapshot !== snapshot) return null;\n\n if (result === \"applied\") {\n Object.assign(snapshot, delta);\n return null;\n }\n if (result === \"respawn\") {\n this.respawn = true;\n return null;\n }\n\n const requested: ReconfigureApplied = {};\n const restored: ReconfigureApplied = {};\n for (const key of Object.keys(delta) as (keyof ReconfigureApplied)[]) {\n // The hook may have applied part of the delta and refined the snapshot.\n Object.assign(config, { [key]: snapshot[key] });\n if (!own.has(key)) {\n Object.assign(requested, { [key]: delta[key] });\n Object.assign(restored, { [key]: snapshot[key] });\n }\n }\n this.options.log?.warn(\"live reconfigure refused; config rolled back\", {\n reason: result.rejected,\n fields: Object.keys(delta),\n });\n if (Object.keys(requested).length > 0) {\n this.options.onLateRejection?.({ message: result.rejected, requested, restored });\n }\n return result.rejected;\n }\n}\n","/**\n * Environment variables that belong to the runner process and must never reach\n * an agent child (the CLI, its tools, MCP servers, hooks).\n *\n * `SKAILE_WS_AUTH_TOKEN` authenticates the host on the runner's own WebSocket.\n * An agent that can read it can connect to the runner as the host and send host\n * commands (prompts, connector mutations such as flow-gate approvals). The\n * runner removes it from `process.env` at startup; every harness strips it again\n * from the env it hands its child, so a value that slips back in through\n * `AgentConfig.env` or an embedder that skipped the startup scrub still stops\n * at the harness.\n */\nexport const RUNNER_PRIVATE_ENV_KEYS: readonly string[] = [\n \"SKAILE_WS_AUTH_TOKEN\",\n \"SKAILE_WS_AUTH_TOKEN_FILE\",\n];\n\n/**\n * Remove every {@link RUNNER_PRIVATE_ENV_KEYS} entry from `env`, in place, and\n * return it. Call it on the final child env, after every merge.\n */\nexport function stripRunnerPrivateEnv<T extends Record<string, string | undefined>>(env: T): T {\n for (const key of RUNNER_PRIVATE_ENV_KEYS) delete env[key];\n return env;\n}\n"]}