@relayflows/sdk 2.0.8 → 2.0.10

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 (474) hide show
  1. package/dist/adapters/base.d.ts +46 -0
  2. package/dist/adapters/base.d.ts.map +1 -0
  3. package/dist/adapters/base.js +15 -0
  4. package/dist/adapters/base.js.map +1 -0
  5. package/dist/adapters/claude.d.ts +5 -0
  6. package/dist/adapters/claude.d.ts.map +1 -0
  7. package/dist/adapters/claude.js +44 -0
  8. package/dist/adapters/claude.js.map +1 -0
  9. package/dist/adapters/codex.d.ts +5 -0
  10. package/dist/adapters/codex.d.ts.map +1 -0
  11. package/dist/adapters/codex.js +45 -0
  12. package/dist/adapters/codex.js.map +1 -0
  13. package/dist/adapters/index.d.ts +14 -0
  14. package/dist/adapters/index.d.ts.map +1 -0
  15. package/dist/adapters/index.js +29 -0
  16. package/dist/adapters/index.js.map +1 -0
  17. package/dist/adapters/wrapper.d.ts +12 -0
  18. package/dist/adapters/wrapper.d.ts.map +1 -0
  19. package/dist/adapters/wrapper.js +31 -0
  20. package/dist/adapters/wrapper.js.map +1 -0
  21. package/dist/agent-relay-transport.d.ts +84 -0
  22. package/dist/agent-relay-transport.d.ts.map +1 -0
  23. package/dist/agent-relay-transport.js +134 -0
  24. package/dist/agent-relay-transport.js.map +1 -0
  25. package/dist/authored-budget.d.ts +13 -0
  26. package/dist/authored-budget.d.ts.map +1 -0
  27. package/dist/authored-budget.js +78 -0
  28. package/dist/authored-budget.js.map +1 -0
  29. package/dist/authored-flow-error.d.ts +1 -1
  30. package/dist/authored-flow-error.d.ts.map +1 -1
  31. package/dist/authored-flow-error.js.map +1 -1
  32. package/dist/authored-flow-executor.d.ts +13 -7
  33. package/dist/authored-flow-executor.d.ts.map +1 -1
  34. package/dist/authored-flow-executor.js +115 -194
  35. package/dist/authored-flow-executor.js.map +1 -1
  36. package/dist/authored-flow-loader.d.ts +10 -1
  37. package/dist/authored-flow-loader.d.ts.map +1 -1
  38. package/dist/authored-flow-loader.js +56 -3
  39. package/dist/authored-flow-loader.js.map +1 -1
  40. package/dist/authored-flow-operation.d.ts +9 -1
  41. package/dist/authored-flow-operation.d.ts.map +1 -1
  42. package/dist/authored-flow-operation.js +35 -4
  43. package/dist/authored-flow-operation.js.map +1 -1
  44. package/dist/authored-helper-effect.d.ts +12 -0
  45. package/dist/authored-helper-effect.d.ts.map +1 -0
  46. package/dist/authored-helper-effect.js +144 -0
  47. package/dist/authored-helper-effect.js.map +1 -0
  48. package/dist/authored-mcp.d.ts +17 -0
  49. package/dist/authored-mcp.d.ts.map +1 -0
  50. package/dist/authored-mcp.js +171 -0
  51. package/dist/authored-mcp.js.map +1 -0
  52. package/dist/authored-memory.d.ts +7 -0
  53. package/dist/authored-memory.d.ts.map +1 -0
  54. package/dist/authored-memory.js +60 -0
  55. package/dist/authored-memory.js.map +1 -0
  56. package/dist/authored-plugin-effect.d.ts +16 -0
  57. package/dist/authored-plugin-effect.d.ts.map +1 -0
  58. package/dist/authored-plugin-effect.js +163 -0
  59. package/dist/authored-plugin-effect.js.map +1 -0
  60. package/dist/authored-step-output.d.ts +23 -0
  61. package/dist/authored-step-output.d.ts.map +1 -0
  62. package/dist/authored-step-output.js +67 -0
  63. package/dist/authored-step-output.js.map +1 -0
  64. package/dist/authored-worker-step.d.ts +15 -0
  65. package/dist/authored-worker-step.d.ts.map +1 -0
  66. package/dist/authored-worker-step.js +136 -0
  67. package/dist/authored-worker-step.js.map +1 -0
  68. package/dist/budget-preflight.d.ts +5 -0
  69. package/dist/budget-preflight.d.ts.map +1 -0
  70. package/dist/budget-preflight.js +33 -0
  71. package/dist/budget-preflight.js.map +1 -0
  72. package/dist/budget.d.ts +14 -0
  73. package/dist/budget.d.ts.map +1 -0
  74. package/dist/budget.js +52 -0
  75. package/dist/budget.js.map +1 -0
  76. package/dist/bundle-transport.d.ts +18 -0
  77. package/dist/bundle-transport.d.ts.map +1 -0
  78. package/dist/bundle-transport.js +111 -0
  79. package/dist/bundle-transport.js.map +1 -0
  80. package/dist/bundle-typescript.d.ts +8 -0
  81. package/dist/bundle-typescript.d.ts.map +1 -0
  82. package/dist/bundle-typescript.js +108 -0
  83. package/dist/bundle-typescript.js.map +1 -0
  84. package/dist/bundle.d.ts +25 -0
  85. package/dist/bundle.d.ts.map +1 -0
  86. package/dist/bundle.js +199 -0
  87. package/dist/bundle.js.map +1 -0
  88. package/dist/child-stop.d.ts +59 -0
  89. package/dist/child-stop.d.ts.map +1 -0
  90. package/dist/child-stop.js +94 -0
  91. package/dist/child-stop.js.map +1 -0
  92. package/dist/cli/add.d.ts +6 -0
  93. package/dist/cli/add.d.ts.map +1 -0
  94. package/dist/cli/add.js +47 -0
  95. package/dist/cli/add.js.map +1 -0
  96. package/dist/cli/build.d.ts +13 -0
  97. package/dist/cli/build.d.ts.map +1 -0
  98. package/dist/cli/build.js +224 -0
  99. package/dist/cli/build.js.map +1 -0
  100. package/dist/cli/bundle-preflight.d.ts +5 -0
  101. package/dist/cli/bundle-preflight.d.ts.map +1 -0
  102. package/dist/cli/bundle-preflight.js +28 -0
  103. package/dist/cli/bundle-preflight.js.map +1 -0
  104. package/dist/cli/check-helper-body.d.ts +4 -0
  105. package/dist/cli/check-helper-body.d.ts.map +1 -0
  106. package/dist/cli/check-helper-body.js +15 -0
  107. package/dist/cli/check-helper-body.js.map +1 -0
  108. package/dist/cli/check-triggers.d.ts +14 -0
  109. package/dist/cli/check-triggers.d.ts.map +1 -0
  110. package/dist/cli/check-triggers.js +37 -0
  111. package/dist/cli/check-triggers.js.map +1 -0
  112. package/dist/cli/check-typescript.d.ts +20 -0
  113. package/dist/cli/check-typescript.d.ts.map +1 -0
  114. package/dist/cli/check-typescript.js +54 -0
  115. package/dist/cli/check-typescript.js.map +1 -0
  116. package/dist/cli/check.d.ts +36 -3
  117. package/dist/cli/check.d.ts.map +1 -1
  118. package/dist/cli/check.js +122 -11
  119. package/dist/cli/check.js.map +1 -1
  120. package/dist/cli/cloud-run.d.ts +8 -0
  121. package/dist/cli/cloud-run.d.ts.map +1 -0
  122. package/dist/cli/cloud-run.js +50 -0
  123. package/dist/cli/cloud-run.js.map +1 -0
  124. package/dist/cli/deploy.d.ts +9 -0
  125. package/dist/cli/deploy.d.ts.map +1 -0
  126. package/dist/cli/deploy.js +58 -0
  127. package/dist/cli/deploy.js.map +1 -0
  128. package/dist/cli/deterministic-failure.d.ts +5 -0
  129. package/dist/cli/deterministic-failure.d.ts.map +1 -0
  130. package/dist/cli/deterministic-failure.js +66 -0
  131. package/dist/cli/deterministic-failure.js.map +1 -0
  132. package/dist/cli/direct-run.d.ts.map +1 -1
  133. package/dist/cli/direct-run.js +83 -7
  134. package/dist/cli/direct-run.js.map +1 -1
  135. package/dist/cli/hn-monitor.d.ts.map +1 -1
  136. package/dist/cli/hn-monitor.js +2 -1
  137. package/dist/cli/hn-monitor.js.map +1 -1
  138. package/dist/cli/replay.d.ts +12 -0
  139. package/dist/cli/replay.d.ts.map +1 -0
  140. package/dist/cli/replay.js +82 -0
  141. package/dist/cli/replay.js.map +1 -0
  142. package/dist/cli/reuse.d.ts +8 -0
  143. package/dist/cli/reuse.d.ts.map +1 -0
  144. package/dist/cli/reuse.js +25 -0
  145. package/dist/cli/reuse.js.map +1 -0
  146. package/dist/cli/run-digest.d.ts +4 -0
  147. package/dist/cli/run-digest.d.ts.map +1 -0
  148. package/dist/cli/run-digest.js +24 -0
  149. package/dist/cli/run-digest.js.map +1 -0
  150. package/dist/cli/run.d.ts +16 -5
  151. package/dist/cli/run.d.ts.map +1 -1
  152. package/dist/cli/run.js +99 -17
  153. package/dist/cli/run.js.map +1 -1
  154. package/dist/cli/serve-webhook.d.ts +40 -0
  155. package/dist/cli/serve-webhook.d.ts.map +1 -0
  156. package/dist/cli/serve-webhook.js +233 -0
  157. package/dist/cli/serve-webhook.js.map +1 -0
  158. package/dist/cli/tick-runner.d.ts.map +1 -1
  159. package/dist/cli/tick-runner.js +2 -1
  160. package/dist/cli/tick-runner.js.map +1 -1
  161. package/dist/cli-adapter.d.ts +8 -14
  162. package/dist/cli-adapter.d.ts.map +1 -1
  163. package/dist/cli-adapter.js +19 -64
  164. package/dist/cli-adapter.js.map +1 -1
  165. package/dist/cli-watch.d.ts +13 -0
  166. package/dist/cli-watch.d.ts.map +1 -0
  167. package/dist/cli-watch.js +185 -0
  168. package/dist/cli-watch.js.map +1 -0
  169. package/dist/cli.d.ts +4 -0
  170. package/dist/cli.d.ts.map +1 -1
  171. package/dist/cli.js +387 -14
  172. package/dist/cli.js.map +1 -1
  173. package/dist/cloud-http.d.ts +22 -0
  174. package/dist/cloud-http.d.ts.map +1 -0
  175. package/dist/cloud-http.js +84 -0
  176. package/dist/cloud-http.js.map +1 -0
  177. package/dist/cloud-run.d.ts +38 -0
  178. package/dist/cloud-run.d.ts.map +1 -0
  179. package/dist/cloud-run.js +112 -0
  180. package/dist/cloud-run.js.map +1 -0
  181. package/dist/compile.d.ts +21 -3
  182. package/dist/compile.d.ts.map +1 -1
  183. package/dist/compile.js +97 -23
  184. package/dist/compile.js.map +1 -1
  185. package/dist/create-flow.d.ts +17 -0
  186. package/dist/create-flow.d.ts.map +1 -0
  187. package/dist/create-flow.js +72 -0
  188. package/dist/create-flow.js.map +1 -0
  189. package/dist/daemon-connection.d.ts +14 -0
  190. package/dist/daemon-connection.d.ts.map +1 -1
  191. package/dist/daemon-connection.js +33 -1
  192. package/dist/daemon-connection.js.map +1 -1
  193. package/dist/demo-hn-monitor.js +2 -1
  194. package/dist/demo-hn-monitor.js.map +1 -1
  195. package/dist/effect-channel.d.ts +30 -0
  196. package/dist/effect-channel.d.ts.map +1 -0
  197. package/dist/effect-channel.js +71 -0
  198. package/dist/effect-channel.js.map +1 -0
  199. package/dist/failure-kinds.d.ts +14 -3
  200. package/dist/failure-kinds.d.ts.map +1 -1
  201. package/dist/failure-kinds.js +27 -0
  202. package/dist/failure-kinds.js.map +1 -1
  203. package/dist/gate-contract.d.ts.map +1 -1
  204. package/dist/gate-contract.js +9 -0
  205. package/dist/gate-contract.js.map +1 -1
  206. package/dist/helper-preflight.d.ts +18 -0
  207. package/dist/helper-preflight.d.ts.map +1 -0
  208. package/dist/helper-preflight.js +32 -0
  209. package/dist/helper-preflight.js.map +1 -0
  210. package/dist/helper-storage.d.ts +5 -0
  211. package/dist/helper-storage.d.ts.map +1 -0
  212. package/dist/helper-storage.js +31 -0
  213. package/dist/helper-storage.js.map +1 -0
  214. package/dist/helper-writeback.d.ts +12 -0
  215. package/dist/helper-writeback.d.ts.map +1 -0
  216. package/dist/helper-writeback.js +95 -0
  217. package/dist/helper-writeback.js.map +1 -0
  218. package/dist/index.d.ts +10 -2
  219. package/dist/index.d.ts.map +1 -1
  220. package/dist/index.js +7 -1
  221. package/dist/index.js.map +1 -1
  222. package/dist/input-binding.d.ts +4 -0
  223. package/dist/input-binding.d.ts.map +1 -0
  224. package/dist/input-binding.js +78 -0
  225. package/dist/input-binding.js.map +1 -0
  226. package/dist/journal-client.d.ts +12 -4
  227. package/dist/journal-client.d.ts.map +1 -1
  228. package/dist/journal-client.js +17 -6
  229. package/dist/journal-client.js.map +1 -1
  230. package/dist/journal-offset.d.ts +3 -0
  231. package/dist/journal-offset.d.ts.map +1 -0
  232. package/dist/journal-offset.js +69 -0
  233. package/dist/journal-offset.js.map +1 -0
  234. package/dist/journal-reader.d.ts +30 -0
  235. package/dist/journal-reader.d.ts.map +1 -0
  236. package/dist/journal-reader.js +156 -0
  237. package/dist/journal-reader.js.map +1 -0
  238. package/dist/json-schema.d.ts +2 -0
  239. package/dist/json-schema.d.ts.map +1 -1
  240. package/dist/json-schema.js +38 -22
  241. package/dist/json-schema.js.map +1 -1
  242. package/dist/llm-worker.d.ts +16 -0
  243. package/dist/llm-worker.d.ts.map +1 -0
  244. package/dist/llm-worker.js +79 -0
  245. package/dist/llm-worker.js.map +1 -0
  246. package/dist/local-agent.d.ts +8 -0
  247. package/dist/local-agent.d.ts.map +1 -0
  248. package/dist/local-agent.js +25 -0
  249. package/dist/local-agent.js.map +1 -0
  250. package/dist/mcp-client.d.ts +15 -0
  251. package/dist/mcp-client.d.ts.map +1 -0
  252. package/dist/mcp-client.js +104 -0
  253. package/dist/mcp-client.js.map +1 -0
  254. package/dist/mcp-config.d.ts +4 -0
  255. package/dist/mcp-config.d.ts.map +1 -0
  256. package/dist/mcp-config.js +61 -0
  257. package/dist/mcp-config.js.map +1 -0
  258. package/dist/mcp-stdio.d.ts +24 -0
  259. package/dist/mcp-stdio.d.ts.map +1 -0
  260. package/dist/mcp-stdio.js +89 -0
  261. package/dist/mcp-stdio.js.map +1 -0
  262. package/dist/model-pricing.d.ts +22 -0
  263. package/dist/model-pricing.d.ts.map +1 -0
  264. package/dist/model-pricing.js +30 -0
  265. package/dist/model-pricing.js.map +1 -0
  266. package/dist/mount-registry.d.ts +9 -0
  267. package/dist/mount-registry.d.ts.map +1 -0
  268. package/dist/mount-registry.js +47 -0
  269. package/dist/mount-registry.js.map +1 -0
  270. package/dist/named-gate-lowering.d.ts +9 -0
  271. package/dist/named-gate-lowering.d.ts.map +1 -0
  272. package/dist/named-gate-lowering.js +152 -0
  273. package/dist/named-gate-lowering.js.map +1 -0
  274. package/dist/named-gates.d.ts +10 -0
  275. package/dist/named-gates.d.ts.map +1 -0
  276. package/dist/named-gates.js +69 -0
  277. package/dist/named-gates.js.map +1 -0
  278. package/dist/observer-link.d.ts +129 -0
  279. package/dist/observer-link.d.ts.map +1 -0
  280. package/dist/observer-link.js +274 -0
  281. package/dist/observer-link.js.map +1 -0
  282. package/dist/plugin-loader.d.ts +13 -0
  283. package/dist/plugin-loader.d.ts.map +1 -0
  284. package/dist/plugin-loader.js +110 -0
  285. package/dist/plugin-loader.js.map +1 -0
  286. package/dist/plugin-manifest.d.ts +27 -0
  287. package/dist/plugin-manifest.d.ts.map +1 -0
  288. package/dist/plugin-manifest.js +89 -0
  289. package/dist/plugin-manifest.js.map +1 -0
  290. package/dist/preflight.d.ts +26 -2
  291. package/dist/preflight.d.ts.map +1 -1
  292. package/dist/preflight.js +175 -1
  293. package/dist/preflight.js.map +1 -1
  294. package/dist/progress.d.ts +14 -0
  295. package/dist/progress.d.ts.map +1 -0
  296. package/dist/progress.js +39 -0
  297. package/dist/progress.js.map +1 -0
  298. package/dist/protocol.d.ts +11 -0
  299. package/dist/protocol.d.ts.map +1 -1
  300. package/dist/pty-sidechannel.d.ts +14 -0
  301. package/dist/pty-sidechannel.d.ts.map +1 -0
  302. package/dist/pty-sidechannel.js +103 -0
  303. package/dist/pty-sidechannel.js.map +1 -0
  304. package/dist/scope-compiler.d.ts +52 -0
  305. package/dist/scope-compiler.d.ts.map +1 -0
  306. package/dist/scope-compiler.js +62 -0
  307. package/dist/scope-compiler.js.map +1 -0
  308. package/dist/slack-preflight.d.ts +6 -0
  309. package/dist/slack-preflight.d.ts.map +1 -0
  310. package/dist/slack-preflight.js +28 -0
  311. package/dist/slack-preflight.js.map +1 -0
  312. package/dist/slack-writeback.d.ts +40 -0
  313. package/dist/slack-writeback.d.ts.map +1 -0
  314. package/dist/slack-writeback.js +60 -0
  315. package/dist/slack-writeback.js.map +1 -0
  316. package/dist/spec.d.ts +134 -4
  317. package/dist/spec.d.ts.map +1 -1
  318. package/dist/spec.js.map +1 -1
  319. package/dist/step-dependencies.d.ts.map +1 -1
  320. package/dist/step-dependencies.js +2 -1
  321. package/dist/step-dependencies.js.map +1 -1
  322. package/dist/step-fields.d.ts +4 -4
  323. package/dist/step-fields.d.ts.map +1 -1
  324. package/dist/step-fields.js +5 -2
  325. package/dist/step-fields.js.map +1 -1
  326. package/dist/trigger-executor.d.ts +7 -0
  327. package/dist/trigger-executor.d.ts.map +1 -0
  328. package/dist/trigger-executor.js +35 -0
  329. package/dist/trigger-executor.js.map +1 -0
  330. package/dist/validate.d.ts.map +1 -1
  331. package/dist/validate.js +53 -6
  332. package/dist/validate.js.map +1 -1
  333. package/dist/webhook-rate-limit.d.ts +29 -0
  334. package/dist/webhook-rate-limit.d.ts.map +1 -0
  335. package/dist/webhook-rate-limit.js +38 -0
  336. package/dist/webhook-rate-limit.js.map +1 -0
  337. package/dist/webhook-signature.d.ts +22 -0
  338. package/dist/webhook-signature.d.ts.map +1 -0
  339. package/dist/webhook-signature.js +53 -0
  340. package/dist/webhook-signature.js.map +1 -0
  341. package/dist/worker-cli.d.ts +13 -1
  342. package/dist/worker-cli.d.ts.map +1 -1
  343. package/dist/worker-cli.js +133 -12
  344. package/dist/worker-cli.js.map +1 -1
  345. package/dist/worker-input.d.ts +4 -0
  346. package/dist/worker-input.d.ts.map +1 -0
  347. package/dist/worker-input.js +14 -0
  348. package/dist/worker-input.js.map +1 -0
  349. package/dist/worker-lease.d.ts +5 -0
  350. package/dist/worker-lease.d.ts.map +1 -0
  351. package/dist/worker-lease.js +80 -0
  352. package/dist/worker-lease.js.map +1 -0
  353. package/dist/worker-spend.d.ts +19 -0
  354. package/dist/worker-spend.d.ts.map +1 -0
  355. package/dist/worker-spend.js +22 -0
  356. package/dist/worker-spend.js.map +1 -0
  357. package/dist/worker-usage.d.ts +7 -0
  358. package/dist/worker-usage.d.ts.map +1 -0
  359. package/dist/worker-usage.js +54 -0
  360. package/dist/worker-usage.js.map +1 -0
  361. package/dist/worker.d.ts +2 -0
  362. package/dist/worker.d.ts.map +1 -1
  363. package/dist/worker.js +22 -8
  364. package/dist/worker.js.map +1 -1
  365. package/dist/wrapper-session.d.ts +1 -1
  366. package/dist/wrapper-session.d.ts.map +1 -1
  367. package/dist/wrapper-session.js +56 -19
  368. package/dist/wrapper-session.js.map +1 -1
  369. package/dist/yaml-helper-effect.d.ts +8 -0
  370. package/dist/yaml-helper-effect.d.ts.map +1 -0
  371. package/dist/yaml-helper-effect.js +79 -0
  372. package/dist/yaml-helper-effect.js.map +1 -0
  373. package/dist/yaml-helpers.d.ts +18 -0
  374. package/dist/yaml-helpers.d.ts.map +1 -0
  375. package/dist/yaml-helpers.js +116 -0
  376. package/dist/yaml-helpers.js.map +1 -0
  377. package/package.json +19 -2
  378. package/src/adapters/base.ts +53 -0
  379. package/src/adapters/claude.ts +55 -0
  380. package/src/adapters/codex.ts +56 -0
  381. package/src/adapters/index.ts +36 -0
  382. package/src/adapters/wrapper.ts +42 -0
  383. package/src/agent-relay-transport.ts +187 -0
  384. package/src/authored-budget.ts +69 -0
  385. package/src/authored-flow-error.ts +10 -0
  386. package/src/authored-flow-executor.ts +170 -293
  387. package/src/authored-flow-loader.ts +60 -3
  388. package/src/authored-flow-operation.ts +38 -5
  389. package/src/authored-helper-effect.ts +143 -0
  390. package/src/authored-mcp.ts +166 -0
  391. package/src/authored-memory.ts +55 -0
  392. package/src/authored-plugin-effect.ts +152 -0
  393. package/src/authored-step-output.ts +107 -0
  394. package/src/authored-worker-step.ts +181 -0
  395. package/src/budget-preflight.ts +31 -0
  396. package/src/budget.ts +49 -0
  397. package/src/bundle-transport.ts +79 -0
  398. package/src/bundle-typescript.ts +98 -0
  399. package/src/bundle.ts +182 -0
  400. package/src/child-stop.ts +138 -0
  401. package/src/cli/add.ts +45 -0
  402. package/src/cli/build.ts +214 -0
  403. package/src/cli/bundle-preflight.ts +28 -0
  404. package/src/cli/check-helper-body.ts +14 -0
  405. package/src/cli/check-triggers.ts +41 -0
  406. package/src/cli/check-typescript.ts +63 -0
  407. package/src/cli/check.ts +132 -14
  408. package/src/cli/cloud-run.ts +47 -0
  409. package/src/cli/deploy.ts +52 -0
  410. package/src/cli/deterministic-failure.ts +69 -0
  411. package/src/cli/direct-run.ts +79 -7
  412. package/src/cli/hn-monitor.ts +2 -1
  413. package/src/cli/replay.ts +81 -0
  414. package/src/cli/reuse.ts +23 -0
  415. package/src/cli/run-digest.ts +24 -0
  416. package/src/cli/run.ts +104 -21
  417. package/src/cli/serve-webhook.ts +246 -0
  418. package/src/cli/tick-runner.ts +2 -1
  419. package/src/cli-adapter.ts +31 -74
  420. package/src/cli-watch.ts +174 -0
  421. package/src/cli.ts +396 -17
  422. package/src/cloud-http.ts +100 -0
  423. package/src/cloud-run.ts +137 -0
  424. package/src/compile.ts +102 -23
  425. package/src/create-flow.ts +82 -0
  426. package/src/daemon-connection.ts +32 -1
  427. package/src/demo-hn-monitor.ts +2 -1
  428. package/src/effect-channel.ts +97 -0
  429. package/src/failure-kinds.ts +38 -0
  430. package/src/gate-contract.ts +7 -0
  431. package/src/helper-preflight.ts +34 -0
  432. package/src/helper-storage.ts +23 -0
  433. package/src/helper-writeback.ts +83 -0
  434. package/src/index.ts +26 -0
  435. package/src/input-binding.ts +76 -0
  436. package/src/journal-client.ts +20 -7
  437. package/src/journal-offset.ts +60 -0
  438. package/src/journal-reader.ts +165 -0
  439. package/src/json-schema.ts +34 -18
  440. package/src/llm-worker.ts +82 -0
  441. package/src/local-agent.ts +30 -0
  442. package/src/mcp-client.ts +97 -0
  443. package/src/mcp-config.ts +42 -0
  444. package/src/mcp-stdio.ts +84 -0
  445. package/src/model-pricing.ts +32 -0
  446. package/src/mount-registry.ts +44 -0
  447. package/src/named-gate-lowering.ts +147 -0
  448. package/src/named-gates.ts +76 -0
  449. package/src/observer-link.ts +368 -0
  450. package/src/plugin-loader.ts +88 -0
  451. package/src/plugin-manifest.ts +76 -0
  452. package/src/preflight.ts +178 -4
  453. package/src/progress.ts +51 -0
  454. package/src/protocol.ts +12 -0
  455. package/src/pty-sidechannel.ts +92 -0
  456. package/src/scope-compiler.ts +105 -0
  457. package/src/slack-preflight.ts +25 -0
  458. package/src/slack-writeback.ts +63 -0
  459. package/src/spec.ts +112 -4
  460. package/src/step-dependencies.ts +3 -1
  461. package/src/step-fields.ts +5 -2
  462. package/src/trigger-executor.ts +34 -0
  463. package/src/validate.ts +47 -6
  464. package/src/webhook-rate-limit.ts +69 -0
  465. package/src/webhook-signature.ts +74 -0
  466. package/src/worker-cli.ts +156 -11
  467. package/src/worker-input.ts +15 -0
  468. package/src/worker-lease.ts +85 -0
  469. package/src/worker-spend.ts +23 -0
  470. package/src/worker-usage.ts +48 -0
  471. package/src/worker.ts +27 -9
  472. package/src/wrapper-session.ts +50 -15
  473. package/src/yaml-helper-effect.ts +78 -0
  474. package/src/yaml-helpers.ts +131 -0
