@skaile/workspaces 3.2.1 → 3.4.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 (215) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/dist/{asset-feeds-SEYSNNEM.js → asset-feeds-CBY723RG.js} +11 -11
  3. package/dist/{asset-feeds-SEYSNNEM.js.map → asset-feeds-CBY723RG.js.map} +1 -1
  4. package/dist/asset-manager/catalog-deployer.js +7 -7
  5. package/dist/asset-manager/index.js +10 -10
  6. package/dist/asset-manager/installer.js +7 -7
  7. package/dist/bridge/drivers/claude-sdk.js +8 -8
  8. package/dist/bridge/drivers/codex.js +3 -3
  9. package/dist/bridge/drivers/continue.js +4 -4
  10. package/dist/bridge/drivers/echo.js +3 -3
  11. package/dist/bridge/drivers/gemini.js +5 -5
  12. package/dist/bridge/drivers/goose.js +4 -4
  13. package/dist/bridge/drivers/omp.js +3 -3
  14. package/dist/bridge/drivers/opencode.js +4 -4
  15. package/dist/bridge/drivers/qwen.js +5 -5
  16. package/dist/bridge/index.js +9 -9
  17. package/dist/{chunk-57RFYEVM.js → chunk-2Y2AWWWM.js} +4 -10
  18. package/dist/chunk-2Y2AWWWM.js.map +1 -0
  19. package/dist/{chunk-O6B3ZZ5S.js → chunk-3A3ETJFD.js} +4 -4
  20. package/dist/{chunk-O6B3ZZ5S.js.map → chunk-3A3ETJFD.js.map} +1 -1
  21. package/dist/{chunk-7GOCNYUV.js → chunk-3A5IKBHQ.js} +47 -47
  22. package/dist/{chunk-7GOCNYUV.js.map → chunk-3A5IKBHQ.js.map} +1 -1
  23. package/dist/{chunk-I7S6DFRU.js → chunk-3Q7JDLLH.js} +46 -6
  24. package/dist/chunk-3Q7JDLLH.js.map +1 -0
  25. package/dist/{chunk-PTAUN5CY.js → chunk-3UGP7I2Y.js} +3 -3
  26. package/dist/{chunk-PTAUN5CY.js.map → chunk-3UGP7I2Y.js.map} +1 -1
  27. package/dist/{chunk-CZZRDYT4.js → chunk-4VTBZ2MF.js} +4 -4
  28. package/dist/{chunk-CZZRDYT4.js.map → chunk-4VTBZ2MF.js.map} +1 -1
  29. package/dist/{chunk-U5POE4BA.js → chunk-5Q7HA4JP.js} +3 -3
  30. package/dist/{chunk-U5POE4BA.js.map → chunk-5Q7HA4JP.js.map} +1 -1
  31. package/dist/{chunk-P43HBWKK.js → chunk-6BV24JPZ.js} +36 -7
  32. package/dist/chunk-6BV24JPZ.js.map +1 -0
  33. package/dist/{chunk-AM5LFRXJ.js → chunk-A7XP4C7C.js} +3 -3
  34. package/dist/{chunk-AM5LFRXJ.js.map → chunk-A7XP4C7C.js.map} +1 -1
  35. package/dist/{chunk-ZNIHTT22.js → chunk-AXFOJ2UG.js} +5 -5
  36. package/dist/{chunk-ZNIHTT22.js.map → chunk-AXFOJ2UG.js.map} +1 -1
  37. package/dist/{chunk-PKEAYYEJ.js → chunk-BCXI27BH.js} +219 -4
  38. package/dist/chunk-BCXI27BH.js.map +1 -0
  39. package/dist/{chunk-3HVASHBF.js → chunk-BJ7QIUBM.js} +6 -15
  40. package/dist/chunk-BJ7QIUBM.js.map +1 -0
  41. package/dist/{chunk-CH3UTJBT.js → chunk-BYPQHEI4.js} +6 -6
  42. package/dist/{chunk-CH3UTJBT.js.map → chunk-BYPQHEI4.js.map} +1 -1
  43. package/dist/{chunk-NWFZUQPF.js → chunk-DFZ6QENJ.js} +18 -18
  44. package/dist/{chunk-NWFZUQPF.js.map → chunk-DFZ6QENJ.js.map} +1 -1
  45. package/dist/{chunk-F5VREBV2.js → chunk-ELPR5XBG.js} +40 -3
  46. package/dist/chunk-ELPR5XBG.js.map +1 -0
  47. package/dist/{chunk-MWFYXUFK.js → chunk-G2CXWUO5.js} +4 -4
  48. package/dist/{chunk-MWFYXUFK.js.map → chunk-G2CXWUO5.js.map} +1 -1
  49. package/dist/{chunk-BEAIJRVF.js → chunk-GHWJHOYX.js} +4 -4
  50. package/dist/{chunk-BEAIJRVF.js.map → chunk-GHWJHOYX.js.map} +1 -1
  51. package/dist/{chunk-FLBDLF3I.js → chunk-HGFKNJA5.js} +6 -4
  52. package/dist/chunk-HGFKNJA5.js.map +1 -0
  53. package/dist/{chunk-BK3WL3QK.js → chunk-JAHHMZWG.js} +3 -3
  54. package/dist/{chunk-BK3WL3QK.js.map → chunk-JAHHMZWG.js.map} +1 -1
  55. package/dist/{chunk-UFY2HFLO.js → chunk-KBXYT5HD.js} +4 -4
  56. package/dist/{chunk-UFY2HFLO.js.map → chunk-KBXYT5HD.js.map} +1 -1
  57. package/dist/{chunk-DNYE3SSL.js → chunk-MR3LQTGA.js} +4 -4
  58. package/dist/{chunk-DNYE3SSL.js.map → chunk-MR3LQTGA.js.map} +1 -1
  59. package/dist/{chunk-HCNVX34E.js → chunk-OI36ITDV.js} +8 -8
  60. package/dist/{chunk-HCNVX34E.js.map → chunk-OI36ITDV.js.map} +1 -1
  61. package/dist/{chunk-BEA7RXI3.js → chunk-P6V5GORE.js} +230 -41
  62. package/dist/chunk-P6V5GORE.js.map +1 -0
  63. package/dist/{chunk-2OCYS5EP.js → chunk-PEGIQ67F.js} +4 -4
  64. package/dist/{chunk-2OCYS5EP.js.map → chunk-PEGIQ67F.js.map} +1 -1
  65. package/dist/{chunk-I7MKEZ6J.js → chunk-PHJ2DU6D.js} +3 -3
  66. package/dist/{chunk-I7MKEZ6J.js.map → chunk-PHJ2DU6D.js.map} +1 -1
  67. package/dist/{chunk-NLZYBWVH.js → chunk-POYF2P7E.js} +10 -10
  68. package/dist/{chunk-NLZYBWVH.js.map → chunk-POYF2P7E.js.map} +1 -1
  69. package/dist/{chunk-NU4E7C5I.js → chunk-PW4SJE3X.js} +3 -3
  70. package/dist/{chunk-NU4E7C5I.js.map → chunk-PW4SJE3X.js.map} +1 -1
  71. package/dist/{chunk-Q26C5GLO.js → chunk-RD6MMBHQ.js} +3 -3
  72. package/dist/{chunk-Q26C5GLO.js.map → chunk-RD6MMBHQ.js.map} +1 -1
  73. package/dist/{chunk-46LE3GNY.js → chunk-RUFTB7QN.js} +3 -3
  74. package/dist/{chunk-46LE3GNY.js.map → chunk-RUFTB7QN.js.map} +1 -1
  75. package/dist/{chunk-BKUANJB7.js → chunk-S5N33NGZ.js} +50 -64
  76. package/dist/chunk-S5N33NGZ.js.map +1 -0
  77. package/dist/{chunk-IAIHZRG7.js → chunk-SJQ7544V.js} +7 -7
  78. package/dist/{chunk-IAIHZRG7.js.map → chunk-SJQ7544V.js.map} +1 -1
  79. package/dist/{chunk-VT6HDD2L.js → chunk-SUGDZOYZ.js} +3 -3
  80. package/dist/{chunk-VT6HDD2L.js.map → chunk-SUGDZOYZ.js.map} +1 -1
  81. package/dist/{chunk-XVIFPGYH.js → chunk-U2KIY532.js} +3 -3
  82. package/dist/{chunk-XVIFPGYH.js.map → chunk-U2KIY532.js.map} +1 -1
  83. package/dist/{chunk-HWEW3VII.js → chunk-VFL4STB7.js} +3 -3
  84. package/dist/{chunk-HWEW3VII.js.map → chunk-VFL4STB7.js.map} +1 -1
  85. package/dist/{chunk-DYMWJAL4.js → chunk-VQ4P7UYE.js} +3 -3
  86. package/dist/{chunk-DYMWJAL4.js.map → chunk-VQ4P7UYE.js.map} +1 -1
  87. package/dist/{chunk-KPZZI2KG.js → chunk-ZCIK44M7.js} +3 -3
  88. package/dist/{chunk-KPZZI2KG.js.map → chunk-ZCIK44M7.js.map} +1 -1
  89. package/dist/cli/index.js +396 -409
  90. package/dist/cli/index.js.map +1 -1
  91. package/dist/cli/src/commands/complete-resolvers.d.ts +4 -0
  92. package/dist/cli/src/commands/complete-resolvers.d.ts.map +1 -1
  93. package/dist/cli/src/commands/flow.d.ts +8 -4
  94. package/dist/cli/src/commands/flow.d.ts.map +1 -1
  95. package/dist/cli/src/commands/run.d.ts.map +1 -1
  96. package/dist/cli/src/commands/validate.d.ts.map +1 -1
  97. package/dist/cli/src/flow-discovery.d.ts +31 -15
  98. package/dist/cli/src/flow-discovery.d.ts.map +1 -1
  99. package/dist/cli/src/paths.d.ts +9 -19
  100. package/dist/cli/src/paths.d.ts.map +1 -1
  101. package/dist/connectors/config.js +7 -7
  102. package/dist/connectors/index.js +14 -14
  103. package/dist/core/index.js +6 -6
  104. package/dist/core/logging.js +2 -2
  105. package/dist/core/manifest.js +2 -2
  106. package/dist/core/runtime-assets.js +4 -4
  107. package/dist/core/src/asset-roots.d.ts +74 -0
  108. package/dist/core/src/asset-roots.d.ts.map +1 -0
  109. package/dist/core/src/index.d.ts +1 -0
  110. package/dist/core/src/index.d.ts.map +1 -1
  111. package/dist/core/workspace-config.js +3 -3
  112. package/dist/deploy/index.js +6 -6
  113. package/dist/discovery/index.js +3 -3
  114. package/dist/{ensure-sources-IM3JMW2L.js → ensure-sources-O6AWQXAY.js} +13 -13
  115. package/dist/{ensure-sources-IM3JMW2L.js.map → ensure-sources-O6AWQXAY.js.map} +1 -1
  116. package/dist/factory-assets/connectors/box.js +14 -14
  117. package/dist/factory-assets/connectors/deploy.js +14 -14
  118. package/dist/factory-assets/connectors/devserver.js +14 -14
  119. package/dist/factory-assets/connectors/flow/CONNECTOR.md +42 -9
  120. package/dist/factory-assets/connectors/flow/adapter.d.ts +1 -1
  121. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  122. package/dist/factory-assets/connectors/flow/adapter.js +14 -14
  123. package/dist/factory-assets/connectors/flow/engine/index.d.ts +2 -0
  124. package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
  125. package/dist/factory-assets/connectors/flow/engine/locate.d.ts +75 -0
  126. package/dist/factory-assets/connectors/flow/engine/locate.d.ts.map +1 -0
  127. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts +56 -0
  128. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts.map +1 -1
  129. package/dist/factory-assets/connectors/flow/engine.js +8 -8
  130. package/dist/factory-assets/connectors/flow/index.d.ts +1 -1
  131. package/dist/factory-assets/connectors/flow/index.d.ts.map +1 -1
  132. package/dist/factory-assets/connectors/flow/node-executor.d.ts +23 -3
  133. package/dist/factory-assets/connectors/flow/node-executor.d.ts.map +1 -1
  134. package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts +4 -0
  135. package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts.map +1 -1
  136. package/dist/factory-assets/connectors/flow/prompt-fragments.js +2 -2
  137. package/dist/factory-assets/connectors/flow/run-flow.d.ts +9 -1
  138. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  139. package/dist/factory-assets/connectors/flow/run-flow.js +16 -16
  140. package/dist/factory-assets/connectors/flow.js +14 -14
  141. package/dist/factory-assets/connectors/git.js +14 -14
  142. package/dist/factory-assets/connectors/gmail.js +14 -14
  143. package/dist/factory-assets/connectors/googledrive.js +14 -14
  144. package/dist/factory-assets/connectors/local.js +14 -14
  145. package/dist/factory-assets/connectors/mattermost.js +14 -14
  146. package/dist/factory-assets/connectors/memory.js +14 -14
  147. package/dist/factory-assets/connectors/minio.js +14 -14
  148. package/dist/factory-assets/connectors/postgres.js +14 -14
  149. package/dist/factory-assets/connectors/s3.js +14 -14
  150. package/dist/factory-assets/connectors/sharepoint.js +14 -14
  151. package/dist/factory-assets/connectors/sqlite.js +14 -14
  152. package/dist/factory-assets/connectors/static-server.js +14 -14
  153. package/dist/factory-assets/connectors/tunnel.js +14 -14
  154. package/dist/factory-assets/connectors/webdav.js +14 -14
  155. package/dist/factory-assets/connectors/xstate-store.js +14 -14
  156. package/dist/factory-assets/connectors/xstate.js +14 -14
  157. package/dist/flows-66NOT5N6.js +20 -0
  158. package/dist/{flows-PBNW6BEH.js.map → flows-66NOT5N6.js.map} +1 -1
  159. package/dist/{helpers-LJFOH4RB.js → helpers-QUGRH2MW.js} +13 -13
  160. package/dist/{helpers-LJFOH4RB.js.map → helpers-QUGRH2MW.js.map} +1 -1
  161. package/dist/library/index.js +8 -8
  162. package/dist/library/install.js +6 -6
  163. package/dist/library/src/config.d.ts +6 -6
  164. package/dist/library/src/config.d.ts.map +1 -1
  165. package/dist/{library-publish-BEFA7OCS.js → library-publish-TCT652H4.js} +18 -18
  166. package/dist/{library-publish-BEFA7OCS.js.map → library-publish-TCT652H4.js.map} +1 -1
  167. package/dist/open-library-6OSZX2O6.js +32 -0
  168. package/dist/{open-library-WJ7P7B4N.js.map → open-library-6OSZX2O6.js.map} +1 -1
  169. package/dist/paths-ESJHWGBR.js +16 -0
  170. package/dist/{paths-2ZZMB7HU.js.map → paths-ESJHWGBR.js.map} +1 -1
  171. package/dist/{plugin-store-EOP3S7OU.js → plugin-store-3BYOBKYT.js} +8 -8
  172. package/dist/{plugin-store-EOP3S7OU.js.map → plugin-store-3BYOBKYT.js.map} +1 -1
  173. package/dist/{project-6RXDBSRV.js → project-5RGSHTZ7.js} +14 -14
  174. package/dist/{project-6RXDBSRV.js.map → project-5RGSHTZ7.js.map} +1 -1
  175. package/dist/resolver/index.js +7 -7
  176. package/dist/runner/index.js +19 -19
  177. package/dist/sdk/asset-manager.js +10 -10
  178. package/dist/sdk/bridge.js +9 -9
  179. package/dist/sdk/core.js +6 -6
  180. package/dist/sdk/flow.js +8 -8
  181. package/dist/sdk/index.js +19 -19
  182. package/dist/sdk/resolver.js +7 -7
  183. package/dist/sdk/runner.js +19 -19
  184. package/dist/sdk/session.js +1 -1
  185. package/dist/session/index.js +1 -1
  186. package/dist/session/src/dispatcher.d.ts +15 -0
  187. package/dist/session/src/dispatcher.d.ts.map +1 -1
  188. package/dist/session/src/workspace-change-digest.d.ts +34 -0
  189. package/dist/session/src/workspace-change-digest.d.ts.map +1 -0
  190. package/dist/{setup-XI7TCIGF.js → setup-X2T3NW7P.js} +11 -11
  191. package/dist/{setup-XI7TCIGF.js.map → setup-X2T3NW7P.js.map} +1 -1
  192. package/dist/skills-TYMTW4V4.js +20 -0
  193. package/dist/{skills-5PJ6YVM7.js.map → skills-TYMTW4V4.js.map} +1 -1
  194. package/dist/{source-TJ457ZRQ.js → source-JS3G5P6Z.js} +17 -17
  195. package/dist/{source-TJ457ZRQ.js.map → source-JS3G5P6Z.js.map} +1 -1
  196. package/dist/{source-manifest-publish-R3Q4MT5W.js → source-manifest-publish-Y7BOFFO4.js} +19 -19
  197. package/dist/{source-manifest-publish-R3Q4MT5W.js.map → source-manifest-publish-Y7BOFFO4.js.map} +1 -1
  198. package/dist/tui/index.js +19 -19
  199. package/dist/workspace-plugin/adapters/mcp.js +11 -11
  200. package/dist/workspace-plugin/adapters/omp.js +7 -7
  201. package/dist/workspace-plugin/index.js +3 -3
  202. package/package.json +1 -1
  203. package/dist/chunk-3HVASHBF.js.map +0 -1
  204. package/dist/chunk-57RFYEVM.js.map +0 -1
  205. package/dist/chunk-BEA7RXI3.js.map +0 -1
  206. package/dist/chunk-BKUANJB7.js.map +0 -1
  207. package/dist/chunk-F5VREBV2.js.map +0 -1
  208. package/dist/chunk-FLBDLF3I.js.map +0 -1
  209. package/dist/chunk-I7S6DFRU.js.map +0 -1
  210. package/dist/chunk-P43HBWKK.js.map +0 -1
  211. package/dist/chunk-PKEAYYEJ.js.map +0 -1
  212. package/dist/flows-PBNW6BEH.js +0 -20
  213. package/dist/open-library-WJ7P7B4N.js +0 -32
  214. package/dist/paths-2ZZMB7HU.js +0 -22
  215. package/dist/skills-5PJ6YVM7.js +0 -20
