@synergenius/flow-weaver 0.33.1 → 0.44.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 (922) hide show
  1. package/LICENSE +201 -226
  2. package/NOTICE +13 -0
  3. package/README.md +152 -244
  4. package/dist/agent/agent-loop.d.ts +4 -2
  5. package/dist/agent/cli-session.d.ts +3 -3
  6. package/dist/agent/cli-session.js +511 -438
  7. package/dist/agent/cli-spawn-config.d.ts +4 -4
  8. package/dist/agent/gate.d.ts +164 -0
  9. package/dist/agent/index.d.ts +4 -4
  10. package/dist/agent/index.js +174 -28
  11. package/dist/agent/mcp-bridge.d.ts +1 -1
  12. package/dist/agent/mcp-bridge.js +114 -128
  13. package/dist/agent/mcp-tool-server.d.ts +2 -2
  14. package/dist/agent/mcp-tool-server.js +147 -189
  15. package/dist/agent/profiles.d.ts +69 -0
  16. package/dist/agent/providers/anthropic.d.ts +2 -4
  17. package/dist/agent/providers/claude-cli.d.ts +4 -5
  18. package/dist/agent/providers/openai-compat.d.ts +8 -1
  19. package/dist/agent/streaming.d.ts +2 -2
  20. package/dist/agent/types.d.ts +16 -10
  21. package/dist/api/builder.d.ts +3 -3
  22. package/dist/api/compile.d.ts +9 -4
  23. package/dist/api/durable-validation.d.ts +15 -0
  24. package/dist/api/generate-in-place.d.ts +21 -19
  25. package/dist/api/generate.d.ts +21 -16
  26. package/dist/api/generated-module/local-node-functions.d.ts +24 -0
  27. package/dist/api/generated-module/module-format.d.ts +23 -0
  28. package/dist/api/generated-module/module-writer.d.ts +34 -0
  29. package/dist/api/generated-module/node-type-imports.d.ts +39 -0
  30. package/dist/api/generated-module/preamble.d.ts +16 -0
  31. package/dist/api/generated-module/workflow-functions.d.ts +29 -0
  32. package/dist/api/graph-identity.d.ts +39 -0
  33. package/dist/api/helpers.d.ts +4 -60
  34. package/dist/api/in-place/built-in-nodes.d.ts +18 -0
  35. package/dist/api/in-place/function-body.d.ts +21 -0
  36. package/dist/api/in-place/fw-imports.d.ts +30 -0
  37. package/dist/api/in-place/macro-coverage.d.ts +14 -0
  38. package/dist/api/in-place/node-type-functions.d.ts +18 -0
  39. package/dist/api/in-place/node-type-jsdoc.d.ts +20 -0
  40. package/dist/api/in-place/orphaned-node-types.d.ts +16 -0
  41. package/dist/api/in-place/runtime-section.d.ts +16 -0
  42. package/dist/api/in-place/signature.d.ts +47 -0
  43. package/dist/api/in-place/source-file.d.ts +19 -0
  44. package/dist/api/in-place/workflow-jsdoc.d.ts +19 -0
  45. package/dist/api/index.d.ts +18 -21
  46. package/dist/api/index.js +259 -53
  47. package/dist/api/inline-engine.generated.d.ts +3 -0
  48. package/dist/api/inline-runtime.d.ts +10 -2
  49. package/dist/api/manipulation/connections.d.ts +1 -1
  50. package/dist/api/manipulation/index.d.ts +8 -8
  51. package/dist/api/manipulation/node-types.d.ts +1 -1
  52. package/dist/api/manipulation/nodes.d.ts +3 -13
  53. package/dist/api/manipulation/ports.d.ts +1 -1
  54. package/dist/api/manipulation/scopes.d.ts +1 -1
  55. package/dist/api/manipulation/workflow.d.ts +1 -1
  56. package/dist/api/modify-operation.d.ts +0 -2
  57. package/dist/api/parse.d.ts +22 -1
  58. package/dist/api/port-references.d.ts +66 -0
  59. package/dist/api/query.d.ts +18 -2
  60. package/dist/api/templates.d.ts +1 -1
  61. package/dist/api/transform.d.ts +1 -1
  62. package/dist/api/validate.d.ts +1 -1
  63. package/dist/api/validation-registry.d.ts +2 -2
  64. package/dist/artifacts/brief.d.ts +43 -0
  65. package/dist/artifacts/index.d.ts +31 -0
  66. package/dist/artifacts/pdf.d.ts +19 -0
  67. package/dist/ast/builder.d.ts +3 -3
  68. package/dist/ast/index.d.ts +4 -4
  69. package/dist/ast/index.js +60 -5
  70. package/dist/ast/serialization-node.d.ts +1 -1
  71. package/dist/ast/serialization.d.ts +1 -1
  72. package/dist/ast/types.d.ts +82 -291
  73. package/dist/ast/workflow-utils.d.ts +4 -4
  74. package/dist/built-in-nodes/coercion-types.d.ts +1 -1
  75. package/dist/built-in-nodes/delay.d.ts +3 -1
  76. package/dist/built-in-nodes/generated-registry.d.ts +1 -1
  77. package/dist/built-in-nodes/index.d.ts +6 -5
  78. package/dist/built-in-nodes/index.js +79 -5
  79. package/dist/built-in-nodes/invoke-workflow.d.ts +2 -1
  80. package/dist/built-in-nodes/mock-types.d.ts +45 -14
  81. package/dist/built-in-nodes/sleep.d.ts +12 -0
  82. package/dist/built-in-nodes/wait-for-agent.d.ts +2 -1
  83. package/dist/built-in-nodes/wait-for-event.d.ts +2 -1
  84. package/dist/chevrotain-parser/coerce-parser.d.ts +1 -1
  85. package/dist/chevrotain-parser/connect-parser.d.ts +1 -1
  86. package/dist/chevrotain-parser/grammar-diagrams.d.ts +1 -1
  87. package/dist/chevrotain-parser/index.d.ts +20 -23
  88. package/dist/chevrotain-parser/node-parser.d.ts +7 -8
  89. package/dist/chevrotain-parser/parse-line.d.ts +54 -0
  90. package/dist/chevrotain-parser/tokens.d.ts +0 -17
  91. package/dist/chevrotain-parser/trigger-cancel-parser.d.ts +6 -1
  92. package/dist/chunks/chunk-4EUSHAY6.js +298 -0
  93. package/dist/chunks/chunk-4KDUEOFD.js +197 -0
  94. package/dist/chunks/chunk-5Y3AIUWY.js +911 -0
  95. package/dist/chunks/chunk-6KMVP6AU.js +20 -0
  96. package/dist/chunks/chunk-6PNJORFL.js +128 -0
  97. package/dist/chunks/chunk-7AAQNGRH.js +2001 -0
  98. package/dist/chunks/chunk-7YYKTPJ5.js +22705 -0
  99. package/dist/chunks/chunk-A5MBOFVY.js +33 -0
  100. package/dist/chunks/chunk-AXNQRVJB.js +18 -0
  101. package/dist/chunks/chunk-B6HQ6YS5.js +572 -0
  102. package/dist/chunks/chunk-CY3RNVML.js +296 -0
  103. package/dist/chunks/chunk-CYHYDLV4.js +653 -0
  104. package/dist/chunks/chunk-CZBCCK4Y.js +82 -0
  105. package/dist/chunks/chunk-DCMGQP5V.js +505 -0
  106. package/dist/chunks/chunk-DIAA66GL.js +72 -0
  107. package/dist/chunks/chunk-DUO6H5PR.js +20 -0
  108. package/dist/chunks/chunk-E5WN7IGO.js +125 -0
  109. package/dist/chunks/chunk-EFGFXXQF.js +184 -0
  110. package/dist/chunks/chunk-F3RTZV2A.js +2811 -0
  111. package/dist/chunks/chunk-FMTLP5ZX.js +1397 -0
  112. package/dist/chunks/chunk-HKZLQJDV.js +79 -0
  113. package/dist/chunks/chunk-INDEVYEC.js +146 -0
  114. package/dist/chunks/chunk-JQTF4R5L.js +390 -0
  115. package/dist/chunks/chunk-KMCAYNUM.js +331 -0
  116. package/dist/chunks/chunk-KMWCCOUJ.js +1444 -0
  117. package/dist/chunks/chunk-KU3CLJI2.js +338 -0
  118. package/dist/chunks/chunk-NDSTGMKR.js +3300 -0
  119. package/dist/chunks/chunk-NQNLUAPO.js +505 -0
  120. package/dist/chunks/chunk-O2U2LO57.js +466 -0
  121. package/dist/chunks/chunk-OOQG7UPP.js +457 -0
  122. package/dist/chunks/chunk-OZQAW5ZG.js +112 -0
  123. package/dist/chunks/chunk-P2CVDGHR.js +487 -0
  124. package/dist/chunks/chunk-P44RIZ7C.js +592 -0
  125. package/dist/chunks/chunk-PEZCT37T.js +1475 -0
  126. package/dist/chunks/chunk-PKWSAW6O.js +152 -0
  127. package/dist/chunks/chunk-Q6MDDZMT.js +4373 -0
  128. package/dist/chunks/chunk-QDE4Z7KW.js +6 -0
  129. package/dist/chunks/chunk-QJDAVSNY.js +8 -0
  130. package/dist/chunks/chunk-QYPORSLO.js +7552 -0
  131. package/dist/chunks/chunk-R4QGNK34.js +183 -0
  132. package/dist/chunks/chunk-REEYC73I.js +3002 -0
  133. package/dist/chunks/chunk-SEWDMQ6Q.js +46 -0
  134. package/dist/chunks/chunk-TAIUWKZB.js +3057 -0
  135. package/dist/chunks/chunk-TN4YZ3O7.js +196 -0
  136. package/dist/chunks/chunk-TRMFB43C.js +143 -0
  137. package/dist/chunks/chunk-VO4QXG2X.js +1016 -0
  138. package/dist/chunks/chunk-VP2P3BPA.js +1002 -0
  139. package/dist/chunks/chunk-VQ7H33J4.js +2176 -0
  140. package/dist/chunks/chunk-VWA7MCV2.js +105 -0
  141. package/dist/chunks/chunk-XAV22WD7.js +253 -0
  142. package/dist/chunks/chunk-YSPBPZDV.js +148 -0
  143. package/dist/chunks/chunk-ZKEGXO73.js +282 -0
  144. package/dist/chunks/chunk-ZMGN6F3S.js +4256 -0
  145. package/dist/chunks/grammar-diagrams-AI7VDXOM.js +14 -0
  146. package/dist/chunks/index.min-ECJD6GZC.js +37 -0
  147. package/dist/chunks/manifest-EPTR5MYH.js +21 -0
  148. package/dist/chunks/openapi-document-6TCGVDUW.js +69 -0
  149. package/dist/chunks/registry-K2U5KUTY.js +23 -0
  150. package/dist/chunks/serialization-node-UGY6CFH6.js +38 -0
  151. package/dist/chunks/validate-GEKSZPIN.js +24 -0
  152. package/dist/chunks/validation-registry-IQZX3UE3.js +7 -0
  153. package/dist/chunks/validator-VXFHLPDW.js +26 -0
  154. package/dist/chunks/workflow-executor-KBGFKHNR.js +36 -0
  155. package/dist/cli/commands/agents.d.ts +16 -0
  156. package/dist/cli/commands/artifact.d.ts +10 -0
  157. package/dist/cli/commands/compile.d.ts +0 -30
  158. package/dist/cli/commands/console.d.ts +32 -0
  159. package/dist/cli/commands/context.d.ts +0 -3
  160. package/dist/cli/commands/describe.js +386 -352
  161. package/dist/cli/commands/dev.d.ts +9 -4
  162. package/dist/cli/commands/diagram.d.ts +3 -5
  163. package/dist/cli/commands/doctor.d.ts +27 -4
  164. package/dist/cli/commands/doctor.js +3307 -633
  165. package/dist/cli/commands/export.d.ts +6 -4
  166. package/dist/cli/commands/grammar.d.ts +0 -3
  167. package/dist/cli/commands/implement.d.ts +1 -1
  168. package/dist/cli/commands/init/agent-handoff.d.ts +28 -0
  169. package/dist/cli/commands/init/config.d.ts +3 -0
  170. package/dist/cli/commands/init/files.d.ts +12 -0
  171. package/dist/cli/commands/init/naming.d.ts +13 -0
  172. package/dist/cli/commands/init/output.d.ts +12 -0
  173. package/dist/cli/commands/init/setup.d.ts +21 -0
  174. package/dist/cli/commands/init/types.d.ts +53 -0
  175. package/dist/cli/commands/init-personas.d.ts +9 -1
  176. package/dist/cli/commands/init.d.ts +24 -88
  177. package/dist/cli/commands/market.d.ts +1 -1
  178. package/dist/cli/commands/mcp-setup.d.ts +1 -4
  179. package/dist/cli/commands/modify.d.ts +0 -5
  180. package/dist/cli/commands/openapi.d.ts +9 -11
  181. package/dist/cli/commands/run.d.ts +0 -4
  182. package/dist/cli/commands/serve.d.ts +24 -26
  183. package/dist/cli/commands/status.d.ts +1 -1
  184. package/dist/cli/exports.d.ts +3 -4
  185. package/dist/cli/exports.js +124 -23
  186. package/dist/cli/flow-weaver-agents-H653446S.mjs +81 -0
  187. package/dist/cli/flow-weaver-artifact-WBFYTW76.mjs +58 -0
  188. package/dist/cli/flow-weaver-chunk-265CEK74.mjs +2 -0
  189. package/dist/cli/flow-weaver-chunk-2C7PZCV5.mjs +186 -0
  190. package/dist/cli/flow-weaver-chunk-3BSYCWPL.mjs +3109 -0
  191. package/dist/cli/flow-weaver-chunk-3MKUQP3D.mjs +547 -0
  192. package/dist/cli/flow-weaver-chunk-3ZLMPQTH.mjs +27 -0
  193. package/dist/cli/flow-weaver-chunk-4DVY73ML.mjs +280 -0
  194. package/dist/cli/flow-weaver-chunk-54M4KNEL.mjs +200 -0
  195. package/dist/cli/flow-weaver-chunk-55QMUZIA.mjs +256 -0
  196. package/dist/cli/flow-weaver-chunk-6ZUJ7LMX.mjs +2003 -0
  197. package/dist/cli/flow-weaver-chunk-7ET6N32V.mjs +419 -0
  198. package/dist/cli/flow-weaver-chunk-7G63RR4K.mjs +8880 -0
  199. package/dist/cli/flow-weaver-chunk-A6M5K3W7.mjs +4418 -0
  200. package/dist/cli/flow-weaver-chunk-AA3NATMX.mjs +154 -0
  201. package/dist/cli/flow-weaver-chunk-APX6MQ5A.mjs +5652 -0
  202. package/dist/cli/flow-weaver-chunk-BHCC5FE5.mjs +17 -0
  203. package/dist/cli/flow-weaver-chunk-DM4BBRRU.mjs +35 -0
  204. package/dist/cli/flow-weaver-chunk-DRN7KPWY.mjs +168 -0
  205. package/dist/cli/flow-weaver-chunk-EKWF27G6.mjs +23 -0
  206. package/dist/cli/flow-weaver-chunk-EM5HWQ4R.mjs +338 -0
  207. package/dist/cli/flow-weaver-chunk-FPPPU2DG.mjs +226 -0
  208. package/dist/cli/flow-weaver-chunk-GAQXZHNO.mjs +3005 -0
  209. package/dist/cli/flow-weaver-chunk-GBUNNP33.mjs +1329 -0
  210. package/dist/cli/flow-weaver-chunk-HMAKDE55.mjs +636 -0
  211. package/dist/cli/flow-weaver-chunk-HQ3ZAN44.mjs +367 -0
  212. package/dist/cli/flow-weaver-chunk-I4APCXYN.mjs +21442 -0
  213. package/dist/cli/flow-weaver-chunk-IJJ4JXTL.mjs +2297 -0
  214. package/dist/cli/flow-weaver-chunk-J7EPZW2I.mjs +33 -0
  215. package/dist/cli/flow-weaver-chunk-KOEMJHLG.mjs +83 -0
  216. package/dist/cli/flow-weaver-chunk-M6CBWQKJ.mjs +271 -0
  217. package/dist/cli/flow-weaver-chunk-MHJ4N652.mjs +1580 -0
  218. package/dist/cli/flow-weaver-chunk-MKAFQWLP.mjs +202 -0
  219. package/dist/cli/flow-weaver-chunk-MMV2XGD3.mjs +3291 -0
  220. package/dist/cli/flow-weaver-chunk-MSI2UJES.mjs +125 -0
  221. package/dist/cli/flow-weaver-chunk-N767YRAI.mjs +48 -0
  222. package/dist/cli/flow-weaver-chunk-NQKKWDGF.mjs +56 -0
  223. package/dist/cli/flow-weaver-chunk-NYZDQYFU.mjs +45 -0
  224. package/dist/cli/flow-weaver-chunk-OMVWSNHJ.mjs +14 -0
  225. package/dist/cli/flow-weaver-chunk-PUWZ47H5.mjs +2188 -0
  226. package/dist/cli/flow-weaver-chunk-QOPRVDES.mjs +46 -0
  227. package/dist/cli/flow-weaver-chunk-RIWE7YTR.mjs +216 -0
  228. package/dist/cli/flow-weaver-chunk-S63Q3JIU.mjs +789 -0
  229. package/dist/cli/flow-weaver-chunk-T7X5A23H.mjs +558 -0
  230. package/dist/cli/flow-weaver-chunk-TLV3VZUN.mjs +2 -0
  231. package/dist/cli/flow-weaver-chunk-TS5P3PIN.mjs +194 -0
  232. package/dist/cli/flow-weaver-chunk-U3EO3X4B.mjs +649 -0
  233. package/dist/cli/flow-weaver-chunk-UNFS3NQP.mjs +34 -0
  234. package/dist/cli/flow-weaver-chunk-V6DHWFQG.mjs +2811 -0
  235. package/dist/cli/flow-weaver-chunk-VXWNLYQU.mjs +9 -0
  236. package/dist/cli/flow-weaver-chunk-W3YNK26P.mjs +149 -0
  237. package/dist/cli/flow-weaver-chunk-XG2WKXYZ.mjs +324 -0
  238. package/dist/cli/flow-weaver-chunk-YLSRZWFK.mjs +2219 -0
  239. package/dist/cli/flow-weaver-chunk-YVPURWS6.mjs +40 -0
  240. package/dist/cli/flow-weaver-chunk-Z44JK332.mjs +582 -0
  241. package/dist/cli/flow-weaver-chunk-Z5ZJPNSY.mjs +517 -0
  242. package/dist/cli/flow-weaver-chunk-ZQALO25T.mjs +594 -0
  243. package/dist/cli/flow-weaver-compile-A2CABDSB.mjs +37 -0
  244. package/dist/cli/flow-weaver-console-6EBHDBTN.mjs +71 -0
  245. package/dist/cli/flow-weaver-context-ECLYANFF.mjs +17 -0
  246. package/dist/cli/flow-weaver-context-ZRUMW2KE.mjs +69 -0
  247. package/dist/cli/flow-weaver-create-WIP4EFNP.mjs +124 -0
  248. package/dist/cli/flow-weaver-deployment-WJJRK7NO.mjs +14 -0
  249. package/dist/cli/flow-weaver-describe-XDIFF5LI.mjs +41 -0
  250. package/dist/cli/flow-weaver-dev-LG2NSQAU.mjs +196 -0
  251. package/dist/cli/flow-weaver-diagram-3EVQARQE.mjs +52 -0
  252. package/dist/cli/flow-weaver-diagram-7LR7O4M2.mjs +44 -0
  253. package/dist/cli/flow-weaver-diff-USF7DJLU.mjs +85 -0
  254. package/dist/cli/flow-weaver-docs-QU2ZOXKH.mjs +96 -0
  255. package/dist/cli/flow-weaver-doctor-K447YWHR.mjs +43 -0
  256. package/dist/cli/flow-weaver-export-LAS6N56Y.mjs +140 -0
  257. package/dist/cli/flow-weaver-grammar-RIRUS3Q6.mjs +49 -0
  258. package/dist/cli/flow-weaver-grammar-diagrams-WXRTW5SK.mjs +15 -0
  259. package/dist/cli/flow-weaver-implement-5JG6BCFZ.mjs +114 -0
  260. package/dist/cli/flow-weaver-index.min-OR5SIHXD.mjs +39 -0
  261. package/dist/cli/flow-weaver-init-34YZNPQX.mjs +972 -0
  262. package/dist/cli/flow-weaver-init-personas-NOGZTQQ2.mjs +48 -0
  263. package/dist/cli/flow-weaver-manifest-4JNUSEB3.mjs +18 -0
  264. package/dist/cli/flow-weaver-market-WA4CKHKV.mjs +444 -0
  265. package/dist/cli/flow-weaver-mcp-setup-O26MGXSD.mjs +22 -0
  266. package/dist/cli/flow-weaver-migrate-VFVEUTPH.mjs +119 -0
  267. package/dist/cli/flow-weaver-modify-VM3JP5K6.mjs +97 -0
  268. package/dist/cli/flow-weaver-openapi-IRBWI3HM.mjs +71 -0
  269. package/dist/cli/flow-weaver-openapi-document-7N6YMPG3.mjs +30 -0
  270. package/dist/cli/flow-weaver-pack-commands-OS2QRXAK.mjs +146 -0
  271. package/dist/cli/flow-weaver-registry-5MLFRPPT.mjs +25 -0
  272. package/dist/cli/flow-weaver-run-DSTLSTHR.mjs +555 -0
  273. package/dist/cli/flow-weaver-serialization-node-LE6PCG4M.mjs +50 -0
  274. package/dist/cli/flow-weaver-serve-NVLCLSOW.mjs +192 -0
  275. package/dist/cli/flow-weaver-server-7IERLVXE.mjs +2925 -0
  276. package/dist/cli/flow-weaver-server-KWF4PXYC.mjs +19112 -0
  277. package/dist/cli/flow-weaver-status-75W2S3YB.mjs +138 -0
  278. package/dist/cli/flow-weaver-strip-AZPXUYVA.mjs +79 -0
  279. package/dist/cli/flow-weaver-templates-DSNMB6K7.mjs +72 -0
  280. package/dist/cli/flow-weaver-validate-A4UWDQN6.mjs +19 -0
  281. package/dist/cli/flow-weaver-validate-GRBZ5W4C.mjs +296 -0
  282. package/dist/cli/flow-weaver-validation-registry-BINGUNXX.mjs +9 -0
  283. package/dist/cli/flow-weaver-validator-TY56CI42.mjs +21 -0
  284. package/dist/cli/flow-weaver-watch-OPPERXL6.mjs +114 -0
  285. package/dist/cli/flow-weaver-workflow-executor-6AHYPXAN.mjs +26 -0
  286. package/dist/cli/flow-weaver.mjs +3557 -89498
  287. package/dist/cli/index.d.ts +5 -2
  288. package/dist/cli/pack-commands-needed.d.ts +12 -0
  289. package/dist/cli/program.d.ts +14 -0
  290. package/dist/cli/templates/ai/mock-provider.d.ts +1 -1
  291. package/dist/cli/templates/index.d.ts +1 -8
  292. package/dist/cli/templates/nodes/agent-router.d.ts +1 -1
  293. package/dist/cli/templates/nodes/aggregator.d.ts +1 -1
  294. package/dist/cli/templates/nodes/conversation-memory.d.ts +1 -1
  295. package/dist/cli/templates/nodes/http.d.ts +1 -1
  296. package/dist/cli/templates/nodes/human-approval.d.ts +1 -1
  297. package/dist/cli/templates/nodes/json-extractor.d.ts +1 -1
  298. package/dist/cli/templates/nodes/llm-call.d.ts +1 -1
  299. package/dist/cli/templates/nodes/prompt-template.d.ts +1 -1
  300. package/dist/cli/templates/nodes/rag-retriever.d.ts +1 -1
  301. package/dist/cli/templates/nodes/tool-executor.d.ts +1 -1
  302. package/dist/cli/templates/nodes/transformer.d.ts +1 -1
  303. package/dist/cli/templates/nodes/validator.d.ts +1 -1
  304. package/dist/cli/templates/shared/approval-types.d.ts +1 -1
  305. package/dist/cli/templates/shared/case.d.ts +14 -0
  306. package/dist/cli/templates/shared/llm-types.d.ts +4 -4
  307. package/dist/cli/templates/workflows/aggregator.d.ts +1 -1
  308. package/dist/cli/templates/workflows/ai-agent.d.ts +1 -1
  309. package/dist/cli/templates/workflows/ai-chat.d.ts +1 -1
  310. package/dist/cli/templates/workflows/ai-rag.d.ts +1 -1
  311. package/dist/cli/templates/workflows/ai-react.d.ts +1 -1
  312. package/dist/cli/templates/workflows/approval.d.ts +10 -0
  313. package/dist/cli/templates/workflows/conditional.d.ts +2 -2
  314. package/dist/cli/templates/workflows/error-handler.d.ts +2 -2
  315. package/dist/cli/templates/workflows/foreach.d.ts +1 -1
  316. package/dist/cli/templates/workflows/sequential.d.ts +1 -1
  317. package/dist/cli/templates/workflows/webhook.d.ts +1 -1
  318. package/dist/cli/utils/interactive.d.ts +6 -0
  319. package/dist/cli/utils/json-option.d.ts +8 -0
  320. package/dist/cli/utils/logger.d.ts +2 -0
  321. package/dist/compiler/durable-source-proof.d.ts +23 -0
  322. package/dist/compiler/executable-artifact.d.ts +29 -0
  323. package/dist/compiler/index.d.ts +4 -0
  324. package/dist/compiler/index.js +36 -0
  325. package/dist/console/app.js +106 -0
  326. package/dist/console/assets/synergenius.svg +18 -0
  327. package/dist/console/author.d.ts +32 -0
  328. package/dist/console/cli-catalog.d.ts +21 -0
  329. package/dist/console/cli-run.d.ts +35 -0
  330. package/dist/console/cli-run.js +46 -0
  331. package/dist/console/debug.d.ts +67 -0
  332. package/dist/console/diff-view.d.ts +96 -0
  333. package/dist/console/export.d.ts +36 -0
  334. package/dist/console/git.d.ts +27 -0
  335. package/dist/console/index.d.ts +4 -0
  336. package/dist/console/index.html +16 -0
  337. package/dist/console/index.js +203 -0
  338. package/dist/console/packs.d.ts +100 -0
  339. package/dist/console/request-guard.d.ts +10 -0
  340. package/dist/console/respond.d.ts +16 -0
  341. package/dist/console/router.d.ts +64 -0
  342. package/dist/console/routes-agents.d.ts +14 -0
  343. package/dist/console/routes-project.d.ts +3 -0
  344. package/dist/console/routes-runs.d.ts +3 -0
  345. package/dist/console/routes-services.d.ts +7 -0
  346. package/dist/console/routes-tools.d.ts +3 -0
  347. package/dist/console/runs.d.ts +69 -0
  348. package/dist/console/scan.d.ts +49 -0
  349. package/dist/console/schema.d.ts +74 -0
  350. package/dist/console/server.d.ts +34 -0
  351. package/dist/console/server.js +43264 -0
  352. package/dist/console/services.d.ts +119 -0
  353. package/dist/console/source.d.ts +23 -0
  354. package/dist/console/status.d.ts +68 -0
  355. package/dist/console/styles.css +1023 -0
  356. package/dist/console/terminals.d.ts +22 -0
  357. package/dist/console/workflow-view.d.ts +153 -0
  358. package/dist/constants.d.ts +5 -1
  359. package/dist/constants.js +56 -167
  360. package/dist/context/index.d.ts +10 -0
  361. package/dist/context/index.js +14 -191
  362. package/dist/coordinator/agent-gate.d.ts +107 -0
  363. package/dist/coordinator/bundle-digest.d.ts +20 -0
  364. package/dist/coordinator/clock-tick.d.ts +4 -0
  365. package/dist/coordinator/effect-receipts.d.ts +10 -0
  366. package/dist/coordinator/errors.d.ts +31 -0
  367. package/dist/coordinator/file-store.d.ts +3 -0
  368. package/dist/coordinator/gate-labeling.d.ts +33 -0
  369. package/dist/coordinator/gate-resolution.d.ts +28 -0
  370. package/dist/coordinator/index.d.ts +12 -0
  371. package/dist/coordinator/index.js +107 -0
  372. package/dist/coordinator/memory-store.d.ts +3 -0
  373. package/dist/coordinator/params.d.ts +18 -0
  374. package/dist/coordinator/run-annotations.d.ts +6 -0
  375. package/dist/coordinator/run-context.d.ts +11 -0
  376. package/dist/coordinator/run-ending.d.ts +5 -0
  377. package/dist/coordinator/run-outcome.d.ts +31 -0
  378. package/dist/coordinator/run-resume.d.ts +6 -0
  379. package/dist/coordinator/run-start.d.ts +4 -0
  380. package/dist/coordinator/run-store.d.ts +275 -0
  381. package/dist/coordinator/run-trace.d.ts +41 -0
  382. package/dist/coordinator/run-views.d.ts +12 -0
  383. package/dist/coordinator/runs-dir.d.ts +26 -0
  384. package/dist/coordinator/store.d.ts +67 -0
  385. package/dist/coordinator/time.d.ts +39 -0
  386. package/dist/coordinator/workflow-selection.d.ts +6 -0
  387. package/dist/deployment/index.d.ts +11 -16
  388. package/dist/deployment/index.js +541 -50
  389. package/dist/deployment/targets/base.d.ts +11 -13
  390. package/dist/deployment/targets/openapi-parts.d.ts +92 -0
  391. package/dist/diagram/arms.d.ts +70 -0
  392. package/dist/diagram/ascii-renderer.d.ts +1 -1
  393. package/dist/diagram/geometry.d.ts +22 -29
  394. package/dist/diagram/graph/bounds.d.ts +30 -0
  395. package/dist/diagram/graph/metrics.d.ts +21 -0
  396. package/dist/diagram/graph/nodes.d.ts +33 -0
  397. package/dist/diagram/graph/placement.d.ts +22 -0
  398. package/dist/diagram/graph/ports.d.ts +23 -0
  399. package/dist/diagram/graph/routing.d.ts +40 -0
  400. package/dist/diagram/graph/scopes.d.ts +30 -0
  401. package/dist/diagram/index.d.ts +15 -23
  402. package/dist/diagram/index.js +632 -111
  403. package/dist/diagram/labels.d.ts +12 -0
  404. package/dist/diagram/lanes.d.ts +93 -0
  405. package/dist/diagram/layout.d.ts +1 -1
  406. package/dist/diagram/material-symbols.d.ts +7 -0
  407. package/dist/diagram/orthogonal-router.d.ts +15 -51
  408. package/dist/diagram/process-view.d.ts +79 -0
  409. package/dist/diagram/spine.d.ts +25 -0
  410. package/dist/diagram/theme.d.ts +3 -5
  411. package/dist/diagram/types.d.ts +6 -20
  412. package/dist/diff/index.js +53 -9
  413. package/dist/diff/types.d.ts +1 -5
  414. package/dist/doc-metadata/extractors/annotations.d.ts +0 -4
  415. package/dist/doc-metadata/extractors/cli-commands.d.ts +2 -1
  416. package/dist/doc-metadata/extractors/core-metadata.d.ts +19 -4
  417. package/dist/doc-metadata/extractors/error-codes.d.ts +1 -1
  418. package/dist/doc-metadata/extractors/mcp-tools.d.ts +7 -3
  419. package/dist/doc-metadata/index.d.ts +1 -2
  420. package/dist/doc-metadata/index.js +2368 -9
  421. package/dist/doc-metadata/types.d.ts +7 -24
  422. package/dist/docs/guide.d.ts +33 -0
  423. package/dist/docs/index.d.ts +7 -4
  424. package/dist/docs/index.js +298 -298
  425. package/dist/docs/pack-topics.d.ts +18 -0
  426. package/dist/editor-completions/annotationValues.d.ts +1 -1
  427. package/dist/editor-completions/contextParser.d.ts +3 -2
  428. package/dist/editor-completions/dataTypes.d.ts +1 -1
  429. package/dist/editor-completions/goToDefinition.d.ts +1 -1
  430. package/dist/editor-completions/index.d.ts +8 -8
  431. package/dist/editor-completions/index.js +1244 -175
  432. package/dist/editor-completions/jsDocAnnotations.d.ts +1 -1
  433. package/dist/editor-completions/modifierCompletions.d.ts +1 -1
  434. package/dist/export/index.d.ts +7 -1
  435. package/dist/generated-branding.js +8 -21
  436. package/dist/generated-version.d.ts +1 -1
  437. package/dist/generated-version.js +7 -3
  438. package/dist/generator/annotation-generator.d.ts +84 -0
  439. package/dist/generator/async-detection.d.ts +1 -1
  440. package/dist/{body-generator.d.ts → generator/body-generator.d.ts} +7 -3
  441. package/dist/generator/code-utils.d.ts +15 -60
  442. package/dist/generator/connection-reads.d.ts +94 -0
  443. package/dist/generator/control-flow-plan.d.ts +74 -0
  444. package/dist/generator/control-flow.d.ts +1 -1
  445. package/dist/generator/exit-assembly.d.ts +11 -0
  446. package/dist/generator/index.d.ts +4 -5
  447. package/dist/generator/index.js +34 -11
  448. package/dist/generator/input-port-values.d.ts +22 -0
  449. package/dist/generator/{scope-function-generator.d.ts → node-arguments.d.ts} +76 -1
  450. package/dist/generator/node-invocation.d.ts +74 -0
  451. package/dist/{node-types-generator.d.ts → generator/node-types-generator.d.ts} +3 -2
  452. package/dist/generator/scope-closure.d.ts +23 -0
  453. package/dist/generator/scoped-child.d.ts +49 -0
  454. package/dist/{sugar-optimizer.d.ts → generator/sugar-optimizer.d.ts} +1 -1
  455. package/dist/generator/unified.d.ts +14 -2
  456. package/dist/generator/workflow-generator.d.ts +37 -0
  457. package/dist/index.d.ts +29 -26
  458. package/dist/index.js +1322 -92
  459. package/dist/jsdoc-port-sync/apply-diff.d.ts +15 -0
  460. package/dist/jsdoc-port-sync/callback-signature.d.ts +17 -0
  461. package/dist/jsdoc-port-sync/diff.d.ts +5 -7
  462. package/dist/jsdoc-port-sync/incomplete-lines.d.ts +41 -0
  463. package/dist/jsdoc-port-sync/index.d.ts +11 -11
  464. package/dist/jsdoc-port-sync/index.js +88 -45
  465. package/dist/jsdoc-port-sync/jsdoc-to-signature.d.ts +66 -0
  466. package/dist/jsdoc-port-sync/port-parser.d.ts +6 -24
  467. package/dist/jsdoc-port-sync/port-tag-placement.d.ts +55 -0
  468. package/dist/jsdoc-port-sync/scoped-ports.d.ts +21 -0
  469. package/dist/jsdoc-port-sync/signature-parser.d.ts +8 -1
  470. package/dist/jsdoc-port-sync/signature-to-jsdoc.d.ts +77 -0
  471. package/dist/jsdoc-port-sync/sync.d.ts +4 -1
  472. package/dist/marketplace/index.d.ts +5 -3
  473. package/dist/marketplace/index.js +62 -10
  474. package/dist/marketplace/install.d.ts +24 -0
  475. package/dist/marketplace/manifest.d.ts +1 -1
  476. package/dist/marketplace/npmrc.d.ts +24 -0
  477. package/dist/marketplace/registry.d.ts +46 -11
  478. package/dist/marketplace/types.d.ts +41 -24
  479. package/dist/marketplace/validator.d.ts +1 -1
  480. package/dist/mcp/debug-session.d.ts +2 -4
  481. package/dist/mcp/dist-imports.d.ts +12 -0
  482. package/dist/mcp/response-utils.d.ts +11 -9
  483. package/dist/mcp/server.d.ts +0 -1
  484. package/dist/mcp/tools-context.d.ts +11 -0
  485. package/dist/mcp/tools-diagram.d.ts +1 -2
  486. package/dist/mcp/tools-export.d.ts +2 -2
  487. package/dist/mcp/tools-marketplace.d.ts +1 -1
  488. package/dist/mcp/tools-run.d.ts +17 -0
  489. package/dist/mcp/tools-workflow.d.ts +3 -0
  490. package/dist/mcp/types.d.ts +4 -14
  491. package/dist/mcp/workflow-executor.d.ts +57 -19
  492. package/dist/npm-packages.d.ts +1 -1
  493. package/dist/npm-packages.js +10 -473
  494. package/dist/parser/annotation-parser.d.ts +88 -0
  495. package/dist/parser/annotation-suggestion.d.ts +23 -0
  496. package/dist/parser/durable-effect-contract.d.ts +10 -0
  497. package/dist/parser/expression-references.d.ts +101 -0
  498. package/dist/parser/external-node-types.d.ts +69 -0
  499. package/dist/{function-like.d.ts → parser/function-like.d.ts} +10 -3
  500. package/dist/parser/generated-sections.d.ts +25 -0
  501. package/dist/parser/import-resolution.d.ts +67 -0
  502. package/dist/parser/import-stub.d.ts +29 -0
  503. package/dist/parser/jsdoc/config-types.d.ts +209 -0
  504. package/dist/parser/jsdoc/graph-tags.d.ts +54 -0
  505. package/dist/parser/jsdoc/node-type-block.d.ts +23 -0
  506. package/dist/parser/jsdoc/parse-line-once.d.ts +11 -0
  507. package/dist/parser/jsdoc/port-tags.d.ts +42 -0
  508. package/dist/parser/jsdoc/runtime-tags.d.ts +65 -0
  509. package/dist/parser/jsdoc/signature-types.d.ts +52 -0
  510. package/dist/parser/jsdoc/workflow-block.d.ts +22 -0
  511. package/dist/parser/jsdoc-parser.d.ts +23 -0
  512. package/dist/parser/macro-expansion.d.ts +80 -0
  513. package/dist/parser/module-resolution.d.ts +38 -0
  514. package/dist/parser/node-inference.d.ts +39 -0
  515. package/dist/parser/npm-node-types.d.ts +24 -0
  516. package/dist/parser/pack-handlers.d.ts +12 -0
  517. package/dist/parser/path-data-resolution.d.ts +75 -0
  518. package/dist/parser/port-inference.d.ts +15 -0
  519. package/dist/{resolve-package-types.d.ts → parser/resolve-package-types.d.ts} +4 -0
  520. package/dist/parser/serialize-deploy-annotations.d.ts +19 -0
  521. package/dist/parser/tag-registry.d.ts +22 -0
  522. package/dist/parser/workflow-extraction.d.ts +39 -0
  523. package/dist/runtime/ExecutionContext.d.ts +87 -99
  524. package/dist/runtime/continuation-core.d.ts +147 -0
  525. package/dist/runtime/continuation.d.ts +48 -0
  526. package/dist/runtime/debug-controller.d.ts +7 -22
  527. package/dist/runtime/durable-execution.d.ts +176 -0
  528. package/dist/runtime/events.d.ts +16 -1
  529. package/dist/runtime/executable-module-contract.d.ts +16 -0
  530. package/dist/runtime/index.d.ts +13 -10
  531. package/dist/runtime/index.js +947 -9
  532. package/dist/runtime/strict-json.d.ts +15 -0
  533. package/dist/server/access.d.ts +12 -0
  534. package/dist/server/api.d.ts +126 -0
  535. package/dist/server/callback-delivery.d.ts +62 -0
  536. package/dist/server/callback-url.d.ts +44 -0
  537. package/dist/server/context.d.ts +35 -0
  538. package/dist/server/http-error.d.ts +10 -0
  539. package/dist/server/index.d.ts +7 -1
  540. package/dist/server/index.js +125 -6
  541. package/dist/server/openapi-document.d.ts +33 -0
  542. package/dist/server/openapi.d.ts +32 -0
  543. package/dist/server/respond.d.ts +35 -0
  544. package/dist/server/route-params.d.ts +17 -0
  545. package/dist/server/route-plan.d.ts +41 -0
  546. package/dist/server/routes-catalog.d.ts +5 -0
  547. package/dist/server/routes-declared.d.ts +12 -0
  548. package/dist/server/routes-runs.d.ts +8 -0
  549. package/dist/server/run-driver.d.ts +58 -0
  550. package/dist/server/run-view.d.ts +26 -0
  551. package/dist/server/transport.d.ts +35 -0
  552. package/dist/server/types.d.ts +143 -52
  553. package/dist/server/webhook-server.d.ts +12 -38
  554. package/dist/server/workflow-registry.d.ts +7 -4
  555. package/dist/service-registry.d.ts +49 -0
  556. package/dist/service-registry.js +123 -0
  557. package/dist/testing/assertions.d.ts +2 -2
  558. package/dist/testing/index.d.ts +14 -13
  559. package/dist/testing/index.js +582 -24
  560. package/dist/testing/mock-approval.d.ts +3 -5
  561. package/dist/testing/mock-llm.d.ts +2 -3
  562. package/dist/testing/recorder.d.ts +5 -6
  563. package/dist/testing/replayer.d.ts +6 -7
  564. package/dist/testing/run-store-check.d.ts +3 -0
  565. package/dist/testing/token-tracker.d.ts +2 -2
  566. package/dist/{type-mappings.d.ts → types/type-mappings.d.ts} +13 -1
  567. package/dist/utils/error-utils.d.ts +4 -2
  568. package/dist/utils/port-ordering.d.ts +2 -2
  569. package/dist/utils/port-tag-utils.d.ts +1 -1
  570. package/dist/validation/agent-detection.d.ts +17 -5
  571. package/dist/validation/agent-rules.d.ts +6 -7
  572. package/dist/validation/core-rules.d.ts +49 -0
  573. package/dist/validation/design-rules.d.ts +9 -3
  574. package/dist/validation/rule-registry.d.ts +3 -3
  575. package/dist/validation/rules/connections.d.ts +27 -0
  576. package/dist/validation/rules/context.d.ts +11 -0
  577. package/dist/validation/rules/cycles.d.ts +17 -0
  578. package/dist/validation/rules/data-flow.d.ts +19 -0
  579. package/dist/validation/rules/scope-topology.d.ts +35 -0
  580. package/dist/validation/rules/type-compatibility.d.ts +30 -0
  581. package/dist/validation/type-checker.d.ts +39 -0
  582. package/dist/validation/validator-helpers.d.ts +31 -0
  583. package/dist/validation/validator.d.ts +30 -0
  584. package/docs/reference/advanced-annotations.md +277 -60
  585. package/docs/reference/built-in-nodes.md +164 -94
  586. package/docs/reference/cancellation.md +44 -0
  587. package/docs/reference/cli-reference.md +252 -234
  588. package/docs/reference/compilation.md +36 -109
  589. package/docs/reference/concepts.md +80 -63
  590. package/docs/reference/console.md +169 -0
  591. package/docs/reference/debugging.md +26 -57
  592. package/docs/reference/deployment.md +217 -143
  593. package/docs/reference/durable-gates.md +445 -0
  594. package/docs/reference/error-codes.md +90 -43
  595. package/docs/reference/export-interface.md +91 -26
  596. package/docs/reference/iterative-development.md +50 -28
  597. package/docs/reference/jsdoc-grammar.md +66 -311
  598. package/docs/reference/library.md +250 -0
  599. package/docs/reference/marketplace.md +301 -152
  600. package/docs/reference/mcp-tools.md +102 -0
  601. package/docs/reference/node-conversion.md +84 -59
  602. package/docs/reference/orientation.md +68 -0
  603. package/docs/reference/scaffold.md +5 -4
  604. package/docs/reference/tutorial.md +106 -166
  605. package/docs/reference/visual-reference.md +1 -1
  606. package/package.json +85 -50
  607. package/dist/agent/agent-loop.js +0 -156
  608. package/dist/agent/cli-spawn-config.js +0 -65
  609. package/dist/agent/device-connection.d.ts +0 -79
  610. package/dist/agent/device-connection.js +0 -184
  611. package/dist/agent/env-allowlist.js +0 -60
  612. package/dist/agent/providers/anthropic.js +0 -198
  613. package/dist/agent/providers/claude-cli.js +0 -161
  614. package/dist/agent/providers/openai-compat.js +0 -205
  615. package/dist/agent/providers/platform.d.ts +0 -23
  616. package/dist/agent/providers/platform.js +0 -132
  617. package/dist/agent/streaming.js +0 -186
  618. package/dist/agent/types.js +0 -20
  619. package/dist/annotation-generator.d.ts +0 -50
  620. package/dist/annotation-generator.js +0 -743
  621. package/dist/api/builder.js +0 -345
  622. package/dist/api/command-runner.js +0 -787
  623. package/dist/api/compile.js +0 -148
  624. package/dist/api/extract-types.js +0 -57
  625. package/dist/api/generate-in-place.js +0 -1477
  626. package/dist/api/generate.js +0 -514
  627. package/dist/api/helpers.js +0 -285
  628. package/dist/api/inline-runtime.js +0 -526
  629. package/dist/api/manipulation/connections.js +0 -151
  630. package/dist/api/manipulation/index.js +0 -41
  631. package/dist/api/manipulation/node-types.js +0 -200
  632. package/dist/api/manipulation/nodes.js +0 -355
  633. package/dist/api/manipulation/ports.js +0 -228
  634. package/dist/api/manipulation/scopes.js +0 -156
  635. package/dist/api/manipulation/workflow.js +0 -116
  636. package/dist/api/modify-operation.js +0 -177
  637. package/dist/api/parse.js +0 -115
  638. package/dist/api/patterns.d.ts +0 -112
  639. package/dist/api/patterns.js +0 -303
  640. package/dist/api/query.js +0 -840
  641. package/dist/api/templates.js +0 -117
  642. package/dist/api/transform.js +0 -40
  643. package/dist/api/validate.js +0 -64
  644. package/dist/api/validation-registry.js +0 -10
  645. package/dist/api/workflow-file-operations.js +0 -180
  646. package/dist/ast/builder.js +0 -395
  647. package/dist/ast/serialization-node.js +0 -30
  648. package/dist/ast/serialization.js +0 -134
  649. package/dist/ast/types.js +0 -2
  650. package/dist/ast/workflow-utils.js +0 -114
  651. package/dist/body-generator.js +0 -35
  652. package/dist/built-in-nodes/coercion-types.js +0 -61
  653. package/dist/built-in-nodes/delay.js +0 -29
  654. package/dist/built-in-nodes/generated-registry.js +0 -299
  655. package/dist/built-in-nodes/invoke-workflow.js +0 -36
  656. package/dist/built-in-nodes/mock-types.js +0 -42
  657. package/dist/built-in-nodes/wait-for-agent.js +0 -31
  658. package/dist/built-in-nodes/wait-for-event.js +0 -25
  659. package/dist/chevrotain-parser/coerce-parser.js +0 -103
  660. package/dist/chevrotain-parser/connect-parser.js +0 -136
  661. package/dist/chevrotain-parser/fan-parser.js +0 -149
  662. package/dist/chevrotain-parser/grammar-diagrams.js +0 -273
  663. package/dist/chevrotain-parser/index.js +0 -31
  664. package/dist/chevrotain-parser/map-parser.js +0 -130
  665. package/dist/chevrotain-parser/node-parser.js +0 -558
  666. package/dist/chevrotain-parser/path-parser.js +0 -140
  667. package/dist/chevrotain-parser/port-parser.js +0 -519
  668. package/dist/chevrotain-parser/position-parser.d.ts +0 -20
  669. package/dist/chevrotain-parser/position-parser.js +0 -83
  670. package/dist/chevrotain-parser/scope-parser.js +0 -104
  671. package/dist/chevrotain-parser/tokens.js +0 -429
  672. package/dist/chevrotain-parser/trigger-cancel-parser.js +0 -291
  673. package/dist/cli/commands/account.d.ts +0 -4
  674. package/dist/cli/commands/account.js +0 -50
  675. package/dist/cli/commands/ai-credentials.d.ts +0 -12
  676. package/dist/cli/commands/ai-credentials.js +0 -95
  677. package/dist/cli/commands/apikey.d.ts +0 -4
  678. package/dist/cli/commands/apikey.js +0 -64
  679. package/dist/cli/commands/auth.d.ts +0 -9
  680. package/dist/cli/commands/auth.js +0 -255
  681. package/dist/cli/commands/compile.js +0 -331
  682. package/dist/cli/commands/connect.d.ts +0 -4
  683. package/dist/cli/commands/connect.js +0 -163
  684. package/dist/cli/commands/context.js +0 -51
  685. package/dist/cli/commands/create.js +0 -139
  686. package/dist/cli/commands/deploy.d.ts +0 -6
  687. package/dist/cli/commands/deploy.js +0 -74
  688. package/dist/cli/commands/dev.js +0 -227
  689. package/dist/cli/commands/diagram.js +0 -39
  690. package/dist/cli/commands/diff.js +0 -57
  691. package/dist/cli/commands/docs.js +0 -74
  692. package/dist/cli/commands/export.js +0 -153
  693. package/dist/cli/commands/grammar.js +0 -40
  694. package/dist/cli/commands/implement.js +0 -91
  695. package/dist/cli/commands/init-personas.js +0 -541
  696. package/dist/cli/commands/init.js +0 -797
  697. package/dist/cli/commands/market.js +0 -440
  698. package/dist/cli/commands/mcp-setup.js +0 -433
  699. package/dist/cli/commands/migrate.js +0 -91
  700. package/dist/cli/commands/modify.js +0 -58
  701. package/dist/cli/commands/openapi.js +0 -71
  702. package/dist/cli/commands/org.d.ts +0 -8
  703. package/dist/cli/commands/org.js +0 -136
  704. package/dist/cli/commands/pattern.d.ts +0 -34
  705. package/dist/cli/commands/pattern.js +0 -186
  706. package/dist/cli/commands/plugin.d.ts +0 -16
  707. package/dist/cli/commands/plugin.js +0 -176
  708. package/dist/cli/commands/run.js +0 -742
  709. package/dist/cli/commands/serve.js +0 -93
  710. package/dist/cli/commands/status.js +0 -123
  711. package/dist/cli/commands/strip.js +0 -61
  712. package/dist/cli/commands/templates.js +0 -58
  713. package/dist/cli/commands/validate.js +0 -267
  714. package/dist/cli/commands/watch.js +0 -71
  715. package/dist/cli/config/credentials.d.ts +0 -15
  716. package/dist/cli/config/credentials.js +0 -43
  717. package/dist/cli/config/platform-client.d.ts +0 -123
  718. package/dist/cli/config/platform-client.js +0 -248
  719. package/dist/cli/env-setup.js +0 -12
  720. package/dist/cli/index.js +0 -850
  721. package/dist/cli/pack-commands.js +0 -122
  722. package/dist/cli/postinstall.d.ts +0 -16
  723. package/dist/cli/postinstall.js +0 -119
  724. package/dist/cli/templates/ai/mock-provider.js +0 -64
  725. package/dist/cli/templates/ai/types.js +0 -5
  726. package/dist/cli/templates/approvals/index.d.ts +0 -15
  727. package/dist/cli/templates/approvals/index.js +0 -241
  728. package/dist/cli/templates/index.js +0 -123
  729. package/dist/cli/templates/nodes/agent-router.js +0 -114
  730. package/dist/cli/templates/nodes/aggregator.js +0 -63
  731. package/dist/cli/templates/nodes/conversation-memory.js +0 -85
  732. package/dist/cli/templates/nodes/http.js +0 -80
  733. package/dist/cli/templates/nodes/human-approval.js +0 -109
  734. package/dist/cli/templates/nodes/json-extractor.js +0 -119
  735. package/dist/cli/templates/nodes/llm-call.js +0 -106
  736. package/dist/cli/templates/nodes/prompt-template.js +0 -52
  737. package/dist/cli/templates/nodes/rag-retriever.js +0 -128
  738. package/dist/cli/templates/nodes/tool-executor.js +0 -108
  739. package/dist/cli/templates/nodes/transformer.js +0 -68
  740. package/dist/cli/templates/nodes/validator.js +0 -62
  741. package/dist/cli/templates/pack-loader.js +0 -58
  742. package/dist/cli/templates/providers/index.js +0 -239
  743. package/dist/cli/templates/shared/approval-types.js +0 -31
  744. package/dist/cli/templates/shared/llm-types.js +0 -109
  745. package/dist/cli/templates/workflows/aggregator.js +0 -101
  746. package/dist/cli/templates/workflows/ai-agent.js +0 -326
  747. package/dist/cli/templates/workflows/ai-chat.js +0 -167
  748. package/dist/cli/templates/workflows/ai-rag.js +0 -184
  749. package/dist/cli/templates/workflows/ai-react.js +0 -293
  750. package/dist/cli/templates/workflows/conditional.js +0 -139
  751. package/dist/cli/templates/workflows/error-handler.js +0 -145
  752. package/dist/cli/templates/workflows/foreach.js +0 -140
  753. package/dist/cli/templates/workflows/sequential.js +0 -200
  754. package/dist/cli/templates/workflows/webhook.js +0 -158
  755. package/dist/cli/utils/cli-helpers.d.ts +0 -44
  756. package/dist/cli/utils/cli-helpers.js +0 -99
  757. package/dist/cli/utils/logger.js +0 -126
  758. package/dist/cli/utils/parse-int-strict.js +0 -17
  759. package/dist/cli/utils/safe-write.js +0 -54
  760. package/dist/deployment/config/defaults.d.ts +0 -29
  761. package/dist/deployment/config/defaults.js +0 -98
  762. package/dist/deployment/config/loader.d.ts +0 -24
  763. package/dist/deployment/config/loader.js +0 -237
  764. package/dist/deployment/config/types.d.ts +0 -117
  765. package/dist/deployment/config/types.js +0 -5
  766. package/dist/deployment/core/adapters.d.ts +0 -66
  767. package/dist/deployment/core/adapters.js +0 -156
  768. package/dist/deployment/core/executor.d.ts +0 -62
  769. package/dist/deployment/core/executor.js +0 -197
  770. package/dist/deployment/core/formatters.d.ts +0 -42
  771. package/dist/deployment/core/formatters.js +0 -146
  772. package/dist/deployment/openapi/generator.d.ts +0 -146
  773. package/dist/deployment/openapi/generator.js +0 -347
  774. package/dist/deployment/openapi/schema-converter.d.ts +0 -49
  775. package/dist/deployment/openapi/schema-converter.js +0 -192
  776. package/dist/deployment/targets/base.js +0 -855
  777. package/dist/deployment/types.d.ts +0 -140
  778. package/dist/deployment/types.js +0 -8
  779. package/dist/diagram/ascii-renderer.js +0 -528
  780. package/dist/diagram/geometry.js +0 -1267
  781. package/dist/diagram/html-viewer.d.ts +0 -21
  782. package/dist/diagram/html-viewer.js +0 -1689
  783. package/dist/diagram/layout.js +0 -143
  784. package/dist/diagram/orthogonal-router.js +0 -568
  785. package/dist/diagram/renderer.d.ts +0 -3
  786. package/dist/diagram/renderer.js +0 -266
  787. package/dist/diagram/theme.js +0 -282
  788. package/dist/diagram/types.js +0 -2
  789. package/dist/diff/WorkflowDiffer.js +0 -429
  790. package/dist/diff/formatDiff.js +0 -239
  791. package/dist/diff/impact.js +0 -119
  792. package/dist/diff/types.js +0 -35
  793. package/dist/doc-metadata/extractors/annotations.js +0 -638
  794. package/dist/doc-metadata/extractors/cli-commands.js +0 -326
  795. package/dist/doc-metadata/extractors/core-metadata.js +0 -61
  796. package/dist/doc-metadata/extractors/error-codes.js +0 -372
  797. package/dist/doc-metadata/extractors/grammar-rules.js +0 -51
  798. package/dist/doc-metadata/extractors/mcp-tools.js +0 -705
  799. package/dist/doc-metadata/extractors/plugin-api.d.ts +0 -19
  800. package/dist/doc-metadata/extractors/plugin-api.js +0 -279
  801. package/dist/doc-metadata/types.js +0 -5
  802. package/dist/editor-completions/annotationValues.js +0 -146
  803. package/dist/editor-completions/contextParser.js +0 -410
  804. package/dist/editor-completions/dataTypes.js +0 -95
  805. package/dist/editor-completions/goToDefinition.js +0 -112
  806. package/dist/editor-completions/jsDocAnnotations.js +0 -359
  807. package/dist/editor-completions/modifierCompletions.js +0 -197
  808. package/dist/editor-completions/types.js +0 -8
  809. package/dist/export/index.js +0 -212
  810. package/dist/extensions/index.d.ts +0 -16
  811. package/dist/extensions/index.js +0 -17
  812. package/dist/friendly-errors.js +0 -761
  813. package/dist/function-like.js +0 -84
  814. package/dist/generator/async-detection.js +0 -56
  815. package/dist/generator/code-utils.js +0 -551
  816. package/dist/generator/compile-target-registry.d.ts +0 -20
  817. package/dist/generator/compile-target-registry.js +0 -20
  818. package/dist/generator/control-flow.js +0 -358
  819. package/dist/generator/dev-mode-registry.d.ts +0 -27
  820. package/dist/generator/dev-mode-registry.js +0 -20
  821. package/dist/generator/scope-function-generator.js +0 -397
  822. package/dist/generator/unified.js +0 -1831
  823. package/dist/generator.d.ts +0 -54
  824. package/dist/generator.js +0 -101
  825. package/dist/jsdoc-parser.d.ts +0 -377
  826. package/dist/jsdoc-parser.js +0 -1189
  827. package/dist/jsdoc-port-sync/constants.js +0 -103
  828. package/dist/jsdoc-port-sync/diff.js +0 -319
  829. package/dist/jsdoc-port-sync/port-parser.js +0 -579
  830. package/dist/jsdoc-port-sync/rename.js +0 -256
  831. package/dist/jsdoc-port-sync/signature-parser.js +0 -559
  832. package/dist/jsdoc-port-sync/sync.js +0 -653
  833. package/dist/marketplace/manifest.js +0 -194
  834. package/dist/marketplace/registry.js +0 -198
  835. package/dist/marketplace/types.js +0 -9
  836. package/dist/marketplace/validator.js +0 -150
  837. package/dist/mcp/agent-channel.d.ts +0 -35
  838. package/dist/mcp/agent-channel.js +0 -61
  839. package/dist/mcp/auto-registration.d.ts +0 -3
  840. package/dist/mcp/auto-registration.js +0 -62
  841. package/dist/mcp/debug-session.js +0 -25
  842. package/dist/mcp/index.d.ts +0 -11
  843. package/dist/mcp/index.js +0 -10
  844. package/dist/mcp/pack-tools.js +0 -59
  845. package/dist/mcp/prompts.js +0 -68
  846. package/dist/mcp/response-utils.js +0 -97
  847. package/dist/mcp/run-registry.d.ts +0 -29
  848. package/dist/mcp/run-registry.js +0 -24
  849. package/dist/mcp/server.js +0 -63
  850. package/dist/mcp/tools-context.js +0 -51
  851. package/dist/mcp/tools-debug.js +0 -451
  852. package/dist/mcp/tools-diagram.js +0 -97
  853. package/dist/mcp/tools-docs.js +0 -62
  854. package/dist/mcp/tools-export.js +0 -222
  855. package/dist/mcp/tools-marketplace.js +0 -132
  856. package/dist/mcp/tools-model.d.ts +0 -3
  857. package/dist/mcp/tools-model.js +0 -279
  858. package/dist/mcp/tools-pattern.d.ts +0 -3
  859. package/dist/mcp/tools-pattern.js +0 -604
  860. package/dist/mcp/tools-query.js +0 -377
  861. package/dist/mcp/tools-resources.js +0 -41
  862. package/dist/mcp/tools-template.js +0 -119
  863. package/dist/mcp/tools-workflow-run.d.ts +0 -40
  864. package/dist/mcp/tools-workflow-run.js +0 -150
  865. package/dist/mcp/types.js +0 -2
  866. package/dist/mcp/workflow-executor.js +0 -242
  867. package/dist/migration/registry.js +0 -29
  868. package/dist/node-types-generator.js +0 -139
  869. package/dist/parser/tag-registry.js +0 -57
  870. package/dist/parser.d.ts +0 -232
  871. package/dist/parser.js +0 -2500
  872. package/dist/plugin/PluginPanel.d.ts +0 -12
  873. package/dist/plugin/PluginPanel.js +0 -5
  874. package/dist/plugin/index.d.ts +0 -13
  875. package/dist/plugin/index.js +0 -14
  876. package/dist/plugin/types.d.ts +0 -75
  877. package/dist/plugin/types.js +0 -8
  878. package/dist/resolve-package-types.js +0 -123
  879. package/dist/runtime/CancellationError.js +0 -20
  880. package/dist/runtime/ExecutionContext.js +0 -280
  881. package/dist/runtime/builtin-functions.js +0 -549
  882. package/dist/runtime/checkpoint.d.ts +0 -84
  883. package/dist/runtime/checkpoint.js +0 -225
  884. package/dist/runtime/debug-controller.js +0 -247
  885. package/dist/runtime/events.js +0 -2
  886. package/dist/runtime/function-registry.js +0 -66
  887. package/dist/runtime/parameter-resolver.js +0 -113
  888. package/dist/server/types.js +0 -5
  889. package/dist/server/webhook-server.js +0 -269
  890. package/dist/server/workflow-registry.js +0 -202
  891. package/dist/shared-project.js +0 -28
  892. package/dist/sugar-optimizer.js +0 -498
  893. package/dist/testing/assertions.js +0 -127
  894. package/dist/testing/mock-approval.js +0 -98
  895. package/dist/testing/mock-llm.js +0 -119
  896. package/dist/testing/recorder.js +0 -70
  897. package/dist/testing/replayer.js +0 -143
  898. package/dist/testing/token-tracker.js +0 -94
  899. package/dist/type-checker.d.ts +0 -42
  900. package/dist/type-checker.js +0 -190
  901. package/dist/type-mappings.js +0 -131
  902. package/dist/types/branded-ports.d.ts +0 -151
  903. package/dist/types/branded-ports.js +0 -121
  904. package/dist/types/index.d.ts +0 -5
  905. package/dist/types/index.js +0 -5
  906. package/dist/types.d.ts +0 -139
  907. package/dist/types.js +0 -15
  908. package/dist/utils/error-utils.js +0 -27
  909. package/dist/utils/lru-cache.js +0 -40
  910. package/dist/utils/port-ordering.js +0 -81
  911. package/dist/utils/port-tag-utils.js +0 -41
  912. package/dist/utils/string-distance.js +0 -56
  913. package/dist/validation/agent-detection.js +0 -115
  914. package/dist/validation/agent-rules.js +0 -262
  915. package/dist/validation/design-rules.js +0 -377
  916. package/dist/validation/rule-registry.js +0 -37
  917. package/dist/validator.d.ts +0 -113
  918. package/dist/validator.js +0 -1631
  919. package/docs/reference/patterns.md +0 -159
  920. package/scripts/postinstall.cjs +0 -86
  921. /package/dist/{shared-project.d.ts → parser/shared-project.d.ts} +0 -0
  922. /package/dist/{friendly-errors.d.ts → validation/friendly-errors.d.ts} +0 -0
