@skaile/workspaces 4.39.0 → 5.0.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 (337) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/{asset-feeds-KXL45ALC.js → asset-feeds-HIWT4DVT.js} +24 -96
  3. package/dist/asset-feeds-HIWT4DVT.js.map +1 -0
  4. package/dist/asset-manager/catalog-deployer.js +10 -9
  5. package/dist/asset-manager/index.js +15 -14
  6. package/dist/asset-manager/installer.js +10 -9
  7. package/dist/asset-manager/src/catalog-deployer.d.ts +1 -3
  8. package/dist/asset-manager/src/catalog-deployer.d.ts.map +1 -1
  9. package/dist/asset-manager/src/index.d.ts +6 -8
  10. package/dist/asset-manager/src/index.d.ts.map +1 -1
  11. package/dist/bridge/drivers/claude-sdk.js +23 -11
  12. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  13. package/dist/bridge/drivers/codex.js +11 -10
  14. package/dist/bridge/drivers/codex.js.map +1 -1
  15. package/dist/bridge/drivers/continue.js +12 -11
  16. package/dist/bridge/drivers/continue.js.map +1 -1
  17. package/dist/bridge/drivers/echo.js +2 -2
  18. package/dist/bridge/drivers/gemini.js +6 -6
  19. package/dist/bridge/drivers/goose.js +12 -11
  20. package/dist/bridge/drivers/goose.js.map +1 -1
  21. package/dist/bridge/drivers/omp.js +3 -3
  22. package/dist/bridge/drivers/opencode.js +12 -11
  23. package/dist/bridge/drivers/opencode.js.map +1 -1
  24. package/dist/bridge/drivers/qwen.js +6 -6
  25. package/dist/bridge/index.js +13 -12
  26. package/dist/bridge/src/drivers/claude-sdk.d.ts +4 -0
  27. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  28. package/dist/bridge/src/types.d.ts +7 -0
  29. package/dist/bridge/src/types.d.ts.map +1 -1
  30. package/dist/{chunk-7RC37XFW.js → chunk-22DN3DB2.js} +59 -12
  31. package/dist/chunk-22DN3DB2.js.map +1 -0
  32. package/dist/{chunk-SM6EUQMY.js → chunk-32DMH2GD.js} +8 -8
  33. package/dist/{chunk-SM6EUQMY.js.map → chunk-32DMH2GD.js.map} +1 -1
  34. package/dist/{chunk-A5EDMBFG.js → chunk-43ZBF3WH.js} +5 -8
  35. package/dist/chunk-43ZBF3WH.js.map +1 -0
  36. package/dist/{chunk-5RWL4L3X.js → chunk-53WMBXSL.js} +60 -14
  37. package/dist/chunk-53WMBXSL.js.map +1 -0
  38. package/dist/{chunk-YCMZHL4T.js → chunk-7QMRP6BC.js} +4 -4
  39. package/dist/{chunk-YCMZHL4T.js.map → chunk-7QMRP6BC.js.map} +1 -1
  40. package/dist/chunk-A2ULN3KX.js +40 -0
  41. package/dist/chunk-A2ULN3KX.js.map +1 -0
  42. package/dist/{chunk-DSB6X25D.js → chunk-AG44ZJ7W.js} +3 -3
  43. package/dist/{chunk-DSB6X25D.js.map → chunk-AG44ZJ7W.js.map} +1 -1
  44. package/dist/{chunk-SSCPTAFJ.js → chunk-CFL5IJHV.js} +3 -3
  45. package/dist/{chunk-SSCPTAFJ.js.map → chunk-CFL5IJHV.js.map} +1 -1
  46. package/dist/{chunk-36ML6SFP.js → chunk-CGJ7B6MZ.js} +4 -4
  47. package/dist/{chunk-36ML6SFP.js.map → chunk-CGJ7B6MZ.js.map} +1 -1
  48. package/dist/{chunk-6X4DHKHP.js → chunk-CT6NQSA4.js} +3 -3
  49. package/dist/{chunk-6X4DHKHP.js.map → chunk-CT6NQSA4.js.map} +1 -1
  50. package/dist/{chunk-5K2VT6E2.js → chunk-DXUQCMVT.js} +3 -3
  51. package/dist/{chunk-5K2VT6E2.js.map → chunk-DXUQCMVT.js.map} +1 -1
  52. package/dist/{chunk-B4IAZTZZ.js → chunk-EB6OPURC.js} +3 -3
  53. package/dist/{chunk-B4IAZTZZ.js.map → chunk-EB6OPURC.js.map} +1 -1
  54. package/dist/{chunk-252TK4RU.js → chunk-GFPG27HK.js} +12 -14
  55. package/dist/chunk-GFPG27HK.js.map +1 -0
  56. package/dist/{chunk-2EL2PBRC.js → chunk-H4EGUQ7M.js} +3 -3
  57. package/dist/{chunk-2EL2PBRC.js.map → chunk-H4EGUQ7M.js.map} +1 -1
  58. package/dist/{chunk-YQEF36D5.js → chunk-H5G3OYY6.js} +4 -4
  59. package/dist/{chunk-YQEF36D5.js.map → chunk-H5G3OYY6.js.map} +1 -1
  60. package/dist/{chunk-C75VKXAM.js → chunk-HD5K3BYW.js} +3 -3
  61. package/dist/{chunk-C75VKXAM.js.map → chunk-HD5K3BYW.js.map} +1 -1
  62. package/dist/{chunk-VJNTB4DN.js → chunk-HTBGJCKP.js} +4 -4
  63. package/dist/{chunk-VJNTB4DN.js.map → chunk-HTBGJCKP.js.map} +1 -1
  64. package/dist/{chunk-JEPSP6XK.js → chunk-HWE3FXF4.js} +17 -11
  65. package/dist/chunk-HWE3FXF4.js.map +1 -0
  66. package/dist/{chunk-QVLQGXT6.js → chunk-I3ITSUWS.js} +5 -5
  67. package/dist/{chunk-QVLQGXT6.js.map → chunk-I3ITSUWS.js.map} +1 -1
  68. package/dist/{chunk-H7N6RWNF.js → chunk-I7Z4FN52.js} +4 -4
  69. package/dist/{chunk-H7N6RWNF.js.map → chunk-I7Z4FN52.js.map} +1 -1
  70. package/dist/{chunk-WCWFS36P.js → chunk-IGXKUCLI.js} +3 -3
  71. package/dist/{chunk-WCWFS36P.js.map → chunk-IGXKUCLI.js.map} +1 -1
  72. package/dist/{chunk-VXPFSZDT.js → chunk-JFVEX4G5.js} +6 -6
  73. package/dist/{chunk-VXPFSZDT.js.map → chunk-JFVEX4G5.js.map} +1 -1
  74. package/dist/{chunk-YYH5EVPM.js → chunk-JUXQUZOQ.js} +12 -4
  75. package/dist/{chunk-YYH5EVPM.js.map → chunk-JUXQUZOQ.js.map} +1 -1
  76. package/dist/{chunk-M7GPCWEV.js → chunk-KREXWKVX.js} +3 -3
  77. package/dist/{chunk-M7GPCWEV.js.map → chunk-KREXWKVX.js.map} +1 -1
  78. package/dist/{chunk-TQ6XNACF.js → chunk-LHFZTVIM.js} +23 -24
  79. package/dist/chunk-LHFZTVIM.js.map +1 -0
  80. package/dist/{chunk-YV3YI3TA.js → chunk-MBVNMPG7.js} +4 -4
  81. package/dist/{chunk-YV3YI3TA.js.map → chunk-MBVNMPG7.js.map} +1 -1
  82. package/dist/{chunk-3C3ODIDE.js → chunk-MX7IRKTO.js} +6 -6
  83. package/dist/{chunk-3C3ODIDE.js.map → chunk-MX7IRKTO.js.map} +1 -1
  84. package/dist/{chunk-UDFWBALP.js → chunk-NFGRW3L7.js} +3 -3
  85. package/dist/{chunk-UDFWBALP.js.map → chunk-NFGRW3L7.js.map} +1 -1
  86. package/dist/{chunk-5LF27VUB.js → chunk-ODT7HSLI.js} +16 -15
  87. package/dist/chunk-ODT7HSLI.js.map +1 -0
  88. package/dist/{chunk-QBQITQAM.js → chunk-PV4OBVA3.js} +3 -3
  89. package/dist/{chunk-QBQITQAM.js.map → chunk-PV4OBVA3.js.map} +1 -1
  90. package/dist/{chunk-ORH2BZEM.js → chunk-QCI6D7E4.js} +69 -22
  91. package/dist/chunk-QCI6D7E4.js.map +1 -0
  92. package/dist/{chunk-DIQDYNXZ.js → chunk-QZLWJETK.js} +3 -3
  93. package/dist/{chunk-DIQDYNXZ.js.map → chunk-QZLWJETK.js.map} +1 -1
  94. package/dist/{chunk-TSVRKUGV.js → chunk-RP4B4HVX.js} +11 -2
  95. package/dist/chunk-RP4B4HVX.js.map +1 -0
  96. package/dist/{chunk-X4DKUGV4.js → chunk-RSHMAEK3.js} +7 -13
  97. package/dist/chunk-RSHMAEK3.js.map +1 -0
  98. package/dist/chunk-RVRB27AN.js +64 -0
  99. package/dist/chunk-RVRB27AN.js.map +1 -0
  100. package/dist/{chunk-5NYBY6ZE.js → chunk-TVOODIZE.js} +3 -3
  101. package/dist/{chunk-5NYBY6ZE.js.map → chunk-TVOODIZE.js.map} +1 -1
  102. package/dist/{chunk-FTPKMJFD.js → chunk-TVYLXZTT.js} +2 -2
  103. package/dist/{chunk-FTPKMJFD.js.map → chunk-TVYLXZTT.js.map} +1 -1
  104. package/dist/{chunk-EOKAFBJ7.js → chunk-TYUJB336.js} +3 -3
  105. package/dist/{chunk-EOKAFBJ7.js.map → chunk-TYUJB336.js.map} +1 -1
  106. package/dist/{chunk-OLMNDIAU.js → chunk-UVOJSWD2.js} +95 -320
  107. package/dist/chunk-UVOJSWD2.js.map +1 -0
  108. package/dist/{chunk-DOVURNRK.js → chunk-VDJKWKH2.js} +3 -3
  109. package/dist/chunk-VDJKWKH2.js.map +1 -0
  110. package/dist/{chunk-VDBP6Y5M.js → chunk-WCQMXBO5.js} +21 -47
  111. package/dist/chunk-WCQMXBO5.js.map +1 -0
  112. package/dist/{chunk-NLKIW2VI.js → chunk-WOJ4AK3Q.js} +3 -3
  113. package/dist/{chunk-NLKIW2VI.js.map → chunk-WOJ4AK3Q.js.map} +1 -1
  114. package/dist/{chunk-XU7JET5Z.js → chunk-X7MHVL4R.js} +16 -100
  115. package/dist/chunk-X7MHVL4R.js.map +1 -0
  116. package/dist/{chunk-K3IBZ2UZ.js → chunk-XUUYAS3Z.js} +3 -3
  117. package/dist/{chunk-K3IBZ2UZ.js.map → chunk-XUUYAS3Z.js.map} +1 -1
  118. package/dist/{chunk-BCUVRJXV.js → chunk-XWLEXD34.js} +3 -3
  119. package/dist/{chunk-BCUVRJXV.js.map → chunk-XWLEXD34.js.map} +1 -1
  120. package/dist/{chunk-P7BU6DAC.js → chunk-YOWFUJO7.js} +69 -31
  121. package/dist/chunk-YOWFUJO7.js.map +1 -0
  122. package/dist/{chunk-OQRB7JUS.js → chunk-YV4J7V53.js} +3 -3
  123. package/dist/{chunk-OQRB7JUS.js.map → chunk-YV4J7V53.js.map} +1 -1
  124. package/dist/{chunk-JXT46QFC.js → chunk-ZDKJHQY2.js} +2 -2
  125. package/dist/{chunk-JXT46QFC.js.map → chunk-ZDKJHQY2.js.map} +1 -1
  126. package/dist/cli/index.js +375 -699
  127. package/dist/cli/index.js.map +1 -1
  128. package/dist/cli/src/asset-feeds.d.ts +1 -8
  129. package/dist/cli/src/asset-feeds.d.ts.map +1 -1
  130. package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
  131. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  132. package/dist/cli/src/commands/library-index.d.ts +5 -12
  133. package/dist/cli/src/commands/library-index.d.ts.map +1 -1
  134. package/dist/cli/src/commands/manage.d.ts +74 -58
  135. package/dist/cli/src/commands/manage.d.ts.map +1 -1
  136. package/dist/cli/src/commands/show.d.ts +1 -1
  137. package/dist/cli/src/commands/skailify-lib.d.ts +0 -31
  138. package/dist/cli/src/commands/skailify-lib.d.ts.map +1 -1
  139. package/dist/cli/src/commands/source-manifest.d.ts.map +1 -1
  140. package/dist/cli/src/commands/validate.d.ts +20 -2
  141. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  142. package/dist/cli/src/flow-discovery.d.ts +2 -2
  143. package/dist/cli/src/hooks/pre-commit-version.d.ts +1 -1
  144. package/dist/cli/src/skill-walker.d.ts +7 -10
  145. package/dist/cli/src/skill-walker.d.ts.map +1 -1
  146. package/dist/connectors/config.js +6 -5
  147. package/dist/connectors/index.js +21 -20
  148. package/dist/core/discovery.js +1 -1
  149. package/dist/core/index.js +9 -8
  150. package/dist/core/manifest.js +2 -2
  151. package/dist/core/models.js +1 -1
  152. package/dist/core/plugin-groupings.d.ts +2 -0
  153. package/dist/core/plugin-groupings.js +4 -0
  154. package/dist/core/plugin-groupings.js.map +1 -0
  155. package/dist/core/publish-manifest.js +2 -2
  156. package/dist/core/ref.js +1 -1
  157. package/dist/core/runtime-assets.js +6 -5
  158. package/dist/core/src/discovery.d.ts +11 -51
  159. package/dist/core/src/discovery.d.ts.map +1 -1
  160. package/dist/core/src/index.d.ts +3 -2
  161. package/dist/core/src/index.d.ts.map +1 -1
  162. package/dist/core/src/models.d.ts +6 -33
  163. package/dist/core/src/models.d.ts.map +1 -1
  164. package/dist/core/src/plugin-groupings.d.ts +31 -0
  165. package/dist/core/src/plugin-groupings.d.ts.map +1 -0
  166. package/dist/core/src/repo-manager.d.ts.map +1 -1
  167. package/dist/core/src/settings.d.ts +1 -1
  168. package/dist/core/src/workspace-config.d.ts +1 -1
  169. package/dist/core/workspace-config.js +5 -4
  170. package/dist/deploy/index.js +9 -8
  171. package/dist/deploy/index.js.map +1 -1
  172. package/dist/discovery/index.js +6 -5
  173. package/dist/discovery/src/discover.d.ts +9 -25
  174. package/dist/discovery/src/discover.d.ts.map +1 -1
  175. package/dist/discovery/src/index.d.ts +0 -2
  176. package/dist/discovery/src/index.d.ts.map +1 -1
  177. package/dist/discovery/src/source-config.d.ts +13 -9
  178. package/dist/discovery/src/source-config.d.ts.map +1 -1
  179. package/dist/discovery/src/tree-entries.d.ts +6 -11
  180. package/dist/discovery/src/tree-entries.d.ts.map +1 -1
  181. package/dist/{ensure-sources-J5CDTQ36.js → ensure-sources-G4FXTJDB.js} +18 -17
  182. package/dist/ensure-sources-G4FXTJDB.js.map +1 -0
  183. package/dist/factory-assets/README.md +1 -1
  184. package/dist/factory-assets/connectors/box.js +21 -20
  185. package/dist/factory-assets/connectors/deploy.js +21 -20
  186. package/dist/factory-assets/connectors/devserver.js +21 -20
  187. package/dist/factory-assets/connectors/flow/CONNECTOR.md +6 -1
  188. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  189. package/dist/factory-assets/connectors/flow/adapter.js +21 -20
  190. package/dist/factory-assets/connectors/flow/contract/flow.v2.schema.json +13 -3
  191. package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -0
  192. package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
  193. package/dist/factory-assets/connectors/flow/contract/output-fields.d.ts +21 -5
  194. package/dist/factory-assets/connectors/flow/contract/output-fields.d.ts.map +1 -1
  195. package/dist/factory-assets/connectors/flow/contract/schema.d.ts +2 -0
  196. package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
  197. package/dist/factory-assets/connectors/flow/contract/sub-flow-output.d.ts +20 -0
  198. package/dist/factory-assets/connectors/flow/contract/sub-flow-output.d.ts.map +1 -0
  199. package/dist/factory-assets/connectors/flow/contract.js +4 -4
  200. package/dist/factory-assets/connectors/flow/engine/bindings.d.ts.map +1 -1
  201. package/dist/factory-assets/connectors/flow/engine/flow-output.d.ts +12 -0
  202. package/dist/factory-assets/connectors/flow/engine/flow-output.d.ts.map +1 -0
  203. package/dist/factory-assets/connectors/flow/engine/index.d.ts +1 -0
  204. package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
  205. package/dist/factory-assets/connectors/flow/engine/loader.d.ts +3 -3
  206. package/dist/factory-assets/connectors/flow/engine/locate.d.ts +2 -2
  207. package/dist/factory-assets/connectors/flow/engine/locate.d.ts.map +1 -1
  208. package/dist/factory-assets/connectors/flow/engine/types.d.ts +0 -2
  209. package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
  210. package/dist/factory-assets/connectors/flow/engine.js +13 -12
  211. package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts.map +1 -1
  212. package/dist/factory-assets/connectors/flow/prompt-fragments.js +3 -3
  213. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  214. package/dist/factory-assets/connectors/flow/run-flow.js +23 -22
  215. package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts +6 -5
  216. package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts.map +1 -1
  217. package/dist/factory-assets/connectors/flow.js +21 -20
  218. package/dist/factory-assets/connectors/git.js +21 -20
  219. package/dist/factory-assets/connectors/gmail.js +21 -20
  220. package/dist/factory-assets/connectors/googledrive.js +21 -20
  221. package/dist/factory-assets/connectors/local.js +21 -20
  222. package/dist/factory-assets/connectors/mattermost.js +21 -20
  223. package/dist/factory-assets/connectors/memory.js +21 -20
  224. package/dist/factory-assets/connectors/minio.js +21 -20
  225. package/dist/factory-assets/connectors/postgres.js +21 -20
  226. package/dist/factory-assets/connectors/s3.js +21 -20
  227. package/dist/factory-assets/connectors/sharepoint.js +21 -20
  228. package/dist/factory-assets/connectors/sqlite.js +21 -20
  229. package/dist/factory-assets/connectors/static-server.js +21 -20
  230. package/dist/factory-assets/connectors/tunnel.js +21 -20
  231. package/dist/factory-assets/connectors/webdav.js +21 -20
  232. package/dist/factory-assets/connectors/xstate-store.js +21 -20
  233. package/dist/factory-assets/connectors/xstate.js +21 -20
  234. package/dist/factory-assets/skills/skaile-author-asset/SKILL.md +37 -26
  235. package/dist/factory-assets/skills/skaile-manage-workspace/SKILL.md +2 -2
  236. package/dist/factory-assets/skills/skailify/SKILL.md +10 -19
  237. package/dist/{flows-PX53XFV7.js → flows-7E2GVW5L.js} +14 -13
  238. package/dist/{flows-PX53XFV7.js.map → flows-7E2GVW5L.js.map} +1 -1
  239. package/dist/{helpers-EP6H3O3S.js → helpers-EVPKJXGS.js} +18 -17
  240. package/dist/{helpers-EP6H3O3S.js.map → helpers-EVPKJXGS.js.map} +1 -1
  241. package/dist/library/index.js +13 -12
  242. package/dist/library/install.js +2 -2
  243. package/dist/library/src/index.d.ts +1 -1
  244. package/dist/library/src/index.d.ts.map +1 -1
  245. package/dist/library/src/local/db.d.ts.map +1 -1
  246. package/dist/library/src/local/library-manager.d.ts.map +1 -1
  247. package/dist/library/src/local/library.d.ts.map +1 -1
  248. package/dist/library/src/local/local-catalog-source.d.ts +0 -9
  249. package/dist/library/src/local/local-catalog-source.d.ts.map +1 -1
  250. package/dist/library/src/local/schema.d.ts +1 -20
  251. package/dist/library/src/local/schema.d.ts.map +1 -1
  252. package/dist/library/src/remote/remote-catalog-source.d.ts +1 -11
  253. package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
  254. package/dist/library/src/sync/manifest-writeback.d.ts +5 -5
  255. package/dist/library/src/sync/manifest-writeback.d.ts.map +1 -1
  256. package/dist/library/src/user-library.d.ts +1 -9
  257. package/dist/library/src/user-library.d.ts.map +1 -1
  258. package/dist/{library-publish-KKT73FJK.js → library-publish-SBEWWTPM.js} +25 -24
  259. package/dist/library-publish-SBEWWTPM.js.map +1 -0
  260. package/dist/open-library-UAZIGZUQ.js +39 -0
  261. package/dist/{open-library-R62UBL6E.js.map → open-library-UAZIGZUQ.js.map} +1 -1
  262. package/dist/paths-U7TA7MTE.js +22 -0
  263. package/dist/{paths-W4LDORQQ.js.map → paths-U7TA7MTE.js.map} +1 -1
  264. package/dist/{plugin-store-D45CREMJ.js → plugin-store-TT45MGQZ.js} +11 -10
  265. package/dist/plugin-store-TT45MGQZ.js.map +1 -0
  266. package/dist/plugins/index.js +1 -1
  267. package/dist/plugins/src/catalog-source.d.ts +4 -55
  268. package/dist/plugins/src/catalog-source.d.ts.map +1 -1
  269. package/dist/plugins/src/index.d.ts +1 -1
  270. package/dist/plugins/src/index.d.ts.map +1 -1
  271. package/dist/{project-GCW5DFAB.js → project-JLD5RCVK.js} +19 -18
  272. package/dist/{project-GCW5DFAB.js.map → project-JLD5RCVK.js.map} +1 -1
  273. package/dist/resolver/index.js +10 -9
  274. package/dist/runner/index.js +32 -31
  275. package/dist/runner/src/compaction/orchestrator.d.ts +2 -1
  276. package/dist/runner/src/compaction/orchestrator.d.ts.map +1 -1
  277. package/dist/runner/src/compaction-gate.d.ts +13 -0
  278. package/dist/runner/src/compaction-gate.d.ts.map +1 -1
  279. package/dist/runner/src/serve.d.ts.map +1 -1
  280. package/dist/sdk/asset-manager.js +15 -14
  281. package/dist/sdk/bridge.js +13 -12
  282. package/dist/sdk/core.js +9 -8
  283. package/dist/sdk/flow.js +13 -12
  284. package/dist/sdk/index.js +32 -31
  285. package/dist/sdk/index.js.map +1 -1
  286. package/dist/sdk/resolver.js +10 -9
  287. package/dist/sdk/runner.js +32 -31
  288. package/dist/secrets/index.js +2 -2
  289. package/dist/{setup-Q3LXY5AE.js → setup-PGZM4SOO.js} +23 -22
  290. package/dist/setup-PGZM4SOO.js.map +1 -0
  291. package/dist/skills-7QVYPIXI.js +26 -0
  292. package/dist/{skills-R3RPIPWP.js.map → skills-7QVYPIXI.js.map} +1 -1
  293. package/dist/source-SDZYXVVV.js +40 -0
  294. package/dist/{source-CFQESKJU.js.map → source-SDZYXVVV.js.map} +1 -1
  295. package/dist/{source-manifest-publish-3TCBA2RV.js → source-manifest-publish-UDLTYV6Y.js} +26 -25
  296. package/dist/source-manifest-publish-UDLTYV6Y.js.map +1 -0
  297. package/dist/tui/index.js +32 -31
  298. package/dist/tui/index.js.map +1 -1
  299. package/dist/workspace-plugin/adapters/mcp.js +16 -15
  300. package/dist/workspace-plugin/adapters/omp.js +13 -13
  301. package/dist/workspace-plugin/adapters/omp.js.map +1 -1
  302. package/dist/workspace-plugin/index.js +1 -1
  303. package/dist/workspace-plugin/src/adapters/mcp.d.ts +4 -4
  304. package/dist/workspace-plugin/src/adapters/mcp.d.ts.map +1 -1
  305. package/dist/workspace-plugin/src/adapters/omp.d.ts +2 -2
  306. package/dist/workspace-plugin/src/tools/skills.d.ts +5 -17
  307. package/dist/workspace-plugin/src/tools/skills.d.ts.map +1 -1
  308. package/package.json +7 -1
  309. package/dist/asset-feeds-KXL45ALC.js.map +0 -1
  310. package/dist/chunk-252TK4RU.js.map +0 -1
  311. package/dist/chunk-5LF27VUB.js.map +0 -1
  312. package/dist/chunk-5RWL4L3X.js.map +0 -1
  313. package/dist/chunk-7RC37XFW.js.map +0 -1
  314. package/dist/chunk-A5EDMBFG.js.map +0 -1
  315. package/dist/chunk-DOVURNRK.js.map +0 -1
  316. package/dist/chunk-JEPSP6XK.js.map +0 -1
  317. package/dist/chunk-OLMNDIAU.js.map +0 -1
  318. package/dist/chunk-ORH2BZEM.js.map +0 -1
  319. package/dist/chunk-P7BU6DAC.js.map +0 -1
  320. package/dist/chunk-QVZA2MDT.js +0 -81
  321. package/dist/chunk-QVZA2MDT.js.map +0 -1
  322. package/dist/chunk-TQ6XNACF.js.map +0 -1
  323. package/dist/chunk-TSVRKUGV.js.map +0 -1
  324. package/dist/chunk-VDBP6Y5M.js.map +0 -1
  325. package/dist/chunk-X4DKUGV4.js.map +0 -1
  326. package/dist/chunk-XU7JET5Z.js.map +0 -1
  327. package/dist/discovery/src/domains.d.ts +0 -149
  328. package/dist/discovery/src/domains.d.ts.map +0 -1
  329. package/dist/ensure-sources-J5CDTQ36.js.map +0 -1
  330. package/dist/library-publish-KKT73FJK.js.map +0 -1
  331. package/dist/open-library-R62UBL6E.js +0 -38
  332. package/dist/paths-W4LDORQQ.js +0 -21
  333. package/dist/plugin-store-D45CREMJ.js.map +0 -1
  334. package/dist/setup-Q3LXY5AE.js.map +0 -1
  335. package/dist/skills-R3RPIPWP.js +0 -25
  336. package/dist/source-CFQESKJU.js +0 -39
  337. package/dist/source-manifest-publish-3TCBA2RV.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { SecretNotFoundError, SecretAccessDeniedError, SecretsError, ProviderUnavailableError } from './chunk-JXT46QFC.js';