@@ -1,4 +1,4 @@
1
- import { fsDeadlineMs, withFsDeadline, tryWithFsDeadline } from './chunk-DYMWJAL4.js';
1
+ import { fsDeadlineMs, withFsDeadline, tryWithFsDeadline } from './chunk-VQ4P7UYE.js';
2
2
  import { createReadStream, createWriteStream } from 'fs';
3
3
  import { readdir, stat, rename, unlink } from 'fs/promises';
4
4
  import { join } from 'path';
@@ -292,5 +292,5 @@ async function probeResumeTranscript(sessionId, opts) {
292
292
  }
293
293
 
294
294
  export { CLOUD_SECRET_ENV_KEYS, SUPPORTED_CLOUDS, buildClaudeCloudEnv, probeResumeTranscript, resolveClaudeConfigDir, scrubPoisonedTranscript };
295
- //# sourceMappingURL=chunk-46LE3GNY.js.map
296
- //# sourceMappingURL=chunk-46LE3GNY.js.map
295
+ //# sourceMappingURL=chunk-RUFTB7QN.js.map
296
+ //# sourceMappingURL=chunk-RUFTB7QN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,SAAS,SAAS;AAuC5E,IAAM,qBAAA,GAAgF;AAAA,EAC3F,OAAA,EAAS;AAAA,IACP,mBAAA;AAAA,IACA,uBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,MAAA,EAAQ,CAAC,qCAAqC,CAAA;AAAA,EAC9C,KAAA,EAAO,CAAC,2BAA2B,CAAA;AAAA,EACnC,OAAA,EAAS,CAAC,sBAAA,EAAwB,mBAAmB;AACvD;AAaA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAuBrF,SAAS,oBAAoB,IAAA,EAQT;AACzB,EAAA,MAAM,EAAE,KAAA,EAAO,WAAA,EAAa,cAAc,OAAA,EAAS,SAAA,EAAW,gBAAe,GAAI,IAAA;AACjF,EAAA,MAAM,MAA8B,EAAE,GAAG,SAAS,GAAI,SAAA,IAAa,EAAC,EAAG;AAGvE,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,WAAW,GAAA,CAAI,oBAAA;AAAA,IACf,QAAQ,GAAA,CAAI,iBAAA;AAAA,IACZ,SAAS,GAAA,CAAI;AAAA,GACf;AAEA,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,EAAG;AAClC,IAAA,IAAI,kBAAkB,QAAA,CAAS,GAAG,KAAK,GAAA,CAAI,UAAA,CAAW,kBAAkB,CAAA,EAAG;AACzE,MAAA,OAAO,IAAI,GAAG,CAAA;AAAA,IAChB;AAAA,EACF;AAEA,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;AAwBzB,SAAS,uBAAuB,GAAA,EAAkD;AACvF,EAAA,OAAO,GAAA,EAAK,qBAAqB,OAAA,CAAQ,GAAA,CAAI,qBAAqBA,IAAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAC7F;AAgBA,eAAsB,qBAAA,CACpB,WACA,IAAA,EAKyC;AACzC,EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-46LE3GNY.js","sourcesContent":["/**\n * AI cloud-provider transport dimension for the `claude-sdk` driver.\n *\n * `cloud` is a config axis orthogonal to `provider` (model vendor) and\n * `driver` (agent runtime). Under `driver: claude-sdk` each non-default value\n * maps to one of the Claude Agent SDK's native env-var transports:\n * Amazon Bedrock, Google Vertex AI, Azure AI Foundry, or a generic\n * `ANTHROPIC_BASE_URL` gateway (LiteLLM / corporate proxy).\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\n/**\n * Canonical list of supported cloud transports. `\"default\"` (or an absent\n * `cloud` field) means the provider's native API — today's behavior, unchanged.\n *\n * The codec in `core/workspace-config.ts` keeps a local copy (`KNOWN_CLOUDS`)\n * to avoid an import cycle; a drift test asserts parity.\n *\n * @since 1.3.0\n */\nexport const SUPPORTED_CLOUDS = [\"default\", \"bedrock\", \"vertex\", \"azure\", \"gateway\"] as const;\n\n/** One of the supported cloud transport identifiers. */\nexport type CloudId = (typeof SUPPORTED_CLOUDS)[number];\n\n/**\n * Non-secret transport settings for a cloud. Sourced from skaile.yaml\n * `cloud_config` (snake_case on the wire, camelCase in-process — converted\n * exactly once at the settings/serve boundary).\n *\n * Must stay field-identical with core's `CloudTransportConfig` and the inline\n * `AgentSessionConfig.cloudConfig` shape (kept separate to avoid a core↔bridge\n * import cycle) — a field added here must be added there too.\n *\n * @since 1.3.0\n */\nexport interface CloudConfig {\n /** bedrock: AWS region (`AWS_REGION`); vertex: `CLOUD_ML_REGION`. */\n region?: string;\n /** vertex only: GCP project (`ANTHROPIC_VERTEX_PROJECT_ID`). */\n projectId?: string;\n /** azure only: Foundry resource name (`ANTHROPIC_FOUNDRY_RESOURCE`). */\n resource?: string;\n /** azure (alternative to `resource`) / gateway (required): endpoint base URL. */\n baseUrl?: string;\n}\n\n/**\n * Secret env keys that make up the credential bundle for each non-default\n * cloud. The platform delivers these env-keyed in the `session_init` secrets\n * map; the runner picks them out via `resolveCloudSecretBundle`.\n *\n * Vertex note: `GOOGLE_APPLICATION_CREDENTIALS_JSON` is our convention for the\n * raw service-account JSON blob. The runner materializes it to a 0600 file and\n * hands the driver `GOOGLE_APPLICATION_CREDENTIALS` (a path) instead — the\n * driver never sees the raw JSON.\n *\n * @since 1.3.0\n */\nexport const CLOUD_SECRET_ENV_KEYS: Record<Exclude<CloudId, \"default\">, readonly string[]> = {\n bedrock: [\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SESSION_TOKEN\",\n \"AWS_BEARER_TOKEN_BEDROCK\",\n ],\n vertex: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\"],\n azure: [\"ANTHROPIC_FOUNDRY_API_KEY\"],\n gateway: [\"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n};\n\n/**\n * Env vars scrubbed from the inherited environment before a non-default cloud\n * transport is assembled. Ambient first-party credentials or a stale\n * `CLAUDE_CODE_USE_*` flag must never leak into a Bedrock/Vertex/Foundry/\n * gateway session (the gateway branch re-adds its own carriers explicitly).\n *\n * Deliberately NOT exhaustive across clouds: ambient cloud-specific vars\n * (AWS_*, GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive\n * so a standalone CLI inherits its own cloud's environment; the SDK ignores\n * vars whose transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * Assemble the Claude Agent SDK child env for a non-default cloud transport.\n *\n * Pure function (no external state touched; the returned `env` is a fresh\n * object — inputs are never mutated): starts from `baseEnv` (caller passes a\n * copy of `process.env` with undefined stripped) merged with `configEnv`,\n * scrubs inherited Anthropic\n * credential/routing vars and every `CLAUDE_CODE_USE_*` flag, then sets exactly\n * one `CLAUDE_CODE_USE_*` flag (none for gateway) plus the cloud's credential\n * bundle and derived non-secret vars. AWS_* / GOOGLE_* ambient values are NOT\n * scrubbed, so a standalone CLI inherits ambient cloud credentials when no\n * explicit `cloudSecrets` bundle is provided. Gateway is the mirror case: its\n * carriers ARE the scrubbed Anthropic vars, so the gateway branch restores\n * them from `cloudSecrets` → `fallbackApiKey` (resolved `apiKeys.anthropic`)\n * → the pre-scrub config/ambient value — otherwise a standalone gateway\n * session would have no reachable auth carrier at all.\n *\n * Never returns `undefined` values; absent settings are simply omitted.\n *\n * @since 1.3.0\n */\nexport function buildClaudeCloudEnv(args: {\n cloud: Exclude<CloudId, \"default\">;\n cloudConfig?: CloudConfig;\n cloudSecrets?: Record<string, string>;\n baseEnv: Record<string, string>;\n configEnv?: Record<string, string>;\n /** Resolved API key (e.g. `apiKeys.anthropic`) — gateway auth fallback only. */\n fallbackApiKey?: string;\n}): Record<string, string> {\n const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — gateway falls back to these carriers.\n const ambient = {\n authToken: env.ANTHROPIC_AUTH_TOKEN,\n apiKey: env.ANTHROPIC_API_KEY,\n baseUrl: env.ANTHROPIC_BASE_URL,\n };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n switch (cloud) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // Explicit bundle values override ambient AWS_* (which survive the scrub\n // so a standalone CLI keeps its ambient credentials).\n for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);\n set(\"AWS_REGION\", cloudConfig?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // Runner-materialized SA file path; ambient GOOGLE_APPLICATION_CREDENTIALS\n // is kept when no bundle value is provided.\n set(\"GOOGLE_APPLICATION_CREDENTIALS\", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", cloudConfig?.projectId);\n set(\"CLOUD_ML_REGION\", cloudConfig?.region);\n break;\n }\n case \"azure\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);\n // Resource wins over base_url when both are configured.\n if (cloudConfig?.resource) {\n env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;\n } else {\n set(\"ANTHROPIC_FOUNDRY_BASE_URL\", cloudConfig?.baseUrl);\n }\n break;\n }\n case \"gateway\": {\n // No CLAUDE_CODE_USE_* flag — the gateway is addressed purely via\n // ANTHROPIC_BASE_URL plus an auth carrier. Explicit bundle wins;\n // standalone sessions fall back to the resolved key / ambient carriers.\n set(\"ANTHROPIC_BASE_URL\", cloudConfig?.baseUrl ?? ambient.baseUrl);\n const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;\n if (authToken) {\n env.ANTHROPIC_AUTH_TOKEN = authToken;\n } else {\n set(\n \"ANTHROPIC_API_KEY\",\n cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey,\n );\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,SAAS,SAAS;AAuC5E,IAAM,qBAAA,GAAgF;AAAA,EAC3F,OAAA,EAAS;AAAA,IACP,mBAAA;AAAA,IACA,uBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,MAAA,EAAQ,CAAC,qCAAqC,CAAA;AAAA,EAC9C,KAAA,EAAO,CAAC,2BAA2B,CAAA;AAAA,EACnC,OAAA,EAAS,CAAC,sBAAA,EAAwB,mBAAmB;AACvD;AAaA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAuBrF,SAAS,oBAAoB,IAAA,EAQT;AACzB,EAAA,MAAM,EAAE,KAAA,EAAO,WAAA,EAAa,cAAc,OAAA,EAAS,SAAA,EAAW,gBAAe,GAAI,IAAA;AACjF,EAAA,MAAM,MAA8B,EAAE,GAAG,SAAS,GAAI,SAAA,IAAa,EAAC,EAAG;AAGvE,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,WAAW,GAAA,CAAI,oBAAA;AAAA,IACf,QAAQ,GAAA,CAAI,iBAAA;AAAA,IACZ,SAAS,GAAA,CAAI;AAAA,GACf;AAEA,EAAA,K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EAAK,KAAK,gDAAA,EAAkD;AAAA,IAC1D,QAAA;AAAA,IACA,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,eAAe,MAAA,CAAO;AAAA,GACvB,CAAA;AACD,EAAA,OAAO,MAAA;AACT;ACtcA,IAAM,uBAAA,GAA0B,GAAA;AAwBzB,SAAS,uBAAuB,GAAA,EAAkD;AACvF,EAAA,OAAO,GAAA,EAAK,qBAAqB,OAAA,CAAQ,GAAA,CAAI,qBAAqBA,IAAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAC7F;AAgBA,eAAsB,qBAAA,CACpB,WACA,IAAA,EAKyC;AACzC,EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-RUFTB7QN.js","sourcesContent":["/**\n * AI cloud-provider transport dimension for the `claude-sdk` driver.\n *\n * `cloud` is a config axis orthogonal to `provider` (model vendor) and\n * `driver` (agent runtime). Under `driver: claude-sdk` each non-default value\n * maps to one of the Claude Agent SDK's native env-var transports:\n * Amazon Bedrock, Google Vertex AI, Azure AI Foundry, or a generic\n * `ANTHROPIC_BASE_URL` gateway (LiteLLM / corporate proxy).\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\n/**\n * Canonical list of supported cloud transports. `\"default\"` (or an absent\n * `cloud` field) means the provider's native API — today's behavior, unchanged.\n *\n * The codec in `core/workspace-config.ts` keeps a local copy (`KNOWN_CLOUDS`)\n * to avoid an import cycle; a drift test asserts parity.\n *\n * @since 1.3.0\n */\nexport const SUPPORTED_CLOUDS = [\"default\", \"bedrock\", \"vertex\", \"azure\", \"gateway\"] as const;\n\n/** One of the supported cloud transport identifiers. */\nexport type CloudId = (typeof SUPPORTED_CLOUDS)[number];\n\n/**\n * Non-secret transport settings for a cloud. Sourced from skaile.yaml\n * `cloud_config` (snake_case on the wire, camelCase in-process — converted\n * exactly once at the settings/serve boundary).\n *\n * Must stay field-identical with core's `CloudTransportConfig` and the inline\n * `AgentSessionConfig.cloudConfig` shape (kept separate to avoid a core↔bridge\n * import cycle) — a field added here must be added there too.\n *\n * @since 1.3.0\n */\nexport interface CloudConfig {\n /** bedrock: AWS region (`AWS_REGION`); vertex: `CLOUD_ML_REGION`. */\n region?: string;\n /** vertex only: GCP project (`ANTHROPIC_VERTEX_PROJECT_ID`). */\n projectId?: string;\n /** azure only: Foundry resource name (`ANTHROPIC_FOUNDRY_RESOURCE`). */\n resource?: string;\n /** azure (alternative to `resource`) / gateway (required): endpoint base URL. */\n baseUrl?: string;\n}\n\n/**\n * Secret env keys that make up the credential bundle for each non-default\n * cloud. The platform delivers these env-keyed in the `session_init` secrets\n * map; the runner picks them out via `resolveCloudSecretBundle`.\n *\n * Vertex note: `GOOGLE_APPLICATION_CREDENTIALS_JSON` is our convention for the\n * raw service-account JSON blob. The runner materializes it to a 0600 file and\n * hands the driver `GOOGLE_APPLICATION_CREDENTIALS` (a path) instead — the\n * driver never sees the raw JSON.\n *\n * @since 1.3.0\n */\nexport const CLOUD_SECRET_ENV_KEYS: Record<Exclude<CloudId, \"default\">, readonly string[]> = {\n bedrock: [\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SESSION_TOKEN\",\n \"AWS_BEARER_TOKEN_BEDROCK\",\n ],\n vertex: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\"],\n azure: [\"ANTHROPIC_FOUNDRY_API_KEY\"],\n gateway: [\"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n};\n\n/**\n * Env vars scrubbed from the inherited environment before a non-default cloud\n * transport is assembled. Ambient first-party credentials or a stale\n * `CLAUDE_CODE_USE_*` flag must never leak into a Bedrock/Vertex/Foundry/\n * gateway session (the gateway branch re-adds its own carriers explicitly).\n *\n * Deliberately NOT exhaustive across clouds: ambient cloud-specific vars\n * (AWS_*, GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive\n * so a standalone CLI inherits its own cloud's environment; the SDK ignores\n * vars whose transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * Assemble the Claude Agent SDK child env for a non-default cloud transport.\n *\n * Pure function (no external state touched; the returned `env` is a fresh\n * object — inputs are never mutated): starts from `baseEnv` (caller passes a\n * copy of `process.env` with undefined stripped) merged with `configEnv`,\n * scrubs inherited Anthropic\n * credential/routing vars and every `CLAUDE_CODE_USE_*` flag, then sets exactly\n * one `CLAUDE_CODE_USE_*` flag (none for gateway) plus the cloud's credential\n * bundle and derived non-secret vars. AWS_* / GOOGLE_* ambient values are NOT\n * scrubbed, so a standalone CLI inherits ambient cloud credentials when no\n * explicit `cloudSecrets` bundle is provided. Gateway is the mirror case: its\n * carriers ARE the scrubbed Anthropic vars, so the gateway branch restores\n * them from `cloudSecrets` → `fallbackApiKey` (resolved `apiKeys.anthropic`)\n * → the pre-scrub config/ambient value — otherwise a standalone gateway\n * session would have no reachable auth carrier at all.\n *\n * Never returns `undefined` values; absent settings are simply omitted.\n *\n * @since 1.3.0\n */\nexport function buildClaudeCloudEnv(args: {\n cloud: Exclude<CloudId, \"default\">;\n cloudConfig?: CloudConfig;\n cloudSecrets?: Record<string, string>;\n baseEnv: Record<string, string>;\n configEnv?: Record<string, string>;\n /** Resolved API key (e.g. `apiKeys.anthropic`) — gateway auth fallback only. */\n fallbackApiKey?: string;\n}): Record<string, string> {\n const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — gateway falls back to these carriers.\n const ambient = {\n authToken: env.ANTHROPIC_AUTH_TOKEN,\n apiKey: env.ANTHROPIC_API_KEY,\n baseUrl: env.ANTHROPIC_BASE_URL,\n };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n switch (cloud) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // Explicit bundle values override ambient AWS_* (which survive the scrub\n // so a standalone CLI keeps its ambient credentials).\n for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);\n set(\"AWS_REGION\", cloudConfig?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // Runner-materialized SA file path; ambient GOOGLE_APPLICATION_CREDENTIALS\n // is kept when no bundle value is provided.\n set(\"GOOGLE_APPLICATION_CREDENTIALS\", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", cloudConfig?.projectId);\n set(\"CLOUD_ML_REGION\", cloudConfig?.region);\n break;\n }\n case \"azure\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);\n // Resource wins over base_url when both are configured.\n if (cloudConfig?.resource) {\n env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;\n } else {\n set(\"ANTHROPIC_FOUNDRY_BASE_URL\", cloudConfig?.baseUrl);\n }\n break;\n }\n case \"gateway\": {\n // No CLAUDE_CODE_USE_* flag — the gateway is addressed purely via\n // ANTHROPIC_BASE_URL plus an auth carrier. Explicit bundle wins;\n // standalone sessions fall back to the resolved key / ambient carriers.\n set(\"ANTHROPIC_BASE_URL\", cloudConfig?.baseUrl ?? ambient.baseUrl);\n const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;\n if (authToken) {\n env.ANTHROPIC_AUTH_TOKEN = authToken;\n } else {\n set(\n \"ANTHROPIC_API_KEY\",\n cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey,\n );\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
@@ -1,13 +1,13 @@
1
1
  import { initTelemetry } from './chunk-4R6DROGN.js';