@@ -0,0 +1,2219 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ const require = __createRequire(import.meta.url);
3
+ import {
4
+ MissingParamsError,
5
+ missingParams
6
+ } from "./flow-weaver-chunk-EKWF27G6.mjs";
7
+ import {
8
+ DEFAULT_MAX_ITERATIONS,
9
+ DEFAULT_MODEL,
10
+ keyEnvOf,
11
+ loadAgentProfiles,
12
+ profileForGate,
13
+ readiness
14
+ } from "./flow-weaver-chunk-TS5P3PIN.mjs";
15
+ import {
16
+ ContinuationRefusalError,
17
+ executeWorkflow
18
+ } from "./flow-weaver-chunk-GBUNNP33.mjs";
19
+ import {
20
+ getAvailableWorkflows
21
+ } from "./flow-weaver-chunk-NQKKWDGF.mjs";
22
+ import {
23
+ DurableSourceProof,
24
+ applyDurableSourceProof,
25
+ compileWorkflow
26
+ } from "./flow-weaver-chunk-V6DHWFQG.mjs";
27
+ import {
28
+ GENERATOR_ABI,
29
+ graphIdentity,
30
+ validateWireValue
31
+ } from "./flow-weaver-chunk-A6M5K3W7.mjs";
32
+ import {
33
+ isMultipleWorkflows,
34
+ parseWorkflow,
35
+ parseWorkflowSourceAtPath
36
+ } from "./flow-weaver-chunk-W3YNK26P.mjs";
37
+ import {
38
+ validateDurableClosure
39
+ } from "./flow-weaver-chunk-EM5HWQ4R.mjs";
40
+ import {
41
+ getErrorMessage
42
+ } from "./flow-weaver-chunk-OMVWSNHJ.mjs";
43
+
44
+ // src/coordinator/runs-dir.ts
45
+ import * as fs from "node:fs";
46
+ import * as os from "node:os";
47
+ import * as path from "node:path";
48
+ function resolveProjectRoot(anchor) {
49
+ let current;
50
+ try {
51
+ current = fs.statSync(anchor).isDirectory() ? path.resolve(anchor) : path.dirname(path.resolve(anchor));
52
+ } catch {
53
+ current = path.dirname(path.resolve(anchor));
54
+ }
55
+ const root = path.parse(current).root;
56
+ for (let dir = current; ; dir = path.dirname(dir)) {
57
+ if (fs.existsSync(path.join(dir, "package.json")) || fs.existsSync(path.join(dir, ".fw"))) {
58
+ return dir;
59
+ }
60
+ if (dir === root || path.dirname(dir) === dir) break;
61
+ }
62
+ return current;
63
+ }
64
+ function defaultRunsDir(anchor) {
65
+ if (process.env.FW_RUNS_DIR) return process.env.FW_RUNS_DIR;
66
+ if (anchor) return path.join(resolveProjectRoot(anchor), ".fw", "runs");
67
+ return path.join(os.homedir(), ".fw", "runs");
68
+ }
69
+
70
+ // src/coordinator/run-store.ts
71
+ import * as path6 from "node:path";
72
+
73
+ // src/coordinator/run-context.ts
74
+ import { randomUUID as randomUUID2 } from "node:crypto";
75
+ import * as os3 from "node:os";
76
+
77
+ // src/coordinator/store.ts
78
+ var DOC_NAME = /^[a-z0-9][a-z0-9_-]{0,80}$/i;
79
+ var RESERVED_DOCS = ["continuation", "trace", "claim", "run"];
80
+ var EFFECT_DOC_PREFIX = "effect-";
81
+ function checkDocName(name) {
82
+ if (!DOC_NAME.test(name)) throw new Error(`not a valid document name: ${name}`);
83
+ }
84
+ var RunBusyError = class extends Error {
85
+ constructor(runId) {
86
+ super(`run ${runId} is being driven by another process. Try again shortly`);
87
+ this.runId = runId;
88
+ }
89
+ runId;
90
+ name = "RunBusyError";
91
+ };
92
+
93
+ // src/coordinator/file-store.ts
94
+ import * as fs2 from "node:fs";
95
+ import * as os2 from "node:os";
96
+ import * as path2 from "node:path";
97
+ import { randomUUID } from "node:crypto";
98
+ function samePath(a, b) {
99
+ const norm = (p) => {
100
+ const resolved = path2.resolve(p).split(path2.sep).join("/");
101
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
102
+ };
103
+ return norm(a) === norm(b);
104
+ }
105
+ var isRunSegment = (runId) => runId.length > 0 && runId.length <= 200 && runId !== "." && runId !== ".." && !/[/\\\0]/.test(runId);
106
+ function createFileRunStore(rootDir) {
107
+ const runDir = (runId) => {
108
+ if (!isRunSegment(runId)) throw new Error(`not a valid run id for the file store: ${JSON.stringify(runId)}`);
109
+ return path2.join(rootDir, runId);
110
+ };
111
+ const recordFile = (runId) => path2.join(runDir(runId), "run.json");
112
+ const claimFile = (runId) => path2.join(runDir(runId), "claim.json");
113
+ const docFile = (runId, name) => {
114
+ checkDocName(name);
115
+ if (name.startsWith(EFFECT_DOC_PREFIX)) return path2.join(runDir(runId), "effects", `${name.slice(EFFECT_DOC_PREFIX.length)}.json`);
116
+ return path2.join(runDir(runId), `${name}.json`);
117
+ };
118
+ const readJson = (file) => {
119
+ if (!fs2.existsSync(file)) return void 0;
120
+ try {
121
+ return JSON.parse(fs2.readFileSync(file, "utf8"));
122
+ } catch {
123
+ return void 0;
124
+ }
125
+ };
126
+ const writeAtomic = (file, data) => {
127
+ fs2.mkdirSync(path2.dirname(file), { recursive: true });
128
+ const tmp = `${file}.tmp-${randomUUID()}`;
129
+ fs2.writeFileSync(tmp, JSON.stringify(data));
130
+ fs2.renameSync(tmp, file);
131
+ };
132
+ const standing = (c) => {
133
+ if (!c) return false;
134
+ if (Date.parse(c.expiresAt) <= Date.now()) return false;
135
+ if (c.host !== os2.hostname() || c.pid === process.pid) return true;
136
+ try {
137
+ process.kill(c.pid, 0);
138
+ return true;
139
+ } catch (e) {
140
+ return e.code !== "ESRCH";
141
+ }
142
+ };
143
+ return {
144
+ async get(runId) {
145
+ return isRunSegment(runId) ? readJson(recordFile(runId)) : void 0;
146
+ },
147
+ async put(record) {
148
+ writeAtomic(recordFile(record.runId), record);
149
+ },
150
+ async list(filter = {}) {
151
+ if (!fs2.existsSync(rootDir)) return [];
152
+ const wanted = filter.filePath ? path2.resolve(filter.filePath) : void 0;
153
+ const records = [];
154
+ for (const entry of fs2.readdirSync(rootDir)) {
155
+ const record = readJson(recordFile(entry));
156
+ if (!record) continue;
157
+ if (wanted && !samePath(record.filePath, wanted)) continue;
158
+ records.push(record);
159
+ }
160
+ return records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
161
+ },
162
+ async remove(runId) {
163
+ fs2.rmSync(runDir(runId), { recursive: true, force: true });
164
+ },
165
+ async getDoc(runId, name) {
166
+ return isRunSegment(runId) ? readJson(docFile(runId, name)) : void 0;
167
+ },
168
+ async putDoc(runId, name, data) {
169
+ writeAtomic(docFile(runId, name), data);
170
+ },
171
+ async deleteDoc(runId, name) {
172
+ fs2.rmSync(docFile(runId, name), { force: true });
173
+ },
174
+ async claim(runId, owner, ttlMs) {
175
+ const file = claimFile(runId);
176
+ const mine = { owner, pid: process.pid, host: os2.hostname(), expiresAt: new Date(Date.now() + ttlMs).toISOString() };
177
+ fs2.mkdirSync(runDir(runId), { recursive: true });
178
+ for (let attempt = 0; attempt < 3; attempt++) {
179
+ const current = readJson(file);
180
+ if (standing(current) && current.owner !== owner) return false;
181
+ if (standing(current) && current.owner === owner) {
182
+ writeAtomic(file, mine);
183
+ return true;
184
+ }
185
+ if (current) {
186
+ const aside = `${file}.lapsed-${randomUUID().slice(0, 8)}`;
187
+ try {
188
+ fs2.renameSync(file, aside);
189
+ } catch (e) {
190
+ if (e.code !== "ENOENT") throw e;
191
+ continue;
192
+ }
193
+ fs2.rmSync(aside, { force: true });
194
+ }
195
+ try {
196
+ fs2.writeFileSync(file, JSON.stringify(mine), { flag: "wx" });
197
+ return true;
198
+ } catch (e) {
199
+ if (e.code !== "EEXIST") throw e;
200
+ }
201
+ }
202
+ return false;
203
+ },
204
+ async release(runId, owner) {
205
+ const file = claimFile(runId);
206
+ const current = readJson(file);
207
+ if (current?.owner === owner) fs2.rmSync(file, { force: true });
208
+ }
209
+ };
210
+ }
211
+
212
+ // src/coordinator/run-context.ts
213
+ function createRunContext(options) {
214
+ const store = options.store ?? createFileRunStore(options.rootDir ?? defaultRunsDir());
215
+ const claimTtl = options.claimTtlMs ?? 60 * 60 * 1e3;
216
+ const instance = `${os3.hostname()}:${process.pid}:${randomUUID2().slice(0, 8)}`;
217
+ let uses = 0;
218
+ async function claimed(runId, work) {
219
+ const owner = `${instance}:${++uses}`;
220
+ if (!await store.claim(runId, owner, claimTtl)) throw new RunBusyError(runId);
221
+ try {
222
+ return await work();
223
+ } finally {
224
+ await store.release(runId, owner);
225
+ }
226
+ }
227
+ async function readRecord(runId) {
228
+ return store.get(runId);
229
+ }
230
+ return { store, claimed, readRecord };
231
+ }
232
+
233
+ // src/coordinator/run-start.ts
234
+ import { randomUUID as randomUUID3 } from "node:crypto";
235
+ import * as path5 from "node:path";
236
+
237
+ // src/coordinator/bundle-digest.ts
238
+ import { createHash } from "node:crypto";
239
+ import { readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
240
+
241
+ // src/compiler/executable-artifact.ts
242
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
243
+ import { tmpdir } from "node:os";
244
+ import { dirname as dirname3, join as join3 } from "node:path";
245
+ import ts from "typescript";
246
+
247
+ // src/runtime/executable-module-contract.ts
248
+ var EXECUTABLE_WORKFLOW_MODULE_FORMAT = 1;
249
+ var EXECUTABLE_WORKFLOW_METADATA_EXPORT = "__flowWeaverExecutableArtifact";
250
+
251
+ // src/compiler/executable-artifact.ts
252
+ async function compileExecutableWorkflowArtifact(request) {
253
+ if (request.workflowName.trim().length === 0) {
254
+ throw new Error("workflowName must be non-empty");
255
+ }
256
+ const workflows = getAvailableWorkflows(request.source);
257
+ if (!workflows.some((workflow) => workflow.functionName === request.workflowName)) {
258
+ throw new Error(`Workflow ${request.workflowName} is not declared by the artifact source`);
259
+ }
260
+ const directory = await mkdtemp(join3(tmpdir(), "flow-weaver-artifact-"));
261
+ const filePath = join3(directory, "workflow.ts");
262
+ try {
263
+ const durableSourceProof = request.durableValidationSource === void 0 ? void 0 : DurableSourceProof.create(
264
+ await parseWorkflowSourceAtPath(
265
+ request.durableValidationSource.sourcePath,
266
+ request.durableValidationSource.source,
267
+ {
268
+ workflowName: request.workflowName,
269
+ ...request.externalNodeTypes === void 0 ? {} : { externalNodeTypes: [...request.externalNodeTypes] },
270
+ ...request.durableValidationSource.resolveImport === void 0 ? {} : { sourceImportResolver: request.durableValidationSource.resolveImport },
271
+ ...request.durableValidationSource.loadSource === void 0 ? {} : { sourceOverrideLoader: request.durableValidationSource.loadSource }
272
+ }
273
+ ),
274
+ request.durableValidationSource.source
275
+ );
276
+ await writeFile(filePath, request.source, { encoding: "utf8", mode: 384 });
277
+ const metadata = await createExecutableWorkflowMetadata(
278
+ filePath,
279
+ request.workflowName,
280
+ request.externalNodeTypes,
281
+ durableSourceProof,
282
+ request.source
283
+ );
284
+ for (const workflow of workflows) {
285
+ await compileWorkflow(filePath, {
286
+ write: true,
287
+ inPlace: true,
288
+ parse: {
289
+ workflowName: workflow.functionName,
290
+ ...request.externalNodeTypes === void 0 ? {} : { externalNodeTypes: [...request.externalNodeTypes] }
291
+ },
292
+ // The deployed artifact keeps step instrumentation. A runtime may
293
+ // choose not to subscribe, but it must be able to report steps.
294
+ generate: { production: false },
295
+ ...durableSourceProof === void 0 ? {} : {
296
+ durableSourceProof,
297
+ durableFlattenedSource: request.source
298
+ }
299
+ });
300
+ }
301
+ const generated = await readFile(filePath, "utf8");
302
+ const transpiled = ts.transpileModule(generated, {
303
+ compilerOptions: {
304
+ module: ts.ModuleKind.ESNext,
305
+ target: ts.ScriptTarget.ESNext,
306
+ esModuleInterop: true
307
+ }
308
+ }).outputText;
309
+ const metadataExport = `
310
+ export const ${EXECUTABLE_WORKFLOW_METADATA_EXPORT} = Object.freeze(${JSON.stringify(metadata)});
311
+ `;
312
+ return Object.freeze({
313
+ formatVersion: 1,
314
+ workflowName: request.workflowName,
315
+ code: `${transpiled}${metadataExport}`
316
+ });
317
+ } finally {
318
+ await rm(directory, { recursive: true, force: true });
319
+ }
320
+ }
321
+ async function createExecutableWorkflowMetadata(filePath, workflowName, externalNodeTypes, durableSourceProof, flattenedSource) {
322
+ const parsed = await parseWorkflow(filePath, {
323
+ workflowName,
324
+ projectDir: dirname3(filePath),
325
+ ...externalNodeTypes === void 0 ? {} : { externalNodeTypes: [...externalNodeTypes] }
326
+ });
327
+ if (parsed.errors.length > 0) {
328
+ throw new Error(`Cannot emit executable artifact metadata: ${parsed.errors.join("; ")}`);
329
+ }
330
+ if (durableSourceProof !== void 0) {
331
+ applyDurableSourceProof(durableSourceProof, parsed, flattenedSource);
332
+ }
333
+ validateDurableClosure(parsed.ast, parsed.allWorkflows);
334
+ const { graphFingerprint, continuationGraph, capabilities } = graphIdentity(parsed.ast, parsed.allWorkflows);
335
+ return Object.freeze({
336
+ formatVersion: EXECUTABLE_WORKFLOW_MODULE_FORMAT,
337
+ generatorAbi: GENERATOR_ABI,
338
+ workflowName,
339
+ workflowNames: parsed.allWorkflows.map((workflow) => workflow.functionName).sort(),
340
+ graphFingerprint,
341
+ continuationGraph,
342
+ capabilities
343
+ });
344
+ }
345
+
346
+ // src/coordinator/bundle-digest.ts
347
+ var cache = /* @__PURE__ */ new Map();
348
+ async function computeBundleDigest(filePath, workflowName) {
349
+ const stat = statSync2(filePath);
350
+ const key = `${filePath}\0${workflowName}`;
351
+ const hit = cache.get(key);
352
+ if (hit && hit.mtimeMs === stat.mtimeMs && hit.size === stat.size) return hit.digest;
353
+ const source = readFileSync2(filePath, "utf8");
354
+ const artifact = await compileExecutableWorkflowArtifact({ source, workflowName });
355
+ const digest = "sha256:" + createHash("sha256").update(artifact.code).digest("hex");
356
+ cache.set(key, { mtimeMs: stat.mtimeMs, size: stat.size, digest });
357
+ return digest;
358
+ }
359
+
360
+ // src/coordinator/effect-receipts.ts
361
+ import { createHash as createHash2 } from "node:crypto";
362
+ import * as path3 from "node:path";
363
+ var effectDoc = (operationKey) => `${EFFECT_DOC_PREFIX}${createHash2("sha256").update(operationKey).digest("hex")}`;
364
+ function createStoreEffectAdapter(store, runId) {
365
+ return {
366
+ async recover(operationKey) {
367
+ let doc;
368
+ try {
369
+ doc = await store.getDoc(runId, effectDoc(operationKey));
370
+ } catch {
371
+ return { kind: "ambiguous" };
372
+ }
373
+ if (doc === void 0) return { kind: "not-committed" };
374
+ if (typeof doc !== "object" || doc === null || !("receipt" in doc)) return { kind: "ambiguous" };
375
+ const record = doc;
376
+ return { kind: "committed", receipt: record.receipt, result: record.result };
377
+ },
378
+ async commit(operationKey, address, execution) {
379
+ await store.putDoc(runId, effectDoc(operationKey), { operationKey, address, result: execution.result, receipt: execution.receipt });
380
+ }
381
+ };
382
+ }
383
+ function createFileEffectAdapter(runDir) {
384
+ return createStoreEffectAdapter(createFileRunStore(path3.dirname(runDir)), path3.basename(runDir));
385
+ }
386
+
387
+ // src/coordinator/gate-labeling.ts
388
+ function labelGate(gate, ast) {
389
+ const instance = ast.instances.find((candidate) => candidate.id === gate.address.nodeId);
390
+ if (!instance) {
391
+ throw new Error(`gate node not found in workflow: ${gate.address.nodeId}`);
392
+ }
393
+ const nodeType = findNodeType(ast.nodeTypes, instance.nodeType, gate.address.nodeType);
394
+ if (!nodeType) {
395
+ throw new Error(
396
+ `node type not found for gate ${gate.address.nodeId}: ${instance.nodeType} / ${gate.address.nodeType}`
397
+ );
398
+ }
399
+ const names = dataPorts(nodeType.inputs);
400
+ const args = readArguments(gate.payload);
401
+ if (args.length !== names.length) {
402
+ throw new Error(
403
+ `gate payload has ${args.length} arguments but node type ${nodeType.name} declares ${names.length} inputs`
404
+ );
405
+ }
406
+ const inputs = {};
407
+ const absent = [];
408
+ names.forEach((name, index) => {
409
+ const argument = args[index];
410
+ if ("absent" in argument) {
411
+ inputs[name] = null;
412
+ absent.push(name);
413
+ } else {
414
+ inputs[name] = argument.value;
415
+ }
416
+ });
417
+ return {
418
+ inputs,
419
+ absent,
420
+ outputs: dataPorts(nodeType.outputs),
421
+ hasSuccessPort: nodeType.hasSuccessPort,
422
+ hasFailurePort: nodeType.hasFailurePort
423
+ };
424
+ }
425
+ var CONTROL_PORT_NAMES = /* @__PURE__ */ new Set(["execute", "onSuccess", "onFailure"]);
426
+ function dataPorts(ports) {
427
+ return Object.keys(ports).filter(
428
+ (name) => !CONTROL_PORT_NAMES.has(name) && !ports[name].isControlFlow
429
+ );
430
+ }
431
+ function findNodeType(nodeTypes, instanceTypeName, functionName) {
432
+ return nodeTypes.find((candidate) => candidate.name === instanceTypeName) ?? nodeTypes.find((candidate) => candidate.functionName === functionName);
433
+ }
434
+ function readArguments(payload) {
435
+ if (typeof payload !== "object" || payload === null || !Array.isArray(payload.arguments)) {
436
+ throw new Error("gate payload is not a positional argument list");
437
+ }
438
+ return payload.arguments;
439
+ }
440
+
441
+ // src/coordinator/run-trace.ts
442
+ function observe(options) {
443
+ const tracing = options?.trace === true || options?.onEvent !== void 0;
444
+ if (!tracing) return { kept: void 0, request: { includeTrace: false, production: true } };
445
+ const kept = [];
446
+ const onEvent = (event) => {
447
+ kept.push({ t: event.timestamp, e: event.data ?? event });
448
+ options?.onEvent?.(event);
449
+ };
450
+ return { kept, request: { includeTrace: true, production: false, onEvent } };
451
+ }
452
+ async function appendTrace(store, record, kept) {
453
+ if (!kept) return false;
454
+ const previous = await readTrace(store, record.runId);
455
+ await store.putDoc(record.runId, "trace", [...previous, ...kept]);
456
+ return true;
457
+ }
458
+ async function readTrace(store, runId) {
459
+ const doc = await store.getDoc(runId, "trace");
460
+ return Array.isArray(doc) ? doc : [];
461
+ }
462
+ function failedNodeIn(kept) {
463
+ if (!kept) return void 0;
464
+ for (let i = kept.length - 1; i >= 0; i--) {
465
+ const e = kept[i].e;
466
+ if (e?.type === "LOG_ERROR" && e.id) return e.id;
467
+ if (e?.type === "STATUS_CHANGED" && e.status === "FAILED" && e.id) return e.id;
468
+ }
469
+ return void 0;
470
+ }
471
+
472
+ // src/built-in-nodes/delay.ts
473
+ function parseDuration(text) {
474
+ if (typeof text !== "string") return void 0;
475
+ const match = /^\s*(\d+)\s*(ms|s|m|h|d)\s*$/.exec(text);
476
+ if (!match) return void 0;
477
+ const units = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
478
+ return Number(match[1]) * units[match[2]];
479
+ }
480
+
481
+ // src/coordinator/time.ts
482
+ function dueFor(gate, now = Date.now()) {
483
+ if (gate.kind === "timer") {
484
+ const ms2 = parseDuration(gate.inputs.duration) ?? 0;
485
+ return { at: new Date(now + ms2).toISOString(), action: "wake" };
486
+ }
487
+ const ms = parseDuration(gate.inputs.timeout);
488
+ if (ms === void 0 || !gate.hasFailurePort) return void 0;
489
+ return { at: new Date(now + ms).toISOString(), action: "timeout" };
490
+ }
491
+
492
+ // src/coordinator/run-outcome.ts
493
+ async function commit(store, record, outcome, ast, kept) {
494
+ const now = (/* @__PURE__ */ new Date()).toISOString();
495
+ const traced = await appendTrace(store, record, kept);
496
+ if (outcome.kind === "yielded") {
497
+ const labeled = labelGate(outcome.gate, ast);
498
+ const gate = {
499
+ id: outcome.gate.id,
500
+ kind: outcome.gate.kind,
501
+ node: outcome.gate.address.nodeId,
502
+ nodeType: outcome.gate.address.nodeType,
503
+ ...labeled
504
+ };
505
+ const next2 = {
506
+ ...record,
507
+ traced,
508
+ status: "waiting",
509
+ gate,
510
+ continuation: outcome.continuation,
511
+ due: dueFor(gate),
512
+ result: void 0,
513
+ error: void 0,
514
+ updatedAt: now
515
+ };
516
+ if (next2.due === void 0) delete next2.due;
517
+ await store.put(next2);
518
+ return next2;
519
+ }
520
+ const next = {
521
+ ...record,
522
+ traced,
523
+ status: "completed",
524
+ gate: void 0,
525
+ continuation: void 0,
526
+ due: void 0,
527
+ result: outcome.result,
528
+ error: void 0,
529
+ updatedAt: now
530
+ };
531
+ await store.put(next);
532
+ await store.deleteDoc(record.runId, "continuation");
533
+ return next;
534
+ }
535
+ async function fail(store, record, error, options, kept) {
536
+ const traced = await appendTrace(store, record, kept);
537
+ const message = getErrorMessage(error);
538
+ const cancelled = options?.abortSignal?.aborted === true;
539
+ await store.put({
540
+ ...record,
541
+ traced,
542
+ status: cancelled ? "cancelled" : "failed",
543
+ gate: void 0,
544
+ continuation: void 0,
545
+ due: void 0,
546
+ result: void 0,
547
+ error: cancelled ? void 0 : message,
548
+ failedNode: cancelled ? void 0 : failedNodeIn(kept),
549
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
550
+ });
551
+ await store.deleteDoc(record.runId, "continuation");
552
+ }
553
+
554
+ // src/coordinator/run-views.ts
555
+ function toView(record) {
556
+ const view = {
557
+ status: record.status,
558
+ runId: record.runId,
559
+ workflowName: record.workflowName
560
+ };
561
+ if (record.status === "waiting" && record.gate) {
562
+ view.gate = {
563
+ kind: record.gate.kind,
564
+ node: record.gate.node,
565
+ inputs: record.gate.inputs,
566
+ absent: record.gate.absent
567
+ };
568
+ if (record.due) view.due = record.due;
569
+ }
570
+ if (record.status === "completed") view.result = record.result;
571
+ if (record.status === "failed") view.error = record.error;
572
+ return view;
573
+ }
574
+ function toSummary(record) {
575
+ return {
576
+ status: record.status,
577
+ runId: record.runId,
578
+ workflowName: record.workflowName,
579
+ filePath: record.filePath,
580
+ gate: record.gate ? { kind: record.gate.kind, node: record.gate.node } : void 0,
581
+ due: record.due,
582
+ params: record.params,
583
+ failedNode: record.failedNode,
584
+ mocks: record.mocks,
585
+ source: record.source,
586
+ agents: record.agents,
587
+ agent: record.agent ? { status: record.agent.status, profile: record.agent.profile, node: record.agent.node } : void 0,
588
+ origin: record.origin,
589
+ createdAt: record.createdAt,
590
+ updatedAt: record.updatedAt
591
+ };
592
+ }
593
+
594
+ // src/coordinator/workflow-selection.ts
595
+ import * as path4 from "node:path";
596
+
597
+ // src/coordinator/errors.ts
598
+ var ParseError = class extends Error {
599
+ name = "ParseError";
600
+ };
601
+ var AmbiguousWorkflowError = class extends Error {
602
+ constructor(names) {
603
+ super(`file declares several workflows. Pass workflowName, one of: ${names.join(", ")}`);
604
+ this.names = names;
605
+ }
606
+ names;
607
+ name = "AmbiguousWorkflowError";
608
+ };
609
+ var RunNotFoundError = class extends Error {
610
+ name = "RunNotFoundError";
611
+ constructor(runId) {
612
+ super(`no run with id ${runId}`);
613
+ }
614
+ };
615
+ var RunNotWaitingError = class extends Error {
616
+ constructor(status) {
617
+ super(`run is ${status}, not waiting at a gate`);
618
+ this.status = status;
619
+ }
620
+ status;
621
+ name = "RunNotWaitingError";
622
+ };
623
+ var BundleChangedError = class extends Error {
624
+ name = "BundleChangedError";
625
+ constructor() {
626
+ super("workflow or its compiled output changed since the run paused. Start a new run");
627
+ }
628
+ };
629
+
630
+ // src/coordinator/workflow-selection.ts
631
+ async function parseSelected(filePath, requested) {
632
+ const projectDir = path4.dirname(filePath);
633
+ const first = await parseWorkflow(filePath, { workflowName: requested, projectDir });
634
+ if (requested === void 0 && isMultipleWorkflows(first.errors)) throw new AmbiguousWorkflowError(first.availableWorkflows);
635
+ if (first.errors.length > 0) throw new ParseError(first.errors.join("\n"));
636
+ const available = first.availableWorkflows;
637
+ let workflowName = requested;
638
+ if (workflowName === void 0) {
639
+ if (available.length === 1) workflowName = available[0];
640
+ else throw new AmbiguousWorkflowError(available);
641
+ } else if (!available.includes(workflowName)) {
642
+ throw new ParseError(`workflow ${workflowName} not found. Available: ${available.join(", ")}`);
643
+ }
644
+ if (first.ast.functionName === workflowName) return { ast: first.ast, workflowName };
645
+ const second = await parseWorkflow(filePath, { workflowName, projectDir });
646
+ if (second.errors.length > 0) throw new ParseError(second.errors.join("\n"));
647
+ return { ast: second.ast, workflowName };
648
+ }
649
+
650
+ // src/coordinator/run-start.ts
651
+ async function startRun(ctx, request, options) {
652
+ const { store, claimed } = ctx;
653
+ const filePath = path5.resolve(request.filePath);
654
+ const { ast, workflowName } = await parseSelected(filePath, request.workflowName);
655
+ const missing = missingParams(ast, request.params);
656
+ if (missing.length) throw new MissingParamsError(workflowName, missing);
657
+ const bundleDigest = await computeBundleDigest(filePath, workflowName);
658
+ const now = (/* @__PURE__ */ new Date()).toISOString();
659
+ const record = {
660
+ formatVersion: 1,
661
+ runId: request.runId ?? randomUUID3(),
662
+ filePath,
663
+ workflowName,
664
+ params: request.params ?? {},
665
+ bundleDigest,
666
+ status: "waiting",
667
+ ...request.mocks ? { mocks: request.mocks } : {},
668
+ ...request.source ? { source: request.source } : {},
669
+ ...request.agents ? { agents: request.agents } : {},
670
+ ...request.origin ? { origin: request.origin } : {},
671
+ createdAt: now,
672
+ updatedAt: now
673
+ };
674
+ return claimed(record.runId, async () => {
675
+ const { kept, request: observed } = observe(options);
676
+ let outcome;
677
+ try {
678
+ outcome = await executeWorkflow({
679
+ runId: record.runId,
680
+ bundleDigest,
681
+ filePath,
682
+ params: record.params,
683
+ workflowName,
684
+ mocks: record.mocks,
685
+ ...observed,
686
+ abortSignal: options?.abortSignal,
687
+ effectAdapter: createStoreEffectAdapter(store, record.runId)
688
+ });
689
+ } catch (error) {
690
+ await fail(store, record, error, options, kept);
691
+ throw error;
692
+ }
693
+ return toView(await commit(store, record, outcome, ast, kept));
694
+ });
695
+ }
696
+
697
+ // src/coordinator/gate-resolution.ts
698
+ var MissingOutputsError = class extends Error {
699
+ constructor(missing) {
700
+ super(`answer is missing gate outputs: ${missing.join(", ")}`);
701
+ this.missing = missing;
702
+ }
703
+ missing;
704
+ name = "MissingOutputsError";
705
+ };
706
+ var InvalidAnswerError = class extends Error {
707
+ name = "InvalidAnswerError";
708
+ };
709
+ function buildGateResolution(gate, gateId, input) {
710
+ const value = {};
711
+ if ("reject" in input) {
712
+ if (gate.hasSuccessPort) value.onSuccess = false;
713
+ if (gate.hasFailurePort) value.onFailure = true;
714
+ for (const port of gate.outputs) value[port] = null;
715
+ } else {
716
+ if (gate.hasSuccessPort) value.onSuccess = true;
717
+ if (gate.hasFailurePort) value.onFailure = false;
718
+ Object.assign(value, dataPorts2(gate.outputs, input.answer));
719
+ }
720
+ try {
721
+ validateWireValue(value);
722
+ } catch (error) {
723
+ throw new InvalidAnswerError(getErrorMessage(error));
724
+ }
725
+ return { gateId, value };
726
+ }
727
+ function dataPorts2(outputs, answer) {
728
+ if (outputs.length === 0) {
729
+ if (answer !== null && answer !== void 0) {
730
+ throw new InvalidAnswerError("this gate has no data outputs, so answer must be null");
731
+ }
732
+ return {};
733
+ }
734
+ if (outputs.length === 1) {
735
+ return { [outputs[0]]: answer };
736
+ }
737
+ if (typeof answer !== "object" || answer === null || Array.isArray(answer)) {
738
+ throw new MissingOutputsError(outputs);
739
+ }
740
+ const record = answer;
741
+ const missing = outputs.filter((port) => !(port in record));
742
+ if (missing.length > 0) throw new MissingOutputsError(missing);
743
+ const picked = {};
744
+ for (const port of outputs) picked[port] = record[port];
745
+ return picked;
746
+ }
747
+
748
+ // src/coordinator/run-resume.ts
749
+ async function resumable(ctx, request) {
750
+ const record = await ctx.readRecord(request.runId);
751
+ if (!record) throw new RunNotFoundError(request.runId);
752
+ if (record.status !== "waiting" || !record.gate) throw new RunNotWaitingError(record.status);
753
+ const digest = await computeBundleDigest(record.filePath, record.workflowName);
754
+ if (digest !== record.bundleDigest) throw new BundleChangedError();
755
+ buildGateResolution(record.gate, record.gate.id, request.input);
756
+ return record;
757
+ }
758
+ async function resumeRun(ctx, request, options) {
759
+ const { store, claimed, readRecord } = ctx;
760
+ const record = await resumable(ctx, request);
761
+ return claimed(record.runId, async () => {
762
+ const current = await readRecord(record.runId);
763
+ if (!current || current.status !== "waiting" || !current.gate) throw new RunNotWaitingError(current?.status ?? "cancelled");
764
+ const continuation = current.continuation ?? await store.getDoc(record.runId, "continuation");
765
+ if (!continuation) throw new RunNotWaitingError(current.status);
766
+ if (continuation.gateId !== current.gate.id) {
767
+ throw new ContinuationRefusalError({ accepted: false, reason: "stale-gate", message: `the run's record names gate ${current.gate.id} but its continuation is at gate ${continuation.gateId}` });
768
+ }
769
+ const resolution = buildGateResolution(current.gate, current.gate.id, request.input);
770
+ const { ast } = await parseSelected(record.filePath, record.workflowName);
771
+ const { kept, request: observed } = observe(options);
772
+ let outcome;
773
+ try {
774
+ outcome = await executeWorkflow({
775
+ runId: record.runId,
776
+ bundleDigest: record.bundleDigest,
777
+ filePath: record.filePath,
778
+ params: record.params,
779
+ workflowName: record.workflowName,
780
+ mocks: record.mocks,
781
+ ...observed,
782
+ abortSignal: options?.abortSignal,
783
+ continuation,
784
+ resolution,
785
+ effectAdapter: createStoreEffectAdapter(store, record.runId)
786
+ });
787
+ } catch (error) {
788
+ if (error instanceof ContinuationRefusalError) throw error;
789
+ await fail(store, current, error, options, kept);
790
+ throw error;
791
+ }
792
+ return toView(await commit(store, current, outcome, ast, kept));
793
+ });
794
+ }
795
+
796
+ // src/coordinator/run-ending.ts
797
+ async function cancelRun(ctx, runId) {
798
+ const { store, claimed, readRecord } = ctx;
799
+ const record = await readRecord(runId);
800
+ if (!record) throw new RunNotFoundError(runId);
801
+ if (record.status !== "waiting") throw new RunNotWaitingError(record.status);
802
+ return claimed(runId, async () => {
803
+ const current = await readRecord(runId);
804
+ if (!current || current.status !== "waiting") throw new RunNotWaitingError(current?.status ?? "cancelled");
805
+ const next = {
806
+ ...current,
807
+ status: "cancelled",
808
+ gate: void 0,
809
+ continuation: void 0,
810
+ due: void 0,
811
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
812
+ };
813
+ await store.put(next);
814
+ await store.deleteDoc(runId, "continuation");
815
+ return toView(next);
816
+ });
817
+ }
818
+ async function removeRun(ctx, runId) {
819
+ const record = await ctx.readRecord(runId);
820
+ if (!record) throw new RunNotFoundError(runId);
821
+ if (record.status === "waiting") throw new RunNotWaitingError(record.status);
822
+ await ctx.store.remove(runId);
823
+ }
824
+
825
+ // src/coordinator/run-annotations.ts
826
+ async function setAgentNote(ctx, runId, note) {
827
+ const { store, claimed, readRecord } = ctx;
828
+ if (!await readRecord(runId)) throw new RunNotFoundError(runId);
829
+ return claimed(runId, async () => {
830
+ const record = await readRecord(runId);
831
+ if (!record) throw new RunNotFoundError(runId);
832
+ const next = { ...record, agent: note, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
833
+ if (note === void 0) delete next.agent;
834
+ await store.put(next);
835
+ return next;
836
+ });
837
+ }
838
+ async function keepDoc(ctx, runId, name, data) {
839
+ checkDocName(name);
840
+ if (RESERVED_DOCS.includes(name) || name.startsWith(EFFECT_DOC_PREFIX)) throw new Error(`${name} is a document the coordinator keeps itself`);
841
+ if (!await ctx.readRecord(runId)) throw new RunNotFoundError(runId);
842
+ await ctx.store.putDoc(runId, name, data);
843
+ }
844
+ async function keptDoc(ctx, runId, name) {
845
+ checkDocName(name);
846
+ return await ctx.store.getDoc(runId, name);
847
+ }
848
+
849
+ // src/coordinator/clock-tick.ts
850
+ async function tickDue(store, resume, now) {
851
+ const result = { woke: [], timedOut: [], skipped: [] };
852
+ const at = new Date(now).toISOString();
853
+ for (const summary of await store.list()) {
854
+ if (summary.status !== "waiting" || !summary.due || summary.due.at > at) continue;
855
+ const { runId, due } = summary;
856
+ const input = due.action === "wake" ? { answer: summary.gate?.outputs.length ? at : null } : { reject: `no answer within ${String(summary.gate?.inputs.timeout ?? "the timeout")}` };
857
+ try {
858
+ const view = await resume({ runId, input });
859
+ (due.action === "wake" ? result.woke : result.timedOut).push(view);
860
+ } catch (error) {
861
+ const name = error instanceof Error ? error.name : "";
862
+ const reason = name === "RunBusyError" ? "busy" : name === "RunNotWaitingError" ? "not-waiting" : name === "BundleChangedError" ? "bundle-changed" : "failed";
863
+ result.skipped.push({ runId, reason, ...reason === "failed" ? { message: getErrorMessage(error) } : {} });
864
+ }
865
+ }
866
+ return result;
867
+ }
868
+
869
+ // src/coordinator/run-store.ts
870
+ function createLocalCoordinator(options = {}) {
871
+ const ctx = createRunContext(options);
872
+ const { store, readRecord } = ctx;
873
+ return {
874
+ store,
875
+ start(request, options2) {
876
+ return startRun(ctx, request, options2);
877
+ },
878
+ checkResume: async (request) => {
879
+ await resumable(ctx, request);
880
+ },
881
+ resume(request, options2) {
882
+ return resumeRun(ctx, request, options2);
883
+ },
884
+ cancel(runId) {
885
+ return cancelRun(ctx, runId);
886
+ },
887
+ async get(runId) {
888
+ const record = await readRecord(runId);
889
+ return record ? toView(record) : void 0;
890
+ },
891
+ record: readRecord,
892
+ trace: (runId) => readTrace(store, runId),
893
+ remove(runId) {
894
+ return removeRun(ctx, runId);
895
+ },
896
+ setAgent(runId, note) {
897
+ return setAgentNote(ctx, runId, note);
898
+ },
899
+ keep(runId, name, data) {
900
+ return keepDoc(ctx, runId, name, data);
901
+ },
902
+ kept(runId, name) {
903
+ return keptDoc(ctx, runId, name);
904
+ },
905
+ // Through `this`, so each due run is resumed by the coordinator as it
906
+ // stands when the tick reaches it.
907
+ tick(now = Date.now()) {
908
+ return tickDue(store, (request) => this.resume(request), now);
909
+ },
910
+ async list(filter = {}) {
911
+ const records = await store.list(filter.filePath ? { filePath: path6.resolve(filter.filePath) } : {});
912
+ return records.map(toSummary);
913
+ }
914
+ };
915
+ }
916
+
917
+ // src/coordinator/agent-gate.ts
918
+ import * as os5 from "node:os";
919
+
920
+ // src/agent/agent-loop.ts
921
+ var DEFAULT_MAX_ITERATIONS2 = 15;
922
+ var TOOL_RESULT_CAP = 1e4;
923
+ function truncateToolResult(result, cap = TOOL_RESULT_CAP) {
924
+ if (result.length <= cap) return result;
925
+ return `${result.slice(0, cap)}
926
+ [truncated: ${result.length - cap} more characters]`;
927
+ }
928
+ async function runAgentLoop(provider, tools, executor, messages, options) {
929
+ const maxIterations = options?.maxIterations ?? DEFAULT_MAX_ITERATIONS2;
930
+ const signal = options?.signal;
931
+ const onStreamEvent = options?.onStreamEvent;
932
+ const onToolEvent = options?.onToolEvent;
933
+ const conversation = [...messages];
934
+ let totalPromptTokens = 0;
935
+ let totalCompletionTokens = 0;
936
+ let totalCacheReadTokens = 0;
937
+ let totalCacheCreationTokens = 0;
938
+ let totalCostUsd = 0;
939
+ let toolCallCount = 0;
940
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
941
+ if (signal?.aborted) {
942
+ return buildResult(false, "Aborted", conversation, toolCallCount, totalPromptTokens, totalCompletionTokens, totalCacheReadTokens, totalCacheCreationTokens, totalCostUsd);
943
+ }
944
+ let text = "";
945
+ let finishReason = "stop";
946
+ const collectedToolCalls = [];
947
+ const activeToolNames = /* @__PURE__ */ new Map();
948
+ const stream = provider.stream(conversation, tools, {
949
+ systemPrompt: options?.systemPrompt,
950
+ model: options?.model,
951
+ maxTokens: options?.maxTokens,
952
+ signal,
953
+ executor,
954
+ onToolEvent
955
+ });
956
+ for await (const event of stream) {
957
+ onStreamEvent?.(event);
958
+ switch (event.type) {
959
+ case "text_delta":
960
+ text += event.text;
961
+ break;
962
+ case "thinking_delta":
963
+ break;
964
+ case "tool_use_start":
965
+ activeToolNames.set(event.id, event.name);
966
+ break;
967
+ case "tool_use_delta":
968
+ break;
969
+ case "tool_use_end":
970
+ collectedToolCalls.push({
971
+ id: event.id,
972
+ name: activeToolNames.get(event.id) ?? "unknown",
973
+ arguments: event.arguments
974
+ });
975
+ activeToolNames.delete(event.id);
976
+ break;
977
+ case "tool_result":
978
+ toolCallCount++;
979
+ break;
980
+ case "usage":
981
+ totalPromptTokens += event.promptTokens;
982
+ totalCompletionTokens += event.completionTokens;
983
+ totalCacheReadTokens += event.cacheReadTokens ?? 0;
984
+ totalCacheCreationTokens += event.cacheCreationTokens ?? 0;
985
+ if (event.costUsd != null) totalCostUsd = event.costUsd;
986
+ break;
987
+ case "message_stop":
988
+ finishReason = event.finishReason;
989
+ break;
990
+ }
991
+ }
992
+ if (collectedToolCalls.length > 0) {
993
+ conversation.push({
994
+ role: "assistant",
995
+ content: text || "",
996
+ toolCalls: collectedToolCalls
997
+ });
998
+ } else if (text) {
999
+ conversation.push({ role: "assistant", content: text });
1000
+ }
1001
+ if (finishReason !== "tool_calls" || collectedToolCalls.length === 0) {
1002
+ if (options?.onTurnEnd) {
1003
+ await options.onTurnEnd({
1004
+ iteration,
1005
+ maxIterations,
1006
+ messages: conversation,
1007
+ toolCallCount,
1008
+ usage: { promptTokens: totalPromptTokens, completionTokens: totalCompletionTokens },
1009
+ isFinalTurn: true
1010
+ });
1011
+ }
1012
+ return buildResult(
1013
+ finishReason !== "error",
1014
+ text || "Task completed",
1015
+ conversation,
1016
+ toolCallCount,
1017
+ totalPromptTokens,
1018
+ totalCompletionTokens,
1019
+ totalCacheReadTokens,
1020
+ totalCacheCreationTokens,
1021
+ totalCostUsd
1022
+ );
1023
+ }
1024
+ for (const tc of collectedToolCalls) {
1025
+ if (signal?.aborted) break;
1026
+ toolCallCount++;
1027
+ onToolEvent?.({ type: "tool_call_start", name: tc.name, args: tc.arguments });
1028
+ let result;
1029
+ let isError;
1030
+ try {
1031
+ const res = await executor(tc.name, tc.arguments);
1032
+ result = res.result;
1033
+ isError = res.isError;
1034
+ } catch (err) {
1035
+ result = getErrorMessage(err);
1036
+ isError = true;
1037
+ }
1038
+ onToolEvent?.({ type: "tool_call_result", name: tc.name, args: tc.arguments, result: result.slice(0, 200), isError });
1039
+ conversation.push({
1040
+ role: "tool",
1041
+ content: truncateToolResult(result),
1042
+ toolCallId: tc.id
1043
+ });
1044
+ }
1045
+ if (options?.onTurnEnd) {
1046
+ const turnResult = await options.onTurnEnd({
1047
+ iteration,
1048
+ maxIterations,
1049
+ messages: conversation,
1050
+ toolCallCount,
1051
+ usage: { promptTokens: totalPromptTokens, completionTokens: totalCompletionTokens },
1052
+ isFinalTurn: false
1053
+ });
1054
+ if (turnResult?.continue === false) {
1055
+ return buildResult(
1056
+ true,
1057
+ turnResult.injectMessage ?? "Stopped by hook",
1058
+ conversation,
1059
+ toolCallCount,
1060
+ totalPromptTokens,
1061
+ totalCompletionTokens,
1062
+ totalCacheReadTokens,
1063
+ totalCacheCreationTokens,
1064
+ totalCostUsd
1065
+ );
1066
+ }
1067
+ if (turnResult?.injectMessage) {
1068
+ conversation.push({ role: "user", content: turnResult.injectMessage });
1069
+ }
1070
+ }
1071
+ }
1072
+ return buildResult(
1073
+ false,
1074
+ `Reached max iterations (${maxIterations})`,
1075
+ conversation,
1076
+ toolCallCount,
1077
+ totalPromptTokens,
1078
+ totalCompletionTokens,
1079
+ totalCacheReadTokens,
1080
+ totalCacheCreationTokens,
1081
+ totalCostUsd
1082
+ );
1083
+ }
1084
+ function buildResult(success, summary, messages, toolCallCount, promptTokens, completionTokens, cacheReadTokens = 0, cacheCreationTokens = 0, costUsd = 0) {
1085
+ return {
1086
+ success,
1087
+ summary,
1088
+ messages,
1089
+ toolCallCount,
1090
+ usage: { promptTokens, completionTokens, cacheReadTokens, cacheCreationTokens, costUsd }
1091
+ };
1092
+ }
1093
+
1094
+ // src/agent/providers/anthropic.ts
1095
+ function buildSystemBlocks(prompt) {
1096
+ const blocks = [
1097
+ { type: "text", text: prompt.prefix, cache_control: { type: "ephemeral" } }
1098
+ ];
1099
+ if (prompt.suffix) {
1100
+ blocks.push({ type: "text", text: prompt.suffix });
1101
+ }
1102
+ return blocks;
1103
+ }
1104
+ var AnthropicProvider = class {
1105
+ apiKey;
1106
+ model;
1107
+ maxTokens;
1108
+ baseUrl;
1109
+ constructor(options) {
1110
+ if (!options.apiKey) {
1111
+ throw new Error("AnthropicProvider requires an API key");
1112
+ }
1113
+ this.apiKey = options.apiKey;
1114
+ this.model = options.model ?? DEFAULT_MODEL.anthropic;
1115
+ this.maxTokens = options.maxTokens ?? 8192;
1116
+ this.baseUrl = options.baseUrl ?? "https://api.anthropic.com";
1117
+ }
1118
+ async *stream(messages, tools, options) {
1119
+ const model = options?.model ?? this.model;
1120
+ const maxTokens = options?.maxTokens ?? this.maxTokens;
1121
+ const apiMessages = messages.map((m) => {
1122
+ if (m.role === "tool") {
1123
+ return {
1124
+ role: "user",
1125
+ content: [{ type: "tool_result", tool_use_id: m.toolCallId, content: m.content }]
1126
+ };
1127
+ }
1128
+ if (m.role === "assistant" && m.toolCalls?.length) {
1129
+ const blocks = [];
1130
+ if (m.content) blocks.push({ type: "text", text: m.content });
1131
+ for (const tc of m.toolCalls) {
1132
+ blocks.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.arguments });
1133
+ }
1134
+ return { role: "assistant", content: blocks };
1135
+ }
1136
+ return { role: m.role, content: m.content };
1137
+ });
1138
+ const apiTools = tools.map((t) => ({
1139
+ name: t.name,
1140
+ description: t.description,
1141
+ input_schema: t.inputSchema
1142
+ }));
1143
+ const body = JSON.stringify({
1144
+ model,
1145
+ max_tokens: maxTokens,
1146
+ stream: true,
1147
+ ...options?.systemPrompt ? { system: buildSystemBlocks(options.systemPrompt) } : {},
1148
+ messages: apiMessages,
1149
+ ...apiTools.length > 0 ? { tools: apiTools } : {}
1150
+ });
1151
+ const response = await fetch(`${this.baseUrl}/v1/messages`, {
1152
+ method: "POST",
1153
+ headers: {
1154
+ "x-api-key": this.apiKey,
1155
+ "anthropic-version": "2025-04-15",
1156
+ "content-type": "application/json"
1157
+ },
1158
+ body,
1159
+ signal: options?.signal ?? AbortSignal.timeout(3e5)
1160
+ });
1161
+ if (!response.ok) {
1162
+ const err = await response.text();
1163
+ throw new Error(`Anthropic API error ${response.status}: ${err.slice(0, 200)}`);
1164
+ }
1165
+ if (!response.body) throw new Error("No response body");
1166
+ const reader = response.body.getReader();
1167
+ const decoder = new TextDecoder();
1168
+ let buffer = "";
1169
+ const activeToolUses = /* @__PURE__ */ new Map();
1170
+ try {
1171
+ while (true) {
1172
+ const { done, value } = await reader.read();
1173
+ if (done) break;
1174
+ buffer += decoder.decode(value, { stream: true });
1175
+ const lines = buffer.split("\n");
1176
+ buffer = lines.pop() || "";
1177
+ for (const line of lines) {
1178
+ if (!line.startsWith("data: ")) continue;
1179
+ const jsonStr = line.slice(6).trim();
1180
+ if (jsonStr === "[DONE]") continue;
1181
+ let event;
1182
+ try {
1183
+ event = JSON.parse(jsonStr);
1184
+ } catch {
1185
+ continue;
1186
+ }
1187
+ const eventType = event.type;
1188
+ if (eventType === "content_block_start") {
1189
+ const block = event.content_block;
1190
+ const index = event.index;
1191
+ if (block.type === "tool_use" && block.id && block.name) {
1192
+ activeToolUses.set(index, { id: block.id, name: block.name, jsonChunks: [] });
1193
+ yield { type: "tool_use_start", id: block.id, name: block.name };
1194
+ }
1195
+ }
1196
+ if (eventType === "content_block_delta") {
1197
+ const delta = event.delta;
1198
+ const index = event.index;
1199
+ if (delta.type === "text_delta" && delta.text) {
1200
+ yield { type: "text_delta", text: delta.text };
1201
+ }
1202
+ if (delta.type === "thinking_delta" && delta.thinking) {
1203
+ yield { type: "thinking_delta", text: delta.thinking };
1204
+ }
1205
+ if (delta.type === "input_json_delta" && delta.partial_json !== void 0) {
1206
+ const active = activeToolUses.get(index);
1207
+ if (active) {
1208
+ active.jsonChunks.push(delta.partial_json);
1209
+ yield { type: "tool_use_delta", id: active.id, partialJson: delta.partial_json };
1210
+ }
1211
+ }
1212
+ }
1213
+ if (eventType === "content_block_stop") {
1214
+ const index = event.index;
1215
+ const active = activeToolUses.get(index);
1216
+ if (active) {
1217
+ activeToolUses.delete(index);
1218
+ let args = {};
1219
+ try {
1220
+ args = JSON.parse(active.jsonChunks.join(""));
1221
+ } catch {
1222
+ }
1223
+ yield { type: "tool_use_end", id: active.id, arguments: args };
1224
+ }
1225
+ }
1226
+ if (eventType === "message_start" && event.message?.usage) {
1227
+ const usage = event.message.usage;
1228
+ yield {
1229
+ type: "usage",
1230
+ promptTokens: usage.input_tokens ?? 0,
1231
+ completionTokens: usage.output_tokens ?? 0
1232
+ };
1233
+ }
1234
+ if (eventType === "message_delta") {
1235
+ const delta = event.delta;
1236
+ if (event.usage) {
1237
+ const usage = event.usage;
1238
+ yield {
1239
+ type: "usage",
1240
+ promptTokens: 0,
1241
+ completionTokens: usage.output_tokens ?? 0
1242
+ };
1243
+ }
1244
+ if (delta?.stop_reason === "tool_use") {
1245
+ yield { type: "message_stop", finishReason: "tool_calls" };
1246
+ } else if (delta?.stop_reason === "end_turn") {
1247
+ yield { type: "message_stop", finishReason: "stop" };
1248
+ } else if (delta?.stop_reason === "max_tokens") {
1249
+ yield { type: "message_stop", finishReason: "length" };
1250
+ } else if (delta?.stop_reason) {
1251
+ yield { type: "message_stop", finishReason: "stop" };
1252
+ }
1253
+ }
1254
+ if (eventType === "error") {
1255
+ const errObj = event.error;
1256
+ throw new Error(`Anthropic stream error: ${errObj?.message ?? "unknown"}`);
1257
+ }
1258
+ }
1259
+ }
1260
+ } finally {
1261
+ reader.releaseLock();
1262
+ }
1263
+ }
1264
+ };
1265
+ function createAnthropicProvider(options) {
1266
+ return new AnthropicProvider(options);
1267
+ }
1268
+
1269
+ // src/agent/types.ts
1270
+ function joinSplitPrompt(prompt) {
1271
+ if (!prompt.suffix) return prompt.prefix;
1272
+ return prompt.prefix + "\n\n" + prompt.suffix;
1273
+ }
1274
+ function stripMcpToolPrefix(name) {
1275
+ return name.replace(/^mcp__[a-zA-Z0-9_-]+__/, "");
1276
+ }
1277
+
1278
+ // src/agent/providers/openai-compat.ts
1279
+ var OpenAICompatProvider = class {
1280
+ apiKey;
1281
+ model;
1282
+ maxTokens;
1283
+ baseUrl;
1284
+ constructor(options) {
1285
+ if (!options.apiKey) {
1286
+ throw new Error("OpenAICompatProvider requires an API key");
1287
+ }
1288
+ this.apiKey = options.apiKey;
1289
+ this.model = options.model ?? "gpt-4o";
1290
+ this.maxTokens = options.maxTokens ?? 4096;
1291
+ this.baseUrl = (options.baseUrl ?? "https://api.openai.com").replace(/\/+$/, "");
1292
+ }
1293
+ async *stream(messages, tools, options) {
1294
+ const model = options?.model ?? this.model;
1295
+ const maxTokens = options?.maxTokens ?? this.maxTokens;
1296
+ const apiMessages = messages.map((m) => formatMessage(m));
1297
+ const apiTools = tools.length > 0 ? tools.map((t) => ({
1298
+ type: "function",
1299
+ function: {
1300
+ name: t.name,
1301
+ description: t.description,
1302
+ parameters: t.inputSchema
1303
+ }
1304
+ })) : void 0;
1305
+ const body = {
1306
+ model,
1307
+ messages: [
1308
+ ...options?.systemPrompt ? [{ role: "system", content: joinSplitPrompt(options.systemPrompt) }] : [],
1309
+ ...apiMessages
1310
+ ],
1311
+ max_tokens: maxTokens,
1312
+ stream: true,
1313
+ // Without this OpenAI sends no usage on a stream, and token totals stay 0.
1314
+ stream_options: { include_usage: true }
1315
+ };
1316
+ if (apiTools && apiTools.length > 0) {
1317
+ body.tools = apiTools;
1318
+ }
1319
+ const response = await fetch(completionsUrl(this.baseUrl), {
1320
+ method: "POST",
1321
+ headers: {
1322
+ "Content-Type": "application/json",
1323
+ Authorization: `Bearer ${this.apiKey}`
1324
+ },
1325
+ body: JSON.stringify(body),
1326
+ signal: options?.signal
1327
+ });
1328
+ if (!response.ok) {
1329
+ const errText = await response.text().catch(() => "");
1330
+ yield { type: "text_delta", text: `OpenAI API error ${response.status}: ${errText.slice(0, 300)}` };
1331
+ yield { type: "message_stop", finishReason: "error" };
1332
+ return;
1333
+ }
1334
+ if (!response.body) {
1335
+ yield { type: "message_stop", finishReason: "error" };
1336
+ return;
1337
+ }
1338
+ const reader = response.body.getReader();
1339
+ const decoder = new TextDecoder();
1340
+ let buffer = "";
1341
+ let hasToolCalls = false;
1342
+ const activeToolCalls = /* @__PURE__ */ new Map();
1343
+ try {
1344
+ while (true) {
1345
+ const { done, value } = await reader.read();
1346
+ if (done) break;
1347
+ buffer += decoder.decode(value, { stream: true });
1348
+ const lines = buffer.split("\n");
1349
+ buffer = lines.pop() || "";
1350
+ for (const line of lines) {
1351
+ if (!line.startsWith("data: ")) continue;
1352
+ const data = line.slice(6).trim();
1353
+ if (data === "[DONE]") {
1354
+ for (const [, tc] of activeToolCalls) {
1355
+ let args = {};
1356
+ try {
1357
+ args = JSON.parse(tc.argsJson);
1358
+ } catch {
1359
+ }
1360
+ yield { type: "tool_use_end", id: tc.id, arguments: args };
1361
+ }
1362
+ yield { type: "message_stop", finishReason: hasToolCalls ? "tool_calls" : "stop" };
1363
+ return;
1364
+ }
1365
+ let parsed;
1366
+ try {
1367
+ parsed = JSON.parse(data);
1368
+ } catch {
1369
+ continue;
1370
+ }
1371
+ if (parsed.usage) {
1372
+ const usage = parsed.usage;
1373
+ yield {
1374
+ type: "usage",
1375
+ promptTokens: usage.prompt_tokens ?? 0,
1376
+ completionTokens: usage.completion_tokens ?? 0
1377
+ };
1378
+ }
1379
+ const choices = parsed.choices;
1380
+ if (!choices || choices.length === 0) continue;
1381
+ const choice = choices[0];
1382
+ const delta = choice.delta;
1383
+ if (!delta) continue;
1384
+ if (delta.content && typeof delta.content === "string") {
1385
+ yield { type: "text_delta", text: delta.content };
1386
+ }
1387
+ const toolCalls = delta.tool_calls;
1388
+ if (toolCalls) {
1389
+ for (const tc of toolCalls) {
1390
+ const index = tc.index ?? 0;
1391
+ const fn = tc.function;
1392
+ if (tc.id) {
1393
+ hasToolCalls = true;
1394
+ const name = fn?.name ? String(fn.name) : "unknown";
1395
+ activeToolCalls.set(index, { id: String(tc.id), name, argsJson: "" });
1396
+ yield { type: "tool_use_start", id: String(tc.id), name };
1397
+ }
1398
+ if (fn?.arguments && typeof fn.arguments === "string") {
1399
+ const existing = activeToolCalls.get(index);
1400
+ if (existing) {
1401
+ existing.argsJson += fn.arguments;
1402
+ yield { type: "tool_use_delta", id: existing.id, partialJson: fn.arguments };
1403
+ }
1404
+ }
1405
+ }
1406
+ }
1407
+ if (choice.finish_reason === "tool_calls") {
1408
+ hasToolCalls = true;
1409
+ }
1410
+ }
1411
+ }
1412
+ } finally {
1413
+ reader.releaseLock();
1414
+ }
1415
+ for (const [, tc] of activeToolCalls) {
1416
+ let args = {};
1417
+ try {
1418
+ args = JSON.parse(tc.argsJson);
1419
+ } catch {
1420
+ }
1421
+ yield { type: "tool_use_end", id: tc.id, arguments: args };
1422
+ }
1423
+ yield { type: "message_stop", finishReason: hasToolCalls ? "tool_calls" : "stop" };
1424
+ }
1425
+ };
1426
+ function completionsUrl(baseUrl) {
1427
+ const base = baseUrl.replace(/\/+$/, "");
1428
+ return /\/v\d+$/.test(base) ? `${base}/chat/completions` : `${base}/v1/chat/completions`;
1429
+ }
1430
+ function formatMessage(m) {
1431
+ if (m.role === "tool") {
1432
+ return {
1433
+ role: "tool",
1434
+ tool_call_id: m.toolCallId,
1435
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
1436
+ };
1437
+ }
1438
+ if (m.role === "assistant" && m.toolCalls?.length) {
1439
+ return {
1440
+ role: "assistant",
1441
+ content: typeof m.content === "string" && m.content ? m.content : null,
1442
+ tool_calls: m.toolCalls.map((tc) => ({
1443
+ id: tc.id,
1444
+ type: "function",
1445
+ function: { name: tc.name, arguments: JSON.stringify(tc.arguments) }
1446
+ }))
1447
+ };
1448
+ }
1449
+ return {
1450
+ role: m.role,
1451
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
1452
+ };
1453
+ }
1454
+ function createOpenAICompatProvider(options) {
1455
+ return new OpenAICompatProvider(options);
1456
+ }
1457
+
1458
+ // src/agent/providers/claude-cli.ts
1459
+ import { spawn as nodeSpawn } from "node:child_process";
1460
+
1461
+ // src/agent/streaming.ts
1462
+ var StreamJsonParser = class {
1463
+ constructor(pushEvent) {
1464
+ this.pushEvent = pushEvent;
1465
+ }
1466
+ pushEvent;
1467
+ hasAssistantText = false;
1468
+ insideToolUse = false;
1469
+ activeToolJsonChunks = /* @__PURE__ */ new Map();
1470
+ /** Reset per-turn state. Call before starting a new turn in persistent sessions. */
1471
+ reset() {
1472
+ this.hasAssistantText = false;
1473
+ this.insideToolUse = false;
1474
+ this.activeToolJsonChunks.clear();
1475
+ }
1476
+ /** Whether any text_delta events have been emitted this turn. */
1477
+ get hasText() {
1478
+ return this.hasAssistantText;
1479
+ }
1480
+ /**
1481
+ * Feed a single NDJSON line (without trailing newline).
1482
+ * Parses and emits StreamEvent(s) via the callback.
1483
+ */
1484
+ feed(line) {
1485
+ if (!line.trim()) return;
1486
+ let event;
1487
+ try {
1488
+ event = JSON.parse(line);
1489
+ } catch {
1490
+ if (line.trim() && !this.hasAssistantText) {
1491
+ this.pushEvent({ type: "text_delta", text: line });
1492
+ }
1493
+ return;
1494
+ }
1495
+ if (event.type === "stream_event" && event.event) {
1496
+ event = event.event;
1497
+ }
1498
+ this.processEvent(event);
1499
+ }
1500
+ processEvent(event) {
1501
+ const block = event.content_block;
1502
+ const delta = event.delta;
1503
+ if (event.type === "content_block_start" && block?.type === "tool_use") {
1504
+ this.insideToolUse = true;
1505
+ const id = block.id || `cli-tool-${Date.now()}`;
1506
+ const name = block.name || "unknown";
1507
+ this.pushEvent({ type: "tool_use_start", id, name });
1508
+ this.activeToolJsonChunks.set(id, { name, chunks: [] });
1509
+ return;
1510
+ }
1511
+ if (event.type === "content_block_start" && block?.type === "text") {
1512
+ this.insideToolUse = false;
1513
+ return;
1514
+ }
1515
+ if (event.type === "content_block_delta" && delta?.type === "input_json_delta") {
1516
+ const lastTool = [...this.activeToolJsonChunks.entries()].pop();
1517
+ if (lastTool) lastTool[1].chunks.push(delta.partial_json || "");
1518
+ return;
1519
+ }
1520
+ if (event.type === "content_block_delta" && delta?.type === "thinking_delta" && delta?.thinking) {
1521
+ this.pushEvent({ type: "thinking_delta", text: delta.thinking });
1522
+ return;
1523
+ }
1524
+ if (event.type === "content_block_delta" && delta?.text && !this.insideToolUse) {
1525
+ this.hasAssistantText = true;
1526
+ this.pushEvent({ type: "text_delta", text: delta.text });
1527
+ return;
1528
+ }
1529
+ if (event.type === "content_block_stop" && this.insideToolUse) {
1530
+ const lastTool = [...this.activeToolJsonChunks.entries()].pop();
1531
+ if (lastTool) {
1532
+ const [id, { chunks }] = lastTool;
1533
+ let args = {};
1534
+ try {
1535
+ args = JSON.parse(chunks.join(""));
1536
+ } catch {
1537
+ }
1538
+ this.pushEvent({ type: "tool_use_end", id, arguments: args });
1539
+ this.activeToolJsonChunks.delete(id);
1540
+ }
1541
+ this.insideToolUse = false;
1542
+ return;
1543
+ }
1544
+ if (event.type === "user" && event.message?.content) {
1545
+ const content = event.message.content;
1546
+ for (const contentBlock of content) {
1547
+ if (contentBlock.type === "tool_result" && contentBlock.tool_use_id) {
1548
+ const text = Array.isArray(contentBlock.content) ? contentBlock.content.map((c) => c.text || "").join("") : String(contentBlock.content || "");
1549
+ this.pushEvent({
1550
+ type: "tool_result",
1551
+ id: contentBlock.tool_use_id,
1552
+ result: text,
1553
+ isError: !!contentBlock.is_error
1554
+ });
1555
+ }
1556
+ }
1557
+ return;
1558
+ }
1559
+ if (event.type === "message_start" && event.message?.usage) {
1560
+ const usage = event.message.usage;
1561
+ this.pushEvent({
1562
+ type: "usage",
1563
+ promptTokens: usage.input_tokens ?? 0,
1564
+ completionTokens: usage.output_tokens ?? 0
1565
+ });
1566
+ return;
1567
+ }
1568
+ if (event.type === "message_delta" && event.usage) {
1569
+ const usage = event.usage;
1570
+ this.pushEvent({
1571
+ type: "usage",
1572
+ promptTokens: 0,
1573
+ completionTokens: usage.output_tokens ?? 0
1574
+ });
1575
+ return;
1576
+ }
1577
+ if (event.type === "message_stop") {
1578
+ this.pushEvent({ type: "message_stop", finishReason: "stop" });
1579
+ return;
1580
+ }
1581
+ if (event.type === "result") {
1582
+ if (event.is_error) {
1583
+ this.pushEvent({ type: "message_stop", finishReason: "error" });
1584
+ return;
1585
+ }
1586
+ if (event.result && !this.hasAssistantText) {
1587
+ this.pushEvent({ type: "text_delta", text: event.result });
1588
+ }
1589
+ if (event.usage) {
1590
+ const usage = event.usage;
1591
+ this.pushEvent({
1592
+ type: "usage",
1593
+ promptTokens: usage.input_tokens ?? 0,
1594
+ completionTokens: usage.output_tokens ?? 0,
1595
+ cacheReadTokens: usage.cache_read_input_tokens ?? void 0,
1596
+ cacheCreationTokens: usage.cache_creation_input_tokens ?? void 0,
1597
+ costUsd: typeof event.total_cost_usd === "number" ? event.total_cost_usd : void 0
1598
+ });
1599
+ }
1600
+ this.pushEvent({ type: "message_stop", finishReason: "stop" });
1601
+ return;
1602
+ }
1603
+ if (event.type === "assistant") {
1604
+ if (event.error === "authentication_failed") {
1605
+ this.pushEvent({ type: "message_stop", finishReason: "error" });
1606
+ }
1607
+ }
1608
+ }
1609
+ };
1610
+
1611
+ // src/agent/mcp-bridge.ts
1612
+ import * as net from "node:net";
1613
+ import * as fs3 from "node:fs";
1614
+ import * as path7 from "node:path";
1615
+ import * as os4 from "node:os";
1616
+ import { fileURLToPath } from "node:url";
1617
+ async function createMcpBridge(tools, executor, onToolEvent, logger) {
1618
+ const tmpDir = fs3.mkdtempSync(path7.join(os4.tmpdir(), "fw-mcp-bridge-"));
1619
+ fs3.chmodSync(tmpDir, 448);
1620
+ const socketPath = path7.join(tmpDir, "bridge.sock");
1621
+ const defsPath = path7.join(tmpDir, "tools.json");
1622
+ const configPath = path7.join(tmpDir, "mcp-config.json");
1623
+ const mcpToolDefs = tools.map((t) => ({
1624
+ name: t.name,
1625
+ description: t.description,
1626
+ inputSchema: t.inputSchema
1627
+ }));
1628
+ fs3.writeFileSync(defsPath, JSON.stringify(mcpToolDefs), "utf-8");
1629
+ const __dirname = path7.dirname(fileURLToPath(import.meta.url));
1630
+ const jsPath = path7.resolve(__dirname, "mcp-tool-server.js");
1631
+ const tsPath = path7.resolve(__dirname, "mcp-tool-server.ts");
1632
+ const scriptPath = fs3.existsSync(jsPath) ? jsPath : tsPath;
1633
+ const mcpCommand = process.execPath;
1634
+ let mcpArgs = [scriptPath];
1635
+ if (scriptPath.endsWith(".ts")) {
1636
+ const tsxCli = path7.resolve(__dirname, "../../node_modules/tsx/dist/cli.mjs");
1637
+ if (fs3.existsSync(tsxCli)) {
1638
+ mcpArgs = [tsxCli, scriptPath];
1639
+ }
1640
+ }
1641
+ const mcpConfig = {
1642
+ mcpServers: {
1643
+ "fw-agent": {
1644
+ type: "stdio",
1645
+ command: mcpCommand,
1646
+ args: mcpArgs,
1647
+ env: {
1648
+ FW_TOOL_SOCKET: socketPath,
1649
+ FW_TOOL_DEFS: defsPath
1650
+ }
1651
+ }
1652
+ }
1653
+ };
1654
+ fs3.writeFileSync(configPath, JSON.stringify(mcpConfig), "utf-8");
1655
+ let currentExecutor = executor;
1656
+ let currentOnToolEvent = onToolEvent;
1657
+ const answer = async (line) => {
1658
+ try {
1659
+ const { name, args } = JSON.parse(line);
1660
+ currentOnToolEvent?.({ type: "tool_call_start", name, args });
1661
+ const { result, isError } = await currentExecutor(name, args);
1662
+ currentOnToolEvent?.({ type: "tool_call_result", name, result, isError });
1663
+ return JSON.stringify({ result, isError });
1664
+ } catch (err) {
1665
+ const msg = getErrorMessage(err);
1666
+ try {
1667
+ logger?.error("MCP bridge tool execution error", err);
1668
+ } catch {
1669
+ }
1670
+ return JSON.stringify({ result: msg, isError: true });
1671
+ }
1672
+ };
1673
+ const server = net.createServer((conn) => {
1674
+ let buf = "";
1675
+ conn.on("data", (chunk) => {
1676
+ buf += chunk.toString();
1677
+ const nlIdx = buf.indexOf("\n");
1678
+ if (nlIdx === -1) return;
1679
+ const line = buf.slice(0, nlIdx).trim();
1680
+ buf = "";
1681
+ answer(line).then((reply) => conn.end(reply)).catch(() => conn.destroy());
1682
+ });
1683
+ });
1684
+ await new Promise((resolve6, reject) => {
1685
+ server.on("error", reject);
1686
+ server.listen(socketPath, () => resolve6());
1687
+ });
1688
+ let cleaned = false;
1689
+ const cleanup = () => {
1690
+ if (cleaned) return;
1691
+ cleaned = true;
1692
+ server.close();
1693
+ try {
1694
+ fs3.unlinkSync(socketPath);
1695
+ } catch {
1696
+ }
1697
+ try {
1698
+ fs3.unlinkSync(defsPath);
1699
+ } catch {
1700
+ }
1701
+ try {
1702
+ fs3.unlinkSync(configPath);
1703
+ } catch {
1704
+ }
1705
+ try {
1706
+ fs3.rmdirSync(tmpDir);
1707
+ } catch {
1708
+ }
1709
+ };
1710
+ const setHandlers = (exec, onEvt) => {
1711
+ currentExecutor = exec;
1712
+ currentOnToolEvent = onEvt;
1713
+ };
1714
+ return { configPath, setHandlers, cleanup };
1715
+ }
1716
+
1717
+ // src/agent/providers/claude-cli.ts
1718
+ var ClaudeCliProvider = class {
1719
+ binPath;
1720
+ cwd;
1721
+ env;
1722
+ model;
1723
+ mcpConfigPath;
1724
+ spawnFn;
1725
+ timeout;
1726
+ disallowedTools;
1727
+ allowedTools;
1728
+ constructor(options = {}) {
1729
+ this.binPath = options.binPath ?? "claude";
1730
+ this.cwd = options.cwd ?? process.cwd();
1731
+ this.env = options.env ?? process.env;
1732
+ this.model = options.model;
1733
+ this.mcpConfigPath = options.mcpConfigPath;
1734
+ this.disallowedTools = options.disallowedTools ?? [];
1735
+ this.allowedTools = options.allowedTools;
1736
+ this.spawnFn = options.spawnFn ?? ((cmd, args, opts) => nodeSpawn(cmd, args, { ...opts, stdio: opts.stdio }));
1737
+ this.timeout = options.timeout ?? 6e5;
1738
+ }
1739
+ async *stream(messages, tools, options) {
1740
+ const model = options?.model ?? this.model;
1741
+ const prompt = formatPrompt(messages);
1742
+ const systemPrompt = options?.systemPrompt ? joinSplitPrompt(options.systemPrompt) : void 0;
1743
+ let bridge = null;
1744
+ let mcpConfigPath = this.mcpConfigPath;
1745
+ if (tools.length > 0 && !mcpConfigPath) {
1746
+ const executor = options?.executor ?? (async () => ({ result: "Tool executor not provided", isError: true }));
1747
+ bridge = await createMcpBridge(
1748
+ tools,
1749
+ executor,
1750
+ options?.onToolEvent
1751
+ );
1752
+ mcpConfigPath = bridge.configPath;
1753
+ }
1754
+ const args = [
1755
+ "-p",
1756
+ "--verbose",
1757
+ "--output-format",
1758
+ "stream-json",
1759
+ "--include-partial-messages",
1760
+ "--setting-sources",
1761
+ "user,local",
1762
+ "--dangerously-skip-permissions",
1763
+ "--permission-mode",
1764
+ "bypassPermissions",
1765
+ ...systemPrompt ? ["--system-prompt", systemPrompt] : [],
1766
+ ...mcpConfigPath ? ["--mcp-config", mcpConfigPath, "--strict-mcp-config"] : [],
1767
+ ...this.disallowedTools.length > 0 ? ["--disallowed-tools", this.disallowedTools.join(" ")] : [],
1768
+ ...this.allowedTools ? ["--allowed-tools", this.allowedTools.join(" ")] : [],
1769
+ ...model ? ["--model", model] : []
1770
+ ];
1771
+ const spawnResult = this.spawnFn(
1772
+ this.binPath,
1773
+ args,
1774
+ { cwd: this.cwd, stdio: ["pipe", "pipe", "pipe"], env: this.env }
1775
+ );
1776
+ const child = "child" in spawnResult ? spawnResult.child : spawnResult;
1777
+ const spawnCleanup = "cleanup" in spawnResult ? spawnResult.cleanup : void 0;
1778
+ const signal = options?.signal;
1779
+ if (signal) {
1780
+ signal.addEventListener(
1781
+ "abort",
1782
+ () => {
1783
+ child.kill("SIGTERM");
1784
+ setTimeout(() => {
1785
+ if (!child.killed) child.kill("SIGKILL");
1786
+ }, 2e3);
1787
+ },
1788
+ { once: true }
1789
+ );
1790
+ }
1791
+ const timeout = options?.timeout ?? this.timeout;
1792
+ const timer = setTimeout(() => {
1793
+ child.kill("SIGTERM");
1794
+ }, timeout);
1795
+ child.stdin.write(prompt);
1796
+ child.stdin.end();
1797
+ const events = [];
1798
+ let done = false;
1799
+ const parser = new StreamJsonParser((event) => {
1800
+ events.push(event);
1801
+ });
1802
+ let stderrBuf = "";
1803
+ child.stderr.on("data", (chunk) => {
1804
+ stderrBuf += chunk.toString();
1805
+ });
1806
+ let stdoutBuffer = "";
1807
+ child.stdout.on("data", (chunk) => {
1808
+ stdoutBuffer += chunk.toString();
1809
+ const lines = stdoutBuffer.split("\n");
1810
+ stdoutBuffer = lines.pop() || "";
1811
+ for (const line of lines) {
1812
+ parser.feed(line);
1813
+ }
1814
+ });
1815
+ child.on("close", (code) => {
1816
+ clearTimeout(timer);
1817
+ if (stdoutBuffer.trim()) {
1818
+ parser.feed(stdoutBuffer);
1819
+ }
1820
+ if (code !== 0 && !parser.hasText && stderrBuf.trim()) {
1821
+ events.push({ type: "text_delta", text: `Claude CLI error: ${stderrBuf.trim().slice(0, 500)}` });
1822
+ }
1823
+ if (!events.some((e) => e.type === "message_stop")) {
1824
+ events.push({ type: "message_stop", finishReason: code === 0 ? "stop" : "error" });
1825
+ }
1826
+ done = true;
1827
+ });
1828
+ child.on("error", () => {
1829
+ clearTimeout(timer);
1830
+ events.push({ type: "message_stop", finishReason: "error" });
1831
+ done = true;
1832
+ });
1833
+ try {
1834
+ while (!done || events.length > 0) {
1835
+ if (events.length > 0) {
1836
+ yield events.shift();
1837
+ } else {
1838
+ await new Promise((r) => setTimeout(r, 10));
1839
+ }
1840
+ }
1841
+ } finally {
1842
+ bridge?.cleanup();
1843
+ spawnCleanup?.();
1844
+ }
1845
+ }
1846
+ };
1847
+ function formatPrompt(messages) {
1848
+ const parts = [];
1849
+ for (const msg of messages) {
1850
+ if (msg.role === "user") {
1851
+ parts.push(`User: ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
1852
+ `);
1853
+ } else if (msg.role === "assistant") {
1854
+ parts.push(`Assistant: ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
1855
+ `);
1856
+ } else if (msg.role === "tool") {
1857
+ parts.push(`Tool result (${msg.toolCallId}): ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
1858
+ `);
1859
+ }
1860
+ }
1861
+ return parts.join("\n");
1862
+ }
1863
+ function createClaudeCliProvider(options) {
1864
+ return new ClaudeCliProvider(options);
1865
+ }
1866
+
1867
+ // src/agent/gate.ts
1868
+ var SUBMIT_TOOL = "submit_answer";
1869
+ var REJECT_TOOL = "reject";
1870
+ function providerFor(profile, env = process.env, cwd) {
1871
+ const ready = readiness(profile, env);
1872
+ if (!ready.ready) throw new Error(`agent profile ${profile.name} is not ready: ${ready.reason}`);
1873
+ const model = profile.model || DEFAULT_MODEL[profile.provider] || void 0;
1874
+ switch (profile.provider) {
1875
+ case "anthropic":
1876
+ return createAnthropicProvider({ apiKey: env[keyEnvOf(profile)], model, baseUrl: profile.baseUrl, maxTokens: profile.maxTokens });
1877
+ case "openai":
1878
+ return createOpenAICompatProvider({ apiKey: env[keyEnvOf(profile)] ?? "none", model, baseUrl: profile.baseUrl, maxTokens: profile.maxTokens });
1879
+ case "claude-cli":
1880
+ return createClaudeCliProvider({ binPath: profile.bin, model: model || void 0, cwd, env, allowedTools: [] });
1881
+ }
1882
+ }
1883
+ function fieldToJsonSchema(f) {
1884
+ if (!f) return {};
1885
+ switch (f.type) {
1886
+ case "string":
1887
+ return { type: "string" };
1888
+ case "number":
1889
+ return { type: "number" };
1890
+ case "boolean":
1891
+ return { type: "boolean" };
1892
+ case "enum":
1893
+ return { enum: f.values };
1894
+ case "array":
1895
+ return { type: "array", items: fieldToJsonSchema(f.items) };
1896
+ case "object": {
1897
+ if (!f.fields) return { type: "object", additionalProperties: true, ...f.text ? { description: f.text } : {} };
1898
+ const properties = {};
1899
+ const required = [];
1900
+ for (const [k, v] of Object.entries(f.fields)) {
1901
+ properties[k] = fieldToJsonSchema(v);
1902
+ if (!v.optional) required.push(k);
1903
+ }
1904
+ return { type: "object", properties, ...required.length ? { required } : {}, additionalProperties: false };
1905
+ }
1906
+ // An `any` field accepts every value, so its schema carries only the
1907
+ // description. A field type this function does not know is treated the same.
1908
+ case "any":
1909
+ default:
1910
+ return f.text ? { description: f.text } : {};
1911
+ }
1912
+ }
1913
+ function answerTool(gate) {
1914
+ const schemaOf = (o) => gate.outputSchema?.[o] ?? void 0;
1915
+ const describe = (o) => gate.outputTypes?.[o] ? ` (${gate.outputTypes[o]})` : "";
1916
+ if (gate.outputs.length === 0) {
1917
+ return { tool: { name: SUBMIT_TOOL, description: "Mark the task as done. It has no result to return.", inputSchema: { type: "object", properties: {} } }, unwrap: () => null };
1918
+ }
1919
+ if (gate.outputs.length === 1) {
1920
+ const o = gate.outputs[0];
1921
+ const s = schemaOf(o);
1922
+ const isObject = !s || s.type === "object" || s.type === "any";
1923
+ if (isObject) {
1924
+ const js = fieldToJsonSchema(s ?? { type: "object" });
1925
+ const properties2 = js.properties ?? {};
1926
+ const inputSchema = { type: "object", properties: properties2, ...js.required ? { required: js.required } : {}, ...js.additionalProperties === void 0 ? { additionalProperties: true } : { additionalProperties: js.additionalProperties } };
1927
+ return { tool: { name: SUBMIT_TOOL, description: `Return the result of the task: the value for \`${o}\`${describe(o)}.`, inputSchema }, unwrap: (args) => args };
1928
+ }
1929
+ return {
1930
+ tool: { name: SUBMIT_TOOL, description: `Return the result of the task as \`value\`: the gate's \`${o}\`${describe(o)}.`, inputSchema: { type: "object", properties: { value: fieldToJsonSchema(s) }, required: ["value"] } },
1931
+ unwrap: (args) => args.value
1932
+ };
1933
+ }
1934
+ const properties = {};
1935
+ for (const o of gate.outputs) properties[o] = { ...fieldToJsonSchema(schemaOf(o)), ...gate.outputTypes?.[o] ? { description: gate.outputTypes[o] } : {} };
1936
+ return {
1937
+ tool: { name: SUBMIT_TOOL, description: `Return the result of the task: one value per output (${gate.outputs.join(", ")}).`, inputSchema: { type: "object", properties, required: [...gate.outputs] } },
1938
+ unwrap: (args) => Object.fromEntries(gate.outputs.map((o) => [o, args[o]]))
1939
+ };
1940
+ }
1941
+ var rejectTool = {
1942
+ name: REJECT_TOOL,
1943
+ description: "Give the task up. The workflow continues along its failure path. Say why in one sentence.",
1944
+ inputSchema: { type: "object", properties: { reason: { type: "string" } }, required: ["reason"] }
1945
+ };
1946
+ function systemPromptFor(profile, workflow, gate) {
1947
+ const lines = [
1948
+ profile.system?.trim() ?? "",
1949
+ `You are completing one step of the workflow "${workflow.name}"${workflow.description ? ` (${workflow.description})` : ""}: the agent gate "${gate.node}".`,
1950
+ "You receive the gate's inputs as JSON: `agentId` names the task, `context` is the material to work from, `prompt` is the instruction when there is one.",
1951
+ `Do the task, then call \`${SUBMIT_TOOL}\` exactly once with the result.${gate.hasFailurePort ? ` If the task cannot be done from what you were given, call \`${REJECT_TOOL}\` with a short reason instead.` : ""}`,
1952
+ "Only the tool call counts. Anything you write in prose is discarded."
1953
+ ];
1954
+ return lines.filter(Boolean).join("\n\n");
1955
+ }
1956
+ function userMessageFor(gate) {
1957
+ const shown = { ...gate.inputs };
1958
+ const parts = [`Inputs:
1959
+ ${JSON.stringify(shown, null, 2)}`];
1960
+ if (typeof gate.inputs.prompt === "string" && gate.inputs.prompt.trim()) parts.push(`Instruction:
1961
+ ${gate.inputs.prompt}`);
1962
+ parts.push(`When done, call ${SUBMIT_TOOL}.`);
1963
+ return parts.join("\n\n");
1964
+ }
1965
+ async function tryProfile(profile, env = process.env, opts = {}) {
1966
+ const started = Date.now();
1967
+ let provider;
1968
+ try {
1969
+ provider = opts.provider ?? providerFor(profile, env, opts.cwd);
1970
+ } catch (e) {
1971
+ return { ok: false, ms: Date.now() - started, error: getErrorMessage(e) };
1972
+ }
1973
+ try {
1974
+ const result = await runAgentLoop(provider, [], async () => ({ result: "", isError: true }), [{ role: "user", content: "Reply with the single word OK." }], {
1975
+ systemPrompt: { prefix: profile.system?.trim() || "You are a terse assistant.", suffix: "" },
1976
+ maxIterations: 1,
1977
+ maxTokens: Math.min(profile.maxTokens ?? 64, 256),
1978
+ model: profile.model || void 0,
1979
+ signal: opts.signal
1980
+ });
1981
+ const text = result.summary.trim();
1982
+ const usage = { promptTokens: result.usage.promptTokens, completionTokens: result.usage.completionTokens, ...result.usage.costUsd ? { costUsd: result.usage.costUsd } : {} };
1983
+ if (!result.success) return { ok: false, ms: Date.now() - started, text, usage, error: text || "the provider returned an error" };
1984
+ return { ok: true, ms: Date.now() - started, text, usage };
1985
+ } catch (e) {
1986
+ return { ok: false, ms: Date.now() - started, error: getErrorMessage(e) };
1987
+ }
1988
+ }
1989
+ function answerFromText(text, gate) {
1990
+ const m = text.match(/```(?:json)?\s*([\s\S]*?)```/) ?? text.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
1991
+ if (!m) return void 0;
1992
+ let parsed;
1993
+ try {
1994
+ parsed = JSON.parse(m[1]);
1995
+ } catch {
1996
+ return void 0;
1997
+ }
1998
+ if (gate.outputs.length > 1) {
1999
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
2000
+ if (!gate.outputs.every((o) => o in parsed)) return void 0;
2001
+ return Object.fromEntries(gate.outputs.map((o) => [o, parsed[o]]));
2002
+ }
2003
+ if (gate.outputs.length === 1) {
2004
+ const s = gate.outputSchema?.[gate.outputs[0]];
2005
+ const one = parsed;
2006
+ if (s && s.type !== "object" && s.type !== "any" && typeof one === "object" && one !== null && gate.outputs[0] in one) return one[gate.outputs[0]];
2007
+ return parsed;
2008
+ }
2009
+ return null;
2010
+ }
2011
+ async function answerGate(opts) {
2012
+ const { gate, workflow, profile } = opts;
2013
+ const env = opts.env ?? process.env;
2014
+ const provider = opts.provider ?? providerFor(profile, env, opts.cwd);
2015
+ const started = Date.now();
2016
+ const emit = (e) => opts.onEvent?.(e);
2017
+ emit({ type: "agent", phase: "start", profile: profile.name, provider: profile.provider, model: profile.model || DEFAULT_MODEL[profile.provider] || void 0 });
2018
+ const { tool, unwrap } = answerTool(gate);
2019
+ const tools = gate.hasFailurePort ? [tool, rejectTool] : [tool];
2020
+ let captured;
2021
+ let usage = { promptTokens: 0, completionTokens: 0 };
2022
+ let text = "";
2023
+ const executor = async (rawName, args) => {
2024
+ const name = stripMcpToolPrefix(rawName);
2025
+ if (name === SUBMIT_TOOL) {
2026
+ captured = { kind: "answer", answer: unwrap(args ?? {}) };
2027
+ return { result: "Recorded. You are done.", isError: false };
2028
+ }
2029
+ if (name === REJECT_TOOL && gate.hasFailurePort) {
2030
+ captured = { kind: "reject", reason: typeof args?.reason === "string" && args.reason.trim() ? args.reason : "rejected by the agent" };
2031
+ return { result: "Recorded. You are done.", isError: false };
2032
+ }
2033
+ return { result: `Unknown tool ${name}. Call ${SUBMIT_TOOL}${gate.hasFailurePort ? ` or ${REJECT_TOOL}` : ""}.`, isError: true };
2034
+ };
2035
+ const onStreamEvent = (ev) => {
2036
+ if (ev.type === "text_delta") {
2037
+ text += ev.text;
2038
+ emit({ type: "agent", phase: "text", text: ev.text });
2039
+ } else if (ev.type === "thinking_delta") emit({ type: "agent", phase: "thinking", text: ev.text });
2040
+ else if (ev.type === "usage") emit({ type: "agent", phase: "usage", promptTokens: ev.promptTokens, completionTokens: ev.completionTokens, costUsd: ev.costUsd });
2041
+ };
2042
+ const onToolEvent = (ev) => {
2043
+ emit({ type: "agent", phase: "tool", stage: ev.type === "tool_call_start" ? "start" : "result", name: stripMcpToolPrefix(ev.name), args: ev.args, result: ev.result, isError: ev.isError });
2044
+ };
2045
+ const system = { prefix: systemPromptFor(profile, workflow, gate), suffix: "" };
2046
+ const messages = [{ role: "user", content: userMessageFor(gate) }];
2047
+ const maxIterations = profile.maxIterations ?? DEFAULT_MAX_ITERATIONS;
2048
+ const run = async (conversation, iterations) => runAgentLoop(provider, tools, executor, conversation, {
2049
+ systemPrompt: system,
2050
+ maxIterations: iterations,
2051
+ maxTokens: profile.maxTokens,
2052
+ model: profile.model || void 0,
2053
+ signal: opts.signal,
2054
+ onStreamEvent,
2055
+ onToolEvent,
2056
+ // Once the answer is in hand there is nothing more to ask. Stop before
2057
+ // another model turn is paid for.
2058
+ onTurnEnd: async () => captured ? { continue: false } : void 0
2059
+ });
2060
+ let transcript = messages;
2061
+ let toolCalls = 0;
2062
+ try {
2063
+ let result = await run(messages, maxIterations);
2064
+ transcript = result.messages;
2065
+ toolCalls = result.toolCallCount;
2066
+ usage = { promptTokens: result.usage.promptTokens, completionTokens: result.usage.completionTokens, ...result.usage.costUsd ? { costUsd: result.usage.costUsd } : {} };
2067
+ if (!captured && result.success && !opts.signal?.aborted) {
2068
+ const nudged = [...result.messages, { role: "user", content: `You have not called ${SUBMIT_TOOL}. Call it now with your result${gate.hasFailurePort ? `, or ${REJECT_TOOL} if you cannot` : ""}.` }];
2069
+ result = await run(nudged, 2);
2070
+ transcript = result.messages;
2071
+ toolCalls += result.toolCallCount;
2072
+ usage = { promptTokens: usage.promptTokens + result.usage.promptTokens, completionTokens: usage.completionTokens + result.usage.completionTokens, ...usage.costUsd || result.usage.costUsd ? { costUsd: (usage.costUsd ?? 0) + (result.usage.costUsd ?? 0) } : {} };
2073
+ }
2074
+ if (!captured) {
2075
+ const fromText = answerFromText(text, gate);
2076
+ if (fromText !== void 0) captured = { kind: "answer", answer: fromText };
2077
+ }
2078
+ if (!captured) {
2079
+ captured = { kind: "failed", error: opts.signal?.aborted ? "stopped before an answer was submitted" : result.success ? `the model did not call ${SUBMIT_TOOL}` : result.summary };
2080
+ }
2081
+ } catch (e) {
2082
+ captured = { kind: "failed", error: getErrorMessage(e) };
2083
+ }
2084
+ const ms = Date.now() - started;
2085
+ emit({ type: "agent", phase: "done", outcome: captured.kind, ms, ...captured.kind === "failed" ? { error: captured.error } : {}, ...captured.kind === "reject" ? { reason: captured.reason } : {} });
2086
+ return { outcome: captured, usage, toolCalls, ms, transcript, text };
2087
+ }
2088
+
2089
+ // src/coordinator/agent-gate.ts
2090
+ function transcriptName(gateId) {
2091
+ return `agent-${gateId.slice(0, 16)}`;
2092
+ }
2093
+ var ANSWER_ABANDONED_AFTER_MS = 60 * 60 * 1e3;
2094
+ function agentOwnerDead(note, now = Date.now()) {
2095
+ const age = now - Date.parse(note.startedAt);
2096
+ if (!note.owner || note.owner.host !== os5.hostname()) return age > ANSWER_ABANDONED_AFTER_MS;
2097
+ if (note.owner.pid === process.pid) return false;
2098
+ try {
2099
+ process.kill(note.owner.pid, 0);
2100
+ return false;
2101
+ } catch (e) {
2102
+ return e.code === "ESRCH";
2103
+ }
2104
+ }
2105
+ function isAnswering(note, gateId) {
2106
+ return !!note && note.status === "answering" && note.gateId === gateId && !agentOwnerDead(note);
2107
+ }
2108
+ async function reclaimStaleAgentAnswers(coordinator) {
2109
+ const reclaimed = [];
2110
+ for (const s of await coordinator.list()) {
2111
+ if (s.status !== "waiting" || s.agent?.status !== "answering") continue;
2112
+ const rec = await coordinator.record(s.runId);
2113
+ if (!rec?.agent || rec.agent.status !== "answering" || !agentOwnerDead(rec.agent)) continue;
2114
+ try {
2115
+ await coordinator.setAgent(s.runId, { ...rec.agent, status: "failed", endedAt: (/* @__PURE__ */ new Date()).toISOString(), error: "the process answering this gate ended before it could answer" });
2116
+ } catch (e) {
2117
+ if (e instanceof RunBusyError) continue;
2118
+ throw e;
2119
+ }
2120
+ reclaimed.push(s.runId);
2121
+ }
2122
+ return reclaimed;
2123
+ }
2124
+ async function answerAgentGate(coordinator, runId, opts) {
2125
+ const rec = await coordinator.record(runId);
2126
+ if (!rec || rec.status !== "waiting" || !rec.gate) return { kind: "skip", why: "not-waiting" };
2127
+ if (rec.gate.kind !== "agent") return { kind: "skip", why: "not-agent" };
2128
+ if (rec.agents === "manual") return { kind: "skip", why: "manual" };
2129
+ if (isAnswering(rec.agent, rec.gate.id)) return { kind: "skip", why: "already-answering" };
2130
+ const env = opts.env ?? process.env;
2131
+ const profiles = opts.profiles ?? loadAgentProfiles(opts.projectDir);
2132
+ const profile = profileForGate(profiles, { workflow: rec.workflowName, node: rec.gate.node, agentId: rec.gate.inputs.agentId });
2133
+ if (!profile) return { kind: "skip", why: "no-profile" };
2134
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2135
+ const model = profile.model || DEFAULT_MODEL[profile.provider] || void 0;
2136
+ const base = { gateId: rec.gate.id, node: rec.gate.node, profile: profile.name, provider: profile.provider, model, status: "answering", startedAt, owner: { pid: process.pid, host: os5.hostname() } };
2137
+ const ready = readiness(profile, env);
2138
+ if (!ready.ready) {
2139
+ const note2 = { ...base, status: "failed", endedAt: startedAt, error: ready.reason };
2140
+ await coordinator.setAgent(runId, note2);
2141
+ return { kind: "not-ready", profile: profile.name, reason: ready.reason ?? "not ready", note: note2 };
2142
+ }
2143
+ await coordinator.setAgent(runId, base);
2144
+ const shape = await opts.outputSchema?.(rec);
2145
+ const result = await answerGate({
2146
+ gate: { node: rec.gate.node, inputs: rec.gate.inputs, absent: rec.gate.absent, outputs: rec.gate.outputs, hasFailurePort: rec.gate.hasFailurePort, outputSchema: shape?.schema ?? null, outputTypes: shape?.types },
2147
+ workflow: { name: rec.workflowName, description: opts.workflowDescription?.(rec) },
2148
+ profile,
2149
+ provider: opts.provider?.(profile, env),
2150
+ env,
2151
+ cwd: opts.projectDir,
2152
+ signal: opts.signal,
2153
+ onEvent: opts.onEvent
2154
+ });
2155
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
2156
+ const transcript = {
2157
+ gateId: rec.gate.id,
2158
+ node: rec.gate.node,
2159
+ profile: profile.name,
2160
+ provider: profile.provider,
2161
+ model,
2162
+ startedAt,
2163
+ endedAt,
2164
+ ms: result.ms,
2165
+ outcome: result.outcome,
2166
+ usage: result.usage,
2167
+ toolCalls: result.toolCalls,
2168
+ text: result.text,
2169
+ messages: result.transcript
2170
+ };
2171
+ if (!await coordinator.record(runId)) return { kind: "skip", why: "not-waiting" };
2172
+ await coordinator.keep(runId, transcriptName(rec.gate.id), transcript);
2173
+ const done = { ...base, endedAt, usage: result.usage, toolCalls: result.toolCalls };
2174
+ if (result.outcome.kind === "answer") {
2175
+ const note2 = { ...done, status: "answered" };
2176
+ await coordinator.setAgent(runId, note2);
2177
+ return { kind: "answer", profile: profile.name, answer: result.outcome.answer, note: note2 };
2178
+ }
2179
+ if (result.outcome.kind === "reject") {
2180
+ const note2 = { ...done, status: "rejected", error: result.outcome.reason };
2181
+ await coordinator.setAgent(runId, note2);
2182
+ return { kind: "reject", profile: profile.name, reason: result.outcome.reason, note: note2 };
2183
+ }
2184
+ const note = { ...done, status: "failed", error: result.outcome.error };
2185
+ await coordinator.setAgent(runId, note);
2186
+ return { kind: "failed", profile: profile.name, error: result.outcome.error, note };
2187
+ }
2188
+ async function noteAnswerMisfit(coordinator, runId, error) {
2189
+ if (!(error instanceof MissingOutputsError || error instanceof InvalidAnswerError)) return false;
2190
+ const agent = (await coordinator.record(runId))?.agent;
2191
+ if (!agent) return false;
2192
+ try {
2193
+ await coordinator.setAgent(runId, { ...agent, status: "failed", error: `the answer did not fit the gate: ${error.message}` });
2194
+ } catch (e) {
2195
+ if (!(e instanceof RunBusyError)) throw e;
2196
+ }
2197
+ return true;
2198
+ }
2199
+
2200
+ export {
2201
+ RunBusyError,
2202
+ defaultRunsDir,
2203
+ computeBundleDigest,
2204
+ createFileEffectAdapter,
2205
+ ParseError,
2206
+ AmbiguousWorkflowError,
2207
+ RunNotFoundError,
2208
+ RunNotWaitingError,
2209
+ BundleChangedError,
2210
+ MissingOutputsError,
2211
+ InvalidAnswerError,
2212
+ createLocalCoordinator,
2213
+ tryProfile,
2214
+ transcriptName,
2215
+ isAnswering,
2216
+ reclaimStaleAgentAnswers,
2217
+ answerAgentGate,
2218
+ noteAnswerMisfit
2219
+ };