@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.
- package/CHANGELOG.md +107 -0
- package/LICENSE +21 -504
- package/MIGRATION.md +1130 -0
- package/README.md +1432 -823
- package/dist/agent/agent.d.ts +4 -22
- package/dist/agent/agent.js +4 -364
- package/dist/agent/base_agent.d.ts +8 -20
- package/dist/agent/base_agent.js +8 -205
- package/dist/agent/control_nodes.d.ts +61 -0
- package/dist/agent/control_nodes.js +164 -0
- package/dist/agent/engine.d.ts +45 -0
- package/dist/agent/engine.js +415 -0
- package/dist/agent/flow.d.ts +77 -0
- package/dist/agent/flow.js +148 -0
- package/dist/agent/index.d.ts +12 -0
- package/dist/agent/index.js +12 -0
- package/dist/agent/lpavrl_agent.d.ts +1 -2
- package/dist/agent/lpavrl_agent.js +2 -175
- package/dist/agent/ooda_agent.d.ts +1 -2
- package/dist/agent/ooda_agent.js +2 -164
- package/dist/agent/pema_agent.d.ts +1 -2
- package/dist/agent/pema_agent.js +2 -168
- package/dist/agent/raor_agent.d.ts +1 -2
- package/dist/agent/raor_agent.js +2 -161
- package/dist/agent/strategies.d.ts +126 -0
- package/dist/agent/strategies.js +159 -0
- package/dist/agent/tools.d.ts +1 -0
- package/dist/agent/tools.js +42 -24
- package/dist/approval.d.ts +42 -0
- package/dist/approval.js +86 -0
- package/dist/budget.d.ts +103 -0
- package/dist/budget.js +133 -0
- package/dist/bun_nodes.d.ts +119 -0
- package/dist/bun_nodes.js +331 -0
- package/dist/contracts.d.ts +30 -0
- package/dist/contracts.js +103 -0
- package/dist/durable.d.ts +278 -0
- package/dist/durable.js +730 -0
- package/dist/eval.d.ts +165 -0
- package/dist/eval.js +263 -0
- package/dist/graph.d.ts +157 -0
- package/dist/graph.js +330 -0
- package/dist/llm/index.d.ts +359 -0
- package/dist/llm/index.js +924 -0
- package/dist/logger.js +7 -3
- package/dist/mcp/client.d.ts +55 -0
- package/dist/mcp/client.js +145 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +106 -0
- package/dist/mcp/server.js +154 -0
- package/dist/mcp/stdio.d.ts +2 -0
- package/dist/mcp/stdio.js +3 -0
- package/dist/memory.d.ts +101 -0
- package/dist/memory.js +217 -0
- package/dist/nodes/browser_control.js +5 -4
- package/dist/nodes/data_extractor.js +2 -1
- package/dist/nodes/data_validation.d.ts +3 -3
- package/dist/nodes/data_validation.js +19 -5
- package/dist/nodes/database.d.ts +2 -1
- package/dist/nodes/database.js +71 -58
- package/dist/nodes/gis.js +1 -1
- package/dist/nodes/git.d.ts +1 -1
- package/dist/nodes/git.js +65 -51
- package/dist/nodes/github.d.ts +1 -0
- package/dist/nodes/hardware_interaction.d.ts +2 -4
- package/dist/nodes/hardware_interaction.js +4 -3
- package/dist/nodes/http.d.ts +1 -7
- package/dist/nodes/http.js +46 -33
- package/dist/nodes/image_gallery.js +45 -45
- package/dist/nodes/index.d.ts +8 -0
- package/dist/nodes/index.js +8 -0
- package/dist/nodes/interactive_webview.d.ts +1 -2
- package/dist/nodes/interactive_webview.js +217 -216
- package/dist/nodes/multimedia_processing.js +1 -1
- package/dist/nodes/navigator.d.ts +7 -0
- package/dist/nodes/navigator.js +48 -8
- package/dist/nodes/pdf_processor.js +2 -1
- package/dist/nodes/remote_execution.js +2 -2
- package/dist/nodes/s3.d.ts +1 -0
- package/dist/nodes/scheduler.js +2 -2
- package/dist/nodes/search.d.ts +1 -1
- package/dist/nodes/search.js +3 -2
- package/dist/nodes/speech_synthesis.js +2 -1
- package/dist/nodes/spreadsheet.d.ts +1 -7
- package/dist/nodes/spreadsheet.js +2 -1
- package/dist/nodes/streaming_llm.d.ts +51 -0
- package/dist/nodes/streaming_llm.js +120 -0
- package/dist/nodes/webhook.d.ts +1 -5
- package/dist/nodes/webhook.js +106 -93
- package/dist/nodes/websockets.js +5 -3
- package/dist/nodes/webview.js +3 -2
- package/dist/optional.d.ts +32 -0
- package/dist/optional.js +61 -0
- package/dist/qflow.d.ts +25 -14
- package/dist/qflow.js +140 -49
- package/dist/schedule.d.ts +41 -0
- package/dist/schedule.js +149 -0
- package/dist/side_effects.d.ts +50 -0
- package/dist/side_effects.js +94 -0
- package/dist/streaming.d.ts +35 -0
- package/dist/streaming.js +199 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +130 -0
- package/dist/tool_spec.d.ts +76 -0
- package/dist/tool_spec.js +321 -0
- package/dist/trace.d.ts +28 -0
- package/dist/trace.js +190 -0
- package/dist/util.d.ts +57 -0
- package/dist/util.js +122 -0
- package/package.json +153 -67
- package/qflow.config.js +18 -18
- package/scripts/postinstall.js +50 -0
- package/scripts/verify-package.js +114 -0
package/dist/durable.js
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { AsyncFlow } from './qflow.js';
|
|
3
|
+
import { normalizeTrace, serializeTrace } from './trace.js';
|
|
4
|
+
import { ApprovalPendingError, FlowVersionMismatchError, SchedulePendingError, SideEffectClaimedError, SideEffectUncertainError, } from './util.js';
|
|
5
|
+
function parseJson(value, fallback = null) {
|
|
6
|
+
if (value == null)
|
|
7
|
+
return fallback;
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(value);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return fallback;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function stringify(value) {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.stringify(value ?? null);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return JSON.stringify(String(value));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function abortError() {
|
|
24
|
+
const error = new Error('Run aborted by AbortSignal.');
|
|
25
|
+
error.name = 'AbortError';
|
|
26
|
+
return error;
|
|
27
|
+
}
|
|
28
|
+
/** Build a viewer-ready trace from persisted run/checkpoint rows. */
|
|
29
|
+
function buildRunTrace(run, checkpoints, { events = [], includeState = false } = {}) {
|
|
30
|
+
const publicCheckpoints = checkpoints.map(checkpoint => includeState
|
|
31
|
+
? checkpoint
|
|
32
|
+
: {
|
|
33
|
+
runId: checkpoint.runId,
|
|
34
|
+
step: checkpoint.step,
|
|
35
|
+
nodeIndex: checkpoint.nodeIndex,
|
|
36
|
+
nodeClass: checkpoint.nodeClass,
|
|
37
|
+
action: checkpoint.action,
|
|
38
|
+
nextNodeIndex: checkpoint.nextNodeIndex,
|
|
39
|
+
createdAt: checkpoint.createdAt,
|
|
40
|
+
});
|
|
41
|
+
const observedCheckpointSteps = new Set(events
|
|
42
|
+
.map(event => event?.step ?? event?.payload?.step)
|
|
43
|
+
.filter((step, index) => step != null && events[index]?.event === 'checkpoint:saved'));
|
|
44
|
+
const syntheticCheckpointEvents = checkpoints
|
|
45
|
+
.filter(checkpoint => !observedCheckpointSteps.has(checkpoint.step))
|
|
46
|
+
.map(checkpoint => ({
|
|
47
|
+
event: 'checkpoint:saved',
|
|
48
|
+
runId: checkpoint.runId,
|
|
49
|
+
step: checkpoint.step,
|
|
50
|
+
nodeClass: checkpoint.nodeClass,
|
|
51
|
+
action: checkpoint.action,
|
|
52
|
+
nextNodeIndex: checkpoint.nextNodeIndex,
|
|
53
|
+
createdAt: checkpoint.createdAt,
|
|
54
|
+
...(includeState ? { shared: checkpoint.shared, params: checkpoint.params, execRes: checkpoint.execRes } : {}),
|
|
55
|
+
}));
|
|
56
|
+
const traceEvents = [
|
|
57
|
+
{ event: 'run:start', runId: run.runId, flowName: run.flowName, flowVersion: run.flowVersion ?? null, status: 'running', createdAt: run.createdAt },
|
|
58
|
+
...events,
|
|
59
|
+
...syntheticCheckpointEvents,
|
|
60
|
+
{ event: 'run:end', runId: run.runId, status: run.status, step: run.step, result: run.result, error: run.error, updatedAt: run.updatedAt },
|
|
61
|
+
];
|
|
62
|
+
return normalizeTrace({
|
|
63
|
+
runId: run.runId,
|
|
64
|
+
flowName: run.flowName,
|
|
65
|
+
status: run.status,
|
|
66
|
+
steps: run.step,
|
|
67
|
+
startedAt: run.createdAt,
|
|
68
|
+
endedAt: run.updatedAt,
|
|
69
|
+
events: traceEvents,
|
|
70
|
+
checkpoints: publicCheckpoints,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** SQLite-backed run state. One checkpointer can back many DurableFlow instances. */
|
|
74
|
+
export class SQLiteCheckpointer {
|
|
75
|
+
constructor(filename = ':memory:', { workerId = `worker-${crypto.randomUUID().slice(0, 8)}`, leaseMs = 60_000 } = {}) {
|
|
76
|
+
this.db = new Database(filename);
|
|
77
|
+
this.workerId = workerId;
|
|
78
|
+
this.leaseMs = leaseMs;
|
|
79
|
+
this.db.exec('PRAGMA journal_mode = WAL;');
|
|
80
|
+
this.db.exec(`
|
|
81
|
+
CREATE TABLE IF NOT EXISTS qflow_runs (
|
|
82
|
+
run_id TEXT PRIMARY KEY,
|
|
83
|
+
flow_name TEXT NOT NULL,
|
|
84
|
+
status TEXT NOT NULL,
|
|
85
|
+
step INTEGER NOT NULL DEFAULT 0,
|
|
86
|
+
cursor_node_index INTEGER,
|
|
87
|
+
shared_json TEXT NOT NULL,
|
|
88
|
+
params_json TEXT NOT NULL,
|
|
89
|
+
result_json TEXT,
|
|
90
|
+
error_json TEXT,
|
|
91
|
+
created_at TEXT NOT NULL,
|
|
92
|
+
updated_at TEXT NOT NULL
|
|
93
|
+
);
|
|
94
|
+
CREATE TABLE IF NOT EXISTS qflow_checkpoints (
|
|
95
|
+
run_id TEXT NOT NULL,
|
|
96
|
+
step INTEGER NOT NULL,
|
|
97
|
+
node_index INTEGER,
|
|
98
|
+
node_class TEXT NOT NULL,
|
|
99
|
+
action TEXT,
|
|
100
|
+
next_node_index INTEGER,
|
|
101
|
+
shared_json TEXT NOT NULL,
|
|
102
|
+
params_json TEXT NOT NULL,
|
|
103
|
+
exec_res_json TEXT,
|
|
104
|
+
created_at TEXT NOT NULL,
|
|
105
|
+
PRIMARY KEY (run_id, step)
|
|
106
|
+
);
|
|
107
|
+
CREATE TABLE IF NOT EXISTS qflow_side_effects (
|
|
108
|
+
run_id TEXT NOT NULL,
|
|
109
|
+
operation_id TEXT NOT NULL,
|
|
110
|
+
kind TEXT,
|
|
111
|
+
status TEXT NOT NULL,
|
|
112
|
+
result_json TEXT,
|
|
113
|
+
error_json TEXT,
|
|
114
|
+
created_at TEXT NOT NULL,
|
|
115
|
+
updated_at TEXT NOT NULL,
|
|
116
|
+
PRIMARY KEY (run_id, operation_id)
|
|
117
|
+
);
|
|
118
|
+
CREATE TABLE IF NOT EXISTS qflow_approvals (
|
|
119
|
+
run_id TEXT NOT NULL,
|
|
120
|
+
approval_id TEXT NOT NULL,
|
|
121
|
+
prompt TEXT,
|
|
122
|
+
status TEXT NOT NULL,
|
|
123
|
+
decision_json TEXT,
|
|
124
|
+
metadata_json TEXT,
|
|
125
|
+
created_at TEXT NOT NULL,
|
|
126
|
+
updated_at TEXT NOT NULL,
|
|
127
|
+
PRIMARY KEY (run_id, approval_id)
|
|
128
|
+
);
|
|
129
|
+
CREATE TABLE IF NOT EXISTS qflow_cache (
|
|
130
|
+
namespace TEXT NOT NULL,
|
|
131
|
+
cache_key TEXT NOT NULL,
|
|
132
|
+
value_json TEXT NOT NULL,
|
|
133
|
+
expires_at INTEGER,
|
|
134
|
+
created_at TEXT NOT NULL,
|
|
135
|
+
PRIMARY KEY (namespace, cache_key)
|
|
136
|
+
);
|
|
137
|
+
`);
|
|
138
|
+
// Databases created by earlier canary builds lack the 2.0.0-canary.4 columns.
|
|
139
|
+
this.#ensureColumn('qflow_runs', 'flow_version', 'TEXT');
|
|
140
|
+
this.#ensureColumn('qflow_runs', 'due_at', 'INTEGER');
|
|
141
|
+
this.#ensureColumn('qflow_checkpoints', 'flow_version', 'TEXT');
|
|
142
|
+
this.#ensureColumn('qflow_side_effects', 'claimed_by', 'TEXT');
|
|
143
|
+
this.#ensureColumn('qflow_side_effects', 'lease_expires_at', 'INTEGER');
|
|
144
|
+
}
|
|
145
|
+
#ensureColumn(table, column, definition) {
|
|
146
|
+
const columns = this.db.prepare(`PRAGMA table_info(${table})`).all().map(row => row.name);
|
|
147
|
+
if (!columns.includes(column))
|
|
148
|
+
this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
|
|
149
|
+
}
|
|
150
|
+
startRun({ runId, flowName, shared, params, version = null }) {
|
|
151
|
+
const now = new Date().toISOString();
|
|
152
|
+
this.db.prepare(`
|
|
153
|
+
INSERT INTO qflow_runs (
|
|
154
|
+
run_id, flow_name, status, step, cursor_node_index, flow_version, due_at,
|
|
155
|
+
shared_json, params_json, result_json, error_json, created_at, updated_at
|
|
156
|
+
) VALUES (?, ?, 'running', 0, NULL, ?, NULL, ?, ?, NULL, NULL, ?, ?)
|
|
157
|
+
`).run(runId, flowName, version, stringify(shared), stringify(params), now, now);
|
|
158
|
+
}
|
|
159
|
+
saveCheckpoint(entry) {
|
|
160
|
+
const now = new Date().toISOString();
|
|
161
|
+
const write = this.db.transaction(() => {
|
|
162
|
+
this.db.prepare(`
|
|
163
|
+
INSERT INTO qflow_checkpoints (
|
|
164
|
+
run_id, step, node_index, node_class, action, next_node_index, flow_version,
|
|
165
|
+
shared_json, params_json, exec_res_json, created_at
|
|
166
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
167
|
+
ON CONFLICT(run_id, step) DO UPDATE SET
|
|
168
|
+
node_index = excluded.node_index,
|
|
169
|
+
node_class = excluded.node_class,
|
|
170
|
+
action = excluded.action,
|
|
171
|
+
next_node_index = excluded.next_node_index,
|
|
172
|
+
flow_version = excluded.flow_version,
|
|
173
|
+
shared_json = excluded.shared_json,
|
|
174
|
+
params_json = excluded.params_json,
|
|
175
|
+
exec_res_json = excluded.exec_res_json,
|
|
176
|
+
created_at = excluded.created_at
|
|
177
|
+
`).run(entry.runId, entry.step, entry.nodeIndex, entry.nodeClass,
|
|
178
|
+
// Actions are normally action names, but standalone eval/dataflow nodes
|
|
179
|
+
// return their exec result. Persist those as JSON instead of handing an
|
|
180
|
+
// object to bun:sqlite.
|
|
181
|
+
typeof entry.action === 'object' && entry.action !== null
|
|
182
|
+
? stringify(entry.action)
|
|
183
|
+
: entry.action ?? null, entry.nextNodeIndex, entry.flowVersion ?? null, stringify(entry.shared), stringify(entry.params), stringify(entry.execRes), now);
|
|
184
|
+
this.db.prepare(`
|
|
185
|
+
INSERT INTO qflow_runs (
|
|
186
|
+
run_id, flow_name, status, step, cursor_node_index,
|
|
187
|
+
shared_json, params_json, result_json, error_json, created_at, updated_at
|
|
188
|
+
) VALUES (?, ?, 'running', ?, ?, ?, ?, NULL, NULL, ?, ?)
|
|
189
|
+
ON CONFLICT(run_id) DO UPDATE SET
|
|
190
|
+
status = 'running',
|
|
191
|
+
step = excluded.step,
|
|
192
|
+
cursor_node_index = excluded.cursor_node_index,
|
|
193
|
+
shared_json = excluded.shared_json,
|
|
194
|
+
params_json = excluded.params_json,
|
|
195
|
+
result_json = NULL,
|
|
196
|
+
error_json = NULL,
|
|
197
|
+
updated_at = excluded.updated_at
|
|
198
|
+
`).run(entry.runId, entry.flowName, entry.step, entry.nextNodeIndex, stringify(entry.shared), stringify(entry.params), now, now);
|
|
199
|
+
});
|
|
200
|
+
write();
|
|
201
|
+
}
|
|
202
|
+
updateRunStatus(runId, status, { step, shared, result = null, error = null } = {}) {
|
|
203
|
+
this.db.prepare(`
|
|
204
|
+
UPDATE qflow_runs
|
|
205
|
+
SET status = ?, step = ?, shared_json = ?, result_json = ?, error_json = ?, updated_at = ?
|
|
206
|
+
WHERE run_id = ?
|
|
207
|
+
`).run(status, step ?? 0, stringify(shared), stringify(result), error ? stringify({ message: error.message, stack: error.stack }) : null, new Date().toISOString(), runId);
|
|
208
|
+
}
|
|
209
|
+
loadRun(runId) {
|
|
210
|
+
const row = this.db.prepare('SELECT * FROM qflow_runs WHERE run_id = ?').get(runId);
|
|
211
|
+
if (!row)
|
|
212
|
+
return null;
|
|
213
|
+
return {
|
|
214
|
+
runId: row.run_id,
|
|
215
|
+
flowName: row.flow_name,
|
|
216
|
+
status: row.status,
|
|
217
|
+
step: row.step,
|
|
218
|
+
cursorNodeIndex: row.cursor_node_index,
|
|
219
|
+
flowVersion: row.flow_version ?? null,
|
|
220
|
+
dueAt: row.due_at ?? null,
|
|
221
|
+
shared: parseJson(row.shared_json, {}),
|
|
222
|
+
params: parseJson(row.params_json, {}),
|
|
223
|
+
result: parseJson(row.result_json),
|
|
224
|
+
error: parseJson(row.error_json),
|
|
225
|
+
createdAt: row.created_at,
|
|
226
|
+
updatedAt: row.updated_at,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
listRuns() {
|
|
230
|
+
return this.db.prepare('SELECT run_id FROM qflow_runs ORDER BY created_at').all()
|
|
231
|
+
.map(row => row.run_id);
|
|
232
|
+
}
|
|
233
|
+
/** Runs suspended by SchedulePendingError, ordered by due time. */
|
|
234
|
+
listScheduledRuns({ before = Infinity } = {}) {
|
|
235
|
+
return this.db.prepare(`
|
|
236
|
+
SELECT run_id, flow_name, flow_version, due_at, step
|
|
237
|
+
FROM qflow_runs
|
|
238
|
+
WHERE status = 'scheduled' AND due_at IS NOT NULL AND due_at <= ?
|
|
239
|
+
ORDER BY due_at
|
|
240
|
+
`).all(before).map(row => ({
|
|
241
|
+
runId: row.run_id,
|
|
242
|
+
flowName: row.flow_name,
|
|
243
|
+
flowVersion: row.flow_version ?? null,
|
|
244
|
+
dueAt: row.due_at,
|
|
245
|
+
step: row.step,
|
|
246
|
+
}));
|
|
247
|
+
}
|
|
248
|
+
setRunDueAt(runId, dueAt) {
|
|
249
|
+
this.db.prepare('UPDATE qflow_runs SET due_at = ?, updated_at = ? WHERE run_id = ?')
|
|
250
|
+
.run(dueAt ?? null, new Date().toISOString(), runId);
|
|
251
|
+
return dueAt;
|
|
252
|
+
}
|
|
253
|
+
setFlowVersion(runId, version) {
|
|
254
|
+
const now = new Date().toISOString();
|
|
255
|
+
const write = this.db.transaction(() => {
|
|
256
|
+
this.db.prepare('UPDATE qflow_runs SET flow_version = ?, updated_at = ? WHERE run_id = ?')
|
|
257
|
+
.run(version, now, runId);
|
|
258
|
+
this.db.prepare('UPDATE qflow_checkpoints SET flow_version = ? WHERE run_id = ?')
|
|
259
|
+
.run(version, runId);
|
|
260
|
+
});
|
|
261
|
+
write();
|
|
262
|
+
return version;
|
|
263
|
+
}
|
|
264
|
+
listCheckpoints(runId) {
|
|
265
|
+
return this.db.prepare(`
|
|
266
|
+
SELECT * FROM qflow_checkpoints WHERE run_id = ? ORDER BY step
|
|
267
|
+
`).all(runId).map(row => ({
|
|
268
|
+
runId: row.run_id,
|
|
269
|
+
step: row.step,
|
|
270
|
+
nodeIndex: row.node_index,
|
|
271
|
+
nodeClass: row.node_class,
|
|
272
|
+
action: row.action,
|
|
273
|
+
nextNodeIndex: row.next_node_index,
|
|
274
|
+
flowVersion: row.flow_version ?? null,
|
|
275
|
+
shared: parseJson(row.shared_json, {}),
|
|
276
|
+
params: parseJson(row.params_json, {}),
|
|
277
|
+
execRes: parseJson(row.exec_res_json),
|
|
278
|
+
createdAt: row.created_at,
|
|
279
|
+
}));
|
|
280
|
+
}
|
|
281
|
+
// --- Durable human approvals -------------------------------------------------
|
|
282
|
+
requestApproval({ runId, approvalId, prompt = null, metadata = null }) {
|
|
283
|
+
if (!runId || !approvalId)
|
|
284
|
+
throw new Error('requestApproval requires runId and approvalId.');
|
|
285
|
+
const existing = this.getApproval(runId, approvalId);
|
|
286
|
+
if (existing)
|
|
287
|
+
return existing;
|
|
288
|
+
const now = new Date().toISOString();
|
|
289
|
+
this.db.prepare(`
|
|
290
|
+
INSERT INTO qflow_approvals (
|
|
291
|
+
run_id, approval_id, prompt, status, decision_json, metadata_json, created_at, updated_at
|
|
292
|
+
) VALUES (?, ?, ?, 'pending', NULL, ?, ?, ?)
|
|
293
|
+
`).run(runId, approvalId, prompt ?? null, stringify(metadata), now, now);
|
|
294
|
+
return this.getApproval(runId, approvalId);
|
|
295
|
+
}
|
|
296
|
+
getApproval(runId, approvalId) {
|
|
297
|
+
const row = this.db.prepare(`
|
|
298
|
+
SELECT * FROM qflow_approvals WHERE run_id = ? AND approval_id = ?
|
|
299
|
+
`).get(runId, approvalId);
|
|
300
|
+
return row ? this.#approvalRecord(row) : null;
|
|
301
|
+
}
|
|
302
|
+
listApprovals(runId, { status = null } = {}) {
|
|
303
|
+
const rows = status
|
|
304
|
+
? this.db.prepare(`SELECT * FROM qflow_approvals WHERE run_id = ? AND status = ? ORDER BY created_at`).all(runId, status)
|
|
305
|
+
: this.db.prepare(`SELECT * FROM qflow_approvals WHERE run_id = ? ORDER BY created_at`).all(runId);
|
|
306
|
+
return rows.map(row => this.#approvalRecord(row));
|
|
307
|
+
}
|
|
308
|
+
#approvalRecord(row) {
|
|
309
|
+
return {
|
|
310
|
+
runId: row.run_id,
|
|
311
|
+
approvalId: row.approval_id,
|
|
312
|
+
prompt: row.prompt,
|
|
313
|
+
status: row.status,
|
|
314
|
+
decision: parseJson(row.decision_json),
|
|
315
|
+
metadata: parseJson(row.metadata_json),
|
|
316
|
+
createdAt: row.created_at,
|
|
317
|
+
updatedAt: row.updated_at,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
#resolveApproval(runId, approvalId) {
|
|
321
|
+
if (approvalId) {
|
|
322
|
+
const record = this.getApproval(runId, approvalId);
|
|
323
|
+
if (!record)
|
|
324
|
+
throw new Error(`Cannot decide approval '${approvalId}': none exists for run '${runId}'.`);
|
|
325
|
+
return record;
|
|
326
|
+
}
|
|
327
|
+
const pending = this.listApprovals(runId, { status: 'pending' });
|
|
328
|
+
if (!pending.length)
|
|
329
|
+
throw new Error(`No pending approvals for run '${runId}'.`);
|
|
330
|
+
return pending[pending.length - 1];
|
|
331
|
+
}
|
|
332
|
+
approve(runId, decision = {}, approvalId = null) {
|
|
333
|
+
const record = this.#resolveApproval(runId, approvalId);
|
|
334
|
+
const value = { ...(decision ?? {}), approved: decision?.approved !== false };
|
|
335
|
+
this.db.prepare(`
|
|
336
|
+
UPDATE qflow_approvals SET status = 'approved', decision_json = ?, updated_at = ?
|
|
337
|
+
WHERE run_id = ? AND approval_id = ?
|
|
338
|
+
`).run(stringify(value), new Date().toISOString(), runId, record.approvalId);
|
|
339
|
+
return this.getApproval(runId, record.approvalId);
|
|
340
|
+
}
|
|
341
|
+
reject(runId, decision = {}, approvalId = null) {
|
|
342
|
+
const record = this.#resolveApproval(runId, approvalId);
|
|
343
|
+
const value = { ...(decision ?? {}), approved: false };
|
|
344
|
+
this.db.prepare(`
|
|
345
|
+
UPDATE qflow_approvals SET status = 'rejected', decision_json = ?, updated_at = ?
|
|
346
|
+
WHERE run_id = ? AND approval_id = ?
|
|
347
|
+
`).run(stringify(value), new Date().toISOString(), runId, record.approvalId);
|
|
348
|
+
return this.getApproval(runId, record.approvalId);
|
|
349
|
+
}
|
|
350
|
+
// --- Deterministic LLM response cache ---------------------------------------
|
|
351
|
+
cacheGet(namespace, key) {
|
|
352
|
+
const row = this.db.prepare(`
|
|
353
|
+
SELECT value_json, expires_at FROM qflow_cache WHERE namespace = ? AND cache_key = ?
|
|
354
|
+
`).get(namespace, key);
|
|
355
|
+
if (!row)
|
|
356
|
+
return null;
|
|
357
|
+
if (row.expires_at != null && row.expires_at <= Date.now()) {
|
|
358
|
+
this.db.prepare('DELETE FROM qflow_cache WHERE namespace = ? AND cache_key = ?').run(namespace, key);
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
return parseJson(row.value_json);
|
|
362
|
+
}
|
|
363
|
+
cacheSet(namespace, key, value, ttlMs = null) {
|
|
364
|
+
const expiresAt = ttlMs == null || ttlMs === Infinity ? null : Date.now() + ttlMs;
|
|
365
|
+
this.db.prepare(`
|
|
366
|
+
INSERT INTO qflow_cache (namespace, cache_key, value_json, expires_at, created_at)
|
|
367
|
+
VALUES (?, ?, ?, ?, ?)
|
|
368
|
+
ON CONFLICT(namespace, cache_key) DO UPDATE SET
|
|
369
|
+
value_json = excluded.value_json,
|
|
370
|
+
expires_at = excluded.expires_at,
|
|
371
|
+
created_at = excluded.created_at
|
|
372
|
+
`).run(namespace, key, stringify(value), expiresAt, new Date().toISOString());
|
|
373
|
+
return key;
|
|
374
|
+
}
|
|
375
|
+
clearCache(namespace = null) {
|
|
376
|
+
const statement = namespace
|
|
377
|
+
? this.db.prepare('DELETE FROM qflow_cache WHERE namespace = ?')
|
|
378
|
+
: this.db.prepare('DELETE FROM qflow_cache');
|
|
379
|
+
const result = namespace ? statement.run(namespace) : statement.run();
|
|
380
|
+
return result.changes;
|
|
381
|
+
}
|
|
382
|
+
loadSideEffect(runId, operationId) {
|
|
383
|
+
const row = this.db.prepare(`
|
|
384
|
+
SELECT * FROM qflow_side_effects WHERE run_id = ? AND operation_id = ?
|
|
385
|
+
`).get(runId, operationId);
|
|
386
|
+
if (!row)
|
|
387
|
+
return null;
|
|
388
|
+
return {
|
|
389
|
+
runId: row.run_id,
|
|
390
|
+
operationId: row.operation_id,
|
|
391
|
+
kind: row.kind,
|
|
392
|
+
status: row.status,
|
|
393
|
+
result: parseJson(row.result_json),
|
|
394
|
+
error: parseJson(row.error_json),
|
|
395
|
+
claimedBy: row.claimed_by ?? null,
|
|
396
|
+
leaseExpiresAt: row.lease_expires_at ?? null,
|
|
397
|
+
createdAt: row.created_at,
|
|
398
|
+
updatedAt: row.updated_at,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
#handleExistingSideEffect(existing, { operationId, onPending, workerId }) {
|
|
402
|
+
if (existing.status === 'completed') {
|
|
403
|
+
return { result: existing.result, replayed: true, operationId, status: 'completed' };
|
|
404
|
+
}
|
|
405
|
+
if (onPending === 'return-null') {
|
|
406
|
+
return { result: null, replayed: true, operationId, status: existing.status };
|
|
407
|
+
}
|
|
408
|
+
if (existing.status === 'failed' && onPending === 'retry')
|
|
409
|
+
return null;
|
|
410
|
+
if (existing.status === 'pending' &&
|
|
411
|
+
existing.claimedBy &&
|
|
412
|
+
existing.claimedBy !== workerId &&
|
|
413
|
+
existing.leaseExpiresAt > Date.now()) {
|
|
414
|
+
throw new SideEffectClaimedError(operationId, existing.claimedBy);
|
|
415
|
+
}
|
|
416
|
+
throw new SideEffectUncertainError(operationId);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Reserve an operation with an INSERT (never an upsert) before running it.
|
|
420
|
+
* Completed operations replay their result; reserved-but-unfinished
|
|
421
|
+
* operations are uncertain, and operations claimed by a live worker are
|
|
422
|
+
* refused so two workers cannot execute the same effect.
|
|
423
|
+
*/
|
|
424
|
+
async runSideEffect({ runId, operationId, execute, kind = 'side_effect', onPending = 'error', workerId = this.workerId, leaseMs = this.leaseMs, }) {
|
|
425
|
+
if (!runId || !operationId)
|
|
426
|
+
throw new Error('runSideEffect requires runId and operationId.');
|
|
427
|
+
if (typeof execute !== 'function')
|
|
428
|
+
throw new Error('runSideEffect requires an execute function.');
|
|
429
|
+
const now = new Date().toISOString();
|
|
430
|
+
const leaseExpiresAt = Date.now() + Math.max(0, leaseMs);
|
|
431
|
+
let reserved = false;
|
|
432
|
+
for (let attempt = 0; attempt < 2 && !reserved; attempt += 1) {
|
|
433
|
+
const current = this.loadSideEffect(runId, operationId);
|
|
434
|
+
if (!current) {
|
|
435
|
+
// INSERT OR IGNORE: a concurrent worker wins the row and we must not
|
|
436
|
+
// reset its reservation (which is what the old upsert did).
|
|
437
|
+
const reservation = this.db.prepare(`
|
|
438
|
+
INSERT OR IGNORE INTO qflow_side_effects (
|
|
439
|
+
run_id, operation_id, kind, status, result_json, error_json,
|
|
440
|
+
claimed_by, lease_expires_at, created_at, updated_at
|
|
441
|
+
) VALUES (?, ?, ?, 'pending', NULL, NULL, ?, ?, ?, ?)
|
|
442
|
+
`).run(runId, operationId, kind, workerId, leaseExpiresAt, now, now);
|
|
443
|
+
reserved = reservation.changes > 0;
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
const outcome = this.#handleExistingSideEffect(current, { operationId, onPending, workerId });
|
|
447
|
+
if (outcome)
|
|
448
|
+
return outcome;
|
|
449
|
+
// Only reached for failed + retry: take ownership of the failed row.
|
|
450
|
+
const claimed = this.db.prepare(`
|
|
451
|
+
UPDATE qflow_side_effects
|
|
452
|
+
SET status = 'pending', claimed_by = ?, lease_expires_at = ?, error_json = NULL, updated_at = ?
|
|
453
|
+
WHERE run_id = ? AND operation_id = ? AND status = 'failed'
|
|
454
|
+
`).run(workerId, leaseExpiresAt, now, runId, operationId);
|
|
455
|
+
reserved = claimed.changes > 0;
|
|
456
|
+
}
|
|
457
|
+
if (!reserved)
|
|
458
|
+
throw new SideEffectUncertainError(operationId);
|
|
459
|
+
try {
|
|
460
|
+
const result = await execute();
|
|
461
|
+
this.db.prepare(`
|
|
462
|
+
UPDATE qflow_side_effects
|
|
463
|
+
SET status = 'completed', result_json = ?, error_json = NULL,
|
|
464
|
+
claimed_by = NULL, lease_expires_at = NULL, updated_at = ?
|
|
465
|
+
WHERE run_id = ? AND operation_id = ?
|
|
466
|
+
`).run(stringify(result), new Date().toISOString(), runId, operationId);
|
|
467
|
+
return { result, replayed: false, operationId, status: 'completed' };
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
this.db.prepare(`
|
|
471
|
+
UPDATE qflow_side_effects
|
|
472
|
+
SET status = 'failed', result_json = NULL, error_json = ?,
|
|
473
|
+
claimed_by = NULL, lease_expires_at = NULL, updated_at = ?
|
|
474
|
+
WHERE run_id = ? AND operation_id = ?
|
|
475
|
+
`).run(stringify({ message: error.message, stack: error.stack }), new Date().toISOString(), runId, operationId);
|
|
476
|
+
throw error;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/** Release a dead worker's claim so an explicit retry can take over. */
|
|
480
|
+
failSideEffect(runId, operationId, error = { message: 'Released by operator' }) {
|
|
481
|
+
this.db.prepare(`
|
|
482
|
+
UPDATE qflow_side_effects
|
|
483
|
+
SET status = 'failed', error_json = ?, claimed_by = NULL, lease_expires_at = NULL, updated_at = ?
|
|
484
|
+
WHERE run_id = ? AND operation_id = ?
|
|
485
|
+
`).run(stringify(error), new Date().toISOString(), runId, operationId);
|
|
486
|
+
return this.loadSideEffect(runId, operationId);
|
|
487
|
+
}
|
|
488
|
+
listSideEffects(runId) {
|
|
489
|
+
return this.db.prepare(`
|
|
490
|
+
SELECT run_id, operation_id, kind, status, claimed_by, lease_expires_at, created_at, updated_at
|
|
491
|
+
FROM qflow_side_effects WHERE run_id = ? ORDER BY created_at
|
|
492
|
+
`).all(runId).map(row => ({
|
|
493
|
+
runId: row.run_id,
|
|
494
|
+
operationId: row.operation_id,
|
|
495
|
+
kind: row.kind,
|
|
496
|
+
status: row.status,
|
|
497
|
+
claimedBy: row.claimed_by ?? null,
|
|
498
|
+
leaseExpiresAt: row.lease_expires_at ?? null,
|
|
499
|
+
createdAt: row.created_at,
|
|
500
|
+
updatedAt: row.updated_at,
|
|
501
|
+
}));
|
|
502
|
+
}
|
|
503
|
+
/** Export a run as a JSON-safe trace for the site viewer. */
|
|
504
|
+
exportRunTrace(runId, options = {}) {
|
|
505
|
+
const run = this.loadRun(runId);
|
|
506
|
+
if (!run)
|
|
507
|
+
throw new Error(`Cannot export trace: no run found for '${runId}'.`);
|
|
508
|
+
return buildRunTrace(run, this.listCheckpoints(runId), options);
|
|
509
|
+
}
|
|
510
|
+
async writeTraceFile(runId, filepath, options = {}) {
|
|
511
|
+
await Bun.write(filepath, serializeTrace(this.exportRunTrace(runId, options)));
|
|
512
|
+
return filepath;
|
|
513
|
+
}
|
|
514
|
+
close() {
|
|
515
|
+
this.db.close();
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* AsyncFlow with a checkpoint after every successful node.
|
|
520
|
+
*
|
|
521
|
+
* `runDurable()` returns `{ runId, result, shared, steps, resumed }`; pass the
|
|
522
|
+
* same `runId` with `resume: true` after a crash to continue from the last
|
|
523
|
+
* committed node boundary. `runAsync()` keeps the normal AsyncFlow return shape.
|
|
524
|
+
*/
|
|
525
|
+
export class DurableFlow extends AsyncFlow {
|
|
526
|
+
constructor(start = null, { checkpointer, name, version = '1.0.0', onVersionMismatch = 'abort', migrate = null, workerId = null, leaseMs = null, } = {}) {
|
|
527
|
+
super(start);
|
|
528
|
+
this.checkpointer = checkpointer ?? new SQLiteCheckpointer(':memory:');
|
|
529
|
+
this.flowName = name ?? this.constructor.name;
|
|
530
|
+
this.version = version;
|
|
531
|
+
this.onVersionMismatch = onVersionMismatch;
|
|
532
|
+
this.migrate = migrate;
|
|
533
|
+
this.workerId = workerId ?? this.checkpointer.workerId ?? null;
|
|
534
|
+
this.leaseMs = leaseMs ?? this.checkpointer.leaseMs ?? null;
|
|
535
|
+
}
|
|
536
|
+
buildNodeIndex() {
|
|
537
|
+
const index = new Map();
|
|
538
|
+
const queue = this.startNode ? [this.startNode] : [];
|
|
539
|
+
const seen = new Set();
|
|
540
|
+
while (queue.length) {
|
|
541
|
+
const node = queue.shift();
|
|
542
|
+
if (!node || seen.has(node))
|
|
543
|
+
continue;
|
|
544
|
+
index.set(node, index.size);
|
|
545
|
+
seen.add(node);
|
|
546
|
+
for (const action of Object.keys(node.successors ?? {}).sort()) {
|
|
547
|
+
queue.push(node.successors[action]);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return index;
|
|
551
|
+
}
|
|
552
|
+
/** Find a resume cursor by index, falling back to the saved node class. */
|
|
553
|
+
findNodeByIndex(index, target, nodeClass = null) {
|
|
554
|
+
for (const [node, nodeIndex] of index) {
|
|
555
|
+
if (nodeIndex === target)
|
|
556
|
+
return node;
|
|
557
|
+
}
|
|
558
|
+
if (nodeClass) {
|
|
559
|
+
for (const node of index.keys()) {
|
|
560
|
+
if (node.constructor.name === nodeClass)
|
|
561
|
+
return node;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return this.startNode;
|
|
565
|
+
}
|
|
566
|
+
#checkVersion(state, runId, shared, flowObserver) {
|
|
567
|
+
const saved = state.flowVersion ?? null;
|
|
568
|
+
const current = this.version ?? null;
|
|
569
|
+
if (saved === current)
|
|
570
|
+
return shared;
|
|
571
|
+
const detail = { runId, expected: saved, actual: current, step: state.step };
|
|
572
|
+
if (this.onVersionMismatch === 'migrate') {
|
|
573
|
+
const result = typeof this.migrate === 'function'
|
|
574
|
+
? this.migrate({ ...detail, shared, checkpoints: this.checkpointer.listCheckpoints(runId) })
|
|
575
|
+
: null;
|
|
576
|
+
const migrated = result && typeof result === 'object' ? result : shared;
|
|
577
|
+
this.checkpointer.setFlowVersion?.(runId, current);
|
|
578
|
+
flowObserver.emit('flow:version_migrated', detail);
|
|
579
|
+
return migrated;
|
|
580
|
+
}
|
|
581
|
+
if (this.onVersionMismatch === 'ignore') {
|
|
582
|
+
flowObserver.emit('flow:version_mismatch', { ...detail, policy: 'ignore' });
|
|
583
|
+
return shared;
|
|
584
|
+
}
|
|
585
|
+
throw new FlowVersionMismatchError(runId, saved, current);
|
|
586
|
+
}
|
|
587
|
+
async runDurable({ shared = {}, runId = crypto.randomUUID(), resume = false, signal, observer = {} } = {}) {
|
|
588
|
+
const flowObserver = this._createFlowObserver(runId, observer);
|
|
589
|
+
const context = {
|
|
590
|
+
...flowObserver,
|
|
591
|
+
runId,
|
|
592
|
+
signal,
|
|
593
|
+
checkpointer: this.checkpointer,
|
|
594
|
+
workerId: this.workerId,
|
|
595
|
+
leaseMs: this.leaseMs,
|
|
596
|
+
};
|
|
597
|
+
let state;
|
|
598
|
+
if (resume) {
|
|
599
|
+
state = this.checkpointer.loadRun(runId);
|
|
600
|
+
if (!state)
|
|
601
|
+
throw new Error(`Cannot resume run '${runId}': no saved state found.`);
|
|
602
|
+
shared = state.shared;
|
|
603
|
+
this.setParams(state.params ?? {});
|
|
604
|
+
shared = this.#checkVersion(state, runId, shared, flowObserver) ?? shared;
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
state = { status: 'running', step: 0, cursorNodeIndex: null };
|
|
608
|
+
this.checkpointer.startRun({
|
|
609
|
+
runId,
|
|
610
|
+
flowName: this.flowName,
|
|
611
|
+
shared,
|
|
612
|
+
params: this.params,
|
|
613
|
+
version: this.version,
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
flowObserver.emit(resume ? 'run:resumed' : 'run:start', {
|
|
617
|
+
runId,
|
|
618
|
+
flowName: this.flowName,
|
|
619
|
+
flowVersion: this.version,
|
|
620
|
+
status: state.status,
|
|
621
|
+
step: state.step,
|
|
622
|
+
});
|
|
623
|
+
const nodeIndex = this.buildNodeIndex();
|
|
624
|
+
const checkpoints = this.checkpointer.listCheckpoints(runId);
|
|
625
|
+
const lastCheckpoint = checkpoints[checkpoints.length - 1];
|
|
626
|
+
// A run that failed before its first checkpoint has no cursor yet; retry
|
|
627
|
+
// from the start node rather than silently completing with no work done.
|
|
628
|
+
let curr = resume && state.cursorNodeIndex != null
|
|
629
|
+
? this.findNodeByIndex(nodeIndex, state.cursorNodeIndex, lastCheckpoint?.nodeClass)
|
|
630
|
+
: this.startNode;
|
|
631
|
+
if (resume && lastCheckpoint?.nodeClass && curr?.constructor?.name !== lastCheckpoint.nodeClass) {
|
|
632
|
+
flowObserver.emit('flow:node_remapped', {
|
|
633
|
+
runId,
|
|
634
|
+
from: lastCheckpoint.nodeClass,
|
|
635
|
+
to: curr?.constructor?.name ?? null,
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
let step = state.step;
|
|
639
|
+
let lastResult = state.result;
|
|
640
|
+
try {
|
|
641
|
+
while (curr) {
|
|
642
|
+
if (signal?.aborted)
|
|
643
|
+
throw abortError();
|
|
644
|
+
curr.setParams({ ...this.params });
|
|
645
|
+
const prepRes = await curr.prepAsync(shared, context);
|
|
646
|
+
const execRes = await curr._exec(prepRes, shared, context);
|
|
647
|
+
const action = await curr.postAsync(shared, prepRes, execRes, context);
|
|
648
|
+
lastResult = execRes;
|
|
649
|
+
step += 1;
|
|
650
|
+
const nextNode = this.getNextNode(curr, action);
|
|
651
|
+
const entry = {
|
|
652
|
+
runId,
|
|
653
|
+
flowName: this.flowName,
|
|
654
|
+
flowVersion: this.version,
|
|
655
|
+
step,
|
|
656
|
+
nodeIndex: nodeIndex.get(curr) ?? null,
|
|
657
|
+
nodeClass: curr.constructor.name,
|
|
658
|
+
action,
|
|
659
|
+
nextNodeIndex: nextNode ? nodeIndex.get(nextNode) ?? null : null,
|
|
660
|
+
shared,
|
|
661
|
+
params: this.params,
|
|
662
|
+
execRes,
|
|
663
|
+
};
|
|
664
|
+
this.checkpointer.saveCheckpoint(entry);
|
|
665
|
+
flowObserver.emit('checkpoint:saved', {
|
|
666
|
+
runId,
|
|
667
|
+
step,
|
|
668
|
+
nodeClass: entry.nodeClass,
|
|
669
|
+
action,
|
|
670
|
+
nextNodeIndex: entry.nextNodeIndex,
|
|
671
|
+
});
|
|
672
|
+
curr = nextNode;
|
|
673
|
+
}
|
|
674
|
+
this.checkpointer.setRunDueAt?.(runId, null);
|
|
675
|
+
this.checkpointer.updateRunStatus(runId, 'completed', { step, shared, result: lastResult });
|
|
676
|
+
flowObserver.emit('run:end', { runId, status: 'completed', step, result: lastResult });
|
|
677
|
+
return { runId, result: lastResult, shared, steps: step, resumed: resume, status: 'completed' };
|
|
678
|
+
}
|
|
679
|
+
catch (error) {
|
|
680
|
+
if (error instanceof ApprovalPendingError) {
|
|
681
|
+
this.checkpointer.setRunDueAt?.(runId, null);
|
|
682
|
+
this.checkpointer.updateRunStatus(runId, 'suspended', { step, shared, result: null });
|
|
683
|
+
flowObserver.emit('approval:pending', {
|
|
684
|
+
runId, approvalId: error.approvalId, prompt: error.prompt, step,
|
|
685
|
+
});
|
|
686
|
+
flowObserver.emit('run:end', { runId, status: 'suspended', step, approvalId: error.approvalId });
|
|
687
|
+
return {
|
|
688
|
+
runId, result: null, shared, steps: step, resumed: resume,
|
|
689
|
+
status: 'suspended', suspended: true, approvalId: error.approvalId,
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
if (error instanceof SchedulePendingError) {
|
|
693
|
+
this.checkpointer.setRunDueAt?.(runId, error.dueAt);
|
|
694
|
+
this.checkpointer.updateRunStatus(runId, 'scheduled', { step, shared, result: null });
|
|
695
|
+
flowObserver.emit('schedule:pending', {
|
|
696
|
+
runId, scheduleId: error.scheduleId, dueAt: error.dueAt, step,
|
|
697
|
+
});
|
|
698
|
+
flowObserver.emit('run:end', { runId, status: 'scheduled', step, dueAt: error.dueAt });
|
|
699
|
+
return {
|
|
700
|
+
runId, result: null, shared, steps: step, resumed: resume,
|
|
701
|
+
status: 'scheduled', suspended: true, scheduled: true,
|
|
702
|
+
scheduleId: error.scheduleId, dueAt: error.dueAt,
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
this.checkpointer.setRunDueAt?.(runId, null);
|
|
706
|
+
this.checkpointer.updateRunStatus(runId, 'failed', { step, shared, result: lastResult, error });
|
|
707
|
+
flowObserver.emit('run:end', { runId, status: 'failed', step, error: { message: error.message } });
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
async runAsync(shared = {}, observer = {}) {
|
|
712
|
+
const outcome = await this.runDurable({ shared, observer });
|
|
713
|
+
return outcome.result;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
/** Functional form for custom checkpointers implementing loadRun/listCheckpoints. */
|
|
717
|
+
export function createRunTrace(checkpointer, runId, options = {}) {
|
|
718
|
+
if (typeof checkpointer?.exportRunTrace === 'function') {
|
|
719
|
+
return checkpointer.exportRunTrace(runId, options);
|
|
720
|
+
}
|
|
721
|
+
const run = checkpointer?.loadRun?.(runId);
|
|
722
|
+
if (!run)
|
|
723
|
+
throw new Error(`Cannot export trace: no run found for '${runId}'.`);
|
|
724
|
+
return buildRunTrace(run, checkpointer.listCheckpoints(runId), options);
|
|
725
|
+
}
|
|
726
|
+
// The durable subpath is the single entry point for long-lived run control.
|
|
727
|
+
export { WaitForApprovalNode, resolveApprovalId } from './approval.js';
|
|
728
|
+
export { ScheduleNode, nextCronTime } from './schedule.js';
|
|
729
|
+
export { BudgetNode, BudgetTracker } from './budget.js';
|
|
730
|
+
export { ApprovalPendingError, SchedulePendingError, FlowVersionMismatchError, SideEffectClaimedError, SideEffectUncertainError, BudgetExceededError, } from './util.js';
|