@nagi-js/core 0.1.1-rc.1 → 0.1.1-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +264 -466
- package/dist/index.js +1316 -394
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3,9 +3,6 @@ var DEF = "__def";
|
|
|
3
3
|
function attachDef(meta, def) {
|
|
4
4
|
return { kind: meta.kind, id: meta.id, [DEF]: def };
|
|
5
5
|
}
|
|
6
|
-
function attachDefMut(step, def) {
|
|
7
|
-
step[DEF] = def;
|
|
8
|
-
}
|
|
9
6
|
function getDef(step) {
|
|
10
7
|
const def = step[DEF];
|
|
11
8
|
if (def === void 0) {
|
|
@@ -16,70 +13,38 @@ function getDef(step) {
|
|
|
16
13
|
return def;
|
|
17
14
|
}
|
|
18
15
|
function needsStepIds(def) {
|
|
19
|
-
|
|
20
|
-
for (const upstream of Object.values(def.needs)) {
|
|
21
|
-
if (upstream && typeof upstream === "object" && "id" in upstream && typeof upstream.id === "string") {
|
|
22
|
-
out.push(upstream.id);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
return out;
|
|
16
|
+
return Object.values(def.needs).map((upstream) => upstream.id);
|
|
26
17
|
}
|
|
27
18
|
function resolveNeeds(def, loadOutput) {
|
|
28
19
|
const result = {};
|
|
29
20
|
for (const [localKey, upstream] of Object.entries(def.needs)) {
|
|
30
|
-
|
|
31
|
-
result[localKey] = loadOutput(upstream.id);
|
|
32
|
-
}
|
|
21
|
+
result[localKey] = loadOutput(upstream.id);
|
|
33
22
|
}
|
|
34
23
|
return result;
|
|
35
24
|
}
|
|
36
|
-
function matchArms(def) {
|
|
37
|
-
return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
|
|
38
|
-
}
|
|
39
25
|
function readSelectedArm(matchId, runState) {
|
|
26
|
+
let selected = null;
|
|
40
27
|
for (const fact of runState.facts) {
|
|
41
28
|
if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
|
|
42
|
-
|
|
29
|
+
selected = fact.arm;
|
|
30
|
+
} else if (fact.kind === "step.reset" && fact.stepId === matchId) {
|
|
31
|
+
selected = null;
|
|
43
32
|
}
|
|
44
33
|
}
|
|
45
|
-
return
|
|
34
|
+
return selected;
|
|
46
35
|
}
|
|
47
36
|
function selectArm(def, args) {
|
|
48
|
-
if (def.mode === "discriminator") {
|
|
49
|
-
const key = def.on(args);
|
|
50
|
-
if (def.arms[key] === void 0) {
|
|
51
|
-
const available = Object.keys(def.arms).join(", ");
|
|
52
|
-
throw new Error(
|
|
53
|
-
`match: discriminator returned "${key}" which has no arm (available: ${available || "<none>"})`
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
return key;
|
|
57
|
-
}
|
|
58
37
|
for (const arm of def.arms) {
|
|
59
38
|
if (arm.otherwise) return arm.id;
|
|
60
39
|
if (arm.when?.(args)) return arm.id;
|
|
61
40
|
}
|
|
62
41
|
throw new Error(
|
|
63
|
-
`match: no
|
|
42
|
+
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
64
43
|
);
|
|
65
44
|
}
|
|
66
45
|
|
|
67
46
|
// src/builder.ts
|
|
68
|
-
var BUILDER_BRAND = /* @__PURE__ */ Symbol.for("nagi.builder");
|
|
69
|
-
function isBuilder(value) {
|
|
70
|
-
return typeof value === "object" && value !== null && value[BUILDER_BRAND] === true;
|
|
71
|
-
}
|
|
72
|
-
function resolveBuildResult(value) {
|
|
73
|
-
if (isBuilder(value)) {
|
|
74
|
-
return Object.fromEntries(value.__steps);
|
|
75
|
-
}
|
|
76
|
-
return value;
|
|
77
|
-
}
|
|
78
|
-
function isDiscriminator(config) {
|
|
79
|
-
return "cases" in config && "on" in config;
|
|
80
|
-
}
|
|
81
47
|
function makeBuilder() {
|
|
82
|
-
const chainSteps = /* @__PURE__ */ new Map();
|
|
83
48
|
function task(config) {
|
|
84
49
|
const def = {
|
|
85
50
|
kind: "task",
|
|
@@ -104,6 +69,7 @@ function makeBuilder() {
|
|
|
104
69
|
kind: "signal",
|
|
105
70
|
needs: config.needs ?? {},
|
|
106
71
|
schema: config.schema,
|
|
72
|
+
...config.names !== void 0 ? { names: config.names } : {},
|
|
107
73
|
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
108
74
|
...config.when !== void 0 ? {
|
|
109
75
|
when: config.when
|
|
@@ -111,30 +77,28 @@ function makeBuilder() {
|
|
|
111
77
|
};
|
|
112
78
|
return attachDef({ kind: "signal", id: "" }, def);
|
|
113
79
|
}
|
|
80
|
+
function subflow(child, config) {
|
|
81
|
+
const def = {
|
|
82
|
+
kind: "subflow",
|
|
83
|
+
needs: config.needs ?? {},
|
|
84
|
+
childFlowId: child.id,
|
|
85
|
+
buildInput: config.input,
|
|
86
|
+
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
87
|
+
...config.when !== void 0 ? {
|
|
88
|
+
when: config.when
|
|
89
|
+
} : {}
|
|
90
|
+
};
|
|
91
|
+
return attachDef(
|
|
92
|
+
{ kind: "subflow", id: "" },
|
|
93
|
+
def
|
|
94
|
+
);
|
|
95
|
+
}
|
|
114
96
|
function match(config) {
|
|
115
|
-
const needs =
|
|
116
|
-
if (isDiscriminator(config)) {
|
|
117
|
-
const arms2 = {};
|
|
118
|
-
for (const [caseKey, build] of Object.entries(config.cases)) {
|
|
119
|
-
const nested = resolveBuildResult(
|
|
120
|
-
build(makeBuilder())
|
|
121
|
-
);
|
|
122
|
-
arms2[caseKey] = { id: caseKey, stepIds: [], _nested: nested };
|
|
123
|
-
}
|
|
124
|
-
const def2 = {
|
|
125
|
-
kind: "match",
|
|
126
|
-
mode: "discriminator",
|
|
127
|
-
needs,
|
|
128
|
-
on: config.on,
|
|
129
|
-
arms: arms2
|
|
130
|
-
};
|
|
131
|
-
return attachDef({ kind: "match", id: "" }, def2);
|
|
132
|
-
}
|
|
133
|
-
const guardConfig = config;
|
|
97
|
+
const needs = config.needs ?? {};
|
|
134
98
|
const arms = [];
|
|
135
|
-
for (let i = 0; i <
|
|
136
|
-
const arm =
|
|
137
|
-
const nested =
|
|
99
|
+
for (let i = 0; i < config.arms.length; i++) {
|
|
100
|
+
const arm = config.arms[i];
|
|
101
|
+
const nested = arm.build(makeBuilder());
|
|
138
102
|
const armId = arm.otherwise ? "otherwise" : `arm${i}`;
|
|
139
103
|
arms.push({
|
|
140
104
|
id: armId,
|
|
@@ -142,80 +106,25 @@ function makeBuilder() {
|
|
|
142
106
|
when: arm.when
|
|
143
107
|
} : {},
|
|
144
108
|
...arm.otherwise ? { otherwise: true } : {},
|
|
145
|
-
|
|
146
|
-
_nested: nested
|
|
109
|
+
nested
|
|
147
110
|
});
|
|
148
111
|
}
|
|
149
|
-
const def = {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
};
|
|
155
|
-
return attachDef({ kind: "match", id: "" }, def);
|
|
156
|
-
}
|
|
157
|
-
function step(key, config) {
|
|
158
|
-
if (chainSteps.has(key)) {
|
|
159
|
-
throw new Error(
|
|
160
|
-
`b.step: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
const shell = { kind: "task", id: "" };
|
|
164
|
-
const needs = {};
|
|
165
|
-
if (config.needs) {
|
|
166
|
-
for (const sibKey of config.needs) {
|
|
167
|
-
const sibling = chainSteps.get(sibKey);
|
|
168
|
-
if (sibling === void 0) {
|
|
169
|
-
throw new Error(
|
|
170
|
-
`b.step("${key}"): unknown sibling "${sibKey}". Available keys so far: ${[...chainSteps.keys()].join(", ") || "<none>"}.`
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
needs[sibKey] = sibling;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
const def = {
|
|
177
|
-
kind: "task",
|
|
178
|
-
needs,
|
|
179
|
-
...config.retry !== void 0 ? { retry: config.retry } : {},
|
|
180
|
-
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
181
|
-
...config.when !== void 0 ? {
|
|
182
|
-
when: config.when
|
|
183
|
-
} : {},
|
|
184
|
-
run: config.run,
|
|
185
|
-
...config.onStart !== void 0 ? { onStart: config.onStart } : {},
|
|
186
|
-
...config.onComplete !== void 0 ? {
|
|
187
|
-
onComplete: config.onComplete
|
|
188
|
-
} : {},
|
|
189
|
-
...config.onError !== void 0 ? { onError: config.onError } : {},
|
|
190
|
-
...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
|
|
191
|
-
};
|
|
192
|
-
attachDefMut(shell, def);
|
|
193
|
-
chainSteps.set(key, shell);
|
|
194
|
-
return builder;
|
|
195
|
-
}
|
|
196
|
-
function include(key, s) {
|
|
197
|
-
if (chainSteps.has(key)) {
|
|
198
|
-
throw new Error(
|
|
199
|
-
`b.include: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
|
|
200
|
-
);
|
|
201
|
-
}
|
|
202
|
-
chainSteps.set(key, s);
|
|
203
|
-
return builder;
|
|
112
|
+
const def = { kind: "match", needs, arms };
|
|
113
|
+
return attachDef(
|
|
114
|
+
{ kind: "match", id: "" },
|
|
115
|
+
def
|
|
116
|
+
);
|
|
204
117
|
}
|
|
205
|
-
|
|
118
|
+
return {
|
|
206
119
|
task,
|
|
207
120
|
signal,
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
include,
|
|
211
|
-
[BUILDER_BRAND]: true,
|
|
212
|
-
__steps: chainSteps
|
|
121
|
+
subflow,
|
|
122
|
+
match
|
|
213
123
|
};
|
|
214
|
-
return builder;
|
|
215
124
|
}
|
|
216
125
|
function flow(config) {
|
|
217
126
|
const builder = makeBuilder();
|
|
218
|
-
const built =
|
|
127
|
+
const built = config.build(builder);
|
|
219
128
|
const idByIdentity = /* @__PURE__ */ new Map();
|
|
220
129
|
collectIds(built, "", idByIdentity);
|
|
221
130
|
const finalSteps = {};
|
|
@@ -227,6 +136,7 @@ function flow(config) {
|
|
|
227
136
|
idByIdentity,
|
|
228
137
|
out: finalSteps
|
|
229
138
|
});
|
|
139
|
+
assertSignalNameUniqueness(config.id, finalSteps);
|
|
230
140
|
return {
|
|
231
141
|
id: config.id,
|
|
232
142
|
input: config.input,
|
|
@@ -236,7 +146,21 @@ function flow(config) {
|
|
|
236
146
|
...config.onComplete !== void 0 ? {
|
|
237
147
|
onComplete: config.onComplete
|
|
238
148
|
} : {},
|
|
239
|
-
...config.onError !== void 0 ? { onError: config.onError } : {}
|
|
149
|
+
...config.onError !== void 0 ? { onError: config.onError } : {},
|
|
150
|
+
...config.concurrency !== void 0 ? { concurrency: normalizeConcurrency(config.concurrency) } : {}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function normalizeConcurrency(c) {
|
|
154
|
+
if (typeof c === "object") {
|
|
155
|
+
return {
|
|
156
|
+
keyFn: c.keyFn,
|
|
157
|
+
mode: c.mode ?? "cancel-in-progress"
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
const key = c;
|
|
161
|
+
return {
|
|
162
|
+
keyFn: (input) => input[key],
|
|
163
|
+
mode: "cancel-in-progress"
|
|
240
164
|
};
|
|
241
165
|
}
|
|
242
166
|
function collectIds(map, prefix, idByIdentity) {
|
|
@@ -245,10 +169,9 @@ function collectIds(map, prefix, idByIdentity) {
|
|
|
245
169
|
idByIdentity.set(step, id);
|
|
246
170
|
const def = step.__def;
|
|
247
171
|
if (def?.kind === "match") {
|
|
248
|
-
const
|
|
249
|
-
for (const arm of arms) {
|
|
250
|
-
|
|
251
|
-
collectIds(arm._nested, `${id}.${arm.id}`, idByIdentity);
|
|
172
|
+
const pending = def;
|
|
173
|
+
for (const arm of pending.arms) {
|
|
174
|
+
collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
|
|
252
175
|
}
|
|
253
176
|
}
|
|
254
177
|
}
|
|
@@ -280,24 +203,22 @@ function walkAndRewrite(args) {
|
|
|
280
203
|
rewrittenNeeds[localKey] = { ...upstream, id: upstreamId };
|
|
281
204
|
}
|
|
282
205
|
if (def.kind === "match") {
|
|
283
|
-
const
|
|
206
|
+
const pending = def;
|
|
284
207
|
const finalizedArms = [];
|
|
285
|
-
for (const arm of
|
|
208
|
+
for (const arm of pending.arms) {
|
|
286
209
|
const armPrefix = `${id}.${arm.id}`;
|
|
287
210
|
const nestedStepIds = [];
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
nestedStepIds.push(`${armPrefix}.${nestedKey}`);
|
|
291
|
-
}
|
|
292
|
-
walkAndRewrite({
|
|
293
|
-
flowId,
|
|
294
|
-
map: arm._nested,
|
|
295
|
-
prefix: armPrefix,
|
|
296
|
-
parentMatch: { matchId: id, armId: arm.id },
|
|
297
|
-
idByIdentity,
|
|
298
|
-
out
|
|
299
|
-
});
|
|
211
|
+
for (const nestedKey of Object.keys(arm.nested)) {
|
|
212
|
+
nestedStepIds.push(`${armPrefix}.${nestedKey}`);
|
|
300
213
|
}
|
|
214
|
+
walkAndRewrite({
|
|
215
|
+
flowId,
|
|
216
|
+
map: arm.nested,
|
|
217
|
+
prefix: armPrefix,
|
|
218
|
+
parentMatch: { matchId: id, armId: arm.id },
|
|
219
|
+
idByIdentity,
|
|
220
|
+
out
|
|
221
|
+
});
|
|
301
222
|
finalizedArms.push({
|
|
302
223
|
id: arm.id,
|
|
303
224
|
...arm.when !== void 0 ? { when: arm.when } : {},
|
|
@@ -305,16 +226,8 @@ function walkAndRewrite(args) {
|
|
|
305
226
|
stepIds: nestedStepIds
|
|
306
227
|
});
|
|
307
228
|
}
|
|
308
|
-
const finalizedDef2 =
|
|
309
|
-
kind: "match",
|
|
310
|
-
mode: "discriminator",
|
|
311
|
-
needs: rewrittenNeeds,
|
|
312
|
-
on: def.on,
|
|
313
|
-
arms: Object.fromEntries(finalizedArms.map((a) => [a.id, a])),
|
|
314
|
-
...parentMatch ? { parentMatch } : {}
|
|
315
|
-
} : {
|
|
229
|
+
const finalizedDef2 = {
|
|
316
230
|
kind: "match",
|
|
317
|
-
mode: "guard",
|
|
318
231
|
needs: rewrittenNeeds,
|
|
319
232
|
arms: finalizedArms,
|
|
320
233
|
...parentMatch ? { parentMatch } : {}
|
|
@@ -327,6 +240,28 @@ function walkAndRewrite(args) {
|
|
|
327
240
|
out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
|
|
328
241
|
}
|
|
329
242
|
}
|
|
243
|
+
function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
244
|
+
const owners = /* @__PURE__ */ new Map();
|
|
245
|
+
for (const stepId of Object.keys(finalSteps)) {
|
|
246
|
+
owners.set(stepId, `step id "${stepId}"`);
|
|
247
|
+
}
|
|
248
|
+
for (const [stepId, step] of Object.entries(finalSteps)) {
|
|
249
|
+
const def = step.__def;
|
|
250
|
+
if (def === void 0 || def.kind !== "signal") continue;
|
|
251
|
+
if (def.names === void 0) continue;
|
|
252
|
+
for (const alias of def.names) {
|
|
253
|
+
if (alias === stepId) continue;
|
|
254
|
+
const prior = owners.get(alias);
|
|
255
|
+
const here = `alias of step "${stepId}"`;
|
|
256
|
+
if (prior !== void 0 && prior !== here) {
|
|
257
|
+
throw new Error(
|
|
258
|
+
`Flow "${flowId}": signal name "${alias}" is declared as both ${prior} and ${here}. Pick one \u2014 signal names share a namespace with step ids.`
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
owners.set(alias, here);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
330
265
|
|
|
331
266
|
// src/canonicalize.ts
|
|
332
267
|
var DEFAULT_RETRY = {
|
|
@@ -338,7 +273,7 @@ function warnSourceHashOnce() {
|
|
|
338
273
|
if (warnedAboutSourceHash) return;
|
|
339
274
|
warnedAboutSourceHash = true;
|
|
340
275
|
console.warn(
|
|
341
|
-
"[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged.
|
|
276
|
+
"[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
|
|
342
277
|
);
|
|
343
278
|
}
|
|
344
279
|
async function canonicalize(flow2) {
|
|
@@ -360,6 +295,7 @@ async function canonicalizeStep(id, def) {
|
|
|
360
295
|
const base = { id, kind: def.kind, needs };
|
|
361
296
|
if (def.kind === "task") return canonicalizeTask(base, def);
|
|
362
297
|
if (def.kind === "signal") return canonicalizeSignal(base, def);
|
|
298
|
+
if (def.kind === "subflow") return canonicalizeSubflow(base, def);
|
|
363
299
|
return canonicalizeMatch(base, def);
|
|
364
300
|
}
|
|
365
301
|
async function canonicalizeTask(base, def) {
|
|
@@ -374,16 +310,23 @@ async function canonicalizeSignal(base, def) {
|
|
|
374
310
|
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
375
311
|
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
376
312
|
out.signalSchema = await canonicalizeSchema(def.schema);
|
|
313
|
+
if (def.names !== void 0) {
|
|
314
|
+
out.signalNames = [...def.names].sort();
|
|
315
|
+
}
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
async function canonicalizeSubflow(base, def) {
|
|
319
|
+
const out = { ...base };
|
|
320
|
+
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
321
|
+
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
322
|
+
out.childFlowId = def.childFlowId;
|
|
323
|
+
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
377
324
|
return out;
|
|
378
325
|
}
|
|
379
326
|
async function canonicalizeMatch(base, def) {
|
|
380
327
|
const out = { ...base };
|
|
381
|
-
out.matchMode = def.mode;
|
|
382
|
-
if (def.mode === "discriminator") {
|
|
383
|
-
out.matchOnHash = await hashFnSource(def.on);
|
|
384
|
-
}
|
|
385
328
|
const arms = [];
|
|
386
|
-
for (const arm of
|
|
329
|
+
for (const arm of def.arms) {
|
|
387
330
|
arms.push(await canonicalizeArm(arm));
|
|
388
331
|
}
|
|
389
332
|
out.matchArms = arms;
|
|
@@ -421,6 +364,15 @@ async function hashFnSource(fn) {
|
|
|
421
364
|
async function sha256Canonical(dag) {
|
|
422
365
|
return sha256Hex(stableStringify(dag));
|
|
423
366
|
}
|
|
367
|
+
async function fingerprintFlows(flows) {
|
|
368
|
+
const entries = [];
|
|
369
|
+
for (const f of flows) {
|
|
370
|
+
const dag = await canonicalize(f);
|
|
371
|
+
entries.push([f.id, await sha256Canonical(dag)]);
|
|
372
|
+
}
|
|
373
|
+
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
374
|
+
return sha256Hex(stableStringify(entries));
|
|
375
|
+
}
|
|
424
376
|
function stableStringify(value) {
|
|
425
377
|
if (value === void 0) return "null";
|
|
426
378
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
@@ -515,12 +467,6 @@ function diffFields(before, after, out) {
|
|
|
515
467
|
if (!schemaEq(before.signalSchema, after.signalSchema)) {
|
|
516
468
|
out.push({ stepId: id, field: "signalSchema" });
|
|
517
469
|
}
|
|
518
|
-
if (before.matchMode !== after.matchMode) {
|
|
519
|
-
out.push({ stepId: id, field: "matchMode" });
|
|
520
|
-
}
|
|
521
|
-
if (before.matchOnHash !== after.matchOnHash) {
|
|
522
|
-
out.push({ stepId: id, field: "matchOn" });
|
|
523
|
-
}
|
|
524
470
|
if (!armsEq(before.matchArms, after.matchArms)) {
|
|
525
471
|
out.push({ stepId: id, field: "matchArms" });
|
|
526
472
|
}
|
|
@@ -567,6 +513,10 @@ var InMemoryStore = class {
|
|
|
567
513
|
snapshots = /* @__PURE__ */ new Map();
|
|
568
514
|
refs = /* @__PURE__ */ new Map();
|
|
569
515
|
globalFacts = [];
|
|
516
|
+
activeByKey = /* @__PURE__ */ new Map();
|
|
517
|
+
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
518
|
+
childrenByParent = /* @__PURE__ */ new Map();
|
|
519
|
+
summaries = /* @__PURE__ */ new Map();
|
|
570
520
|
leaseMs;
|
|
571
521
|
constructor(opts = {}) {
|
|
572
522
|
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
@@ -575,13 +525,59 @@ var InMemoryStore = class {
|
|
|
575
525
|
const list = this.facts.get(runId) ?? [];
|
|
576
526
|
list.push(fact);
|
|
577
527
|
this.facts.set(runId, list);
|
|
528
|
+
if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
|
|
529
|
+
const slot = this.keyByActiveRun.get(runId);
|
|
530
|
+
if (slot !== void 0) {
|
|
531
|
+
this.keyByActiveRun.delete(runId);
|
|
532
|
+
if (this.activeByKey.get(slot) === runId) {
|
|
533
|
+
this.activeByKey.delete(slot);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (fact.kind === "step.reset") {
|
|
538
|
+
const leasePrefix = `${runId}::${fact.stepId}::`;
|
|
539
|
+
for (const key of this.leases.keys()) {
|
|
540
|
+
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
541
|
+
}
|
|
542
|
+
this.outputs.delete(`${runId}::${fact.stepId}`);
|
|
543
|
+
}
|
|
578
544
|
}
|
|
579
|
-
async tryStartRun(runId, fact) {
|
|
580
|
-
if (this.facts.has(runId)) {
|
|
581
|
-
return { started: false };
|
|
545
|
+
async tryStartRun(runId, fact, concurrency) {
|
|
546
|
+
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
547
|
+
return { started: false, canceled: [] };
|
|
548
|
+
}
|
|
549
|
+
const canceled = [];
|
|
550
|
+
if (concurrency !== void 0) {
|
|
551
|
+
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
552
|
+
const priorRunId = this.activeByKey.get(slot);
|
|
553
|
+
if (priorRunId !== void 0) {
|
|
554
|
+
const cancelFact = {
|
|
555
|
+
kind: "flow.canceled",
|
|
556
|
+
cause: "concurrency",
|
|
557
|
+
runId: priorRunId,
|
|
558
|
+
at: fact.at,
|
|
559
|
+
canceledByRunId: runId,
|
|
560
|
+
concurrencyKey: concurrency.key
|
|
561
|
+
};
|
|
562
|
+
await this.appendFact(priorRunId, cancelFact);
|
|
563
|
+
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
564
|
+
}
|
|
565
|
+
this.activeByKey.set(slot, runId);
|
|
566
|
+
this.keyByActiveRun.set(runId, slot);
|
|
582
567
|
}
|
|
583
568
|
this.facts.set(runId, [fact]);
|
|
584
|
-
|
|
569
|
+
const parentRunId = fact.parent?.runId;
|
|
570
|
+
if (parentRunId !== void 0) {
|
|
571
|
+
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
572
|
+
set.add(runId);
|
|
573
|
+
this.childrenByParent.set(parentRunId, set);
|
|
574
|
+
}
|
|
575
|
+
return { started: true, canceled };
|
|
576
|
+
}
|
|
577
|
+
async listChildren(parentRunId) {
|
|
578
|
+
const set = this.childrenByParent.get(parentRunId);
|
|
579
|
+
if (set === void 0) return [];
|
|
580
|
+
return Array.from(set);
|
|
585
581
|
}
|
|
586
582
|
async loadRunState(runId) {
|
|
587
583
|
return projectRunState(runId, this.facts.get(runId) ?? []);
|
|
@@ -617,8 +613,10 @@ var InMemoryStore = class {
|
|
|
617
613
|
const result = await body(void 0);
|
|
618
614
|
if (result.fact.kind === "step.completed") {
|
|
619
615
|
await this.completeStep(runId, stepId, result.output, result.fact);
|
|
620
|
-
} else {
|
|
616
|
+
} else if (result.fact.kind === "step.failed") {
|
|
621
617
|
await this.failStep(runId, stepId, result.fact.error, result.fact);
|
|
618
|
+
} else {
|
|
619
|
+
await this.appendFact(runId, result.fact);
|
|
622
620
|
}
|
|
623
621
|
return result.output;
|
|
624
622
|
}
|
|
@@ -638,11 +636,172 @@ var InMemoryStore = class {
|
|
|
638
636
|
async appendGlobalFact(fact) {
|
|
639
637
|
this.globalFacts.push(fact);
|
|
640
638
|
}
|
|
641
|
-
/** Test-only: peek at the in-memory global fact log. */
|
|
642
639
|
readGlobalFacts() {
|
|
643
640
|
return this.globalFacts;
|
|
644
641
|
}
|
|
642
|
+
async queryRuns(opts) {
|
|
643
|
+
const where = opts.where ?? {};
|
|
644
|
+
const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
|
|
645
|
+
const matches = (summary) => {
|
|
646
|
+
if (where.flowId !== void 0 && summary.flowId !== where.flowId)
|
|
647
|
+
return false;
|
|
648
|
+
if (statuses !== void 0 && !statuses.includes(summary.status))
|
|
649
|
+
return false;
|
|
650
|
+
if (where.input !== void 0 && !containsJson(summary.input, where.input))
|
|
651
|
+
return false;
|
|
652
|
+
return true;
|
|
653
|
+
};
|
|
654
|
+
const summaries = [];
|
|
655
|
+
for (const [runId, factList] of this.facts) {
|
|
656
|
+
const summary = summarize(runId, factList);
|
|
657
|
+
if (summary === null) continue;
|
|
658
|
+
if (matches(summary)) summaries.push(summary);
|
|
659
|
+
}
|
|
660
|
+
for (const summary of this.summaries.values()) {
|
|
661
|
+
if (matches(summary)) summaries.push(summary);
|
|
662
|
+
}
|
|
663
|
+
summaries.sort((a, b) => {
|
|
664
|
+
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
665
|
+
if (t !== 0) return t;
|
|
666
|
+
return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
|
|
667
|
+
});
|
|
668
|
+
if (opts.latest === true) {
|
|
669
|
+
return { runs: summaries.slice(0, 1), cursor: null };
|
|
670
|
+
}
|
|
671
|
+
const limit = clampLimit(opts.limit);
|
|
672
|
+
let start = 0;
|
|
673
|
+
if (opts.cursor !== void 0) {
|
|
674
|
+
const c = decodeCursor(opts.cursor);
|
|
675
|
+
start = summaries.findIndex(
|
|
676
|
+
(s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
|
|
677
|
+
);
|
|
678
|
+
if (start === -1) start = summaries.length;
|
|
679
|
+
}
|
|
680
|
+
const page = summaries.slice(start, start + limit);
|
|
681
|
+
const hasMore = start + limit < summaries.length;
|
|
682
|
+
const last = page[page.length - 1];
|
|
683
|
+
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
684
|
+
return { runs: page, cursor };
|
|
685
|
+
}
|
|
686
|
+
async pruneFacts(opts) {
|
|
687
|
+
const olderThanMs = opts.olderThan.getTime();
|
|
688
|
+
const statusSet = new Set(opts.statuses);
|
|
689
|
+
const victims = [];
|
|
690
|
+
for (const [runId, factList] of this.facts) {
|
|
691
|
+
const summary = summarize(runId, factList);
|
|
692
|
+
if (summary === null) continue;
|
|
693
|
+
if (summary.completedAt === null) continue;
|
|
694
|
+
if (!statusSet.has(summary.status)) continue;
|
|
695
|
+
if (summary.completedAt.getTime() >= olderThanMs) continue;
|
|
696
|
+
const first = factList[0];
|
|
697
|
+
const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
|
|
698
|
+
victims.push({
|
|
699
|
+
runId,
|
|
700
|
+
summary,
|
|
701
|
+
factCount: factList.length,
|
|
702
|
+
parentRunId
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
let runsPruned = 0;
|
|
706
|
+
let factsPruned = 0;
|
|
707
|
+
for (const v of victims) {
|
|
708
|
+
this.facts.delete(v.runId);
|
|
709
|
+
deleteByRunPrefix(this.outputs, v.runId);
|
|
710
|
+
deleteByRunPrefix(this.onces, v.runId);
|
|
711
|
+
deleteByRunPrefix(this.leases, v.runId);
|
|
712
|
+
this.childrenByParent.delete(v.runId);
|
|
713
|
+
if (v.parentRunId !== void 0) {
|
|
714
|
+
const siblings = this.childrenByParent.get(v.parentRunId);
|
|
715
|
+
if (siblings !== void 0) {
|
|
716
|
+
siblings.delete(v.runId);
|
|
717
|
+
if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
if (opts.keepSummary) {
|
|
721
|
+
this.summaries.set(v.runId, v.summary);
|
|
722
|
+
} else {
|
|
723
|
+
this.summaries.delete(v.runId);
|
|
724
|
+
}
|
|
725
|
+
runsPruned += 1;
|
|
726
|
+
factsPruned += v.factCount;
|
|
727
|
+
}
|
|
728
|
+
return { runsPruned, factsPruned };
|
|
729
|
+
}
|
|
645
730
|
};
|
|
731
|
+
function deleteByRunPrefix(map, runId) {
|
|
732
|
+
const prefix = `${runId}::`;
|
|
733
|
+
for (const key of map.keys()) {
|
|
734
|
+
if (key.startsWith(prefix)) map.delete(key);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
function summarize(runId, facts) {
|
|
738
|
+
const first = facts[0];
|
|
739
|
+
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
740
|
+
const projected = projectRunState(runId, facts);
|
|
741
|
+
let completedAt = null;
|
|
742
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
743
|
+
const f = facts[i];
|
|
744
|
+
if (f === void 0) continue;
|
|
745
|
+
if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
|
|
746
|
+
completedAt = f.at;
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
runId,
|
|
752
|
+
flowId: first.flowId,
|
|
753
|
+
status: projected.status,
|
|
754
|
+
startedAt: first.at,
|
|
755
|
+
completedAt,
|
|
756
|
+
input: first.input
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
var DEFAULT_LIMIT = 50;
|
|
760
|
+
var MAX_LIMIT = 500;
|
|
761
|
+
function clampLimit(limit) {
|
|
762
|
+
if (limit === void 0) return DEFAULT_LIMIT;
|
|
763
|
+
if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
|
|
764
|
+
return Math.min(limit, MAX_LIMIT);
|
|
765
|
+
}
|
|
766
|
+
function encodeCursor(c) {
|
|
767
|
+
const bytes = new TextEncoder().encode(JSON.stringify(c));
|
|
768
|
+
let binary = "";
|
|
769
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
770
|
+
binary += String.fromCharCode(bytes[i]);
|
|
771
|
+
}
|
|
772
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
773
|
+
}
|
|
774
|
+
function decodeCursor(s) {
|
|
775
|
+
try {
|
|
776
|
+
const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
777
|
+
const binary = atob(b64);
|
|
778
|
+
const bytes = new Uint8Array(binary.length);
|
|
779
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
780
|
+
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
781
|
+
if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
|
|
782
|
+
return parsed;
|
|
783
|
+
}
|
|
784
|
+
throw new Error("malformed cursor body");
|
|
785
|
+
} catch (err) {
|
|
786
|
+
throw new Error(
|
|
787
|
+
`queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
function containsJson(haystack, needle) {
|
|
792
|
+
if (Array.isArray(needle)) {
|
|
793
|
+
if (!Array.isArray(haystack)) return false;
|
|
794
|
+
return needle.every((n) => haystack.some((h) => containsJson(h, n)));
|
|
795
|
+
}
|
|
796
|
+
if (needle !== null && typeof needle === "object") {
|
|
797
|
+
if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
|
|
798
|
+
return false;
|
|
799
|
+
return Object.entries(needle).every(
|
|
800
|
+
([k, v]) => k in haystack && containsJson(haystack[k], v)
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
return haystack === needle;
|
|
804
|
+
}
|
|
646
805
|
function projectRunState(runId, facts) {
|
|
647
806
|
let flowId = "";
|
|
648
807
|
let status = "pending";
|
|
@@ -663,6 +822,9 @@ function projectRunState(runId, facts) {
|
|
|
663
822
|
case "flow.failed":
|
|
664
823
|
status = "failed";
|
|
665
824
|
break;
|
|
825
|
+
case "flow.canceled":
|
|
826
|
+
status = "canceled";
|
|
827
|
+
break;
|
|
666
828
|
case "step.started":
|
|
667
829
|
steps[fact.stepId] = {
|
|
668
830
|
stepId: fact.stepId,
|
|
@@ -686,6 +848,14 @@ function projectRunState(runId, facts) {
|
|
|
686
848
|
error: fact.error
|
|
687
849
|
};
|
|
688
850
|
break;
|
|
851
|
+
case "step.canceled":
|
|
852
|
+
steps[fact.stepId] = {
|
|
853
|
+
stepId: fact.stepId,
|
|
854
|
+
status: "canceled",
|
|
855
|
+
attempts: fact.attempt,
|
|
856
|
+
...fact.error !== void 0 ? { error: fact.error } : {}
|
|
857
|
+
};
|
|
858
|
+
break;
|
|
689
859
|
case "step.skipped":
|
|
690
860
|
steps[fact.stepId] = {
|
|
691
861
|
stepId: fact.stepId,
|
|
@@ -693,6 +863,9 @@ function projectRunState(runId, facts) {
|
|
|
693
863
|
attempts: 0
|
|
694
864
|
};
|
|
695
865
|
break;
|
|
866
|
+
case "step.reset":
|
|
867
|
+
delete steps[fact.stepId];
|
|
868
|
+
break;
|
|
696
869
|
}
|
|
697
870
|
}
|
|
698
871
|
return {
|
|
@@ -796,7 +969,6 @@ var InMemoryClock = class {
|
|
|
796
969
|
}, delay);
|
|
797
970
|
this.timers.set(key, handle);
|
|
798
971
|
}
|
|
799
|
-
/** Clear any pending scheduled timers. Call from test teardown. */
|
|
800
972
|
dispose() {
|
|
801
973
|
for (const t of this.timers.values()) clearTimeout(t);
|
|
802
974
|
this.timers.clear();
|
|
@@ -810,10 +982,6 @@ var InMemoryTrigger = class {
|
|
|
810
982
|
this.handlers = this.handlers.filter((h) => h !== handler);
|
|
811
983
|
};
|
|
812
984
|
}
|
|
813
|
-
/**
|
|
814
|
-
* Test-only: synchronously dispatch a wake-up to all subscribers.
|
|
815
|
-
* Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
|
|
816
|
-
*/
|
|
817
985
|
fire(runId) {
|
|
818
986
|
for (const h of this.handlers) h(runId);
|
|
819
987
|
}
|
|
@@ -823,8 +991,11 @@ var InMemoryTrigger = class {
|
|
|
823
991
|
function makeIdempotencyKey(runId, stepId) {
|
|
824
992
|
return (scope) => `nagi:${runId}:${stepId}:${scope}`;
|
|
825
993
|
}
|
|
826
|
-
function makeOnce(
|
|
827
|
-
|
|
994
|
+
function makeOnce({
|
|
995
|
+
runId,
|
|
996
|
+
stepId,
|
|
997
|
+
store
|
|
998
|
+
}) {
|
|
828
999
|
return async function once(scope, fn) {
|
|
829
1000
|
const cached = await store.getOnce(runId, stepId, scope);
|
|
830
1001
|
if (cached !== null) return cached;
|
|
@@ -873,19 +1044,31 @@ function nextRunnable(args) {
|
|
|
873
1044
|
}
|
|
874
1045
|
function checkUpstream(def, runState) {
|
|
875
1046
|
for (const upstream of Object.values(def.needs)) {
|
|
876
|
-
if (!upstream || typeof upstream !== "object" || !("id" in upstream) || typeof upstream.id !== "string") {
|
|
877
|
-
continue;
|
|
878
|
-
}
|
|
879
1047
|
const upstreamState = runState.steps[upstream.id];
|
|
880
1048
|
if (upstreamState === void 0) return "blocked";
|
|
881
1049
|
if (upstreamState.status === "completed") continue;
|
|
882
|
-
if (upstreamState.status === "skipped"
|
|
1050
|
+
if (upstreamState.status === "skipped") {
|
|
1051
|
+
if (manualSkipCascade(upstream.id, runState) === "continue") continue;
|
|
1052
|
+
return "transitive-skip";
|
|
1053
|
+
}
|
|
1054
|
+
if (upstreamState.status === "failed") {
|
|
883
1055
|
return "transitive-skip";
|
|
884
1056
|
}
|
|
885
1057
|
return "blocked";
|
|
886
1058
|
}
|
|
887
1059
|
return "ready";
|
|
888
1060
|
}
|
|
1061
|
+
function manualSkipCascade(stepId, runState) {
|
|
1062
|
+
for (let i = runState.facts.length - 1; i >= 0; i--) {
|
|
1063
|
+
const f = runState.facts[i];
|
|
1064
|
+
if (f === void 0) continue;
|
|
1065
|
+
if (f.kind !== "step.skipped") continue;
|
|
1066
|
+
if (f.stepId !== stepId) continue;
|
|
1067
|
+
if (f.reason !== "manual") return "skip";
|
|
1068
|
+
return f.cascade ?? "skip";
|
|
1069
|
+
}
|
|
1070
|
+
return "skip";
|
|
1071
|
+
}
|
|
889
1072
|
function checkParentMatch(def, runState) {
|
|
890
1073
|
if (!def.parentMatch) return "ready";
|
|
891
1074
|
const { matchId, armId } = def.parentMatch;
|
|
@@ -904,7 +1087,7 @@ function aggregateMatch(matchId, flow2, runState) {
|
|
|
904
1087
|
if (def.kind !== "match") return { kind: "pending" };
|
|
905
1088
|
const selected = readSelectedArm(matchId, runState);
|
|
906
1089
|
if (selected === null) return { kind: "pending" };
|
|
907
|
-
const arm = def.
|
|
1090
|
+
const arm = def.arms.find((a) => a.id === selected);
|
|
908
1091
|
if (!arm) return { kind: "pending" };
|
|
909
1092
|
const output = {};
|
|
910
1093
|
let allTerminal = true;
|
|
@@ -937,6 +1120,105 @@ function flowTermination(flow2, runState) {
|
|
|
937
1120
|
}
|
|
938
1121
|
return { done, failed };
|
|
939
1122
|
}
|
|
1123
|
+
function nextTransition(flow2, runState) {
|
|
1124
|
+
const promotions = readyPromotions(flow2, runState);
|
|
1125
|
+
if (promotions.length > 0) return { kind: "promote-match", promotions };
|
|
1126
|
+
const term = flowTermination(flow2, runState);
|
|
1127
|
+
if (term.done) {
|
|
1128
|
+
if (isFlowTerminal(runState.facts)) return { kind: "settled" };
|
|
1129
|
+
if (term.failed) return { kind: "fail", error: flowFailureError(runState) };
|
|
1130
|
+
return { kind: "complete", output: computeFlowOutput(flow2, runState) };
|
|
1131
|
+
}
|
|
1132
|
+
const input = extractInput(runState);
|
|
1133
|
+
const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
|
|
1134
|
+
if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
|
|
1135
|
+
if (skip.length > 0) return { kind: "skip", skip };
|
|
1136
|
+
return { kind: "waiting" };
|
|
1137
|
+
}
|
|
1138
|
+
function readyPromotions(flow2, runState) {
|
|
1139
|
+
const out = [];
|
|
1140
|
+
for (const [matchId, step] of Object.entries(flow2.steps)) {
|
|
1141
|
+
const def = getDef(step);
|
|
1142
|
+
if (def.kind !== "match") continue;
|
|
1143
|
+
const state = runState.steps[matchId];
|
|
1144
|
+
if (state?.status !== "running") continue;
|
|
1145
|
+
const agg = aggregateMatch(matchId, flow2, runState);
|
|
1146
|
+
if (agg.kind === "pending") continue;
|
|
1147
|
+
const attempt = state.attempts > 0 ? state.attempts : 1;
|
|
1148
|
+
if (agg.kind === "fail-fast") {
|
|
1149
|
+
const failedNested = runState.steps[agg.failedStepId];
|
|
1150
|
+
const error = failedNested?.error ?? {
|
|
1151
|
+
name: "Error",
|
|
1152
|
+
message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
|
|
1153
|
+
};
|
|
1154
|
+
out.push({
|
|
1155
|
+
matchId,
|
|
1156
|
+
attempt,
|
|
1157
|
+
result: { kind: "fail", error }
|
|
1158
|
+
});
|
|
1159
|
+
} else {
|
|
1160
|
+
out.push({
|
|
1161
|
+
matchId,
|
|
1162
|
+
attempt,
|
|
1163
|
+
result: { kind: "complete", output: agg.output }
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
return out;
|
|
1168
|
+
}
|
|
1169
|
+
function flowFailureError(runState) {
|
|
1170
|
+
const failedStep = Object.values(runState.steps).find(
|
|
1171
|
+
(s) => s.status === "failed"
|
|
1172
|
+
);
|
|
1173
|
+
return failedStep?.error ?? { name: "Error", message: "step failed" };
|
|
1174
|
+
}
|
|
1175
|
+
function isFlowTerminal(facts) {
|
|
1176
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1177
|
+
const f = facts[i];
|
|
1178
|
+
if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
|
|
1179
|
+
return true;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return false;
|
|
1183
|
+
}
|
|
1184
|
+
function computeFlowOutput(flow2, runState) {
|
|
1185
|
+
if (flow2.output === void 0) return null;
|
|
1186
|
+
const stepOutputs = {};
|
|
1187
|
+
for (const [sid, sstate] of Object.entries(runState.steps)) {
|
|
1188
|
+
if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
|
|
1189
|
+
}
|
|
1190
|
+
return flow2.output(stepOutputs);
|
|
1191
|
+
}
|
|
1192
|
+
function descendantsOf(flow2, stepId) {
|
|
1193
|
+
const children = /* @__PURE__ */ new Map();
|
|
1194
|
+
const addEdge = (from, to) => {
|
|
1195
|
+
const bucket = children.get(from);
|
|
1196
|
+
if (bucket) bucket.push(to);
|
|
1197
|
+
else children.set(from, [to]);
|
|
1198
|
+
};
|
|
1199
|
+
for (const [id, step] of Object.entries(flow2.steps)) {
|
|
1200
|
+
const def = getDef(step);
|
|
1201
|
+
for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
|
|
1202
|
+
if (def.kind === "match") {
|
|
1203
|
+
for (const arm of def.arms) {
|
|
1204
|
+
for (const armStepId of arm.stepIds) addEdge(id, armStepId);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
const out = [stepId];
|
|
1209
|
+
const seen = /* @__PURE__ */ new Set([stepId]);
|
|
1210
|
+
for (let i = 0; i < out.length; i++) {
|
|
1211
|
+
const current = out[i];
|
|
1212
|
+
if (current === void 0) continue;
|
|
1213
|
+
for (const child of children.get(current) ?? []) {
|
|
1214
|
+
if (seen.has(child)) continue;
|
|
1215
|
+
if (!(child in flow2.steps)) continue;
|
|
1216
|
+
seen.add(child);
|
|
1217
|
+
out.push(child);
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
return out;
|
|
1221
|
+
}
|
|
940
1222
|
function extractInput(runState) {
|
|
941
1223
|
for (const fact of runState.facts) {
|
|
942
1224
|
if (fact.kind === "flow.started") return fact.input;
|
|
@@ -980,6 +1262,10 @@ async function dispatchMessage(deps, message) {
|
|
|
980
1262
|
}
|
|
981
1263
|
const def = getDef(step);
|
|
982
1264
|
const preState = await store.loadRunState(runId);
|
|
1265
|
+
if (preState.status === "canceled") {
|
|
1266
|
+
await queue.ack(message.receipt);
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
983
1269
|
const preStep = preState.steps[stepId];
|
|
984
1270
|
if (preStep && (preStep.status === "completed" || preStep.status === "failed" || preStep.status === "skipped")) {
|
|
985
1271
|
await queue.ack(message.receipt);
|
|
@@ -997,7 +1283,7 @@ async function dispatchMessage(deps, message) {
|
|
|
997
1283
|
attempt,
|
|
998
1284
|
at: clock.now()
|
|
999
1285
|
});
|
|
1000
|
-
const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1286
|
+
const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1001
1287
|
const startEvent = {
|
|
1002
1288
|
runId,
|
|
1003
1289
|
flowId: flow2.id,
|
|
@@ -1013,7 +1299,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1013
1299
|
const startedAt = Date.now();
|
|
1014
1300
|
try {
|
|
1015
1301
|
if (def.kind === "task") {
|
|
1016
|
-
const output = await executeTask({
|
|
1302
|
+
const { output, skipAdvance } = await executeTask({
|
|
1017
1303
|
deps,
|
|
1018
1304
|
message,
|
|
1019
1305
|
def,
|
|
@@ -1021,6 +1307,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1021
1307
|
stepId,
|
|
1022
1308
|
attempt
|
|
1023
1309
|
});
|
|
1310
|
+
if (skipAdvance) return;
|
|
1024
1311
|
const completeEvent = {
|
|
1025
1312
|
runId,
|
|
1026
1313
|
flowId: flow2.id,
|
|
@@ -1045,6 +1332,10 @@ async function dispatchMessage(deps, message) {
|
|
|
1045
1332
|
} else if (def.kind === "match") {
|
|
1046
1333
|
await executeMatch({ deps, message, def, runId, stepId, attempt });
|
|
1047
1334
|
await advance(deps, runId);
|
|
1335
|
+
} else if (def.kind === "subflow") {
|
|
1336
|
+
await executeSubflow({ deps, message, def, runId, stepId });
|
|
1337
|
+
await queue.ack(message.receipt);
|
|
1338
|
+
return;
|
|
1048
1339
|
}
|
|
1049
1340
|
} catch (err) {
|
|
1050
1341
|
await handleStepError({
|
|
@@ -1068,35 +1359,142 @@ async function executeTask(args) {
|
|
|
1068
1359
|
const runState = await store.loadRunState(runId);
|
|
1069
1360
|
const input = extractInput(runState);
|
|
1070
1361
|
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1071
|
-
const
|
|
1362
|
+
const ac = new AbortController();
|
|
1363
|
+
const watcher = startCancelWatcher({
|
|
1364
|
+
store,
|
|
1072
1365
|
runId,
|
|
1073
1366
|
stepId,
|
|
1074
1367
|
attempt,
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1368
|
+
ac,
|
|
1369
|
+
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
1370
|
+
});
|
|
1371
|
+
try {
|
|
1372
|
+
let stepAbortedHere = false;
|
|
1373
|
+
const output = await store.runStep(
|
|
1374
|
+
runId,
|
|
1375
|
+
stepId,
|
|
1376
|
+
attempt,
|
|
1377
|
+
async (tx) => {
|
|
1378
|
+
const ctx = makeStepCtx({
|
|
1379
|
+
runId,
|
|
1380
|
+
stepId,
|
|
1381
|
+
attempt,
|
|
1382
|
+
input,
|
|
1383
|
+
store,
|
|
1384
|
+
clock,
|
|
1385
|
+
tx,
|
|
1386
|
+
signal: ac.signal,
|
|
1387
|
+
...deps.logger !== void 0 ? { logger: deps.logger } : {}
|
|
1388
|
+
});
|
|
1389
|
+
const out = await def.run({ input, needs, ctx });
|
|
1390
|
+
const postState = await store.loadRunState(runId);
|
|
1391
|
+
if (postState.status === "canceled") {
|
|
1392
|
+
const canceledFact = {
|
|
1393
|
+
kind: "step.canceled",
|
|
1394
|
+
runId,
|
|
1395
|
+
stepId,
|
|
1396
|
+
attempt,
|
|
1397
|
+
at: clock.now()
|
|
1398
|
+
};
|
|
1399
|
+
return { output: out, fact: canceledFact };
|
|
1400
|
+
}
|
|
1401
|
+
if (hasAbortRequest(postState.facts, stepId, attempt)) {
|
|
1402
|
+
stepAbortedHere = true;
|
|
1403
|
+
const canceledFact = {
|
|
1404
|
+
kind: "step.canceled",
|
|
1405
|
+
runId,
|
|
1406
|
+
stepId,
|
|
1407
|
+
attempt,
|
|
1408
|
+
at: clock.now()
|
|
1409
|
+
};
|
|
1410
|
+
return { output: out, fact: canceledFact };
|
|
1411
|
+
}
|
|
1412
|
+
const fact = {
|
|
1413
|
+
kind: "step.completed",
|
|
1414
|
+
runId,
|
|
1415
|
+
stepId,
|
|
1416
|
+
attempt,
|
|
1417
|
+
output: out,
|
|
1418
|
+
at: clock.now()
|
|
1419
|
+
};
|
|
1420
|
+
return { output: out, fact };
|
|
1421
|
+
}
|
|
1422
|
+
);
|
|
1423
|
+
await queue.ack(message.receipt);
|
|
1424
|
+
return { output, skipAdvance: stepAbortedHere };
|
|
1425
|
+
} finally {
|
|
1426
|
+
watcher.stop();
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1430
|
+
function startCancelWatcher(args) {
|
|
1431
|
+
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
1432
|
+
let stopped = false;
|
|
1433
|
+
void (async () => {
|
|
1434
|
+
while (!stopped) {
|
|
1435
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
1436
|
+
if (stopped) return;
|
|
1437
|
+
try {
|
|
1438
|
+
const s = await store.loadRunState(runId);
|
|
1439
|
+
if (s.status === "canceled" || s.status === "failed" || s.status === "completed") {
|
|
1440
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
if (hasAbortRequest(s.facts, stepId, attempt)) {
|
|
1444
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
} catch {
|
|
1448
|
+
}
|
|
1096
1449
|
}
|
|
1097
|
-
);
|
|
1098
|
-
|
|
1099
|
-
|
|
1450
|
+
})();
|
|
1451
|
+
return {
|
|
1452
|
+
stop: () => {
|
|
1453
|
+
stopped = true;
|
|
1454
|
+
}
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
function hasAbortRequest(facts, stepId, attempt) {
|
|
1458
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1459
|
+
const f = facts[i];
|
|
1460
|
+
if (f === void 0) continue;
|
|
1461
|
+
if (f.kind === "step.reset" && f.stepId === stepId) return false;
|
|
1462
|
+
if (f.kind === "step.abort-requested" && f.stepId === stepId && f.attempt === attempt) {
|
|
1463
|
+
return true;
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
return false;
|
|
1467
|
+
}
|
|
1468
|
+
var NagiAbortError = class extends Error {
|
|
1469
|
+
runId;
|
|
1470
|
+
scope;
|
|
1471
|
+
constructor(runId, scope) {
|
|
1472
|
+
super(
|
|
1473
|
+
scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
1474
|
+
);
|
|
1475
|
+
this.name = "NagiAbortError";
|
|
1476
|
+
this.runId = runId;
|
|
1477
|
+
this.scope = scope;
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
async function executeSubflow(args) {
|
|
1481
|
+
const { deps, message, def, runId, stepId } = args;
|
|
1482
|
+
const { store } = deps;
|
|
1483
|
+
const child = deps.lookupFlow(def.childFlowId);
|
|
1484
|
+
if (child === void 0) {
|
|
1485
|
+
throw new Error(
|
|
1486
|
+
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
1487
|
+
);
|
|
1488
|
+
}
|
|
1489
|
+
const runState = await store.loadRunState(runId);
|
|
1490
|
+
const parentInput = extractInput(runState);
|
|
1491
|
+
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1492
|
+
const childInput = def.buildInput({ input: parentInput, needs });
|
|
1493
|
+
await deps.startChildRun({
|
|
1494
|
+
child,
|
|
1495
|
+
childInput,
|
|
1496
|
+
parent: { runId, stepId, attempt: message.attempt }
|
|
1497
|
+
});
|
|
1100
1498
|
}
|
|
1101
1499
|
async function executeMatch(args) {
|
|
1102
1500
|
const { deps, message, def, runId, stepId } = args;
|
|
@@ -1118,6 +1516,24 @@ async function handleStepError(args) {
|
|
|
1118
1516
|
const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
|
|
1119
1517
|
const { store, queue, clock } = deps;
|
|
1120
1518
|
const error = serializeError(err);
|
|
1519
|
+
const postState = await store.loadRunState(runId);
|
|
1520
|
+
const runIsCanceled = postState.status === "canceled";
|
|
1521
|
+
const stepAborted = hasAbortRequest(postState.facts, stepId, attempt);
|
|
1522
|
+
if (runIsCanceled || stepAborted) {
|
|
1523
|
+
const isAbort = err instanceof NagiAbortError || err instanceof Error && err.name === "AbortError";
|
|
1524
|
+
const canceledFact = {
|
|
1525
|
+
kind: "step.canceled",
|
|
1526
|
+
runId,
|
|
1527
|
+
stepId,
|
|
1528
|
+
attempt,
|
|
1529
|
+
...isAbort ? { error } : {},
|
|
1530
|
+
at: clock.now()
|
|
1531
|
+
};
|
|
1532
|
+
await store.appendFact(runId, canceledFact);
|
|
1533
|
+
await queue.ack(message.receipt);
|
|
1534
|
+
if (!stepAborted) await advance(deps, runId);
|
|
1535
|
+
return;
|
|
1536
|
+
}
|
|
1121
1537
|
const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
|
|
1122
1538
|
const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
|
|
1123
1539
|
if (shouldRetry) {
|
|
@@ -1173,46 +1589,31 @@ async function handleStepError(args) {
|
|
|
1173
1589
|
}
|
|
1174
1590
|
var MAX_ADVANCE_ITERS = 1024;
|
|
1175
1591
|
async function advance(deps, runId) {
|
|
1176
|
-
const { store, queue
|
|
1592
|
+
const { store, queue } = deps;
|
|
1177
1593
|
const flow2 = await deps.flowFor(runId);
|
|
1178
1594
|
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
1179
1595
|
const runState = await store.loadRunState(runId);
|
|
1180
|
-
const
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
if (decision.skip.length === 0 && decision.runnable.length === 0) return;
|
|
1202
|
-
for (const { stepId, reason } of decision.skip) {
|
|
1203
|
-
await store.appendFact(runId, {
|
|
1204
|
-
kind: "step.skipped",
|
|
1205
|
-
runId,
|
|
1206
|
-
stepId,
|
|
1207
|
-
reason,
|
|
1208
|
-
at: clock.now()
|
|
1209
|
-
});
|
|
1210
|
-
}
|
|
1211
|
-
for (const stepId of decision.runnable) {
|
|
1212
|
-
await queue.enqueue(runId, stepId);
|
|
1213
|
-
}
|
|
1214
|
-
if (decision.runnable.length > 0) {
|
|
1215
|
-
return;
|
|
1596
|
+
const t = nextTransition(flow2, runState);
|
|
1597
|
+
switch (t.kind) {
|
|
1598
|
+
case "settled":
|
|
1599
|
+
case "waiting":
|
|
1600
|
+
return;
|
|
1601
|
+
case "complete":
|
|
1602
|
+
await finalizeFlowCompletion({ deps, flow: flow2, runId, output: t.output });
|
|
1603
|
+
return;
|
|
1604
|
+
case "fail":
|
|
1605
|
+
await finalizeFlowFailure({ deps, flow: flow2, runId, error: t.error });
|
|
1606
|
+
return;
|
|
1607
|
+
case "dispatch":
|
|
1608
|
+
await recordSkips(deps, runId, t.skip);
|
|
1609
|
+
for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
|
|
1610
|
+
return;
|
|
1611
|
+
case "skip":
|
|
1612
|
+
await recordSkips(deps, runId, t.skip);
|
|
1613
|
+
continue;
|
|
1614
|
+
case "promote-match":
|
|
1615
|
+
await applyPromotions(deps, flow2, runState, t.promotions);
|
|
1616
|
+
continue;
|
|
1216
1617
|
}
|
|
1217
1618
|
}
|
|
1218
1619
|
const cycleError = {
|
|
@@ -1224,93 +1625,92 @@ async function advance(deps, runId) {
|
|
|
1224
1625
|
await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
|
|
1225
1626
|
}
|
|
1226
1627
|
}
|
|
1227
|
-
async function
|
|
1228
|
-
const { deps, flow: flow2, runState } = args;
|
|
1628
|
+
async function recordSkips(deps, runId, skip) {
|
|
1229
1629
|
const { store, clock } = deps;
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1630
|
+
for (const { stepId, reason } of skip) {
|
|
1631
|
+
await store.appendFact(runId, {
|
|
1632
|
+
kind: "step.skipped",
|
|
1633
|
+
runId,
|
|
1634
|
+
stepId,
|
|
1635
|
+
reason,
|
|
1636
|
+
at: clock.now()
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
async function markStepComplete(args) {
|
|
1641
|
+
const { deps, flow: flow2, runId, stepId, attempt, kind, output } = args;
|
|
1642
|
+
const at = deps.clock.now();
|
|
1643
|
+
const fact = {
|
|
1644
|
+
kind: "step.completed",
|
|
1645
|
+
runId,
|
|
1646
|
+
stepId,
|
|
1647
|
+
attempt,
|
|
1648
|
+
output,
|
|
1649
|
+
at
|
|
1650
|
+
};
|
|
1651
|
+
await deps.store.completeStep(runId, stepId, output, fact);
|
|
1652
|
+
await fireHook(
|
|
1653
|
+
deps.hooks?.onStepComplete,
|
|
1654
|
+
{
|
|
1655
|
+
runId,
|
|
1656
|
+
flowId: flow2.id,
|
|
1657
|
+
stepId,
|
|
1658
|
+
attempt,
|
|
1659
|
+
kind,
|
|
1660
|
+
output,
|
|
1661
|
+
durationMs: 0,
|
|
1662
|
+
at
|
|
1663
|
+
},
|
|
1664
|
+
"onStepComplete",
|
|
1665
|
+
deps
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
async function markStepFail(args) {
|
|
1669
|
+
const { deps, flow: flow2, runId, stepId, attempt, kind, error } = args;
|
|
1670
|
+
const at = deps.clock.now();
|
|
1671
|
+
const fact = { kind: "step.failed", runId, stepId, attempt, error, at };
|
|
1672
|
+
await deps.store.failStep(runId, stepId, error, fact);
|
|
1673
|
+
await fireHook(
|
|
1674
|
+
deps.hooks?.onStepError,
|
|
1675
|
+
{ runId, flowId: flow2.id, stepId, attempt, kind, error, at },
|
|
1676
|
+
"onStepError",
|
|
1677
|
+
deps
|
|
1678
|
+
);
|
|
1679
|
+
}
|
|
1680
|
+
async function applyPromotions(deps, flow2, runState, promotions) {
|
|
1681
|
+
for (const { matchId, attempt, result } of promotions) {
|
|
1682
|
+
if (result.kind === "fail") {
|
|
1683
|
+
await markStepFail({
|
|
1684
|
+
deps,
|
|
1685
|
+
flow: flow2,
|
|
1247
1686
|
runId: runState.runId,
|
|
1248
1687
|
stepId: matchId,
|
|
1249
1688
|
attempt,
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
};
|
|
1253
|
-
|
|
1254
|
-
await
|
|
1255
|
-
deps
|
|
1256
|
-
|
|
1257
|
-
runId: runState.runId,
|
|
1258
|
-
flowId: flow2.id,
|
|
1259
|
-
stepId: matchId,
|
|
1260
|
-
attempt,
|
|
1261
|
-
kind: "match",
|
|
1262
|
-
error,
|
|
1263
|
-
at: clock.now()
|
|
1264
|
-
},
|
|
1265
|
-
"onStepError",
|
|
1266
|
-
deps
|
|
1267
|
-
);
|
|
1268
|
-
promoted = true;
|
|
1269
|
-
continue;
|
|
1270
|
-
}
|
|
1271
|
-
const fact = {
|
|
1272
|
-
kind: "step.completed",
|
|
1273
|
-
runId: runState.runId,
|
|
1274
|
-
stepId: matchId,
|
|
1275
|
-
attempt,
|
|
1276
|
-
output: agg.output,
|
|
1277
|
-
at: clock.now()
|
|
1278
|
-
};
|
|
1279
|
-
await store.completeStep(runState.runId, matchId, agg.output, fact);
|
|
1280
|
-
await fireHook(
|
|
1281
|
-
deps.hooks?.onStepComplete,
|
|
1282
|
-
{
|
|
1689
|
+
kind: "match",
|
|
1690
|
+
error: result.error
|
|
1691
|
+
});
|
|
1692
|
+
} else {
|
|
1693
|
+
await markStepComplete({
|
|
1694
|
+
deps,
|
|
1695
|
+
flow: flow2,
|
|
1283
1696
|
runId: runState.runId,
|
|
1284
|
-
flowId: flow2.id,
|
|
1285
1697
|
stepId: matchId,
|
|
1286
1698
|
attempt,
|
|
1287
1699
|
kind: "match",
|
|
1288
|
-
output:
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
},
|
|
1292
|
-
"onStepComplete",
|
|
1293
|
-
deps
|
|
1294
|
-
);
|
|
1295
|
-
promoted = true;
|
|
1700
|
+
output: result.output
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1296
1703
|
}
|
|
1297
|
-
return promoted;
|
|
1298
1704
|
}
|
|
1299
1705
|
function makeStepCtx(args) {
|
|
1300
|
-
const { runId, stepId, attempt, input, store, clock, tx } = args;
|
|
1301
|
-
const ac = new AbortController();
|
|
1706
|
+
const { runId, stepId, attempt, input, store, clock, tx, signal } = args;
|
|
1302
1707
|
return {
|
|
1303
1708
|
input,
|
|
1304
1709
|
runId,
|
|
1305
1710
|
stepId,
|
|
1306
1711
|
attempt,
|
|
1307
|
-
signal
|
|
1712
|
+
signal,
|
|
1308
1713
|
now: () => clock.now(),
|
|
1309
|
-
// `tx` is supplied by `Store.runStep` — for adapters with no real
|
|
1310
|
-
// transaction (in-memory) it is `undefined as Tx`, and handlers that
|
|
1311
|
-
// touch `ctx.tx` will throw on the first call. Adapters that need
|
|
1312
|
-
// typed transactional clients (e.g. `@nagi-js/postgres`) augment
|
|
1313
|
-
// `Register.tx` and pass a real Kysely transaction here.
|
|
1314
1714
|
tx,
|
|
1315
1715
|
logger: args.logger ?? consoleLogger(),
|
|
1316
1716
|
once: makeOnce({ runId, stepId, store }),
|
|
@@ -1341,10 +1741,6 @@ function retryAllows(policy, err) {
|
|
|
1341
1741
|
if (!policy.retryOn) return true;
|
|
1342
1742
|
return policy.retryOn(err);
|
|
1343
1743
|
}
|
|
1344
|
-
function isFlowTerminal(facts) {
|
|
1345
|
-
const last = facts[facts.length - 1];
|
|
1346
|
-
return last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
|
|
1347
|
-
}
|
|
1348
1744
|
async function finalizeFlowFailure(args) {
|
|
1349
1745
|
const { deps, flow: flow2, runId, error } = args;
|
|
1350
1746
|
const { store, clock } = deps;
|
|
@@ -1357,11 +1753,11 @@ async function finalizeFlowFailure(args) {
|
|
|
1357
1753
|
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
1358
1754
|
await fireHook(flow2.onError, event, "flow.onError", deps);
|
|
1359
1755
|
await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
|
|
1756
|
+
await propagateToParent(deps, runId, { kind: "failed", error });
|
|
1360
1757
|
}
|
|
1361
1758
|
async function finalizeFlowCompletion(args) {
|
|
1362
|
-
const { deps, flow: flow2, runId,
|
|
1759
|
+
const { deps, flow: flow2, runId, output } = args;
|
|
1363
1760
|
const { store, clock } = deps;
|
|
1364
|
-
const output = computeFlowOutput(flow2, runState);
|
|
1365
1761
|
await store.appendFact(runId, {
|
|
1366
1762
|
kind: "flow.completed",
|
|
1367
1763
|
runId,
|
|
@@ -1371,14 +1767,67 @@ async function finalizeFlowCompletion(args) {
|
|
|
1371
1767
|
const event = { runId, flowId: flow2.id, output, at: clock.now() };
|
|
1372
1768
|
await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
|
|
1373
1769
|
await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
|
|
1770
|
+
await propagateToParent(deps, runId, { kind: "completed", output });
|
|
1374
1771
|
}
|
|
1375
|
-
function
|
|
1376
|
-
|
|
1377
|
-
const
|
|
1378
|
-
|
|
1379
|
-
|
|
1772
|
+
async function propagateToParent(deps, childRunId, outcome) {
|
|
1773
|
+
const { store } = deps;
|
|
1774
|
+
const childState = await store.loadRunState(childRunId);
|
|
1775
|
+
const startedFact = childState.facts.find((f) => f.kind === "flow.started");
|
|
1776
|
+
if (startedFact?.parent === void 0) {
|
|
1777
|
+
return;
|
|
1380
1778
|
}
|
|
1381
|
-
|
|
1779
|
+
const { runId: parentRunId, stepId: parentStepId } = startedFact.parent;
|
|
1780
|
+
const parentState = await store.loadRunState(parentRunId);
|
|
1781
|
+
if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
|
|
1782
|
+
deps.logger?.info(
|
|
1783
|
+
"nagi: subflow wake skipped \u2014 parent run already terminal",
|
|
1784
|
+
{
|
|
1785
|
+
parentRunId,
|
|
1786
|
+
parentStepId,
|
|
1787
|
+
childRunId,
|
|
1788
|
+
parentStatus: parentState.status
|
|
1789
|
+
}
|
|
1790
|
+
);
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
const parentStep = parentState.steps[parentStepId];
|
|
1794
|
+
if (parentStep?.status !== "running") {
|
|
1795
|
+
deps.logger?.info("nagi: subflow wake skipped \u2014 parent step not running", {
|
|
1796
|
+
parentRunId,
|
|
1797
|
+
parentStepId,
|
|
1798
|
+
childRunId,
|
|
1799
|
+
parentStepStatus: parentStep?.status ?? "missing"
|
|
1800
|
+
});
|
|
1801
|
+
return;
|
|
1802
|
+
}
|
|
1803
|
+
const attempt = parentStep.attempts > 0 ? parentStep.attempts : 1;
|
|
1804
|
+
const parentFlow = await deps.flowFor(parentRunId);
|
|
1805
|
+
if (outcome.kind === "completed") {
|
|
1806
|
+
const subflowOutput = {
|
|
1807
|
+
childRunId,
|
|
1808
|
+
output: outcome.output
|
|
1809
|
+
};
|
|
1810
|
+
await markStepComplete({
|
|
1811
|
+
deps,
|
|
1812
|
+
flow: parentFlow,
|
|
1813
|
+
runId: parentRunId,
|
|
1814
|
+
stepId: parentStepId,
|
|
1815
|
+
attempt,
|
|
1816
|
+
kind: "subflow",
|
|
1817
|
+
output: subflowOutput
|
|
1818
|
+
});
|
|
1819
|
+
} else {
|
|
1820
|
+
await markStepFail({
|
|
1821
|
+
deps,
|
|
1822
|
+
flow: parentFlow,
|
|
1823
|
+
runId: parentRunId,
|
|
1824
|
+
stepId: parentStepId,
|
|
1825
|
+
attempt,
|
|
1826
|
+
kind: "subflow",
|
|
1827
|
+
error: outcome.error
|
|
1828
|
+
});
|
|
1829
|
+
}
|
|
1830
|
+
await advance(deps, parentRunId);
|
|
1382
1831
|
}
|
|
1383
1832
|
function serializeError(err) {
|
|
1384
1833
|
if (err instanceof Error) {
|
|
@@ -1504,6 +1953,24 @@ var NagiRuntimeError = class extends Error {
|
|
|
1504
1953
|
this.name = "NagiRuntimeError";
|
|
1505
1954
|
}
|
|
1506
1955
|
};
|
|
1956
|
+
var NagiCanceledError = class extends Error {
|
|
1957
|
+
runId;
|
|
1958
|
+
canceledByRunId;
|
|
1959
|
+
concurrencyKey;
|
|
1960
|
+
constructor(args) {
|
|
1961
|
+
super(
|
|
1962
|
+
`Run ${args.runId} was canceled (superseded by run ${args.canceledByRunId} for concurrency key "${args.concurrencyKey}").`
|
|
1963
|
+
);
|
|
1964
|
+
this.name = "NagiCanceledError";
|
|
1965
|
+
this.runId = args.runId;
|
|
1966
|
+
this.canceledByRunId = args.canceledByRunId;
|
|
1967
|
+
this.concurrencyKey = args.concurrencyKey;
|
|
1968
|
+
this.cause = {
|
|
1969
|
+
canceledByRunId: args.canceledByRunId,
|
|
1970
|
+
concurrencyKey: args.concurrencyKey
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
};
|
|
1507
1974
|
var NagiSnapshotDriftError = class extends Error {
|
|
1508
1975
|
runId;
|
|
1509
1976
|
expected;
|
|
@@ -1518,8 +1985,9 @@ var NagiSnapshotDriftError = class extends Error {
|
|
|
1518
1985
|
this.actual = args.actual;
|
|
1519
1986
|
}
|
|
1520
1987
|
};
|
|
1521
|
-
async function
|
|
1988
|
+
async function nagiImpl(config) {
|
|
1522
1989
|
const clock = config.clock ?? new InMemoryClock();
|
|
1990
|
+
await config.queue.ensureSchema?.();
|
|
1523
1991
|
const flowsById = /* @__PURE__ */ new Map();
|
|
1524
1992
|
const flowHashById = /* @__PURE__ */ new Map();
|
|
1525
1993
|
for (const f of config.flows) {
|
|
@@ -1549,6 +2017,7 @@ async function nagi(config) {
|
|
|
1549
2017
|
});
|
|
1550
2018
|
}
|
|
1551
2019
|
}
|
|
2020
|
+
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
1552
2021
|
async function flowFor(runId) {
|
|
1553
2022
|
const runState = await config.store.loadRunState(runId);
|
|
1554
2023
|
const flow2 = flowsById.get(runState.flowId);
|
|
@@ -1559,8 +2028,180 @@ async function nagi(config) {
|
|
|
1559
2028
|
}
|
|
1560
2029
|
return flow2;
|
|
1561
2030
|
}
|
|
2031
|
+
function lookupFlow(flowId) {
|
|
2032
|
+
return flowsById.get(flowId);
|
|
2033
|
+
}
|
|
2034
|
+
async function startRunInternal(args) {
|
|
2035
|
+
const { flow: flow2, validatedInput, runId, parent } = args;
|
|
2036
|
+
const startedAt = clock.now();
|
|
2037
|
+
const flowHash = flowHashById.get(flow2.id);
|
|
2038
|
+
const fact = {
|
|
2039
|
+
kind: "flow.started",
|
|
2040
|
+
runId,
|
|
2041
|
+
flowId: flow2.id,
|
|
2042
|
+
input: validatedInput,
|
|
2043
|
+
at: startedAt,
|
|
2044
|
+
...flowHash !== void 0 ? { flowHash } : {},
|
|
2045
|
+
codeVersion,
|
|
2046
|
+
...parent !== void 0 ? { parent: { runId: parent.runId, stepId: parent.stepId } } : {}
|
|
2047
|
+
};
|
|
2048
|
+
let concurrencyArg;
|
|
2049
|
+
if (flow2.concurrency !== void 0) {
|
|
2050
|
+
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
2051
|
+
if (typeof derived !== "string" || derived.length === 0) {
|
|
2052
|
+
throw new NagiValidationError([
|
|
2053
|
+
{
|
|
2054
|
+
message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
2055
|
+
path: ["concurrency", "keyFn"]
|
|
2056
|
+
}
|
|
2057
|
+
]);
|
|
2058
|
+
}
|
|
2059
|
+
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
2060
|
+
}
|
|
2061
|
+
const { started, canceled } = await config.store.tryStartRun(
|
|
2062
|
+
runId,
|
|
2063
|
+
fact,
|
|
2064
|
+
concurrencyArg
|
|
2065
|
+
);
|
|
2066
|
+
if (!started) return { started: false };
|
|
2067
|
+
for (const c of canceled) {
|
|
2068
|
+
const cancelError = new NagiCanceledError({
|
|
2069
|
+
runId: c.runId,
|
|
2070
|
+
canceledByRunId: runId,
|
|
2071
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2072
|
+
});
|
|
2073
|
+
const serialized = {
|
|
2074
|
+
...serializeError(cancelError),
|
|
2075
|
+
cause: {
|
|
2076
|
+
canceledByRunId: runId,
|
|
2077
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
const errorEvent = {
|
|
2081
|
+
runId: c.runId,
|
|
2082
|
+
flowId: flow2.id,
|
|
2083
|
+
error: serialized,
|
|
2084
|
+
at: c.fact.at
|
|
2085
|
+
};
|
|
2086
|
+
await fireHook(
|
|
2087
|
+
flow2.onError,
|
|
2088
|
+
errorEvent,
|
|
2089
|
+
"flow.onError",
|
|
2090
|
+
dispatchDeps
|
|
2091
|
+
);
|
|
2092
|
+
await fireHook(
|
|
2093
|
+
config.hooks?.onFlowError,
|
|
2094
|
+
errorEvent,
|
|
2095
|
+
"onFlowError",
|
|
2096
|
+
dispatchDeps
|
|
2097
|
+
);
|
|
2098
|
+
await propagateToParent(dispatchDeps, c.runId, {
|
|
2099
|
+
kind: "canceled",
|
|
2100
|
+
error: serialized
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
2103
|
+
const startEvent = parent !== void 0 ? {
|
|
2104
|
+
runId,
|
|
2105
|
+
flowId: flow2.id,
|
|
2106
|
+
input: validatedInput,
|
|
2107
|
+
at: startedAt,
|
|
2108
|
+
parent
|
|
2109
|
+
} : {
|
|
2110
|
+
runId,
|
|
2111
|
+
flowId: flow2.id,
|
|
2112
|
+
input: validatedInput,
|
|
2113
|
+
at: startedAt
|
|
2114
|
+
};
|
|
2115
|
+
await fireHook(
|
|
2116
|
+
flow2.onStart,
|
|
2117
|
+
startEvent,
|
|
2118
|
+
"flow.onStart",
|
|
2119
|
+
dispatchDeps
|
|
2120
|
+
);
|
|
2121
|
+
await fireHook(
|
|
2122
|
+
config.hooks?.onFlowStart,
|
|
2123
|
+
startEvent,
|
|
2124
|
+
"onFlowStart",
|
|
2125
|
+
dispatchDeps
|
|
2126
|
+
);
|
|
2127
|
+
await advance(dispatchDeps, runId);
|
|
2128
|
+
return { started: true };
|
|
2129
|
+
}
|
|
2130
|
+
async function startChildRun(args) {
|
|
2131
|
+
const { child, childInput, parent } = args;
|
|
2132
|
+
if (!flowsById.has(child.id)) {
|
|
2133
|
+
throw new NagiRuntimeError(
|
|
2134
|
+
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
2135
|
+
);
|
|
2136
|
+
}
|
|
2137
|
+
const validated = await validate(child.input, childInput);
|
|
2138
|
+
const childRunId = mintRunId();
|
|
2139
|
+
const { started } = await startRunInternal({
|
|
2140
|
+
flow: child,
|
|
2141
|
+
validatedInput: validated,
|
|
2142
|
+
runId: childRunId,
|
|
2143
|
+
parent
|
|
2144
|
+
});
|
|
2145
|
+
if (!started) {
|
|
2146
|
+
throw new NagiRuntimeError(
|
|
2147
|
+
`startChildRun: minted child runId collided with an existing run (${childRunId})`
|
|
2148
|
+
);
|
|
2149
|
+
}
|
|
2150
|
+
return childRunId;
|
|
2151
|
+
}
|
|
2152
|
+
async function cancelRunRecursive(runId, args) {
|
|
2153
|
+
const state = await config.store.loadRunState(runId);
|
|
2154
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2155
|
+
config.logger?.info("nagi: cancel skipped \u2014 run already terminal", {
|
|
2156
|
+
runId,
|
|
2157
|
+
status: state.status
|
|
2158
|
+
});
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
const flow2 = flowsById.get(state.flowId);
|
|
2162
|
+
const canceledFact = {
|
|
2163
|
+
...args,
|
|
2164
|
+
kind: "flow.canceled",
|
|
2165
|
+
runId,
|
|
2166
|
+
at: clock.now()
|
|
2167
|
+
};
|
|
2168
|
+
await config.store.appendFact(runId, canceledFact);
|
|
2169
|
+
const cancelError = {
|
|
2170
|
+
name: "NagiCanceledError",
|
|
2171
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2172
|
+
};
|
|
2173
|
+
if (flow2 !== void 0) {
|
|
2174
|
+
const event = {
|
|
2175
|
+
runId,
|
|
2176
|
+
flowId: flow2.id,
|
|
2177
|
+
error: cancelError,
|
|
2178
|
+
at: clock.now()
|
|
2179
|
+
};
|
|
2180
|
+
await fireHook(flow2.onError, event, "flow.onError", dispatchDeps);
|
|
2181
|
+
await fireHook(
|
|
2182
|
+
config.hooks?.onFlowError,
|
|
2183
|
+
event,
|
|
2184
|
+
"onFlowError",
|
|
2185
|
+
dispatchDeps
|
|
2186
|
+
);
|
|
2187
|
+
}
|
|
2188
|
+
const children = await config.store.listChildren(runId);
|
|
2189
|
+
for (const childId of children) {
|
|
2190
|
+
await cancelRunRecursive(childId, {
|
|
2191
|
+
cause: "explicit",
|
|
2192
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2193
|
+
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
await propagateToParent(dispatchDeps, runId, {
|
|
2197
|
+
kind: "canceled",
|
|
2198
|
+
error: cancelError
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
1562
2201
|
const dispatchDeps = {
|
|
1563
2202
|
flowFor,
|
|
2203
|
+
lookupFlow,
|
|
2204
|
+
startChildRun,
|
|
1564
2205
|
store: config.store,
|
|
1565
2206
|
queue: config.queue,
|
|
1566
2207
|
clock,
|
|
@@ -1568,11 +2209,15 @@ async function nagi(config) {
|
|
|
1568
2209
|
...config.logger !== void 0 ? { logger: config.logger } : {},
|
|
1569
2210
|
...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
|
|
1570
2211
|
};
|
|
1571
|
-
|
|
2212
|
+
const wf = {
|
|
1572
2213
|
async start(flow2, input, opts) {
|
|
1573
|
-
|
|
2214
|
+
return wf.startById(flow2.id, input, opts);
|
|
2215
|
+
},
|
|
2216
|
+
async startById(flowId, input, opts) {
|
|
2217
|
+
const flow2 = flowsById.get(flowId);
|
|
2218
|
+
if (!flow2) {
|
|
1574
2219
|
throw new NagiRuntimeError(
|
|
1575
|
-
`Flow "${
|
|
2220
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1576
2221
|
);
|
|
1577
2222
|
}
|
|
1578
2223
|
let runId;
|
|
@@ -1590,43 +2235,10 @@ async function nagi(config) {
|
|
|
1590
2235
|
runId = mintRunId();
|
|
1591
2236
|
}
|
|
1592
2237
|
const validated = await validate(flow2.input, input);
|
|
1593
|
-
|
|
1594
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
1595
|
-
const fact = {
|
|
1596
|
-
kind: "flow.started",
|
|
1597
|
-
runId,
|
|
1598
|
-
flowId: flow2.id,
|
|
1599
|
-
input: validated,
|
|
1600
|
-
at: startedAt,
|
|
1601
|
-
...flowHash !== void 0 ? { flowHash } : {},
|
|
1602
|
-
...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
|
|
1603
|
-
};
|
|
1604
|
-
const { started } = await config.store.tryStartRun(runId, fact);
|
|
1605
|
-
if (!started) {
|
|
1606
|
-
return runId;
|
|
1607
|
-
}
|
|
1608
|
-
const startEvent = {
|
|
1609
|
-
runId,
|
|
1610
|
-
flowId: flow2.id,
|
|
1611
|
-
input: validated,
|
|
1612
|
-
at: startedAt
|
|
1613
|
-
};
|
|
1614
|
-
await fireHook(
|
|
1615
|
-
flow2.onStart,
|
|
1616
|
-
startEvent,
|
|
1617
|
-
"flow.onStart",
|
|
1618
|
-
dispatchDeps
|
|
1619
|
-
);
|
|
1620
|
-
await fireHook(
|
|
1621
|
-
config.hooks?.onFlowStart,
|
|
1622
|
-
startEvent,
|
|
1623
|
-
"onFlowStart",
|
|
1624
|
-
dispatchDeps
|
|
1625
|
-
);
|
|
1626
|
-
await advance(dispatchDeps, runId);
|
|
2238
|
+
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
1627
2239
|
return runId;
|
|
1628
2240
|
},
|
|
1629
|
-
async signal(runId,
|
|
2241
|
+
async signal(runId, signalName, payload) {
|
|
1630
2242
|
const runState = await config.store.loadRunState(runId);
|
|
1631
2243
|
const flow2 = flowsById.get(runState.flowId);
|
|
1632
2244
|
if (!flow2) {
|
|
@@ -1634,53 +2246,71 @@ async function nagi(config) {
|
|
|
1634
2246
|
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
1635
2247
|
);
|
|
1636
2248
|
}
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
);
|
|
2249
|
+
let stepId;
|
|
2250
|
+
let def;
|
|
2251
|
+
const direct = flow2.steps[signalName];
|
|
2252
|
+
if (direct !== void 0) {
|
|
2253
|
+
const d = getDef(direct);
|
|
2254
|
+
if (d.kind === "signal" && d.names === void 0) {
|
|
2255
|
+
stepId = signalName;
|
|
2256
|
+
def = d;
|
|
2257
|
+
}
|
|
1642
2258
|
}
|
|
1643
|
-
|
|
1644
|
-
|
|
2259
|
+
if (stepId === void 0) {
|
|
2260
|
+
for (const [id, s] of Object.entries(flow2.steps)) {
|
|
2261
|
+
const d = getDef(s);
|
|
2262
|
+
if (d.kind === "signal" && d.names?.includes(signalName)) {
|
|
2263
|
+
stepId = id;
|
|
2264
|
+
def = d;
|
|
2265
|
+
break;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
if (stepId === void 0 || def === void 0) {
|
|
1645
2270
|
throw new NagiRuntimeError(
|
|
1646
|
-
`
|
|
2271
|
+
`Flow "${flow2.id}" has no signal step accepting "${signalName}".`
|
|
1647
2272
|
);
|
|
1648
2273
|
}
|
|
1649
|
-
const stepState = runState.steps[
|
|
2274
|
+
const stepState = runState.steps[stepId];
|
|
1650
2275
|
if (stepState?.status !== "running") {
|
|
2276
|
+
if (stepState?.status === "completed") {
|
|
2277
|
+
config.logger?.info("nagi: signal arrived after step resolved", {
|
|
2278
|
+
runId,
|
|
2279
|
+
stepId,
|
|
2280
|
+
signalName
|
|
2281
|
+
});
|
|
2282
|
+
return;
|
|
2283
|
+
}
|
|
1651
2284
|
throw new NagiRuntimeError(
|
|
1652
|
-
`Step "${
|
|
2285
|
+
`Step "${stepId}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
|
|
1653
2286
|
);
|
|
1654
2287
|
}
|
|
1655
2288
|
const validated = await validate(def.schema, payload);
|
|
1656
2289
|
const attempt = stepState.attempts > 0 ? stepState.attempts : 1;
|
|
2290
|
+
const carriesAlias = signalName !== stepId;
|
|
1657
2291
|
await config.store.appendFact(runId, {
|
|
1658
2292
|
kind: "signal.received",
|
|
1659
2293
|
runId,
|
|
1660
|
-
stepId
|
|
2294
|
+
stepId,
|
|
1661
2295
|
payload: validated,
|
|
1662
|
-
at: clock.now()
|
|
2296
|
+
at: clock.now(),
|
|
2297
|
+
...carriesAlias ? { signalName } : {}
|
|
1663
2298
|
});
|
|
1664
2299
|
const completedFact = {
|
|
1665
2300
|
kind: "step.completed",
|
|
1666
2301
|
runId,
|
|
1667
|
-
stepId
|
|
2302
|
+
stepId,
|
|
1668
2303
|
attempt,
|
|
1669
2304
|
output: validated,
|
|
1670
2305
|
at: clock.now()
|
|
1671
2306
|
};
|
|
1672
|
-
await config.store.completeStep(
|
|
1673
|
-
runId,
|
|
1674
|
-
stepName,
|
|
1675
|
-
validated,
|
|
1676
|
-
completedFact
|
|
1677
|
-
);
|
|
2307
|
+
await config.store.completeStep(runId, stepId, validated, completedFact);
|
|
1678
2308
|
await fireHook(
|
|
1679
2309
|
config.hooks?.onSignalReceived,
|
|
1680
2310
|
{
|
|
1681
2311
|
runId,
|
|
1682
2312
|
flowId: flow2.id,
|
|
1683
|
-
stepId
|
|
2313
|
+
stepId,
|
|
1684
2314
|
attempt,
|
|
1685
2315
|
kind: "signal",
|
|
1686
2316
|
payload: validated,
|
|
@@ -1691,6 +2321,21 @@ async function nagi(config) {
|
|
|
1691
2321
|
);
|
|
1692
2322
|
await advance(dispatchDeps, runId);
|
|
1693
2323
|
},
|
|
2324
|
+
async cancel(runId, opts) {
|
|
2325
|
+
await cancelRunRecursive(runId, {
|
|
2326
|
+
cause: "explicit",
|
|
2327
|
+
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
2328
|
+
});
|
|
2329
|
+
},
|
|
2330
|
+
operator() {
|
|
2331
|
+
return makeOperator({
|
|
2332
|
+
deps: dispatchDeps,
|
|
2333
|
+
clock,
|
|
2334
|
+
flowsById,
|
|
2335
|
+
cancelRunRecursive,
|
|
2336
|
+
...config.logger !== void 0 ? { logger: config.logger } : {}
|
|
2337
|
+
});
|
|
2338
|
+
},
|
|
1694
2339
|
worker(workerConfig) {
|
|
1695
2340
|
if (config.flows.length === 0) {
|
|
1696
2341
|
throw new NagiRuntimeError(
|
|
@@ -1707,10 +2352,16 @@ async function nagi(config) {
|
|
|
1707
2352
|
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
1708
2353
|
);
|
|
1709
2354
|
}
|
|
2355
|
+
if (runState.status === "canceled") {
|
|
2356
|
+
throw new NagiRuntimeError(
|
|
2357
|
+
`Run ${runId} was canceled (superseded by a newer run with the same concurrency key). Replay is not supported for canceled runs \u2014 start a new run instead.`
|
|
2358
|
+
);
|
|
2359
|
+
}
|
|
1710
2360
|
if (opts.mode === "inspect") return;
|
|
1711
2361
|
const fireHooks = opts.fireHooks !== false;
|
|
1712
2362
|
const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
|
|
1713
2363
|
let replayDeps = baseDeps;
|
|
2364
|
+
let effectiveFlow = liveFlow;
|
|
1714
2365
|
const pinned = runState.flowHash;
|
|
1715
2366
|
if (pinned !== void 0) {
|
|
1716
2367
|
const liveHash = flowHashById.get(liveFlow.id);
|
|
@@ -1733,13 +2384,129 @@ async function nagi(config) {
|
|
|
1733
2384
|
liveFlow
|
|
1734
2385
|
);
|
|
1735
2386
|
replayDeps = { ...baseDeps, flowFor: async () => synthesized };
|
|
2387
|
+
effectiveFlow = synthesized;
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
if (opts.from !== void 0) {
|
|
2391
|
+
if (runState.status === "running") {
|
|
2392
|
+
throw new NagiRuntimeError(
|
|
2393
|
+
`Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
|
|
2394
|
+
);
|
|
2395
|
+
}
|
|
2396
|
+
if (!(opts.from in effectiveFlow.steps)) {
|
|
2397
|
+
throw new NagiValidationError([
|
|
2398
|
+
{
|
|
2399
|
+
message: `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
|
|
2400
|
+
path: ["from"]
|
|
2401
|
+
}
|
|
2402
|
+
]);
|
|
2403
|
+
}
|
|
2404
|
+
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
2405
|
+
const at = clock.now();
|
|
2406
|
+
for (const stepId of cascade) {
|
|
2407
|
+
const fact = stepId === opts.from ? { kind: "step.reset", runId, at, stepId } : {
|
|
2408
|
+
kind: "step.reset",
|
|
2409
|
+
runId,
|
|
2410
|
+
at,
|
|
2411
|
+
stepId,
|
|
2412
|
+
cascadedFrom: opts.from
|
|
2413
|
+
};
|
|
2414
|
+
await config.store.appendFact(runId, fact);
|
|
1736
2415
|
}
|
|
1737
2416
|
}
|
|
1738
2417
|
await advance(replayDeps, runId);
|
|
1739
2418
|
if (!fireHooks) await drainInline(replayDeps);
|
|
2419
|
+
},
|
|
2420
|
+
async queryRuns(opts = {}) {
|
|
2421
|
+
if (opts.latest === true) {
|
|
2422
|
+
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
2423
|
+
throw new NagiValidationError([
|
|
2424
|
+
{
|
|
2425
|
+
message: "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
|
|
2426
|
+
path: ["latest"]
|
|
2427
|
+
}
|
|
2428
|
+
]);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
return config.store.queryRuns(opts);
|
|
2432
|
+
},
|
|
2433
|
+
async pruneFacts(opts) {
|
|
2434
|
+
if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
|
|
2435
|
+
throw new NagiValidationError([
|
|
2436
|
+
{
|
|
2437
|
+
message: "pruneFacts: `olderThan` must be a valid Date.",
|
|
2438
|
+
path: ["olderThan"]
|
|
2439
|
+
}
|
|
2440
|
+
]);
|
|
2441
|
+
}
|
|
2442
|
+
const statuses = opts.statuses ?? [
|
|
2443
|
+
"completed"
|
|
2444
|
+
];
|
|
2445
|
+
for (const s of statuses) {
|
|
2446
|
+
if (s !== "completed" && s !== "failed" && s !== "canceled") {
|
|
2447
|
+
throw new NagiValidationError([
|
|
2448
|
+
{
|
|
2449
|
+
message: `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
|
|
2450
|
+
path: ["statuses"]
|
|
2451
|
+
}
|
|
2452
|
+
]);
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
const batchSize = opts.batchSize ?? 1e3;
|
|
2456
|
+
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
2457
|
+
throw new NagiValidationError([
|
|
2458
|
+
{
|
|
2459
|
+
message: "pruneFacts: `batchSize` must be a positive integer.",
|
|
2460
|
+
path: ["batchSize"]
|
|
2461
|
+
}
|
|
2462
|
+
]);
|
|
2463
|
+
}
|
|
2464
|
+
const keepSummary = opts.keepSummary ?? true;
|
|
2465
|
+
return config.store.pruneFacts({
|
|
2466
|
+
olderThan: opts.olderThan,
|
|
2467
|
+
statuses,
|
|
2468
|
+
batchSize,
|
|
2469
|
+
keepSummary
|
|
2470
|
+
});
|
|
1740
2471
|
}
|
|
1741
2472
|
};
|
|
2473
|
+
Object.defineProperty(wf, "__dispatchDeps", {
|
|
2474
|
+
value: dispatchDeps,
|
|
2475
|
+
enumerable: false,
|
|
2476
|
+
writable: false,
|
|
2477
|
+
configurable: false
|
|
2478
|
+
});
|
|
2479
|
+
return wf;
|
|
2480
|
+
}
|
|
2481
|
+
async function nagiRun(config) {
|
|
2482
|
+
const wf = await nagiImpl(config);
|
|
2483
|
+
const internal = new AbortController();
|
|
2484
|
+
const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
|
|
2485
|
+
const worker = wf.worker({ ...config.worker, signal });
|
|
2486
|
+
const loop = worker.run();
|
|
2487
|
+
loop.catch((err) => {
|
|
2488
|
+
if (signal.aborted) return;
|
|
2489
|
+
config.logger?.error("nagi.run: worker exited unexpectedly", {
|
|
2490
|
+
error: String(err)
|
|
2491
|
+
});
|
|
2492
|
+
});
|
|
2493
|
+
let stopping;
|
|
2494
|
+
const stop = () => {
|
|
2495
|
+
stopping ??= (async () => {
|
|
2496
|
+
internal.abort();
|
|
2497
|
+
try {
|
|
2498
|
+
await loop;
|
|
2499
|
+
} catch {
|
|
2500
|
+
}
|
|
2501
|
+
})();
|
|
2502
|
+
return stopping;
|
|
2503
|
+
};
|
|
2504
|
+
return { wf, stop };
|
|
1742
2505
|
}
|
|
2506
|
+
var nagi = Object.assign(
|
|
2507
|
+
nagiImpl,
|
|
2508
|
+
{ run: nagiRun }
|
|
2509
|
+
);
|
|
1743
2510
|
function mintRunId() {
|
|
1744
2511
|
return `run-${crypto.randomUUID()}`;
|
|
1745
2512
|
}
|
|
@@ -1751,6 +2518,161 @@ async function drainInline(deps) {
|
|
|
1751
2518
|
for (const msg of messages) await dispatchMessage(deps, msg);
|
|
1752
2519
|
}
|
|
1753
2520
|
}
|
|
2521
|
+
function makeOperator(o) {
|
|
2522
|
+
const { deps, clock, flowsById, cancelRunRecursive } = o;
|
|
2523
|
+
const store = deps.store;
|
|
2524
|
+
function resolveFlow(flowId, runId) {
|
|
2525
|
+
const flow2 = flowsById.get(flowId);
|
|
2526
|
+
if (!flow2) {
|
|
2527
|
+
throw new NagiRuntimeError(
|
|
2528
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
2529
|
+
);
|
|
2530
|
+
}
|
|
2531
|
+
return flow2;
|
|
2532
|
+
}
|
|
2533
|
+
async function skip(runId, stepId, opts) {
|
|
2534
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2535
|
+
throw new NagiValidationError([
|
|
2536
|
+
{
|
|
2537
|
+
message: "operator.skip: opts.actor must be a non-empty string",
|
|
2538
|
+
path: ["actor"]
|
|
2539
|
+
}
|
|
2540
|
+
]);
|
|
2541
|
+
}
|
|
2542
|
+
const cascade = opts.cascade ?? "skip";
|
|
2543
|
+
const state = await store.loadRunState(runId);
|
|
2544
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2545
|
+
if (!(stepId in flow2.steps)) {
|
|
2546
|
+
throw new NagiValidationError([
|
|
2547
|
+
{
|
|
2548
|
+
message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2549
|
+
path: ["stepId"]
|
|
2550
|
+
}
|
|
2551
|
+
]);
|
|
2552
|
+
}
|
|
2553
|
+
const stepState = state.steps[stepId];
|
|
2554
|
+
if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
|
|
2555
|
+
o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
|
|
2556
|
+
runId,
|
|
2557
|
+
stepId,
|
|
2558
|
+
status: stepState.status
|
|
2559
|
+
});
|
|
2560
|
+
return;
|
|
2561
|
+
}
|
|
2562
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2563
|
+
throw new NagiRuntimeError(
|
|
2564
|
+
`operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
|
|
2565
|
+
);
|
|
2566
|
+
}
|
|
2567
|
+
const fact = {
|
|
2568
|
+
kind: "step.skipped",
|
|
2569
|
+
runId,
|
|
2570
|
+
at: clock.now(),
|
|
2571
|
+
stepId,
|
|
2572
|
+
reason: "manual",
|
|
2573
|
+
actor: opts.actor,
|
|
2574
|
+
cascade,
|
|
2575
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2576
|
+
};
|
|
2577
|
+
await store.appendFact(runId, fact);
|
|
2578
|
+
await advance(deps, runId);
|
|
2579
|
+
}
|
|
2580
|
+
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
2581
|
+
const start = Date.now();
|
|
2582
|
+
while (Date.now() - start < deadlineMs) {
|
|
2583
|
+
const s = await store.loadRunState(runId);
|
|
2584
|
+
const ss = s.steps[stepId];
|
|
2585
|
+
if (ss === void 0) return;
|
|
2586
|
+
if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
|
|
2587
|
+
return;
|
|
2588
|
+
}
|
|
2589
|
+
if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
|
|
2590
|
+
return;
|
|
2591
|
+
}
|
|
2592
|
+
if (ss.attempts > attempt) return;
|
|
2593
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
2594
|
+
}
|
|
2595
|
+
throw new NagiRuntimeError(
|
|
2596
|
+
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
2597
|
+
);
|
|
2598
|
+
}
|
|
2599
|
+
async function retry(runId, stepId, opts) {
|
|
2600
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2601
|
+
throw new NagiValidationError([
|
|
2602
|
+
{
|
|
2603
|
+
message: "operator.retry: opts.actor must be a non-empty string",
|
|
2604
|
+
path: ["actor"]
|
|
2605
|
+
}
|
|
2606
|
+
]);
|
|
2607
|
+
}
|
|
2608
|
+
const state = await store.loadRunState(runId);
|
|
2609
|
+
if (state.status === "canceled") {
|
|
2610
|
+
throw new NagiRuntimeError(
|
|
2611
|
+
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
2612
|
+
);
|
|
2613
|
+
}
|
|
2614
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2615
|
+
if (!(stepId in flow2.steps)) {
|
|
2616
|
+
throw new NagiValidationError([
|
|
2617
|
+
{
|
|
2618
|
+
message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2619
|
+
path: ["stepId"]
|
|
2620
|
+
}
|
|
2621
|
+
]);
|
|
2622
|
+
}
|
|
2623
|
+
const stepState = state.steps[stepId];
|
|
2624
|
+
if (stepState !== void 0 && stepState.status === "running") {
|
|
2625
|
+
const abortFact = {
|
|
2626
|
+
kind: "step.abort-requested",
|
|
2627
|
+
runId,
|
|
2628
|
+
at: clock.now(),
|
|
2629
|
+
stepId,
|
|
2630
|
+
attempt: stepState.attempts,
|
|
2631
|
+
actor: opts.actor,
|
|
2632
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2633
|
+
};
|
|
2634
|
+
await store.appendFact(runId, abortFact);
|
|
2635
|
+
await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
|
|
2636
|
+
}
|
|
2637
|
+
const cascade = descendantsOf(flow2, stepId);
|
|
2638
|
+
const at = clock.now();
|
|
2639
|
+
for (const id of cascade) {
|
|
2640
|
+
const fact = id === stepId ? {
|
|
2641
|
+
kind: "step.reset",
|
|
2642
|
+
runId,
|
|
2643
|
+
at,
|
|
2644
|
+
stepId: id,
|
|
2645
|
+
actor: opts.actor,
|
|
2646
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2647
|
+
} : {
|
|
2648
|
+
kind: "step.reset",
|
|
2649
|
+
runId,
|
|
2650
|
+
at,
|
|
2651
|
+
stepId: id,
|
|
2652
|
+
cascadedFrom: stepId
|
|
2653
|
+
};
|
|
2654
|
+
await store.appendFact(runId, fact);
|
|
2655
|
+
}
|
|
2656
|
+
await advance(deps, runId);
|
|
2657
|
+
}
|
|
2658
|
+
async function abort(runId, opts) {
|
|
2659
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2660
|
+
throw new NagiValidationError([
|
|
2661
|
+
{
|
|
2662
|
+
message: "operator.abort: opts.actor must be a non-empty string",
|
|
2663
|
+
path: ["actor"]
|
|
2664
|
+
}
|
|
2665
|
+
]);
|
|
2666
|
+
}
|
|
2667
|
+
await cancelRunRecursive(runId, {
|
|
2668
|
+
cause: "operator",
|
|
2669
|
+
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
2670
|
+
actor: opts.actor,
|
|
2671
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2672
|
+
});
|
|
2673
|
+
}
|
|
2674
|
+
return { skip, retry, abort };
|
|
2675
|
+
}
|
|
1754
2676
|
async function validate(schema, value) {
|
|
1755
2677
|
const result = await schema["~standard"].validate(value);
|
|
1756
2678
|
if ("issues" in result && result.issues !== void 0) {
|
|
@@ -1800,6 +2722,6 @@ function synthesizeReplayFlow(dag, liveFlow) {
|
|
|
1800
2722
|
};
|
|
1801
2723
|
}
|
|
1802
2724
|
|
|
1803
|
-
export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
|
|
2725
|
+
export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
|
|
1804
2726
|
//# sourceMappingURL=index.js.map
|
|
1805
2727
|
//# sourceMappingURL=index.js.map
|