yaml-flow 7.1.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/browser/asset-integrity.json +8 -4
  2. package/browser/board-livecards-client.js +1 -1
  3. package/browser/board-livecards-localstorage.js +5 -5
  4. package/browser/live-cards.js +19 -3309
  5. package/cli/board-live-cards-lib-tjYsPt5U.d.ts +321 -0
  6. package/{dist/cli → cli}/browser-api/board-live-cards-browser-adapter.d.ts +3 -5
  7. package/{dist/cli → cli}/browser-api/card-store-browser-api.d.ts +1 -2
  8. package/{dist/cli → cli}/browser-api/card-store-browser-api.js +1 -1
  9. package/cli/execution-interface-C_A6WCiK.d.ts +284 -0
  10. package/{dist/cli → cli}/node/artifacts-store-cli.js +2 -2
  11. package/cli/node/batch-runner-cli.js +3 -0
  12. package/cli/node/board-live-cards-cli.js +15 -0
  13. package/{dist/cli → cli}/node/execution-adapter.d.ts +3 -3
  14. package/cli/node/execution-adapter.js +3 -0
  15. package/{dist/cli → cli}/node/fs-board-adapter.d.ts +24 -11
  16. package/cli/node/fs-board-adapter.js +14 -0
  17. package/cli/node/step-machine-cli.d.ts +7 -0
  18. package/cli/node/step-machine-cli.js +5 -0
  19. package/{dist/board-live-cards-public-5n1-syA3.d.cts → cli/types-CziUxkiv.d.ts} +68 -5
  20. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/card-store-ref.json +1 -0
  21. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/chat-handler.json +1 -0
  22. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/outputs-store-ref.json +1 -0
  23. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/task-executor.json +1 -0
  24. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.state-snapshot/board/graph.json +29 -0
  25. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.state-snapshot/board/lastJournalProcessedId.json +1 -0
  26. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime-out/.outputs/status.json +25 -0
  27. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-market-prices/computed_values.json +67 -0
  28. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-portfolio/computed_values.json +1 -0
  29. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-portfolio-value/computed_values.json +52 -0
  30. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/holdings.json +22 -0
  31. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/positions.json +46 -0
  32. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/quotes.json +35 -0
  33. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/status.json +113 -0
  34. package/examples/{example-board → board}/demo-server-config.json +0 -1
  35. package/examples/{example-board → board}/demo-server.js +23 -48
  36. package/examples/{example-board → board}/demo-shell-with-server.html +3 -3
  37. package/examples/{example-board → board}/demo-task-executor.js +71 -24
  38. package/examples/board/gandalf-cards/card-source-kinds.json +36 -0
  39. package/examples/board/gandalf-cards/cards/_index.json +7 -0
  40. package/examples/board/gandalf-cards/cards/card-source-kinds.json +64 -0
  41. package/examples/board/source-def-flows/copilot.flow.json +33 -0
  42. package/examples/board/source-def-flows/mock.flow.json +35 -0
  43. package/examples/board/source-def-flows/url-list.flow.json +33 -0
  44. package/examples/board/source-def-flows/url.flow.json +33 -0
  45. package/examples/board/source-def-flows/workiq.flow.json +34 -0
  46. package/examples/board/source-def-handlers/copilot-source-handler.js +141 -0
  47. package/examples/board/source-def-handlers/http-source-handler.js +145 -0
  48. package/examples/board/source_def_flows.json +249 -0
  49. package/examples/board/test/demo-http-test.js +317 -0
  50. package/examples/{example-board → board-local}/demo-shell-localstorage.html +4 -4
  51. package/examples/{browser/boards/portfolio-tracker → portfolio-tracker/handlers}/portfolio-tracker-fetch-prices.js +1 -1
  52. package/examples/{browser/boards/portfolio-tracker/portfolio-tracker-public.js → portfolio-tracker/portfolio-tracker.js} +11 -14
  53. package/examples/{browser/boards/portfolio-tracker → portfolio-tracker/test}/portfolio-t4.js +32 -50
  54. package/lib/artifacts-store-lib-public-BABrgFkV.d.ts +119 -0
  55. package/lib/artifacts-store-lib-public-DGa8BpJT.d.cts +119 -0
  56. package/lib/artifacts-store-public.cjs +2 -0
  57. package/lib/artifacts-store-public.d.cts +5 -0
  58. package/lib/artifacts-store-public.d.ts +5 -0
  59. package/lib/artifacts-store-public.js +2 -0
  60. package/lib/board-live-cards-node.cjs +14 -0
  61. package/{dist/cli/node/execution-adapter.d.cts → lib/board-live-cards-node.d.cts} +45 -85
  62. package/lib/board-live-cards-node.d.ts +134 -0
  63. package/lib/board-live-cards-node.js +14 -0
  64. package/lib/board-live-cards-public-BnmRAbQV.d.cts +383 -0
  65. package/{dist/board-live-cards-public-CK_J8uv0.d.ts → lib/board-live-cards-public-CsmYrvpd.d.ts} +142 -76
  66. package/lib/board-live-cards-public.cjs +3 -0
  67. package/lib/board-live-cards-public.d.cts +4 -0
  68. package/lib/board-live-cards-public.d.ts +4 -0
  69. package/lib/board-live-cards-public.js +3 -0
  70. package/lib/board-live-cards-server-runtime.cjs +9 -0
  71. package/lib/board-live-cards-server-runtime.d.cts +6 -0
  72. package/lib/board-live-cards-server-runtime.d.ts +6 -0
  73. package/lib/board-live-cards-server-runtime.js +9 -0
  74. package/lib/board-livegraph-runtime/index.cjs +3 -0
  75. package/{dist → lib}/board-livegraph-runtime/index.d.cts +1 -2
  76. package/{dist → lib}/board-livegraph-runtime/index.d.ts +1 -2
  77. package/lib/board-livegraph-runtime/index.js +3 -0
  78. package/{dist/storage-refs.cjs → lib/board-worker-adapter.cjs} +2 -2
  79. package/{dist/storage-refs.d.cts → lib/board-worker-adapter.d.cts} +4 -3
  80. package/{dist/storage-refs.d.ts → lib/board-worker-adapter.d.ts} +4 -3
  81. package/{dist/storage-refs.js → lib/board-worker-adapter.js} +2 -2
  82. package/{dist → lib}/card-compute/index.cjs +1 -1
  83. package/{dist → lib}/card-compute/index.js +1 -1
  84. package/lib/card-store-public.cjs +2 -0
  85. package/lib/card-store-public.d.cts +61 -0
  86. package/lib/card-store-public.d.ts +61 -0
  87. package/lib/card-store-public.js +2 -0
  88. package/lib/card-validation.cjs +10 -0
  89. package/lib/card-validation.d.cts +35 -0
  90. package/lib/card-validation.d.ts +35 -0
  91. package/lib/card-validation.js +10 -0
  92. package/{dist/constants-oCEbNpul.d.ts → lib/constants-BPVLb3Es.d.ts} +1 -1
  93. package/{dist/constants-BzZUyYlp.d.cts → lib/constants-DXxsRN9y.d.cts} +1 -1
  94. package/{dist → lib}/continuous-event-graph/index.cjs +2 -2
  95. package/{dist → lib}/continuous-event-graph/index.d.cts +3 -5
  96. package/{dist → lib}/continuous-event-graph/index.d.ts +3 -5
  97. package/{dist → lib}/continuous-event-graph/index.js +2 -2
  98. package/{dist → lib}/event-graph/index.d.cts +2 -2
  99. package/{dist → lib}/event-graph/index.d.ts +2 -2
  100. package/{dist → lib}/execution-refs.d.cts +29 -10
  101. package/{dist → lib}/execution-refs.d.ts +29 -10
  102. package/lib/index.cjs +25 -0
  103. package/{dist → lib}/index.d.cts +7 -8
  104. package/{dist → lib}/index.d.ts +7 -8
  105. package/lib/index.js +25 -0
  106. package/{dist/live-cards-bridge-BXbVTsna.d.cts → lib/live-cards-bridge-DC_ZU0eS.d.ts} +134 -3
  107. package/{dist/live-cards-bridge-Ds28XR15.d.ts → lib/live-cards-bridge-b25aAVvE.d.cts} +134 -3
  108. package/lib/loader-CuuLjxVA.d.cts +42 -0
  109. package/lib/loader-Zborm2pq.d.ts +42 -0
  110. package/lib/server-runtime/index.cjs +9 -0
  111. package/{dist → lib}/server-runtime/index.d.cts +4 -4
  112. package/{dist → lib}/server-runtime/index.d.ts +4 -4
  113. package/lib/server-runtime/index.js +9 -0
  114. package/lib/step-machine/index.d.cts +64 -0
  115. package/lib/step-machine/index.d.ts +64 -0
  116. package/lib/step-machine-public/index.cjs +5 -0
  117. package/{dist → lib}/step-machine-public/index.d.cts +14 -1
  118. package/{dist → lib}/step-machine-public/index.d.ts +14 -1
  119. package/lib/step-machine-public/index.js +5 -0
  120. package/lib/storage-interface-BhAON-gW.d.cts +84 -0
  121. package/lib/storage-interface-BhAON-gW.d.ts +84 -0
  122. package/lib/stores/index.cjs +3 -0
  123. package/lib/stores/index.d.cts +4 -0
  124. package/lib/stores/index.d.ts +4 -0
  125. package/lib/stores/index.js +3 -0
  126. package/lib/stores/kv.cjs +3 -0
  127. package/lib/stores/kv.d.cts +32 -0
  128. package/lib/stores/kv.d.ts +32 -0
  129. package/lib/stores/kv.js +3 -0
  130. package/{dist → lib}/stores/memory.d.cts +1 -1
  131. package/{dist → lib}/stores/memory.d.ts +1 -1
  132. package/{dist/types-HGDTWIun.d.ts → lib/types-CBxkYuLY.d.ts} +2 -1
  133. package/{dist/types-ycun84cq.d.cts → lib/types-DQ1bKuB1.d.cts} +11 -0
  134. package/{dist/types-ycun84cq.d.ts → lib/types-DQ1bKuB1.d.ts} +11 -0
  135. package/{dist/types-CU3DjTKL.d.cts → lib/types-DkFvgxwq.d.cts} +2 -1
  136. package/package.json +79 -119
  137. package/board-live-cards-cli.js +0 -37
  138. package/browser/board-livecards-client.js.map +0 -1
  139. package/browser/board-livecards-localstorage.js.map +0 -1
  140. package/browser/board-livegraph-engine.js +0 -3
  141. package/browser/board-livegraph-engine.js.map +0 -1
  142. package/browser/card-compute.js +0 -266
  143. package/browser/compute-jsonata.js.map +0 -1
  144. package/card-store.js +0 -37
  145. package/dist/batch/index.cjs.map +0 -1
  146. package/dist/batch/index.js.map +0 -1
  147. package/dist/board-live-cards-lib-Bg6EvCo5.d.cts +0 -136
  148. package/dist/board-live-cards-lib-jM2uYG1v.d.ts +0 -136
  149. package/dist/board-livegraph-runtime/index.cjs +0 -3
  150. package/dist/board-livegraph-runtime/index.cjs.map +0 -1
  151. package/dist/board-livegraph-runtime/index.js +0 -3
  152. package/dist/board-livegraph-runtime/index.js.map +0 -1
  153. package/dist/card-compute/index.cjs.map +0 -1
  154. package/dist/card-compute/index.js.map +0 -1
  155. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs +0 -3
  156. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs.map +0 -1
  157. package/dist/cli/browser-api/board-live-cards-browser-adapter.d.cts +0 -37
  158. package/dist/cli/browser-api/board-live-cards-browser-adapter.js.map +0 -1
  159. package/dist/cli/browser-api/card-store-browser-api.cjs +0 -2
  160. package/dist/cli/browser-api/card-store-browser-api.cjs.map +0 -1
  161. package/dist/cli/browser-api/card-store-browser-api.d.cts +0 -26
  162. package/dist/cli/browser-api/card-store-browser-api.js.map +0 -1
  163. package/dist/cli/node/artifacts-store-cli.cjs +0 -11
  164. package/dist/cli/node/artifacts-store-cli.cjs.map +0 -1
  165. package/dist/cli/node/artifacts-store-cli.d.cts +0 -8
  166. package/dist/cli/node/artifacts-store-cli.js.map +0 -1
  167. package/dist/cli/node/board-live-cards-cli.cjs +0 -15
  168. package/dist/cli/node/board-live-cards-cli.cjs.map +0 -1
  169. package/dist/cli/node/board-live-cards-cli.d.cts +0 -20
  170. package/dist/cli/node/board-live-cards-cli.js +0 -15
  171. package/dist/cli/node/board-live-cards-cli.js.map +0 -1
  172. package/dist/cli/node/card-store-cli.cjs +0 -8
  173. package/dist/cli/node/card-store-cli.cjs.map +0 -1
  174. package/dist/cli/node/card-store-cli.d.cts +0 -15
  175. package/dist/cli/node/card-store-cli.js.map +0 -1
  176. package/dist/cli/node/execution-adapter.cjs +0 -3
  177. package/dist/cli/node/execution-adapter.cjs.map +0 -1
  178. package/dist/cli/node/execution-adapter.js +0 -3
  179. package/dist/cli/node/execution-adapter.js.map +0 -1
  180. package/dist/cli/node/fs-board-adapter.cjs +0 -14
  181. package/dist/cli/node/fs-board-adapter.cjs.map +0 -1
  182. package/dist/cli/node/fs-board-adapter.d.cts +0 -204
  183. package/dist/cli/node/fs-board-adapter.js +0 -14
  184. package/dist/cli/node/fs-board-adapter.js.map +0 -1
  185. package/dist/cli/node/source-cli-task-executor.cjs +0 -11
  186. package/dist/cli/node/source-cli-task-executor.cjs.map +0 -1
  187. package/dist/cli/node/source-cli-task-executor.js.map +0 -1
  188. package/dist/config/index.cjs.map +0 -1
  189. package/dist/config/index.js.map +0 -1
  190. package/dist/continuous-event-graph/index.cjs.map +0 -1
  191. package/dist/continuous-event-graph/index.js.map +0 -1
  192. package/dist/event-graph/index.cjs.map +0 -1
  193. package/dist/event-graph/index.js.map +0 -1
  194. package/dist/execution-refs.cjs.map +0 -1
  195. package/dist/execution-refs.js.map +0 -1
  196. package/dist/index.cjs +0 -30
  197. package/dist/index.cjs.map +0 -1
  198. package/dist/index.js +0 -30
  199. package/dist/index.js.map +0 -1
  200. package/dist/inference/index.cjs +0 -7
  201. package/dist/inference/index.cjs.map +0 -1
  202. package/dist/inference/index.d.cts +0 -229
  203. package/dist/inference/index.d.ts +0 -229
  204. package/dist/inference/index.js +0 -7
  205. package/dist/inference/index.js.map +0 -1
  206. package/dist/server-runtime/index.cjs +0 -9
  207. package/dist/server-runtime/index.cjs.map +0 -1
  208. package/dist/server-runtime/index.js +0 -9
  209. package/dist/server-runtime/index.js.map +0 -1
  210. package/dist/step-machine/index.cjs.map +0 -1
  211. package/dist/step-machine/index.d.cts +0 -102
  212. package/dist/step-machine/index.d.ts +0 -102
  213. package/dist/step-machine/index.js.map +0 -1
  214. package/dist/step-machine-public/index.cjs +0 -3
  215. package/dist/step-machine-public/index.cjs.map +0 -1
  216. package/dist/step-machine-public/index.js +0 -3
  217. package/dist/step-machine-public/index.js.map +0 -1
  218. package/dist/storage-refs.cjs.map +0 -1
  219. package/dist/storage-refs.js.map +0 -1
  220. package/dist/stores/file.cjs +0 -2
  221. package/dist/stores/file.cjs.map +0 -1
  222. package/dist/stores/file.d.cts +0 -36
  223. package/dist/stores/file.d.ts +0 -36
  224. package/dist/stores/file.js +0 -2
  225. package/dist/stores/file.js.map +0 -1
  226. package/dist/stores/index.cjs +0 -2
  227. package/dist/stores/index.cjs.map +0 -1
  228. package/dist/stores/index.d.cts +0 -4
  229. package/dist/stores/index.d.ts +0 -4
  230. package/dist/stores/index.js +0 -2
  231. package/dist/stores/index.js.map +0 -1
  232. package/dist/stores/localStorage.cjs +0 -2
  233. package/dist/stores/localStorage.cjs.map +0 -1
  234. package/dist/stores/localStorage.d.cts +0 -34
  235. package/dist/stores/localStorage.d.ts +0 -34
  236. package/dist/stores/localStorage.js +0 -2
  237. package/dist/stores/localStorage.js.map +0 -1
  238. package/dist/stores/memory.cjs.map +0 -1
  239. package/dist/stores/memory.js.map +0 -1
  240. package/dist/types-CHSdoAAA.d.cts +0 -135
  241. package/dist/types-CoW0gQl3.d.ts +0 -135
  242. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-fetch-prices.py +0 -201
  243. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.js +0 -370
  244. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.py +0 -398
  245. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-inference-adapter.js +0 -196
  246. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.js +0 -300
  247. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.py +0 -617
  248. package/examples/browser/boards/portfolio-tracker/portfolio-tracker.py +0 -366
  249. package/examples/browser/livecards-browser/index.html +0 -41
  250. package/examples/browser/step-machine-browser/index.html +0 -367
  251. package/examples/cli/step-machine-cli/portfolio-tracker/--base-ref/.runtime-out +0 -1
  252. package/examples/cli/step-machine-cli/portfolio-tracker/--base-ref/board-graph.json +0 -32
  253. package/examples/cli/step-machine-cli/portfolio-tracker/cards/holdings-table.json +0 -22
  254. package/examples/cli/step-machine-cli/portfolio-tracker/cards/portfolio-form.json +0 -43
  255. package/examples/cli/step-machine-cli/portfolio-tracker/cards/portfolio-value.json +0 -15
  256. package/examples/cli/step-machine-cli/portfolio-tracker/cards/price-fetch.json +0 -15
  257. package/examples/cli/step-machine-cli/portfolio-tracker/fetch-prices.js +0 -48
  258. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +0 -125
  259. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +0 -32
  260. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +0 -26
  261. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/poll-status-cli.js +0 -49
  262. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +0 -25
  263. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +0 -23
  264. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/status-cli.js +0 -21
  265. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +0 -38
  266. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +0 -48
  267. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +0 -31
  268. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/_board_pycli.py +0 -107
  269. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/add-cards.py +0 -51
  270. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/init-board.py +0 -45
  271. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/poll-status.py +0 -71
  272. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/reset-board-dir.py +0 -36
  273. package/examples/cli/step-machine-cli/portfolio-tracker/inline-python-demo.flow.yaml +0 -26
  274. package/examples/cli/step-machine-cli/portfolio-tracker/inline-python-handlers.py +0 -39
  275. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker-pycli.flow.yaml +0 -80
  276. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +0 -76
  277. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.input.json +0 -44
  278. package/examples/cli/step-machine-cli/portfolio-tracker/run-inline-python-demo-pycli.py +0 -43
  279. package/examples/cli/step-machine-cli/portfolio-tracker/run-portfolio-tracker-pycli.py +0 -77
  280. package/examples/cli/step-machine-cli/portfolio-tracker/run-portfolio-tracker.bat +0 -28
  281. package/examples/cli/step-machine-demo/jsonata-init-board-cli.js +0 -31
  282. package/examples/cli/step-machine-demo/jsonata-init-board.flow.yaml +0 -54
  283. package/examples/cli/step-machine-demo/one-step-cli-only.flow.yaml +0 -21
  284. package/examples/cli/step-machine-demo/step-cli-echo-y.js +0 -15
  285. package/examples/cli/step-machine-demo/step2-double-cli.js +0 -33
  286. package/examples/cli/step-machine-demo/two-step-math.flow.yaml +0 -93
  287. package/examples/cli/step-machine-demo/two-step-mixed.flow.yaml +0 -43
  288. package/examples/example-board/agent-instructions-cardlayout.md +0 -56
  289. package/examples/example-board/agent-instructions.md +0 -834
  290. package/examples/example-board/demo-shell.html +0 -63
  291. package/examples/index.html +0 -785
  292. package/examples/npm-libs/batch/batch-step-machine.ts +0 -121
  293. package/examples/npm-libs/continuous-event-graph/live-cards-board.ts +0 -215
  294. package/examples/npm-libs/continuous-event-graph/live-portfolio-dashboard.ts +0 -555
  295. package/examples/npm-libs/continuous-event-graph/portfolio-tracker.ts +0 -287
  296. package/examples/npm-libs/continuous-event-graph/reactive-monitoring.ts +0 -265
  297. package/examples/npm-libs/continuous-event-graph/reactive-pipeline.ts +0 -168
  298. package/examples/npm-libs/continuous-event-graph/soc-incident-board.ts +0 -287
  299. package/examples/npm-libs/continuous-event-graph/stock-dashboard.ts +0 -229
  300. package/examples/npm-libs/event-graph/ci-cd-pipeline.ts +0 -243
  301. package/examples/npm-libs/event-graph/executor-diamond.ts +0 -165
  302. package/examples/npm-libs/event-graph/executor-pipeline.ts +0 -161
  303. package/examples/npm-libs/event-graph/research-pipeline.ts +0 -137
  304. package/examples/npm-libs/flows/ai-conversation.yaml +0 -116
  305. package/examples/npm-libs/flows/order-processing.yaml +0 -143
  306. package/examples/npm-libs/flows/simple-greeting.yaml +0 -54
  307. package/examples/npm-libs/graph-of-graphs/multi-stage-etl.ts +0 -307
  308. package/examples/npm-libs/graph-of-graphs/url-processing-pipeline.ts +0 -254
  309. package/examples/npm-libs/inference/azure-deployment.ts +0 -149
  310. package/examples/npm-libs/inference/copilot-cli.ts +0 -138
  311. package/examples/npm-libs/inference/data-pipeline.ts +0 -145
  312. package/examples/npm-libs/inference/pluggable-adapters.ts +0 -254
  313. package/examples/npm-libs/node/ai-conversation.ts +0 -195
  314. package/examples/npm-libs/node/simple-greeting.ts +0 -101
  315. package/examples/step-machine-cli/portfolio-tracker/cards/holdings-table.json +0 -22
  316. package/examples/step-machine-cli/portfolio-tracker/cards/portfolio-form.json +0 -43
  317. package/examples/step-machine-cli/portfolio-tracker/cards/portfolio-value.json +0 -15
  318. package/examples/step-machine-cli/portfolio-tracker/cards/price-fetch.json +0 -15
  319. package/examples/step-machine-cli/portfolio-tracker/fetch-prices.js +0 -48
  320. package/examples/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +0 -57
  321. package/examples/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +0 -27
  322. package/examples/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +0 -25
  323. package/examples/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +0 -29
  324. package/examples/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +0 -27
  325. package/examples/step-machine-cli/portfolio-tracker/handlers/status-cli.js +0 -25
  326. package/examples/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +0 -37
  327. package/examples/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +0 -53
  328. package/examples/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +0 -35
  329. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker-task-executor.cjs +0 -96
  330. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +0 -227
  331. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker.input.json +0 -38
  332. package/examples/step-machine-cli/portfolio-tracker/run-portfolio-tracker.bat +0 -28
  333. package/step-machine-cli.js +0 -407
  334. /package/{dist/cli → cli}/browser-api/board-live-cards-browser-adapter.js +0 -0
  335. /package/{dist/board-livegraph-runtime → cli/browser-api}/jsonata-sync.cjs +0 -0
  336. /package/{dist/cli → cli}/node/artifacts-store-cli.d.ts +0 -0
  337. /package/{dist/cli/node/source-cli-task-executor.d.cts → cli/node/batch-runner-cli.d.ts} +0 -0
  338. /package/{dist/cli → cli}/node/board-live-cards-cli.d.ts +0 -0
  339. /package/{dist/cli → cli}/node/card-store-cli.d.ts +0 -0
  340. /package/{dist/cli → cli}/node/card-store-cli.js +0 -0
  341. /package/{dist/card-compute → cli/node}/jsonata-sync.cjs +0 -0
  342. /package/{dist/cli → cli}/node/source-cli-task-executor.d.ts +0 -0
  343. /package/{dist/cli → cli}/node/source-cli-task-executor.js +0 -0
  344. /package/examples/{example-board → board}/cards/card-concentration.json +0 -0
  345. /package/examples/{example-board → board}/cards/card-my-identity.json +0 -0
  346. /package/examples/{example-board → board}/cards/card-portfolio-action.json +0 -0
  347. /package/examples/{example-board → board}/cards/card-portfolio-intelligence.json +0 -0
  348. /package/examples/{example-board → board}/cards/card-portfolio-risks.json +0 -0
  349. /package/examples/{example-board → board}/cards/card-rebalance-impact.json +0 -0
  350. /package/examples/{example-board → board}/cards/card-rebalance-sim.json +0 -0
  351. /package/examples/{example-board → board}/cards/cardT-market-prices.json +0 -0
  352. /package/examples/{example-board → board}/cards/cardT-portfolio-value.json +0 -0
  353. /package/examples/{example-board → board}/cards/cardT-portfolio.json +0 -0
  354. /package/examples/{example-board → board}/demo-chat-handler.js +0 -0
  355. /package/examples/{example-board → board}/scripts/copilot_wrapper.bat +0 -0
  356. /package/examples/{example-board → board}/scripts/copilot_wrapper_helper.ps1 +0 -0
  357. /package/examples/{example-board → board}/scripts/workiq_wrapper.mjs +0 -0
  358. /package/examples/{browser/boards/portfolio-tracker → board/test}/portfolio-tracker-sse-worker.js +0 -0
  359. /package/{dist → lib}/batch/index.cjs +0 -0
  360. /package/{dist → lib}/batch/index.d.cts +0 -0
  361. /package/{dist → lib}/batch/index.d.ts +0 -0
  362. /package/{dist → lib}/batch/index.js +0 -0
  363. /package/{dist/cli/browser-api → lib/board-livegraph-runtime}/jsonata-sync.cjs +0 -0
  364. /package/{dist → lib}/card-compute/index.d.cts +0 -0
  365. /package/{dist → lib}/card-compute/index.d.ts +0 -0
  366. /package/{dist/cli/node → lib/card-compute}/jsonata-sync.cjs +0 -0
  367. /package/{dist → lib}/config/index.cjs +0 -0
  368. /package/{dist → lib}/config/index.d.cts +0 -0
  369. /package/{dist → lib}/config/index.d.ts +0 -0
  370. /package/{dist → lib}/config/index.js +0 -0
  371. /package/{dist → lib}/continuous-event-graph/jsonata-sync.cjs +0 -0
  372. /package/{dist → lib}/event-graph/index.cjs +0 -0
  373. /package/{dist → lib}/event-graph/index.js +0 -0
  374. /package/{dist → lib}/execution-refs.cjs +0 -0
  375. /package/{dist → lib}/execution-refs.js +0 -0
  376. /package/{dist → lib}/jsonata-sync.cjs +0 -0
  377. /package/{dist → lib}/server-runtime/jsonata-sync.cjs +0 -0
  378. /package/{dist → lib}/step-machine/index.cjs +0 -0
  379. /package/{dist → lib}/step-machine/index.js +0 -0
  380. /package/{dist → lib}/step-machine-public/jsonata-sync.cjs +0 -0
  381. /package/{dist → lib}/stores/memory.cjs +0 -0
  382. /package/{dist → lib}/stores/memory.js +0 -0
  383. /package/{dist → lib}/types-BBhqYGhE.d.cts +0 -0
  384. /package/{dist → lib}/types-BBhqYGhE.d.ts +0 -0
  385. /package/{dist → lib}/validate-BAVzUJWa.d.ts +0 -0
  386. /package/{dist → lib}/validate-Dbu7ygys.d.cts +0 -0
