@skaile/workspaces 5.16.0 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (369) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/app-sdk/index.js +1 -1
  3. package/dist/{asset-feeds-BELBSJEE.js → asset-feeds-WAKBHGEV.js} +21 -21
  4. package/dist/{asset-feeds-BELBSJEE.js.map → asset-feeds-WAKBHGEV.js.map} +1 -1
  5. package/dist/asset-manager/catalog-deployer.js +8 -8
  6. package/dist/asset-manager/index.js +18 -14
  7. package/dist/asset-manager/installer.js +10 -10
  8. package/dist/asset-manager/renderers.js +9 -9
  9. package/dist/asset-manager/src/index.d.ts +122 -5
  10. package/dist/asset-manager/src/index.d.ts.map +1 -1
  11. package/dist/asset-manager/src/installer.d.ts +13 -10
  12. package/dist/asset-manager/src/installer.d.ts.map +1 -1
  13. package/dist/asset-manager/src/mcp-config.d.ts +61 -1
  14. package/dist/asset-manager/src/mcp-config.d.ts.map +1 -1
  15. package/dist/asset-manager/src/renderers.d.ts.map +1 -1
  16. package/dist/bridge/drivers/claude-sdk.js +287 -104
  17. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  18. package/dist/bridge/drivers/codex.js +12 -12
  19. package/dist/bridge/drivers/continue.js +11 -11
  20. package/dist/bridge/drivers/echo.js +4 -4
  21. package/dist/bridge/drivers/gemini.js +7 -7
  22. package/dist/bridge/drivers/goose.js +11 -11
  23. package/dist/bridge/drivers/omp.js +34 -8
  24. package/dist/bridge/drivers/omp.js.map +1 -1
  25. package/dist/bridge/drivers/opencode.js +11 -11
  26. package/dist/bridge/drivers/qwen.js +7 -7
  27. package/dist/bridge/index.js +16 -16
  28. package/dist/bridge/src/driver-model-check.d.ts +8 -8
  29. package/dist/bridge/src/driver-model-check.d.ts.map +1 -1
  30. package/dist/bridge/src/drivers/claude-sdk.d.ts +74 -20
  31. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  32. package/dist/bridge/src/drivers/claude-self-turns.d.ts +25 -6
  33. package/dist/bridge/src/drivers/claude-self-turns.d.ts.map +1 -1
  34. package/dist/bridge/src/drivers/omp-models-yml.d.ts +5 -0
  35. package/dist/bridge/src/drivers/omp-models-yml.d.ts.map +1 -1
  36. package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
  37. package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts +10 -0
  38. package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts.map +1 -1
  39. package/dist/bridge/src/drivers/scrub-transcript.d.ts +20 -0
  40. package/dist/bridge/src/drivers/scrub-transcript.d.ts.map +1 -1
  41. package/dist/bridge/src/index.d.ts +1 -1
  42. package/dist/bridge/src/index.d.ts.map +1 -1
  43. package/dist/{chunk-FWAJUWXQ.js → chunk-24AXETE3.js} +55 -17
  44. package/dist/chunk-24AXETE3.js.map +1 -0
  45. package/dist/{chunk-ZVZTCDUN.js → chunk-2NOLF7B2.js} +37 -9
  46. package/dist/chunk-2NOLF7B2.js.map +1 -0
  47. package/dist/{chunk-NSNM2ZXF.js → chunk-3KMREAR2.js} +45 -5
  48. package/dist/chunk-3KMREAR2.js.map +1 -0
  49. package/dist/{chunk-D54T2F54.js → chunk-5TBFN46Z.js} +4 -4
  50. package/dist/chunk-5TBFN46Z.js.map +1 -0
  51. package/dist/{chunk-6RTEUWXX.js → chunk-6HK6RUFM.js} +3 -3
  52. package/dist/{chunk-6RTEUWXX.js.map → chunk-6HK6RUFM.js.map} +1 -1
  53. package/dist/{chunk-PGZDSDOB.js → chunk-6Z5KTFJT.js} +3 -3
  54. package/dist/{chunk-PGZDSDOB.js.map → chunk-6Z5KTFJT.js.map} +1 -1
  55. package/dist/{chunk-PW3TYWOI.js → chunk-AJ7EGIFR.js} +3 -3
  56. package/dist/{chunk-PW3TYWOI.js.map → chunk-AJ7EGIFR.js.map} +1 -1
  57. package/dist/{chunk-46IRZJV4.js → chunk-CD7SVH6W.js} +4 -4
  58. package/dist/{chunk-46IRZJV4.js.map → chunk-CD7SVH6W.js.map} +1 -1
  59. package/dist/{chunk-WKEBNB5S.js → chunk-CKBCX3HQ.js} +4 -4
  60. package/dist/{chunk-WKEBNB5S.js.map → chunk-CKBCX3HQ.js.map} +1 -1
  61. package/dist/{chunk-H7R7R5BN.js → chunk-CKICWXMU.js} +18 -15
  62. package/dist/chunk-CKICWXMU.js.map +1 -0
  63. package/dist/{chunk-YK3XLEQJ.js → chunk-CKNIYIV2.js} +83 -77
  64. package/dist/chunk-CKNIYIV2.js.map +1 -0
  65. package/dist/{chunk-SPV2CXJ3.js → chunk-D6UBEYQH.js} +4 -4
  66. package/dist/{chunk-SPV2CXJ3.js.map → chunk-D6UBEYQH.js.map} +1 -1
  67. package/dist/{chunk-5CE6J4DB.js → chunk-DA2MCPFN.js} +53 -16
  68. package/dist/chunk-DA2MCPFN.js.map +1 -0
  69. package/dist/{chunk-A26MUUN7.js → chunk-DJD36HC5.js} +7 -7
  70. package/dist/{chunk-A26MUUN7.js.map → chunk-DJD36HC5.js.map} +1 -1
  71. package/dist/{chunk-Y25V2MW2.js → chunk-E5YNGE3I.js} +4 -4
  72. package/dist/{chunk-Y25V2MW2.js.map → chunk-E5YNGE3I.js.map} +1 -1
  73. package/dist/{chunk-OJHPG6HK.js → chunk-EELKR2WP.js} +45 -28
  74. package/dist/chunk-EELKR2WP.js.map +1 -0
  75. package/dist/{chunk-YIDZJHY6.js → chunk-EFLKSMCO.js} +3 -3
  76. package/dist/{chunk-YIDZJHY6.js.map → chunk-EFLKSMCO.js.map} +1 -1
  77. package/dist/{chunk-SMUIYYCH.js → chunk-EZVZDCHZ.js} +24 -15
  78. package/dist/chunk-EZVZDCHZ.js.map +1 -0
  79. package/dist/{chunk-SAGBVBY2.js → chunk-FHIMIXT3.js} +5 -5
  80. package/dist/{chunk-SAGBVBY2.js.map → chunk-FHIMIXT3.js.map} +1 -1
  81. package/dist/{chunk-D5REDKVU.js → chunk-FKU57Q5Q.js} +3 -3
  82. package/dist/{chunk-D5REDKVU.js.map → chunk-FKU57Q5Q.js.map} +1 -1
  83. package/dist/{chunk-J4RRH2NP.js → chunk-FV2MSBVA.js} +4 -4
  84. package/dist/{chunk-J4RRH2NP.js.map → chunk-FV2MSBVA.js.map} +1 -1
  85. package/dist/{chunk-YW2BNDSE.js → chunk-GOCWM7FN.js} +22 -4
  86. package/dist/chunk-GOCWM7FN.js.map +1 -0
  87. package/dist/{chunk-TXGVG7VH.js → chunk-GRKU3S5V.js} +3 -3
  88. package/dist/{chunk-TXGVG7VH.js.map → chunk-GRKU3S5V.js.map} +1 -1
  89. package/dist/{chunk-AP24HESN.js → chunk-H6UVIKQ2.js} +3 -3
  90. package/dist/{chunk-AP24HESN.js.map → chunk-H6UVIKQ2.js.map} +1 -1
  91. package/dist/{chunk-ES6ARJPQ.js → chunk-HPVMTX6M.js} +15 -10
  92. package/dist/chunk-HPVMTX6M.js.map +1 -0
  93. package/dist/{chunk-A7AZ3RL5.js → chunk-JJ7LDI3S.js} +7 -7
  94. package/dist/{chunk-A7AZ3RL5.js.map → chunk-JJ7LDI3S.js.map} +1 -1
  95. package/dist/{chunk-OHNNCXMB.js → chunk-JY7GVNYU.js} +32 -18
  96. package/dist/chunk-JY7GVNYU.js.map +1 -0
  97. package/dist/{chunk-HUKUYWBJ.js → chunk-JYWW32JI.js} +17 -6
  98. package/dist/chunk-JYWW32JI.js.map +1 -0
  99. package/dist/{chunk-VJ2DZLDM.js → chunk-K5LVU2MN.js} +13 -7
  100. package/dist/chunk-K5LVU2MN.js.map +1 -0
  101. package/dist/{chunk-5RDZ5JHH.js → chunk-KC6HGWXN.js} +4 -4
  102. package/dist/{chunk-5RDZ5JHH.js.map → chunk-KC6HGWXN.js.map} +1 -1
  103. package/dist/{chunk-X5O56UO4.js → chunk-L2AMXONH.js} +3 -3
  104. package/dist/chunk-L2AMXONH.js.map +1 -0
  105. package/dist/{chunk-RTNWU2UD.js → chunk-L5XUEC2W.js} +4 -4
  106. package/dist/{chunk-RTNWU2UD.js.map → chunk-L5XUEC2W.js.map} +1 -1
  107. package/dist/{chunk-TKI7YDWE.js → chunk-L6IFN6ER.js} +54 -9
  108. package/dist/chunk-L6IFN6ER.js.map +1 -0
  109. package/dist/{chunk-L6UMSKDF.js → chunk-LW7ZI6EQ.js} +8 -36
  110. package/dist/chunk-LW7ZI6EQ.js.map +1 -0
  111. package/dist/{chunk-XGR7IDTY.js → chunk-MQIRRN76.js} +3 -3
  112. package/dist/{chunk-XGR7IDTY.js.map → chunk-MQIRRN76.js.map} +1 -1
  113. package/dist/{chunk-ISSYT5AZ.js → chunk-N5P2WBUL.js} +3 -3
  114. package/dist/{chunk-ISSYT5AZ.js.map → chunk-N5P2WBUL.js.map} +1 -1
  115. package/dist/{chunk-E634MBP6.js → chunk-ODDATIII.js} +8 -8
  116. package/dist/{chunk-E634MBP6.js.map → chunk-ODDATIII.js.map} +1 -1
  117. package/dist/{chunk-WXWQNJCT.js → chunk-PUK7TQT4.js} +3 -3
  118. package/dist/{chunk-WXWQNJCT.js.map → chunk-PUK7TQT4.js.map} +1 -1
  119. package/dist/{chunk-72KZJE3G.js → chunk-PZ6NF5DE.js} +16 -23
  120. package/dist/chunk-PZ6NF5DE.js.map +1 -0
  121. package/dist/{chunk-5DCOG5B5.js → chunk-RD6N2D7I.js} +3 -3
  122. package/dist/{chunk-5DCOG5B5.js.map → chunk-RD6N2D7I.js.map} +1 -1
  123. package/dist/{chunk-TADJCATD.js → chunk-RO2BPKXK.js} +3 -3
  124. package/dist/{chunk-TADJCATD.js.map → chunk-RO2BPKXK.js.map} +1 -1
  125. package/dist/{chunk-6GSE63K2.js → chunk-SRNCN4X2.js} +13 -5
  126. package/dist/chunk-SRNCN4X2.js.map +1 -0
  127. package/dist/{chunk-PIC23DDE.js → chunk-T2TQAH2X.js} +42 -11
  128. package/dist/chunk-T2TQAH2X.js.map +1 -0
  129. package/dist/{chunk-DADAZLFW.js → chunk-TDQ2ERCM.js} +695 -96
  130. package/dist/chunk-TDQ2ERCM.js.map +1 -0
  131. package/dist/{chunk-SXWGLW23.js → chunk-U2FI547Z.js} +4 -4
  132. package/dist/{chunk-SXWGLW23.js.map → chunk-U2FI547Z.js.map} +1 -1
  133. package/dist/{chunk-CQFVKN6S.js → chunk-V4RV2NJF.js} +240 -84
  134. package/dist/chunk-V4RV2NJF.js.map +1 -0
  135. package/dist/{chunk-D3PU3C6F.js → chunk-VKPBUPH7.js} +41 -15
  136. package/dist/chunk-VKPBUPH7.js.map +1 -0
  137. package/dist/{chunk-FT4ZHLYR.js → chunk-WDXZA7QW.js} +33 -3
  138. package/dist/chunk-WDXZA7QW.js.map +1 -0
  139. package/dist/{chunk-FSSRBWYL.js → chunk-WJCQFNF6.js} +4 -4
  140. package/dist/chunk-WJCQFNF6.js.map +1 -0
  141. package/dist/{chunk-2SKPPIV7.js → chunk-WJLYL6RY.js} +5 -5
  142. package/dist/{chunk-2SKPPIV7.js.map → chunk-WJLYL6RY.js.map} +1 -1
  143. package/dist/{chunk-6Q7NKTDG.js → chunk-X54YR4AW.js} +2 -2
  144. package/dist/{chunk-6Q7NKTDG.js.map → chunk-X54YR4AW.js.map} +1 -1
  145. package/dist/{chunk-D5WTOVLG.js → chunk-Y56YIT6J.js} +2 -2
  146. package/dist/chunk-Y56YIT6J.js.map +1 -0
  147. package/dist/{chunk-ZIW34FGO.js → chunk-YIF2IJUA.js} +3 -3
  148. package/dist/{chunk-ZIW34FGO.js.map → chunk-YIF2IJUA.js.map} +1 -1
  149. package/dist/{chunk-HG52NGAV.js → chunk-YU6AURJY.js} +3 -3
  150. package/dist/{chunk-HG52NGAV.js.map → chunk-YU6AURJY.js.map} +1 -1
  151. package/dist/{chunk-FSLVMZXR.js → chunk-YZ3N7IUU.js} +72 -31
  152. package/dist/chunk-YZ3N7IUU.js.map +1 -0
  153. package/dist/{chunk-DQOAPR4M.js → chunk-ZNN7ONJX.js} +8 -4
  154. package/dist/chunk-ZNN7ONJX.js.map +1 -0
  155. package/dist/cli/index.js +349 -150
  156. package/dist/cli/index.js.map +1 -1
  157. package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
  158. package/dist/cli/src/commands/catalog.d.ts.map +1 -1
  159. package/dist/cli/src/commands/config.d.ts.map +1 -1
  160. package/dist/cli/src/commands/integration.d.ts.map +1 -1
  161. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  162. package/dist/cli/src/commands/library-publish.d.ts.map +1 -1
  163. package/dist/cli/src/commands/plugin/claude-code.d.ts.map +1 -1
  164. package/dist/cli/src/commands/plugin/codex.d.ts +6 -0
  165. package/dist/cli/src/commands/plugin/codex.d.ts.map +1 -1
  166. package/dist/cli/src/commands/project.d.ts.map +1 -1
  167. package/dist/cli/src/commands/run.d.ts.map +1 -1
  168. package/dist/cli/src/commands/serve.d.ts +5 -0
  169. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  170. package/dist/cli/src/commands/source.d.ts.map +1 -1
  171. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  172. package/dist/cli/src/commands/verify.d.ts.map +1 -1
  173. package/dist/cli/src/driver-error.d.ts +3 -1
  174. package/dist/cli/src/driver-error.d.ts.map +1 -1
  175. package/dist/cli/src/helpers.d.ts +6 -4
  176. package/dist/cli/src/helpers.d.ts.map +1 -1
  177. package/dist/cli/src/plugin-store/index.d.ts +6 -0
  178. package/dist/cli/src/plugin-store/index.d.ts.map +1 -1
  179. package/dist/cli/src/skill-checks.d.ts +4 -3
  180. package/dist/cli/src/skill-checks.d.ts.map +1 -1
  181. package/dist/connectors/config.js +5 -5
  182. package/dist/connectors/index.js +22 -22
  183. package/dist/connectors/src/connector-manager.d.ts.map +1 -1
  184. package/dist/connectors/src/connector-types.d.ts +5 -0
  185. package/dist/connectors/src/connector-types.d.ts.map +1 -1
  186. package/dist/connectors/src/watcher.d.ts.map +1 -1
  187. package/dist/{connectors-44RE2QEM.js → connectors-QL4GBMH3.js} +25 -25
  188. package/dist/{connectors-44RE2QEM.js.map → connectors-QL4GBMH3.js.map} +1 -1
  189. package/dist/connectors-shared/index.js +2 -2
  190. package/dist/core/index.js +7 -7
  191. package/dist/core/manifest.js +2 -2
  192. package/dist/core/models.js +1 -1
  193. package/dist/core/publish-manifest.js +3 -3
  194. package/dist/core/ref.js +1 -1
  195. package/dist/core/runtime-assets.js +5 -5
  196. package/dist/core/src/bind.d.ts +30 -0
  197. package/dist/core/src/bind.d.ts.map +1 -0
  198. package/dist/core/src/index.d.ts +4 -3
  199. package/dist/core/src/index.d.ts.map +1 -1
  200. package/dist/core/src/lock.d.ts +11 -2
  201. package/dist/core/src/lock.d.ts.map +1 -1
  202. package/dist/core/src/manifest.d.ts.map +1 -1
  203. package/dist/core/src/models.d.ts +19 -0
  204. package/dist/core/src/models.d.ts.map +1 -1
  205. package/dist/core/src/publish-manifest.d.ts +15 -13
  206. package/dist/core/src/publish-manifest.d.ts.map +1 -1
  207. package/dist/core/src/store.d.ts +2 -1
  208. package/dist/core/src/store.d.ts.map +1 -1
  209. package/dist/core/src/workspace-config.d.ts +26 -1
  210. package/dist/core/src/workspace-config.d.ts.map +1 -1
  211. package/dist/core/store.js +1 -1
  212. package/dist/core/workspace-config.js +4 -4
  213. package/dist/deploy/index.js +7 -7
  214. package/dist/discovery/index.js +5 -5
  215. package/dist/discovery/src/parse-manifest.d.ts +1 -1
  216. package/dist/discovery/src/source-config.d.ts +2 -1
  217. package/dist/discovery/src/source-config.d.ts.map +1 -1
  218. package/dist/{ensure-sources-R6AHZ7RV.js → ensure-sources-CEFODJCE.js} +21 -17
  219. package/dist/ensure-sources-CEFODJCE.js.map +1 -0
  220. package/dist/factory-assets/connectors/box.js +22 -22
  221. package/dist/factory-assets/connectors/deploy.js +22 -22
  222. package/dist/factory-assets/connectors/devserver.js +22 -22
  223. package/dist/factory-assets/connectors/flow/adapter.js +22 -22
  224. package/dist/factory-assets/connectors/flow/engine.js +9 -9
  225. package/dist/factory-assets/connectors/flow/run-flow.js +24 -24
  226. package/dist/factory-assets/connectors/flow.js +22 -22
  227. package/dist/factory-assets/connectors/git.js +22 -22
  228. package/dist/factory-assets/connectors/gmail.js +22 -22
  229. package/dist/factory-assets/connectors/googledrive.js +22 -22
  230. package/dist/factory-assets/connectors/local.js +22 -22
  231. package/dist/factory-assets/connectors/mattermost.js +22 -22
  232. package/dist/factory-assets/connectors/memory.js +22 -22
  233. package/dist/factory-assets/connectors/minio.js +22 -22
  234. package/dist/factory-assets/connectors/postgres.js +22 -22
  235. package/dist/factory-assets/connectors/s3.js +22 -22
  236. package/dist/factory-assets/connectors/sharepoint.js +22 -22
  237. package/dist/factory-assets/connectors/sqlite.js +22 -22
  238. package/dist/factory-assets/connectors/static-server.js +22 -22
  239. package/dist/factory-assets/connectors/tunnel.js +22 -22
  240. package/dist/factory-assets/connectors/webdav.js +22 -22
  241. package/dist/factory-assets/connectors/xstate-store/adapter.d.ts +1 -1
  242. package/dist/factory-assets/connectors/xstate-store/adapter.d.ts.map +1 -1
  243. package/dist/factory-assets/connectors/xstate-store.js +22 -22
  244. package/dist/factory-assets/connectors/xstate.js +22 -22
  245. package/dist/{flows-YKC53LDP.js → flows-BHY73K3O.js} +12 -12
  246. package/dist/{flows-YKC53LDP.js.map → flows-BHY73K3O.js.map} +1 -1
  247. package/dist/{helpers-FNQL5PI7.js → helpers-R22QNPFN.js} +21 -17
  248. package/dist/{helpers-FNQL5PI7.js.map → helpers-R22QNPFN.js.map} +1 -1
  249. package/dist/library/index.js +11 -11
  250. package/dist/library/install.js +4 -4
  251. package/dist/library/src/index.d.ts +1 -1
  252. package/dist/library/src/index.d.ts.map +1 -1
  253. package/dist/library/src/manifest-writer.d.ts +17 -1
  254. package/dist/library/src/manifest-writer.d.ts.map +1 -1
  255. package/dist/{library-publish-GHPVY42Y.js → library-publish-VBE3X2TH.js} +63 -66
  256. package/dist/library-publish-VBE3X2TH.js.map +1 -0
  257. package/dist/model-endpoint/index.js +10 -10
  258. package/dist/model-endpoint/src/server.d.ts.map +1 -1
  259. package/dist/open-library-JP5TC5UX.js +42 -0
  260. package/dist/{open-library-YSUGNP36.js.map → open-library-JP5TC5UX.js.map} +1 -1
  261. package/dist/open-registry-RBELV5YH.js +32 -0
  262. package/dist/{open-registry-YPRQDUMK.js.map → open-registry-RBELV5YH.js.map} +1 -1
  263. package/dist/paths-BFM6K2QO.js +22 -0
  264. package/dist/{paths-P55DTBEK.js.map → paths-BFM6K2QO.js.map} +1 -1
  265. package/dist/plugin-store-QOQDM24E.js +23 -0
  266. package/dist/{plugin-store-IPIBZRBX.js.map → plugin-store-QOQDM24E.js.map} +1 -1
  267. package/dist/{project-NDSLXERO.js → project-6ETXGQWD.js} +48 -48
  268. package/dist/{project-NDSLXERO.js.map → project-6ETXGQWD.js.map} +1 -1
  269. package/dist/resolver/index.js +8 -8
  270. package/dist/runner/index.js +40 -40
  271. package/dist/runner/src/agent.d.ts.map +1 -1
  272. package/dist/runner/src/capability-roundtrip.d.ts.map +1 -1
  273. package/dist/runner/src/coalesced-restart.d.ts +41 -0
  274. package/dist/runner/src/coalesced-restart.d.ts.map +1 -0
  275. package/dist/runner/src/compaction/prompt.d.ts.map +1 -1
  276. package/dist/runner/src/mcp-runtime-handlers.d.ts +27 -0
  277. package/dist/runner/src/mcp-runtime-handlers.d.ts.map +1 -1
  278. package/dist/runner/src/runner-capabilities.d.ts +7 -0
  279. package/dist/runner/src/runner-capabilities.d.ts.map +1 -1
  280. package/dist/runner/src/serve.d.ts.map +1 -1
  281. package/dist/runner/src/session-capability-wiring.d.ts +2 -0
  282. package/dist/runner/src/session-capability-wiring.d.ts.map +1 -1
  283. package/dist/sdk/asset-manager.js +18 -14
  284. package/dist/sdk/bridge.js +16 -16
  285. package/dist/sdk/core.js +7 -7
  286. package/dist/sdk/flow.js +9 -9
  287. package/dist/sdk/index.js +40 -40
  288. package/dist/sdk/resolver.js +8 -8
  289. package/dist/sdk/runner.js +40 -40
  290. package/dist/sdk/session.js +2 -2
  291. package/dist/sdk/transport/ws/server.js +19 -1
  292. package/dist/sdk/transport/ws.js +19 -1
  293. package/dist/sdk/transport.js +19 -1
  294. package/dist/sdk/types.js +1 -1
  295. package/dist/{serve-preflight-ON2LS3SD.js → serve-preflight-BTGTZUDN.js} +9 -9
  296. package/dist/{serve-preflight-ON2LS3SD.js.map → serve-preflight-BTGTZUDN.js.map} +1 -1
  297. package/dist/session/index.js +2 -2
  298. package/dist/{setup-MFPEQS2I.js → setup-JQDTYPSD.js} +30 -26
  299. package/dist/setup-JQDTYPSD.js.map +1 -0
  300. package/dist/{skills-7G6QCDEM.js → skills-RSZVUIYZ.js} +13 -13
  301. package/dist/{skills-7G6QCDEM.js.map → skills-RSZVUIYZ.js.map} +1 -1
  302. package/dist/{source-4QVRD5NV.js → source-FPLHY3DP.js} +50 -50
  303. package/dist/{source-4QVRD5NV.js.map → source-FPLHY3DP.js.map} +1 -1
  304. package/dist/{source-manifest-publish-ZIO24GUM.js → source-manifest-publish-LY4H63VA.js} +52 -52
  305. package/dist/{source-manifest-publish-ZIO24GUM.js.map → source-manifest-publish-LY4H63VA.js.map} +1 -1
  306. package/dist/transport/index.js +19 -1
  307. package/dist/transport/src/ws/server.d.ts +2 -16
  308. package/dist/transport/src/ws/server.d.ts.map +1 -1
  309. package/dist/transport/ws/server.js +19 -1
  310. package/dist/transport/ws.js +19 -1
  311. package/dist/tui/index.js +57 -45
  312. package/dist/tui/index.js.map +1 -1
  313. package/dist/tui/src/repl.d.ts +4 -1
  314. package/dist/tui/src/repl.d.ts.map +1 -1
  315. package/dist/types/index.js +1 -1
  316. package/dist/types/manifests.js +1 -1
  317. package/dist/types/src/events.d.ts +7 -4
  318. package/dist/types/src/events.d.ts.map +1 -1
  319. package/dist/types/src/manifests/index.d.ts +1 -1
  320. package/dist/types/src/manifests/index.d.ts.map +1 -1
  321. package/dist/types/src/manifests/scaffold-body.d.ts +8 -0
  322. package/dist/types/src/manifests/scaffold-body.d.ts.map +1 -1
  323. package/dist/types/src/manifests/skill.d.ts +0 -2
  324. package/dist/types/src/manifests/skill.d.ts.map +1 -1
  325. package/dist/workspace-plugin/adapters/mcp.js +29 -29
  326. package/dist/workspace-plugin/adapters/omp.js +32 -18
  327. package/dist/workspace-plugin/adapters/omp.js.map +1 -1
  328. package/dist/workspace-plugin/index.js +1 -1
  329. package/dist/workspace-plugin/src/adapters/claude-code.d.ts +1 -1
  330. package/dist/workspace-plugin/src/adapters/omp.d.ts +8 -5
  331. package/dist/workspace-plugin/src/adapters/omp.d.ts.map +1 -1
  332. package/dist/workspace-plugin/src/plugin.d.ts +7 -1
  333. package/dist/workspace-plugin/src/plugin.d.ts.map +1 -1
  334. package/package.json +1 -1
  335. package/dist/chunk-5CE6J4DB.js.map +0 -1
  336. package/dist/chunk-6GSE63K2.js.map +0 -1
  337. package/dist/chunk-72KZJE3G.js.map +0 -1
  338. package/dist/chunk-CQFVKN6S.js.map +0 -1
  339. package/dist/chunk-D3PU3C6F.js.map +0 -1
  340. package/dist/chunk-D54T2F54.js.map +0 -1
  341. package/dist/chunk-D5WTOVLG.js.map +0 -1
  342. package/dist/chunk-DADAZLFW.js.map +0 -1
  343. package/dist/chunk-DQOAPR4M.js.map +0 -1
  344. package/dist/chunk-ES6ARJPQ.js.map +0 -1
  345. package/dist/chunk-FSLVMZXR.js.map +0 -1
  346. package/dist/chunk-FSSRBWYL.js.map +0 -1
  347. package/dist/chunk-FT4ZHLYR.js.map +0 -1
  348. package/dist/chunk-FWAJUWXQ.js.map +0 -1
  349. package/dist/chunk-H7R7R5BN.js.map +0 -1
  350. package/dist/chunk-HUKUYWBJ.js.map +0 -1
  351. package/dist/chunk-L6UMSKDF.js.map +0 -1
  352. package/dist/chunk-NSNM2ZXF.js.map +0 -1
  353. package/dist/chunk-OHNNCXMB.js.map +0 -1
  354. package/dist/chunk-OJHPG6HK.js.map +0 -1
  355. package/dist/chunk-PIC23DDE.js.map +0 -1
  356. package/dist/chunk-SMUIYYCH.js.map +0 -1
  357. package/dist/chunk-TKI7YDWE.js.map +0 -1
  358. package/dist/chunk-VJ2DZLDM.js.map +0 -1
  359. package/dist/chunk-X5O56UO4.js.map +0 -1
  360. package/dist/chunk-YK3XLEQJ.js.map +0 -1
  361. package/dist/chunk-YW2BNDSE.js.map +0 -1
  362. package/dist/chunk-ZVZTCDUN.js.map +0 -1
  363. package/dist/ensure-sources-R6AHZ7RV.js.map +0 -1
  364. package/dist/library-publish-GHPVY42Y.js.map +0 -1
  365. package/dist/open-library-YSUGNP36.js +0 -40
  366. package/dist/open-registry-YPRQDUMK.js +0 -32
  367. package/dist/paths-P55DTBEK.js +0 -22
  368. package/dist/plugin-store-IPIBZRBX.js +0 -23
  369. package/dist/setup-MFPEQS2I.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { resolveAgentExec } from './chunk-YROR332M.js';
