@fractal-solutions/qflow 1.0.83 → 2.0.0-canary.4

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 (114) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +21 -504
  3. package/MIGRATION.md +1130 -0
  4. package/README.md +1432 -823
  5. package/dist/agent/agent.d.ts +4 -22
  6. package/dist/agent/agent.js +4 -364
  7. package/dist/agent/base_agent.d.ts +8 -20
  8. package/dist/agent/base_agent.js +8 -205
  9. package/dist/agent/control_nodes.d.ts +61 -0
  10. package/dist/agent/control_nodes.js +164 -0
  11. package/dist/agent/engine.d.ts +45 -0
  12. package/dist/agent/engine.js +415 -0
  13. package/dist/agent/flow.d.ts +77 -0
  14. package/dist/agent/flow.js +148 -0
  15. package/dist/agent/index.d.ts +12 -0
  16. package/dist/agent/index.js +12 -0
  17. package/dist/agent/lpavrl_agent.d.ts +1 -2
  18. package/dist/agent/lpavrl_agent.js +2 -175
  19. package/dist/agent/ooda_agent.d.ts +1 -2
  20. package/dist/agent/ooda_agent.js +2 -164
  21. package/dist/agent/pema_agent.d.ts +1 -2
  22. package/dist/agent/pema_agent.js +2 -168
  23. package/dist/agent/raor_agent.d.ts +1 -2
  24. package/dist/agent/raor_agent.js +2 -161
  25. package/dist/agent/strategies.d.ts +126 -0
  26. package/dist/agent/strategies.js +159 -0
  27. package/dist/agent/tools.d.ts +1 -0
  28. package/dist/agent/tools.js +42 -24
  29. package/dist/approval.d.ts +42 -0
  30. package/dist/approval.js +86 -0
  31. package/dist/budget.d.ts +103 -0
  32. package/dist/budget.js +133 -0
  33. package/dist/bun_nodes.d.ts +119 -0
  34. package/dist/bun_nodes.js +331 -0
  35. package/dist/contracts.d.ts +30 -0
  36. package/dist/contracts.js +103 -0
  37. package/dist/durable.d.ts +278 -0
  38. package/dist/durable.js +730 -0
  39. package/dist/eval.d.ts +165 -0
  40. package/dist/eval.js +263 -0
  41. package/dist/graph.d.ts +157 -0
  42. package/dist/graph.js +330 -0
  43. package/dist/llm/index.d.ts +359 -0
  44. package/dist/llm/index.js +924 -0
  45. package/dist/logger.js +7 -3
  46. package/dist/mcp/client.d.ts +55 -0
  47. package/dist/mcp/client.js +145 -0
  48. package/dist/mcp/index.d.ts +2 -0
  49. package/dist/mcp/index.js +2 -0
  50. package/dist/mcp/server.d.ts +106 -0
  51. package/dist/mcp/server.js +154 -0
  52. package/dist/mcp/stdio.d.ts +2 -0
  53. package/dist/mcp/stdio.js +3 -0
  54. package/dist/memory.d.ts +101 -0
  55. package/dist/memory.js +217 -0
  56. package/dist/nodes/browser_control.js +5 -4
  57. package/dist/nodes/data_extractor.js +2 -1
  58. package/dist/nodes/data_validation.d.ts +3 -3
  59. package/dist/nodes/data_validation.js +19 -5
  60. package/dist/nodes/database.d.ts +2 -1
  61. package/dist/nodes/database.js +71 -58
  62. package/dist/nodes/gis.js +1 -1
  63. package/dist/nodes/git.d.ts +1 -1
  64. package/dist/nodes/git.js +65 -51
  65. package/dist/nodes/github.d.ts +1 -0
  66. package/dist/nodes/hardware_interaction.d.ts +2 -4
  67. package/dist/nodes/hardware_interaction.js +4 -3
  68. package/dist/nodes/http.d.ts +1 -7
  69. package/dist/nodes/http.js +46 -33
  70. package/dist/nodes/image_gallery.js +45 -45
  71. package/dist/nodes/index.d.ts +8 -0
  72. package/dist/nodes/index.js +8 -0
  73. package/dist/nodes/interactive_webview.d.ts +1 -2
  74. package/dist/nodes/interactive_webview.js +217 -216
  75. package/dist/nodes/multimedia_processing.js +1 -1
  76. package/dist/nodes/navigator.d.ts +7 -0
  77. package/dist/nodes/navigator.js +48 -8
  78. package/dist/nodes/pdf_processor.js +2 -1
  79. package/dist/nodes/remote_execution.js +2 -2
  80. package/dist/nodes/s3.d.ts +1 -0
  81. package/dist/nodes/scheduler.js +2 -2
  82. package/dist/nodes/search.d.ts +1 -1
  83. package/dist/nodes/search.js +3 -2
  84. package/dist/nodes/speech_synthesis.js +2 -1
  85. package/dist/nodes/spreadsheet.d.ts +1 -7
  86. package/dist/nodes/spreadsheet.js +2 -1
  87. package/dist/nodes/streaming_llm.d.ts +51 -0
  88. package/dist/nodes/streaming_llm.js +120 -0
  89. package/dist/nodes/webhook.d.ts +1 -5
  90. package/dist/nodes/webhook.js +106 -93
  91. package/dist/nodes/websockets.js +5 -3
  92. package/dist/nodes/webview.js +3 -2
  93. package/dist/optional.d.ts +32 -0
  94. package/dist/optional.js +61 -0
  95. package/dist/qflow.d.ts +25 -14
  96. package/dist/qflow.js +140 -49
  97. package/dist/schedule.d.ts +41 -0
  98. package/dist/schedule.js +149 -0
  99. package/dist/side_effects.d.ts +50 -0
  100. package/dist/side_effects.js +94 -0
  101. package/dist/streaming.d.ts +35 -0
  102. package/dist/streaming.js +199 -0
  103. package/dist/testing.d.ts +47 -0
  104. package/dist/testing.js +130 -0
  105. package/dist/tool_spec.d.ts +76 -0
  106. package/dist/tool_spec.js +321 -0
  107. package/dist/trace.d.ts +28 -0
  108. package/dist/trace.js +190 -0
  109. package/dist/util.d.ts +57 -0
  110. package/dist/util.js +122 -0
  111. package/package.json +153 -67
  112. package/qflow.config.js +18 -18
  113. package/scripts/postinstall.js +50 -0
  114. package/scripts/verify-package.js +114 -0