1
+ import { SecretNotFoundError, SecretAccessDeniedError, SecretsError, ProviderUnavailableError } from './chunk-ZDKJHQY2.js';
2
2
  import { globalSkaileDir } from './chunk-TLKM4M47.js';
3
3
  import * as crypto from 'crypto';
4
4
  import * as fs from 'fs';
@@ -532,5 +532,5 @@ var SecretsRouter = class {
532
532
  var VERSION = "0.0.0";
533
533
 
534
534
  export { CredentialLifecycleService, EnvSecretsProvider, LocalSecretsProvider, SecretsRouter, VERSION };
535
- //# sourceMappingURL=chunk-B4IAZTZZ.js.map
536
- //# sourceMappingURL=chunk-B4IAZTZZ.js.map
535
+ //# sourceMappingURL=chunk-EB6OPURC.js.map
536
+ //# sourceMappingURL=chunk-EB6OPURC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../secrets/src/lifecycle.ts","../secrets/src/providers/env.ts","../secrets/src/providers/local.ts","../secrets/src/router.ts","../secrets/src/index.ts"],"names":["provider"],"mappings":";;;;;;;;AAuCO,IAAM,6BAAN,MAAiC;AAAA,EAC9B,MAAA;AAAA;AAAA;AAAA;AAAA,EAKR,WAAA,CAAY,QAAuB,OAAA,EAA8C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MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,UAAA,EAAa,EAAE,CAAA,gBAAA,CAAA,EAAmB;AAAA,IAC/D;AACA,IAAA,OAAO,SAAS,cAAA,EAAe;AAAA,EACjC;AACF;;;ACvNO,IAAM,OAAA,GAAU","file":"chunk-B4IAZTZZ.js","sourcesContent":["/**\n * CredentialLifecycleService — manages OAuth token refresh outside the SecretsRouter.\n *\n * Works with opaque token blobs stored via the {@link SecretsRouter}; providers remain\n * OAuth-unaware. Phase 1 ships non-OAuth paths (always returns `not_applicable`).\n * Full proactive OAuth refresh with expiry checking ships in Phase 3.4.\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\n\nimport type { SecretsRouter } from \"./router.js\";\n\n/**\n * Configuration for {@link CredentialLifecycleService}.\n *\n * Controls how aggressively the service proactively refreshes credentials before they expire.\n * The default lead time is 300 seconds (5 minutes).\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\nexport interface CredentialLifecycleConfig {\n /** How far before expiry to trigger a proactive refresh (seconds). */\n refreshLeadTimeSec: number;\n}\n\n/**\n * Result returned by {@link CredentialLifecycleService.refreshIfNeeded}.\n *\n * The `reason` discriminant indicates why a refresh did or did not occur.\n * An `error` string is present only when `reason` is `refresh_failed`.\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\nexport interface RefreshResult {\n refreshed: boolean;\n reason: \"not_applicable\" | \"still_valid\" | \"refreshed\" | \"refresh_failed\";\n error?: string;\n}\n\nexport class CredentialLifecycleService {\n private router: SecretsRouter;\n\n // `_config` is accepted for signature stability but not stored yet: Phase 1\n // ships no OAuth refresh, so there is nothing to configure. Phase 3.4 will\n // store and read `refreshLeadTimeSec` when proactive refresh lands.\n constructor(router: SecretsRouter, _config?: Partial<CredentialLifecycleConfig>) {\n this.router = router;\n }\n\n /**\n * Attempt to refresh a credential if needed.\n * Phase 1: always returns not_applicable (no OAuth support yet).\n */\n async refreshIfNeeded(credentialRef: string): Promise<RefreshResult> {\n // Phase 1: no OAuth refresh implemented.\n // The credential exists and is valid as-is (static secrets, env vars, etc.)\n try {\n await this.router.getMetadata(credentialRef);\n return { refreshed: false, reason: \"not_applicable\" };\n } catch {\n return { refreshed: false, reason: \"refresh_failed\", error: \"Credential not found\" };\n }\n }\n\n /**\n * Check if a credential is still valid (not expired).\n * Phase 1: always returns true for non-OAuth credentials.\n */\n async isValid(credentialRef: string): Promise<boolean> {\n try {\n await this.router.getSecret(credentialRef);\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * EnvSecretsProvider — read-only provider that resolves secrets from environment variables.\n *\n * Refs are expected to be plain env var names (e.g. `DATABASE_URL`). The provider is\n * always available with zero configuration and requires no encryption or keychain access.\n * `setSecret` and `deleteSecret` always throw `SecretAccessDeniedError` because\n * environment variables are managed externally to the running process.\n *\n * @docLink packages/secrets/concepts#env-secrets-provider\n */\n\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport { SecretAccessDeniedError, SecretNotFoundError } from \"@skaile/workspaces/plugins\";\n\n/**\n * Sentinel timestamp for env secrets, which have no real created/updated time.\n * The Unix epoch is unambiguously not \"now\", so consumers can recognise it as\n * \"unknown\" rather than treating it as a genuine recent timestamp.\n */\nconst ENV_UNKNOWN_TIMESTAMP = new Date(0);\n\nexport class EnvSecretsProvider implements ISecretsProvider {\n readonly id = \"env\";\n\n async getSecret(ref: string): Promise<Uint8Array> {\n const value = process.env[ref];\n if (value === undefined) {\n throw new SecretNotFoundError(ref);\n }\n return new TextEncoder().encode(value);\n }\n\n async setSecret(_ref: string, _value: Uint8Array, _opts?: SetSecretOptions): Promise<void> {\n throw new SecretAccessDeniedError(\"EnvSecretsProvider is read-only\");\n }\n\n async deleteSecret(_ref: string): Promise<void> {\n throw new SecretAccessDeniedError(\"EnvSecretsProvider is read-only\");\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n let keys = Object.keys(process.env);\n if (filter?.prefix) {\n keys = keys.filter((k) => k.startsWith(filter.prefix!));\n }\n if (filter?.limit) {\n keys = keys.slice(0, filter.limit);\n }\n return keys;\n }\n\n async testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n return { ok: true, latencyMs: 0 };\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const value = process.env[ref];\n if (value === undefined) {\n throw new SecretNotFoundError(ref);\n }\n // Env vars carry no creation/modification time. `SecretMetadata` requires\n // both fields, so use the Unix epoch as a documented \"unknown\" sentinel\n // rather than `new Date()`, which would falsely imply the secret was just\n // created/updated. The read-only scope summary already signals the source.\n return {\n ref,\n createdAt: ENV_UNKNOWN_TIMESTAMP,\n updatedAt: ENV_UNKNOWN_TIMESTAMP,\n scopeSummary: \"environment variable (read-only)\",\n };\n }\n\n getCapabilities(): ProviderCapabilities {\n return {\n supportsRotation: false,\n supportsExpiry: false,\n supportsBatch: false,\n scopeModel: \"flat\",\n };\n }\n}\n","/**\n * LocalSecretsProvider — AES-256-GCM encrypted file-blob storage at `~/.skaile/secrets/`.\n *\n * Each secret is stored as a separate `.enc` file named by the SHA-256 hash of the ref\n * (collision-free, filesystem-safe). A companion `.meta.json` stores the original ref,\n * timestamps, and optional user metadata. The master key is derived via PBKDF2-SHA-512\n * from one of three {@link KeyStrategy} sources: OS keychain (keytar), a passphrase from\n * `SKAILE_SECRETS_PASSPHRASE`, or a machine-derived passphrase as last resort.\n * Switching strategies re-encrypts all existing secrets with the new key.\n *\n * @docLink packages/secrets/concepts#local-secrets-provider\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n// The narrow module, not the `core` barrel: the barrel's chunks use `import.meta`,\n// which CommonJS-transpiling consumers (ts-jest) cannot load.\nimport { globalSkaileDir } from \"../../../core/src/cache-paths.js\";\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport {\n ProviderUnavailableError,\n SecretNotFoundError,\n SecretsError,\n} from \"@skaile/workspaces/plugins\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nconst AUTH_TAG_LENGTH = 16;\nconst SALT_LENGTH = 32;\nconst KEY_LENGTH = 32;\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_DIGEST = \"sha512\";\n\nconst KEYCHAIN_SERVICE = \"skaile-secrets\";\nconst KEYCHAIN_ACCOUNT = \"master-key\";\n\n/** Env var that provides the passphrase at runtime (never stored on disk). */\nconst PASSPHRASE_ENV = \"SKAILE_SECRETS_PASSPHRASE\";\n\n/**\n * Master key derivation strategy used by {@link LocalSecretsProvider}.\n *\n * - `keychain` — OS keychain (via keytar); most secure, requires keytar to be installed.\n * - `passphrase` — PBKDF2 from `SKAILE_SECRETS_PASSPHRASE` env var; portable across machines.\n * - `machine` — deterministic from hostname + username; least secure, last-resort fallback.\n *\n * The active strategy is persisted in `~/.skaile/secrets/.key-strategy`. Switching strategies\n * re-encrypts all existing secrets with the new key.\n *\n * @docLink packages/secrets/concepts#local-secrets-provider\n */\nexport type KeyStrategy = \"keychain\" | \"passphrase\" | \"machine\";\n\n// ---------------------------------------------------------------------------\n// Key derivation\n// ---------------------------------------------------------------------------\n\nfunction deriveMasterKey(passphrase: string, salt: Buffer): Buffer {\n return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);\n}\n\nfunction getMachinePassphrase(): string {\n // Deterministic but not secret -- last resort only.\n return `skaile:${os.hostname()}:${os.userInfo().username}`;\n}\n\n/** Hash a passphrase for verification (stored in .master). */\nfunction hashPassphrase(passphrase: string): string {\n return crypto.createHash(\"sha256\").update(passphrase).digest(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Filename hashing (injective: sha256 of ref)\n// ---------------------------------------------------------------------------\n\nfunction refToHash(ref: string): string {\n return crypto.createHash(\"sha256\").update(ref).digest(\"hex\").slice(0, 40);\n}\n\n// ---------------------------------------------------------------------------\n// Encryption / decryption\n// ---------------------------------------------------------------------------\n\nfunction encrypt(data: Uint8Array, key: Buffer): Buffer {\n const iv = crypto.randomBytes(IV_LENGTH);\n const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n const authTag = cipher.getAuthTag();\n // Format: [iv (12)] [authTag (16)] [ciphertext (...)]\n return Buffer.concat([iv, authTag, encrypted]);\n}\n\nfunction decrypt(blob: Buffer, key: Buffer): Buffer {\n const iv = blob.subarray(0, IV_LENGTH);\n const authTag = blob.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);\n const ciphertext = blob.subarray(IV_LENGTH + AUTH_TAG_LENGTH);\n const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n decipher.setAuthTag(authTag);\n return Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport class LocalSecretsProvider implements ISecretsProvider {\n readonly id = \"local\";\n private secretsDir: string;\n private masterKey: Buffer | null = null;\n private salt: Buffer | null = null;\n private strategy: KeyStrategy = \"machine\";\n\n constructor(secretsDir?: string) {\n this.secretsDir = secretsDir ?? path.join(globalSkaileDir(), \"secrets\");\n }\n\n // -- Initialization --------------------------------------------------------\n\n private ensureDir(): void {\n if (!fs.existsSync(this.secretsDir)) {\n fs.mkdirSync(this.secretsDir, { recursive: true, mode: 0o700 });\n }\n }\n\n private loadOrCreateSalt(): Buffer {\n const saltPath = path.join(this.secretsDir, \".salt\");\n if (fs.existsSync(saltPath)) {\n return fs.readFileSync(saltPath);\n }\n const salt = crypto.randomBytes(SALT_LENGTH);\n fs.writeFileSync(saltPath, salt, { mode: 0o600 });\n return salt;\n }\n\n private async ensureKey(): Promise<void> {\n if (this.masterKey) return;\n\n this.ensureDir();\n this.salt = this.loadOrCreateSalt();\n\n // Determine strategy\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n if (fs.existsSync(strategyPath)) {\n this.strategy = fs.readFileSync(strategyPath, \"utf-8\").trim() as KeyStrategy;\n } else {\n // Auto-detect: try keychain, fall back to machine\n this.strategy = (await this.tryKeychainStrategy()) ? \"keychain\" : \"machine\";\n fs.writeFileSync(strategyPath, this.strategy, { mode: 0o600 });\n }\n\n // Derive key from strategy\n const passphrase = await this.getPassphraseForStrategy(this.strategy);\n this.masterKey = deriveMasterKey(passphrase, this.salt);\n }\n\n private async tryKeychainStrategy(): Promise<boolean> {\n try {\n // `keytar` is an optional OS-keychain native module the user installs\n // themselves; the `as string` specifier keeps it out of tsc resolution.\n const keytar = await import(\"keytar\" as string);\n let stored = await keytar.getPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);\n if (!stored) {\n stored = crypto.randomBytes(32).toString(\"base64\");\n await keytar.setPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, stored);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n private async getPassphraseForStrategy(strategy: KeyStrategy): Promise<string> {\n switch (strategy) {\n case \"keychain\": {\n try {\n // `keytar` is an optional OS-keychain native module the user installs\n // themselves; the `as string` specifier keeps it out of tsc resolution.\n const keytar = await import(\"keytar\" as string);\n const stored = await keytar.getPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);\n if (stored) return stored;\n } catch {\n // Keychain failed; fall through to machine\n }\n return getMachinePassphrase();\n }\n case \"passphrase\": {\n const envPassphrase = process.env[PASSPHRASE_ENV];\n if (envPassphrase) {\n // Verify against stored hash if it exists\n const masterPath = path.join(this.secretsDir, \".master\");\n if (fs.existsSync(masterPath)) {\n const storedHash = fs.readFileSync(masterPath, \"utf-8\").trim();\n if (hashPassphrase(envPassphrase) !== storedHash) {\n throw new SecretsError(\n `Passphrase from ${PASSPHRASE_ENV} does not match stored hash. ` +\n \"Use skaile auth set-key-strategy passphrase to reset.\",\n \"PASSPHRASE_MISMATCH\",\n );\n }\n }\n return envPassphrase;\n }\n // No env var -- hard error. Silent fallback to machine would\n // produce a different key, causing AES-GCM auth-tag failures\n // on secrets encrypted with the real passphrase.\n throw new SecretsError(\n `Strategy is \"passphrase\" but ${PASSPHRASE_ENV} is not set. ` +\n `Export it before running: export ${PASSPHRASE_ENV}='...'`,\n \"PASSPHRASE_REQUIRED\",\n );\n }\n case \"machine\":\n return getMachinePassphrase();\n default:\n return getMachinePassphrase();\n }\n }\n\n // -- Strategy management ---------------------------------------------------\n\n /**\n * Set the key strategy explicitly. Called by `skaile auth set-key-strategy`.\n *\n * When existing secrets are present, they are re-encrypted with the new key\n * to prevent data loss from key mismatch.\n */\n async setKeyStrategy(strategy: KeyStrategy, passphrase?: string): Promise<void> {\n this.ensureDir();\n\n // --- 1. Validate new strategy prerequisites -------------------------\n\n const effectivePassphrase = passphrase ?? process.env[PASSPHRASE_ENV];\n\n if (strategy === \"passphrase\") {\n if (!effectivePassphrase) {\n throw new SecretsError(\n `Passphrase required. Pass it as an argument or set ${PASSPHRASE_ENV}.`,\n \"PASSPHRASE_REQUIRED\",\n );\n }\n }\n\n if (strategy === \"keychain\") {\n const success = await this.tryKeychainStrategy();\n if (!success) {\n throw new ProviderUnavailableError(\"local\", \"OS keychain not available\");\n }\n }\n\n // --- 2. Load the OLD key under the current strategy -----------------\n // ensureKey() reads the current strategy file and derives the key\n // that was used to encrypt existing secrets. This is critical for\n // cross-process scenarios where masterKey starts as null.\n\n const encFiles = this.listEncFiles();\n if (encFiles.length > 0) {\n await this.ensureKey();\n const oldKey = this.masterKey!;\n\n // Derive the new key\n const salt = this.salt!;\n const newPassphrase =\n strategy === \"passphrase\"\n ? effectivePassphrase!\n : strategy === \"keychain\"\n ? await this.getPassphraseForStrategy(\"keychain\")\n : getMachinePassphrase();\n const newKey = deriveMasterKey(newPassphrase, salt);\n\n // Re-encrypt each secret with the new key. A single failure must abort the\n // whole switch: committing the new strategy while a secret is still under\n // the old key orphans that secret (the registry advertises a key that no\n // longer decrypts it). Collect failures and throw before the commit below,\n // leaving `.key-strategy`/`.master` — and every secret — on the old key.\n const failed: string[] = [];\n for (const encFile of encFiles) {\n const filePath = path.join(this.secretsDir, encFile);\n const blob = fs.readFileSync(filePath);\n try {\n const plaintext = decrypt(blob, oldKey);\n const reEncrypted = encrypt(plaintext, newKey);\n fs.writeFileSync(filePath, reEncrypted, { mode: 0o600 });\n } catch {\n failed.push(encFile);\n }\n }\n if (failed.length > 0) {\n throw new Error(\n `[skaile/secrets] Key-strategy switch aborted: could not re-encrypt ` +\n `${failed.length} secret(s) (${failed.join(\", \")}). The previous strategy ` +\n \"is unchanged; resolve the failing secrets before retrying.\",\n );\n }\n }\n\n // --- 3. Commit the new strategy (last write -- failure above leaves\n // the old strategy intact) ------------------------------------\n\n if (strategy === \"passphrase\") {\n const masterPath = path.join(this.secretsDir, \".master\");\n fs.writeFileSync(masterPath, hashPassphrase(effectivePassphrase!), { mode: 0o600 });\n }\n\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n fs.writeFileSync(strategyPath, strategy, { mode: 0o600 });\n this.masterKey = null;\n this.strategy = strategy;\n }\n\n getKeyStrategy(): KeyStrategy {\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n if (fs.existsSync(strategyPath)) {\n return fs.readFileSync(strategyPath, \"utf-8\").trim() as KeyStrategy;\n }\n return \"machine\";\n }\n\n // -- File helpers ----------------------------------------------------------\n\n private encFilename(ref: string): string {\n return `${refToHash(ref)}.enc`;\n }\n\n private metaFilename(ref: string): string {\n return `${refToHash(ref)}.meta.json`;\n }\n\n private metaPath(ref: string): string {\n return path.join(this.secretsDir, this.metaFilename(ref));\n }\n\n private listEncFiles(): string[] {\n if (!fs.existsSync(this.secretsDir)) return [];\n return fs.readdirSync(this.secretsDir).filter((f) => f.endsWith(\".enc\"));\n }\n\n // -- ISecretsProvider implementation ----------------------------------------\n\n async getSecret(ref: string): Promise<Uint8Array> {\n await this.ensureKey();\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n const blob = fs.readFileSync(filePath);\n const decrypted = decrypt(blob, this.masterKey!);\n\n // Update lastAccessedAt\n const metaFile = this.metaPath(ref);\n if (fs.existsSync(metaFile)) {\n try {\n const meta = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n meta.lastAccessedAt = new Date().toISOString();\n fs.writeFileSync(metaFile, JSON.stringify(meta), { mode: 0o600 });\n } catch {\n // Non-fatal\n }\n }\n\n return new Uint8Array(decrypted);\n }\n\n async setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void> {\n await this.ensureKey();\n this.ensureDir();\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n const encrypted = encrypt(value, this.masterKey!);\n fs.writeFileSync(filePath, encrypted, { mode: 0o600 });\n\n // Write metadata (stores the original ref for reverse lookup)\n const now = new Date().toISOString();\n const metaFile = this.metaPath(ref);\n let existing: Record<string, unknown> = {};\n if (fs.existsSync(metaFile)) {\n try {\n existing = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n } catch {\n // Overwrite corrupt meta\n }\n }\n const meta = {\n ref,\n createdAt: existing.createdAt ?? now,\n updatedAt: now,\n lastAccessedAt: now,\n ...(opts?.metadata ? { userMeta: opts.metadata } : {}),\n ...(opts?.ttlSeconds\n ? { expiresAt: new Date(Date.now() + opts.ttlSeconds * 1000).toISOString() }\n : {}),\n };\n fs.writeFileSync(metaFile, JSON.stringify(meta, null, 2), { mode: 0o600 });\n }\n\n async deleteSecret(ref: string): Promise<void> {\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n const metaFile = this.metaPath(ref);\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n fs.unlinkSync(filePath);\n if (fs.existsSync(metaFile)) {\n fs.unlinkSync(metaFile);\n }\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n this.ensureDir();\n // Read refs from meta files (the .enc filenames are hashes, not refs)\n const metaFiles = fs.readdirSync(this.secretsDir).filter((f) => f.endsWith(\".meta.json\"));\n let refs: string[] = [];\n for (const mf of metaFiles) {\n try {\n const meta = JSON.parse(fs.readFileSync(path.join(this.secretsDir, mf), \"utf-8\"));\n if (meta.ref) refs.push(meta.ref);\n } catch {\n // Skip corrupt meta files\n }\n }\n if (filter?.prefix) {\n refs = refs.filter((r) => r.startsWith(filter.prefix!));\n }\n if (filter?.limit) {\n refs = refs.slice(0, filter.limit);\n }\n return refs;\n }\n\n async testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n const start = Date.now();\n try {\n await this.ensureKey();\n // Write + read + delete a test secret\n const testRef = `__test_${crypto.randomBytes(4).toString(\"hex\")}`;\n const testValue = new TextEncoder().encode(\"test\");\n await this.setSecret(testRef, testValue);\n const read = await this.getSecret(testRef);\n await this.deleteSecret(testRef);\n if (new TextDecoder().decode(read) !== \"test\") {\n return { ok: false, error: \"Round-trip mismatch\" };\n }\n return { ok: true, latencyMs: Date.now() - start };\n } catch (e) {\n return {\n ok: false,\n latencyMs: Date.now() - start,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const metaFile = this.metaPath(ref);\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n if (fs.existsSync(metaFile)) {\n const raw = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n return {\n ref: raw.ref ?? ref,\n createdAt: new Date(raw.createdAt),\n updatedAt: new Date(raw.updatedAt),\n lastAccessedAt: raw.lastAccessedAt ? new Date(raw.lastAccessedAt) : undefined,\n owner: raw.owner,\n scopeSummary: \"local encrypted file\",\n };\n }\n // Fallback: derive from file stat\n const stat = fs.statSync(filePath);\n return {\n ref,\n createdAt: stat.birthtime,\n updatedAt: stat.mtime,\n scopeSummary: \"local encrypted file\",\n };\n }\n\n getCapabilities(): ProviderCapabilities {\n return {\n supportsRotation: false,\n supportsExpiry: false,\n supportsBatch: false,\n scopeModel: \"flat\",\n };\n }\n}\n","/**\n * SecretsRouter — audit chokepoint for all secret operations.\n *\n * Registers {@link ISecretsProvider} implementations by id, routes credential refs by\n * prefix or via routing config, and emits {@link CredentialAccessed} events for every\n * get, set, delete, list, and metadata operation. Routing rules are evaluated top-to-bottom;\n * the first matching prefix wins and falls back to the configured default provider.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\n\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport { ProviderUnavailableError } from \"@skaile/workspaces/plugins\";\n\n// ---------------------------------------------------------------------------\n// Audit event\n// ---------------------------------------------------------------------------\n\n/**\n * Audit event emitted by {@link SecretsRouter} after every secret operation.\n *\n * Delivered synchronously to all registered {@link AuditSink} functions. Errors thrown\n * by sinks are swallowed to ensure they never break the underlying secret operation.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface CredentialAccessed {\n credential_ref: string;\n operation: \"get\" | \"set\" | \"delete\" | \"list\" | \"metadata\";\n provider_id: string;\n caller_session_id?: string;\n caller_tool_call?: string;\n timestamp: Date;\n}\n\n/**\n * Callback function that receives {@link CredentialAccessed} audit events from {@link SecretsRouter}.\n *\n * Register sinks via `SecretsRouter.addSink()`. Sinks run synchronously after each operation;\n * exceptions are caught and suppressed so they cannot interrupt credential resolution.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport type AuditSink = (event: CredentialAccessed) => void;\n\n// ---------------------------------------------------------------------------\n// Routing config\n// ---------------------------------------------------------------------------\n\n/**\n * A single routing rule that maps a credential ref prefix to a provider.\n *\n * Rules in {@link SecretsRouterConfig.rules} are evaluated top-to-bottom;\n * the first rule whose `prefix` matches the start of the credential ref wins.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface RoutingRule {\n /** Prefix match on credential_ref. First match wins. */\n prefix: string;\n /** Provider id to route to. */\n provider_id: string;\n}\n\n/**\n * Configuration object for {@link SecretsRouter}.\n *\n * Specifies the default provider id used when no routing rule matches, and an optional\n * ordered list of {@link RoutingRule} entries for prefix-based routing.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface SecretsRouterConfig {\n /** Default provider id when no routing rule matches. */\n default_provider: string;\n /** Ordered routing rules. Evaluated top-to-bottom; first prefix match wins. */\n rules?: RoutingRule[];\n}\n\n// ---------------------------------------------------------------------------\n// Router\n// ---------------------------------------------------------------------------\n\nexport class SecretsRouter {\n private providers = new Map<string, ISecretsProvider>();\n private config: SecretsRouterConfig;\n private sinks: AuditSink[] = [];\n\n /** Caller context for audit events (set per-request by the runner). */\n callerSessionId?: string;\n callerToolCall?: string;\n\n constructor(config: SecretsRouterConfig) {\n this.config = config;\n }\n\n // -- Provider registration ------------------------------------------------\n\n register(provider: ISecretsProvider): void {\n this.providers.set(provider.id, provider);\n }\n\n unregister(id: string): void {\n this.providers.delete(id);\n }\n\n listProviders(): string[] {\n return [...this.providers.keys()];\n }\n\n // -- Audit sinks -----------------------------------------------------------\n\n addSink(sink: AuditSink): void {\n this.sinks.push(sink);\n }\n\n private emit(ref: string, operation: CredentialAccessed[\"operation\"], providerId: string): void {\n const event: CredentialAccessed = {\n credential_ref: ref,\n operation,\n provider_id: providerId,\n caller_session_id: this.callerSessionId,\n caller_tool_call: this.callerToolCall,\n timestamp: new Date(),\n };\n for (const sink of this.sinks) {\n try {\n sink(event);\n } catch {\n // Audit sink errors must not break the secret operation.\n }\n }\n }\n\n // -- Routing ---------------------------------------------------------------\n\n private resolve(ref: string): ISecretsProvider {\n // Check routing rules first\n if (this.config.rules) {\n for (const rule of this.config.rules) {\n if (ref.startsWith(rule.prefix)) {\n const provider = this.providers.get(rule.provider_id);\n if (provider) return provider;\n }\n }\n }\n\n // Fall back to default\n const provider = this.providers.get(this.config.default_provider);\n if (!provider) {\n throw new ProviderUnavailableError(\n this.config.default_provider,\n `No provider registered for default id \"${this.config.default_provider}\"`,\n );\n }\n return provider;\n }\n\n // -- Delegated operations --------------------------------------------------\n\n async getSecret(ref: string): Promise<Uint8Array> {\n const provider = this.resolve(ref);\n this.emit(ref, \"get\", provider.id);\n return provider.getSecret(ref);\n }\n\n async setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void> {\n const provider = this.resolve(ref);\n this.emit(ref, \"set\", provider.id);\n return provider.setSecret(ref, value, opts);\n }\n\n async deleteSecret(ref: string): Promise<void> {\n const provider = this.resolve(ref);\n this.emit(ref, \"delete\", provider.id);\n return provider.deleteSecret(ref);\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n // List aggregates from the default provider only (per-provider listing\n // would require iterating all providers; deferred to Phase 3 with\n // federated catalogs).\n const provider = this.providers.get(this.config.default_provider);\n if (!provider) return [];\n this.emit(\"*\", \"list\", provider.id);\n return provider.listSecrets(filter);\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const provider = this.resolve(ref);\n this.emit(ref, \"metadata\", provider.id);\n return provider.getMetadata(ref);\n }\n\n getCapabilities(providerId?: string): ProviderCapabilities | null {\n const id = providerId ?? this.config.default_provider;\n const provider = this.providers.get(id);\n return provider?.getCapabilities() ?? null;\n }\n\n async testConnection(\n providerId?: string,\n ): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n const id = providerId ?? this.config.default_provider;\n const provider = this.providers.get(id);\n if (!provider) {\n return { ok: false, error: `Provider \"${id}\" not registered` };\n }\n return provider.testConnection();\n }\n}\n","/** Package version of `@skaile/secrets`. */\nexport const VERSION = \"0.0.0\";\n\n// Re-export interface + errors from plugins (convenience for consumers)\nexport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nexport {\n ProviderUnavailableError,\n SecretAccessDeniedError,\n SecretExpiredError,\n SecretNotFoundError,\n SecretsError,\n} from \"@skaile/workspaces/plugins\";\nexport type { CredentialLifecycleConfig, RefreshResult } from \"./lifecycle.js\";\n// Lifecycle\nexport { CredentialLifecycleService } from \"./lifecycle.js\";\nexport { EnvSecretsProvider } from \"./providers/env.js\";\nexport type { KeyStrategy } from \"./providers/local.js\";\n// Built-in providers\nexport { LocalSecretsProvider } from \"./providers/local.js\";\nexport type { AuditSink, CredentialAccessed, RoutingRule, SecretsRouterConfig } from \"./router.js\";\n// Router\nexport { SecretsRouter } from \"./router.js\";\n"]}
1
+ {"version":3,"sources":["../secrets/src/lifecycle.ts","../secrets/src/providers/env.ts","../secrets/src/providers/local.ts","../secrets/src/router.ts","../secrets/src/index.ts"],"names":["provider"],"mappings":";;;;;;;;AAuCO,IAAM,6BAAN,MAAiC;AAAA,EAC9B,MAAA;AAAA;AAAA;AAAA;AAAA,EAKR,WAAA,CAAY,QAAuB,OAAA,EAA8C;AAC/E,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,gBAAgB,aAAA,EAA+C;AAGnE,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA;AAC3C,MAAA,OAAO,EAAE,SAAA,EAAW,KAAA,EAAO,MAAA,EAAQ,gBAAA,EAAiB;AAAA,IACtD,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,EAAE,SAAA,EAAW,KAAA,EAAO,MAAA,EAAQ,gBAAA,EAAkB,OAAO,sBAAA,EAAuB;AAAA,IACrF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,QAAQ,aAAA,EAAyC;AACrD,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,MAAA,CAAO,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,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AACjC,IAAA,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,UAAA,EAAY,QAAA,CAAS,EAAE,CAAA;AACtC,IAAA,OAAO,QAAA,CAAS,YAAY,GAAG,CAAA;AAAA,EACjC;AAAA,EAEA,gBAAgB,UAAA,EAAkD;AAChE,IAAA,MAAM,EAAA,GAAK,UAAA,IAAc,IAAA,CAAK,MAAA,CAAO,gBAAA;AACrC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,EAAE,CAAA;AACtC,IAAA,OAAO,QAAA,EAAU,iBAAgB,IAAK,IAAA;AAAA,EACxC;AAAA,EAEA,MAAM,eACJ,UAAA,EAC8D;AAC9D,IAAA,MAAM,EAAA,GAAK,UAAA,IAAc,IAAA,CAAK,MAAA,CAAO,gBAAA;AACrC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,EAAE,CAAA;AACtC,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,UAAA,EAAa,EAAE,CAAA,gBAAA,CAAA,EAAmB;AAAA,IAC/D;AACA,IAAA,OAAO,SAAS,cAAA,EAAe;AAAA,EACjC;AACF;;;ACvNO,IAAM,OAAA,GAAU","file":"chunk-EB6OPURC.js","sourcesContent":["/**\n * CredentialLifecycleService — manages OAuth token refresh outside the SecretsRouter.\n *\n * Works with opaque token blobs stored via the {@link SecretsRouter}; providers remain\n * OAuth-unaware. Phase 1 ships non-OAuth paths (always returns `not_applicable`).\n * Full proactive OAuth refresh with expiry checking ships in Phase 3.4.\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\n\nimport type { SecretsRouter } from \"./router.js\";\n\n/**\n * Configuration for {@link CredentialLifecycleService}.\n *\n * Controls how aggressively the service proactively refreshes credentials before they expire.\n * The default lead time is 300 seconds (5 minutes).\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\nexport interface CredentialLifecycleConfig {\n /** How far before expiry to trigger a proactive refresh (seconds). */\n refreshLeadTimeSec: number;\n}\n\n/**\n * Result returned by {@link CredentialLifecycleService.refreshIfNeeded}.\n *\n * The `reason` discriminant indicates why a refresh did or did not occur.\n * An `error` string is present only when `reason` is `refresh_failed`.\n *\n * @docLink packages/secrets/concepts#credential-lifecycle\n */\nexport interface RefreshResult {\n refreshed: boolean;\n reason: \"not_applicable\" | \"still_valid\" | \"refreshed\" | \"refresh_failed\";\n error?: string;\n}\n\nexport class CredentialLifecycleService {\n private router: SecretsRouter;\n\n // `_config` is accepted for signature stability but not stored yet: Phase 1\n // ships no OAuth refresh, so there is nothing to configure. Phase 3.4 will\n // store and read `refreshLeadTimeSec` when proactive refresh lands.\n constructor(router: SecretsRouter, _config?: Partial<CredentialLifecycleConfig>) {\n this.router = router;\n }\n\n /**\n * Attempt to refresh a credential if needed.\n * Phase 1: always returns not_applicable (no OAuth support yet).\n */\n async refreshIfNeeded(credentialRef: string): Promise<RefreshResult> {\n // Phase 1: no OAuth refresh implemented.\n // The credential exists and is valid as-is (static secrets, env vars, etc.)\n try {\n await this.router.getMetadata(credentialRef);\n return { refreshed: false, reason: \"not_applicable\" };\n } catch {\n return { refreshed: false, reason: \"refresh_failed\", error: \"Credential not found\" };\n }\n }\n\n /**\n * Check if a credential is still valid (not expired).\n * Phase 1: always returns true for non-OAuth credentials.\n */\n async isValid(credentialRef: string): Promise<boolean> {\n try {\n await this.router.getSecret(credentialRef);\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * EnvSecretsProvider — read-only provider that resolves secrets from environment variables.\n *\n * Refs are expected to be plain env var names (e.g. `DATABASE_URL`). The provider is\n * always available with zero configuration and requires no encryption or keychain access.\n * `setSecret` and `deleteSecret` always throw `SecretAccessDeniedError` because\n * environment variables are managed externally to the running process.\n *\n * @docLink packages/secrets/concepts#env-secrets-provider\n */\n\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport { SecretAccessDeniedError, SecretNotFoundError } from \"@skaile/workspaces/plugins\";\n\n/**\n * Sentinel timestamp for env secrets, which have no real created/updated time.\n * The Unix epoch is unambiguously not \"now\", so consumers can recognise it as\n * \"unknown\" rather than treating it as a genuine recent timestamp.\n */\nconst ENV_UNKNOWN_TIMESTAMP = new Date(0);\n\nexport class EnvSecretsProvider implements ISecretsProvider {\n readonly id = \"env\";\n\n async getSecret(ref: string): Promise<Uint8Array> {\n const value = process.env[ref];\n if (value === undefined) {\n throw new SecretNotFoundError(ref);\n }\n return new TextEncoder().encode(value);\n }\n\n async setSecret(_ref: string, _value: Uint8Array, _opts?: SetSecretOptions): Promise<void> {\n throw new SecretAccessDeniedError(\"EnvSecretsProvider is read-only\");\n }\n\n async deleteSecret(_ref: string): Promise<void> {\n throw new SecretAccessDeniedError(\"EnvSecretsProvider is read-only\");\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n let keys = Object.keys(process.env);\n if (filter?.prefix) {\n keys = keys.filter((k) => k.startsWith(filter.prefix!));\n }\n if (filter?.limit) {\n keys = keys.slice(0, filter.limit);\n }\n return keys;\n }\n\n async testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n return { ok: true, latencyMs: 0 };\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const value = process.env[ref];\n if (value === undefined) {\n throw new SecretNotFoundError(ref);\n }\n // Env vars carry no creation/modification time. `SecretMetadata` requires\n // both fields, so use the Unix epoch as a documented \"unknown\" sentinel\n // rather than `new Date()`, which would falsely imply the secret was just\n // created/updated. The read-only scope summary already signals the source.\n return {\n ref,\n createdAt: ENV_UNKNOWN_TIMESTAMP,\n updatedAt: ENV_UNKNOWN_TIMESTAMP,\n scopeSummary: \"environment variable (read-only)\",\n };\n }\n\n getCapabilities(): ProviderCapabilities {\n return {\n supportsRotation: false,\n supportsExpiry: false,\n supportsBatch: false,\n scopeModel: \"flat\",\n };\n }\n}\n","/**\n * LocalSecretsProvider — AES-256-GCM encrypted file-blob storage at `~/.skaile/secrets/`.\n *\n * Each secret is stored as a separate `.enc` file named by the SHA-256 hash of the ref\n * (collision-free, filesystem-safe). A companion `.meta.json` stores the original ref,\n * timestamps, and optional user metadata. The master key is derived via PBKDF2-SHA-512\n * from one of three {@link KeyStrategy} sources: OS keychain (keytar), a passphrase from\n * `SKAILE_SECRETS_PASSPHRASE`, or a machine-derived passphrase as last resort.\n * Switching strategies re-encrypts all existing secrets with the new key.\n *\n * @docLink packages/secrets/concepts#local-secrets-provider\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n// The narrow module, not the `core` barrel: the barrel's chunks use `import.meta`,\n// which CommonJS-transpiling consumers (ts-jest) cannot load.\nimport { globalSkaileDir } from \"../../../core/src/cache-paths.js\";\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport {\n ProviderUnavailableError,\n SecretNotFoundError,\n SecretsError,\n} from \"@skaile/workspaces/plugins\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nconst AUTH_TAG_LENGTH = 16;\nconst SALT_LENGTH = 32;\nconst KEY_LENGTH = 32;\nconst PBKDF2_ITERATIONS = 100_000;\nconst PBKDF2_DIGEST = \"sha512\";\n\nconst KEYCHAIN_SERVICE = \"skaile-secrets\";\nconst KEYCHAIN_ACCOUNT = \"master-key\";\n\n/** Env var that provides the passphrase at runtime (never stored on disk). */\nconst PASSPHRASE_ENV = \"SKAILE_SECRETS_PASSPHRASE\";\n\n/**\n * Master key derivation strategy used by {@link LocalSecretsProvider}.\n *\n * - `keychain` — OS keychain (via keytar); most secure, requires keytar to be installed.\n * - `passphrase` — PBKDF2 from `SKAILE_SECRETS_PASSPHRASE` env var; portable across machines.\n * - `machine` — deterministic from hostname + username; least secure, last-resort fallback.\n *\n * The active strategy is persisted in `~/.skaile/secrets/.key-strategy`. Switching strategies\n * re-encrypts all existing secrets with the new key.\n *\n * @docLink packages/secrets/concepts#local-secrets-provider\n */\nexport type KeyStrategy = \"keychain\" | \"passphrase\" | \"machine\";\n\n// ---------------------------------------------------------------------------\n// Key derivation\n// ---------------------------------------------------------------------------\n\nfunction deriveMasterKey(passphrase: string, salt: Buffer): Buffer {\n return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);\n}\n\nfunction getMachinePassphrase(): string {\n // Deterministic but not secret -- last resort only.\n return `skaile:${os.hostname()}:${os.userInfo().username}`;\n}\n\n/** Hash a passphrase for verification (stored in .master). */\nfunction hashPassphrase(passphrase: string): string {\n return crypto.createHash(\"sha256\").update(passphrase).digest(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Filename hashing (injective: sha256 of ref)\n// ---------------------------------------------------------------------------\n\nfunction refToHash(ref: string): string {\n return crypto.createHash(\"sha256\").update(ref).digest(\"hex\").slice(0, 40);\n}\n\n// ---------------------------------------------------------------------------\n// Encryption / decryption\n// ---------------------------------------------------------------------------\n\nfunction encrypt(data: Uint8Array, key: Buffer): Buffer {\n const iv = crypto.randomBytes(IV_LENGTH);\n const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n const authTag = cipher.getAuthTag();\n // Format: [iv (12)] [authTag (16)] [ciphertext (...)]\n return Buffer.concat([iv, authTag, encrypted]);\n}\n\nfunction decrypt(blob: Buffer, key: Buffer): Buffer {\n const iv = blob.subarray(0, IV_LENGTH);\n const authTag = blob.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);\n const ciphertext = blob.subarray(IV_LENGTH + AUTH_TAG_LENGTH);\n const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n decipher.setAuthTag(authTag);\n return Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport class LocalSecretsProvider implements ISecretsProvider {\n readonly id = \"local\";\n private secretsDir: string;\n private masterKey: Buffer | null = null;\n private salt: Buffer | null = null;\n private strategy: KeyStrategy = \"machine\";\n\n constructor(secretsDir?: string) {\n this.secretsDir = secretsDir ?? path.join(globalSkaileDir(), \"secrets\");\n }\n\n // -- Initialization --------------------------------------------------------\n\n private ensureDir(): void {\n if (!fs.existsSync(this.secretsDir)) {\n fs.mkdirSync(this.secretsDir, { recursive: true, mode: 0o700 });\n }\n }\n\n private loadOrCreateSalt(): Buffer {\n const saltPath = path.join(this.secretsDir, \".salt\");\n if (fs.existsSync(saltPath)) {\n return fs.readFileSync(saltPath);\n }\n const salt = crypto.randomBytes(SALT_LENGTH);\n fs.writeFileSync(saltPath, salt, { mode: 0o600 });\n return salt;\n }\n\n private async ensureKey(): Promise<void> {\n if (this.masterKey) return;\n\n this.ensureDir();\n this.salt = this.loadOrCreateSalt();\n\n // Determine strategy\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n if (fs.existsSync(strategyPath)) {\n this.strategy = fs.readFileSync(strategyPath, \"utf-8\").trim() as KeyStrategy;\n } else {\n // Auto-detect: try keychain, fall back to machine\n this.strategy = (await this.tryKeychainStrategy()) ? \"keychain\" : \"machine\";\n fs.writeFileSync(strategyPath, this.strategy, { mode: 0o600 });\n }\n\n // Derive key from strategy\n const passphrase = await this.getPassphraseForStrategy(this.strategy);\n this.masterKey = deriveMasterKey(passphrase, this.salt);\n }\n\n private async tryKeychainStrategy(): Promise<boolean> {\n try {\n // `keytar` is an optional OS-keychain native module the user installs\n // themselves; the `as string` specifier keeps it out of tsc resolution.\n const keytar = await import(\"keytar\" as string);\n let stored = await keytar.getPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);\n if (!stored) {\n stored = crypto.randomBytes(32).toString(\"base64\");\n await keytar.setPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, stored);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n private async getPassphraseForStrategy(strategy: KeyStrategy): Promise<string> {\n switch (strategy) {\n case \"keychain\": {\n try {\n // `keytar` is an optional OS-keychain native module the user installs\n // themselves; the `as string` specifier keeps it out of tsc resolution.\n const keytar = await import(\"keytar\" as string);\n const stored = await keytar.getPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);\n if (stored) return stored;\n } catch {\n // Keychain failed; fall through to machine\n }\n return getMachinePassphrase();\n }\n case \"passphrase\": {\n const envPassphrase = process.env[PASSPHRASE_ENV];\n if (envPassphrase) {\n // Verify against stored hash if it exists\n const masterPath = path.join(this.secretsDir, \".master\");\n if (fs.existsSync(masterPath)) {\n const storedHash = fs.readFileSync(masterPath, \"utf-8\").trim();\n if (hashPassphrase(envPassphrase) !== storedHash) {\n throw new SecretsError(\n `Passphrase from ${PASSPHRASE_ENV} does not match stored hash. ` +\n \"Use skaile auth set-key-strategy passphrase to reset.\",\n \"PASSPHRASE_MISMATCH\",\n );\n }\n }\n return envPassphrase;\n }\n // No env var -- hard error. Silent fallback to machine would\n // produce a different key, causing AES-GCM auth-tag failures\n // on secrets encrypted with the real passphrase.\n throw new SecretsError(\n `Strategy is \"passphrase\" but ${PASSPHRASE_ENV} is not set. ` +\n `Export it before running: export ${PASSPHRASE_ENV}='...'`,\n \"PASSPHRASE_REQUIRED\",\n );\n }\n case \"machine\":\n return getMachinePassphrase();\n default:\n return getMachinePassphrase();\n }\n }\n\n // -- Strategy management ---------------------------------------------------\n\n /**\n * Set the key strategy explicitly. Called by `skaile auth set-key-strategy`.\n *\n * When existing secrets are present, they are re-encrypted with the new key\n * to prevent data loss from key mismatch.\n */\n async setKeyStrategy(strategy: KeyStrategy, passphrase?: string): Promise<void> {\n this.ensureDir();\n\n // --- 1. Validate new strategy prerequisites -------------------------\n\n const effectivePassphrase = passphrase ?? process.env[PASSPHRASE_ENV];\n\n if (strategy === \"passphrase\") {\n if (!effectivePassphrase) {\n throw new SecretsError(\n `Passphrase required. Pass it as an argument or set ${PASSPHRASE_ENV}.`,\n \"PASSPHRASE_REQUIRED\",\n );\n }\n }\n\n if (strategy === \"keychain\") {\n const success = await this.tryKeychainStrategy();\n if (!success) {\n throw new ProviderUnavailableError(\"local\", \"OS keychain not available\");\n }\n }\n\n // --- 2. Load the OLD key under the current strategy -----------------\n // ensureKey() reads the current strategy file and derives the key\n // that was used to encrypt existing secrets. This is critical for\n // cross-process scenarios where masterKey starts as null.\n\n const encFiles = this.listEncFiles();\n if (encFiles.length > 0) {\n await this.ensureKey();\n const oldKey = this.masterKey!;\n\n // Derive the new key\n const salt = this.salt!;\n const newPassphrase =\n strategy === \"passphrase\"\n ? effectivePassphrase!\n : strategy === \"keychain\"\n ? await this.getPassphraseForStrategy(\"keychain\")\n : getMachinePassphrase();\n const newKey = deriveMasterKey(newPassphrase, salt);\n\n // Re-encrypt each secret with the new key. A single failure must abort the\n // whole switch: committing the new strategy while a secret is still under\n // the old key orphans that secret (the registry advertises a key that no\n // longer decrypts it). Collect failures and throw before the commit below,\n // leaving `.key-strategy`/`.master` — and every secret — on the old key.\n const failed: string[] = [];\n for (const encFile of encFiles) {\n const filePath = path.join(this.secretsDir, encFile);\n const blob = fs.readFileSync(filePath);\n try {\n const plaintext = decrypt(blob, oldKey);\n const reEncrypted = encrypt(plaintext, newKey);\n fs.writeFileSync(filePath, reEncrypted, { mode: 0o600 });\n } catch {\n failed.push(encFile);\n }\n }\n if (failed.length > 0) {\n throw new Error(\n `[skaile/secrets] Key-strategy switch aborted: could not re-encrypt ` +\n `${failed.length} secret(s) (${failed.join(\", \")}). The previous strategy ` +\n \"is unchanged; resolve the failing secrets before retrying.\",\n );\n }\n }\n\n // --- 3. Commit the new strategy (last write -- failure above leaves\n // the old strategy intact) ------------------------------------\n\n if (strategy === \"passphrase\") {\n const masterPath = path.join(this.secretsDir, \".master\");\n fs.writeFileSync(masterPath, hashPassphrase(effectivePassphrase!), { mode: 0o600 });\n }\n\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n fs.writeFileSync(strategyPath, strategy, { mode: 0o600 });\n this.masterKey = null;\n this.strategy = strategy;\n }\n\n getKeyStrategy(): KeyStrategy {\n const strategyPath = path.join(this.secretsDir, \".key-strategy\");\n if (fs.existsSync(strategyPath)) {\n return fs.readFileSync(strategyPath, \"utf-8\").trim() as KeyStrategy;\n }\n return \"machine\";\n }\n\n // -- File helpers ----------------------------------------------------------\n\n private encFilename(ref: string): string {\n return `${refToHash(ref)}.enc`;\n }\n\n private metaFilename(ref: string): string {\n return `${refToHash(ref)}.meta.json`;\n }\n\n private metaPath(ref: string): string {\n return path.join(this.secretsDir, this.metaFilename(ref));\n }\n\n private listEncFiles(): string[] {\n if (!fs.existsSync(this.secretsDir)) return [];\n return fs.readdirSync(this.secretsDir).filter((f) => f.endsWith(\".enc\"));\n }\n\n // -- ISecretsProvider implementation ----------------------------------------\n\n async getSecret(ref: string): Promise<Uint8Array> {\n await this.ensureKey();\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n const blob = fs.readFileSync(filePath);\n const decrypted = decrypt(blob, this.masterKey!);\n\n // Update lastAccessedAt\n const metaFile = this.metaPath(ref);\n if (fs.existsSync(metaFile)) {\n try {\n const meta = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n meta.lastAccessedAt = new Date().toISOString();\n fs.writeFileSync(metaFile, JSON.stringify(meta), { mode: 0o600 });\n } catch {\n // Non-fatal\n }\n }\n\n return new Uint8Array(decrypted);\n }\n\n async setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void> {\n await this.ensureKey();\n this.ensureDir();\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n const encrypted = encrypt(value, this.masterKey!);\n fs.writeFileSync(filePath, encrypted, { mode: 0o600 });\n\n // Write metadata (stores the original ref for reverse lookup)\n const now = new Date().toISOString();\n const metaFile = this.metaPath(ref);\n let existing: Record<string, unknown> = {};\n if (fs.existsSync(metaFile)) {\n try {\n existing = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n } catch {\n // Overwrite corrupt meta\n }\n }\n const meta = {\n ref,\n createdAt: existing.createdAt ?? now,\n updatedAt: now,\n lastAccessedAt: now,\n ...(opts?.metadata ? { userMeta: opts.metadata } : {}),\n ...(opts?.ttlSeconds\n ? { expiresAt: new Date(Date.now() + opts.ttlSeconds * 1000).toISOString() }\n : {}),\n };\n fs.writeFileSync(metaFile, JSON.stringify(meta, null, 2), { mode: 0o600 });\n }\n\n async deleteSecret(ref: string): Promise<void> {\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n const metaFile = this.metaPath(ref);\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n fs.unlinkSync(filePath);\n if (fs.existsSync(metaFile)) {\n fs.unlinkSync(metaFile);\n }\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n this.ensureDir();\n // Read refs from meta files (the .enc filenames are hashes, not refs)\n const metaFiles = fs.readdirSync(this.secretsDir).filter((f) => f.endsWith(\".meta.json\"));\n let refs: string[] = [];\n for (const mf of metaFiles) {\n try {\n const meta = JSON.parse(fs.readFileSync(path.join(this.secretsDir, mf), \"utf-8\"));\n if (meta.ref) refs.push(meta.ref);\n } catch {\n // Skip corrupt meta files\n }\n }\n if (filter?.prefix) {\n refs = refs.filter((r) => r.startsWith(filter.prefix!));\n }\n if (filter?.limit) {\n refs = refs.slice(0, filter.limit);\n }\n return refs;\n }\n\n async testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n const start = Date.now();\n try {\n await this.ensureKey();\n // Write + read + delete a test secret\n const testRef = `__test_${crypto.randomBytes(4).toString(\"hex\")}`;\n const testValue = new TextEncoder().encode(\"test\");\n await this.setSecret(testRef, testValue);\n const read = await this.getSecret(testRef);\n await this.deleteSecret(testRef);\n if (new TextDecoder().decode(read) !== \"test\") {\n return { ok: false, error: \"Round-trip mismatch\" };\n }\n return { ok: true, latencyMs: Date.now() - start };\n } catch (e) {\n return {\n ok: false,\n latencyMs: Date.now() - start,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const metaFile = this.metaPath(ref);\n const filePath = path.join(this.secretsDir, this.encFilename(ref));\n if (!fs.existsSync(filePath)) {\n throw new SecretNotFoundError(ref);\n }\n if (fs.existsSync(metaFile)) {\n const raw = JSON.parse(fs.readFileSync(metaFile, \"utf-8\"));\n return {\n ref: raw.ref ?? ref,\n createdAt: new Date(raw.createdAt),\n updatedAt: new Date(raw.updatedAt),\n lastAccessedAt: raw.lastAccessedAt ? new Date(raw.lastAccessedAt) : undefined,\n owner: raw.owner,\n scopeSummary: \"local encrypted file\",\n };\n }\n // Fallback: derive from file stat\n const stat = fs.statSync(filePath);\n return {\n ref,\n createdAt: stat.birthtime,\n updatedAt: stat.mtime,\n scopeSummary: \"local encrypted file\",\n };\n }\n\n getCapabilities(): ProviderCapabilities {\n return {\n supportsRotation: false,\n supportsExpiry: false,\n supportsBatch: false,\n scopeModel: \"flat\",\n };\n }\n}\n","/**\n * SecretsRouter — audit chokepoint for all secret operations.\n *\n * Registers {@link ISecretsProvider} implementations by id, routes credential refs by\n * prefix or via routing config, and emits {@link CredentialAccessed} events for every\n * get, set, delete, list, and metadata operation. Routing rules are evaluated top-to-bottom;\n * the first matching prefix wins and falls back to the configured default provider.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\n\nimport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nimport { ProviderUnavailableError } from \"@skaile/workspaces/plugins\";\n\n// ---------------------------------------------------------------------------\n// Audit event\n// ---------------------------------------------------------------------------\n\n/**\n * Audit event emitted by {@link SecretsRouter} after every secret operation.\n *\n * Delivered synchronously to all registered {@link AuditSink} functions. Errors thrown\n * by sinks are swallowed to ensure they never break the underlying secret operation.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface CredentialAccessed {\n credential_ref: string;\n operation: \"get\" | \"set\" | \"delete\" | \"list\" | \"metadata\";\n provider_id: string;\n caller_session_id?: string;\n caller_tool_call?: string;\n timestamp: Date;\n}\n\n/**\n * Callback function that receives {@link CredentialAccessed} audit events from {@link SecretsRouter}.\n *\n * Register sinks via `SecretsRouter.addSink()`. Sinks run synchronously after each operation;\n * exceptions are caught and suppressed so they cannot interrupt credential resolution.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport type AuditSink = (event: CredentialAccessed) => void;\n\n// ---------------------------------------------------------------------------\n// Routing config\n// ---------------------------------------------------------------------------\n\n/**\n * A single routing rule that maps a credential ref prefix to a provider.\n *\n * Rules in {@link SecretsRouterConfig.rules} are evaluated top-to-bottom;\n * the first rule whose `prefix` matches the start of the credential ref wins.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface RoutingRule {\n /** Prefix match on credential_ref. First match wins. */\n prefix: string;\n /** Provider id to route to. */\n provider_id: string;\n}\n\n/**\n * Configuration object for {@link SecretsRouter}.\n *\n * Specifies the default provider id used when no routing rule matches, and an optional\n * ordered list of {@link RoutingRule} entries for prefix-based routing.\n *\n * @docLink packages/secrets/concepts#secrets-router\n */\nexport interface SecretsRouterConfig {\n /** Default provider id when no routing rule matches. */\n default_provider: string;\n /** Ordered routing rules. Evaluated top-to-bottom; first prefix match wins. */\n rules?: RoutingRule[];\n}\n\n// ---------------------------------------------------------------------------\n// Router\n// ---------------------------------------------------------------------------\n\nexport class SecretsRouter {\n private providers = new Map<string, ISecretsProvider>();\n private config: SecretsRouterConfig;\n private sinks: AuditSink[] = [];\n\n /** Caller context for audit events (set per-request by the runner). */\n callerSessionId?: string;\n callerToolCall?: string;\n\n constructor(config: SecretsRouterConfig) {\n this.config = config;\n }\n\n // -- Provider registration ------------------------------------------------\n\n register(provider: ISecretsProvider): void {\n this.providers.set(provider.id, provider);\n }\n\n unregister(id: string): void {\n this.providers.delete(id);\n }\n\n listProviders(): string[] {\n return [...this.providers.keys()];\n }\n\n // -- Audit sinks -----------------------------------------------------------\n\n addSink(sink: AuditSink): void {\n this.sinks.push(sink);\n }\n\n private emit(ref: string, operation: CredentialAccessed[\"operation\"], providerId: string): void {\n const event: CredentialAccessed = {\n credential_ref: ref,\n operation,\n provider_id: providerId,\n caller_session_id: this.callerSessionId,\n caller_tool_call: this.callerToolCall,\n timestamp: new Date(),\n };\n for (const sink of this.sinks) {\n try {\n sink(event);\n } catch {\n // Audit sink errors must not break the secret operation.\n }\n }\n }\n\n // -- Routing ---------------------------------------------------------------\n\n private resolve(ref: string): ISecretsProvider {\n // Check routing rules first\n if (this.config.rules) {\n for (const rule of this.config.rules) {\n if (ref.startsWith(rule.prefix)) {\n const provider = this.providers.get(rule.provider_id);\n if (provider) return provider;\n }\n }\n }\n\n // Fall back to default\n const provider = this.providers.get(this.config.default_provider);\n if (!provider) {\n throw new ProviderUnavailableError(\n this.config.default_provider,\n `No provider registered for default id \"${this.config.default_provider}\"`,\n );\n }\n return provider;\n }\n\n // -- Delegated operations --------------------------------------------------\n\n async getSecret(ref: string): Promise<Uint8Array> {\n const provider = this.resolve(ref);\n this.emit(ref, \"get\", provider.id);\n return provider.getSecret(ref);\n }\n\n async setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void> {\n const provider = this.resolve(ref);\n this.emit(ref, \"set\", provider.id);\n return provider.setSecret(ref, value, opts);\n }\n\n async deleteSecret(ref: string): Promise<void> {\n const provider = this.resolve(ref);\n this.emit(ref, \"delete\", provider.id);\n return provider.deleteSecret(ref);\n }\n\n async listSecrets(filter?: ListFilter): Promise<string[]> {\n // List aggregates from the default provider only (per-provider listing\n // would require iterating all providers; deferred to Phase 3 with\n // federated catalogs).\n const provider = this.providers.get(this.config.default_provider);\n if (!provider) return [];\n this.emit(\"*\", \"list\", provider.id);\n return provider.listSecrets(filter);\n }\n\n async getMetadata(ref: string): Promise<SecretMetadata> {\n const provider = this.resolve(ref);\n this.emit(ref, \"metadata\", provider.id);\n return provider.getMetadata(ref);\n }\n\n getCapabilities(providerId?: string): ProviderCapabilities | null {\n const id = providerId ?? this.config.default_provider;\n const provider = this.providers.get(id);\n return provider?.getCapabilities() ?? null;\n }\n\n async testConnection(\n providerId?: string,\n ): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {\n const id = providerId ?? this.config.default_provider;\n const provider = this.providers.get(id);\n if (!provider) {\n return { ok: false, error: `Provider \"${id}\" not registered` };\n }\n return provider.testConnection();\n }\n}\n","/** Package version of `@skaile/secrets`. */\nexport const VERSION = \"0.0.0\";\n\n// Re-export interface + errors from plugins (convenience for consumers)\nexport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"@skaile/workspaces/plugins\";\nexport {\n ProviderUnavailableError,\n SecretAccessDeniedError,\n SecretExpiredError,\n SecretNotFoundError,\n SecretsError,\n} from \"@skaile/workspaces/plugins\";\nexport type { CredentialLifecycleConfig, RefreshResult } from \"./lifecycle.js\";\n// Lifecycle\nexport { CredentialLifecycleService } from \"./lifecycle.js\";\nexport { EnvSecretsProvider } from \"./providers/env.js\";\nexport type { KeyStrategy } from \"./providers/local.js\";\n// Built-in providers\nexport { LocalSecretsProvider } from \"./providers/local.js\";\nexport type { AuditSink, CredentialAccessed, RoutingRule, SecretsRouterConfig } from \"./router.js\";\n// Router\nexport { SecretsRouter } from \"./router.js\";\n"]}
@@ -1,12 +1,13 @@
1
1
  import { initTelemetry } from './chunk-4R6DROGN.js';
2
- import { parseSkillFrontmatter, validateFlowVersions } from './chunk-OQRB7JUS.js';
3
- import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner, driveOrchestratorTurn } from './chunk-5RWL4L3X.js';
4
- import { loadFlow, flowLookupRoots, findFlowFileInRoots, FLOW_FILE_EXTENSIONS } from './chunk-7RC37XFW.js';
5
- import { renderStimulusPrompt } from './chunk-K3IBZ2UZ.js';
6
- import { flowSkillVersionPins } from './chunk-UDFWBALP.js';
7
- import { resolveSettings } from './chunk-YV3YI3TA.js';
8
- import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-JEPSP6XK.js';
9
- import { isValidAssetName } from './chunk-A5EDMBFG.js';
2
+ import { parseSkillFrontmatter, validateFlowVersions } from './chunk-YV4J7V53.js';
3
+ import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner, driveOrchestratorTurn } from './chunk-53WMBXSL.js';
4
+ import { loadFlow, flowLookupRoots, findFlowFileInRoots, FLOW_FILE_EXTENSIONS } from './chunk-22DN3DB2.js';
5
+ import { renderStimulusPrompt } from './chunk-XUUYAS3Z.js';
6
+ import { flowSkillVersionPins } from './chunk-NFGRW3L7.js';
7
+ import { resolveSettings } from './chunk-MBVNMPG7.js';
8
+ import { findKindDirs } from './chunk-A2ULN3KX.js';
9
+ import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-HWE3FXF4.js';
10
+ import { isValidAssetName } from './chunk-43ZBF3WH.js';
10
11
  import { createLogger } from './chunk-BOFL7GIF.js';