2
- import { parseSkillFrontmatter, validateFlowVersions } from './chunk-CZZRDYT4.js';
3
- import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner } from './chunk-BEA7RXI3.js';
4
- import { loadFlow } from './chunk-I7S6DFRU.js';
5
- import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-FLBDLF3I.js';
6
- import { nodeAssets } from './chunk-F5VREBV2.js';
7
- import { resolveSettings, resolveApiKey } from './chunk-P43HBWKK.js';
8
- import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-Q26C5GLO.js';
2
+ import { parseSkillFrontmatter, validateFlowVersions } from './chunk-4VTBZ2MF.js';
3
+ import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner } from './chunk-P6V5GORE.js';
4
+ import { loadFlow, flowLookupRoots, findFlowFileInRoots, FLOW_FILE_EXTENSIONS } from './chunk-3Q7JDLLH.js';
5
+ import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-HGFKNJA5.js';
6
+ import { flowSkillVersionPins } from './chunk-ELPR5XBG.js';
7
+ import { resolveSettings, resolveApiKey } from './chunk-6BV24JPZ.js';
8
+ import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-RD6MMBHQ.js';
9
9
  import { isValidAssetName } from './chunk-GEEW6SY2.js';
10
- import { createLogger } from './chunk-7GOCNYUV.js';
10
+ import { createLogger } from './chunk-3A5IKBHQ.js';
11
11
  import fs from 'fs';