@@ -1,6 +1,6 @@
1
- import { accessSync, constants } from 'node:fs';
1
+ import { accessSync, constants, realpathSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
- import { resolve } from 'node:path';
3
+ import { dirname, resolve } from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import {
6
6
  getAuthoredFlowDefinition,
@@ -9,7 +9,7 @@ import {
9
9
  } from './authored-flow.js';
10
10
 
11
11
  export class AuthoredFlowLoadError extends Error {
12
- constructor(message: string) {
12
+ constructor(message: string, readonly kind: 'invalid_spec' | 'use_not_found' | 'use_invalid' | 'use_cycle' = 'invalid_spec') {
13
13
  super(message);
14
14
  this.name = 'AuthoredFlowLoadError';
15
15
  }
@@ -28,10 +28,67 @@ export interface LoadedAuthoredFlow {
28
28
  * `getAuthoredFlowDefinition` import.
29
29
  */
30
30
  readonly getDefinition: GetFlowDefinition;
31
+ /** Dependency-first load order, each canonical absolute path appearing once. */
32
+ readonly graph: readonly LoadedAuthoredFlowNode[];
33
+ }
34
+
35
+ export interface LoadedAuthoredFlowNode {
36
+ readonly path: string;
37
+ readonly handle: FlowHandle;
38
+ readonly getDefinition: GetFlowDefinition;
39
+ readonly use: readonly string[];
31
40
  }
32
41
 
33
42
  /** Import and validate a direct-run module without executing its authored body. */
34
43
  export async function loadAuthoredFlow(path: string): Promise<LoadedAuthoredFlow> {
44
+ const loaded = new Map<string, LoadedAuthoredFlowNode>();
45
+ const visiting = new Set<string>();
46
+ async function visit(sourcePath: string, isRoot = false): Promise<LoadedAuthoredFlowNode> {
47
+ let absolutePath: string;
48
+ try {
49
+ absolutePath = realpathSync(sourcePath);
50
+ accessSync(absolutePath, constants.R_OK);
51
+ } catch {
52
+ throw new AuthoredFlowLoadError(`Flow "${sourcePath}" is not readable.`, isRoot ? 'invalid_spec' : 'use_not_found');
53
+ }
54
+ if (visiting.has(absolutePath)) {
55
+ throw new AuthoredFlowLoadError(`Flow use cycle: ${[...visiting, absolutePath].join(' -> ')}`, 'use_cycle');
56
+ }
57
+ const cached = loaded.get(absolutePath);
58
+ if (cached !== undefined) return cached;
59
+ visiting.add(absolutePath);
60
+ try {
61
+ const { handle, getDefinition } = await importAuthoredFlow(absolutePath);
62
+ const dependencies: string[] = [];
63
+ for (const entry of getDefinition(handle).header.use ?? []) {
64
+ // Validate again at the SDK boundary: the author's surface package may
65
+ // be a different version from the runtime loading the graph.
66
+ if (!/^(?:\.\/|\.\.\/).+\.flow\.ts$/.test(entry) || /[?#\\\\]/.test(entry)) {
67
+ throw new AuthoredFlowLoadError(`Flow "${absolutePath}" use must contain relative .flow.ts paths.`, 'use_invalid');
68
+ }
69
+ const child = await visit(resolve(dirname(absolutePath), entry));
70
+ if (dependencies.includes(child.path)) {
71
+ throw new AuthoredFlowLoadError(`Flow "${absolutePath}" declares the same use path more than once.`, 'use_invalid');
72
+ }
73
+ dependencies.push(child.path);
74
+ }
75
+ const node = Object.freeze({ path: absolutePath, handle, getDefinition, use: Object.freeze(dependencies) });
76
+ loaded.set(absolutePath, node);
77
+ return node;
78
+ } catch (error) {
79
+ if (error instanceof AuthoredFlowLoadError && error.kind === 'invalid_spec' && !isRoot) {
80
+ throw new AuthoredFlowLoadError(error.message, 'use_invalid');
81
+ }
82
+ throw error;
83
+ } finally {
84
+ visiting.delete(absolutePath);
85
+ }
86
+ }
87
+ const root = await visit(resolve(path), true);
88
+ return Object.freeze({ handle: root.handle, getDefinition: root.getDefinition, graph: Object.freeze([...loaded.values()]) });
89
+ }
90
+
91
+ async function importAuthoredFlow(path: string): Promise<Pick<LoadedAuthoredFlow, 'handle' | 'getDefinition'>> {
35
92
  const absolutePath = resolve(path);
36
93
  try {
37
94
  accessSync(absolutePath, constants.R_OK);
@@ -1,17 +1,36 @@
1
1
  import { executionAsyncId } from 'node:async_hooks';
2
- import type { Step } from '@relayflows/surface';
2
+ import type { NamedGate, Step } from '@relayflows/surface';
3
3
  import { AuthoredFlowExecutionError } from './authored-flow-error.js';
4
4
  import {
5
5
  AuthoredFlowLifecycle,
6
6
  type AuthoredOperationInvocation,
7
7
  } from './authored-flow-lifecycle.js';
8
8
 
9
+ /** Slice-P kinds the surface `.gate(config)` accepts and the SDK lowers. */
10
+ const NAMED_GATE_KINDS = new Set([
11
+ 'references_input', 'subprocess_gate', 'word_count_bounds', 'regex_match',
12
+ ]);
13
+
14
+ function isNamedGateConfig(candidate: unknown): candidate is NamedGate {
15
+ return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate)
16
+ && typeof (candidate as { type?: unknown }).type === 'string'
17
+ && NAMED_GATE_KINDS.has((candidate as { type: string }).type);
18
+ }
19
+
9
20
  type OperationState = 'created' | 'running' | 'fulfilled' | 'rejected';
10
21
  const nativePromiseThen = Promise.prototype.then;
11
22
 
12
23
  /** A root authored operation whose outcome cannot be hidden by promise handlers. */
13
24
  export class AuthoredFlowOperation<T> {
14
25
  readonly step: Step<T>;
26
+ /**
27
+ * Named-gate config attached via `.gate({type: '…', …})`. The start closure
28
+ * reads this at spec-build time and injects it into the compiled StepSpec's
29
+ * `verification:` field — journal-honest via slice P's named-gate lowering.
30
+ * Undefined means no postfix gate (default behavior). Predicate `.gate(fn)`
31
+ * still throws `unsupported_gate` and never sets this field.
32
+ */
33
+ namedGate: NamedGate | undefined = undefined;
15
34
  private state: OperationState = 'created';
16
35
  private thenInvoked = false;
17
36
  private rootFailureRecorded = false;
@@ -40,11 +59,21 @@ export class AuthoredFlowOperation<T> {
40
59
 
41
60
  observeRejection(this.promise, (error) => this.recordRootFailure(error));
42
61
  const operation = this;
43
- this.step = Object.freeze({
44
- gate(): never {
62
+ const step: Step<T> = {
63
+ gate(configOrPredicate: NamedGate | ((value: T) => boolean), _because?: string): Step<T> {
64
+ if (isNamedGateConfig(configOrPredicate)) {
65
+ // Config-object gate: lowers into the compiled StepSpec's
66
+ // `verification:` field via slice-P named-gate lowering.
67
+ operation.namedGate = configOrPredicate;
68
+ return step;
69
+ }
70
+ // Predicate gate: closures cannot be journaled (covenant 1
71
+ // journal-as-truth). Refuse — authors should use a config-object
72
+ // gate or the declarative `verification:` block.
45
73
  throw new AuthoredFlowExecutionError(
46
74
  'unsupported_gate',
47
- 'postfix gates are not lowered by the initial authored executor',
75
+ 'postfix .gate(predicate) closures cannot be journaled; '
76
+ + 'use .gate({type: "…", …}) with a slice-P named gate instead.',
48
77
  );
49
78
  },
50
79
  then<TResult1 = T, TResult2 = never>(
@@ -64,7 +93,11 @@ export class AuthoredFlowOperation<T> {
64
93
  (error) => operation.recordCallbackFailure(error),
65
94
  );
66
95
  },
67
- });
96
+ };
97
+ // Freeze the `then`/`gate` method table so the surface's Step contract
98
+ // stays intact, but keep `namedGate` reachable via the enclosing
99
+ // operation reference (not through the surface Step handle).
100
+ this.step = Object.freeze(step);
68
101
  this.scope.registerStep(this.step, this);
69
102
  }
70
103
 
@@ -0,0 +1,143 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { JournalClient } from './journal-client.js';
5
+ import { AuthoredFlowExecutionError, type AuthoredFlowExecutionErrorCode } from './authored-flow-error.js';
6
+ import { readCompletedStepOutput } from './authored-step-output.js';
7
+ import type { AuthoredFlowJournalStep } from './authored-flow-executor.js';
8
+ import { compileSpec, toKernelSpec } from './compile.js';
9
+ import { SPEC_SCHEMA_VERSION, type KernelAgentStep } from './spec.js';
10
+ import type { StepDispatchEvent } from './protocol.js';
11
+ import { withWorkerLease } from './worker-lease.js';
12
+ import { helperProviders, type HelperCall } from '@relayflows/surface/runtime';
13
+ import { helperWriteback, HelperDeliveryError } from './helper-writeback.js';
14
+ import { checkSlackHelpers } from './slack-preflight.js';
15
+ import { atomicJson, readSlackReceipt, receiptPath, slackWriteback, type SlackCall } from './slack-writeback.js';
16
+
17
+ type ProviderCall = HelperCall | SlackCall;
18
+
19
+ export function assertHelperCredentials(provider: string): void {
20
+ const namespace = helperProviders.find(p => p.provider === provider)?.namespace;
21
+ if (!namespace) throw new AuthoredFlowExecutionError('helper_provider.unsupported', `Unknown helper ${provider}`);
22
+ const report = checkSlackHelpers({ header: { tools: { [namespace]: true } }, body() {} });
23
+ if (!report.ok) {
24
+ const diagnostic = report.diagnostics[0]!;
25
+ throw new AuthoredFlowExecutionError(
26
+ diagnostic.kind as AuthoredFlowExecutionErrorCode, diagnostic.message);
27
+ }
28
+ }
29
+
30
+ /** Each helper uses the existing agent lease + effect protocol; no new kernel verb. */
31
+ export async function runHelperEffect(
32
+ journal: JournalClient, name: string, stepId: string, call: ProviderCall,
33
+ dataDir: string, journalSteps: AuthoredFlowJournalStep[],
34
+ ): Promise<unknown> {
35
+ assertHelperCredentials(call.provider);
36
+ if (call.provider === 'notion' && call.verb === 'appendBlock' && process.env.RELAYFLOWS_NOTION_MOCK !== '1') {
37
+ throw new AuthoredFlowExecutionError('helper_provider.unsupported', 'Notion appendBlock has no upstream mount writeback route');
38
+ }
39
+ const stream = `${call.provider}-helper-${randomUUID()}`;
40
+ const spec = toKernelSpec(compileSpec({
41
+ version: SPEC_SCHEMA_VERSION, name: `${name}/${stepId}`,
42
+ steps: [{ id: stepId, type: 'agent', instruction: JSON.stringify(call),
43
+ maxIterations: 3, recoveryMode: 'reset',
44
+ surfaces: { streams: [{ stream }], external: [`/${call.provider}`] } }],
45
+ }));
46
+ const outcome = await journal.runStart(spec);
47
+ await atomicJson(join(dataDir, 'helper-runs', `${outcome.run_id}.json`), { provider: call.provider });
48
+ await driveHelperEffect(journal, outcome.run_id, spec.steps[0] as KernelAgentStep, call, dataDir);
49
+ const output = await readCompletedStepOutput(journal, outcome.run_id, stepId, journalSteps);
50
+ return (output as { receipt: unknown }).receipt;
51
+ }
52
+
53
+ /** Recognize only the journaled helper envelope, so ordinary agent runs keep their worker path. */
54
+ export async function resumeHelperEffect(journal: JournalClient, runId: string, dataDir: string): Promise<boolean> {
55
+ if (!/^[A-Za-z0-9_-]+$/.test(runId) || !existsSync(join(dataDir, 'helper-runs', `${runId}.json`))) return false;
56
+ const entries = (await journal.journalRead(runId, 1)).entries as Array<{
57
+ entry_type: string; payload: { spec?: { steps?: KernelAgentStep[] } };
58
+ }>;
59
+ const steps = entries.find(entry => entry.entry_type === 'run.spawned')?.payload.spec?.steps;
60
+ if (steps?.length !== 1) return false;
61
+ const step = steps[0]!;
62
+ if (step.type !== 'agent' || !step.surfaces?.streams?.[0]?.stream.includes('-helper-')) return false;
63
+ const call = JSON.parse(step.instruction) as ProviderCall;
64
+ if (call.type !== 'effect' || !helperProviders.some(p => p.provider === call.provider && p.supported)) return false;
65
+ const snapshot = await journal.runGet(runId);
66
+ if (snapshot.status === 'completed' || snapshot.status === 'failed') return true;
67
+ assertHelperCredentials(call.provider);
68
+ await driveHelperEffect(journal, runId, step, call, dataDir);
69
+ return true;
70
+ }
71
+
72
+ async function driveHelperEffect(
73
+ journal: JournalClient, runId: string, step: KernelAgentStep, call: ProviderCall, dataDir: string,
74
+ ): Promise<void> {
75
+ const client = new JournalClient(journal.socketPath);
76
+ const stream = step.surfaces!.streams![0]!.stream;
77
+ const pins = { workspace: [], streams: [{ stream, read_offset: 0 }] };
78
+ let resolve!: () => void;
79
+ let reject!: (error: unknown) => void;
80
+ const completed = new Promise<void>((yes, no) => { resolve = yes; reject = no; });
81
+ // Observe early dispatch failures even while attach/run.resume is still pending.
82
+ void completed.catch(() => undefined);
83
+ let executing = false;
84
+ client.on('step.dispatch', (dispatch: StepDispatchEvent) => {
85
+ if (executing || dispatch.run_id !== runId || dispatch.step_id !== step.id) return;
86
+ executing = true;
87
+ void completeHelperDispatch(client, dispatch, call, dataDir).then(resolve, reject);
88
+ });
89
+ client.on('error', reject);
90
+ try {
91
+ await client.connect();
92
+ await client.hello('flows-provider-helper');
93
+ await client.workerAttach(`${call.provider}-${randomUUID()}`, ['agent'], pins, 1);
94
+ const outcome = await journal.runResume(runId);
95
+ if (outcome.status === 'completed') return;
96
+ if (outcome.status === 'failed') {
97
+ throw new AuthoredFlowExecutionError('step_failed', `Helper run ${runId} ${outcome.status}`, undefined, runId);
98
+ }
99
+ await completed;
100
+ } catch (error) {
101
+ if (error instanceof AuthoredFlowExecutionError) throw error;
102
+ throw new AuthoredFlowExecutionError('step_failed', error instanceof Error ? error.message : 'Helper effect failed', 'worker_error', runId);
103
+ } finally { client.close(); }
104
+ }
105
+
106
+ async function completeHelperDispatch(client: JournalClient, dispatch: StepDispatchEvent, call: ProviderCall, dataDir: string): Promise<void> {
107
+ let output: unknown;
108
+ try {
109
+ output = await withWorkerLease(client, dispatch, async signal => {
110
+ const file = receiptPath(dataDir, dispatch.run_id, dispatch.step_id);
111
+ let receipt: unknown;
112
+ await client.performEffect({
113
+ runId: dispatch.run_id, stepId: dispatch.step_id, attempt: dispatch.attempt,
114
+ idempotencyKey: dispatch.idempotency_key, surfacePath: `/${call.provider}`,
115
+ revisionBefore: 'pending', revisionAfter: `${dispatch.run_id}:${dispatch.step_id}`,
116
+ }, async () => {
117
+ try { receipt = await readSlackReceipt(file); }
118
+ catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
120
+ receipt = await (call.provider === 'slack' && 'params' in call
121
+ ? slackWriteback(call, dataDir, dispatch.run_id, dispatch.step_id, signal)
122
+ : helperWriteback(call as HelperCall, dataDir, dispatch.run_id, dispatch.step_id, signal));
123
+ await atomicJson(file, receipt);
124
+ }
125
+ signal.throwIfAborted();
126
+ });
127
+ // Also required after a confirmed election followed by a crash before step.complete.
128
+ if (receipt === undefined) receipt = await readSlackReceipt(file);
129
+ return { ...call, idempotencyKey: `${dispatch.run_id}:${dispatch.step_id}`, receipt };
130
+ });
131
+ } catch (error) {
132
+ if (!(error instanceof HelperDeliveryError)) throw error;
133
+ await client.stepComplete(dispatch.run_id, dispatch.step_id, dispatch.attempt,
134
+ dispatch.idempotency_key, 'worker_error', {
135
+ output: { ...call, diagnostic: error.message },
136
+ started_pins: dispatch.pins, end_pins: dispatch.pins, effects: [],
137
+ });
138
+ return;
139
+ }
140
+ await client.stepComplete(dispatch.run_id, dispatch.step_id, dispatch.attempt,
141
+ dispatch.idempotency_key, 'success', { output, started_pins: dispatch.pins, end_pins: dispatch.pins,
142
+ effects: [{ surface_path: `/${call.provider}`, idempotency_key: dispatch.idempotency_key }] });
143
+ }
@@ -0,0 +1,166 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import type { Ctx, Step } from '@relayflows/surface';
3
+ import { compileSpec, toKernelSpec } from './compile.js';
4
+ import { snapshotJsonValue } from './json-value.js';
5
+ import { McpError, openMcpSession } from './mcp-client.js';
6
+ import type { McpServerConfig } from './spec.js';
7
+ import { SPEC_SCHEMA_VERSION } from './spec.js';
8
+ import type { JournalClient } from './journal-client.js';
9
+ import type { StepDispatchEvent } from './protocol.js';
10
+ import { AuthoredFlowExecutionError } from './authored-flow-error.js';
11
+ import type { AuthoredFlowJournalStep } from './authored-flow-executor.js';
12
+ import { readCompletedStepOutput } from './authored-step-output.js';
13
+ import { withWorkerLease } from './worker-lease.js';
14
+
15
+ /** Own keys expose precisely the preflight inventory, including prototype-like names. */
16
+ export function buildMcpProxy(
17
+ inventory: Readonly<Record<string, readonly string[]>>,
18
+ invoke: (server: string, tool: string, args: unknown, known: boolean) => Step<unknown>,
19
+ ): Ctx['mcp'] {
20
+ const servers: Record<string, Record<string, (args: unknown) => Step<unknown>>> = Object.create(null);
21
+ for (const [server, names] of Object.entries(inventory)) {
22
+ const tools: Record<string, (args: unknown) => Step<unknown>> = Object.create(null);
23
+ const call = (tool: string, known: boolean) => (args: unknown) =>
24
+ invoke(server, tool, snapshotJsonValue(args, `f.mcp.${server}.${tool} arguments`), known);
25
+ for (const tool of names) tools[tool] = call(tool, true);
26
+ servers[server] = new Proxy(Object.freeze(tools), {
27
+ get(target, key) {
28
+ if (typeof key !== 'string') return undefined;
29
+ if (Object.hasOwn(target, key)) return target[key];
30
+ // Calling a tool outside the inventory still creates an operation,
31
+ // so worker_error is journaled like other runtime failures.
32
+ return call(key, false);
33
+ },
34
+ });
35
+ }
36
+ return Object.freeze(servers);
37
+ }
38
+
39
+ export class McpStepError extends AuthoredFlowExecutionError {
40
+ constructor(readonly diagnostic: string, runId: string) {
41
+ super('step_failed', diagnostic, 'worker_error', runId);
42
+ }
43
+ }
44
+
45
+ /** Helpers lower to an existing agent effect, never a fourth kernel primitive.
46
+ * The MCP receipt lives in step.completed.output: { type, input, output, ... }.
47
+ * A private stream routes the step to this short-lived SDK worker exclusively.
48
+ */
49
+ export async function runMcpEffect(
50
+ journal: JournalClient, flowName: string, id: string, server: string, tool: string,
51
+ args: unknown, known: boolean, config: McpServerConfig,
52
+ journalSteps: AuthoredFlowJournalStep[],
53
+ ): Promise<unknown> {
54
+ const idempotencyKey = `mcp:${server}:${tool}:${createHash('sha256').update(JSON.stringify(args)).digest('hex')}`;
55
+ const surfacePath = `/mcp/${pathPart(server)}/${pathPart(tool)}`;
56
+ const stream = `mcp-worker-${randomUUID()}`;
57
+ const instruction = JSON.stringify({ type: 'mcp', server, tool, input: args });
58
+ const peer = journal.createPeer();
59
+ let diagnostic: string | undefined;
60
+ let settled!: () => void;
61
+ let failed!: (error: unknown) => void;
62
+ const completed = new Promise<void>((resolve, reject) => { settled = resolve; failed = reject; });
63
+ void completed.catch(() => undefined);
64
+ let timer: ReturnType<typeof setTimeout> | undefined;
65
+ let work: Promise<void> | undefined;
66
+ let dispatchExpired = false;
67
+ const dispatch = (event: StepDispatchEvent): void => {
68
+ if (dispatchExpired) return;
69
+ const dispatched = event.spec as { instruction?: string; surfaces?: { streams?: { stream: string }[] } };
70
+ if (event.step_id !== id || event.step_type !== 'agent' || work !== undefined
71
+ || dispatched?.instruction !== instruction
72
+ || !dispatched.surfaces?.streams?.some(pin => pin.stream === stream)) {
73
+ failed(new Error('MCP worker received an unexpected dispatch'));
74
+ return;
75
+ }
76
+ clearTimeout(timer);
77
+ timer = undefined;
78
+ work = execute(event);
79
+ void work.then(settled, failed);
80
+ };
81
+ async function execute(event: StepDispatchEvent): Promise<void> {
82
+ const receipt = { type: 'mcp' as const, server, tool, input: args, idempotencyKey };
83
+ let output: unknown;
84
+ let confirmed = false;
85
+ try {
86
+ if (!known) throw new Error('mcp_unknown_tool');
87
+ // Renew the worker lease while the MCP tool is in flight. Without this,
88
+ // a tool that runs longer than the initial lease loses ownership and
89
+ // the write-back path fails — see worker-lease.ts for the renewal contract.
90
+ confirmed = await withWorkerLease(peer, event, async () => {
91
+ return peer.performEffect({
92
+ runId: event.run_id, stepId: id, attempt: event.attempt, idempotencyKey: event.idempotency_key,
93
+ surfacePath, revisionBefore: 'pending', revisionAfter: idempotencyKey,
94
+ }, async () => {
95
+ const session = await openMcpSession(config, 10_000);
96
+ try {
97
+ output = await session.callTool(tool, args);
98
+ if (typeof output === 'object' && output !== null && 'isError' in output && output.isError === true) {
99
+ throw new Error('mcp_tool_error');
100
+ }
101
+ } finally { await session.close(); }
102
+ });
103
+ });
104
+ // A confirmed election without its receipt is an interrupted writeback,
105
+ // not a successful result we may invent or a call we may safely repeat.
106
+ if (!confirmed) throw new Error('mcp_result_unavailable');
107
+ } catch (error) {
108
+ if (error instanceof McpError) diagnostic = error.code;
109
+ else if (error instanceof Error && ['mcp_unknown_tool', 'mcp_tool_error', 'mcp_result_unavailable'].includes(error.message)) diagnostic = error.message;
110
+ else throw error; // Journal failures remain fail-closed, never provider errors.
111
+ }
112
+ await peer.stepComplete(event.run_id, id, event.attempt, event.idempotency_key,
113
+ diagnostic === undefined ? 'success' : 'worker_error', {
114
+ output: { ...receipt, output: output ?? null, ...(diagnostic ? { diagnostic } : {}) },
115
+ started_pins: event.pins, end_pins: event.pins,
116
+ ...(diagnostic ? { trajectory_tail: { ...receipt, diagnostic } } : {}),
117
+ effects: confirmed ? [{ surface_path: surfacePath, idempotency_key: event.idempotency_key }] : [],
118
+ });
119
+ }
120
+ let childRunId: string | undefined;
121
+ try {
122
+ await peer.connect();
123
+ await peer.hello('flows-mcp');
124
+ peer.on('step.dispatch', dispatch);
125
+ await peer.workerAttach(stream, ['agent'], { workspace: [], streams: [{ stream, read_offset: 0 }] }, 1);
126
+ const spec = toKernelSpec(compileSpec({ version: SPEC_SCHEMA_VERSION, name: `${flowName}/${id}`,
127
+ steps: [{ id, type: 'agent', instruction,
128
+ surfaces: { streams: [{ stream }], external: [surfacePath] }, maxIterations: 1 }],
129
+ }));
130
+ timer = setTimeout(() => {
131
+ dispatchExpired = true;
132
+ failed(new Error('MCP worker dispatch deadline exceeded'));
133
+ }, 30_000);
134
+ // Propagate a dispatch failure even if run.start itself is still pending.
135
+ const starting = journal.runStart(spec);
136
+ await Promise.race([starting, completed]);
137
+ const outcome = await starting;
138
+ childRunId = outcome.run_id;
139
+ await completed;
140
+ if (diagnostic !== undefined) {
141
+ try { await readCompletedStepOutput(journal, outcome.run_id, id, journalSteps); }
142
+ catch (error) {
143
+ if (!(error instanceof AuthoredFlowExecutionError) || error.code !== 'step_failed') throw error;
144
+ throw new McpStepError(diagnostic, outcome.run_id);
145
+ }
146
+ }
147
+ const receipt = await readCompletedStepOutput(journal, outcome.run_id, id, journalSteps) as { output: unknown };
148
+ return receipt.output;
149
+ } finally {
150
+ clearTimeout(timer);
151
+ peer.off('step.dispatch', dispatch);
152
+ // If the dispatch deadline fired we started a child run that will never
153
+ // be worked -- cancel it so its journal doesn't stay indeterminate.
154
+ // Best-effort: the parent flow already surfaced the deadline via the
155
+ // rejected `completed` promise, so a cancel error here must not mask it.
156
+ if (dispatchExpired && childRunId !== undefined) {
157
+ try { await journal.runCancel(childRunId); } catch { /* fail-open on cleanup */ }
158
+ }
159
+ peer.close();
160
+ await work?.catch(() => undefined);
161
+ }
162
+ }
163
+
164
+ function pathPart(value: string): string {
165
+ return encodeURIComponent(value).replaceAll('.', '%2E');
166
+ }
@@ -0,0 +1,55 @@
1
+ import type { MemoryHelper } from '@relayflows/surface';
2
+ import { createHash } from 'node:crypto';
3
+ import { access, stat } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { AuthoredFlowExecutionError } from './authored-flow-error.js';
7
+ import { preflightMemory } from './preflight.js';
8
+
9
+ /** Stable across runs; disjoint from other flow files and other named flows. */
10
+ export function scriptMemoryScope(flowPath: string, name: string): string {
11
+ const absolute = resolve(flowPath);
12
+ const key = createHash('sha256').update(JSON.stringify([absolute, name])).digest('hex');
13
+ return join(dirname(absolute), '.relayflows', 'memory', 'scripts', key);
14
+ }
15
+
16
+ export async function probeScriptMemory(): Promise<void> {
17
+ const { defaultDbPath, openAiHist } = await import('ai-hist');
18
+ const path = defaultDbPath();
19
+ await access(path, constants.R_OK);
20
+ if (!(await stat(path)).isFile()) throw new Error('memory database must be a file');
21
+ const reader = await openAiHist({ dbPath: path, fallback: 'error' });
22
+ try { reader.search('', { limit: 1 }); } finally { reader.close(); }
23
+ }
24
+
25
+ export async function assertMemoryReachable(): Promise<void> {
26
+ const refusal = await preflightMemory(probeScriptMemory);
27
+ if (refusal) throw new AuthoredFlowExecutionError('memory_unreachable', refusal.message);
28
+ }
29
+
30
+ export function authoredMemory(
31
+ scope: string,
32
+ assertOpen: () => void,
33
+ enabled: boolean,
34
+ ): MemoryHelper {
35
+ async function read<T>(action: (reader: import('ai-hist').AiHist) => T): Promise<T> {
36
+ assertOpen();
37
+ if (!enabled) throw new AuthoredFlowExecutionError('unsupported_header', 'f.memory requires script memory; memory.script is false');
38
+ await assertMemoryReachable();
39
+ assertOpen();
40
+ const { openAiHist } = await import('ai-hist');
41
+ const reader = await openAiHist({ projectScope: scope, fallback: 'error' });
42
+ try { return action(reader); } finally { reader.close(); }
43
+ }
44
+ return {
45
+ recall: (query, options) => read(reader => reader.search(query, { ...options, project: scope })),
46
+ why: task => read(reader => {
47
+ const entry = reader.whyForTask(task);
48
+ return entry?.projectId === scope ? [entry] : [];
49
+ }),
50
+ async learn() {
51
+ assertOpen();
52
+ throw new AuthoredFlowExecutionError('unsupported_verb', 'f.memory.learn requires the follow-up journal-backed trajectory writer');
53
+ },
54
+ };
55
+ }