package/MIGRATION.md ADDED
@@ -0,0 +1,1130 @@
1
+ # Migrating to qflow 2.0
2
+
3
+ > Applies to `2.0.0-canary.4`. Earlier canaries introduced the provider-neutral
4
+ > node families; this canary closes the production gaps around approval,
5
+ > scheduling, replay, budgets, versioning and memory.
6
+ >
7
+ > This guide is written to be read in order the first time, then used as a
8
+ > lookup table afterwards. Every section follows the same shape: **what changed
9
+ > and why**, **1-2-3 steps to migrate**, **what each option means**, and
10
+ > **what can go wrong**.
11
+
12
+ ---
13
+
14
+ ## How to use this guide
15
+
16
+ Migration is a loop, not a single commit:
17
+
18
+ 1. **Change the foundation first** — runtime, install, and imports (sections 2-3).
19
+ 2. **Fix the seams** — lifecycle signatures, flow options, agents and streaming
20
+ (sections 4-7). This is where most 1.x code needs a small edit.
21
+ 3. **Adopt the 2.0 behaviour deliberately** — durability, replay, approval,
22
+ scheduling, budgets, memory and traces (sections 8-17). These are additive:
23
+ nothing here is required for a simple flow to keep working.
24
+
25
+ If you are starting a new project, skip the "before" snippets and read sections
26
+ 8-15 as the recommended architecture.
27
+
28
+ ### Which path is yours?
29
+
30
+ | You are coming from | Read | Expected work |
31
+ | --- | --- | --- |
32
+ | 1.x, ordinary flows and nodes | 2 → 3 → 4 → 5 → 16 | Small import and signature changes |
33
+ | 1.x with agents | 2 → 3 → 4 → 6 → 7 | Keep positional constructors; optionally switch to the options object |
34
+ | 1.x with `DurableFlow` | Add 8 → 9 → 10 → 11 → 12 | New run statuses and checkpointer methods; old `resume` calls still work |
35
+ | 2.0 canary.1/.2 | Add 7 → 17 | Trace format and optional-dependency changes |
36
+ | 2.0 canary.3 | Add 9 → 15 | Gap closures; no existing import breaks |
37
+ | A new 2.0 project | 2 → 3 → 8 → 15 → 17 | Build on durable runs, replay and traces from day one |
38
+
39
+ ---
40
+
41
+ ## Contents
42
+
43
+ - [1. Compatibility at a glance](#1-compatibility-at-a-glance)
44
+ - [2. Runtime: Bun only](#2-runtime-bun-only)
45
+ - [3. Imports: one package, many subpaths](#3-imports-one-package-many-subpaths)
46
+ - [4. Async lifecycle: the observer argument](#4-async-lifecycle-the-observer-argument)
47
+ - [5. Flow options](#5-flow-options)
48
+ - [6. Agents](#6-agents)
49
+ - [7. Streaming and provider-neutral LLM](#7-streaming-and-provider-neutral-llm)
50
+ - [8. Durable runs: the contract you build on](#8-durable-runs-the-contract-you-build-on)
51
+ - [9. Side effects: replay and worker leases](#9-side-effects-replay-and-worker-leases)
52
+ - [10. Flow versioning](#10-flow-versioning)
53
+ - [11. Durable human approval](#11-durable-human-approval)
54
+ - [12. Durable scheduling](#12-durable-scheduling)
55
+ - [13. Deterministic LLM replay and caching](#13-deterministic-llm-replay-and-caching)
56
+ - [14. Budget guardrails](#14-budget-guardrails)
57
+ - [15. Multi-tenant memory](#15-multi-tenant-memory)
58
+ - [16. Optional dependencies](#16-optional-dependencies)
59
+ - [17. Traces and evaluation](#17-traces-and-evaluation)
60
+ - [18. Other 2.0 node families](#18-other-20-node-families)
61
+ - [19. Migration checklist](#19-migration-checklist)
62
+ - [20. Error-code reference](#20-error-code-reference)
63
+ - [21. Troubleshooting](#21-troubleshooting)
64
+
65
+ ---
66
+
67
+ ## 1. Compatibility at a glance
68
+
69
+ **What changed:** 2.0 is a deliberate breaking release, but the break is narrow.
70
+ The core abstractions and every built-in node import still exist. What changed
71
+ is the runtime, the import paths, and a few *new* behaviours around durability.
72
+
73
+ | 1.x API | 2.0 status | Action |
74
+ | --- | --- | --- |
75
+ | `Node`, `Flow`, `BatchNode`, `BatchFlow` | Unchanged | None |
76
+ | `AsyncNode`, `AsyncFlow`, async batch variants | Unchanged, plus an optional 3rd/4th `observer` argument | None, or adopt `observer.emit()` |
77
+ | `new Flow(start)` / `new AsyncFlow(start)` | Unchanged, optional 2nd options argument | None, or add guards |
78
+ | `node.setParams()`, `node.next()` | Unchanged | None |
79
+ | Vendor LLM nodes (`OpenAILLMNode`, …) | Still exported | Keep them, or move to `LLMNode` |
80
+ | Agent classes (`AgentNode`, `RAORAgent`, …) | Still exported, now engine-backed | Keep positional constructor, or move to options object |
81
+ | `DurableFlow`, `SQLiteCheckpointer` | Enhanced, not replaced | Read sections 8-12 |
82
+ | `recordFlow()` snapshots | Normalized into one trace format | Read section 17 |
83
+ | Node.js runtime | Removed | Move to Bun |
84
+
85
+ **Why it changed:** qflow's growth is in Bun-native execution (`bun:sqlite`,
86
+ `Bun.spawn`, Bun streaming `fetch`) and agent orchestration. Supporting two
87
+ runtimes would freeze those APIs at their lowest common denominator. The
88
+ breaking change is the price of making durable, observable agents a first-class
89
+ feature instead of an example.
90
+
91
+ ---
92
+
93
+ ## 2. Runtime: Bun only
94
+
95
+ ### What changed and why
96
+
97
+ 2.0 calls Bun APIs directly. There is no Node.js compatibility shim, no
98
+ `node:` fallback for storage, and no plan to add one. This keeps the durable
99
+ checkpointer, process nodes and streaming nodes small and fast.
100
+
101
+ ### 1-2-3 steps
102
+
103
+ 1. Install Bun (the project is developed against Bun 1.4.x) and use it for
104
+ scripts, tests and production.
105
+ 2. Replace package-manager and runner commands:
106
+
107
+ ```bash
108
+ # before
109
+ npm install @fractal-solutions/qflow
110
+ npm test
111
+
112
+ # after
113
+ bun add @fractal-solutions/qflow
114
+ bun test tests
115
+ bun run build
116
+ ```
117
+
118
+ 3. Check for Node-only assumptions in your own code: CommonJS `require()`,
119
+ `fs` calls inside async nodes, or a `package.json` without `"type": "module"`.
120
+ qflow itself is ESM-only.
121
+
122
+ ### What to expect
123
+
124
+ | Symptom | Cause | Fix |
125
+ | --- | --- | --- |
126
+ | `Bun is not defined` | Running under Node | Run with `bun` |
127
+ | `Cannot find package 'bun:sqlite'` | Bundler or Node target | Build for Bun; mark `bun:*` external |
128
+ | Import errors for `fs`/`path` | Old deep imports | Use the documented subpaths (section 3) |
129
+
130
+ `Bun.env` is a convenient replacement for `process.env`, and works in Bun.
131
+ Keep using `process.env` if your deployment tooling expects it.
132
+
133
+ ---
134
+
135
+ ## 3. Imports: one package, many subpaths
136
+
137
+ ### What changed and why
138
+
139
+ qflow stays **one npm package**, but it is no longer one giant entry point.
140
+ Each subpath is a small module with its own dependencies. This keeps the base
141
+ install light and means importing a flow never loads Playwright, xlsx, ssh2 or
142
+ a browser webview.
143
+
144
+ ### 1-2-3 steps
145
+
146
+ 1. Replace bare deep paths (for example
147
+ `@fractal-solutions/qflow/src/nodes/...`) with a public subpath.
148
+ 2. Pick the narrowest subpath that contains what you need; `/nodes` is the
149
+ broad catalog, the specific subpaths are the focused toolboxes.
150
+ 3. Run your tests with `bun test tests` — any missed import fails immediately.
151
+
152
+ ```js
153
+ // before (1.x, conceptual)
154
+ import { DurableFlow } from '@fractal-solutions/qflow/dist/durable';
155
+ import { LLMNode } from '@fractal-solutions/qflow/src/nodes/llm';
156
+
157
+ // after (2.0)
158
+ import { DurableFlow } from '@fractal-solutions/qflow/durable';
159
+ import { LLMNode } from '@fractal-solutions/qflow/llm';
160
+ ```
161
+
162
+ ### Subpath reference
163
+
164
+ | Import | Contains | Use it when |
165
+ | --- | --- | --- |
166
+ | `@fractal-solutions/qflow` | `Node`, `Flow`, `AsyncNode`, `AsyncFlow`, batch variants | Writing core flows |
167
+ | `@fractal-solutions/qflow/nodes` | The whole built-in node catalog, including the 2.0 families | You want one catalog import |
168
+ | `@fractal-solutions/qflow/agent` | `AgentEngine`, strategies, legacy agents, control nodes | Building agents |
169
+ | `@fractal-solutions/qflow/mcp` | `QFlowMCPServer`, `MCPClientNode` | Exposing or calling MCP tools |
170
+ | `@fractal-solutions/qflow/streaming` | `streamChatCompletions()`, streaming event names | Low-level streaming |
171
+ | `@fractal-solutions/qflow/llm` | `LLMNode`, adapters, `llm:*` event names | Calling models |
172
+ | `@fractal-solutions/qflow/tool-spec` | `ToolSpec`, `ToolRegistry`, `generateToolDocs()` | Sharing tool definitions |
173
+ | `@fractal-solutions/qflow/contracts` | `StateContract`, `defineState()` | Validating `shared` |
174
+ | `@fractal-solutions/qflow/side-effects` | `ReplaySafeNode`, `withReplaySafeSideEffect()`, side-effect errors | Safe external calls |
175
+ | `@fractal-solutions/qflow/graph` | `FanOutNode`, `FanInNode`, map/reduce/join/branch/cycle nodes | Routing data |
176
+ | `@fractal-solutions/qflow/eval` | `AssertNode`, `ScoreNode`, `CompareNode`, `ReplayNode` | Regression suites |
177
+ | `@fractal-solutions/qflow/bun` | `BunSpawnNode`, `SQLiteQueryNode`, `FileWatchNode`, stream nodes | Local Bun-native work |
178
+ | `@fractal-solutions/qflow/durable` | `SQLiteCheckpointer`, `DurableFlow`, `createRunTrace()`, plus approval/schedule/budget helpers and durable errors | Long-lived runs |
179
+ | `@fractal-solutions/qflow/approval` | `WaitForApprovalNode`, `resolveApprovalId()` | Human decisions |
180
+ | `@fractal-solutions/qflow/schedule` | `ScheduleNode`, `nextCronTime()` | Time-based suspension |
181
+ | `@fractal-solutions/qflow/budget` | `BudgetTracker`, `BudgetNode`, `BudgetExceededError` | Cost/latency limits |
182
+ | `@fractal-solutions/qflow/memory` | `MemoryStore`, `InMemoryMemoryStore`, `SQLiteMemoryStore`, `MemoryStoreNode` | Reusable recall |
183
+ | `@fractal-solutions/qflow/testing` | `MockNode`, `MockLLMNode`, `recordFlow()` | Tests and traces |
184
+ | `@fractal-solutions/qflow/trace` | `normalizeTrace()`, `serializeTrace()`, `writeTraceFile()` | Trace export |
185
+ | `@fractal-solutions/qflow/optional` | `OPTIONAL_DEPENDENCIES`, `loadOptional()` | Diagnosing optional packages |
186
+ | `@fractal-solutions/qflow/logger` | `log`, `setLogLevel`, `LogLevel` | Logging control |
187
+
188
+ **Gotcha:** deep imports into `src/` or `dist/` are not part of the public API.
189
+ They bypass the export map and will break on the next release. The four new
190
+ gap-closure modules (`approval`, `schedule`, `budget`, `memory`) are also
191
+ re-exported from `/nodes`, and the durable helpers from `/durable`, so you can
192
+ choose whichever import style fits your project.
193
+
194
+ ---
195
+
196
+ ## 4. Async lifecycle: the observer argument
197
+
198
+ ### What changed and why
199
+
200
+ Async lifecycle methods gained one **optional** final argument, the flow
201
+ observer. It lets any node emit events without knowing which flow owns it.
202
+ That is what makes streaming, approval requests, budget checks and replay
203
+ hits visible in one trace.
204
+
205
+ ### 1-2-3 steps
206
+
207
+ 1. If your method accepts fewer arguments, do nothing — it still works.
208
+ 2. If you want events, add the third argument and call `observer.emit?.()`.
209
+ 3. Subscribe on the flow with `flow.on(name, handler)` or `flow.onAny(handler)`.
210
+
211
+ ```js
212
+ import { AsyncFlow, AsyncNode } from '@fractal-solutions/qflow';
213
+
214
+ class ChargeNode extends AsyncNode {
215
+ async prepAsync(shared, observer) {
216
+ observer.emit?.('charge:prepared', { orderId: shared.orderId });
217
+ return shared.order;
218
+ }
219
+
220
+ async execAsync(prepRes, shared, observer) {
221
+ observer.emit?.('charge:start', { amount: prepRes.amount });
222
+ return { charged: true };
223
+ }
224
+
225
+ async postAsync(shared, prepRes, execRes, observer) {
226
+ shared.charge = execRes;
227
+ observer.emit?.('charge:done', execRes);
228
+ return 'default';
229
+ }
230
+ }
231
+
232
+ const flow = new AsyncFlow(new ChargeNode());
233
+ flow.on('charge:start', payload => console.log(payload));
234
+ flow.onAny(({ event, payload, nested }) => console.log(event, nested));
235
+ await flow.runAsync({ orderId: 'ord-1', order: { amount: 42 } });
236
+ ```
237
+
238
+ ### Lifecycle signature reference
239
+
240
+ | Method | Arguments | Returns | Notes |
241
+ | --- | --- | --- | --- |
242
+ | `prepAsync` | `(shared, observer)` | `Promise<prepRes>` | `observer` includes `emit`, `runId`, `signal`, `checkpointer`, `workerId`, `leaseMs` inside `DurableFlow` |
243
+ | `execAsync` | `(prepRes, shared, observer)` | `Promise<execRes>` | Retry happens in `_exec`; keep `execAsync` side-effect-aware |
244
+ | `postAsync` | `(shared, prepRes, execRes, observer)` | `Promise<action>` | Action chooses the successor via `node.next(target, action)` |
245
+
246
+ `AsyncFlow.on('*')` and `AsyncFlow.onAny()` receive **every** event, including
247
+ node lifecycle, custom events and new `approval:*`, `budget:*`, `memory:*`,
248
+ `llm:*` and `flow:version_*` events. Events from nested flows are forwarded with
249
+ `nested: true` and `parentFlowId`, so one listener can follow the whole tree.
250
+
251
+ ---
252
+
253
+ ## 5. Flow options
254
+
255
+ ### What changed and why
256
+
257
+ `Flow` and `AsyncFlow` accept an optional second argument. These are guardrails,
258
+ not required configuration. Loops and agents can otherwise run forever or hide
259
+ a failed node in a long trace.
260
+
261
+ ### 1-2-3 steps
262
+
263
+ 1. Start with `new AsyncFlow(startNode)` — existing code is valid.
264
+ 2. Add the guardrails that match your failure mode (`maxSteps` for loops,
265
+ `timeout` for slow I/O, `onError` for recovery).
266
+ 3. Assert on the events (`flow:end` with `status: 'failed'`) in tests.
267
+
268
+ ```js
269
+ const flow = new AsyncFlow(startNode, {
270
+ maxSteps: 100,
271
+ timeout: 30_000,
272
+ onError: recoveryNode,
273
+ });
274
+ ```
275
+
276
+ | Option | Type | Default | Allowed values | Meaning |
277
+ | --- | --- | --- | --- | --- |
278
+ | `maxSteps` | `number` | `Infinity` | Positive integer or `Infinity` | Maximum node visits before the flow fails; the primary loop guard |
279
+ | `timeout` | `number` (ms) | none | Positive integer | Total run deadline; expiry rejects with `TimeoutError` |
280
+ | `onError` | `Node` / `AsyncNode` | `null` | A node instance | Receives control when a node fails; `shared.error` is populated |
281
+
282
+ **Gotcha:** `maxSteps` counts *visits*, so a cycle that goes around twice with
283
+ three nodes uses six steps. Set it above the expected path length, not the
284
+ number of unique nodes.
285
+
286
+ ---
287
+
288
+ ## 6. Agents
289
+
290
+ ### What changed and why
291
+
292
+ All five agent classes (`AgentNode`, `RAORAgent`, `OODAAgent`, `LPAVRLAgent`,
293
+ `PEMAAgent`) remain available with their original positional constructors.
294
+ Internally they now share one `AgentEngine`, so a reasoning pattern is data
295
+ (a strategy) instead of a new class. That is what makes `asFlow()`, trace-driven
296
+ evaluation and custom patterns cheap.
297
+
298
+ ### 1-2-3 steps
299
+
300
+ 1. Keep your existing `new RAORAgent(llmNode, tools)` call if it works.
301
+ 2. For new code, use the options object so strategy and tool permissions are
302
+ explicit.
303
+ 3. If you need a new pattern, register a strategy instead of subclassing.
304
+
305
+ ```js
306
+ import { AgentNode, agentStrategies } from '@fractal-solutions/qflow/agent';
307
+
308
+ const agent = new AgentNode({
309
+ llmNode,
310
+ availableTools,
311
+ strategy: 'raor', // default | raor | ooda | lpavrl | pema | your id
312
+ requireFinishConfirmation: false, // true makes a second LLM call confirm completion
313
+ toolRegistry, // optional; takes precedence over availableTools
314
+ grantedCapabilities: ['read'],
315
+ grantedPermissions: ['public'],
316
+ });
317
+
318
+ agentStrategies.myPattern = {
319
+ id: 'myPattern',
320
+ label: 'My pattern',
321
+ strictParsing: false,
322
+ phases: [{ name: 'ACT', prompt: 'Choose a tool.', kind: 'action' }],
323
+ postPhases: [],
324
+ noToolCallsPrompt: () => 'Call a tool or finish.',
325
+ onToolError: errors => `Handle these errors: ${errors}`,
326
+ };
327
+ ```
328
+
329
+ | Option | Type | Default | Meaning |
330
+ | --- | --- | --- | --- |
331
+ | `llmNode` | `LLMNode`-compatible node | required | Produces the next reasoning message |
332
+ | `availableTools` | `ToolSpec[]` / node definitions | `[]` | Tools offered to the model when no registry is given |
333
+ | `toolRegistry` | `ToolRegistry` | `null` | Shared source of tools, permissions and idempotency |
334
+ | `strategy` | `string` | `'default'` | Strategy id; built-ins plus anything in `agentStrategies` |
335
+ | `requireFinishConfirmation` | `boolean` | strategy-dependent | Ask the model to confirm the final answer |
336
+ | `grantedCapabilities` / `grantedPermissions` | `string[]` | `[]` | Filters which registry tools the agent may see and call |
337
+
338
+ `agent.asFlow()` returns an `AsyncFlow` with one node per strategy phase and a
339
+ `graph` property (`{ nodes, edges }`). It is the bridge to the eval and visual
340
+ authoring stories in sections 17-18.
341
+
342
+ ---
343
+
344
+ ## 7. Streaming and provider-neutral LLM
345
+
346
+ ### What changed and why
347
+
348
+ The old `StreamingLLMNode` still works with OpenAI-compatible endpoints. 2.0
349
+ adds `LLMNode` with a pluggable adapter registry, capability negotiation and a
350
+ normalized result, so switching vendors does not rewrite prompt code.
351
+
352
+ ### 1-2-3 steps
353
+
354
+ 1. Replace a vendor node with `LLMNode` when you need more than one provider.
355
+ 2. Declare required capabilities (`stream`, `toolCalls`, `structuredOutput`,
356
+ `reasoning`) so failures happen before an API call.
357
+ 3. Listen to `llm:delta` for UI and to `llm:done` / `llm:usage` for accounting.
358
+
359
+ ```js
360
+ import { AsyncFlow } from '@fractal-solutions/qflow';
361
+ import { LLMNode } from '@fractal-solutions/qflow/llm';
362
+
363
+ const llm = new LLMNode({
364
+ provider: 'openai', // openai | anthropic | ollama | gemini | custom id | adapter object
365
+ model: 'gpt-4o-mini',
366
+ apiKey: Bun.env.OPENAI_API_KEY,
367
+ fallbackProviders: ['ollama'], // tried in order after retries are exhausted
368
+ maxRetries: 2,
369
+ pricing: { inputPerMillion: 0.15, outputPerMillion: 0.6 },
370
+ stream: true,
371
+ });
372
+
373
+ const flow = new AsyncFlow(llm);
374
+ flow.on('llm:delta', ({ delta }) => process.stdout.write(delta));
375
+ flow.on('llm:capability', ({ missing }) => console.warn('unsupported', missing));
376
+ const result = await flow.runAsync({ prompt: 'Summarize this release.' });
377
+ // result: { text, reasoning, toolCalls, usage: { prompt, completion, total, cost }, ... }
378
+ ```
379
+
380
+ | Option | Type | Default | Meaning |
381
+ | --- | --- | --- | --- |
382
+ | `provider` | `string` / adapter object | required unless `adapter` is set | Adapter id, or any object with `complete()`/optional `stream()` |
383
+ | `adapter` | object | `null` | Direct adapter instance, used for the first provider |
384
+ | `model` | `string` | adapter default | Model name sent to the provider |
385
+ | `fallbackProviders` | `string[]` | `[]` | Ordered backup providers |
386
+ | `maxRetries` | `number` | `1` | Attempts per provider |
387
+ | `capabilities` / `requireCapabilities` | `string[]` | `[]` | Capabilities that must be supported before calling |
388
+ | `stream` | `boolean` | `false` | Use `stream()` and emit `llm:delta` / `llm:reasoning` |
389
+ | `tools` | array | `null` | Tool schemas; implies the `toolCalls` capability |
390
+ | `responseFormat` | object | `null` | Structured-output request; implies `structuredOutput` |
391
+ | `pricing` | object / function | `null` | `inputPerMillion` / `outputPerMillion`, or `({provider,model,usage}) => cost` |
392
+ | `cache`, `cacheKey`, `cacheTtlMs`, `budget` | see sections 13-14 | disabled | Deterministic replay and spend limits |
393
+
394
+ Events: `llm:delta`, `llm:reasoning`, `llm:done`, `llm:retry`, `llm:fallback`,
395
+ `llm:negotiated`, `llm:capability`, `llm:usage`, `llm:tool_call`, and the new
396
+ `llm:cache_hit`.
397
+
398
+ **Gotcha:** `LLMNode` returns a normalized object. `AgentEngine` expects raw
399
+ completion text from its LLM; use an adapter node that returns `execRes.text`
400
+ when composing them, as the examples in `examples/v2/` do.
401
+
402
+ ---
403
+
404
+ ## 8. Durable runs: the contract you build on
405
+
406
+ ### What changed and why
407
+
408
+ `DurableFlow` still checkpoints every successful node and still resumes with
409
+ the same `runId`. 2.0 adds three more outcomes: a run can be **suspended** for
410
+ a human decision, **scheduled** for a future time, or **guarded by a flow
411
+ version**. Those states are persisted in SQLite, so they survive process
412
+ restarts and can be driven by an API or worker queue.
413
+
414
+ ### 1-2-3 steps
415
+
416
+ 1. Create one `SQLiteCheckpointer` per database file and share it across flow
417
+ instances (including after a restart).
418
+ 2. Start with `runDurable({ runId, shared })`; keep the returned `runId`.
419
+ 3. Inspect `status` instead of assuming every call completes; resume or act on
420
+ `suspended` / `scheduled`, and let real errors throw.
421
+
422
+ ```js
423
+ import { DurableFlow, SQLiteCheckpointer } from '@fractal-solutions/qflow/durable';
424
+
425
+ const checkpointer = new SQLiteCheckpointer('./runs.db', {
426
+ workerId: 'worker-1', // optional identity for side-effect leases
427
+ leaseMs: 60_000, // optional reservation lifetime
428
+ });
429
+ const flow = new DurableFlow(startNode, {
430
+ checkpointer,
431
+ name: 'checkout',
432
+ version: '1.0.0',
433
+ });
434
+
435
+ const outcome = await flow.runDurable({ runId: 'order-1', shared: { orderId: 'ord-1' } });
436
+ if (outcome.status === 'suspended') {
437
+ // a human decision is recorded in SQLite; see section 11
438
+ } else if (outcome.status === 'scheduled') {
439
+ // a due time is stored; see section 12
440
+ }
441
+
442
+ // After a crash, or after an approval/decision:
443
+ await flow.runDurable({ runId: 'order-1', resume: true });
444
+ ```
445
+
446
+ ### `runDurable()` parameters
447
+
448
+ | Parameter | Type | Default | Meaning |
449
+ | --- | --- | --- | --- |
450
+ | `shared` | object | `{}` | Initial shared state; ignored on `resume` (saved state wins) |
451
+ | `runId` | `string` | random UUID | Stable run identity; you must keep it to resume |
452
+ | `resume` | `boolean` | `false` | Load saved state, check the version, and re-enter the waiting node |
453
+ | `signal` | `AbortSignal` | `undefined` | Checked at node boundaries; passed to nodes via the observer |
454
+ | `observer` | object | `{}` | Extra event handler(s); an existing `on*` handler is added automatically |
455
+
456
+ ### `runDurable()` result
457
+
458
+ | Field | Type | Meaning |
459
+ | --- | --- | --- |
460
+ | `runId` | `string` | The run you passed or generated |
461
+ | `status` | `'completed' \| 'suspended' \| 'scheduled'` | Final persisted state; failures throw |
462
+ | `result` | any | Last node's exec result, or `null` when suspended/scheduled |
463
+ | `shared` | object | Current shared state, including decisions and recorded reservations |
464
+ | `steps` | `number` | Node visits committed so far |
465
+ | `resumed` | `boolean` | Whether this call used `resume: true` |
466
+ | `approvalId` / `dueAt` | `string` / `number` | Only on `suspended` / `scheduled` |
467
+
468
+ ### Checkpointer methods you can call from outside a flow
469
+
470
+ | Method | Arguments | Returns | Use |
471
+ | --- | --- | --- | --- |
472
+ | `listRuns()` | none | `string[]` | Audit run IDs |
473
+ | `loadRun(runId)` | `string` | run record incl. `status`, `step`, `flowVersion`, `dueAt` | Inspect a run |
474
+ | `listCheckpoints(runId)` | `string` | checkpoint records | Debug or feed an eval suite |
475
+ | `listApprovals(runId, {status})` | `string`, options | approval records | Build a review queue |
476
+ | `listScheduledRuns({before})` | options | `{runId, flowName, flowVersion, dueAt, step}[]` | Find due runs to resume |
477
+ | `loadSideEffect(runId, operationId)` | strings | reservation record | Audit external calls |
478
+ | `exportRunTrace(runId, options)` | string, options | viewer-ready trace | Export to JSON |
479
+
480
+ **Gotcha:** `DurableFlow.runAsync(shared, observer)` still returns only the
481
+ last result. It starts a *new* durable run each time; use `runDurable()` when
482
+ the run id matters.
483
+
484
+ ---
485
+
486
+ ## 9. Side effects: replay and worker leases
487
+
488
+ ### What changed and why
489
+
490
+ The original reservation rule was: completed effects replay, unfinished ones
491
+ are uncertain. That prevented a retry from charging twice, but two workers
492
+ could still race to *start* the same operation. 2.0 adds a lease and an
493
+ identity: reservation is now an atomic `INSERT OR IGNORE` that records which
494
+ worker owns the operation and when the claim expires. A second live worker gets
495
+ `QFLOW_SIDE_EFFECT_CLAIMED` instead of executing.
496
+
497
+ ### 1-2-3 steps
498
+
499
+ 1. Give every external effect a stable `operationId` template, for example
500
+ `'{{orderId}}'`. It is prefixed with the kind at runtime: `charge:ord-1`.
501
+ 2. Give each worker a distinct `workerId` (hostname, pod name, queue worker id)
502
+ and choose a `leaseMs` longer than the effect's worst-case duration.
503
+ 3. Treat `SideEffectUncertainError` as "requires human/operator decision",
504
+ and `SideEffectClaimedError` as "someone else owns this right now".
505
+
506
+ ```js
507
+ import { DurableFlow, SQLiteCheckpointer } from '@fractal-solutions/qflow/durable';
508
+ import { ReplaySafeNode, SideEffectClaimedError, SideEffectUncertainError } from '@fractal-solutions/qflow/side-effects';
509
+
510
+ const charge = new ReplaySafeNode({
511
+ operationId: '{{orderId}}',
512
+ kind: 'charge',
513
+ execute: async ({ input }) => paymentApi.charge(input),
514
+ });
515
+
516
+ const checkpointer = new SQLiteCheckpointer('./runs.db', { workerId: 'worker-1', leaseMs: 60_000 });
517
+ const flow = new DurableFlow(charge, { checkpointer });
518
+ try {
519
+ await flow.runDurable({ runId: 'order-charge-1', shared: { orderId: 'ord-1', input: { amount: 42 } } });
520
+ } catch (error) {
521
+ if (error instanceof SideEffectClaimedError) {
522
+ // Another worker has the lease; retry later or let it finish.
523
+ } else if (error instanceof SideEffectUncertainError) {
524
+ // The provider may have committed. Reconcile before retrying.
525
+ } else {
526
+ throw error;
527
+ }
528
+ }
529
+ await flow.runDurable({ runId: 'order-charge-1', resume: true }); // replays the recorded result
530
+ ```
531
+
532
+ ### Options reference
533
+
534
+ | Option | Where | Type | Default | Meaning |
535
+ | --- | --- | --- | --- | --- |
536
+ | `operationId` | node params / constructor | `string` template, function, `true` | `true` | Stable key for one external call. `{{key}}` reads `shared`/`params`; `true` hashes params+shared. No `kind:` prefix in the template. |
537
+ | `kind` | constructor | `string` | `'side_effect'` | Namespace prefix and audit label |
538
+ | `onPending` | constructor / params | `'error' \| 'retry' \| 'return-null'` | `'error'` | What to do with an unfinished reservation. `retry` only applies to `failed` rows. |
539
+ | `workerId` | checkpointer, flow or node | `string` | generated per checkpointer | Owner written on the reservation |
540
+ | `leaseMs` | checkpointer, flow or node | `number` (ms) | `60_000` | How long the claim prevents another worker from taking over |
541
+ | `execute` | constructor | `async (args) => any` | required | The external call; called only when this worker owns the operation |
542
+
543
+ | Error | Code | Meaning | Safe response |
544
+ | --- | --- | --- | --- |
545
+ | `SideEffectClaimedError` | `QFLOW_SIDE_EFFECT_CLAIMED` | Another worker holds a live lease | Wait, or check whether it finished |
546
+ | `SideEffectUncertainError` | `QFLOW_SIDE_EFFECT_UNCERTAIN` | A reservation exists with no committed result and no live claim | Reconcile with the provider; never blindly retry |
547
+
548
+ **Gotcha:** if a worker dies mid-call, its reservation stays `pending` until
549
+ someone decides. After an operator confirms the effect did **not** happen, call
550
+ `checkpointer.failSideEffect(runId, operationId)` and retry with
551
+ `onPending: 'retry'`. That is an explicit decision, not an automatic one.
552
+
553
+ `HttpRequestNode`, `GitNode`, `WebHookNode` and `DatabaseNode` also accept
554
+ `operationId` templates and go through the same reservation path.
555
+
556
+ ---
557
+
558
+ ## 10. Flow versioning
559
+
560
+ ### What changed and why
561
+
562
+ A resumed run can outlive the code that started it. Without a version check, a
563
+ changed graph can resume at a stale node index and silently skip work. 2.0
564
+ stores the flow version on the run and every checkpoint, then lets you choose
565
+ what a mismatch means.
566
+
567
+ ### 1-2-3 steps
568
+
569
+ 1. Set `version` on every `DurableFlow` that can be resumed (a semver string is
570
+ a good convention).
571
+ 2. Choose a policy: leave `abort` for strict environments, use `migrate` when
572
+ you can transform `shared`, and reserve `ignore` for genuinely compatible
573
+ changes.
574
+ 3. On `migrate`, write a small pure function that returns the new `shared`.
575
+
576
+ ```js
577
+ import { DurableFlow, FlowVersionMismatchError } from '@fractal-solutions/qflow/durable';
578
+
579
+ const flow = new DurableFlow(startNode, {
580
+ checkpointer,
581
+ version: '2.0.0',
582
+ onVersionMismatch: 'migrate',
583
+ migrate: ({ expected, actual, shared, checkpoints, runId }) => ({
584
+ ...shared,
585
+ customerTier: shared.plan ?? 'free', // old key → new key
586
+ }),
587
+ });
588
+ await flow.runDurable({ runId: 'long-lived-run', resume: true });
589
+ ```
590
+
591
+ | Option | Type | Default | Allowed values | Meaning |
592
+ | --- | --- | --- | --- | --- |
593
+ | `version` | `string` / `null` | `'1.0.0'` | Any stable identifier | Written to the run and checkpoints at start; compared on resume |
594
+ | `onVersionMismatch` | `string` | `'abort'` | `abort`, `migrate`, `ignore` | Policy when saved and current versions differ |
595
+ | `migrate` | `(context) => object \| null` | `null` | Pure function | Called only for `migrate`; returned object replaces `shared` |
596
+
597
+ Policy details:
598
+
599
+ | Policy | What happens | Use when |
600
+ | --- | --- | --- |
601
+ | `abort` | Throws `FlowVersionMismatchError` (`QFLOW_FLOW_VERSION_MISMATCH`) | Default; safest for money-moving flows |
602
+ | `migrate` | Calls `migrate()`, replaces `shared`, updates run + checkpoint versions, emits `flow:version_migrated` | You can transform state deterministically |
603
+ | `ignore` | Emits `flow:version_mismatch` with `policy: 'ignore'` and resumes | The change cannot affect in-flight runs |
604
+
605
+ **Gotcha:** if a saved node no longer exists, resume falls back to the saved
606
+ node *class name* and emits `flow:node_remapped`. Rename nodes deliberately;
607
+ check that event in tests when refactoring a graph.
608
+
609
+ ---
610
+
611
+ ## 11. Durable human approval
612
+
613
+ ### What changed and why
614
+
615
+ The old `HumanApprovalNode` asked a model or a callback inside the same process.
616
+ That cannot survive a restart, let alone a review queue. `WaitForApprovalNode`
617
+ writes a pending approval to SQLite and lets `DurableFlow` return
618
+ `status: 'suspended'`. A UI or webhook calls `approve()` / `reject()` later, and
619
+ resume re-enters the same node to read the decision.
620
+
621
+ ### 1-2-3 steps
622
+
623
+ 1. Put `WaitForApprovalNode` in the graph and give it a stable `approvalId`
624
+ template such as `'{{requestId}}'`.
625
+ 2. Run durably; when `status === 'suspended'`, show the record from
626
+ `checkpointer.listApprovals(runId, { status: 'pending' })` to a reviewer.
627
+ 3. Call `approve(runId, decision, approvalId)` or `reject(...)`, then resume the
628
+ same `runId`.
629
+
630
+ ```js
631
+ import { DurableFlow, SQLiteCheckpointer, WaitForApprovalNode } from '@fractal-solutions/qflow/durable';
632
+
633
+ const gate = new WaitForApprovalNode({
634
+ approvalId: '{{requestId}}',
635
+ prompt: 'Approve refund?',
636
+ });
637
+ gate.next(shipRefund, 'approve'); // register both actions separately
638
+ gate.next(cancelRefund, 'reject');
639
+
640
+ const checkpointer = new SQLiteCheckpointer('./runs.db');
641
+ const flow = new DurableFlow(gate, { checkpointer, version: '1.0.0' });
642
+
643
+ const pending = await flow.runDurable({
644
+ runId: 'refund-req-1',
645
+ shared: { requestId: 'req-1' },
646
+ });
647
+ // pending.status === 'suspended', pending.approvalId === 'approval:req-1'
648
+
649
+ await checkpointer.approve('refund-req-1', { answer: 'yes', by: 'alice' }, 'approval:req-1');
650
+ const finished = await flow.runDurable({ runId: 'refund-req-1', resume: true });
651
+ // finished.shared.approval = { approved: true, answer: 'yes', by: 'alice', ... }
652
+ ```
653
+
654
+ ### `WaitForApprovalNode` options
655
+
656
+ | Option | Type | Default | Meaning |
657
+ | --- | --- | --- | --- |
658
+ | `approvalId` | `string` template, function, `true` | `true` | Stable decision key. Templates use `{{sharedKey}}` and are prefixed with `approval:`; functions receive `{params, shared, prompt}` and are used verbatim. |
659
+ | `prompt` | `string` | `null` | Question shown to the reviewer; `params.prompt` and `shared[promptKey]` also work |
660
+ | `promptKey` | `string` | `'approvalPrompt'` | Shared-state key to read the prompt from |
661
+ | `resultKey` | `string` | `'approval'` | Shared key for the decision object |
662
+ | `approvalsKey` | `string` | `'approvals'` | Shared key for the `approvalId → decision` map |
663
+ | `metadata` | JSON-serializable object | `null` | Stored on the approval record (UI hints, amount, links) |
664
+
665
+ ### Checkpointer approval API
666
+
667
+ | Method | Returns | Meaning |
668
+ | --- | --- | --- |
669
+ | `requestApproval({runId, approvalId, prompt, metadata})` | approval record | Idempotent insert; existing records are returned unchanged |
670
+ | `getApproval(runId, approvalId)` | record / `null` | Fetch one decision |
671
+ | `listApprovals(runId, {status})` | records | `status`: `pending`, `approved`, `rejected` |
672
+ | `approve(runId, decision, approvalId?)` | record | Sets `status: 'approved'` and forces `decision.approved = true` unless explicitly `false` |
673
+ | `reject(runId, decision, approvalId?)` | record | Sets `status: 'rejected'` and `decision.approved = false` |
674
+
675
+ If `approvalId` is omitted on `approve`/`reject`, the **last pending** approval
676
+ for the run is used. With multiple gates, always pass the id.
677
+
678
+ Routing: with successors registered, the node takes `approve` unless
679
+ `approved === false` or `status === 'rejected'`, then `reject`. With no
680
+ successors it returns the decision object as the result.
681
+
682
+ Events: `approval:requested`, `approval:resolved`, `approval:pending` (on the
683
+ durable run). Error code on a direct node run: `QFLOW_APPROVAL_PENDING`.
684
+
685
+ **Gotcha:** this node needs a durable context. In a plain `AsyncFlow` it throws
686
+ because there is no `runId`/checkpointer — use `DurableFlow`, or the agent-level
687
+ `HumanApprovalNode` if you only need an in-process decision.
688
+
689
+ Full walkthrough: [durable human approval](documentation/tutorials/durable-approval.md).
690
+
691
+ ---
692
+
693
+ ## 12. Durable scheduling
694
+
695
+ ### What changed and why
696
+
697
+ `SchedulerNode` starts a process timer and needs a live worker. That is fine for
698
+ short delays but not for "remind this customer in three days". `ScheduleNode`
699
+ persists a due time and suspends the run. Any worker can then query
700
+ `listScheduledRuns()` and resume the runs that are due.
701
+
702
+ ### 1-2-3 steps
703
+
704
+ 1. Add `ScheduleNode` with `at`, `delayMs` or `cron` and run durably.
705
+ 2. Persist the `dueAt` returned by `runDurable`; a scheduler process polls
706
+ `checkpointer.listScheduledRuns({ before: Date.now() })`.
707
+ 3. Resume each due `runId` with `{ resume: true }`; the node re-checks the same
708
+ stored due time and continues.
709
+
710
+ ```js
711
+ import { DurableFlow, SQLiteCheckpointer, ScheduleNode, nextCronTime } from '@fractal-solutions/qflow/durable';
712
+
713
+ const wait = new ScheduleNode({ delayMs: 60_000 });
714
+ wait.next(sendReminder, 'due');
715
+ const flow = new DurableFlow(wait, { checkpointer });
716
+
717
+ const paused = await flow.runDurable({ runId: 'reminder-1', shared: {} });
718
+ // paused.status === 'scheduled', paused.dueAt === epoch ms
719
+
720
+ const due = checkpointer.listScheduledRuns({ before: Date.now() });
721
+ for (const run of due) {
722
+ await flow.runDurable({ runId: run.runId, resume: true });
723
+ }
724
+
725
+ // Cron uses standard 5-field syntax, with no optional dependency:
726
+ const next = nextCronTime('0 3 * * *', new Date()); // next 03:00 local time
727
+ ```
728
+
729
+ ### `ScheduleNode` options
730
+
731
+ | Option | Type | Default | Meaning |
732
+ | --- | --- | --- | --- |
733
+ | `at` | `Date`, ISO `string`, epoch `number` | `null` | Absolute due time. Saved into `shared[dueAtKey]` on first run. |
734
+ | `delayMs` | `number` (ms) | `null` | Relative due time, computed once when the node first runs |
735
+ | `cron` | `string` | `null` | Five fields: `minute hour day month weekday` (e.g. `'0 3 * * *'`) |
736
+ | `scheduleId` | `string` | generated | Stable id for the schedule; also stored in `shared[scheduleIdKey]` |
737
+ | `dueAtKey` | `string` | `'scheduledAt'` | Shared key holding the persisted due time |
738
+ | `scheduleIdKey` | `string` | `'scheduleId'` | Shared key holding the schedule id |
739
+ | `resultKey` | `string` | `'scheduleResult'` | Shared key for `{scheduleId, dueAt, firedAt}` |
740
+
741
+ Resolution order: `params.at` → constructor `at` → saved `shared[dueAtKey]`,
742
+ then `delayMs`, then `cron`. `params.now` (Date or epoch ms) overrides the
743
+ clock, which is useful in tests.
744
+
745
+ Cron syntax supports `*`, lists (`1,15`), ranges (`9-17`) and steps (`*/15`).
746
+ Weekday accepts `0` or `7` for Sunday. If both day-of-month and weekday are
747
+ restricted, a date matches either. `nextCronTime()` returns epoch ms.
748
+
749
+ **Gotcha:** once a due time is saved it wins over a fresh `cron` calculation on
750
+ re-entry. To compute the next occurrence after a scheduled node fires, delete
751
+ `shared[dueAtKey]` before visiting the node again, or start a new run for the
752
+ next slot.
753
+
754
+ Events: `schedule:waiting`, `schedule:pending`. Error code:
755
+ `QFLOW_SCHEDULE_PENDING`. Full walkthrough:
756
+ [durable scheduling](documentation/tutorials/durable-scheduling.md).
757
+
758
+ ---
759
+
760
+ ## 13. Deterministic LLM replay and caching
761
+
762
+ ### What changed and why
763
+
764
+ Model calls are the most expensive and least deterministic part of an agent
765
+ run. In a long-lived flow, replaying a checkpoint should not send the same
766
+ prompt again, and two workers should not pay twice for the same request. 2.0
767
+ adds a response cache with stable keys; a `llm:cache_hit` event makes replay
768
+ visible in traces.
769
+
770
+ ### 1-2-3 steps
771
+
772
+ 1. Add `cache: true` to `LLMNode` inside a `DurableFlow` (the checkpointer
773
+ becomes the cache store automatically), or pass your own
774
+ `{ get, set }` object.
775
+ 2. Leave `cacheKey` unset for a hash of the request, or set a template such as
776
+ `'{{tenant}}:{{prompt}}'` when you want humans to read/mutate keys.
777
+ 3. Set `cacheTtlMs` when the prompt depends on changing data, and listen for
778
+ `llm:cache_hit` in tests.
779
+
780
+ ```js
781
+ import { AsyncFlow } from '@fractal-solutions/qflow';
782
+ import { LLMNode, LLM_CACHE_HIT_EVENT } from '@fractal-solutions/qflow/llm';
783
+
784
+ const llm = new LLMNode({
785
+ provider: 'openai',
786
+ model: 'gpt-4o-mini',
787
+ cache: true, // or { get, set }
788
+ cacheKey: '{{tenant}}:{{prompt}}', // optional; default is a request hash
789
+ cacheTtlMs: 24 * 60 * 60 * 1000, // optional; null means no expiry
790
+ });
791
+ const flow = new AsyncFlow(llm);
792
+ flow.on(LLM_CACHE_HIT_EVENT, ({ key }) => console.log('replayed', key));
793
+ await flow.runAsync({ prompt: 'Summarize this release.', tenant: 'acme' });
794
+ ```
795
+
796
+ For a checkpointer-backed cache outside a flow, pass the checkpointer directly:
797
+
798
+ ```js
799
+ llm.setParams({ checkpointer, cache: true });
800
+ ```
801
+
802
+ ### Options reference
803
+
804
+ | Option | Type | Default | Meaning |
805
+ | --- | --- | --- | --- |
806
+ | `cache` | `true`, `{ get(key), set(key, value, ttlMs) }`, `null` | `null` | `true` uses the checkpointer's `cacheGet`/`cacheSet` in the `llm` namespace |
807
+ | `cacheKey` | `string` template, function `({request, shared}) => string`, `null` | request hash | Hash covers provider, model, messages/prompt, tools, response format, temperature and max tokens. `operationId` is a fallback template. |
808
+ | `cacheTtlMs` | `number` / `null` | `null` | Lifetime in ms for checkpointer entries; `null` never expires, `<= 0` expires immediately |
809
+ | `budget` | `BudgetTracker` | `null` | Recorded after a real completion, not after a cache hit |
810
+
811
+ Checkpointer cache methods: `cacheGet(namespace, key)`,
812
+ `cacheSet(namespace, key, value, ttlMs)`, `clearCache(namespace?)`. The LLM
813
+ namespace is `'llm'`.
814
+
815
+ **Gotcha:** a cached result is returned *before* capability negotiation and
816
+ budget accounting. That is intentional (a replay costs nothing), but it means a
817
+ cache key must fully identify the prompt, model, tools and output format. If
818
+ any of those change, use a different key or clear the namespace.
819
+
820
+ Full walkthrough: [deterministic LLM replay](documentation/tutorials/llm-deterministic-cache.md).
821
+
822
+ ---
823
+
824
+ ## 14. Budget guardrails
825
+
826
+ ### What changed and why
827
+
828
+ Agents can loop, escalate model size and quietly burn money. 2.0 provides a
829
+ `BudgetTracker` that accumulates real usage and a `BudgetNode` that turns a
830
+ limit into a graph edge (`continue` / `exceeded`) or a coded error.
831
+
832
+ ### 1-2-3 steps
833
+
834
+ 1. Create a `BudgetTracker` with cost, token, duration and step limits.
835
+ 2. Pass it to `LLMNode` via `budget` so every real completion is recorded, and
836
+ add a `BudgetNode` where you want a routing decision.
837
+ 3. Wire `exceeded` to a safe fallback (smaller model, human review, or a
838
+ refusal node).
839
+
840
+ ```js
841
+ import { AsyncFlow } from '@fractal-solutions/qflow';
842
+ import { BudgetTracker, BudgetNode, BudgetExceededError } from '@fractal-solutions/qflow/budget';
843
+ import { LLMNode } from '@fractal-solutions/qflow/llm';
844
+
845
+ const budget = new BudgetTracker({
846
+ maxCost: 0.50, // USD
847
+ maxTokens: 20_000, // prompt + completion
848
+ maxDurationMs: 60_000,
849
+ maxSteps: 50,
850
+ });
851
+
852
+ const llm = new LLMNode({ provider: 'openai', model: 'gpt-4o-mini', budget });
853
+ const guard = new BudgetNode({ tracker: budget, maxCost: 0.50 });
854
+ guard.next(llm, 'continue');
855
+ guard.next(stopNode, 'exceeded');
856
+
857
+ const result = await new AsyncFlow(guard).runAsync({ prompt: 'Draft the plan.' });
858
+ // if a tracker check fails with throwOnExceed, error.code === 'QFLOW_BUDGET_EXCEEDED'
859
+ ```
860
+
861
+ ### `BudgetTracker` options and methods
862
+
863
+ | Option | Type | Default | Meaning |
864
+ | --- | --- | --- | --- |
865
+ | `maxCost` | `number` | `Infinity` | Spend ceiling in the currency used by your pricing function |
866
+ | `maxTokens` | `number` | `Infinity` | Total token ceiling |
867
+ | `maxDurationMs` | `number` | `Infinity` | Wall-clock ceiling from `startedAt` |
868
+ | `maxSteps` | `number` | `Infinity` | Step ceiling; `LLMNode` supplies `shared.agentFlowSteps` |
869
+ | `startedAt` | `Date`, epoch `number` | now | Start of the duration window |
870
+
871
+ | Method | Meaning |
872
+ | --- | --- |
873
+ | `record(usage, cost)` | Add one call's usage (`total`/`total_tokens`, else prompt+completion) and cost |
874
+ | `snapshot({steps, now})` | `{cost, tokens, calls, steps, durationMs}` |
875
+ | `check(context)` | Snapshot plus limits, `reasons[]` and `exceeded` |
876
+ | `assertWithin(context)` | Throws `BudgetExceededError` with `reasons` and `snapshot` |
877
+ | `reset({startedAt})` | Zero counters and restart the clock |
878
+
879
+ ### `BudgetNode` options
880
+
881
+ | Option | Type | Default | Meaning |
882
+ | --- | --- | --- | --- |
883
+ | `maxCost`, `maxTokens`, `maxDurationMs`, `maxSteps` | `number` | `Infinity` | Limits; `params` and `shared[limitsKey]` can override them |
884
+ | `tracker` | `BudgetTracker` | `null` | Source of accumulated usage; without one the node reads `shared.llmCost` / `shared.llmUsage` |
885
+ | `limitsKey` | `string` | `'budget'` | Shared key holding a limits object |
886
+ | `outputKey` | `string` | `'budget'` | Shared key for the check result |
887
+ | `throwOnExceed` | `boolean` | `false` | Throw `BudgetExceededError` instead of routing to `exceeded` |
888
+
889
+ Events: `budget:check` (every check), `budget:exceeded` (only when crossed).
890
+ Full walkthrough: [budget guardrails](documentation/tutorials/budget-guardrails.md).
891
+
892
+ ---
893
+
894
+ ## 15. Multi-tenant memory
895
+
896
+ ### What changed and why
897
+
898
+ `MemoryNode` is a keyword store tied to one local file. 2.0 adds a store
899
+ interface with two implementations and a node wrapper, so each tenant,
900
+ project or agent run can own a store while the flow code stays identical.
901
+
902
+ ### 1-2-3 steps
903
+
904
+ 1. Create one store per tenant: `new SQLiteMemoryStore('./tenant-acme.db')`
905
+ for persistence, or `new InMemoryMemoryStore()` for tests.
906
+ 2. Put the store in `shared.memoryStore` (or pass it to the node constructor)
907
+ and use `MemoryStoreNode` with `operation: 'add'` / `'search'`.
908
+ 3. Dispose of SQLite stores with `close()` when a tenant is removed.
909
+
910
+ ```js
911
+ import { AsyncFlow } from '@fractal-solutions/qflow';
912
+ import { InMemoryMemoryStore, MemoryStoreNode } from '@fractal-solutions/qflow/memory';
913
+
914
+ const store = new InMemoryMemoryStore();
915
+ const add = new MemoryStoreNode({ operation: 'add' });
916
+ await new AsyncFlow(add).runAsync({
917
+ memoryStore: store,
918
+ memoryInput: { text: 'Refunds over $500 need approval', tags: ['policy'] },
919
+ });
920
+
921
+ const search = new MemoryStoreNode({ operation: 'search', limit: 3 });
922
+ const hits = await new AsyncFlow(search).runAsync({
923
+ memoryStore: store,
924
+ memoryInput: { query: 'refund approval', tags: ['policy'] },
925
+ });
926
+ // hits: [{ id, text, tags, metadata, createdAt, score }, ...]
927
+ ```
928
+
929
+ ### Store API
930
+
931
+ | Method | Arguments | Returns | Meaning |
932
+ | --- | --- | --- | --- |
933
+ | `add` | `{id?, text, tags?, metadata?}` | record | Upsert by id; `text` is required |
934
+ | `search` | `query, {limit?, tags?}` | scored records | Lexical overlap + tag bonus; higher score first |
935
+ | `get` | `id` | record / `null` | Fetch by id |
936
+ | `delete` | `id` | `boolean` | Remove by id |
937
+ | `list` | none | records | All records, oldest first |
938
+ | `clear` | none | `number` | Remove all and return the count |
939
+
940
+ `SQLiteMemoryStore(filename = ':memory:')` also has `close()`.
941
+ `InMemoryMemoryStore` is process-local and intentionally disposable.
942
+
943
+ ### `MemoryStoreNode` options
944
+
945
+ | Option | Type | Default | Meaning |
946
+ | --- | --- | --- | --- |
947
+ | `store` | `MemoryStore` | `null` | Explicit store; otherwise `shared.memoryStore`, or a new store is created and saved there |
948
+ | `operation` | `string` | `'add'` | `add`, `search`, `get`, `delete`, `list`, `clear` |
949
+ | `inputKey` | `string` | `'memoryInput'` | Shared key for the operation payload |
950
+ | `outputKey` | `string` | `'memoryResult'` | Shared key for the result |
951
+ | `storeKey` | `string` | `'memoryStore'` | Shared key used to find/create the store |
952
+ | `database` | `string` | `null` | If set, a new store uses `SQLiteMemoryStore(database)` |
953
+ | `limit` | `number` | `5` | Default search result limit |
954
+
955
+ A string payload is treated as `{ text: payload }`. Search reads
956
+ `query ?? text ?? ''`. Events: `memory:add` (`{id}`), `memory:search`
957
+ (`{count}`). Full walkthrough: [multi-tenant memory](documentation/tutorials/multi-tenant-memory.md).
958
+
959
+ ---
960
+
961
+ ## 16. Optional dependencies
962
+
963
+ ### What changed and why
964
+
965
+ Heavy packages (Playwright, webview-bun, xlsx, serialport, ssh2, simple-git,
966
+ ws, cheerio, ajv, node-cron, …) moved from `dependencies` to
967
+ `optionalDependencies`. Nothing loads them until the specific node action runs.
968
+ Importing the catalog is now cheap and CI no longer needs a browser to install.
969
+
970
+ ### 1-2-3 steps
971
+
972
+ 1. Install only the integrations you use:
973
+
974
+ ```bash
975
+ bun add --optional playwright
976
+ bun add --optional webview-bun
977
+ bun add --optional xlsx
978
+ ```
979
+
980
+ 2. Keep those declarations in `package.json` so lockfiles and CI stay stable.
981
+ 3. If a node throws `QFLOW_OPTIONAL_DEPENDENCY_MISSING`, run the exact command
982
+ printed in the error message.
983
+
984
+ `loadOptional(name)` in `@fractal-solutions/qflow/optional` is the guarded
985
+ loader. It throws an actionable error instead of a bare module-not-found. Use
986
+ `OPTIONAL_DEPENDENCIES` to see the full package map.
987
+
988
+ ---
989
+
990
+ ## 17. Traces and evaluation
991
+
992
+ ### What changed and why
993
+
994
+ `recordFlow()` used to produce a testing-specific shape. 2.0 normalizes flow
995
+ snapshots, recorded events and durable-run checkpoints into one trace format,
996
+ which is also what the browser viewer at `#trace` consumes and what the eval
997
+ nodes compare. One contract means a production trace can become a regression
998
+ test without translation.
999
+
1000
+ ### 1-2-3 steps
1001
+
1002
+ 1. Record events while the flow runs (there is no `observer` property on the
1003
+ recorder; pass `recorder.events` when exporting).
1004
+ 2. Write the trace JSON with Bun; the viewer is browser-only, so paste or
1005
+ upload the file there.
1006
+ 3. Feed the same JSON to `ReplayNode` / `createEvalSuite()` in CI.
1007
+
1008
+ ```js
1009
+ import { recordFlow } from '@fractal-solutions/qflow/testing';
1010
+ import { writeTraceFile, normalizeTrace } from '@fractal-solutions/qflow/trace';
1011
+ import { DurableFlow, createRunTrace } from '@fractal-solutions/qflow/durable';
1012
+
1013
+ const recorder = recordFlow(flow);
1014
+ await flow.runAsync(shared);
1015
+ await writeTraceFile(recorder.events, './trace.json');
1016
+
1017
+ // Durable runs already have checkpoints:
1018
+ const trace = createRunTrace(checkpointer, runId, {
1019
+ events: recorder.events,
1020
+ includeState: true, // optional; includes shared/params/execRes per checkpoint
1021
+ });
1022
+ await writeTraceFile(trace, './durable-trace.json');
1023
+ ```
1024
+
1025
+ | Function | Input | Output | Meaning |
1026
+ | --- | --- | --- | --- |
1027
+ | `normalizeTrace(value)` | recorded events or run record | normalized trace | One shape for viewer and eval |
1028
+ | `writeTraceFile(value, path)` | trace/events, file path | `Promise<string>` | JSON written via Bun |
1029
+ | `createRunTrace(checkpointer, runId, options)` | checkpointer, id, options | normalized trace | Rebuilds a trace from persisted rows |
1030
+ | `compareTraces(a, b)` | two traces | diff result | Ignores volatile ids/timings/stacks by default |
1031
+
1032
+ `AssertNode`, `ScoreNode`, `CompareNode` and `ReplayNode` live in `/eval`;
1033
+ events are `eval:assert`, `eval:score`, `eval:compare`, `eval:replay`.
1034
+
1035
+ ---
1036
+
1037
+ ## 18. Other 2.0 node families
1038
+
1039
+ These arrived in canary.3 and remain additive. Full examples are in
1040
+ [`examples/v2/`](examples/v2/README.md) and the
1041
+ [tutorial index](documentation/tutorials/README.md).
1042
+
1043
+ | Family | Import | What it gives you |
1044
+ | --- | --- | --- |
1045
+ | Provider-neutral LLM | `/llm` | Adapters, capabilities, retries, fallbacks, usage/cost |
1046
+ | Tool specs | `/tool-spec` | One tool definition for agents, MCP, LLM schemas and docs |
1047
+ | Replay-safe effects | `/side-effects` | Reservations and replay with coded errors and leases |
1048
+ | Dataflow | `/graph`, `/contracts` | Map/reduce/join/branch/cycle with state validation |
1049
+ | Agent control | `/agent` | Plan/critic/reflect/finish/approval as nodes; `asFlow()` |
1050
+ | Evaluation | `/eval` | Assert/score/compare/replay against normalized traces |
1051
+ | Bun-native | `/bun` | Process, SQLite, file-watch and Web Stream nodes |
1052
+
1053
+ ---
1054
+
1055
+ ## 19. Migration checklist
1056
+
1057
+ Print this, work top to bottom, and tick only what you have actually verified:
1058
+
1059
+ - [ ] All scripts, tests and deploys run with `bun`, not `node`/`npm`.
1060
+ - [ ] No imports from `src/`, `dist/` or another package deep path.
1061
+ - [ ] Async lifecycle methods either ignore `observer` or use `observer.emit?.()`.
1062
+ - [ ] Loops have `maxSteps`; slow I/O has a `timeout`; recovery has `onError`.
1063
+ - [ ] Agents use a registered strategy id; custom patterns are registered, not subclassed.
1064
+ - [ ] Every durable flow has a `version` and an explicit mismatch policy.
1065
+ - [ ] Every durable run has a caller-owned `runId` and code that checks `status`.
1066
+ - [ ] Every external side effect has a stable `operationId` and each worker a `workerId`.
1067
+ - [ ] Approval flows have a reviewer path (`listApprovals` → `approve`/`reject` → resume).
1068
+ - [ ] Scheduled flows have a poller (`listScheduledRuns` → resume) or an external trigger.
1069
+ - [ ] Expensive LLM calls use `cache` and a `BudgetTracker`.
1070
+ - [ ] Tenant data uses separate memory stores and stores are closed when removed.
1071
+ - [ ] Optional packages are installed explicitly and pinned in the lockfile.
1072
+ - [ ] A trace can be exported, viewed at `#trace`, and replayed in a test.
1073
+ - [ ] `bun test tests`, `bun run build` and `bun run examples:v2` are green.
1074
+
1075
+ ---
1076
+
1077
+ ## 20. Error-code reference
1078
+
1079
+ | Code | Class | Meaning |
1080
+ | --- | --- | --- |
1081
+ | `QFLOW_OPTIONAL_DEPENDENCY_MISSING` | — | An optional integration package is not installed |
1082
+ | `QFLOW_SIDE_EFFECT_UNCERTAIN` | `SideEffectUncertainError` | Reservation exists with no committed result |
1083
+ | `QFLOW_SIDE_EFFECT_CLAIMED` | `SideEffectClaimedError` | Another worker holds a live lease |
1084
+ | `QFLOW_APPROVAL_PENDING` | `ApprovalPendingError` | Approval node needs a decision |
1085
+ | `QFLOW_SCHEDULE_PENDING` | `SchedulePendingError` | Schedule node is not due yet |
1086
+ | `QFLOW_FLOW_VERSION_MISMATCH` | `FlowVersionMismatchError` | Resume targets a different flow version |
1087
+ | `QFLOW_BUDGET_EXCEEDED` | `BudgetExceededError` | A cost/token/duration/step limit was crossed |
1088
+ | `QFLOW_LLM_CAPABILITY_MISSING` | `Error` with code requested capability is unsupported |
1089
+
1090
+ ---
1091
+
1092
+ ## 21. Troubleshooting
1093
+
1094
+ **"My durable run says `suspended` and never continues."**
1095
+ That is the approval contract. List pending approvals, record a decision, then
1096
+ resume the *same* `runId`. Do not start a new run.
1097
+
1098
+ **"My scheduled run resumes but fires immediately."**
1099
+ The stored due time wins over a new `cron` value. Delete `shared[dueAtKey]` if
1100
+ you meant to schedule the next slot.
1101
+
1102
+ **"Two workers both tried to charge."**
1103
+ Give each worker a distinct `workerId` and make sure `leaseMs` exceeds the
1104
+ effect duration. The second worker should receive `QFLOW_SIDE_EFFECT_CLAIMED`.
1105
+
1106
+ **"Resume threw `QFLOW_FLOW_VERSION_MISMATCH`."**
1107
+ Either deploy the previous version, or set `onVersionMismatch: 'migrate'` with a
1108
+ pure migration function. `ignore` is only safe if the change cannot touch
1109
+ in-flight state.
1110
+
1111
+ **"An LLM replay hit an old prompt."**
1112
+ Cache keys are your responsibility when you use a template. Include every
1113
+ input that changes the answer (tenant, prompt, model, tool set) or clear the
1114
+ `llm` cache namespace.
1115
+
1116
+ **"Budget checks never fire."**
1117
+ `BudgetNode` reads `shared.llmCost` / `shared.llmUsage` unless you pass a
1118
+ `tracker`. Pass the same tracker to `LLMNode` and to the node, and check that
1119
+ your pricing function actually returns a cost.
1120
+
1121
+ **"Memory search returns nothing."**
1122
+ Search is lexical, not semantic: it filters by token overlap and tag bonus. Use
1123
+ words present in the stored text, or use `SemanticMemoryNode` (requires Ollama)
1124
+ for meaning-based recall.
1125
+
1126
+ ---
1127
+
1128
+ ## License
1129
+
1130
+ qflow 2.0 is MIT licensed, matching `package.json` and npm metadata.