2
- import { tryWithFsDeadline, fsDeadlineMs, withFsDeadline } from './chunk-YW2BNDSE.js';
2
+ import { tryWithFsDeadline, fsDeadlineMs, withFsDeadline } from './chunk-GOCWM7FN.js';
3
3
  import { entryTransport, normalizeAnthropicBaseUrl, resolveEntryBaseUrl } from './chunk-MJHSLODD.js';
4
4
  import { createWriteStream, createReadStream } from 'fs';
5
5
  import { unlink, rename, readdir, stat } from 'fs/promises';
@@ -221,6 +221,40 @@ var localTranscriptStore = {
221
221
  await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), void 0, fsDeadlineMs());
222
222
  }
223
223
  };
224
+ var COST_STATE_MODEL_FIELDS = [
225
+ "inputTokens",
226
+ "outputTokens",
227
+ "cacheReadInputTokens",
228
+ "cacheCreationInputTokens",
229
+ "webSearchRequests",
230
+ "costUSD"
231
+ ];
232
+ function isCount(value) {
233
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
234
+ }
235
+ function readCostState(line, sessionId) {
236
+ if (!line.includes('"cost-state"')) return null;
237
+ let entry;
238
+ try {
239
+ entry = JSON.parse(line.replace(/^\0+/, ""));
240
+ } catch {
241
+ return null;
242
+ }
243
+ if (entry.type !== "cost-state" || entry.sessionId !== sessionId) return null;
244
+ const total = entry.totalCostUSD;
245
+ if (!isCount(total)) return null;
246
+ const usage = entry.modelUsage;
247
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
248
+ for (const model of Object.values(usage)) {
249
+ if (!model || typeof model !== "object") return null;
250
+ const counters = model;
251
+ if (!COST_STATE_MODEL_FIELDS.every((field) => isCount(counters[field]))) return null;
252
+ }
253
+ return {
254
+ totalCostUSD: total,
255
+ modelUsage: usage
256
+ };
257
+ }
224
258
  function repairLine(line, counters) {
225
259
  if (line.trim() === "") return line;
226
260
  const eol = line.endsWith("\r") ? "\r" : "";
@@ -247,7 +281,8 @@ async function scrubPoisonedTranscript(opts) {
247
281
  corrected: 0,
248
282
  stubbed: 0,
249
283
  cacheStripped: 0,
250
- changed: false
284
+ changed: false,
285
+ costState: null
251
286
  };
252
287
  let filePath;
253
288
  try {
@@ -266,11 +301,15 @@ async function scrubPoisonedTranscript(opts) {
266
301
  }
267
302
  result.filePath = filePath;
268
303
  const counters = { corrected: 0, stubbed: 0, cacheStripped: 0 };
304
+ let costState = null;
269
305
  try {
270
306
  await withFsDeadline(
271
307
  `scan transcript ${filePath}`,
272
308
  async () => {
273
- for await (const line of streamLines(store.read(filePath))) repairLine(line, counters);
309
+ for await (const line of streamLines(store.read(filePath))) {
310
+ repairLine(line, counters);
311
+ costState = readCostState(line, sessionId) ?? costState;
312
+ }
274
313
  },
275
314
  timeoutMs
276
315
  );
@@ -284,6 +323,7 @@ async function scrubPoisonedTranscript(opts) {
284
323
  result.corrected = counters.corrected;
285
324
  result.stubbed = counters.stubbed;
286
325
  result.cacheStripped = counters.cacheStripped;
326
+ result.costState = costState;
287
327
  if (totalChanges(counters) === 0) {
288
328
  return result;
289
329
  }
@@ -512,5 +552,5 @@ async function probeResumeTranscript(sessionId, opts) {
512
552
  }
513
553
 
514
554
  export { ANTHROPIC_DEFAULT_BASE_URL, APPROVE_ONCE, DENY, agentTranscriptStore, approvalCardOf, buildClaudeEndpointEnv, claudeEndpointMode, localTranscriptStore, probeResumeTranscript, resolveClaudeConfigDir, scrubPoisonedTranscript, transcriptStoreForRuntime };
515
- //# sourceMappingURL=chunk-NSNM2ZXF.js.map
516
- //# sourceMappingURL=chunk-NSNM2ZXF.js.map
555
+ //# sourceMappingURL=chunk-3KMREAR2.js.map
556
+ //# sourceMappingURL=chunk-3KMREAR2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../bridge/src/approval-card.ts","../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/agent-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;;;;AAUO,IAAM,YAAA,GAAe;AAErB,IAAM,IAAA,GAAO;AAab,SAAS,eAAe,KAAA,EAA6C;AAC1E,EAAA,IAAI,KAAA,CAAM,IAAA,KAAS,eAAA,IAAmB,CAAC,KAAA,CAAM,QAAQ,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG,OAAO,MAAA;AACpF,EAAA,KAAA,MAAW,KAAA,IAAS,KAAA,CAAM,OAAA,CAAQ,OAAA,EAAS;AACzC,IAAA,IAAI,KAAA,CAAM,IAAA,KAAS,UAAA,IAAc,KAAA,CAAM,SAAS,iBAAA,EAAmB;AACnE,IAAA,MAAM,QAAQ,KAAA,CAAM,KAAA;AACpB,IAAA,MAAM,WAAW,KAAA,EAAO,QAAA;AACxB,IAAA,MAAM,YAAY,KAAA,EAAO,SAAA;AACzB,IAAA,MAAM,QAAQ,KAAA,CAAM,OAAA,CAAQ,SAAS,CAAA,GAAK,SAAA,CAAU,CAAC,CAAA,GAA+B,MAAA;AACpF,IAAA,IACE,CAAC,YACD,OAAO,KAAA,EAAO,aAAa,QAAA,IAC3B,CAAC,MAAM,OAAA,CAAQ,QAAA,CAAS,OAAO,CAAA,IAC/B,CAAC,SAAS,OAAA,CAAQ,KAAA,CAAM,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAQ,CAAA,EACpD;AACA,MAAA;AAA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EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-3KMREAR2.js","sourcesContent":["/**\n * The tool-approval card a driver raises for `permissionMode: \"interactive\"`: a `message_start`\n * carrying an `AskUserQuestion` tool call whose input has an `approval` description. The\n * normalizer turns it into a `question` event with `approval`; a host that reads the driver's\n * events directly (the REPL, a single-shot run) recognises it with {@link approvalCardOf} and\n * answers with {@link APPROVE_ONCE} or {@link DENY} through `driver.answerQuestion`.\n */\nimport type { AgentEvent } from \"./types.js\";\n\n/** The one positive answer of an approval card. */\nexport const APPROVE_ONCE = \"Approve once\";\n/** The negative answer of an approval card. */\nexport const DENY = \"Deny\";\n\n/** What a host needs to ask and answer one approval card. */\nexport interface ApprovalCard {\n /** The question text; the key `answerQuestion` takes. */\n question: string;\n requestId?: string;\n kind: \"command\" | \"file\" | \"permissions\" | \"mcp\";\n /** Bounded plain text of what the tool call is about to do. */\n details: string[];\n}\n\n/** The approval card an event carries, else `undefined`. */\nexport function approvalCardOf(event: AgentEvent): ApprovalCard | undefined {\n if (event.type !== \"message_start\" || !Array.isArray(event.message.content)) return undefined;\n for (const block of event.message.content) {\n if (block.type !== \"tool_use\" || block.name !== \"AskUserQuestion\") continue;\n const input = block.input as Record<string, unknown> | undefined;\n const approval = input?.approval as { kind?: unknown; details?: unknown } | undefined;\n const questions = input?.questions;\n const first = Array.isArray(questions) ? (questions[0] as { question?: unknown }) : undefined;\n if (\n !approval ||\n typeof first?.question !== \"string\" ||\n !Array.isArray(approval.details) ||\n !approval.details.every((d) => typeof d === \"string\")\n ) {\n continue;\n }\n return {\n question: first.question,\n ...(typeof input?.requestId === \"string\" ? { requestId: input.requestId } : {}),\n kind: approval.kind as ApprovalCard[\"kind\"],\n details: approval.details as string[],\n };\n }\n return undefined;\n}\n","/**\n * AI endpoint transport for the `claude-sdk` driver — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the driver calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the driver because the\n * vars it emits — `CLAUDE_CODE_USE_*`, `ANTHROPIC_*` — are the Claude Agent\n * SDK's own contract, not a portable one).\n *\n * A registry entry says what the deleted `cloud` axis said — Amazon Bedrock,\n * Google Vertex AI, Azure AI Foundry, a generic gateway — with `surface` +\n * `transport` + `base_url` + `credential`, and says it for the direct\n * endpoint too, which the `cloud` axis could not address at all.\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n entryTransport,\n normalizeAnthropicBaseUrl,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/**\n * Env vars scrubbed from the inherited environment before an endpoint env is\n * assembled. Ambient first-party credentials or a stale `CLAUDE_CODE_USE_*`\n * flag must never leak into a session whose entry points elsewhere (the\n * ambient carriers are restored explicitly when the entry has none of its\n * own).\n *\n * Deliberately NOT exhaustive: ambient transport-specific vars (AWS_*,\n * GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive so a\n * standalone CLI inherits its own signing chain; the SDK ignores vars whose\n * transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * The Anthropic first-party endpoint. An entry that resolves to exactly this\n * host needs no `ANTHROPIC_BASE_URL`: the SDK already points there, and an\n * explicit value would make every default session look like a third-party\n * redirect to Claude Code's own telemetry and auth heuristics.\n */\nexport const ANTHROPIC_DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n/**\n * Headers the SDK owns and an entry must not restate through\n * `ANTHROPIC_CUSTOM_HEADERS`: the protocol version it was built against, and\n * the two credential carriers (which are `credential.ref`'s job — a literal\n * secret in `headers` is a validation error anyway).\n */\nconst SDK_OWNED_HEADERS: Record<string, true> = {\n \"anthropic-version\": true,\n authorization: true,\n \"x-api-key\": true,\n};\n\n/**\n * Which of the Claude Agent SDK's four native transports an entry addresses.\n *\n * The SDK has no `transport` field: it switches on a `CLAUDE_CODE_USE_*` flag.\n * Bedrock and Vertex are their own wire surfaces, so they are recognized by\n * `surface` as well as by `transport` — a legacy-derived entry that had no\n * region (and therefore no `params`, and therefore no `transport`) is still a\n * Bedrock session, exactly as it was before the registry existed.\n */\nexport type ClaudeEndpointMode = \"anthropic\" | \"bedrock\" | \"vertex\" | \"foundry\";\n\n/** Classify a registry entry into its {@link ClaudeEndpointMode}. */\nexport function claudeEndpointMode(entry: AIProviderEntry): ClaudeEndpointMode {\n const surface = (entry as AIProviderLlmEntry).surface;\n const transport = entryTransport(entry);\n if (surface === \"bedrock-converse-stream\" || transport === \"bedrock\") return \"bedrock\";\n if (surface === \"google-vertex\" || transport === \"vertex\") return \"vertex\";\n if (transport === \"foundry\") return \"foundry\";\n return \"anthropic\";\n}\n\n/** Arguments for {@link buildClaudeEndpointEnv}. */\nexport interface ClaudeEndpointEnvInput {\n /** The selected registry entry — the whole endpoint definition. */\n entry: AIProviderEntry;\n /**\n * The entry's credential, already resolved from its `credential.ref`\n * (`resolveEntryCredential`). Absent for `kind: none`, for an ambient\n * `sigv4` / `google_adc` / `azure_entra` chain, for `oauth` (whose blob the\n * runner writes to the Claude credentials file, never to the env), and for a\n * reference that did not resolve.\n */\n credential?: string;\n /**\n * The driver's base environment — `process.env` with `undefined` dropped.\n * The endpoint vars are layered **on top** of it, never instead of it, so\n * `PATH`, `HOME` and `SKAILE_SESSION_ID` reach the child.\n */\n baseEnv: Record<string, string>;\n /** `AgentConfig.env` plus any credential material the session carried. */\n configEnv?: Record<string, string>;\n}\n\n/**\n * Assemble the Claude Agent SDK child env for one registry entry (plan §2.3).\n *\n * Pure (no external state read, no input mutated). Starts from `baseEnv`\n * merged with `configEnv`, scrubs the inherited Anthropic credential/routing\n * vars and every `CLAUDE_CODE_USE_*` flag, then writes exactly what the entry\n * describes: at most one transport flag, the endpoint, and the credential in\n * the carrier its `kind` names.\n *\n * Credential kinds (§1.4): `api_key_header` → `ANTHROPIC_API_KEY` (the SDK\n * sends it as `x-api-key`); `bearer` → `ANTHROPIC_AUTH_TOKEN` (sent as\n * `Authorization: Bearer`); `sigv4` / `google_adc` / `azure_entra` emit\n * nothing and let the AWS/Google/Azure chain sign — which is why the scrub\n * deliberately spares ambient `AWS_*` / `GOOGLE_*` values; `oauth` and `none`\n * emit nothing, and the pre-scrub ambient carriers are restored so an OAuth or\n * shell-configured session keeps the auth it had.\n *\n * Never returns `undefined` or empty values; absent settings are omitted.\n */\nexport function buildClaudeEndpointEnv(args: ClaudeEndpointEnvInput): Record<string, string> {\n const { entry, credential, baseEnv, configEnv } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — an entry with no credential material of its\n // own falls back to these, the way the gateway branch always has.\n const ambient = { authToken: env.ANTHROPIC_AUTH_TOKEN, apiKey: env.ANTHROPIC_API_KEY };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n const kind = entry.credential?.kind ?? \"none\";\n const params = (entry as AIProviderLlmEntry).params as Record<string, string> | undefined;\n\n // Static headers ride as ANTHROPIC_CUSTOM_HEADERS (`Name: Value` per line),\n // the only channel the SDK offers. An entry with none leaves an ambient\n // value alone.\n const headers = Object.entries(entry.headers ?? {}).filter(\n ([name]) => !SDK_OWNED_HEADERS[name.toLowerCase()],\n );\n if (headers.length > 0) {\n env.ANTHROPIC_CUSTOM_HEADERS = headers.map(([name, value]) => `${name}: ${value}`).join(\"\\n\");\n }\n\n switch (claudeEndpointMode(entry)) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // The AWS credential bundle itself is `configEnv` material (AWS_*), and\n // ambient AWS_* survived the scrub, so a standalone CLI keeps its own.\n set(\"AWS_REGION\", params?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // GOOGLE_APPLICATION_CREDENTIALS is a path the runner materialized; it\n // arrives through `configEnv` or ambient, never from `credential`.\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", params?.project);\n set(\"CLOUD_ML_REGION\", params?.location);\n break;\n }\n case \"foundry\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n // §1.3: an explicit `base_url` wins over the resource-derived endpoint,\n // and the SDK has a separate var for each form.\n if (entry.base_url) set(\"ANTHROPIC_FOUNDRY_BASE_URL\", entry.base_url);\n else set(\"ANTHROPIC_FOUNDRY_RESOURCE\", params?.resource);\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", credential);\n break;\n }\n case \"anthropic\": {\n const baseUrl = normalizeAnthropicBaseUrl(resolveEntryBaseUrl(entry));\n if (baseUrl && baseUrl.toLowerCase() !== ANTHROPIC_DEFAULT_BASE_URL) {\n env.ANTHROPIC_BASE_URL = baseUrl;\n }\n if (kind === \"bearer\") set(\"ANTHROPIC_AUTH_TOKEN\", credential);\n else if (kind === \"api_key_header\") set(\"ANTHROPIC_API_KEY\", credential);\n if (!credential) {\n // `oauth` / `none` / an unresolved ref: the ambient carriers are the\n // only auth this session has, and the scrub just removed them.\n if (ambient.authToken) env.ANTHROPIC_AUTH_TOKEN = ambient.authToken;\n else set(\"ANTHROPIC_API_KEY\", ambient.apiKey);\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n /**\n * Where the transcript is read and written. Defaults to this process's own\n * filesystem access ({@link localTranscriptStore}); with the agent uid split\n * the transcript belongs to the agent uid and must be reached through it.\n */\n store?: TranscriptStore;\n}\n\n/**\n * Filesystem access to Claude Code transcripts. The CLI creates them 0600 in\n * 0700 dirs, so when it runs as a different uid than the runner, only that uid\n * can locate, read or rewrite them (see `agent-transcript.ts`).\n *\n * @category Transcript repair\n */\nexport interface TranscriptStore {\n /** Path of `<sessionId>.jsonl` under `<configDir>/projects/`, or `null` when absent. */\n locate(configDir: string, sessionId: string, timeoutMs?: number): Promise<string | null>;\n /** The file's contents as UTF-8 chunks. */\n read(filePath: string): AsyncIterable<string>;\n /** Atomically replace the file with `chunks` via a `.scrub-tmp` sibling. */\n replace(filePath: string, chunks: AsyncIterable<string>): Promise<void>;\n /** Remove the sibling a failed or abandoned {@link replace} left (best effort). */\n discardTemp(filePath: string): Promise<void>;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n /**\n * The last valid `cost-state` entry of this session, read during the same\n * pass. The CLI restores its run totals from it on `--resume`, so it is the\n * baseline of the resumed spawn's first `total_cost_usd` and `modelUsage`.\n * `null` when the transcript holds none (the CLI then starts from zero) or\n * could not be read.\n */\n costState: TranscriptCostState | null;\n}\n\n/**\n * The run totals the Claude Code CLI saves into a transcript as a\n * `{\"type\":\"cost-state\"}` entry and restores on `--resume`.\n *\n * @category Transcript repair\n */\nexport interface TranscriptCostState {\n /** The CLI's run-cumulative `total_cost_usd` at the time of the save. */\n totalCostUSD: number;\n /** The CLI's run-cumulative per-model usage, keyed by model id, in SDK field names. */\n modelUsage: Record<string, Record<string, number>>;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(chunks: AsyncIterable<string>): AsyncGenerator<string> {\n let pending = \"\";\n for await (const chunk of chunks) {\n pending += chunk;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n}\n\n/**\n * The runner's own filesystem access: the default {@link TranscriptStore}.\n *\n * @category Transcript repair\n */\nexport const localTranscriptStore: TranscriptStore = {\n locate: (configDir, sessionId, timeoutMs) =>\n locateTranscriptPath(configDir, sessionId, timeoutMs),\n async *read(filePath) {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n try {\n for await (const chunk of stream) yield chunk as string;\n } finally {\n stream.destroy();\n }\n },\n async replace(filePath, chunks) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await pipeline(chunks, createWriteStream(tmpPath, { encoding: \"utf8\" }));\n await rename(tmpPath, filePath);\n },\n async discardTemp(filePath) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, fsDeadlineMs());\n },\n};\n\n/**\n * Per-model counters the CLI's `cost-state` schema requires (checked against\n * `@anthropic-ai/claude-agent-sdk` 0.3.289; `thinkingTokens` is optional there).\n */\nconst COST_STATE_MODEL_FIELDS = [\n \"inputTokens\",\n \"outputTokens\",\n \"cacheReadInputTokens\",\n \"cacheCreationInputTokens\",\n \"webSearchRequests\",\n \"costUSD\",\n] as const;\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\n/**\n * Read a `cost-state` entry of `sessionId` off one JSONL line, or `null` when\n * the line is anything else. Mirrors the CLI, which skips an entry that fails\n * its schema and keeps the last valid one, so an entry with a bad total or a\n * per-model counter that is not a non-negative number is not a restorable\n * state. Leading NUL bytes (a torn append) are stripped, as the CLI does.\n */\nfunction readCostState(line: string, sessionId: string): TranscriptCostState | null {\n if (!line.includes('\"cost-state\"')) return null;\n let entry: { type?: unknown; sessionId?: unknown; totalCostUSD?: unknown; modelUsage?: unknown };\n try {\n entry = JSON.parse(line.replace(/^\\0+/, \"\"));\n } catch {\n return null;\n }\n if (entry.type !== \"cost-state\" || entry.sessionId !== sessionId) return null;\n const total = entry.totalCostUSD;\n if (!isCount(total)) return null;\n const usage = entry.modelUsage;\n if (!usage || typeof usage !== \"object\" || Array.isArray(usage)) return null;\n for (const model of Object.values(usage)) {\n if (!model || typeof model !== \"object\") return null;\n const counters = model as Record<string, unknown>;\n if (!COST_STATE_MODEL_FIELDS.every((field) => isCount(counters[field]))) return null;\n }\n return {\n totalCostUSD: total,\n modelUsage: usage as Record<string, Record<string, number>>,\n };\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const store = opts.store ?? localTranscriptStore;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n costState: null,\n };\n\n let filePath: string | null;\n try {\n filePath = await store.locate(configDir, sessionId, timeoutMs);\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to locate transcript\", {\n configDir,\n sessionId,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n let costState: TranscriptCostState | null = null;\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(store.read(filePath))) {\n repairLine(line, counters);\n costState = readCostState(line, sessionId) ?? costState;\n }\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n result.costState = costState;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const source = filePath;\n try {\n await withFsDeadline(\n `rewrite transcript ${source}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await store.replace(\n source,\n (async function* () {\n let first = true;\n for await (const line of streamLines(store.read(source))) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n );\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written `.scrub-tmp` in the SDK's projects dir, also\n // when the deadline abandoned the replace mid-write.\n await store.discardTemp(source).catch(() => {});\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { fsDeadlineMs, withFsDeadline } from \"@skaile/workspaces/core\";\nimport { resolveAgentExec } from \"./agent-exec.js\";\nimport { localTranscriptStore, type TranscriptStore } from \"./drivers/scrub-transcript.js\";\n\n/**\n * Transcripts reached through the agent launch shim.\n *\n * With the uid split on, the Claude CLI runs as the agent uid and creates its\n * transcripts 0600 in 0700 dirs, so the runner can no longer list, read or\n * rewrite them itself. This store runs plain tools (`find`, `cat`, `sh`, `mv`)\n * as the agent uid through the shim instead. The child gets only `PATH` and\n * `LC_ALL`, never the runner's environment, and runs in `/` because the\n * runner's own cwd may not be enterable by the agent uid.\n */\nexport function agentTranscriptStore(shim: string): TranscriptStore {\n // A replace the scrub's deadline abandoned keeps running; discardTemp stops\n // it before removing its temp file.\n const inFlight = new Map<string, ChildProcess>();\n // Paths whose rewrite discardTemp gave up on: their rename must never run.\n const cancelled = new Set<string>();\n const track = (filePath: string, child: ChildProcess) => {\n inFlight.set(filePath, child);\n child.once(\"close\", () => {\n if (inFlight.get(filePath) === child) inFlight.delete(filePath);\n });\n };\n return {\n async locate(configDir, sessionId, timeoutMs = 10_000) {\n // A session id is a UUID; anything glob- or path-shaped is not ours.\n if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return null;\n const projectsDir = join(configDir, \"projects\");\n // Markers on stdout, not exit codes, carry the answer: a shim or launcher\n // failure has exit codes of its own and must never read as \"not found\".\n const { stdout } = await collect(\n runAsAgent(shim, [\n \"sh\",\n \"-c\",\n '[ -d \"$1\" ] || { echo \"@@no-projects\"; exit 0; }; ' +\n 'find \"$1\" -mindepth 2 -maxdepth 2 -type f -name \"$2\" -print -quit; echo \"@@find:$?\"',\n \"sh\",\n projectsDir,\n `${sessionId}.jsonl`,\n ]),\n timeoutMs,\n );\n const lines = stdout.split(\"\\n\").map((l) => l.trim());\n // A missing projects/ is the same \"not found\" as a failed readdir locally.\n if (lines.includes(\"@@no-projects\")) return null;\n const status = lines.find((l) => l.startsWith(\"@@find:\"));\n if (status === undefined)\n throw new Error(\"locating a transcript as the agent uid failed (no answer from the shim)\");\n // A path find printed counts even if it later hit an unreadable sibling.\n const found = lines.find((l) => l.startsWith(\"/\"));\n if (found) return found;\n if (status !== \"@@find:0\")\n throw new Error(`locating a transcript as the agent uid failed (${status.slice(2)})`);\n return null;\n },\n\n async *read(filePath) {\n const child = runAsAgent(shim, [\"cat\", \"--\", filePath]);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n child.stdout?.setEncoding(\"utf8\");\n for await (const chunk of child.stdout as AsyncIterable<string>) yield chunk;\n const code = await exited;\n if (code !== 0)\n throw new Error(`reading ${filePath} as the agent uid failed: ${await stderr}`);\n },\n\n async replace(filePath, chunks) {\n const child = runAsAgent(shim, [\n \"sh\",\n \"-c\",\n // 0600 like the CLI's own files. Only writes the temp file: the rename\n // is a separate step below, run only after the input was fully sent,\n // so a killed or starved writer can never commit a partial transcript.\n 'umask 077; cat > \"$1.scrub-tmp\"',\n \"sh\",\n filePath,\n ]);\n cancelled.delete(filePath);\n track(filePath, child);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n const stdin = child.stdin;\n if (!stdin) throw new Error(\"agent shim has no stdin\");\n // A child that dies early surfaces through its exit code, not an EPIPE crash.\n stdin.on(\"error\", () => {});\n const gone = exited.then(\n () => undefined,\n () => undefined,\n );\n // Stop pulling input as soon as the child is gone (killed by discardTemp,\n // or failed), instead of waiting on a producer that may never resume.\n const input = chunks[Symbol.asyncIterator]();\n let drained = false;\n try {\n for (;;) {\n const next = await Promise.race([\n input.next(),\n gone.then(() => ({ dead: true as const })),\n ]);\n if (\"dead\" in next || stdin.destroyed) break;\n if (next.done) {\n drained = true;\n break;\n }\n if (!stdin.write(next.value)) {\n await Promise.race([new Promise((resolve) => stdin.once(\"drain\", resolve)), gone]);\n }\n }\n } finally {\n stdin.end();\n // Close the producer too, so the reader feeding it (a `cat` through\n // the shim) is torn down rather than left blocked on a full pipe.\n if (!drained) void input.return?.()?.catch(() => {});\n }\n const code = await exited;\n if (code !== 0 || !drained)\n throw new Error(`rewriting ${filePath} as the agent uid failed: ${await stderr}`);\n if (cancelled.has(filePath)) throw new Error(`rewrite of ${filePath} was abandoned`);\n const mover = runAsAgent(shim, [\"mv\", \"-f\", \"--\", `${filePath}.scrub-tmp`, filePath]);\n track(filePath, mover);\n const moved = await collect(mover, 10_000);\n if (moved.code !== 0) throw new Error(`renaming the rewritten ${filePath} failed`);\n },\n\n async discardTemp(filePath) {\n // Before anything else, so a writer that is just finishing never renames.\n cancelled.add(filePath);\n const pending = inFlight.get(filePath);\n if (pending && pending.exitCode === null && pending.signalCode === null) {\n // The writer cannot commit (the rename is a separate step), so this only\n // stops it; bounded, since a writer stuck on a hung mount may never die.\n const closed = new Promise((resolve) => pending.once(\"close\", resolve));\n pending.kill(\"SIGKILL\");\n await withFsDeadline(`stop the rewrite of ${filePath}`, () => closed, fsDeadlineMs());\n }\n await collect(runAsAgent(shim, [\"rm\", \"-f\", \"--\", `${filePath}.scrub-tmp`]), 10_000);\n },\n };\n}\n\n/**\n * The transcript store for this runner: through the agent shim when\n * `SKAILE_AGENT_EXEC` is set, the runner's own filesystem otherwise.\n */\nexport function transcriptStoreForRuntime(\n env: Record<string, string | undefined> = process.env,\n): TranscriptStore {\n const shim = resolveAgentExec(env);\n return shim ? agentTranscriptStore(shim) : localTranscriptStore;\n}\n\nfunction runAsAgent(shim: string, argv: string[]): ChildProcess {\n return spawn(shim, [\"--\", ...argv], {\n cwd: \"/\",\n env: { PATH: process.env.PATH ?? \"/usr/bin:/bin\", LC_ALL: \"C\" },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\nfunction exitOf(child: ChildProcess): Promise<number> {\n return new Promise((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"close\", (code) => resolve(code ?? 1));\n });\n}\n\n/** Keep the last 1 KiB of stderr for the error message, and keep the pipe drained. */\nfunction drain(child: ChildProcess): Promise<string> {\n return new Promise((resolve) => {\n let tail = \"\";\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (c: string) => {\n tail = (tail + c).slice(-1024);\n });\n child.stderr?.once(\"close\", () => resolve(tail.trim()));\n });\n}\n\nasync function collect(\n child: ChildProcess,\n timeoutMs: number,\n): Promise<{ code: number; stdout: string }> {\n let stdout = \"\";\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (c: string) => {\n stdout += c;\n });\n void drain(child);\n child.stdin?.end();\n let timer: NodeJS.Timeout | undefined;\n try {\n const code = await Promise.race([\n exitOf(child),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(`agent shim did not answer within ${timeoutMs} ms`));\n }, timeoutMs);\n }),\n ]);\n return { code, stdout };\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { globalSkaileDir } from './chunk-L5VSIPQD.js';
2
2
  import { DRIVER_TARGETS } from './chunk-IG5LZ3WU.js';
3
- import { lstatSync } from 'fs';
3
+ import { lstatSync, statSync } from 'fs';
4
4
  import { homedir } from 'os';
5
5
  import { join, resolve } from 'path';
6
6
 
@@ -29,7 +29,7 @@ function isDeployed(kind, name, target, globalInstall, cwd) {
29
29
  const paths = kind === "agent" && target === "omp" ? [`${deployedDir(kind, name, target, globalInstall, cwd)}.md`] : deployedPaths(kind, name, target, globalInstall, cwd);
30
30
  return paths.some((p) => {
31
31
  try {
32
- lstatSync(p);
32
+ if (lstatSync(p).isSymbolicLink()) statSync(p);
33
33
  return true;
34
34
  } catch {
35
35
  return false;
@@ -38,5 +38,5 @@ function isDeployed(kind, name, target, globalInstall, cwd) {
38
38
  }
39
39
 
40
40
  export { deployedBase, deployedDir, deployedPaths, isDeployed };
41
- //# sourceMappingURL=chunk-D54T2F54.js.map
42
- //# sourceMappingURL=chunk-D54T2F54.js.map
41
+ //# sourceMappingURL=chunk-5TBFN46Z.js.map
42
+ //# sourceMappingURL=chunk-5TBFN46Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../core/src/store.ts"],"names":[],"mappings":";;;;;;AA6BO,SAAS,YAAA,CACd,IAAA,EACA,MAAA,EACA,aAAA,EACA,GAAA,EACQ;AACR,EAAA,MAAM,SAAA,GAAY,eAAe,MAAM,CAAA;AACvC,EAAA,IAAI,CAAC,SAAA,EAAW,MAAM,IAAI,KAAA,CAAM,CAAA,wBAAA,EAA2B,MAAM,CAAA,CAAA,CAAG,CAAA;AACpE,EAAA,MAAM,KAAA,GAAQ,gBAAgB,QAAA,GAAW,OAAA;AACzC,EAAA,MAAM,KAAA,GAAQ,UAAU,KAAK,CAAA;AAC7B,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,IAAI,CAAA,IAAK,MAAM,KAAA,IAAS,EAAA;AAC9C,EAAA,IAAI,aAAA,EAAe;AAGjB,IAAA,IAAI,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,UAAA,CAAW,YAAY,CAAA,EAAG;AAC/D,MAAA,OAAO,KAAK,eAAA,EAAgB,EAAG,QAAQ,KAAA,CAAM,WAAA,CAAY,MAAM,CAAC,CAAA;AAAA,IAClE;AACA,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,OAAA,CAAQ,GAAA,IAAO,OAAA,CAAQ,GAAA,IAAO,OAAO,CAAA;AAC9C;AAaO,SAAS,WAAA,CACd,IAAA,EACA,IAAA,EACA,MAAA,EACA,eACA,GAAA,EACQ;AACR,EAAA,OAAO,KAAK,YAAA,CAAa,IAAA,EAAM,QAAQ,aAAA,EAAe,GAAG,GAAG,IAAI,CAAA;AAClE;AAeO,SAAS,aAAA,CACd,IAAA,EACA,IAAA,EACA,MAAA,EACA,eACA,GAAA,EACU;AACV,EAAA,MAAM,MAAM,WAAA,CAAY,IAAA,EAAM,IAAA,EAAM,MAAA,EAAQ,eAAe,GAAG,CAAA;AAC9D,EAAA,OAAO,IAAA,KAAS,OAAA,GAAU,CAAC,GAAA,EAAK,CAAA,EAAG,GAAG,CAAA,GAAA,CAAA,EAAO,CAAA,EAAG,GAAG,CAAA,KAAA,CAAO,CAAA,GAAI,CAAC,GAAG,CAAA;AACpE;AAmBO,SAAS,UAAA,CACd,IAAA,EACA,IAAA,EACA,MAAA,EACA,eACA,GAAA,EACS;AACT,EAAA,MAAM,KAAA,GACJ,SAAS,OAAA,IAAW,MAAA,KAAW,QAC3B,CAAC,CAAA,EAAG,YAAY,IAAA,EAAM,IAAA,EAAM,QAAQ,aAAA,EAAe,GAAG,CAAC,CAAA,GAAA,CAAK,CAAA,GAC5D,cAAc,IAAA,EAAM,IAAA,EAAM,MAAA,EAAQ,aAAA,EAAe,GAAG,CAAA;AAC1D,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM;AACvB,IAAA,IAAI;AAEF,MAAA,IAAI,UAAU,CAAC,CAAA,CAAE,cAAA,EAAe,WAAY,CAAC,CAAA;AAC7C,MAAA,OAAO,IAAA;AAAA,IACT,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-5TBFN46Z.js","sourcesContent":["/**\n * Deploy-target helpers — resolve framework-specific install paths.\n *\n * This module contains only deploy path resolution. All catalog, repository,\n * and history I/O has moved to @skaile/asset-manager (project-local).\n */\n\nimport { lstatSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { globalSkaileDir } from \"./cache-paths.js\";\nimport type { DriverTarget } from \"./driver-targets.js\";\nimport { type AiComponent, DRIVER_TARGETS } from \"./driver-targets.js\";\n\n// ── Deploy-target helpers ─────────────────────────────────────────────────────\n\n/**\n * Resolve the base deploy directory for an asset kind in a given driver target + scope.\n * For local scope, the path is relative to `cwd` (defaults to `process.cwd()`).\n * For global scope, `~` is expanded to the home directory.\n *\n * @param kind - Asset component type (e.g. `\"skill\"`, `\"agent\"`)\n * @param target - Driver target identifier (e.g. `\"claude-code\"`, `\"omp\"`)\n * @param globalInstall - `true` for user-global install, `false` for project-local\n * @param cwd - Working directory for project-local installs (default: `process.cwd()`)\n * @returns Absolute path to the base deploy directory\n * @throws When `target` is not found in `DRIVER_TARGETS`\n * @docLink packages/core/concepts#deployed-base\n */\nexport function deployedBase(\n kind: AiComponent,\n target: DriverTarget,\n globalInstall: boolean,\n cwd?: string,\n): string {\n const targetMap = DRIVER_TARGETS[target];\n if (!targetMap) throw new Error(`Unknown deploy target: '${target}'`);\n const scope = globalInstall ? \"global\" : \"local\";\n const paths = targetMap[scope];\n const destStr = paths[kind] ?? paths.skill ?? \"\";\n if (globalInstall) {\n // `~/.skaile/...` is skaile's own per-user root, so it follows `$SKAILE_HOME`;\n // every other `~/...` is a driver's home dir (`~/.claude`, `~/.omp`, ...).\n if (destStr === \"~/.skaile\" || destStr.startsWith(\"~/.skaile/\")) {\n return join(globalSkaileDir(), destStr.slice(\"~/.skaile\".length));\n }\n return destStr.replace(/^~/, homedir());\n }\n return resolve(cwd ?? process.cwd(), destStr);\n}\n\n/**\n * Return the full deploy path for a named asset: `<deployedBase>/<name>`.\n *\n * @param kind - Asset component type\n * @param name - Asset name (becomes the directory/file name under the base)\n * @param target - Driver target identifier\n * @param globalInstall - `true` for user-global, `false` for project-local\n * @param cwd - Working directory for local installs\n * @returns Absolute path to the asset's deploy directory\n * @docLink packages/core/concepts#deployed-dir\n */\nexport function deployedDir(\n kind: AiComponent,\n name: string,\n target: DriverTarget,\n globalInstall: boolean,\n cwd?: string,\n): string {\n return join(deployedBase(kind, target, globalInstall, cwd), name);\n}\n\n/**\n * Every path a deploy of `name` can occupy. Skills, prompts, flows and contracts\n * deploy to `<base>/<name>`; an agent is rendered into the harness's native file\n * (`<base>/<name>.md` for claude-code, `<base>/<name>.toml` for codex) or a\n * directory (`<base>/<name>/` for omp), so all three count.\n *\n * @param kind - Asset component type\n * @param name - Asset name\n * @param target - Driver target identifier\n * @param globalInstall - `true` for user-global, `false` for project-local\n * @param cwd - Working directory for local installs\n * @returns Absolute paths, the {@link deployedDir} first\n */\nexport function deployedPaths(\n kind: AiComponent,\n name: string,\n target: DriverTarget,\n globalInstall: boolean,\n cwd?: string,\n): string[] {\n const dir = deployedDir(kind, name, target, globalInstall, cwd);\n return kind === \"agent\" ? [dir, `${dir}.md`, `${dir}.toml`] : [dir];\n}\n\n/**\n * Check whether an asset is already deployed at one of its {@link deployedPaths}.\n * Uses `lstatSync` so symlinks are treated as deployed; a dangling symlink (its target is gone)\n * is not a deploy.\n *\n * An omp agent is the exception: the renderer writes a package directory (`<name>/`) and the\n * flat `<name>.md` omp loads, so the directory alone is not a deploy. A deleted flat file reads\n * as not deployed, as a deleted claude-code agent file does.\n *\n * @param kind - Asset component type\n * @param name - Asset name\n * @param target - Driver target identifier\n * @param globalInstall - `true` for user-global, `false` for project-local\n * @param cwd - Working directory for local installs\n * @returns `true` if a deploy path exists, `false` otherwise\n * @docLink packages/core/concepts#is-deployed\n */\nexport function isDeployed(\n kind: AiComponent,\n name: string,\n target: DriverTarget,\n globalInstall: boolean,\n cwd?: string,\n): boolean {\n const paths =\n kind === \"agent\" && target === \"omp\"\n ? [`${deployedDir(kind, name, target, globalInstall, cwd)}.md`]\n : deployedPaths(kind, name, target, globalInstall, cwd);\n return paths.some((p) => {\n try {\n // A symlink counts as deployed, a dangling one does not: nothing is behind it (p1061).\n if (lstatSync(p).isSymbolicLink()) statSync(p);\n return true;\n } catch {\n return false;\n }\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getProviderPreset, providerCredentialEnvName } from './chunk-6Q7NKTDG.js';
1
+ import { getProviderPreset, providerCredentialEnvName } from './chunk-X54YR4AW.js';
2
2
  import { globalSkaileDir } from './chunk-L5VSIPQD.js';
3
3
  import { registryEntries, parseModelRef, isEntryEnabled, resolveEntryBaseUrl } from './chunk-MJHSLODD.js';
4
4
  import { createHash } from 'crypto';
@@ -121,5 +121,5 @@ function writeCodexConfigToml(home, document) {
121
121
  }
122
122
 
123
123
  export { buildCodexConfigDocument, codexProviderTableId, codexSessionHome, writeCodexConfigToml };
124
- //# sourceMappingURL=chunk-6RTEUWXX.js.map
125
- //# sourceMappingURL=chunk-6RTEUWXX.js.map
124
+ //# sourceMappingURL=chunk-6HK6RUFM.js.map
125
+ //# sourceMappingURL=chunk-6HK6RUFM.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/codex/config-toml.ts"],"names":["stringifyToml"],"mappings":";;;;;;;;AAyDA,IAAM,cAAA,GAA6D;AAAA,EACjE,wBAAA,EAA0B,WAAA;AAAA,EAC1B,kBAAA,EAAoB,WAAA;AAAA,EACpB,wBAAA,EAA0B;AAC5B,CAAA;AAQA,IAAM,8CAAmD,IAAI,GAAA,CAAI,CAAC,QAAA,EAAU,QAAA,EAAU,UAAU,CAAC,CAAA;AAM1F,SAAS,qBAAqB,EAAA,EAAoB;AACvD,EAAA,OAAO,4BAA4B,GAAA,CAAI,EAAE,CAAA,GAAI,CAAA,OAAA,EAAU,EAAE,CAAA,CAAA,GAAK,EAAA;AAChE;AAGA,IAAM,yBAAA,GAAkD;AAAA,EACtD,cAAA,EAAgB,IAAA;AAAA,EAChB,MAAA,EAAQ,IAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAA;AAyDA,SAAS,mBAAA,CACP,KAAA,EACA,QAAA,EACA,QAAA,EACS;AACT,EAAA,IAAI,QAAA,CAAS,IAAA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AA,GAAO,IAAA,CAAK,IAAA,EAAM,aAAa,CAAA;AAGrC,EAAA,SAAA,CAAU,MAAM,EAAE,SAAA,EAAW,IAAA,EAAM,IAAA,EAAM,KAAO,CAAA;AAChD,EAAA,IAAI,OAAO,IAAA,CAAK,QAAA,CAAS,eAAe,CAAA,CAAE,WAAW,CAAA,EAAG;AACtD,IAAA,MAAA,CAAO,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAC5B,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,IAAA,EAAM,iBAAiB,CAAA;AAC9C,EAAA,MAAA,CAAO,SAAA,EAAW,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AACjC,EAAA,aAAA,CAAc,SAAA,EAAW,sBAAsB,QAAQ,CAAA,EAAG,EAAE,IAAA,EAAM,GAAA,EAAO,IAAA,EAAM,IAAA,EAAM,CAAA;AACrF,EAAA,UAAA,CAAW,WAAW,IAAI,CAAA;AAC1B,EAAA,OAAO,IAAA;AACT","file":"chunk-6RTEUWXX.js","sourcesContent":["/**\n * Codex's `config.toml` adapter — the AI provider registry materialized into\n * the only provider surface the Codex CLI reads (plan §2.3, codex rows).\n *\n * Codex is a **file-shaped** driver: it takes its endpoints from\n * `$CODEX_HOME/config.toml`, never from per-request options. Both codex modes\n * therefore get a session-private `CODEX_HOME` holding a rendered document:\n *\n * - every addressable registry entry becomes `[model_providers.<id>]` with\n * `base_url`, `env_key`, `wire_api`, `query_params` and `http_headers`\n * mapping 1:1 onto the entry's `base_url`, `credential`, `surface`,\n * `query_params` and `headers`;\n * - `model_provider` and `model` at the top level name the selected entry.\n *\n * The rendered file never contains a credential **value** — `env_key` holds\n * the *name* of the per-entry variable (`SKAILE_AIP_<ID>_KEY`, minted by\n * {@link providerCredentialEnvName}), and the value rides in the child\n * environment. An `oauth` entry has no env carrier at all: it gets\n * `requires_openai_auth`, which routes codex to its own auth manager.\n *\n * **Surface coverage.** Codex names the wire protocol `wire_api` and, as of\n * codex-cli 0.154, accepts exactly one value: `responses`. `chat` was removed\n * (\"`wire_api = \\\"chat\\\"` is no longer supported\", openai/codex#7782), and an\n * unknown value fails the *whole* document at load time — one unaddressable\n * entry would take the rest of the registry down with it. Entries whose\n * surface codex cannot speak (`openai-completions`, `anthropic-messages`,\n * `bedrock-converse-stream`, `google-*`) are therefore left out and reported\n * in {@link CodexConfigBuild.skipped} for the driver to log.\n *\n * @docLink packages/bridge/drivers#codex-driver\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { globalSkaileDir } from \"@skaile/workspaces/core\";\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n parseModelRef,\n registryEntries,\n type ResolvedModelRef,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { stringify as stringifyToml } from \"smol-toml\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { providerCredentialEnvName } from \"../provider-materialize/credential-env.js\";\n\n/**\n * `surface` → codex `wire_api`. Only the responses-flavoured surfaces have a\n * codex spelling; see the module docstring for why `openai-completions` is\n * absent rather than mapped to the removed `chat` value.\n */\nconst CODEX_WIRE_API: Partial<Record<AIProviderSurface, string>> = {\n \"openai-codex-responses\": \"responses\",\n \"openai-responses\": \"responses\",\n \"azure-openai-responses\": \"responses\",\n};\n\n/**\n * Provider ids codex reserves for its own built-ins. A `[model_providers.<id>]`\n * table under one of them fails the whole document (\"model_providers contains\n * reserved built-in provider IDs\"), so such an entry is rendered under\n * {@link codexProviderTableId}.\n */\nconst CODEX_RESERVED_PROVIDER_IDS: ReadonlySet<string> = new Set([\"openai\", \"ollama\", \"lmstudio\"]);\n\n/**\n * The `[model_providers.<id>]` table name for a registry entry: the entry id,\n * or `skaile-<id>` when codex reserves that id (the `openai` preset).\n */\nexport function codexProviderTableId(id: string): string {\n return CODEX_RESERVED_PROVIDER_IDS.has(id) ? `skaile-${id}` : id;\n}\n\n/** Credential kinds whose value the adapter hands over in an env var. */\nconst ENV_DELIVERED_CREDENTIALS: Record<string, true> = {\n api_key_header: true,\n bearer: true,\n command: true,\n};\n\n/** One `[model_providers.<id>]` table, in codex's own vocabulary. */\nexport interface CodexModelProviderTable {\n /** Display name. Codex rejects a provider table without one. */\n name: string;\n base_url?: string;\n /** Name of the variable carrying the credential — never the credential. */\n env_key?: string;\n wire_api?: string;\n /** Routes codex to its own auth manager (ChatGPT subscription / stored key). */\n requires_openai_auth?: boolean;\n query_params?: Record<string, string>;\n http_headers?: Record<string, string>;\n}\n\n/** The subset of codex's `config.toml` this adapter owns. */\nexport interface CodexConfigDocument {\n /** Table id the session addresses (see {@link codexProviderTableId}); absent when nothing rendered. */\n model_provider?: string;\n /** Provider-side model id. */\n model?: string;\n model_providers: Record<string, CodexModelProviderTable>;\n}\n\n/** An entry codex cannot address, and why. */\nexport interface CodexSkippedEntry {\n id: string;\n reason: string;\n}\n\n/** Result of {@link buildCodexConfigDocument}. */\nexport interface CodexConfigBuild {\n document: CodexConfigDocument;\n /** Selected registry entry id (not the table id), when it rendered. */\n providerId?: string;\n /** Provider-side model id of the selection, when the selector named one. */\n model?: string;\n /**\n * Entries left out of the document. Non-fatal: codex keeps its built-in\n * providers, so a session whose selection was skipped behaves exactly as it\n * did before the registry existed.\n */\n skipped: CodexSkippedEntry[];\n /** Notes from `modelRef` resolution (dangling role, disabled provider, …). */\n warnings: string[];\n /**\n * Set when the selector named an entry codex cannot address: the session\n * must stop with `reason`, not fall back to codex's built-in providers.\n */\n unaddressable?: { id: string; reason: string };\n}\n\n/**\n * Whether the session's selector named the entry `selected` resolved to, rather\n * than reaching it by registry order alone.\n */\nfunction selectionNamesEntry(\n input: CodexConfigInput,\n selected: ResolvedModelRef,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n): boolean {\n if (selected.role && selected.modelId !== undefined) return true;\n const selector = input.modelRef?.trim() || input.model?.trim() || \"\";\n if (selector.startsWith(`${selected.providerId}/`)) return true;\n const entry = registryEntries(registry).find(([id]) => id === selected.providerId)?.[1] as\n | AIProviderLlmEntry\n | undefined;\n const modelId = selected.modelId;\n return (\n modelId !== undefined &&\n (entry?.model_map?.[modelId] !== undefined || entry?.capabilities?.[modelId] !== undefined)\n );\n}\n\n/** Inputs {@link buildCodexConfigDocument} reads off an `AgentConfig`. */\nexport interface CodexConfigInput {\n registry?: AIProviderRegistry | MergedAIProviderRegistry;\n /** `\"<providerId>/<modelId>\"`, a bare model id, or `\"@role\"`. */\n modelRef?: string;\n /** Legacy model field, used as the selector when `modelRef` is absent. */\n model?: string;\n /** Roles table (`skaile.yaml`), consulted for an `@role` selector. */\n roles?: Record<string, string>;\n}\n\n/**\n * Render one entry as a codex provider table, or explain why codex cannot\n * address it.\n */\nexport function renderCodexProviderTable(\n id: string,\n entry: AIProviderEntry,\n): { table: CodexModelProviderTable } | { skipped: string } {\n if (!isEntryEnabled(entry)) return { skipped: \"entry is disabled\" };\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\")\n return { skipped: `kind '${entry.kind}' is not a model endpoint` };\n const llm = entry as AIProviderLlmEntry;\n // `surface` and `base_url` may live on the catalog preset the entry names —\n // the catalog layer fills them during a merge, but an entry handed straight\n // to a driver has not necessarily been through one.\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n const surface = llm.surface ?? preset?.surface;\n const wireApi = surface ? CODEX_WIRE_API[surface] : undefined;\n if (!wireApi)\n return {\n skipped: surface\n ? `codex has no wire_api for surface '${surface}'`\n : \"entry declares no surface\",\n };\n const credentialKind = entry.credential?.kind;\n const table: CodexModelProviderTable = { name: entry.label ?? id };\n const baseUrl = resolveEntryBaseUrl(entry) ?? preset?.base_url;\n if (baseUrl) table.base_url = baseUrl;\n if (credentialKind && ENV_DELIVERED_CREDENTIALS[credentialKind])\n table.env_key = providerCredentialEnvName(id);\n table.wire_api = wireApi;\n if (credentialKind === \"oauth\") table.requires_openai_auth = true;\n if (llm.query_params && Object.keys(llm.query_params).length > 0)\n table.query_params = { ...llm.query_params };\n if (entry.headers && Object.keys(entry.headers).length > 0)\n table.http_headers = { ...entry.headers };\n return { table };\n}\n\n/**\n * Build the document for a session: every addressable entry, plus the\n * selection when it resolved to one of them.\n */\nexport function buildCodexConfigDocument(input: CodexConfigInput): CodexConfigBuild {\n const document: CodexConfigDocument = { model_providers: {} };\n const skipped: CodexSkippedEntry[] = [];\n const entries = input.registry ? registryEntries(input.registry) : [];\n for (const [id, entry] of entries) {\n const rendered = renderCodexProviderTable(id, entry);\n if (\"skipped\" in rendered) skipped.push({ id, reason: rendered.skipped });\n else document.model_providers[codexProviderTableId(id)] = rendered.table;\n }\n\n if (!input.registry) return { document, skipped, warnings: [] };\n // An empty selector resolves the same way a bare one does — first entry in\n // registry order. A session that configured an endpoint and named no model\n // still means that endpoint, not codex's built-in default.\n const selected = parseModelRef(\n input.modelRef?.trim() || input.model?.trim() || \"\",\n input.registry,\n input.roles,\n );\n if (!selected) return { document, skipped, warnings: [] };\n const warnings = selected.warnings;\n const tableId = codexProviderTableId(selected.providerId);\n if (!document.model_providers[tableId]) {\n // A selector that names the entry (`ollama/llama3`, a role or a model its\n // `model_map` lists) and cannot be rendered must not fall through to\n // codex's built-in OpenAI: the prompt would go to a provider the user did\n // not pick. A bare model id that matched no entry only landed on the first\n // entry by registry order, so codex's own providers stay the right answer.\n const reason = skipped.find((s) => s.id === selected.providerId)?.reason;\n if (reason && selectionNamesEntry(input, selected, input.registry)) {\n return {\n document,\n skipped,\n warnings,\n unaddressable: { id: selected.providerId, reason },\n };\n }\n return { document, skipped, warnings };\n }\n document.model_provider = tableId;\n if (selected.providerModelId) document.model = selected.providerModelId;\n return {\n document,\n providerId: selected.providerId,\n ...(selected.providerModelId ? { model: selected.providerModelId } : {}),\n skipped,\n warnings,\n };\n}\n\n/** Serialize a document to TOML. Deterministic: registry order throughout. */\nexport function renderCodexConfigToml(document: CodexConfigDocument): string {\n const ordered: Record<string, unknown> = {};\n if (document.model_provider) ordered.model_provider = document.model_provider;\n if (document.model) ordered.model = document.model;\n ordered.model_providers = document.model_providers;\n return `${stringifyToml(ordered)}\\n`;\n}\n\n/**\n * The session-private codex home.\n *\n * Deliberately outside `cwd`: codex's `workspace-write` sandbox makes the\n * working tree writable by the model, and a config home inside it would let a\n * turn rewrite its own `base_url`. `$SKAILE_HOME` (honoured by\n * {@link globalSkaileDir}) relocates the whole tree, which is also the test\n * seam.\n */\nexport function codexSessionHome(config: { cwd: string; sessionId?: string }): string {\n const key =\n config.sessionId && /^[A-Za-z0-9._-]{1,128}$/.test(config.sessionId)\n ? config.sessionId\n : createHash(\"sha256\")\n .update(config.sessionId ?? config.cwd)\n .digest(\"hex\")\n .slice(0, 32);\n return join(globalSkaileDir(), \"codex\", key);\n}\n\n/**\n * Write `<home>/config.toml`, creating the home always. Atomic: a\n * partially written document would fail codex's config load for the whole\n * session.\n *\n * A document with no provider tables says nothing codex does not already\n * know, so nothing is written and a file left by an earlier render is\n * removed — a session that no longer carries a registry must not keep\n * answering to the one it used to have.\n *\n * @returns the absolute path written, or `undefined` when there was nothing\n * to render.\n */\nexport function writeCodexConfigToml(\n home: string,\n document: CodexConfigDocument,\n): string | undefined {\n const path = join(home, \"config.toml\");\n // codex exits when CODEX_HOME names a directory that does not exist, so the\n // home exists before the early return too.\n mkdirSync(home, { recursive: true, mode: 0o700 });\n if (Object.keys(document.model_providers).length === 0) {\n rmSync(path, { force: true });\n return undefined;\n }\n const temporary = join(home, \"config.toml.new\");\n rmSync(temporary, { force: true });\n writeFileSync(temporary, renderCodexConfigToml(document), { mode: 0o600, flag: \"wx\" });\n renameSync(temporary, path);\n return path;\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/codex/config-toml.ts"],"names":["stringifyToml"],"mappings":";;;;;;;;AAyDA,IAAM,cAAA,GAA6D;AAAA,EACjE,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/**\n * Codex's `config.toml` adapter — the AI provider registry materialized into\n * the only provider surface the Codex CLI reads (plan §2.3, codex rows).\n *\n * Codex is a **file-shaped** driver: it takes its endpoints from\n * `$CODEX_HOME/config.toml`, never from per-request options. Both codex modes\n * therefore get a session-private `CODEX_HOME` holding a rendered document:\n *\n * - every addressable registry entry becomes `[model_providers.<id>]` with\n * `base_url`, `env_key`, `wire_api`, `query_params` and `http_headers`\n * mapping 1:1 onto the entry's `base_url`, `credential`, `surface`,\n * `query_params` and `headers`;\n * - `model_provider` and `model` at the top level name the selected entry.\n *\n * The rendered file never contains a credential **value** — `env_key` holds\n * the *name* of the per-entry variable (`SKAILE_AIP_<ID>_KEY`, minted by\n * {@link providerCredentialEnvName}), and the value rides in the child\n * environment. An `oauth` entry has no env carrier at all: it gets\n * `requires_openai_auth`, which routes codex to its own auth manager.\n *\n * **Surface coverage.** Codex names the wire protocol `wire_api` and, as of\n * codex-cli 0.154, accepts exactly one value: `responses`. `chat` was removed\n * (\"`wire_api = \\\"chat\\\"` is no longer supported\", openai/codex#7782), and an\n * unknown value fails the *whole* document at load time — one unaddressable\n * entry would take the rest of the registry down with it. Entries whose\n * surface codex cannot speak (`openai-completions`, `anthropic-messages`,\n * `bedrock-converse-stream`, `google-*`) are therefore left out and reported\n * in {@link CodexConfigBuild.skipped} for the driver to log.\n *\n * @docLink packages/bridge/drivers#codex-driver\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { globalSkaileDir } from \"@skaile/workspaces/core\";\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n parseModelRef,\n registryEntries,\n type ResolvedModelRef,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { stringify as stringifyToml } from \"smol-toml\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { providerCredentialEnvName } from \"../provider-materialize/credential-env.js\";\n\n/**\n * `surface` → codex `wire_api`. Only the responses-flavoured surfaces have a\n * codex spelling; see the module docstring for why `openai-completions` is\n * absent rather than mapped to the removed `chat` value.\n */\nconst CODEX_WIRE_API: Partial<Record<AIProviderSurface, string>> = {\n \"openai-codex-responses\": \"responses\",\n \"openai-responses\": \"responses\",\n \"azure-openai-responses\": \"responses\",\n};\n\n/**\n * Provider ids codex reserves for its own built-ins. A `[model_providers.<id>]`\n * table under one of them fails the whole document (\"model_providers contains\n * reserved built-in provider IDs\"), so such an entry is rendered under\n * {@link codexProviderTableId}.\n */\nconst CODEX_RESERVED_PROVIDER_IDS: ReadonlySet<string> = new Set([\"openai\", \"ollama\", \"lmstudio\"]);\n\n/**\n * The `[model_providers.<id>]` table name for a registry entry: the entry id,\n * or `skaile-<id>` when codex reserves that id (the `openai` preset).\n */\nexport function codexProviderTableId(id: string): string {\n return CODEX_RESERVED_PROVIDER_IDS.has(id) ? `skaile-${id}` : id;\n}\n\n/** Credential kinds whose value the adapter hands over in an env var. */\nconst ENV_DELIVERED_CREDENTIALS: Record<string, true> = {\n api_key_header: true,\n bearer: true,\n command: true,\n};\n\n/** One `[model_providers.<id>]` table, in codex's own vocabulary. */\nexport interface CodexModelProviderTable {\n /** Display name. Codex rejects a provider table without one. */\n name: string;\n base_url?: string;\n /** Name of the variable carrying the credential — never the credential. */\n env_key?: string;\n wire_api?: string;\n /** Routes codex to its own auth manager (ChatGPT subscription / stored key). */\n requires_openai_auth?: boolean;\n query_params?: Record<string, string>;\n http_headers?: Record<string, string>;\n}\n\n/** The subset of codex's `config.toml` this adapter owns. */\nexport interface CodexConfigDocument {\n /** Table id the session addresses (see {@link codexProviderTableId}); absent when nothing rendered. */\n model_provider?: string;\n /** Provider-side model id. */\n model?: string;\n model_providers: Record<string, CodexModelProviderTable>;\n}\n\n/** An entry codex cannot address, and why. */\nexport interface CodexSkippedEntry {\n id: string;\n reason: string;\n}\n\n/** Result of {@link buildCodexConfigDocument}. */\nexport interface CodexConfigBuild {\n document: CodexConfigDocument;\n /** Selected registry entry id (not the table id), when it rendered. */\n providerId?: string;\n /** Provider-side model id of the selection, when the selector named one. */\n model?: string;\n /**\n * Entries left out of the document. Non-fatal: codex keeps its built-in\n * providers, so a session whose selection was skipped behaves exactly as it\n * did before the registry existed.\n */\n skipped: CodexSkippedEntry[];\n /** Notes from `modelRef` resolution (dangling role, disabled provider, …). */\n warnings: string[];\n /**\n * Set when the selector named an entry codex cannot address: the session\n * must stop with `reason`, not fall back to codex's built-in providers.\n */\n unaddressable?: { id: string; reason: string };\n}\n\n/**\n * Whether the session's selector named the entry `selected` resolved to, rather\n * than reaching it by registry order alone.\n */\nfunction selectionNamesEntry(\n input: CodexConfigInput,\n selected: ResolvedModelRef,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n): boolean {\n if (selected.role && selected.modelId !== undefined) return true;\n const selector = input.modelRef?.trim() || input.model?.trim() || \"\";\n if (selector.startsWith(`${selected.providerId}/`)) return true;\n const entry = registryEntries(registry).find(([id]) => id === selected.providerId)?.[1] as\n | AIProviderLlmEntry\n | undefined;\n const modelId = selected.modelId;\n return (\n modelId !== undefined &&\n (entry?.model_map?.[modelId] !== undefined || entry?.capabilities?.[modelId] !== undefined)\n );\n}\n\n/** Inputs {@link buildCodexConfigDocument} reads off an `AgentConfig`. */\nexport interface CodexConfigInput {\n registry?: AIProviderRegistry | MergedAIProviderRegistry;\n /** `\"<providerId>/<modelId>\"`, a bare model id, or `\"@role\"`. */\n modelRef?: string;\n /** Legacy model field, used as the selector when `modelRef` is absent. */\n model?: string;\n /** Roles table (`skaile.yaml`), consulted for an `@role` selector. */\n roles?: Record<string, string>;\n}\n\n/**\n * Render one entry as a codex provider table, or explain why codex cannot\n * address it.\n */\nexport function renderCodexProviderTable(\n id: string,\n entry: AIProviderEntry,\n): { table: CodexModelProviderTable } | { skipped: string } {\n if (!isEntryEnabled(entry)) return { skipped: \"entry is disabled\" };\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\")\n return { skipped: `kind '${entry.kind}' is not a model endpoint` };\n const llm = entry as AIProviderLlmEntry;\n // `surface` and `base_url` may live on the catalog preset the entry names —\n // the catalog layer fills them during a merge, but an entry handed straight\n // to a driver has not necessarily been through one.\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n const surface = llm.surface ?? preset?.surface;\n const wireApi = surface ? CODEX_WIRE_API[surface] : undefined;\n if (!wireApi)\n return {\n skipped: surface\n ? `codex has no wire_api for surface '${surface}'`\n : \"entry declares no surface\",\n };\n const credentialKind = entry.credential?.kind;\n const table: CodexModelProviderTable = { name: entry.label ?? id };\n const baseUrl = resolveEntryBaseUrl(entry) ?? preset?.base_url;\n if (baseUrl) table.base_url = baseUrl;\n if (credentialKind && ENV_DELIVERED_CREDENTIALS[credentialKind])\n table.env_key = providerCredentialEnvName(id);\n table.wire_api = wireApi;\n if (credentialKind === \"oauth\") table.requires_openai_auth = true;\n if (llm.query_params && Object.keys(llm.query_params).length > 0)\n table.query_params = { ...llm.query_params };\n if (entry.headers && Object.keys(entry.headers).length > 0)\n table.http_headers = { ...entry.headers };\n return { table };\n}\n\n/**\n * Build the document for a session: every addressable entry, plus the\n * selection when it resolved to one of them.\n */\nexport function buildCodexConfigDocument(input: CodexConfigInput): CodexConfigBuild {\n const document: CodexConfigDocument = { model_providers: {} };\n const skipped: CodexSkippedEntry[] = [];\n const entries = input.registry ? registryEntries(input.registry) : [];\n for (const [id, entry] of entries) {\n const rendered = renderCodexProviderTable(id, entry);\n if (\"skipped\" in rendered) skipped.push({ id, reason: rendered.skipped });\n else document.model_providers[codexProviderTableId(id)] = rendered.table;\n }\n\n if (!input.registry) return { document, skipped, warnings: [] };\n // An empty selector resolves the same way a bare one does — first entry in\n // registry order. A session that configured an endpoint and named no model\n // still means that endpoint, not codex's built-in default.\n const selected = parseModelRef(\n input.modelRef?.trim() || input.model?.trim() || \"\",\n input.registry,\n input.roles,\n );\n if (!selected) return { document, skipped, warnings: [] };\n const warnings = selected.warnings;\n const tableId = codexProviderTableId(selected.providerId);\n if (!document.model_providers[tableId]) {\n // A selector that names the entry (`ollama/llama3`, a role or a model its\n // `model_map` lists) and cannot be rendered must not fall through to\n // codex's built-in OpenAI: the prompt would go to a provider the user did\n // not pick. A bare model id that matched no entry only landed on the first\n // entry by registry order, so codex's own providers stay the right answer.\n const reason = skipped.find((s) => s.id === selected.providerId)?.reason;\n if (reason && selectionNamesEntry(input, selected, input.registry)) {\n return {\n document,\n skipped,\n warnings,\n unaddressable: { id: selected.providerId, reason },\n };\n }\n return { document, skipped, warnings };\n }\n document.model_provider = tableId;\n if (selected.providerModelId) document.model = selected.providerModelId;\n return {\n document,\n providerId: selected.providerId,\n ...(selected.providerModelId ? { model: selected.providerModelId } : {}),\n skipped,\n warnings,\n };\n}\n\n/** Serialize a document to TOML. Deterministic: registry order throughout. */\nexport function renderCodexConfigToml(document: CodexConfigDocument): string {\n const ordered: Record<string, unknown> = {};\n if (document.model_provider) ordered.model_provider = document.model_provider;\n if (document.model) ordered.model = document.model;\n ordered.model_providers = document.model_providers;\n return `${stringifyToml(ordered)}\\n`;\n}\n\n/**\n * The session-private codex home.\n *\n * Deliberately outside `cwd`: codex's `workspace-write` sandbox makes the\n * working tree writable by the model, and a config home inside it would let a\n * turn rewrite its own `base_url`. `$SKAILE_HOME` (honoured by\n * {@link globalSkaileDir}) relocates the whole tree, which is also the test\n * seam.\n */\nexport function codexSessionHome(config: { cwd: string; sessionId?: string }): string {\n const key =\n config.sessionId && /^[A-Za-z0-9._-]{1,128}$/.test(config.sessionId)\n ? config.sessionId\n : createHash(\"sha256\")\n .update(config.sessionId ?? config.cwd)\n .digest(\"hex\")\n .slice(0, 32);\n return join(globalSkaileDir(), \"codex\", key);\n}\n\n/**\n * Write `<home>/config.toml`, creating the home always. Atomic: a\n * partially written document would fail codex's config load for the whole\n * session.\n *\n * A document with no provider tables says nothing codex does not already\n * know, so nothing is written and a file left by an earlier render is\n * removed — a session that no longer carries a registry must not keep\n * answering to the one it used to have.\n *\n * @returns the absolute path written, or `undefined` when there was nothing\n * to render.\n */\nexport function writeCodexConfigToml(\n home: string,\n document: CodexConfigDocument,\n): string | undefined {\n const path = join(home, \"config.toml\");\n // codex exits when CODEX_HOME names a directory that does not exist, so the\n // home exists before the early return too.\n mkdirSync(home, { recursive: true, mode: 0o700 });\n if (Object.keys(document.model_providers).length === 0) {\n rmSync(path, { force: true });\n return undefined;\n }\n const temporary = join(home, \"config.toml.new\");\n rmSync(temporary, { force: true });\n writeFileSync(temporary, renderCodexConfigToml(document), { mode: 0o600, flag: \"wx\" });\n renameSync(temporary, path);\n return path;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { findAiAssetsRoot } from './chunk-AP24HESN.js';
1
+ import { findAiAssetsRoot } from './chunk-H6UVIKQ2.js';
2
2
 
3
3
  // workspace-plugin/src/utils/ai-assets.ts
4
4
  function findAiAssetsRoot2(startDir) {
@@ -6,5 +6,5 @@ function findAiAssetsRoot2(startDir) {
6
6
  }
7
7
 
8
8
  export { findAiAssetsRoot2 as findAiAssetsRoot };
9
- //# sourceMappingURL=chunk-PGZDSDOB.js.map
10
- //# sourceMappingURL=chunk-PGZDSDOB.js.map
9
+ //# sourceMappingURL=chunk-6Z5KTFJT.js.map
10
+ //# sourceMappingURL=chunk-6Z5KTFJT.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../workspace-plugin/src/utils/ai-assets.ts"],"names":["findAiAssetsRoot"],"mappings":";;;AA+BO,SAASA,kBAAiB,QAAA,EAA0C;AACzE,EAAA,OAAO,iBAAuB,QAAQ,CAAA;AACxC","file":"chunk-PGZDSDOB.js","sourcesContent":["// utils/ai-assets.ts\n// Shared utility for locating the ai-assets root directory.\n//\n// This is NOT a startup path (an earlier comment here claimed it was). Every\n// caller is an agent-invokable tool in `tools/flows.ts` / `tools/skills.ts`, so\n// the walk runs on a request path inside the long-lived `skaile serve` process,\n// once per tool invocation. With `projectDir = /skaile` the upward walk passes\n// directly beside the rclone FUSE workspace mount, so a synchronous `statSync`\n// here parks the whole event loop when that mount wedges — the failure mode\n// behind the 2026-08-07 outages. See issue #454.\nimport { findAiAssetsRoot as findAiAssetsRootShared } from \"@skaile/workspaces/asset-manager/catalog-deployer\";\n\n/**\n * Walk up from `startDir` looking for an `ai-assets/` directory.\n *\n * Delegates to the shared implementation in `asset-manager/catalog-deployer`,\n * which is async, deadline-bounded, level-capped, and refuses a candidate that\n * resolves at or under a workspace mount (continuing upward so a legitimate\n * parent still wins).\n *\n * @param startDir - Absolute path to begin the upward search from (typically\n * the skaile `projectDir`).\n * Note the upward walk is now level-capped rather than running to the\n * filesystem root. Six levels covers every real layout and stops an\n * unbounded climb across mount boundaries.\n *\n * @returns Absolute path to the first usable `ai-assets/` directory found, or\n * `null` if no match exists within the cap.\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function findAiAssetsRoot(startDir: string): Promise<string | null> {\n return findAiAssetsRootShared(startDir);\n}\n"]}
1
+ {"version":3,"sources":["../workspace-plugin/src/utils/ai-assets.ts"],"names":["findAiAssetsRoot"],"mappings":";;;AA+BO,SAASA,kBAAiB,QAAA,EAA0C;AACzE,EAAA,OAAO,iBAAuB,QAAQ,CAAA;AACxC","file":"chunk-6Z5KTFJT.js","sourcesContent":["// utils/ai-assets.ts\n// Shared utility for locating the ai-assets root directory.\n//\n// This is NOT a startup path (an earlier comment here claimed it was). Every\n// caller is an agent-invokable tool in `tools/flows.ts` / `tools/skills.ts`, so\n// the walk runs on a request path inside the long-lived `skaile serve` process,\n// once per tool invocation. With `projectDir = /skaile` the upward walk passes\n// directly beside the rclone FUSE workspace mount, so a synchronous `statSync`\n// here parks the whole event loop when that mount wedges — the failure mode\n// behind the 2026-08-07 outages. See issue #454.\nimport { findAiAssetsRoot as findAiAssetsRootShared } from \"@skaile/workspaces/asset-manager/catalog-deployer\";\n\n/**\n * Walk up from `startDir` looking for an `ai-assets/` directory.\n *\n * Delegates to the shared implementation in `asset-manager/catalog-deployer`,\n * which is async, deadline-bounded, level-capped, and refuses a candidate that\n * resolves at or under a workspace mount (continuing upward so a legitimate\n * parent still wins).\n *\n * @param startDir - Absolute path to begin the upward search from (typically\n * the skaile `projectDir`).\n * Note the upward walk is now level-capped rather than running to the\n * filesystem root. Six levels covers every real layout and stops an\n * unbounded climb across mount boundaries.\n *\n * @returns Absolute path to the first usable `ai-assets/` directory found, or\n * `null` if no match exists within the cap.\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function findAiAssetsRoot(startDir: string): Promise<string | null> {\n return findAiAssetsRootShared(startDir);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { declaresActivityLabel, stripActivityLabel } from './chunk-D5WTOVLG.js';
1
+ import { declaresActivityLabel, stripActivityLabel } from './chunk-Y56YIT6J.js';
2
2
  import { randomUUID } from 'crypto';
3
3
 
4
4
  async function dispatchCapability(hooks, name, input, onBackgroundError = () => {
@@ -52,5 +52,5 @@ function filterRenderCapabilities(caps) {
52
52
  }
53
53
 
54
54
  export { dispatchCapability, filterRenderCapabilities, renderFallback };
55
- //# sourceMappingURL=chunk-PW3TYWOI.js.map
56
- //# sourceMappingURL=chunk-PW3TYWOI.js.map
55
+ //# sourceMappingURL=chunk-AJ7EGIFR.js.map
56
+ //# sourceMappingURL=chunk-AJ7EGIFR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/capability-dispatch.ts"],"names":[],"mappings":";;;AAgFA,eAAsB,kBAAA,CACpB,KAAA,EACA,IAAA,EACA,KAAA,EACA,oBAA4D,MAAM;AAAC,CAAA,EACnE,MAAA,EACmC;AACnC,EAAA,MAAA,EAAQ,cAAA,EAAe;AACvB,EAAA,MAAM,SAAS,UAAA,EAAW;AAC1B,EAAA,MAAM,GAAA,GAAM,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA;AAI9B,EAAA,IAAI,CAAC,qBAAA,CAAsB,GAAA,EAAK,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AAS,OAAA,CAAQ,0BAAA,EAA4B,CAAC,QAAQ,IAAA,KAAiB;AAC5E,IAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,KAAA,EAAO,IAAI,CAAA;AAClC,IAAA,OAAO,UAAU,MAAA,IAAa,KAAA,KAAU,IAAA,GAAO,EAAA,GAAK,OAAO,KAAK,CAAA;AAAA,EAClE,CAAC,CAAA;AACH;AAEA,SAAS,QAAA,CAAS,KAA8B,IAAA,EAAuB;AACrE,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC5B,EAAA,IAAI,OAAA,GAAmB,GAAA;AACvB,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,YAAY,IAAA,IAAQ,OAAA,KAAY,MAAA,IAAa,OAAO,YAAY,QAAA,EAAU;AAC5E,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,OAAA,GAAW,QAAoC,IAAI,CAAA;AAAA,EACrD;AACA,EAAA,OAAO,OAAA;AACT;AAYO,SAAS,yBAAyB,IAAA,EAAkC;AACzE,EAAA,OAAO,KAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,MAAS,CAAA;AAClD","file":"chunk-PW3TYWOI.js","sourcesContent":["/**\n * Capability dispatch helpers for bridge drivers.\n *\n * The runner builds a {@link BridgeCapabilityHooks} bundle from its\n * `CapabilityRegistry` and threads it through `AgentConfig.capabilities`.\n * Drivers consume the bundle via these helpers without taking a runtime\n * dependency on `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * Three behaviours are layered into a single dispatch path:\n *\n * 1. **Standard tool call** — the LLM invokes a capability; the bridge calls\n * `hooks.invoke()`, awaits the result, and returns it to the LLM.\n * 2. **Fire-and-forget** — when the resolved Capability has `fireAndForget`\n * set, the bridge resolves to `{}` immediately and runs the handler in\n * the background. Background errors are logged but never surfaced to the\n * LLM since the call is already settled.\n * 3. **Render capability** — when the resolved Capability has a non-undefined\n * `render`, the bridge emits `RenderInvokedEvent` to the runner via\n * `hooks.emitRender` and (when `render.fallback` is set) a parallel text\n * event via `hooks.emitText` with simple `{{prop}}` substitution. The\n * placeholder convention follows the v2 spec — top-level keys of `props`\n * only, with optional dotted-path traversal (`{{user.name}}`). The legacy\n * AAP `{{props.x}}` form was retired in Phase 6.\n *\n * @category Capabilities\n * @since 2.0.0\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n type Capability,\n declaresActivityLabel,\n stripActivityLabel,\n} from \"@skaile/workspaces/types\";\nimport type { BridgeCapabilityHooks } from \"./types.js\";\n\n/**\n * Result of a capability dispatch returned by {@link dispatchCapability}.\n *\n * The bridge feeds `{ result }` back to the LLM tool-use response. For\n * fire-and-forget capabilities `result` is always `{}` and `background` is `true`.\n *\n * @docLink packages/bridge/concepts#capability-dispatch-result\n */\nexport interface CapabilityDispatchResult {\n /** Value returned to the LLM. `{}` for fire-and-forget capabilities. */\n result: unknown;\n /** True when the handler is still running in the background (fire-and-forget). */\n background: boolean;\n /** The per-dispatch call id minted for this invocation (see {@link dispatchCapability}). */\n callId: string;\n}\n\n/**\n * Run a capability invocation through the runner-provided hooks, applying\n * render-event emission and fire-and-forget short-circuit.\n *\n * The result is always shaped for direct return to the LLM. For\n * fire-and-forget capabilities the background promise is fired and any error\n * is logged through `onBackgroundError` (defaulting to a no-op). For all\n * other capabilities the handler is awaited; errors propagate as a rejection\n * so the driver can surface them as tool errors.\n *\n * **Dispatch call id.** Every dispatch mints a fresh `randomUUID()` and uses it\n * for `render_invoked.callId`, `hooks.invoke`'s `callId` and — for client\n * capabilities — the outbound `capability_invoked.callId`. It is deliberately\n * NOT the driver's tool-call id: those are only as unique as the model\n * provider makes them (some harnesses emit `call_0` on every turn), and the\n * runner's pending-call map is keyed by this id, so a late `capability_result`\n * for a timed-out call must never be able to resolve a later call that reused\n * the provider's id. Drivers map results back to their tool calls through the\n * returned value, never through this id.\n *\n * @param hooks - Capability dispatch bundle from `AgentConfig.capabilities`.\n * @param name - Registered capability name.\n * @param input - Raw tool input from the LLM.\n * @param onBackgroundError - Optional error handler for fire-and-forget failures; receives the dispatch call id.\n * @param signal - Optional abort signal forwarded to the handler.\n * @returns Resolved dispatch result with the LLM-facing value, background flag and dispatch call id.\n * @docLink packages/bridge/concepts#dispatch-capability\n */\nexport async function dispatchCapability(\n hooks: BridgeCapabilityHooks,\n name: string,\n input: unknown,\n onBackgroundError: (err: unknown, callId: string) => void = () => {},\n signal?: AbortSignal,\n): Promise<CapabilityDispatchResult> {\n signal?.throwIfAborted();\n const callId = randomUUID();\n const cap = hooks.resolve(name);\n // The advertised `activity_label` is for the UI only. Strip it before render\n // props and the handler: strict inputs would reject it and external MCP\n // passthrough would forward it. Kept when the capability declares it itself.\n if (!declaresActivityLabel(cap?.inputSchema)) input = stripActivityLabel(input);\n\n // Render emission happens before invocation so clients see the props the\n // LLM passed in even if the handler errors. The runner's gateway forwards\n // the event over the transport.\n if (cap?.render && hooks.emitRender) {\n hooks.emitRender({\n type: \"render_invoked\",\n capabilityName: name,\n props: input,\n callId,\n });\n if (cap.render.fallback && hooks.emitText) {\n const fallback = renderFallback(cap.render.fallback, input);\n hooks.emitText(fallback);\n }\n }\n\n if (cap?.fireAndForget) {\n // Resolve immediately; run handler in background.\n void hooks.invoke(name, input, signal, callId).catch((err) => onBackgroundError(err, callId));\n return { result: {}, background: true, callId };\n }\n\n const result = await hooks.invoke(name, input, signal, callId);\n return { result, background: false, callId };\n}\n\n/**\n * Substitute `{{prop}}` placeholders inside a fallback template using the\n * input record. Top-level keys of `props` resolve directly\n * (`{{name}}` → `props.name`); dotted paths traverse nested records\n * (`{{user.name}}` → `props.user.name`). Missing keys collapse to an empty\n * string; non-record inputs collapse all placeholders.\n *\n * The convention is fixed by the v2 spec (§1, `RenderSpec.fallback`). The\n * legacy AAP form `{{props.x}}` is no longer accepted — author fallbacks\n * with bare keys.\n *\n * Intentionally minimal — full template engines belong in the platform's\n * render layer, not the bridge.\n *\n * @param template - Fallback string from `RenderSpec.fallback` with `{{key}}` placeholders.\n * @param input - LLM tool input object; non-object values collapse all placeholders.\n * @returns Template with all resolvable placeholders replaced.\n * @docLink packages/bridge/concepts#render-fallback\n */\nexport function renderFallback(template: string, input: unknown): string {\n if (!input || typeof input !== \"object\") {\n return template.replace(/\\{\\{\\s*[\\w$.]+\\s*\\}\\}/g, \"\");\n }\n const props = input as Record<string, unknown>;\n return template.replace(/\\{\\{\\s*([\\w$.]+)\\s*\\}\\}/g, (_match, path: string) => {\n const value = readPath(props, path);\n return value === undefined || value === null ? \"\" : String(value);\n });\n}\n\nfunction readPath(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== \"object\") {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Filter a capability list to those marked as render-capable (having a `render` spec).\n *\n * Used by drivers that emit a separate render manifest at registration time.\n * Currently unused in production drivers; reserved for future phases.\n *\n * @param caps - Full capability list to filter.\n * @returns Subset of capabilities with a non-undefined `render` property.\n * @docLink packages/bridge/concepts#filter-render-capabilities\n */\nexport function filterRenderCapabilities(caps: Capability[]): Capability[] {\n return caps.filter((c) => c.render !== undefined);\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/capability-dispatch.ts"],"names":[],"mappings":";;;AAgFA,eAAsB,kBAAA,CACpB,KAAA,EACA,IAAA,EACA,KAAA,EACA,oBAA4D,MAAM;AAAC,CAAA,EACnE,MAAA,EACmC;AACnC,EAAA,MAAA,EAAQ,cAAA,EAAe;AACvB,EAAA,MAAM,SAAS,UAAA,EAAW;AAC1B,EAAA,MAAM,GAAA,GAAM,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA;AAI9B,EAAA,IAAI,CAAC,qBAAA,CAAsB,GAAA,EAAK,WAAW,CAAA,EAAG,KAAA,GAAQ,mBAAmB,KAAK,CAAA;AAK9E,EAAA,IAAI,GAAA,EAAK,M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GAAQ,QAAA,CAAS,KAAA,EAAO,IAAI,CAAA;AAClC,IAAA,OAAO,UAAU,MAAA,IAAa,KAAA,KAAU,IAAA,GAAO,EAAA,GAAK,OAAO,KAAK,CAAA;AAAA,EAClE,CAAC,CAAA;AACH;AAEA,SAAS,QAAA,CAAS,KAA8B,IAAA,EAAuB;AACrE,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC5B,EAAA,IAAI,OAAA,GAAmB,GAAA;AACvB,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,YAAY,IAAA,IAAQ,OAAA,KAAY,MAAA,IAAa,OAAO,YAAY,QAAA,EAAU;AAC5E,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,OAAA,GAAW,QAAoC,IAAI,CAAA;AAAA,EACrD;AACA,EAAA,OAAO,OAAA;AACT;AAYO,SAAS,yBAAyB,IAAA,EAAkC;AACzE,EAAA,OAAO,KAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,MAAS,CAAA;AAClD","file":"chunk-AJ7EGIFR.js","sourcesContent":["/**\n * Capability dispatch helpers for bridge drivers.\n *\n * The runner builds a {@link BridgeCapabilityHooks} bundle from its\n * `CapabilityRegistry` and threads it through `AgentConfig.capabilities`.\n * Drivers consume the bundle via these helpers without taking a runtime\n * dependency on `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * Three behaviours are layered into a single dispatch path:\n *\n * 1. **Standard tool call** — the LLM invokes a capability; the bridge calls\n * `hooks.invoke()`, awaits the result, and returns it to the LLM.\n * 2. **Fire-and-forget** — when the resolved Capability has `fireAndForget`\n * set, the bridge resolves to `{}` immediately and runs the handler in\n * the background. Background errors are logged but never surfaced to the\n * LLM since the call is already settled.\n * 3. **Render capability** — when the resolved Capability has a non-undefined\n * `render`, the bridge emits `RenderInvokedEvent` to the runner via\n * `hooks.emitRender` and (when `render.fallback` is set) a parallel text\n * event via `hooks.emitText` with simple `{{prop}}` substitution. The\n * placeholder convention follows the v2 spec — top-level keys of `props`\n * only, with optional dotted-path traversal (`{{user.name}}`). The legacy\n * AAP `{{props.x}}` form was retired in Phase 6.\n *\n * @category Capabilities\n * @since 2.0.0\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n type Capability,\n declaresActivityLabel,\n stripActivityLabel,\n} from \"@skaile/workspaces/types\";\nimport type { BridgeCapabilityHooks } from \"./types.js\";\n\n/**\n * Result of a capability dispatch returned by {@link dispatchCapability}.\n *\n * The bridge feeds `{ result }` back to the LLM tool-use response. For\n * fire-and-forget capabilities `result` is always `{}` and `background` is `true`.\n *\n * @docLink packages/bridge/concepts#capability-dispatch-result\n */\nexport interface CapabilityDispatchResult {\n /** Value returned to the LLM. `{}` for fire-and-forget capabilities. */\n result: unknown;\n /** True when the handler is still running in the background (fire-and-forget). */\n background: boolean;\n /** The per-dispatch call id minted for this invocation (see {@link dispatchCapability}). */\n callId: string;\n}\n\n/**\n * Run a capability invocation through the runner-provided hooks, applying\n * render-event emission and fire-and-forget short-circuit.\n *\n * The result is always shaped for direct return to the LLM. For\n * fire-and-forget capabilities the background promise is fired and any error\n * is logged through `onBackgroundError` (defaulting to a no-op). For all\n * other capabilities the handler is awaited; errors propagate as a rejection\n * so the driver can surface them as tool errors.\n *\n * **Dispatch call id.** Every dispatch mints a fresh `randomUUID()` and uses it\n * for `render_invoked.callId`, `hooks.invoke`'s `callId` and — for client\n * capabilities — the outbound `capability_invoked.callId`. It is deliberately\n * NOT the driver's tool-call id: those are only as unique as the model\n * provider makes them (some harnesses emit `call_0` on every turn), and the\n * runner's pending-call map is keyed by this id, so a late `capability_result`\n * for a timed-out call must never be able to resolve a later call that reused\n * the provider's id. Drivers map results back to their tool calls through the\n * returned value, never through this id.\n *\n * @param hooks - Capability dispatch bundle from `AgentConfig.capabilities`.\n * @param name - Registered capability name.\n * @param input - Raw tool input from the LLM.\n * @param onBackgroundError - Optional error handler for fire-and-forget failures; receives the dispatch call id.\n * @param signal - Optional abort signal forwarded to the handler.\n * @returns Resolved dispatch result with the LLM-facing value, background flag and dispatch call id.\n * @docLink packages/bridge/concepts#dispatch-capability\n */\nexport async function dispatchCapability(\n hooks: BridgeCapabilityHooks,\n name: string,\n input: unknown,\n onBackgroundError: (err: unknown, callId: string) => void = () => {},\n signal?: AbortSignal,\n): Promise<CapabilityDispatchResult> {\n signal?.throwIfAborted();\n const callId = randomUUID();\n const cap = hooks.resolve(name);\n // The advertised `activity_label` is for the UI only. Strip it before render\n // props and the handler: strict inputs would reject it and external MCP\n // passthrough would forward it. Kept when the capability declares it itself.\n if (!declaresActivityLabel(cap?.inputSchema)) input = stripActivityLabel(input);\n\n // Render emission happens before invocation so clients see the props the\n // LLM passed in even if the handler errors. The runner's gateway forwards\n // the event over the transport.\n if (cap?.render && hooks.emitRender) {\n hooks.emitRender({\n type: \"render_invoked\",\n capabilityName: name,\n props: input,\n callId,\n });\n if (cap.render.fallback && hooks.emitText) {\n const fallback = renderFallback(cap.render.fallback, input);\n hooks.emitText(fallback);\n }\n }\n\n if (cap?.fireAndForget) {\n // Resolve immediately; run handler in background.\n void hooks.invoke(name, input, signal, callId).catch((err) => onBackgroundError(err, callId));\n return { result: {}, background: true, callId };\n }\n\n const result = await hooks.invoke(name, input, signal, callId);\n return { result, background: false, callId };\n}\n\n/**\n * Substitute `{{prop}}` placeholders inside a fallback template using the\n * input record. Top-level keys of `props` resolve directly\n * (`{{name}}` → `props.name`); dotted paths traverse nested records\n * (`{{user.name}}` → `props.user.name`). Missing keys collapse to an empty\n * string; non-record inputs collapse all placeholders.\n *\n * The convention is fixed by the v2 spec (§1, `RenderSpec.fallback`). The\n * legacy AAP form `{{props.x}}` is no longer accepted — author fallbacks\n * with bare keys.\n *\n * Intentionally minimal — full template engines belong in the platform's\n * render layer, not the bridge.\n *\n * @param template - Fallback string from `RenderSpec.fallback` with `{{key}}` placeholders.\n * @param input - LLM tool input object; non-object values collapse all placeholders.\n * @returns Template with all resolvable placeholders replaced.\n * @docLink packages/bridge/concepts#render-fallback\n */\nexport function renderFallback(template: string, input: unknown): string {\n if (!input || typeof input !== \"object\") {\n return template.replace(/\\{\\{\\s*[\\w$.]+\\s*\\}\\}/g, \"\");\n }\n const props = input as Record<string, unknown>;\n return template.replace(/\\{\\{\\s*([\\w$.]+)\\s*\\}\\}/g, (_match, path: string) => {\n const value = readPath(props, path);\n return value === undefined || value === null ? \"\" : String(value);\n });\n}\n\nfunction readPath(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== \"object\") {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Filter a capability list to those marked as render-capable (having a `render` spec).\n *\n * Used by drivers that emit a separate render manifest at registration time.\n * Currently unused in production drivers; reserved for future phases.\n *\n * @param caps - Full capability list to filter.\n * @returns Subset of capabilities with a non-undefined `render` property.\n * @docLink packages/bridge/concepts#filter-render-capabilities\n */\nexport function filterRenderCapabilities(caps: Capability[]): Capability[] {\n return caps.filter((c) => c.render !== undefined);\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { findAiAssetsRoot } from './chunk-PGZDSDOB.js';
1
+ import { findAiAssetsRoot } from './chunk-6Z5KTFJT.js';
2
2
  import { okJson, err, ok } from './chunk-X5YPJV4N.js';
3
- import { parseSkillRequirements, validateRequirements, buildRequiresPreamble, parseSkillFrontmatter } from './chunk-D5REDKVU.js';
3
+ import { parseSkillRequirements, validateRequirements, buildRequiresPreamble, parseSkillFrontmatter } from './chunk-FKU57Q5Q.js';
4
4
  import { findKindDirs } from './chunk-A2ULN3KX.js';
5
5
  import fs from 'fs/promises';
6
6
  import path from 'path';
@@ -136,5 +136,5 @@ async function skillGetPreamble(projectDir, skillId) {
136
136
  }
137
137
 
138
138
  export { skillCheckRequirements, skillGetPreamble, skillList, skillSearch, skillShow };
139
- //# sourceMappingURL=chunk-46IRZJV4.js.map
140
- //# sourceMappingURL=chunk-46IRZJV4.js.map
139
+ //# sourceMappingURL=chunk-CD7SVH6W.js.map
140
+ //# sourceMappingURL=chunk-CD7SVH6W.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../workspace-plugin/src/tools/skills.ts"],"names":[],"mappings":";;;;;;;AA0BA,eAAe,cAAA,CAAe,KAAa,GAAA,EAAkC;AAC3E,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,EAAA,CAAG,OAAA,CAAQ,KAAK,EAAE,aAAA,EAAe,MAAM,CAAA;AAAA,EACzD,CAAA,CAAA,MAAQ;AACN,IAAA;AAAA,EACF;AAGA,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,EAAE,MAAA,EAAO,IAAK,CAAA,CAAE,IAAA,KAAS,UAAU,CAAA;AAC1E,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,UAAU,CAAA;AAC7C,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,GAAU,MAAM,EAAA,CAAG,QAAA,CAAS,aAAa,OAAO,CAAA;AACtD,MAAA,MAAM,EAAA,GAAK,sBAAsB,OAAO,CAAA;AACxC,MAAA,MAAM,IAAA,GAAO,OAAO,EAAA,CAAG,IAAA,KAAS,WAAW,EAAA,CAAG,IAAA,GAAO,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA;AACtE,MAAA,MAAM,cAAc,OAAO,EAAA,CAAG,WAAA,KAAgB,QAAA,GAAW,GAAG,WAAA,GAAc,EAAA;AAC1E,MAAA,MAAM,SAAS,OAAO,EAAA,CAAG,MAAA,KAAW,QAAA,GAAW,GAAG,MAAA,GAAS,KAAA,CAAA;AAC3D,MAAA,MAAM,UAAU,OAAO,EAAA,CAAG,OAAA,KAAY,QAAA,GAAW,GAAG,OAAA,GAAU,KAAA,CAAA;AAC9D,MAA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pD,IAAA,MAAM,UAAU,MAAM,EAAA,CAAG,QAAA,CAAS,KAAA,CAAM,MAAM,OAAO,CAAA;AAErD,IAAA,MAAM,YAAA,GAAe,uBAAuB,OAAO,CAAA;AACnD,IAAA,MAAM,QAAA,GAAW,qBAAA,CAAsB,YAAA,EAAc,OAAO,CAAA;AAC5D,IAAA,OAAO,EAAA,CAAG,YAAY,4BAA4B,CAAA;AAAA,EACpD,SAAS,CAAA,EAAY;AACnB,IAAA,OAAO,IAAI,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF","file":"chunk-46IRZJV4.js","sourcesContent":["// src/tools/skills.ts\n\nimport type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { findKindDirs } from \"@skaile/workspaces/core/discovery\";\nimport {\n buildRequiresPreamble,\n parseSkillFrontmatter,\n parseSkillRequirements,\n validateRequirements,\n} from \"@skaile/workspaces/resolver\";\nimport type { ToolResult } from \"../types.js\";\nimport { err, ok, okJson } from \"../types.js\";\nimport { findAiAssetsRoot } from \"../utils/ai-assets.js\";\n\ninterface SkillEntry {\n id: string;\n name: string;\n description: string;\n source?: string;\n version?: string;\n keywords?: string[];\n path: string;\n}\n\nasync function walkForSkillMd(dir: string, acc: SkillEntry[]): Promise<void> {\n let entries: Dirent<string>[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n // Check if this directory contains a SKILL.md\n const hasSkillMd = entries.some((e) => e.isFile() && e.name === \"SKILL.md\");\n if (hasSkillMd) {\n const skillMdPath = path.join(dir, \"SKILL.md\");\n try {\n const content = await fs.readFile(skillMdPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n const name = typeof fm.name === \"string\" ? fm.name : path.basename(dir);\n const description = typeof fm.description === \"string\" ? fm.description : \"\";\n const source = typeof fm.source === \"string\" ? fm.source : undefined;\n const version = typeof fm.version === \"string\" ? fm.version : undefined;\n const keywords = Array.isArray(fm.keywords) ? (fm.keywords as string[]) : undefined;\n acc.push({\n id: path.basename(dir),\n name,\n description,\n source,\n version,\n keywords,\n path: skillMdPath,\n });\n } catch {\n // skip unreadable files\n }\n return; // don't recurse inside a skill directory\n }\n\n // Recurse into subdirectories\n for (const entry of entries) {\n if (entry.isDirectory()) {\n await walkForSkillMd(path.join(dir, entry.name), acc);\n }\n }\n}\n\nasync function scanSkills(aiAssetsRoot: string): Promise<SkillEntry[]> {\n const acc: SkillEntry[] = [];\n for (const skillsDir of findKindDirs(aiAssetsRoot, \"skills\")) {\n await walkForSkillMd(skillsDir, acc);\n }\n // A `skills/` dir nested inside another is walked twice; keep each SKILL.md once.\n return [...new Map(acc.map((s) => [s.path, s])).values()];\n}\n\n// ── Exported tool functions ────────────────────────────────────────────────────\n\n/**\n * List all skills in the `ai-assets` catalog.\n *\n * Walks every `skills/` directory at any depth under the `ai-assets` root\n * looking for `SKILL.md` files. Returns a JSON array of skill summaries\n * `{ id, name, description, source, version, keywords }`.\n *\n * @param projectDir - Absolute path to the skaile project root.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillList(projectDir: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return okJson([]);\n const skills = await scanSkills(aiAssetsRoot);\n return okJson(\n skills.map((s) => ({\n id: s.id,\n name: s.name,\n description: s.description,\n source: s.source,\n version: s.version,\n keywords: s.keywords,\n })),\n );\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Show the full `SKILL.md` content for a skill.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param skillId - Skill ID (directory name) as returned by {@link skillList}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillShow(projectDir: string, skillId: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n return ok(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Search skills by name, description, ID, or keywords.\n *\n * Case-insensitive substring match against all text fields in every skill\n * entry. Returns the same summary shape as {@link skillList}.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param query - Search string.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillSearch(projectDir: string, query: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return okJson([]);\n const skills = await scanSkills(aiAssetsRoot);\n const q = query.toLowerCase();\n const matched = skills.filter(\n (s) =>\n s.name.toLowerCase().includes(q) ||\n s.description.toLowerCase().includes(q) ||\n s.id.toLowerCase().includes(q) ||\n (s.keywords ?? []).some((k) => k.toLowerCase().includes(q)),\n );\n return okJson(\n matched.map((s) => ({\n id: s.id,\n name: s.name,\n description: s.description,\n source: s.source,\n version: s.version,\n keywords: s.keywords,\n })),\n );\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Validate that all prerequisites declared in a skill's `SKILL.md` are\n * satisfied in `targetDir`.\n *\n * Uses `@skaile/workspaces/resolver` to parse the `REQUIRES` / `READS` / `WRITES`\n * DSL and run the requirement checks against the filesystem. Returns a\n * validation report as JSON.\n *\n * @param projectDir - Absolute path to the skaile project root (for skill lookup).\n * @param skillId - Skill ID as returned by {@link skillList}.\n * @param targetDir - Directory to validate against (typically the user's project).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillCheckRequirements(\n projectDir: string,\n skillId: string,\n targetDir: string,\n): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n\n const requirements = parseSkillRequirements(content);\n const report = await validateRequirements(skillId, requirements, targetDir);\n return okJson(report);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Get the formatted `REQUIRES`/`INPUT`/`READS`/`WRITES` DSL preamble for a skill.\n *\n * Uses `@skaile/workspaces/resolver` to build the requirements preamble that can be\n * prepended to the skill prompt for injection into the agent's context.\n * Returns `\"(no requirements declared)\"` when the skill has no requirements.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param skillId - Skill ID as returned by {@link skillList}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillGetPreamble(projectDir: string, skillId: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n\n const requirements = parseSkillRequirements(content);\n const preamble = buildRequiresPreamble(requirements, skillId);\n return ok(preamble || \"(no requirements declared)\");\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n"]}
1
+ {"version":3,"sources":["../workspace-plugin/src/tools/skills.ts"],"names":[],"mappings":";;;;;;;AA0BA,eAAe,cAAA,CAAe,KAAa,GAAA,EAAkC;AAC3E,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAM,EAAA,CAAG,OAAA,CAAQ,KAAK,EAAE,aAAA,EAAe,MAAM,CAAA;AAAA,EACzD,CAAA,CAAA,MAAQ;AACN,IAAA;AAAA,EACF;AAGA,EAAA,M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ools/skills.ts\n\nimport type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { findKindDirs } from \"@skaile/workspaces/core/discovery\";\nimport {\n buildRequiresPreamble,\n parseSkillFrontmatter,\n parseSkillRequirements,\n validateRequirements,\n} from \"@skaile/workspaces/resolver\";\nimport type { ToolResult } from \"../types.js\";\nimport { err, ok, okJson } from \"../types.js\";\nimport { findAiAssetsRoot } from \"../utils/ai-assets.js\";\n\ninterface SkillEntry {\n id: string;\n name: string;\n description: string;\n source?: string;\n version?: string;\n keywords?: string[];\n path: string;\n}\n\nasync function walkForSkillMd(dir: string, acc: SkillEntry[]): Promise<void> {\n let entries: Dirent<string>[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n // Check if this directory contains a SKILL.md\n const hasSkillMd = entries.some((e) => e.isFile() && e.name === \"SKILL.md\");\n if (hasSkillMd) {\n const skillMdPath = path.join(dir, \"SKILL.md\");\n try {\n const content = await fs.readFile(skillMdPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n const name = typeof fm.name === \"string\" ? fm.name : path.basename(dir);\n const description = typeof fm.description === \"string\" ? fm.description : \"\";\n const source = typeof fm.source === \"string\" ? fm.source : undefined;\n const version = typeof fm.version === \"string\" ? fm.version : undefined;\n const keywords = Array.isArray(fm.keywords) ? (fm.keywords as string[]) : undefined;\n acc.push({\n id: path.basename(dir),\n name,\n description,\n source,\n version,\n keywords,\n path: skillMdPath,\n });\n } catch {\n // skip unreadable files\n }\n return; // don't recurse inside a skill directory\n }\n\n // Recurse into subdirectories\n for (const entry of entries) {\n if (entry.isDirectory()) {\n await walkForSkillMd(path.join(dir, entry.name), acc);\n }\n }\n}\n\nasync function scanSkills(aiAssetsRoot: string): Promise<SkillEntry[]> {\n const acc: SkillEntry[] = [];\n for (const skillsDir of findKindDirs(aiAssetsRoot, \"skills\")) {\n await walkForSkillMd(skillsDir, acc);\n }\n // A `skills/` dir nested inside another is walked twice; keep each SKILL.md once.\n return [...new Map(acc.map((s) => [s.path, s])).values()];\n}\n\n// ── Exported tool functions ────────────────────────────────────────────────────\n\n/**\n * List all skills in the `ai-assets` catalog.\n *\n * Walks every `skills/` directory at any depth under the `ai-assets` root\n * looking for `SKILL.md` files. Returns a JSON array of skill summaries\n * `{ id, name, description, source, version, keywords }`.\n *\n * @param projectDir - Absolute path to the skaile project root.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillList(projectDir: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return okJson([]);\n const skills = await scanSkills(aiAssetsRoot);\n return okJson(\n skills.map((s) => ({\n id: s.id,\n name: s.name,\n description: s.description,\n source: s.source,\n version: s.version,\n keywords: s.keywords,\n })),\n );\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Show the full `SKILL.md` content for a skill.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param skillId - Skill ID (directory name) as returned by {@link skillList}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillShow(projectDir: string, skillId: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n return ok(content);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Search skills by name, description, ID, or keywords.\n *\n * Case-insensitive substring match against all text fields in every skill\n * entry. Returns the same summary shape as {@link skillList}.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param query - Search string.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillSearch(projectDir: string, query: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return okJson([]);\n const skills = await scanSkills(aiAssetsRoot);\n const q = query.toLowerCase();\n const matched = skills.filter(\n (s) =>\n s.name.toLowerCase().includes(q) ||\n s.description.toLowerCase().includes(q) ||\n s.id.toLowerCase().includes(q) ||\n (s.keywords ?? []).some((k) => k.toLowerCase().includes(q)),\n );\n return okJson(\n matched.map((s) => ({\n id: s.id,\n name: s.name,\n description: s.description,\n source: s.source,\n version: s.version,\n keywords: s.keywords,\n })),\n );\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Validate that all prerequisites declared in a skill's `SKILL.md` are\n * satisfied in `targetDir`.\n *\n * Uses `@skaile/workspaces/resolver` to parse the `REQUIRES` / `READS` / `WRITES`\n * DSL and run the requirement checks against the filesystem. Returns a\n * validation report as JSON.\n *\n * @param projectDir - Absolute path to the skaile project root (for skill lookup).\n * @param skillId - Skill ID as returned by {@link skillList}.\n * @param targetDir - Directory to validate against (typically the user's project).\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillCheckRequirements(\n projectDir: string,\n skillId: string,\n targetDir: string,\n): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n\n const requirements = parseSkillRequirements(content);\n const report = await validateRequirements(skillId, requirements, targetDir);\n return okJson(report);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Get the formatted `REQUIRES`/`INPUT`/`READS`/`WRITES` DSL preamble for a skill.\n *\n * Uses `@skaile/workspaces/resolver` to build the requirements preamble that can be\n * prepended to the skill prompt for injection into the agent's context.\n * Returns `\"(no requirements declared)\"` when the skill has no requirements.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param skillId - Skill ID as returned by {@link skillList}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function skillGetPreamble(projectDir: string, skillId: string): Promise<ToolResult> {\n try {\n const aiAssetsRoot = await findAiAssetsRoot(projectDir);\n if (!aiAssetsRoot) return err(`Skill not found: ${skillId}`);\n const skills = await scanSkills(aiAssetsRoot);\n const skill = skills.find((s) => s.id === skillId);\n if (!skill) return err(`Skill not found: ${skillId}`);\n const content = await fs.readFile(skill.path, \"utf-8\");\n\n const requirements = parseSkillRequirements(content);\n const preamble = buildRequiresPreamble(requirements, skillId);\n return ok(preamble || \"(no requirements declared)\");\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n"]}