11
12
  import fs from 'fs';
12
13
  import path from 'path';
@@ -467,10 +468,7 @@ function findAiResourcesDir(projectDir) {
467
468
  return null;
468
469
  }
469
470
  function findSkillMd(aiResourcesDir, skillId) {
470
- for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {
471
- if (!domain.isDirectory()) continue;
472
- const skillsDir = path.join(aiResourcesDir, domain.name, "skills");
473
- if (!fs.existsSync(skillsDir)) continue;
471
+ for (const skillsDir of findKindDirs(aiResourcesDir, "skills")) {
474
472
  const found = walkForSkill(skillsDir, skillId);
475
473
  if (found) return found;
476
474
  }
@@ -518,5 +516,5 @@ function walkForSkill(dir, skillId) {
518
516
  }
519
517
 
520
518
  export { awaitAgentEnd, resolveFlowPath, resumeFlow, runFlow };
521
- //# sourceMappingURL=chunk-252TK4RU.js.map
522
- //# sourceMappingURL=chunk-252TK4RU.js.map
519
+ //# sourceMappingURL=chunk-GFPG27HK.js.map
520
+ //# sourceMappingURL=chunk-GFPG27HK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;;AAiEA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AAEjD,IAAM,0BAAA,uBAAiC,GAAA,CAAI;AAAA,EACzC,eAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF,CAAC,CAAA;AAuHD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,2BAAA;AAAA,IACA,kBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,gBAAA;AAAA,IACA,+BAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CA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A,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-GFPG27HK.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n findKindDirs,\n isValidAssetName,\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution, FlowPromptEvent } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n findFlowFileInRoots,\n FLOW_FILE_EXTENSIONS,\n type FlowLookupMiss,\n flowLookupRoots,\n loadFlow,\n} from \"./engine/index.js\";\nimport { flowSkillVersionPins } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.js\";\nimport { driveOrchestratorTurn } from \"./orchestrator-turn.js\";\nimport { renderStimulusPrompt, type TurnStimulus } from \"./prompt-fragments.js\";\nimport { SessionSubpromptRunner } from \"./subprompt-runner.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent harness. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n */\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs. Defaults to true; first-class gate nodes are never bypassed. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: wsConfigEarly.logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown, _signal?: AbortSignal, callId?: string) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId, callId }),\n };\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n // Same endpoints and credentials the session driver used: the registry\n // and the credential env `createAgentSession` already resolved — not a\n // new resolution, not a new secret channel.\n const subpromptRunner = new SessionSubpromptRunner({\n driverType: agentSession.driverType,\n sessionModel: agentSession.model,\n workspaceDir: opts.projectDir,\n registry: agentSession.registry,\n credentialEnv: agentSession.credentialEnv,\n ...(agentSession.modelRef ? { modelRef: agentSession.modelRef } : {}),\n });\n let driverStarted = false;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It hands the turn to\n // `driveOrchestratorTurn`, which rebuilds the five-section prompt so the\n // agent sees the same flow context the legacy orchestrator produced — and\n // announces it, so a CLI consumer's `onEvent` stream carries the prompt too.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n // Same widening the `state_changed` forwarder below performs: `onEvent` is\n // typed against the bridge's driver-level union, which has no case for a\n // runtime-level event.\n const emitFlowPrompt = (event: FlowPromptEvent): void => {\n opts.onEvent?.(event as unknown as AgentEvent);\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n subpromptRunner,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow: childFlow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n });\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals. It is\n // discarded in favour of the structured stimulus, which\n // `driveOrchestratorTurn` rebuilds the full prompt from; that keeps the\n // prompt shape stable and the structured form already contains\n // everything the fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n nodeExecutor,\n subpromptRunner,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: wsConfigEarly.logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flowSkillVersionPins(flow);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.skillId;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const checks = validateFlowVersions(pinnedNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\n/**\n * Assert `found` sits inside one of `roots`.\n *\n * A backstop, not the primary control: `isValidAssetName` already rejects every\n * id containing a separator, and `findFlowFileInRoots` skips any candidate that\n * escapes its search dir. So on today's code this cannot fire — it is here to\n * fail loudly rather than silently if a future lookup stops enforcing\n * containment itself. Widening the accepted extensions must never widen which\n * paths are reachable, and this is the line that keeps that honest.\n */\nfunction assertContainedInAnyRoot(found: string, roots: string[], flowId: string): void {\n const resolved = path.resolve(found);\n const inside = roots.some((root) => {\n const relative = path.relative(path.resolve(root), resolved);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n if (!inside) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n}\n\n/** One line per near-miss: a file that is right there but was still rejected. */\nfunction describeMisses(misses: FlowLookupMiss[], heading: string): string {\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const miss of misses) {\n if (seen.has(miss.path)) continue;\n seen.add(miss.path);\n lines.push(\n miss.reason === \"id-mismatch\"\n ? ` ${miss.path}: declares id ${JSON.stringify(miss.declaredId ?? \"\")}`\n : ` ${miss.path}: could not be parsed (${miss.error ?? \"unknown error\"})`,\n );\n }\n return lines.length > 0 ? `\\n${heading}\\n${lines.join(\"\\n\")}` : \"\";\n}\n\n/**\n * Resolve one flow identity through the CLI/serve host's normal lookup order —\n * the same roots and filenames `skaile run` and `flow list` use, via\n * {@link flowLookupRoots} / {@link findFlowFileInRoots}. Resolution is by the\n * **declared** `id`, not by filename.\n *\n * @throws {Error} When `flowId` is not a canonical asset name, when no file\n * declares it, or when a match somehow resolves outside every lookup root.\n */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n // Sub-flow targets and resumed session records are the two callers, so an\n // identity that is not canonical is a bug in the caller, not a missing file.\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const roots = flowLookupRoots(projectDir);\n const misses: FlowLookupMiss[] = [];\n const found = findFlowFileInRoots(flowId, roots, { onMiss: (m) => misses.push(m) });\n if (found) {\n assertContainedInAnyRoot(found, roots, flowId);\n return found;\n }\n\n // A file that is present but unparseable is a different problem from a missing\n // one, and \"not found\" is the wrong headline for it — that exact misdirection\n // is what this change exists to remove, so don't reintroduce it here.\n if (misses.length > 0 && misses.every((m) => m.reason === \"unparseable\")) {\n throw new Error(\n `Flow ${flowId} was found but could not be loaded.` + describeMisses(misses, \"Candidates:\"),\n );\n }\n\n const shown = roots.slice(0, 3).join(\", \");\n const more = roots.length > 3 ? \", …\" : \"\";\n // Spelled from FLOW_FILE_EXTENSIONS so the message cannot drift from the\n // candidate list the lookup actually probes.\n const accepted = FLOW_FILE_EXTENSIONS.map((ext) => `${flowId}${ext}`).join(\" | \");\n throw new Error(\n `Flow not found: ${flowId}. Searched ${roots.length} root(s) (${shown || \"none\"}${more}) ` +\n `for ${accepted} — flat, or inside a ${flowId}/ directory.` +\n describeMisses(misses, \"Near misses:\"),\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID in any `skills/` directory under ai-assets */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const skillsDir of findKindDirs(aiResourcesDir, \"skills\")) {\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on an `error` that is not an in-place retry).\n * Identical contract to the legacy `awaitAgentEnd` helper from\n * `flow-orchestrator.ts`. Phase 4 lifts the helper into `run-flow.ts` because\n * the bus now owns turn driving. Exported for tests only.\n */\nexport function awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n // An in-place retry replays this same turn; its own end settles it.\n else if (event.type === \"error\" && event.retrying !== true) {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { parseAssetRef } from './chunk-A5EDMBFG.js';
1
+ import { parseAssetRef } from './chunk-43ZBF3WH.js';
2
2
  import { createHash } from 'crypto';
3
3
  import { rm, mkdir, writeFile } from 'fs/promises';
4
4
  import { resolve, join, sep, dirname, isAbsolute } from 'path';
@@ -124,5 +124,5 @@ async function installFlat(manifest, targetDir, fetcher) {
124
124
  }
125
125
 
126
126
  export { installFromManifest, longestCommonDirPrefix };
127
- //# sourceMappingURL=chunk-2EL2PBRC.js.map
128
- //# sourceMappingURL=chunk-2EL2PBRC.js.map
127
+ //# sourceMappingURL=chunk-H4EGUQ7M.js.map
128
+ //# sourceMappingURL=chunk-H4EGUQ7M.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../library/src/install/install-from-manifest.ts"],"names":[],"mappings":";;;;;AA+CA,SAAS,sBAAA,CAAuB,aAAqB,CAAA,EAAiB;AACpE,EAAA,MAAM,MAAM,MAAa;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,CAAC,CAAA,CAAE,CAAA;AAAA,EACjD,CAAA;AACA,EAAA,IAAI,CAAC,CAAA,IAAK,CAAA,CAAE,MAAA,KAAW,GAAG,GAAA,EAAI;AAC9B,EAAA,IAAI,UAAA,CAAW,CAAC,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,EAAG,GAAA,EAAI;AAClE,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,KAAA,CAAM,OAAO,CAAA;AAChC,EAAA,IAAI,SAAS,IAAA,CAAK,CAAC,MAAM,CAAA,KAAM,IAAI,GAAG,GAAA,EAAI;AAC1C,EAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,WAAA,EAAa,CAAC,CAAA;AACvC,EAAA,IAAI,QAAA,KAAa,eAAe,CAAC,QAAA,CAAS,WAAW,WAAA,GAAc,GAAG,GAAG,GAAA,EAAI;AAC/E;AAgBA,SAAS,sBAAA,CAAuB,MAAc,KAAA,EAAqB;AAIjE,EAAA,MAAM,cAAA,GAAiB,CAAC,GAAG,KAAK,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,UAAA,CAAW,CAAC,CAAA,GAAI,EAAI,CAAA;AACpE,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AAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,SAAA,CAAU,MAAM,GAAG,CAAA;AAAA,EAC3B;AAEA,EAAA,OAAO,EAAE,aAAa,MAAA,EAAO;AAC/B","file":"chunk-2EL2PBRC.js","sourcesContent":["/**\n * Pointer-only install path.\n *\n * Given an {@link InstallManifest} (the Pointer Triple the Catalog hands\n * clients), this:\n *\n * 1. fetches the asset bytes directly from the upstream repo at the pinned\n * commit (via an injectable fetcher, default {@link fetchAssetFilesFromGitHub});\n * 2. verifies EVERY per-file SHA256 against `manifest.files[].sha256`;\n * 3. verifies the composite SHA256 rollup over the sorted\n * `<path>:<sha256>\\n` lines against `manifest.sha256`;\n * 4. writes the verified bytes under `<libraryRoot>/@<publisher>/<name>/<version>`.\n *\n * Any hash mismatch is a hard failure — bytes are not written if per-file\n * verification fails, and the composite check is the second gate.\n *\n * @docLink packages/library/concepts#install\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve, sep } from \"node:path\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { parseAssetRef } from \"../../../core/src/models.js\";\n\n/**\n * Validate a single manifest-supplied file path against path traversal.\n *\n * `manifest.files[].path` comes off the network — the attacker controls the\n * entire manifest (and therefore every hash in it), so hash verification can\n * NEVER mitigate a malicious *destination*. A path like\n * `../../../../home/user/.bashrc` or an absolute path would escape\n * `installPath` and yield an arbitrary file write. Every path is checked\n * BEFORE any fetch or write happens; the first bad path aborts the entire\n * install with a hard throw.\n *\n * A path is rejected if ANY of:\n * - it is empty;\n * - it is absolute (`path.isAbsolute`) or has a leading slash;\n * - it contains a `..` segment;\n * - `path.resolve(installPath, p)` is not `installPath` itself and does not\n * start with `installPath + path.sep` (escapes the install dir).\n *\n * @throws An error matching `/unsafe path in manifest/` on the first bad path.\n */\nfunction assertSafeManifestPath(installPath: string, p: string): void {\n const bad = (): never => {\n throw new Error(`unsafe path in manifest: ${p}`);\n };\n if (!p || p.length === 0) bad();\n if (isAbsolute(p) || p.startsWith(\"/\") || p.startsWith(\"\\\\\")) bad();\n const segments = p.split(/[/\\\\]/);\n if (segments.some((s) => s === \"..\")) bad();\n const resolved = resolve(installPath, p);\n if (resolved !== installPath && !resolved.startsWith(installPath + sep)) bad();\n}\n\n/**\n * Validate one component (publisher / name / version) of the attacker-controlled\n * `manifest.ref`.\n *\n * `installPath` is built by joining these components onto `libraryRoot`. A\n * component containing a path separator or a `..` / leading-dot segment would\n * let `installPath` itself escape `libraryRoot` — yielding an arbitrary file\n * write AND, via the pre-write `rm(installPath, { recursive })`, an arbitrary\n * recursive delete. The per-file `assertSafeManifestPath` guard cannot catch\n * this: it only validates each `f.path` *relative to* `installPath`, never\n * `installPath` itself. Components must be plain identifier-like strings.\n *\n * @throws An error matching `/unsafe ref/` on a bad component.\n */\nfunction assertSafeRefComponent(kind: string, value: string): void {\n // Reject empty, leading-dot (covers `.` and `..`), path separators, and\n // ASCII control characters (NUL et al.) — fails a malformed segment fast\n // with a domain-specific error rather than a raw EINVAL deeper in.\n const hasControlChar = [...value].some((c) => c.charCodeAt(0) < 0x20);\n if (!value || value.startsWith(\".\") || /[/\\\\]/.test(value) || hasControlChar) {\n throw new Error(`unsafe ref ${kind} component in manifest: '${value}'`);\n }\n}\n\n/**\n * Longest common **directory** prefix across manifest paths, compared by whole\n * slash-delimited segments (never raw-string — so `app/` and `app-data/` never\n * collide). Each path's basename is excluded, so the result is always a\n * directory prefix and every path keeps a non-empty remainder after stripping.\n *\n * Used by flat mode to reproduce the platform pointer-installer's asset-rooting:\n * the store persists repo-root-relative paths (e.g. `skaile-platform/mcpo/xls/MCP.md`)\n * but the runner scans `.skaile/assets/<kind>/<name>/` for immediate-child files,\n * so this prefix is stripped from the WRITE path while the fetch keeps the full\n * repo path. Returns `''` when there is no common directory (a no-op strip).\n */\nexport function longestCommonDirPrefix(paths: readonly string[]): string {\n if (paths.length === 0) return \"\";\n const dirSegments = paths.map((p) => p.split(\"/\").slice(0, -1));\n let common = dirSegments[0]!;\n for (let i = 1; i < dirSegments.length && common.length > 0; i++) {\n const segs = dirSegments[i]!;\n let n = 0;\n while (n < common.length && n < segs.length && common[n] === segs[n]) n++;\n common = common.slice(0, n);\n }\n return common.join(\"/\");\n}\n\n/**\n * Fetcher signature — fetches `{ path → Buffer }` for the requested paths at\n * a pinned upstream commit. {@link fetchAssetFilesFromGitHub} is the default\n * production implementation; tests inject a mock.\n */\nexport type AssetFetcher = (opts: {\n url: string;\n commitSha: string;\n paths: string[];\n}) => Promise<Record<string, Buffer>>;\n\n/**\n * Options for {@link installFromManifest}.\n */\nexport interface InstallOpts {\n /** The pointer-only install manifest from the Catalog. */\n manifest: InstallManifest;\n /** Filesystem root the asset is installed under (ref-derived mode). */\n libraryRoot: string;\n /**\n * Pluggable fetcher so tests can inject mock data. Defaults to\n * {@link fetchAssetFilesFromGitHub} in production.\n */\n fetcher?: AssetFetcher;\n /**\n * Flat-layout mode. When set, install-core reproduces the platform\n * pointer-installer's behavior: it ignores `libraryRoot`/ref-derivation, does\n * NOT parse `manifest.ref` and does NOT verify the composite sha256, strips\n * the longest-common-dir prefix from each path, per-file sha256-verifies, and\n * writes the stripped paths as immediate children of `targetDir` (what the\n * runner's `.skaile/assets/<kind>/<name>/` scan requires). `installPath` is\n * `targetDir`. Absent → unchanged ref-derived `@<pub>/name/version/<path>`\n * layout with composite verify.\n */\n targetDir?: string;\n}\n\n/**\n * Result of a successful {@link installFromManifest} call.\n */\nexport interface InstallResult {\n /** Absolute path the asset files were written to. */\n installPath: string;\n}\n\n/**\n * Fetch, verify, and write an asset's files per its {@link InstallManifest}.\n *\n * @throws An error matching `/hash mismatch/i` if any per-file SHA256 differs.\n * @throws An error matching `/composite hash mismatch/i` if the rollup differs.\n * @throws An error if the ref is malformed or the fetcher omits a file.\n */\nexport async function installFromManifest(opts: InstallOpts): Promise<InstallResult> {\n const { manifest, libraryRoot } = opts;\n const fetcher =\n opts.fetcher ?? (await import(\"./source-fetch-github.js\")).fetchAssetFilesFromGitHub;\n\n // Flat mode: reproduce the platform pointer-installer's asset-rooted layout.\n // No ref parse, no composite verify — the platform store may not satisfy a\n // ref-grammar or composite, and the runner only needs immediate-child files.\n if (opts.targetDir !== undefined) {\n return installFlat(manifest, opts.targetDir, fetcher);\n }\n\n // 1. Parse ref into install path: `skill:@x/git#1.0.0` → `<root>/@x/git/1.0.0`.\n // Done first so the C1 path-traversal guard can resolve against installPath\n // BEFORE any network fetch happens. The ref is attacker-controlled, so each\n // segment is further validated as a safe path component (H1) after parsing.\n // `parseAssetRef` is the single canonical grammar (`kind:@publisher/name#version`);\n // the legacy trailing-`@version` shape was removed in core and is rejected here.\n let parsed: ReturnType<typeof parseAssetRef>;\n try {\n parsed = parseAssetRef(manifest.ref);\n } catch (e) {\n throw new Error(`invalid ref: ${manifest.ref}: ${e instanceof Error ? e.message : String(e)}`);\n }\n const publisher = parsed.publisher;\n const name = parsed.name;\n const version = parsed.pin;\n if (!publisher) throw new Error(`invalid ref: ${manifest.ref} (missing publisher)`);\n if (!version) throw new Error(`invalid ref: ${manifest.ref} (missing version pin)`);\n assertSafeRefComponent(\"publisher\", publisher);\n assertSafeRefComponent(\"name\", name);\n assertSafeRefComponent(\"version\", version);\n const root = resolve(libraryRoot);\n const installPath = resolve(join(root, `@${publisher}`, name, version));\n // Defense in depth: even with the segment guards above, assert the built\n // installPath stays strictly inside libraryRoot before any write or `rm`.\n if (installPath !== root && !installPath.startsWith(root + sep)) {\n throw new Error(`unsafe install path: ref '${manifest.ref}' resolves outside the library root`);\n }\n\n // 2. [C1] Validate EVERY manifest path against traversal BEFORE fetching.\n // The attacker controls the manifest (and thus all hashes) — hashes verify\n // content, never destination. Reject the whole install on the first bad path.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n }\n\n // 3. Fetch all files at the pinned commit.\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // 4. Verify per-file SHA256 — hard fail before writing anything. The path\n // key used to read from the fetcher result is re-guarded as defense in depth.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n }\n\n // 5. Verify composite SHA256 over the sorted `<path>:<sha256>\\n` lines.\n const sortedLines = manifest.files\n .slice()\n .sort((a, b) => a.path.localeCompare(b.path))\n .map((e) => `${e.path}:${e.sha256}\\n`)\n .join(\"\");\n const actualComposite = createHash(\"sha256\").update(sortedLines, \"utf-8\").digest(\"hex\");\n if (actualComposite !== manifest.sha256) {\n throw new Error(`composite hash mismatch: expected ${manifest.sha256}, got ${actualComposite}`);\n }\n\n // 6. [M1] Write all verified files. A failed install must leave NO partial\n // directory: any prior `installPath` is removed first (clean overwrite), and\n // a mid-loop write failure removes the partially-written tree before\n // rethrowing.\n await rm(installPath, { recursive: true, force: true });\n try {\n for (const f of manifest.files) {\n const target = join(installPath, f.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, bytes[f.path]!);\n }\n } catch (e) {\n await rm(installPath, { recursive: true, force: true }).catch(() => {});\n throw e;\n }\n\n return { installPath };\n}\n\n/**\n * Flat-layout install — the platform pointer-installer's behavior, made canonical\n * in install-core. Validates every path, fetches with the FULL repo paths, per-file\n * sha256-verifies, then strips the longest-common-dir prefix and writes each file\n * as `join(targetDir, path.slice(assetRoot.length + 1))` — immediate children of\n * `targetDir`. No ref parse, no composite check.\n */\nasync function installFlat(\n manifest: InstallManifest,\n targetDir: string,\n fetcher: AssetFetcher,\n): Promise<InstallResult> {\n const target = resolve(targetDir);\n\n // Gate every path before any fetch — the attacker controls the whole manifest.\n for (const f of manifest.files) {\n assertSafeManifestPath(target, f.path);\n }\n\n // Fetch keys off the FULL repo path (matches the upstream tree).\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // Strip the asset-root dir prefix from the WRITE path only — the fetch above\n // still keyed off the full repo path. Stripping removes leading whole segments\n // (never the basename), so a non-empty remainder always survives.\n const assetRoot = longestCommonDirPrefix(paths);\n\n for (const f of manifest.files) {\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n const relPath = assetRoot ? f.path.slice(assetRoot.length + 1) : f.path;\n // Re-guard the post-strip destination — it is what we actually write.\n assertSafeManifestPath(target, relPath);\n const dest = join(target, relPath);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, buf);\n }\n\n return { installPath: target };\n}\n"]}
1
+ {"version":3,"sources":["../library/src/install/install-from-manifest.ts"],"names":[],"mappings":";;;;;AA+CA,SAAS,sBAAA,CAAuB,aAAqB,CAAA,EAAiB;AACpE,EAAA,MAAM,MAAM,MAAa;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,CAAC,CAAA,CAAE,CAAA;AAAA,EACjD,CAAA;AACA,EAAA,IAAI,CAAC,CAAA,IAAK,CAAA,CAAE,MAAA,KAAW,GAAG,GAAA,EAAI;AAC9B,EAAA,IAAI,UAAA,CAAW,CAAC,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,GAAG,CAAA,IAAK,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,EAAG,GAAA,EAAI;AAClE,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,K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AAE,OAAO,KAAK,CAAA;AAC5D,IAAA,IAAI,MAAA,KAAW,EAAE,MAAA,EAAQ;AACvB,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAqB,CAAA,CAAE,IAAI,cAAc,CAAA,CAAE,MAAM,CAAA,MAAA,EAAS,MAAM,CAAA,CAAE,CAAA;AAAA,IACpF;AACA,IAAA,MAAM,OAAA,GAAU,YAAY,CAAA,CAAE,IAAA,CAAK,MAAM,SAAA,CAAU,MAAA,GAAS,CAAC,CAAA,GAAI,CAAA,CAAE,IAAA;AAEnE,IAAA,sBAAA,CAAuB,QAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,MAAA,EAAQ,OAAO,CAAA;AACjC,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,SAAA,CAAU,MAAM,GAAG,CAAA;AAAA,EAC3B;AAEA,EAAA,OAAO,EAAE,aAAa,MAAA,EAAO;AAC/B","file":"chunk-H4EGUQ7M.js","sourcesContent":["/**\n * Pointer-only install path.\n *\n * Given an {@link InstallManifest} (the Pointer Triple the Catalog hands\n * clients), this:\n *\n * 1. fetches the asset bytes directly from the upstream repo at the pinned\n * commit (via an injectable fetcher, default {@link fetchAssetFilesFromGitHub});\n * 2. verifies EVERY per-file SHA256 against `manifest.files[].sha256`;\n * 3. verifies the composite SHA256 rollup over the sorted\n * `<path>:<sha256>\\n` lines against `manifest.sha256`;\n * 4. writes the verified bytes under `<libraryRoot>/@<publisher>/<name>/<version>`.\n *\n * Any hash mismatch is a hard failure — bytes are not written if per-file\n * verification fails, and the composite check is the second gate.\n *\n * @docLink packages/library/concepts#install\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve, sep } from \"node:path\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { parseAssetRef } from \"../../../core/src/models.js\";\n\n/**\n * Validate a single manifest-supplied file path against path traversal.\n *\n * `manifest.files[].path` comes off the network — the attacker controls the\n * entire manifest (and therefore every hash in it), so hash verification can\n * NEVER mitigate a malicious *destination*. A path like\n * `../../../../home/user/.bashrc` or an absolute path would escape\n * `installPath` and yield an arbitrary file write. Every path is checked\n * BEFORE any fetch or write happens; the first bad path aborts the entire\n * install with a hard throw.\n *\n * A path is rejected if ANY of:\n * - it is empty;\n * - it is absolute (`path.isAbsolute`) or has a leading slash;\n * - it contains a `..` segment;\n * - `path.resolve(installPath, p)` is not `installPath` itself and does not\n * start with `installPath + path.sep` (escapes the install dir).\n *\n * @throws An error matching `/unsafe path in manifest/` on the first bad path.\n */\nfunction assertSafeManifestPath(installPath: string, p: string): void {\n const bad = (): never => {\n throw new Error(`unsafe path in manifest: ${p}`);\n };\n if (!p || p.length === 0) bad();\n if (isAbsolute(p) || p.startsWith(\"/\") || p.startsWith(\"\\\\\")) bad();\n const segments = p.split(/[/\\\\]/);\n if (segments.some((s) => s === \"..\")) bad();\n const resolved = resolve(installPath, p);\n if (resolved !== installPath && !resolved.startsWith(installPath + sep)) bad();\n}\n\n/**\n * Validate one component (publisher / name / version) of the attacker-controlled\n * `manifest.ref`.\n *\n * `installPath` is built by joining these components onto `libraryRoot`. A\n * component containing a path separator or a `..` / leading-dot segment would\n * let `installPath` itself escape `libraryRoot` — yielding an arbitrary file\n * write AND, via the pre-write `rm(installPath, { recursive })`, an arbitrary\n * recursive delete. The per-file `assertSafeManifestPath` guard cannot catch\n * this: it only validates each `f.path` *relative to* `installPath`, never\n * `installPath` itself. Components must be plain identifier-like strings.\n *\n * @throws An error matching `/unsafe ref/` on a bad component.\n */\nfunction assertSafeRefComponent(kind: string, value: string): void {\n // Reject empty, leading-dot (covers `.` and `..`), path separators, and\n // ASCII control characters (NUL et al.) — fails a malformed segment fast\n // with a domain-specific error rather than a raw EINVAL deeper in.\n const hasControlChar = [...value].some((c) => c.charCodeAt(0) < 0x20);\n if (!value || value.startsWith(\".\") || /[/\\\\]/.test(value) || hasControlChar) {\n throw new Error(`unsafe ref ${kind} component in manifest: '${value}'`);\n }\n}\n\n/**\n * Longest common **directory** prefix across manifest paths, compared by whole\n * slash-delimited segments (never raw-string — so `app/` and `app-data/` never\n * collide). Each path's basename is excluded, so the result is always a\n * directory prefix and every path keeps a non-empty remainder after stripping.\n *\n * Used by flat mode to reproduce the platform pointer-installer's asset-rooting:\n * the store persists repo-root-relative paths (e.g. `skaile-platform/mcpo/xls/MCP.md`)\n * but the runner scans `.skaile/assets/<kind>/<name>/` for immediate-child files,\n * so this prefix is stripped from the WRITE path while the fetch keeps the full\n * repo path. Returns `''` when there is no common directory (a no-op strip).\n */\nexport function longestCommonDirPrefix(paths: readonly string[]): string {\n if (paths.length === 0) return \"\";\n const dirSegments = paths.map((p) => p.split(\"/\").slice(0, -1));\n let common = dirSegments[0]!;\n for (let i = 1; i < dirSegments.length && common.length > 0; i++) {\n const segs = dirSegments[i]!;\n let n = 0;\n while (n < common.length && n < segs.length && common[n] === segs[n]) n++;\n common = common.slice(0, n);\n }\n return common.join(\"/\");\n}\n\n/**\n * Fetcher signature — fetches `{ path → Buffer }` for the requested paths at\n * a pinned upstream commit. {@link fetchAssetFilesFromGitHub} is the default\n * production implementation; tests inject a mock.\n */\nexport type AssetFetcher = (opts: {\n url: string;\n commitSha: string;\n paths: string[];\n}) => Promise<Record<string, Buffer>>;\n\n/**\n * Options for {@link installFromManifest}.\n */\nexport interface InstallOpts {\n /** The pointer-only install manifest from the Catalog. */\n manifest: InstallManifest;\n /** Filesystem root the asset is installed under (ref-derived mode). */\n libraryRoot: string;\n /**\n * Pluggable fetcher so tests can inject mock data. Defaults to\n * {@link fetchAssetFilesFromGitHub} in production.\n */\n fetcher?: AssetFetcher;\n /**\n * Flat-layout mode. When set, install-core reproduces the platform\n * pointer-installer's behavior: it ignores `libraryRoot`/ref-derivation, does\n * NOT parse `manifest.ref` and does NOT verify the composite sha256, strips\n * the longest-common-dir prefix from each path, per-file sha256-verifies, and\n * writes the stripped paths as immediate children of `targetDir` (what the\n * runner's `.skaile/assets/<kind>/<name>/` scan requires). `installPath` is\n * `targetDir`. Absent → unchanged ref-derived `@<pub>/name/version/<path>`\n * layout with composite verify.\n */\n targetDir?: string;\n}\n\n/**\n * Result of a successful {@link installFromManifest} call.\n */\nexport interface InstallResult {\n /** Absolute path the asset files were written to. */\n installPath: string;\n}\n\n/**\n * Fetch, verify, and write an asset's files per its {@link InstallManifest}.\n *\n * @throws An error matching `/hash mismatch/i` if any per-file SHA256 differs.\n * @throws An error matching `/composite hash mismatch/i` if the rollup differs.\n * @throws An error if the ref is malformed or the fetcher omits a file.\n */\nexport async function installFromManifest(opts: InstallOpts): Promise<InstallResult> {\n const { manifest, libraryRoot } = opts;\n const fetcher =\n opts.fetcher ?? (await import(\"./source-fetch-github.js\")).fetchAssetFilesFromGitHub;\n\n // Flat mode: reproduce the platform pointer-installer's asset-rooted layout.\n // No ref parse, no composite verify — the platform store may not satisfy a\n // ref-grammar or composite, and the runner only needs immediate-child files.\n if (opts.targetDir !== undefined) {\n return installFlat(manifest, opts.targetDir, fetcher);\n }\n\n // 1. Parse ref into install path: `skill:@x/git#1.0.0` → `<root>/@x/git/1.0.0`.\n // Done first so the C1 path-traversal guard can resolve against installPath\n // BEFORE any network fetch happens. The ref is attacker-controlled, so each\n // segment is further validated as a safe path component (H1) after parsing.\n // `parseAssetRef` is the single canonical grammar (`kind:@publisher/name#version`);\n // the legacy trailing-`@version` shape was removed in core and is rejected here.\n let parsed: ReturnType<typeof parseAssetRef>;\n try {\n parsed = parseAssetRef(manifest.ref);\n } catch (e) {\n throw new Error(`invalid ref: ${manifest.ref}: ${e instanceof Error ? e.message : String(e)}`);\n }\n const publisher = parsed.publisher;\n const name = parsed.name;\n const version = parsed.pin;\n if (!publisher) throw new Error(`invalid ref: ${manifest.ref} (missing publisher)`);\n if (!version) throw new Error(`invalid ref: ${manifest.ref} (missing version pin)`);\n assertSafeRefComponent(\"publisher\", publisher);\n assertSafeRefComponent(\"name\", name);\n assertSafeRefComponent(\"version\", version);\n const root = resolve(libraryRoot);\n const installPath = resolve(join(root, `@${publisher}`, name, version));\n // Defense in depth: even with the segment guards above, assert the built\n // installPath stays strictly inside libraryRoot before any write or `rm`.\n if (installPath !== root && !installPath.startsWith(root + sep)) {\n throw new Error(`unsafe install path: ref '${manifest.ref}' resolves outside the library root`);\n }\n\n // 2. [C1] Validate EVERY manifest path against traversal BEFORE fetching.\n // The attacker controls the manifest (and thus all hashes) — hashes verify\n // content, never destination. Reject the whole install on the first bad path.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n }\n\n // 3. Fetch all files at the pinned commit.\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // 4. Verify per-file SHA256 — hard fail before writing anything. The path\n // key used to read from the fetcher result is re-guarded as defense in depth.\n for (const f of manifest.files) {\n assertSafeManifestPath(installPath, f.path);\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n }\n\n // 5. Verify composite SHA256 over the sorted `<path>:<sha256>\\n` lines.\n const sortedLines = manifest.files\n .slice()\n .sort((a, b) => a.path.localeCompare(b.path))\n .map((e) => `${e.path}:${e.sha256}\\n`)\n .join(\"\");\n const actualComposite = createHash(\"sha256\").update(sortedLines, \"utf-8\").digest(\"hex\");\n if (actualComposite !== manifest.sha256) {\n throw new Error(`composite hash mismatch: expected ${manifest.sha256}, got ${actualComposite}`);\n }\n\n // 6. [M1] Write all verified files. A failed install must leave NO partial\n // directory: any prior `installPath` is removed first (clean overwrite), and\n // a mid-loop write failure removes the partially-written tree before\n // rethrowing.\n await rm(installPath, { recursive: true, force: true });\n try {\n for (const f of manifest.files) {\n const target = join(installPath, f.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, bytes[f.path]!);\n }\n } catch (e) {\n await rm(installPath, { recursive: true, force: true }).catch(() => {});\n throw e;\n }\n\n return { installPath };\n}\n\n/**\n * Flat-layout install — the platform pointer-installer's behavior, made canonical\n * in install-core. Validates every path, fetches with the FULL repo paths, per-file\n * sha256-verifies, then strips the longest-common-dir prefix and writes each file\n * as `join(targetDir, path.slice(assetRoot.length + 1))` — immediate children of\n * `targetDir`. No ref parse, no composite check.\n */\nasync function installFlat(\n manifest: InstallManifest,\n targetDir: string,\n fetcher: AssetFetcher,\n): Promise<InstallResult> {\n const target = resolve(targetDir);\n\n // Gate every path before any fetch — the attacker controls the whole manifest.\n for (const f of manifest.files) {\n assertSafeManifestPath(target, f.path);\n }\n\n // Fetch keys off the FULL repo path (matches the upstream tree).\n const paths = manifest.files.map((f) => f.path);\n const bytes = await fetcher({\n url: manifest.source.url,\n commitSha: manifest.source.commitSha,\n paths,\n });\n\n // Strip the asset-root dir prefix from the WRITE path only — the fetch above\n // still keyed off the full repo path. Stripping removes leading whole segments\n // (never the basename), so a non-empty remainder always survives.\n const assetRoot = longestCommonDirPrefix(paths);\n\n for (const f of manifest.files) {\n const buf = bytes[f.path];\n if (!buf) throw new Error(`fetcher returned no bytes for ${f.path}`);\n const actual = createHash(\"sha256\").update(buf).digest(\"hex\");\n if (actual !== f.sha256) {\n throw new Error(`hash mismatch for ${f.path}: expected ${f.sha256}, got ${actual}`);\n }\n const relPath = assetRoot ? f.path.slice(assetRoot.length + 1) : f.path;\n // Re-guard the post-strip destination — it is what we actually write.\n assertSafeManifestPath(target, relPath);\n const dest = join(target, relPath);\n await mkdir(dirname(dest), { recursive: true });\n await writeFile(dest, buf);\n }\n\n return { installPath: target };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { resolveSkWorkspaceConfig } from './chunk-JEPSP6XK.js';
2
- import { parseFrontmatter } from './chunk-5K2VT6E2.js';
1
+ import { resolveSkWorkspaceConfig } from './chunk-HWE3FXF4.js';
2
+ import { parseFrontmatter } from './chunk-DXUQCMVT.js';
3
3
  import { createLogger } from './chunk-BOFL7GIF.js';
4
4
  import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
5
5
  import { join } from 'path';
@@ -496,5 +496,5 @@ function resolveAuthRef(auth, mountId) {
496
496
  }
497
497
 
498
498
  export { ConnectorFieldMissingError, ConnectorStartupError, EnvSecretProvider, ForgeSecretProvider, InMemorySecretProvider, LegacyAuthGrammarError, LockedSecretProvider, OAuthRequiredError, PreMintedSecretProvider, SecretProviderChain, createCliSecretProviderChain, createForgeSecretProviderChain, deriveSingleMaterializedConnectorDeclaration, fromMaterializedConnectorMd, isKnownSecretRef, loadConnectorDeclarations, loadMaterializedConnectorDeclarations, loadYamlConnectorDeclarations, readUnavailableMarker, resolveAuthRef, resolveBackendAuthFor, resolvedConfigToDeclarations, withMaterializedConnectorDeclarations };
499
- //# sourceMappingURL=chunk-YQEF36D5.js.map
500
- //# sourceMappingURL=chunk-YQEF36D5.js.map
499
+ //# sourceMappingURL=chunk-H5G3OYY6.js.map
500
+ //# sourceMappingURL=chunk-H5G3OYY6.js.map