@@ -1,7 +0,0 @@
1
- 'use strict';var child_process=require('child_process');function g(t){return t?Array.isArray(t.provides)?t.provides:[]:[]}function l(t){return t?Array.isArray(t.requires)?t.requires:[]:[]}function y(t){return t.tasks??{}}function C(t,e,s){let n=t.tasks[e]??m(),o={};if(s){let i=s.tasks[e],c=l(i);for(let r of c)for(let[u,f]of Object.entries(s.tasks))if(g(f).includes(r)){let p=t.tasks[u];p?.lastDataHash&&(o[r]=p.lastDataHash);break}}let a={...n,status:"running",startedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),progress:0,error:void 0,startConsumedHashes:o};return {...t,tasks:{...t.tasks,[e]:a},lastUpdated:new Date().toISOString()}}function O(t,e,s,n,o,a){let i=t.tasks[s]??m(),c=e.tasks[s];if(!c)throw new Error(`Task "${s}" not found in graph`);let r;n&&c.on&&c.on[n]?r=c.on[n]:r=g(c);let u=i.startConsumedHashes?{...i.startConsumedHashes}:{...i.lastConsumedHashes};if(!i.startConsumedHashes){let S=c.requires??[];for(let h of S)for(let[k,d]of Object.entries(e.tasks))if(g(d).includes(h)){let T=t.tasks[k];T?.lastDataHash&&(u[h]=T.lastDataHash);break}}let f={...i,status:"completed",completedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),executionCount:i.executionCount+1,lastEpoch:i.executionCount+1,lastDataHash:o,data:a,lastConsumedHashes:u,error:void 0},p=[...new Set([...t.availableOutputs,...r])];return {...t,tasks:{...t.tasks,[s]:f},availableOutputs:p,lastUpdated:new Date().toISOString()}}function I(t,e,s,n){let o=t.tasks[s]??m(),a=e.tasks[s];if(a?.retry){let r=o.retryCount+1;if(r<=a.retry.max_attempts){let u={...o,status:"not-started",retryCount:r,lastUpdated:new Date().toISOString(),error:n};return {...t,tasks:{...t.tasks,[s]:u},lastUpdated:new Date().toISOString()}}}let i={...o,status:"failed",failedAt:new Date().toISOString(),lastUpdated:new Date().toISOString(),error:n,executionCount:o.executionCount+1},c=t.availableOutputs;if(a?.on_failure&&a.on_failure.length>0&&(c=[...new Set([...t.availableOutputs,...a.on_failure])]),a?.circuit_breaker&&i.executionCount>=a.circuit_breaker.max_executions){let r=a.circuit_breaker.on_break;c=[...new Set([...c,...r])];}return {...t,tasks:{...t.tasks,[s]:i},availableOutputs:c,lastUpdated:new Date().toISOString()}}function A(t,e,s,n){let o=t.tasks[e]??m(),a={...o,progress:typeof n=="number"?n:o.progress,messages:[...o.messages??[],...s?[{message:s,timestamp:new Date().toISOString(),status:o.status}]:[]],lastUpdated:new Date().toISOString()};return {...t,tasks:{...t.tasks,[e]:a},lastUpdated:new Date().toISOString()}}function w(t,e){let s=t.tasks[e];if(!s)return t;let n={...s,status:"not-started",startedAt:void 0,completedAt:void 0,failedAt:void 0,error:void 0,data:void 0,progress:null,lastUpdated:new Date().toISOString()};return {...t,tasks:{...t.tasks,[e]:n},lastUpdated:new Date().toISOString()}}function m(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function x(t,e){let{config:s,state:n}=t;if("executionId"in e&&e.executionId&&e.executionId!==n.executionId)return t;switch(e.type){case "task-started":return {config:s,state:C(n,e.taskName,s)};case "task-completed":return {config:s,state:O(n,s,e.taskName,e.result,e.dataHash,e.data)};case "task-failed":return {config:s,state:I(n,s,e.taskName,e.error)};case "task-progress":return {config:s,state:A(n,e.taskName,e.message,e.progress)};case "task-restart":return {config:s,state:w(n,e.taskName)};case "inject-tokens":return {config:s,state:{...n,availableOutputs:[...new Set([...n.availableOutputs,...e.tokens])],lastUpdated:new Date().toISOString()}};case "agent-action":return {config:s,state:M(n,e.action)};case "task-upsert":return D(t,e.taskName,e.taskConfig);case "task-removal":return N(t,e.taskName);case "node-requires-add":return v(t,e.nodeName,e.tokens);case "node-requires-remove":return _(t,e.nodeName,e.tokens);case "node-provides-add":return U(t,e.nodeName,e.tokens);case "node-provides-remove":return j(t,e.nodeName,e.tokens);default:return t}}function D(t,e,s){let n=!!t.config.tasks[e];return {config:{...t.config,tasks:{...t.config.tasks,[e]:s}},state:{...t.state,tasks:{...t.state.tasks,[e]:n?t.state.tasks[e]:P()},lastUpdated:new Date().toISOString()}}}function N(t,e){if(!t.config.tasks[e])return t;let{[e]:s,...n}=t.config.tasks,{[e]:o,...a}=t.state.tasks;return {config:{...t.config,tasks:n},state:{...t.state,tasks:a,lastUpdated:new Date().toISOString()}}}function v(t,e,s){let n=t.config.tasks[e];if(!n)return t;let o=l(n),a=s.filter(i=>!o.includes(i));return a.length===0?t:{config:{...t.config,tasks:{...t.config.tasks,[e]:{...n,requires:[...o,...a]}}},state:t.state}}function _(t,e,s){let n=t.config.tasks[e];if(!n)return t;let o=l(n),a=o.filter(i=>!s.includes(i));return a.length===o.length?t:{config:{...t.config,tasks:{...t.config.tasks,[e]:{...n,requires:a}}},state:t.state}}function U(t,e,s){let n=t.config.tasks[e];if(!n)return t;let o=g(n),a=s.filter(i=>!o.includes(i));return a.length===0?t:{config:{...t.config,tasks:{...t.config.tasks,[e]:{...n,provides:[...o,...a]}}},state:t.state}}function j(t,e,s){let n=t.config.tasks[e];if(!n)return t;let o=g(n),a=o.filter(i=>!s.includes(i));return a.length===o.length?t:{config:{...t.config,tasks:{...t.config.tasks,[e]:{...n,provides:a}}},state:t.state}}function P(){return {status:"not-started",executionCount:0,retryCount:0,lastEpoch:0,messages:[],progress:null}}function M(t,e){let s=new Date().toISOString();switch(e){case "stop":return {...t,status:"stopped",lastUpdated:s};case "pause":return {...t,status:"paused",lastUpdated:s};case "resume":return {...t,status:"running",lastUpdated:s};default:return t}}var E=.5,H=`You are a workflow completion analyzer. Given a graph of tasks with their current states, evidence, and inference hints, determine which tasks appear to be completed based on the available evidence.
2
-
3
- For each task you analyze, provide a JSON response. Be conservative \u2014 only mark tasks as completed when the evidence strongly supports it.`;function G(t,e={}){let{scope:s,context:n,systemPrompt:o}=e,a=y(t.config),{state:i}=t,c=L(t,s);if(c.length===0)return "";let r=[];r.push(o||H),r.push(""),r.push("## Graph State"),r.push(""),r.push(`Available tokens: ${i.availableOutputs.length>0?i.availableOutputs.join(", "):"(none)"}`),r.push("");let u=Object.entries(i.tasks).filter(([f,p])=>p.status==="completed").map(([f])=>f);u.length>0&&(r.push(`Completed tasks: ${u.join(", ")}`),r.push("")),r.push("## Tasks to Analyze"),r.push("");for(let f of c){let p=a[f],S=i.tasks[f];r.push(`### ${f}`),p.description&&r.push(`Description: ${p.description}`);let h=l(p),k=g(p);h.length>0&&r.push(`Requires: ${h.join(", ")}`),k.length>0&&r.push(`Provides: ${k.join(", ")}`),r.push(`Current status: ${S?.status||"not-started"}`);let d=p.inference;d&&(d.criteria&&r.push(`Completion criteria: ${d.criteria}`),d.keywords?.length&&r.push(`Keywords: ${d.keywords.join(", ")}`),d.suggestedChecks?.length&&r.push(`Suggested checks: ${d.suggestedChecks.join("; ")}`)),r.push("");}return n&&(r.push("## Additional Context / Evidence"),r.push(""),r.push(n),r.push("")),r.push("## Response Format"),r.push(""),r.push("Respond with a JSON array of objects, one per task you have evidence for:"),r.push("```json"),r.push("["),r.push(" {"),r.push(' "taskName": "task-name",'),r.push(' "confidence": 0.0 to 1.0,'),r.push(' "reasoning": "explanation of why you believe this task is complete or not"'),r.push(" }"),r.push("]"),r.push("```"),r.push(""),r.push("Rules:"),r.push('- Only include tasks from the "Tasks to Analyze" section'),r.push("- confidence 0.0 = no evidence of completion, 1.0 = certain it is complete"),r.push("- If you have no evidence for a task, omit it from the array"),r.push("- Be conservative \u2014 require clear evidence before high confidence"),r.push("- Respond ONLY with the JSON array, no additional text"),r.join(`
4
- `)}async function b(t,e,s={}){s.threshold??E;let o=L(t,s.scope);if(o.length===0)return {suggestions:[],promptUsed:"",rawResponse:"",analyzedNodes:[]};let a=G(t,s),i=await e.analyze(a);return {suggestions:F(i,o),promptUsed:a,rawResponse:i,analyzedNodes:o}}function R(t,e,s=E){let n=t;for(let o of e.suggestions){if(o.confidence<s)continue;let a=n.state.tasks[o.taskName];if(!a||a.status==="completed"||a.status==="running")continue;let i=new Date().toISOString();n=x(n,{type:"task-started",taskName:o.taskName,timestamp:i}),n=x(n,{type:"task-completed",taskName:o.taskName,timestamp:i,result:"llm-inferred"});}return n}async function q(t,e,s={}){let n=s.threshold??E,o=await b(t,e,s),a=R(t,o,n),i=o.suggestions.filter(r=>r.confidence>=n),c=o.suggestions.filter(r=>r.confidence<n);return {live:a,inference:o,applied:i,skipped:c}}function L(t,e){let s=y(t.config),{state:n}=t,o=[];for(let[a,i]of Object.entries(s)){let c=n.tasks[a];c?.status==="completed"||c?.status==="running"||(e?e.includes(a)&&o.push(a):i.inference?.autoDetectable&&o.push(a));}return o}function F(t,e,s){let n=new Set(e);try{let o=$(t);if(!o)return [];let a=JSON.parse(o);if(!Array.isArray(a))return [];let i=[];for(let c of a){if(!c||typeof c!="object"||typeof c.taskName!="string"||typeof c.confidence!="number"||!n.has(c.taskName))continue;let r=Math.max(0,Math.min(1,c.confidence));i.push({taskName:c.taskName,confidence:r,reasoning:typeof c.reasoning=="string"?c.reasoning:"",detectionMethod:"llm-inferred"});}return i}catch{return []}}function $(t){if(!t||typeof t!="string")return null;let e=t.trim(),s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)return s[1].trim();let n=e.indexOf("["),o=e.lastIndexOf("]");return n!==-1&&o>n?e.slice(n,o+1):e.startsWith("[")?e:null}function z(t){let e=t.timeout??6e4;return {analyze:s=>new Promise((n,o)=>{let a=t.args(s),i=child_process.execFile(t.command,t.stdin?t.args(""):a,{timeout:e,cwd:t.cwd,env:t.env?{...process.env,...t.env}:void 0,maxBuffer:10*1024*1024},(c,r,u)=>{c?o(new Error(`CLI adapter failed: ${t.command} exited with ${c.code??"error"}`+(u?`
5
- stderr: ${u.slice(0,500)}`:"")+`
6
- ${c.message}`)):n(r);});t.stdin&&i.stdin&&(i.stdin.write(s),i.stdin.end());})}}function K(t){let e=t.timeout??6e4;return {analyze:async s=>{let n=t.buildBody?t.buildBody(s):{prompt:s},o=new AbortController,a=setTimeout(()=>o.abort(),e);try{let i=await fetch(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.headers??{}},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let r=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${r.slice(0,500)}`)}let c=await i.json();return t.extractResponse?t.extractResponse(c):typeof c.response=="string"?c.response:typeof c.text=="string"?c.text:typeof c.content=="string"?c.content:JSON.stringify(c)}finally{clearTimeout(a);}}}}exports.applyInferences=R;exports.buildInferencePrompt=G;exports.createCliAdapter=z;exports.createHttpAdapter=K;exports.inferAndApply=q;exports.inferCompletions=b;//# sourceMappingURL=index.cjs.map
7
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/event-graph/graph-helpers.ts","../../src/event-graph/task-transitions.ts","../../src/continuous-event-graph/core.ts","../../src/inference/core.ts","../../src/inference/adapters.ts"],"names":["getProvides","task","getRequires","getAllTasks","graph","applyTaskStart","state","taskName","existingTask","createDefaultGraphEngineStore","startConsumedHashes","taskConfig","requires","token","otherName","otherConfig","otherState","updatedTask","applyTaskCompletion","result","dataHash","data","outputTokens","lastConsumedHashes","newOutputs","applyTaskFailure","error","retryCount","breakTokens","applyTaskProgress","message","progress","applyTaskRestart","applyEvent","live","event","config","applyAgentAction","addNode","removeNode","addRequires","removeRequires","addProvides","removeProvides","name","exists","_removedConfig","remainingTasks","_removedState","remainingStates","nodeName","tokens","current","toAdd","t","remaining","action","now","DEFAULT_THRESHOLD","DEFAULT_SYSTEM_PROMPT","buildInferencePrompt","options","scope","context","systemPrompt","graphTasks","candidates","getAnalyzableCandidates","lines","completedTasks","_","ts","taskState","provides","hints","inferCompletions","adapter","analyzedNodes","prompt","rawResponse","parseInferenceResponse","applyInferences","threshold","suggestion","inferAndApply","inference","updated","applied","s","skipped","validNodes","_threshold","validSet","jsonStr","extractJson","parsed","suggestions","item","confidence","text","trimmed","fenceMatch","firstBracket","lastBracket","createCliAdapter","opts","timeout","resolve","reject","args","child","execFile","stdout","stderr","createHttpAdapter","body","controller","timer","response","json"],"mappings":"wDAcO,SAASA,EAAYC,CAAAA,CAAwC,CAClE,OAAKA,CAAAA,CACD,MAAM,OAAA,CAAQA,CAAAA,CAAK,QAAQ,CAAA,CAAUA,EAAK,QAAA,CACvC,GAFW,EAGpB,CAEO,SAASC,CAAAA,CAAYD,CAAAA,CAAwC,CAClE,OAAKA,CAAAA,CACD,KAAA,CAAM,QAAQA,CAAAA,CAAK,QAAQ,EAAUA,CAAAA,CAAK,QAAA,CACvC,EAAC,CAFU,EAGpB,CAEO,SAASE,CAAAA,CAAYC,CAAAA,CAAgD,CAC1E,OAAOA,CAAAA,CAAM,KAAA,EAAS,EACxB,CCfO,SAASC,EAAeC,CAAAA,CAAuBC,CAAAA,CAAkBH,EAAqC,CAC3G,IAAMI,CAAAA,CAAeF,CAAAA,CAAM,MAAMC,CAAQ,CAAA,EAAKE,GAA8B,CAKtEC,CAAAA,CAA8C,EAAC,CACrD,GAAIN,CAAAA,CAAO,CACT,IAAMO,CAAAA,CAAaP,CAAAA,CAAM,MAAMG,CAAQ,CAAA,CACjCK,EAAWV,CAAAA,CAAYS,CAAU,CAAA,CACvC,IAAA,IAAWE,KAASD,CAAAA,CAClB,IAAA,GAAW,CAACE,CAAAA,CAAWC,CAAW,IAAK,MAAA,CAAO,OAAA,CAAQX,CAAAA,CAAM,KAAK,EAC/D,GAAIJ,CAAAA,CAAYe,CAAW,CAAA,CAAE,SAASF,CAAK,CAAA,CAAG,CAC5C,IAAMG,EAAaV,CAAAA,CAAM,KAAA,CAAMQ,CAAS,CAAA,CACpCE,CAAAA,EAAY,eAAcN,CAAAA,CAAoBG,CAAK,CAAA,CAAIG,CAAAA,CAAW,cACtE,KACF,CAGN,CAEA,IAAMC,CAAAA,CAAgC,CACpC,GAAGT,CAAAA,CACH,MAAA,CAAQ,SAAA,CACR,UAAW,IAAI,IAAA,GAAO,WAAA,EAAY,CAClC,YAAa,IAAI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AAA,CAAUA,CAAI,CAC5B,QAAE,CACA,YAAA,CAAaF,CAAK,EACpB,CACF,CACF,CACF","file":"index.cjs","sourcesContent":["/**\n * Event Graph — Graph Helpers\n *\n * Pure functions for manipulating the requires/provides task dependency graph.\n * No I/O, no side effects.\n */\n\nimport type { GraphConfig, TaskConfig, GraphEngineStore, ExecutionState, RefreshStrategy } from './types.js';\nimport { TASK_STATUS } from './constants.js';\n\n// ============================================================================\n// Accessors — normalize requires/provides to always be arrays\n// ============================================================================\n\nexport function getProvides(task: TaskConfig | undefined): string[] {\n if (!task) return [];\n if (Array.isArray(task.provides)) return task.provides;\n return [];\n}\n\nexport function getRequires(task: TaskConfig | undefined): string[] {\n if (!task) return [];\n if (Array.isArray(task.requires)) return task.requires;\n return [];\n}\n\nexport function getAllTasks(graph: GraphConfig): Record<string, TaskConfig> {\n return graph.tasks ?? {};\n}\n\nexport function getTask(graph: GraphConfig, taskName: string): TaskConfig | undefined {\n return graph.tasks[taskName];\n}\n\nexport function hasTask(graph: GraphConfig, taskName: string): boolean {\n return taskName in graph.tasks;\n}\n\n// ============================================================================\n// Task State Predicates\n// ============================================================================\n\nexport function isNonActiveTask(taskState: GraphEngineStore | undefined): boolean {\n if (!taskState) return false;\n return taskState.status === TASK_STATUS.FAILED || taskState.status === TASK_STATUS.INACTIVATED;\n}\n\nexport function isTaskCompleted(taskState: GraphEngineStore | undefined): boolean {\n return taskState?.status === TASK_STATUS.COMPLETED;\n}\n\nexport function isTaskRunning(taskState: GraphEngineStore | undefined): boolean {\n return taskState?.status === TASK_STATUS.RUNNING;\n}\n\nexport function getRefreshStrategy(taskConfig: TaskConfig, graphSettings?: { refreshStrategy?: RefreshStrategy }): RefreshStrategy {\n return taskConfig.refreshStrategy ?? graphSettings?.refreshStrategy ?? 'data-changed';\n}\n\nexport function isRerunnable(taskConfig: TaskConfig, graphSettings?: { refreshStrategy?: RefreshStrategy }): boolean {\n return getRefreshStrategy(taskConfig, graphSettings) !== 'once';\n}\n\nexport function getMaxExecutions(taskConfig: TaskConfig): number | undefined {\n return taskConfig.maxExecutions;\n}\n\n// ============================================================================\n// Available Outputs Computation\n// ============================================================================\n\n/**\n * Dynamically compute available outputs from all completed tasks.\n * Tasks with strategies other than 'once' may have completed and reset.\n * Pure function.\n */\nexport function computeAvailableOutputs(\n graph: GraphConfig,\n taskStates: Record<string, GraphEngineStore>\n): string[] {\n const outputs: Set<string> = new Set();\n\n for (const [taskName, taskState] of Object.entries(taskStates)) {\n if (taskState.status === TASK_STATUS.COMPLETED) {\n const taskConfig = graph.tasks[taskName];\n if (taskConfig) {\n const provides = getProvides(taskConfig);\n provides.forEach(output => outputs.add(output));\n }\n }\n }\n\n return Array.from(outputs);\n}\n\n// ============================================================================\n// Conflict Detection\n// ============================================================================\n\n/**\n * Group candidate tasks by the outputs they provide.\n * Used to detect conflicts (multiple tasks providing the same output).\n */\nexport function groupTasksByProvides(\n candidateTaskNames: string[],\n tasks: Record<string, TaskConfig>\n): Record<string, string[]> {\n const outputGroups: Record<string, string[]> = {};\n\n candidateTaskNames.forEach(taskName => {\n const task = tasks[taskName];\n if (!task) return;\n const provides = getProvides(task);\n provides.forEach(output => {\n if (!outputGroups[output]) {\n outputGroups[output] = [];\n }\n outputGroups[output].push(taskName);\n });\n });\n\n return outputGroups;\n}\n\n/**\n * Check if a task's outputs conflict with other candidates.\n */\nexport function hasOutputConflict(\n taskName: string,\n taskProvides: string[],\n candidates: string[],\n tasks: Record<string, TaskConfig>\n): boolean {\n for (const otherName of candidates) {\n if (otherName === taskName) continue;\n const otherProvides = getProvides(tasks[otherName]);\n const overlapping = taskProvides.some(output => otherProvides.includes(output));\n if (overlapping) return true;\n }\n return false;\n}\n\n// ============================================================================\n// Immutable Graph Mutation\n// ============================================================================\n\nexport function addKeyToProvides(task: TaskConfig, key: string): TaskConfig {\n const current = getProvides(task);\n if (current.includes(key)) return task;\n return { ...task, provides: [...current, key] };\n}\n\nexport function removeKeyFromProvides(task: TaskConfig, key: string): TaskConfig {\n const current = getProvides(task);\n return { ...task, provides: current.filter(p => p !== key) };\n}\n\nexport function addKeyToRequires(task: TaskConfig, key: string): TaskConfig {\n const current = getRequires(task);\n if (current.includes(key)) return task;\n return { ...task, requires: [...current, key] };\n}\n\nexport function removeKeyFromRequires(task: TaskConfig, key: string): TaskConfig {\n const current = getRequires(task);\n return { ...task, requires: current.filter(r => r !== key) };\n}\n\n// ============================================================================\n// Dynamic Task Management\n// ============================================================================\n\n/**\n * Add a new task to a graph config. Returns a new GraphConfig (immutable).\n */\nexport function addDynamicTask(\n graph: GraphConfig,\n taskName: string,\n taskConfig: TaskConfig\n): GraphConfig {\n return {\n ...graph,\n tasks: {\n ...graph.tasks,\n [taskName]: taskConfig,\n },\n };\n}\n\n/**\n * Create default task state for a new task.\n */\nexport function createDefaultGraphEngineStore(): GraphEngineStore {\n return {\n status: 'not-started',\n executionCount: 0,\n retryCount: 0,\n lastEpoch: 0,\n messages: [],\n progress: null,\n };\n}\n\n/**\n * Create the initial execution state for a graph.\n */\nexport function createInitialExecutionState(\n graph: GraphConfig,\n executionId: string\n): ExecutionState {\n const tasks: Record<string, GraphEngineStore> = {};\n for (const taskName of Object.keys(graph.tasks)) {\n tasks[taskName] = createDefaultGraphEngineStore();\n }\n\n return {\n status: 'running',\n tasks,\n availableOutputs: [],\n stuckDetection: { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] },\n lastUpdated: new Date().toISOString(),\n executionId,\n executionConfig: {\n executionMode: graph.settings.execution_mode ?? 'eligibility-mode',\n conflictStrategy: graph.settings.conflict_strategy ?? 'alphabetical',\n completionStrategy: graph.settings.completion,\n },\n };\n}\n","/**\n * Event Graph — Task State Transitions\n *\n * Pure functions for applying task lifecycle events to execution state.\n * Each function: f(state, ...) → newState\n */\n\nimport type { ExecutionState, GraphEngineStore, GraphConfig } from './types.js';\nimport { getProvides, getRequires } from './graph-helpers.js';\n\n/**\n * Apply task start to execution state. Pure function.\n */\nexport function applyTaskStart(state: ExecutionState, taskName: string, graph?: GraphConfig): ExecutionState {\n const existingTask = state.tasks[taskName] ?? createDefaultGraphEngineStore();\n\n // Snapshot upstream hashes at start time so that if an upstream task\n // completes while this task is running, applyTaskCompletion can detect\n // the mid-flight change and not absorb it into lastConsumedHashes.\n const startConsumedHashes: Record<string, string> = {};\n if (graph) {\n const taskConfig = graph.tasks[taskName];\n const requires = getRequires(taskConfig);\n for (const token of requires) {\n for (const [otherName, otherConfig] of Object.entries(graph.tasks)) {\n if (getProvides(otherConfig).includes(token)) {\n const otherState = state.tasks[otherName];\n if (otherState?.lastDataHash) startConsumedHashes[token] = otherState.lastDataHash;\n break;\n }\n }\n }\n }\n\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n status: 'running',\n startedAt: new Date().toISOString(),\n lastUpdated: new Date().toISOString(),\n progress: 0,\n error: undefined,\n startConsumedHashes,\n };\n\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n lastUpdated: new Date().toISOString(),\n };\n}\n\n/**\n * Apply task completion to execution state.\n * Handles: default provides, conditional provides (on), refresh strategy, data hash tracking.\n * Pure function.\n */\nexport function applyTaskCompletion(\n state: ExecutionState,\n graph: GraphConfig,\n taskName: string,\n result?: string,\n dataHash?: string,\n data?: Record<string, unknown>\n): ExecutionState {\n const existingTask = state.tasks[taskName] ?? createDefaultGraphEngineStore();\n const taskConfig = graph.tasks[taskName];\n if (!taskConfig) {\n throw new Error(`Task \"${taskName}\" not found in graph`);\n }\n\n // Determine which outputs to produce\n let outputTokens: string[];\n if (result && taskConfig.on && taskConfig.on[result]) {\n // Conditional routing — use the on[result] provides\n outputTokens = taskConfig.on[result];\n } else {\n // Default provides\n outputTokens = getProvides(taskConfig);\n }\n\n // Use hashes snapshotted at task-start time as lastConsumedHashes.\n // This ensures that if an upstream task completed while this task was\n // running (mid-flight change), the old hash is preserved in\n // lastConsumedHashes → data-changed detects the difference on the\n // next schedule pass and re-runs this task.\n // Fall back to reading current upstream state only when startConsumedHashes\n // is absent (e.g. restored from an older snapshot without the field).\n const lastConsumedHashes: Record<string, string> = existingTask.startConsumedHashes\n ? { ...existingTask.startConsumedHashes }\n : { ...existingTask.lastConsumedHashes };\n\n if (!existingTask.startConsumedHashes) {\n // Legacy fallback: populate from current upstream state\n const requires = taskConfig.requires ?? [];\n for (const token of requires) {\n for (const [otherName, otherConfig] of Object.entries(graph.tasks)) {\n if (getProvides(otherConfig).includes(token)) {\n const otherState = state.tasks[otherName];\n if (otherState?.lastDataHash) {\n lastConsumedHashes[token] = otherState.lastDataHash;\n }\n break;\n }\n }\n }\n }\n\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n status: 'completed',\n completedAt: new Date().toISOString(),\n lastUpdated: new Date().toISOString(),\n executionCount: existingTask.executionCount + 1,\n lastEpoch: existingTask.executionCount + 1,\n lastDataHash: dataHash,\n data,\n lastConsumedHashes,\n error: undefined,\n };\n\n // Merge new outputs with existing available outputs\n const newOutputs = [...new Set([...state.availableOutputs, ...outputTokens])];\n\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n availableOutputs: newOutputs,\n lastUpdated: new Date().toISOString(),\n };\n}\n\n/**\n * Apply task failure to execution state.\n * Handles: retry logic, on_failure token injection, circuit breaker.\n * Pure function.\n */\nexport function applyTaskFailure(\n state: ExecutionState,\n graph: GraphConfig,\n taskName: string,\n error: string\n): ExecutionState {\n const existingTask = state.tasks[taskName] ?? createDefaultGraphEngineStore();\n const taskConfig = graph.tasks[taskName];\n\n // Check retry\n if (taskConfig?.retry) {\n const retryCount = existingTask.retryCount + 1;\n if (retryCount <= taskConfig.retry.max_attempts) {\n // Retry — set back to not-started with incremented retry count\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n status: 'not-started',\n retryCount,\n lastUpdated: new Date().toISOString(),\n error,\n };\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n lastUpdated: new Date().toISOString(),\n };\n }\n }\n\n // No more retries — mark as failed\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n status: 'failed',\n failedAt: new Date().toISOString(),\n lastUpdated: new Date().toISOString(),\n error,\n executionCount: existingTask.executionCount + 1,\n };\n\n // Inject failure tokens if configured\n let newOutputs = state.availableOutputs;\n if (taskConfig?.on_failure && taskConfig.on_failure.length > 0) {\n newOutputs = [...new Set([...state.availableOutputs, ...taskConfig.on_failure])];\n }\n\n // Check circuit breaker\n if (taskConfig?.circuit_breaker && updatedTask.executionCount >= taskConfig.circuit_breaker.max_executions) {\n const breakTokens = taskConfig.circuit_breaker.on_break;\n newOutputs = [...new Set([...newOutputs, ...breakTokens])];\n }\n\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n availableOutputs: newOutputs,\n lastUpdated: new Date().toISOString(),\n };\n}\n\n/**\n * Apply task progress update. Pure function.\n */\nexport function applyTaskProgress(\n state: ExecutionState,\n taskName: string,\n message?: string,\n progress?: number\n): ExecutionState {\n const existingTask = state.tasks[taskName] ?? createDefaultGraphEngineStore();\n\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n progress: typeof progress === 'number' ? progress : existingTask.progress,\n messages: [\n ...(existingTask.messages ?? []),\n ...(message ? [{ message, timestamp: new Date().toISOString(), status: existingTask.status }] : []),\n ],\n lastUpdated: new Date().toISOString(),\n };\n\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n lastUpdated: new Date().toISOString(),\n };\n}\n\n/**\n * Apply task restart to execution state.\n * Resets the task to not-started, preserving executionCount and lastEpoch\n * (history). Clears data, error, progress. The task becomes eligible for\n * scheduling again on the next drain cycle.\n * Pure function.\n */\nexport function applyTaskRestart(\n state: ExecutionState,\n taskName: string,\n): ExecutionState {\n const existingTask = state.tasks[taskName];\n if (!existingTask) return state;\n\n const updatedTask: GraphEngineStore = {\n ...existingTask,\n status: 'not-started',\n startedAt: undefined,\n completedAt: undefined,\n failedAt: undefined,\n error: undefined,\n data: undefined,\n progress: null,\n lastUpdated: new Date().toISOString(),\n };\n\n return {\n ...state,\n tasks: { ...state.tasks, [taskName]: updatedTask },\n lastUpdated: new Date().toISOString(),\n };\n}\n\nfunction createDefaultGraphEngineStore(): GraphEngineStore {\n return {\n status: 'not-started',\n executionCount: 0,\n retryCount: 0,\n lastEpoch: 0,\n messages: [],\n progress: null,\n };\n}\n","/**\n * Continuous Event Graph — Core\n *\n * All functions are pure: f(LiveGraph, input) → LiveGraph\n *\n * - createLiveGraph: bootstrap from a GraphConfig\n * - applyEvent: reduce an event (task-started, task-completed, etc.)\n * - addNode / removeNode: structural graph mutations\n * - addRequires / removeRequires / addProvides / removeProvides: wiring mutations\n */\n\nimport type { GraphConfig, TaskConfig, GraphEvent, LiveGraph, NodeInfo, LiveGraphSnapshot } from './types.js';\nimport type { ExecutionState, GraphEngineStore } from '../event-graph/types.js';\nimport { getProvides, getRequires } from '../event-graph/graph-helpers.js';\nimport {\n applyTaskStart,\n applyTaskCompletion,\n applyTaskFailure,\n applyTaskProgress,\n applyTaskRestart,\n} from '../event-graph/task-transitions.js';\n\n// ============================================================================\n// Create\n// ============================================================================\n\n/**\n * Create a LiveGraph from a GraphConfig.\n * Initialises execution state for all tasks in the config.\n */\nexport function createLiveGraph(config: GraphConfig, executionId?: string): LiveGraph {\n const id = executionId ?? `live-${Date.now()}`;\n const tasks: Record<string, GraphEngineStore> = {};\n\n for (const taskName of Object.keys(config.tasks)) {\n tasks[taskName] = createDefaultGraphEngineStore();\n }\n\n const state: ExecutionState = {\n status: 'running',\n tasks,\n availableOutputs: [],\n stuckDetection: { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] },\n lastUpdated: new Date().toISOString(),\n executionId: id,\n executionConfig: {\n executionMode: config.settings.execution_mode ?? 'eligibility-mode',\n conflictStrategy: config.settings.conflict_strategy ?? 'alphabetical',\n completionStrategy: config.settings.completion,\n },\n };\n\n return { config, state };\n}\n\n// ============================================================================\n// Event Reducer\n// ============================================================================\n\n/**\n * Apply an event to the LiveGraph, producing a new LiveGraph.\n * Events are the shared vocabulary — both execution state transitions\n * (task-started, task-completed, etc.) and structural mutations\n * (task-upsert, task-removal, node-requires-add, etc.).\n *\n * Pure function: f(LiveGraph, GraphEvent) → LiveGraph\n */\nexport function applyEvent(live: LiveGraph, event: GraphEvent): LiveGraph {\n const { config, state } = live;\n\n // Ghost event filtering\n if ('executionId' in event && event.executionId && event.executionId !== state.executionId) {\n return live;\n }\n\n switch (event.type) {\n // --- Execution state transitions ---\n\n case 'task-started':\n return { config, state: applyTaskStart(state, event.taskName, config) };\n\n case 'task-completed':\n return { config, state: applyTaskCompletion(state, config, event.taskName, event.result, event.dataHash, event.data) };\n\n case 'task-failed':\n return { config, state: applyTaskFailure(state, config, event.taskName, event.error) };\n\n case 'task-progress':\n return { config, state: applyTaskProgress(state, event.taskName, event.message, event.progress) };\n\n case 'task-restart':\n return { config, state: applyTaskRestart(state, event.taskName) };\n\n case 'inject-tokens':\n return {\n config,\n state: {\n ...state,\n availableOutputs: [...new Set([...state.availableOutputs, ...event.tokens])],\n lastUpdated: new Date().toISOString(),\n },\n };\n\n case 'agent-action':\n return { config, state: applyAgentAction(state, event.action) };\n\n // --- Structural mutations ---\n\n case 'task-upsert':\n return addNode(live, event.taskName, event.taskConfig);\n\n case 'task-removal':\n return removeNode(live, event.taskName);\n\n case 'node-requires-add':\n return addRequires(live, event.nodeName, event.tokens);\n\n case 'node-requires-remove':\n return removeRequires(live, event.nodeName, event.tokens);\n\n case 'node-provides-add':\n return addProvides(live, event.nodeName, event.tokens);\n\n case 'node-provides-remove':\n return removeProvides(live, event.nodeName, event.tokens);\n\n default:\n return live;\n }\n}\n\n/**\n * Apply multiple events atomically to a LiveGraph.\n * Events are reduced sequentially, but the caller only sees the final state.\n * Use this for batch processing (e.g. draining a journal of pending events).\n */\nexport function applyEvents(live: LiveGraph, events: GraphEvent[]): LiveGraph {\n return events.reduce((current, event) => applyEvent(current, event), live);\n}\n\n// ============================================================================\n// Graph Mutations — node-level\n// ============================================================================\n\n/**\n * Upsert a node (task) in the live graph. Updates both config and state atomically.\n * If the node already exists, replaces its config but preserves its state.\n * If new, creates fresh default state.\n */\nexport function addNode(live: LiveGraph, name: string, taskConfig: TaskConfig): LiveGraph {\n const exists = !!live.config.tasks[name];\n return {\n config: {\n ...live.config,\n tasks: { ...live.config.tasks, [name]: taskConfig },\n },\n state: {\n ...live.state,\n tasks: {\n ...live.state.tasks,\n [name]: exists ? live.state.tasks[name] : createDefaultGraphEngineStore(),\n },\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n/**\n * Remove a node (task) from the live graph. Updates both config and state atomically.\n * If the node doesn't exist, returns the graph unchanged.\n * NOTE: Does not clean up references — other nodes' requires/provides are left intact.\n * The caller can use removeRequires() to clean up if needed.\n */\nexport function removeNode(live: LiveGraph, name: string): LiveGraph {\n if (!live.config.tasks[name]) return live;\n\n const { [name]: _removedConfig, ...remainingTasks } = live.config.tasks;\n const { [name]: _removedState, ...remainingStates } = live.state.tasks;\n\n return {\n config: {\n ...live.config,\n tasks: remainingTasks,\n },\n state: {\n ...live.state,\n tasks: remainingStates,\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n// ============================================================================\n// Graph Mutations — wiring\n// ============================================================================\n\n/**\n * Add requires tokens to a node. If the node doesn't exist, returns unchanged.\n * Deduplicates — won't add tokens already in requires.\n */\nexport function addRequires(live: LiveGraph, nodeName: string, tokens: string[]): LiveGraph {\n const task = live.config.tasks[nodeName];\n if (!task) return live;\n\n const current = getRequires(task);\n const toAdd = tokens.filter(t => !current.includes(t));\n if (toAdd.length === 0) return live;\n\n return {\n config: {\n ...live.config,\n tasks: {\n ...live.config.tasks,\n [nodeName]: { ...task, requires: [...current, ...toAdd] },\n },\n },\n state: live.state,\n };\n}\n\n/**\n * Remove requires tokens from a node. If the node doesn't exist, returns unchanged.\n */\nexport function removeRequires(live: LiveGraph, nodeName: string, tokens: string[]): LiveGraph {\n const task = live.config.tasks[nodeName];\n if (!task) return live;\n\n const current = getRequires(task);\n const remaining = current.filter(t => !tokens.includes(t));\n if (remaining.length === current.length) return live;\n\n return {\n config: {\n ...live.config,\n tasks: {\n ...live.config.tasks,\n [nodeName]: { ...task, requires: remaining },\n },\n },\n state: live.state,\n };\n}\n\n/**\n * Add provides tokens to a node. If the node doesn't exist, returns unchanged.\n * Deduplicates — won't add tokens already in provides.\n */\nexport function addProvides(live: LiveGraph, nodeName: string, tokens: string[]): LiveGraph {\n const task = live.config.tasks[nodeName];\n if (!task) return live;\n\n const current = getProvides(task);\n const toAdd = tokens.filter(t => !current.includes(t));\n if (toAdd.length === 0) return live;\n\n return {\n config: {\n ...live.config,\n tasks: {\n ...live.config.tasks,\n [nodeName]: { ...task, provides: [...current, ...toAdd] },\n },\n },\n state: live.state,\n };\n}\n\n/**\n * Remove provides tokens from a node. If the node doesn't exist, returns unchanged.\n */\nexport function removeProvides(live: LiveGraph, nodeName: string, tokens: string[]): LiveGraph {\n const task = live.config.tasks[nodeName];\n if (!task) return live;\n\n const current = getProvides(task);\n const remaining = current.filter(t => !tokens.includes(t));\n if (remaining.length === current.length) return live;\n\n return {\n config: {\n ...live.config,\n tasks: {\n ...live.config.tasks,\n [nodeName]: { ...task, provides: remaining },\n },\n },\n state: live.state,\n };\n}\n\n// ============================================================================\n// Convenience — inject tokens via mutation (sugar over applyEvent)\n// ============================================================================\n\n/**\n * Inject tokens into the live graph's available outputs.\n * Equivalent to applyEvent(live, { type: 'inject-tokens', tokens, timestamp }).\n */\nexport function injectTokens(live: LiveGraph, tokens: string[]): LiveGraph {\n return applyEvent(live, {\n type: 'inject-tokens',\n tokens,\n timestamp: new Date().toISOString(),\n });\n}\n\n/**\n * Drain (remove) tokens from the live graph's available outputs.\n * Inverse of injectTokens — useful for expiring stale data or revoking signals.\n * Tokens that aren't currently available are silently ignored.\n * Pure function.\n */\nexport function drainTokens(live: LiveGraph, tokens: string[]): LiveGraph {\n const toRemove = new Set(tokens);\n const remaining = live.state.availableOutputs.filter(t => !toRemove.has(t));\n\n if (remaining.length === live.state.availableOutputs.length) return live;\n\n return {\n config: live.config,\n state: {\n ...live.state,\n availableOutputs: remaining,\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n// ============================================================================\n// Node lifecycle\n// ============================================================================\n\n/**\n * Reset a node's state back to not-started, clearing error, retry count, progress.\n * Config is untouched. Useful when a failed task should be retried later.\n * If the node doesn't exist, returns unchanged.\n */\nexport function resetNode(live: LiveGraph, name: string): LiveGraph {\n if (!live.config.tasks[name] || !live.state.tasks[name]) return live;\n\n return {\n config: live.config,\n state: {\n ...live.state,\n tasks: {\n ...live.state.tasks,\n [name]: createDefaultGraphEngineStore(),\n },\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n/**\n * Disable a node — sets its status to 'inactivated'.\n * The scheduler will skip inactivated tasks. Config is untouched.\n * If the node doesn't exist or is already inactivated, returns unchanged.\n */\nexport function disableNode(live: LiveGraph, name: string): LiveGraph {\n const taskState = live.state.tasks[name];\n if (!taskState || taskState.status === 'inactivated') return live;\n\n return {\n config: live.config,\n state: {\n ...live.state,\n tasks: {\n ...live.state.tasks,\n [name]: { ...taskState, status: 'inactivated', lastUpdated: new Date().toISOString() },\n },\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n/**\n * Enable a previously-disabled node — sets its status back to 'not-started'.\n * Only acts on 'inactivated' nodes. If the node isn't inactivated, returns unchanged.\n */\nexport function enableNode(live: LiveGraph, name: string): LiveGraph {\n const taskState = live.state.tasks[name];\n if (!taskState || taskState.status !== 'inactivated') return live;\n\n return {\n config: live.config,\n state: {\n ...live.state,\n tasks: {\n ...live.state.tasks,\n [name]: { ...taskState, status: 'not-started', lastUpdated: new Date().toISOString() },\n },\n lastUpdated: new Date().toISOString(),\n },\n };\n}\n\n// ============================================================================\n// Read: getNode\n// ============================================================================\n\n/**\n * Get the config and state for a single node.\n * Returns undefined if the node doesn't exist.\n */\nexport function getNode(live: LiveGraph, name: string): NodeInfo | undefined {\n const config = live.config.tasks[name];\n if (!config) return undefined;\n const state = live.state.tasks[name] ?? createDefaultGraphEngineStore();\n return { name, config, state };\n}\n\n// ============================================================================\n// Persistence: snapshot / restore\n// ============================================================================\n\n/**\n * Serialize a LiveGraph to a plain JSON-safe object.\n * Can be persisted to disk, database, etc.\n */\nexport function snapshot(live: LiveGraph): LiveGraphSnapshot {\n return {\n version: 1,\n config: live.config,\n state: live.state,\n snapshotAt: new Date().toISOString(),\n };\n}\n\n/**\n * Restore a LiveGraph from a snapshot. Validates the shape.\n * Throws if the snapshot is invalid.\n */\nexport function restore(data: unknown): LiveGraph {\n if (!data || typeof data !== 'object') {\n throw new Error('Invalid snapshot: expected an object');\n }\n\n const snap = data as Record<string, unknown>;\n\n if (!snap.config || typeof snap.config !== 'object') {\n throw new Error('Invalid snapshot: missing or invalid \"config\"');\n }\n if (!snap.state || typeof snap.state !== 'object') {\n throw new Error('Invalid snapshot: missing or invalid \"state\"');\n }\n\n const config = snap.config as GraphConfig;\n const state = snap.state as ExecutionState;\n\n if (!config.settings || typeof config.settings !== 'object') {\n throw new Error('Invalid snapshot: config.settings missing');\n }\n if (!config.tasks || typeof config.tasks !== 'object') {\n throw new Error('Invalid snapshot: config.tasks missing');\n }\n if (!state.tasks || typeof state.tasks !== 'object') {\n throw new Error('Invalid snapshot: state.tasks missing');\n }\n if (!Array.isArray(state.availableOutputs)) {\n throw new Error('Invalid snapshot: state.availableOutputs must be an array');\n }\n\n return { config, state };\n}\n\n// ============================================================================\n// Internals\n// ============================================================================\n\nfunction createDefaultGraphEngineStore(): GraphEngineStore {\n return {\n status: 'not-started',\n executionCount: 0,\n retryCount: 0,\n lastEpoch: 0,\n messages: [],\n progress: null,\n };\n}\n\nfunction applyAgentAction(\n state: ExecutionState,\n action: 'start' | 'stop' | 'pause' | 'resume',\n): ExecutionState {\n const now = new Date().toISOString();\n switch (action) {\n case 'stop':\n return { ...state, status: 'stopped', lastUpdated: now };\n case 'pause':\n return { ...state, status: 'paused', lastUpdated: now };\n case 'resume':\n return { ...state, status: 'running', lastUpdated: now };\n default:\n return state;\n }\n}\n","/**\n * Inference — Core\n *\n * LLM inference layer for continuous-event-graph.\n * Pluggable adapter pattern: yaml-flow builds the prompt and parses the\n * response; the caller provides the LLM via an InferenceAdapter.\n *\n * Core pattern:\n * buildInferencePrompt(live) → prompt string (pure, sync)\n * inferCompletions(live, adapter, opts) → InferenceResult (async, calls LLM)\n * applyInferences(live, result, thresh) → LiveGraph (pure, sync)\n * inferAndApply(live, adapter, opts) → InferAndApplyResult (async, convenience)\n */\n\nimport type { LiveGraph } from '../continuous-event-graph/types.js';\nimport type {\n InferenceAdapter,\n InferenceOptions,\n InferenceResult,\n InferredCompletion,\n InferAndApplyResult,\n} from './types.js';\nimport { getAllTasks } from '../event-graph/graph-helpers.js';\nimport { getRequires, getProvides } from '../event-graph/graph-helpers.js';\nimport { applyEvent } from '../continuous-event-graph/core.js';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_THRESHOLD = 0.5;\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a workflow completion analyzer. Given a graph of tasks with their current states, evidence, and inference hints, determine which tasks appear to be completed based on the available evidence.\n\nFor each task you analyze, provide a JSON response. Be conservative — only mark tasks as completed when the evidence strongly supports it.`;\n\n// ============================================================================\n// buildInferencePrompt — pure, sync\n// ============================================================================\n\n/**\n * Build an LLM prompt from the current LiveGraph state.\n * Includes only nodes that are:\n * - Not yet completed\n * - Have `inference.autoDetectable` set to true (or are in scope)\n *\n * Pure function — no side effects.\n */\nexport function buildInferencePrompt(\n live: LiveGraph,\n options: InferenceOptions = {},\n): string {\n const { scope, context, systemPrompt } = options;\n const graphTasks = getAllTasks(live.config);\n const { state } = live;\n\n // Determine which nodes to analyze\n const candidates = getAnalyzableCandidates(live, scope);\n\n if (candidates.length === 0) {\n return '';\n }\n\n const lines: string[] = [];\n\n // System context\n lines.push(systemPrompt || DEFAULT_SYSTEM_PROMPT);\n lines.push('');\n\n // Graph overview\n lines.push('## Graph State');\n lines.push('');\n lines.push(`Available tokens: ${state.availableOutputs.length > 0 ? state.availableOutputs.join(', ') : '(none)'}`);\n lines.push('');\n\n // Completed tasks (for context)\n const completedTasks = Object.entries(state.tasks)\n .filter(([_, ts]) => ts.status === 'completed')\n .map(([name]) => name);\n if (completedTasks.length > 0) {\n lines.push(`Completed tasks: ${completedTasks.join(', ')}`);\n lines.push('');\n }\n\n // Candidate nodes\n lines.push('## Tasks to Analyze');\n lines.push('');\n\n for (const taskName of candidates) {\n const taskConfig = graphTasks[taskName];\n const taskState = state.tasks[taskName];\n\n lines.push(`### ${taskName}`);\n if (taskConfig.description) {\n lines.push(`Description: ${taskConfig.description}`);\n }\n\n const requires = getRequires(taskConfig);\n const provides = getProvides(taskConfig);\n if (requires.length > 0) lines.push(`Requires: ${requires.join(', ')}`);\n if (provides.length > 0) lines.push(`Provides: ${provides.join(', ')}`);\n lines.push(`Current status: ${taskState?.status || 'not-started'}`);\n\n // Inference hints\n const hints = taskConfig.inference;\n if (hints) {\n if (hints.criteria) lines.push(`Completion criteria: ${hints.criteria}`);\n if (hints.keywords?.length) lines.push(`Keywords: ${hints.keywords.join(', ')}`);\n if (hints.suggestedChecks?.length) lines.push(`Suggested checks: ${hints.suggestedChecks.join('; ')}`);\n }\n\n lines.push('');\n }\n\n // Additional evidence/context\n if (context) {\n lines.push('## Additional Context / Evidence');\n lines.push('');\n lines.push(context);\n lines.push('');\n }\n\n // Response format instructions\n lines.push('## Response Format');\n lines.push('');\n lines.push('Respond with a JSON array of objects, one per task you have evidence for:');\n lines.push('```json');\n lines.push('[');\n lines.push(' {');\n lines.push(' \"taskName\": \"task-name\",');\n lines.push(' \"confidence\": 0.0 to 1.0,');\n lines.push(' \"reasoning\": \"explanation of why you believe this task is complete or not\"');\n lines.push(' }');\n lines.push(']');\n lines.push('```');\n lines.push('');\n lines.push('Rules:');\n lines.push('- Only include tasks from the \"Tasks to Analyze\" section');\n lines.push('- confidence 0.0 = no evidence of completion, 1.0 = certain it is complete');\n lines.push('- If you have no evidence for a task, omit it from the array');\n lines.push('- Be conservative — require clear evidence before high confidence');\n lines.push('- Respond ONLY with the JSON array, no additional text');\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// inferCompletions — async, calls LLM\n// ============================================================================\n\n/**\n * Ask an LLM to analyze the current graph state and suggest completions.\n *\n * Builds a prompt from the LiveGraph, sends it through the adapter,\n * parses the structured response, and returns an InferenceResult.\n */\nexport async function inferCompletions(\n live: LiveGraph,\n adapter: InferenceAdapter,\n options: InferenceOptions = {},\n): Promise<InferenceResult> {\n const threshold = options.threshold ?? DEFAULT_THRESHOLD;\n const analyzedNodes = getAnalyzableCandidates(live, options.scope);\n\n // Nothing to analyze\n if (analyzedNodes.length === 0) {\n return { suggestions: [], promptUsed: '', rawResponse: '', analyzedNodes: [] };\n }\n\n const prompt = buildInferencePrompt(live, options);\n const rawResponse = await adapter.analyze(prompt);\n const suggestions = parseInferenceResponse(rawResponse, analyzedNodes, threshold);\n\n return {\n suggestions,\n promptUsed: prompt,\n rawResponse,\n analyzedNodes,\n };\n}\n\n// ============================================================================\n// applyInferences — pure, sync\n// ============================================================================\n\n/**\n * Apply inferred completions to a LiveGraph.\n * Only applies suggestions at or above the given confidence threshold.\n *\n * Under the hood, this fires `task-started` + `task-completed` events\n * for each accepted suggestion (if the task isn't already running/completed).\n *\n * Pure function — returns a new LiveGraph.\n */\nexport function applyInferences(\n live: LiveGraph,\n result: InferenceResult,\n threshold: number = DEFAULT_THRESHOLD,\n): LiveGraph {\n let current = live;\n\n for (const suggestion of result.suggestions) {\n if (suggestion.confidence < threshold) continue;\n\n const taskState = current.state.tasks[suggestion.taskName];\n if (!taskState) continue;\n\n // Skip already completed or running tasks\n if (taskState.status === 'completed' || taskState.status === 'running') continue;\n\n // Apply start + complete events\n const now = new Date().toISOString();\n current = applyEvent(current, {\n type: 'task-started',\n taskName: suggestion.taskName,\n timestamp: now,\n });\n current = applyEvent(current, {\n type: 'task-completed',\n taskName: suggestion.taskName,\n timestamp: now,\n result: 'llm-inferred',\n });\n }\n\n return current;\n}\n\n// ============================================================================\n// inferAndApply — async, convenience\n// ============================================================================\n\n/**\n * Convenience: infer completions and apply them in one step.\n * Returns the updated LiveGraph + full audit trail of what was inferred vs applied.\n */\nexport async function inferAndApply(\n live: LiveGraph,\n adapter: InferenceAdapter,\n options: InferenceOptions = {},\n): Promise<InferAndApplyResult> {\n const threshold = options.threshold ?? DEFAULT_THRESHOLD;\n const inference = await inferCompletions(live, adapter, options);\n const updated = applyInferences(live, inference, threshold);\n\n const applied = inference.suggestions.filter(s => s.confidence >= threshold);\n const skipped = inference.suggestions.filter(s => s.confidence < threshold);\n\n return {\n live: updated,\n inference,\n applied,\n skipped,\n };\n}\n\n// ============================================================================\n// Internals\n// ============================================================================\n\n/**\n * Determine which nodes should be analyzed.\n * - If scope is provided, use those (filtered to non-completed with hints)\n * - Otherwise, find all non-completed nodes with `inference.autoDetectable === true`\n */\nfunction getAnalyzableCandidates(live: LiveGraph, scope?: string[]): string[] {\n const graphTasks = getAllTasks(live.config);\n const { state } = live;\n\n const candidates: string[] = [];\n\n for (const [name, config] of Object.entries(graphTasks)) {\n const taskState = state.tasks[name];\n\n // Skip completed/running tasks\n if (taskState?.status === 'completed' || taskState?.status === 'running') continue;\n\n if (scope) {\n // If scope is provided, include if name is in scope\n if (scope.includes(name)) candidates.push(name);\n } else {\n // Otherwise, include only if autoDetectable\n if (config.inference?.autoDetectable) candidates.push(name);\n }\n }\n\n return candidates;\n}\n\n/**\n * Parse the LLM's raw response into structured InferredCompletion objects.\n * Handles edge cases: markdown fences, preamble text, malformed JSON.\n */\nfunction parseInferenceResponse(\n rawResponse: string,\n validNodes: string[],\n _threshold: number,\n): InferredCompletion[] {\n const validSet = new Set(validNodes);\n\n try {\n // Try to extract JSON from the response (handle markdown fences, preamble, etc.)\n const jsonStr = extractJson(rawResponse);\n if (!jsonStr) return [];\n\n const parsed = JSON.parse(jsonStr);\n\n // Must be an array\n if (!Array.isArray(parsed)) return [];\n\n const suggestions: InferredCompletion[] = [];\n\n for (const item of parsed) {\n // Validate shape\n if (!item || typeof item !== 'object') continue;\n if (typeof item.taskName !== 'string') continue;\n if (typeof item.confidence !== 'number') continue;\n\n // Must reference a valid node\n if (!validSet.has(item.taskName)) continue;\n\n // Clamp confidence to [0, 1]\n const confidence = Math.max(0, Math.min(1, item.confidence));\n\n suggestions.push({\n taskName: item.taskName,\n confidence,\n reasoning: typeof item.reasoning === 'string' ? item.reasoning : '',\n detectionMethod: 'llm-inferred',\n });\n }\n\n return suggestions;\n } catch {\n // JSON parse failed — return empty\n return [];\n }\n}\n\n/**\n * Extract JSON array from raw LLM text.\n * Handles: bare JSON, markdown-fenced JSON, preamble/postamble text.\n */\nfunction extractJson(text: string): string | null {\n if (!text || typeof text !== 'string') return null;\n\n const trimmed = text.trim();\n\n // Try 1: Markdown fence (```json ... ``` or ``` ... ```)\n const fenceMatch = trimmed.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) return fenceMatch[1].trim();\n\n // Try 2: Find first [ ... last ]\n const firstBracket = trimmed.indexOf('[');\n const lastBracket = trimmed.lastIndexOf(']');\n if (firstBracket !== -1 && lastBracket > firstBracket) {\n return trimmed.slice(firstBracket, lastBracket + 1);\n }\n\n // Try 3: Maybe it's bare JSON\n if (trimmed.startsWith('[')) return trimmed;\n\n return null;\n}\n","/**\n * Inference — Built-in Adapter Factories\n *\n * Ready-made adapter constructors for common LLM interfaces.\n * Each returns an InferenceAdapter.\n *\n * CLI adapters spawn a child process and capture stdout.\n * HTTP adapters POST to an endpoint and read the response.\n */\n\nimport { execFile } from 'node:child_process';\nimport type { InferenceAdapter } from './types.js';\n\n// ============================================================================\n// CLI Adapter — execute any local command\n// ============================================================================\n\nexport interface CliAdapterOptions {\n /** The command to execute (e.g., 'gh', 'ollama', 'llm') */\n command: string;\n /**\n * Arguments builder: receives the prompt and returns the args array.\n * The prompt is passed as an argument — NOT via stdin — unless you override.\n *\n * @example gh copilot: (prompt) => ['copilot', 'suggest', '-t', 'shell', prompt]\n * @example ollama: (prompt) => ['run', 'llama3', prompt]\n * @example llm cli: (prompt) => ['--model', 'gpt-4o', prompt]\n */\n args: (prompt: string) => string[];\n /** Max execution time in ms (default: 60000) */\n timeout?: number;\n /** Working directory for the child process */\n cwd?: string;\n /** Environment variables to pass to the child process */\n env?: Record<string, string>;\n /**\n * If true, pass the prompt via stdin instead of as a CLI argument.\n * Useful for long prompts that exceed shell argument limits.\n * Default: false\n */\n stdin?: boolean;\n}\n\n/**\n * Create an InferenceAdapter that executes a local CLI command.\n * The prompt is passed as a CLI argument (or via stdin if opts.stdin=true).\n * stdout is captured as the LLM response.\n *\n * @example\n * // GitHub Copilot CLI\n * const adapter = createCliAdapter({\n * command: 'gh',\n * args: (prompt) => ['copilot', 'suggest', '-t', 'shell', prompt],\n * });\n *\n * @example\n * // Ollama (local LLM)\n * const adapter = createCliAdapter({\n * command: 'ollama',\n * args: (prompt) => ['run', 'llama3', prompt],\n * });\n *\n * @example\n * // Simon Willison's llm CLI\n * const adapter = createCliAdapter({\n * command: 'llm',\n * args: (prompt) => ['--model', 'gpt-4o', prompt],\n * });\n *\n * @example\n * // Any script (stdin mode for long prompts)\n * const adapter = createCliAdapter({\n * command: 'python',\n * args: () => ['my_llm_script.py'],\n * stdin: true,\n * });\n */\nexport function createCliAdapter(opts: CliAdapterOptions): InferenceAdapter {\n const timeout = opts.timeout ?? 60_000;\n\n return {\n analyze: (prompt: string): Promise<string> => {\n return new Promise((resolve, reject) => {\n const args = opts.args(prompt);\n\n const child = execFile(\n opts.command,\n opts.stdin ? opts.args('') : args,\n {\n timeout,\n cwd: opts.cwd,\n env: opts.env ? { ...process.env, ...opts.env } : undefined,\n maxBuffer: 10 * 1024 * 1024, // 10MB\n },\n (error, stdout, stderr) => {\n if (error) {\n reject(new Error(\n `CLI adapter failed: ${opts.command} exited with ${error.code ?? 'error'}` +\n (stderr ? `\\nstderr: ${stderr.slice(0, 500)}` : '') +\n `\\n${error.message}`,\n ));\n } else {\n resolve(stdout);\n }\n },\n );\n\n // If stdin mode, write the prompt to the child's stdin\n if (opts.stdin && child.stdin) {\n child.stdin.write(prompt);\n child.stdin.end();\n }\n });\n },\n };\n}\n\n// ============================================================================\n// HTTP Adapter — POST to any endpoint\n// ============================================================================\n\nexport interface HttpAdapterOptions {\n /** The endpoint URL to POST to */\n url: string;\n /** Additional headers (Authorization, etc.) */\n headers?: Record<string, string>;\n /**\n * Build the request body from the prompt.\n * Default: `{ prompt }`\n */\n buildBody?: (prompt: string) => unknown;\n /**\n * Extract the response text from the parsed JSON response.\n * Default: `(json) => json.response ?? json.text ?? json.content ?? JSON.stringify(json)`\n */\n extractResponse?: (json: Record<string, unknown>) => string;\n /** Request timeout in ms (default: 60000) */\n timeout?: number;\n}\n\n/**\n * Create an InferenceAdapter that POSTs to an HTTP endpoint.\n *\n * @example\n * // Ollama HTTP API\n * const adapter = createHttpAdapter({\n * url: 'http://localhost:11434/api/generate',\n * buildBody: (prompt) => ({ model: 'llama3', prompt, stream: false }),\n * extractResponse: (json) => json.response as string,\n * });\n *\n * @example\n * // Custom API with auth\n * const adapter = createHttpAdapter({\n * url: 'https://my-llm.example.com/analyze',\n * headers: { Authorization: `Bearer ${process.env.API_KEY}` },\n * });\n */\nexport function createHttpAdapter(opts: HttpAdapterOptions): InferenceAdapter {\n const timeout = opts.timeout ?? 60_000;\n\n return {\n analyze: async (prompt: string): Promise<string> => {\n const body = opts.buildBody ? opts.buildBody(prompt) : { prompt };\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(opts.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.headers ?? {}),\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(`HTTP ${response.status}: ${text.slice(0, 500)}`);\n }\n\n const json = await response.json() as Record<string, unknown>;\n\n if (opts.extractResponse) {\n return opts.extractResponse(json);\n }\n\n // Default extraction: try common response fields\n if (typeof json.response === 'string') return json.response;\n if (typeof json.text === 'string') return json.text;\n if (typeof json.content === 'string') return json.content;\n return JSON.stringify(json);\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n"]}
@@ -1,229 +0,0 @@
1
- import { L as LiveGraph } from '../types-CHSdoAAA.cjs';
2
- import '../types-BBhqYGhE.cjs';
3
-
4
- /**
5
- * Inference — Types
6
- *
7
- * Type definitions for the LLM inference layer.
8
- * Pluggable adapter pattern: yaml-flow never calls an LLM directly.
9
- * The caller provides an InferenceAdapter that talks to their LLM of choice.
10
- */
11
-
12
- /**
13
- * The caller implements this to connect any LLM provider.
14
- * yaml-flow builds the prompt; the adapter sends it and returns the raw response.
15
- */
16
- interface InferenceAdapter {
17
- /** Send a prompt to an LLM and return the raw text response */
18
- analyze(prompt: string): Promise<string>;
19
- }
20
- /**
21
- * Optional inference metadata on a TaskConfig.
22
- * Tells the LLM what to look for when judging completion.
23
- */
24
- interface InferenceHints {
25
- /** Human-readable completion criteria (e.g., "Azure infrastructure setup completed") */
26
- criteria?: string;
27
- /** Keywords to help the LLM understand the domain */
28
- keywords?: string[];
29
- /** Suggested checks for verification (e.g., ["scan logs for 'Deployment Succeeded'"]) */
30
- suggestedChecks?: string[];
31
- /** Whether the LLM should attempt to auto-detect completion for this node */
32
- autoDetectable?: boolean;
33
- }
34
- interface InferenceOptions {
35
- /** Only return suggestions above this confidence threshold (default: 0.5) */
36
- threshold?: number;
37
- /** Only analyze these specific nodes (default: all non-completed autoDetectable nodes) */
38
- scope?: string[];
39
- /** Additional context to inject into the prompt (e.g., deployment logs, test output) */
40
- context?: string;
41
- /** Custom system prompt prefix (optional — uses a sensible default) */
42
- systemPrompt?: string;
43
- }
44
- interface InferenceResult {
45
- /** Individual suggestions for node completions */
46
- suggestions: InferredCompletion[];
47
- /** The prompt that was sent to the LLM (for audit/debug) */
48
- promptUsed: string;
49
- /** The raw text response from the LLM */
50
- rawResponse: string;
51
- /** Nodes that were analyzed */
52
- analyzedNodes: string[];
53
- }
54
- interface InferredCompletion {
55
- /** The task/node name */
56
- taskName: string;
57
- /** Confidence score from the LLM (0.0 - 1.0) */
58
- confidence: number;
59
- /** LLM's reasoning for why it thinks this node is complete */
60
- reasoning: string;
61
- /** Always 'llm-inferred' — distinguishes from manual/automated completions */
62
- detectionMethod: 'llm-inferred';
63
- }
64
- interface InferAndApplyResult {
65
- /** The updated LiveGraph with inferred completions applied */
66
- live: LiveGraph;
67
- /** The full inference result (including suggestions below threshold) */
68
- inference: InferenceResult;
69
- /** Only the suggestions that were actually applied (above threshold) */
70
- applied: InferredCompletion[];
71
- /** Suggestions that were skipped (below threshold) */
72
- skipped: InferredCompletion[];
73
- }
74
-
75
- /**
76
- * Inference — Core
77
- *
78
- * LLM inference layer for continuous-event-graph.
79
- * Pluggable adapter pattern: yaml-flow builds the prompt and parses the
80
- * response; the caller provides the LLM via an InferenceAdapter.
81
- *
82
- * Core pattern:
83
- * buildInferencePrompt(live) → prompt string (pure, sync)
84
- * inferCompletions(live, adapter, opts) → InferenceResult (async, calls LLM)
85
- * applyInferences(live, result, thresh) → LiveGraph (pure, sync)
86
- * inferAndApply(live, adapter, opts) → InferAndApplyResult (async, convenience)
87
- */
88
-
89
- /**
90
- * Build an LLM prompt from the current LiveGraph state.
91
- * Includes only nodes that are:
92
- * - Not yet completed
93
- * - Have `inference.autoDetectable` set to true (or are in scope)
94
- *
95
- * Pure function — no side effects.
96
- */
97
- declare function buildInferencePrompt(live: LiveGraph, options?: InferenceOptions): string;
98
- /**
99
- * Ask an LLM to analyze the current graph state and suggest completions.
100
- *
101
- * Builds a prompt from the LiveGraph, sends it through the adapter,
102
- * parses the structured response, and returns an InferenceResult.
103
- */
104
- declare function inferCompletions(live: LiveGraph, adapter: InferenceAdapter, options?: InferenceOptions): Promise<InferenceResult>;
105
- /**
106
- * Apply inferred completions to a LiveGraph.
107
- * Only applies suggestions at or above the given confidence threshold.
108
- *
109
- * Under the hood, this fires `task-started` + `task-completed` events
110
- * for each accepted suggestion (if the task isn't already running/completed).
111
- *
112
- * Pure function — returns a new LiveGraph.
113
- */
114
- declare function applyInferences(live: LiveGraph, result: InferenceResult, threshold?: number): LiveGraph;
115
- /**
116
- * Convenience: infer completions and apply them in one step.
117
- * Returns the updated LiveGraph + full audit trail of what was inferred vs applied.
118
- */
119
- declare function inferAndApply(live: LiveGraph, adapter: InferenceAdapter, options?: InferenceOptions): Promise<InferAndApplyResult>;
120
-
121
- /**
122
- * Inference — Built-in Adapter Factories
123
- *
124
- * Ready-made adapter constructors for common LLM interfaces.
125
- * Each returns an InferenceAdapter.
126
- *
127
- * CLI adapters spawn a child process and capture stdout.
128
- * HTTP adapters POST to an endpoint and read the response.
129
- */
130
-
131
- interface CliAdapterOptions {
132
- /** The command to execute (e.g., 'gh', 'ollama', 'llm') */
133
- command: string;
134
- /**
135
- * Arguments builder: receives the prompt and returns the args array.
136
- * The prompt is passed as an argument — NOT via stdin — unless you override.
137
- *
138
- * @example gh copilot: (prompt) => ['copilot', 'suggest', '-t', 'shell', prompt]
139
- * @example ollama: (prompt) => ['run', 'llama3', prompt]
140
- * @example llm cli: (prompt) => ['--model', 'gpt-4o', prompt]
141
- */
142
- args: (prompt: string) => string[];
143
- /** Max execution time in ms (default: 60000) */
144
- timeout?: number;
145
- /** Working directory for the child process */
146
- cwd?: string;
147
- /** Environment variables to pass to the child process */
148
- env?: Record<string, string>;
149
- /**
150
- * If true, pass the prompt via stdin instead of as a CLI argument.
151
- * Useful for long prompts that exceed shell argument limits.
152
- * Default: false
153
- */
154
- stdin?: boolean;
155
- }
156
- /**
157
- * Create an InferenceAdapter that executes a local CLI command.
158
- * The prompt is passed as a CLI argument (or via stdin if opts.stdin=true).
159
- * stdout is captured as the LLM response.
160
- *
161
- * @example
162
- * // GitHub Copilot CLI
163
- * const adapter = createCliAdapter({
164
- * command: 'gh',
165
- * args: (prompt) => ['copilot', 'suggest', '-t', 'shell', prompt],
166
- * });
167
- *
168
- * @example
169
- * // Ollama (local LLM)
170
- * const adapter = createCliAdapter({
171
- * command: 'ollama',
172
- * args: (prompt) => ['run', 'llama3', prompt],
173
- * });
174
- *
175
- * @example
176
- * // Simon Willison's llm CLI
177
- * const adapter = createCliAdapter({
178
- * command: 'llm',
179
- * args: (prompt) => ['--model', 'gpt-4o', prompt],
180
- * });
181
- *
182
- * @example
183
- * // Any script (stdin mode for long prompts)
184
- * const adapter = createCliAdapter({
185
- * command: 'python',
186
- * args: () => ['my_llm_script.py'],
187
- * stdin: true,
188
- * });
189
- */
190
- declare function createCliAdapter(opts: CliAdapterOptions): InferenceAdapter;
191
- interface HttpAdapterOptions {
192
- /** The endpoint URL to POST to */
193
- url: string;
194
- /** Additional headers (Authorization, etc.) */
195
- headers?: Record<string, string>;
196
- /**
197
- * Build the request body from the prompt.
198
- * Default: `{ prompt }`
199
- */
200
- buildBody?: (prompt: string) => unknown;
201
- /**
202
- * Extract the response text from the parsed JSON response.
203
- * Default: `(json) => json.response ?? json.text ?? json.content ?? JSON.stringify(json)`
204
- */
205
- extractResponse?: (json: Record<string, unknown>) => string;
206
- /** Request timeout in ms (default: 60000) */
207
- timeout?: number;
208
- }
209
- /**
210
- * Create an InferenceAdapter that POSTs to an HTTP endpoint.
211
- *
212
- * @example
213
- * // Ollama HTTP API
214
- * const adapter = createHttpAdapter({
215
- * url: 'http://localhost:11434/api/generate',
216
- * buildBody: (prompt) => ({ model: 'llama3', prompt, stream: false }),
217
- * extractResponse: (json) => json.response as string,
218
- * });
219
- *
220
- * @example
221
- * // Custom API with auth
222
- * const adapter = createHttpAdapter({
223
- * url: 'https://my-llm.example.com/analyze',
224
- * headers: { Authorization: `Bearer ${process.env.API_KEY}` },
225
- * });
226
- */
227
- declare function createHttpAdapter(opts: HttpAdapterOptions): InferenceAdapter;
228
-
229
- export { type CliAdapterOptions, type HttpAdapterOptions, type InferAndApplyResult, type InferenceAdapter, type InferenceHints, type InferenceOptions, type InferenceResult, type InferredCompletion, applyInferences, buildInferencePrompt, createCliAdapter, createHttpAdapter, inferAndApply, inferCompletions };