12
12
  import path from 'path';
13
13
  import * as z from 'zod';
@@ -373,31 +373,7 @@ async function resumeFlow(opts) {
373
373
  }
374
374
  }
375
375
  async function validatePinnedVersions(flow, projectDir, log) {
376
- const pinnedNodes = flow.nodes.flatMap((node) => {
377
- const fromAssets = nodeAssets(node).flatMap((asset) => {
378
- if (!asset.startsWith("skill:")) return [];
379
- const hashIndex = asset.lastIndexOf("#");
380
- if (hashIndex <= "skill:".length || hashIndex === asset.length - 1) return [];
381
- const identity = asset.slice("skill:".length, hashIndex);
382
- const skillId = identity.slice(identity.lastIndexOf("/") + 1);
383
- return [
384
- {
385
- nodeId: node.id,
386
- skillId,
387
- requestedVersion: asset.slice(hashIndex + 1)
388
- }
389
- ];
390
- });
391
- if (fromAssets.length > 0) return fromAssets;
392
- if (node.type !== "skill" || !node.data?.version) return [];
393
- return [
394
- {
395
- nodeId: node.id,
396
- skillId: node.data.skill ?? node.id,
397
- requestedVersion: node.data.version
398
- }
399
- ];
400
- });
376
+ const pinnedNodes = flowSkillVersionPins(flow);
401
377
  if (pinnedNodes.length === 0) return;
402
378
  const skillVersions = /* @__PURE__ */ new Map();
403
379
  const aiResourcesDir = findAiResourcesDir(projectDir);
@@ -426,41 +402,51 @@ ${lines.join("\n")}`);
426
402
  log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);
427
403
  }
428
404
  }
405
+ function assertContainedInAnyRoot(found, roots, flowId) {
406
+ const resolved = path.resolve(found);
407
+ const inside = roots.some((root) => {
408
+ const relative = path.relative(path.resolve(root), resolved);
409
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
410
+ });
411
+ if (!inside) {
412
+ throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);
413
+ }
414
+ }
415
+ function describeMisses(misses, heading) {
416
+ const seen = /* @__PURE__ */ new Set();
417
+ const lines = [];
418
+ for (const miss of misses) {
419
+ if (seen.has(miss.path)) continue;
420
+ seen.add(miss.path);
421
+ lines.push(
422
+ miss.reason === "id-mismatch" ? ` ${miss.path}: declares id ${JSON.stringify(miss.declaredId ?? "")}` : ` ${miss.path}: could not be parsed (${miss.error ?? "unknown error"})`
423
+ );
424
+ }
425
+ return lines.length > 0 ? `
426
+ ${heading}
427
+ ${lines.join("\n")}` : "";
428
+ }
429
429
  function resolveFlowPath(flowId, projectDir) {
430
430
  if (!isValidAssetName(flowId)) {
431
431
  throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);
432
432
  }
433
- const contained = (root, ...segments) => {
434
- const resolvedRoot = path.resolve(root);
435
- const candidate = path.resolve(resolvedRoot, ...segments);
436
- const relative = path.relative(resolvedRoot, candidate);
437
- if (relative.startsWith("..") || path.isAbsolute(relative)) {
438
- throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);
439
- }
440
- return candidate;
441
- };
442
- const flowRoot = path.resolve(projectDir, ".skaile", "flows");
443
- const armInstalled = contained(flowRoot, flowId, `${flowId}.flow.yaml`);
444
- if (fs.existsSync(armInstalled)) return armInstalled;
445
- const manual = contained(flowRoot, `${flowId}.flow.yaml`);
446
- if (fs.existsSync(manual)) return manual;
447
- let dir = projectDir;
448
- for (let i = 0; i < 6; i++) {
449
- const aiResources = path.join(dir, "ai-assets");
450
- if (fs.existsSync(aiResources)) {
451
- for (const domain of fs.readdirSync(aiResources)) {
452
- const flowsDir = path.join(aiResources, domain, "flows");
453
- const candidate = contained(flowsDir, `${flowId}.flow.yaml`);
454
- if (fs.existsSync(candidate)) return candidate;
455
- const legacy = contained(flowsDir, `${flowId}.json`);
456
- if (fs.existsSync(legacy)) return legacy;
457
- }
458
- throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);
459
- }
460
- dir = path.dirname(dir);
433
+ const roots = flowLookupRoots(projectDir);
434
+ const misses = [];
435
+ const found = findFlowFileInRoots(flowId, roots, { onMiss: (m) => misses.push(m) });
436
+ if (found) {
437
+ assertContainedInAnyRoot(found, roots, flowId);
438
+ return found;
439
+ }
440
+ if (misses.length > 0 && misses.every((m) => m.reason === "unparseable")) {
441
+ throw new Error(
442
+ `Flow ${flowId} was found but could not be loaded.` + describeMisses(misses, "Candidates:")
443
+ );
461
444
  }
445
+ const shown = roots.slice(0, 3).join(", ");
446
+ const more = roots.length > 3 ? ", \u2026" : "";
447
+ const accepted = FLOW_FILE_EXTENSIONS.map((ext) => `${flowId}${ext}`).join(" | ");
462
448
  throw new Error(
463
- `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`
449
+ `Flow not found: ${flowId}. Searched ${roots.length} root(s) (${shown || "none"}${more}) for ${accepted} \u2014 flat, or inside a ${flowId}/ directory.` + describeMisses(misses, "Near misses:")
464
450
  );
465
451
  }
466
452
  function findAiResourcesDir(projectDir) {
@@ -526,5 +512,5 @@ function walkForSkill(dir, skillId) {
526
512
  }
527
513
 
528
514
  export { resolveFlowPath, resumeFlow, runFlow };
529
- //# sourceMappingURL=chunk-BKUANJB7.js.map
530
- //# sourceMappingURL=chunk-BKUANJB7.js.map
515
+ //# sourceMappingURL=chunk-S5N33NGZ.js.map
516
+ //# sourceMappingURL=chunk-S5N33NGZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;AAoEA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2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":"chunk-S5N33NGZ.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 isValidAssetName,\n resolveAgentDir,\n resolveApiKey,\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 } 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 {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} 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 driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\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 provider: opts.provider,\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 provider: settings.provider,\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 as { logging?: unknown }).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) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\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 provider: session.provider,\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 credential path the session driver used: `resolveApiKey` against the\n // same already-resolved `settings` — not a new resolution, not a new secret\n // channel. CLI runs never set a non-default cloud transport (createAgentSession\n // above passes none), so cloud/cloudConfig/cloudSecrets are intentionally omitted.\n const subpromptRunner = new SessionSubpromptRunner({\n driverType: agentSession.driverType,\n provider: agentSession.provider,\n sessionModel: agentSession.model,\n workspaceDir: opts.projectDir,\n apiKey: resolveApiKey(agentSession.provider ?? \"anthropic\", settings),\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 rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\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 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 awaitAgentEnd(\n driver,\n buildOrchestratorPrompt(childFlow, execution, stimulus),\n opts.onEvent,\n 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.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // 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 const fullPrompt = buildOrchestratorPrompt(flow, execution, stimulus);\n await ensureDriverStarted();\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\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 as { logging?: unknown }).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 provider: session.provider,\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.` +\n 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 by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\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 `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction 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 else if (event.type === \"error\") {\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,6 +1,6 @@
1
- import { logErr, logOk, colorRef, logInfo, S, logWarn, formatSoftDepHint } from './chunk-XVIFPGYH.js';
2
- import { AssetManager } from './chunk-HCNVX34E.js';
3
- import { readLock } from './chunk-P43HBWKK.js';
1
+ import { logErr, logOk, colorRef, logInfo, S, logWarn, formatSoftDepHint } from './chunk-U2KIY532.js';
2
+ import { AssetManager } from './chunk-OI36ITDV.js';
3
+ import { readLock } from './chunk-6BV24JPZ.js';
4
4
  import { SUPPORTED_DRIVER_TARGETS } from './chunk-MENCWIHW.js';
5
5
  import { parseAssetRef } from './chunk-GEEW6SY2.js';
6
6
  import path from 'path';
@@ -82,7 +82,7 @@ async function runRefInstall(ref, opts) {
82
82
  const spinner2 = p.spinner();
83
83
  spinner2.start(`Installing ${ref}`);
84
84
  try {
85
- const { openCatalogSource, openLibrary } = await import('./open-library-WJ7P7B4N.js');
85
+ const { openCatalogSource, openLibrary } = await import('./open-library-6OSZX2O6.js');
86
86
  const catalog = await openCatalogSource({ projectDir: path.resolve(opts.projectDir) });
87
87
  if (!supportsInstallManifest(catalog)) {
88
88
  throw new Error(
@@ -122,7 +122,7 @@ async function runYamlInstall(opts) {
122
122
  return;
123
123
  }
124
124
  try {
125
- const { ensureSourcesCloned } = await import('./ensure-sources-IM3JMW2L.js');
125
+ const { ensureSourcesCloned } = await import('./ensure-sources-O6AWQXAY.js');
126
126
  const hydrate = ensureSourcesCloned(projectDir, { quiet: true });
127
127
  if (hydrate.cloned.length > 0) {
128
128
  logOk(`Cloned source(s): ${hydrate.cloned.join(", ")}`);
@@ -288,5 +288,5 @@ function makeCleanCommand() {
288
288
  }
289
289
 
290
290
  export { makeCheckCommand, makeCleanCommand, makeInstallCommand, reportInstalledSoftDeps, runPointerOnlyInstall, supportsInstallManifest };
291
- //# sourceMappingURL=chunk-IAIHZRG7.js.map
292
- //# sourceMappingURL=chunk-IAIHZRG7.js.map
291
+ //# sourceMappingURL=chunk-SJQ7544V.js.map
292
+ //# sourceMappingURL=chunk-SJQ7544V.js.map