@nagi-js/core 0.1.1-rc.6 → 0.1.1-rc.9
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 +125 -628
- package/dist/index.js +967 -433
- 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,26 +13,15 @@ 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) {
|
|
40
26
|
let selected = null;
|
|
41
27
|
for (const fact of runState.facts) {
|
|
@@ -48,41 +34,17 @@ function readSelectedArm(matchId, runState) {
|
|
|
48
34
|
return selected;
|
|
49
35
|
}
|
|
50
36
|
function selectArm(def, args) {
|
|
51
|
-
if (def.mode === "discriminator") {
|
|
52
|
-
const key = def.on(args);
|
|
53
|
-
if (def.arms[key] === void 0) {
|
|
54
|
-
const available = Object.keys(def.arms).join(", ");
|
|
55
|
-
throw new Error(
|
|
56
|
-
`match: discriminator returned "${key}" which has no arm (available: ${available || "<none>"})`
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
return key;
|
|
60
|
-
}
|
|
61
37
|
for (const arm of def.arms) {
|
|
62
38
|
if (arm.otherwise) return arm.id;
|
|
63
39
|
if (arm.when?.(args)) return arm.id;
|
|
64
40
|
}
|
|
65
41
|
throw new Error(
|
|
66
|
-
`match: no
|
|
42
|
+
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
67
43
|
);
|
|
68
44
|
}
|
|
69
45
|
|
|
70
46
|
// src/builder.ts
|
|
71
|
-
var BUILDER_BRAND = /* @__PURE__ */ Symbol.for("nagi.builder");
|
|
72
|
-
function isBuilder(value) {
|
|
73
|
-
return typeof value === "object" && value !== null && value[BUILDER_BRAND] === true;
|
|
74
|
-
}
|
|
75
|
-
function resolveBuildResult(value) {
|
|
76
|
-
if (isBuilder(value)) {
|
|
77
|
-
return Object.fromEntries(value.__steps);
|
|
78
|
-
}
|
|
79
|
-
return value;
|
|
80
|
-
}
|
|
81
|
-
function isDiscriminator(config) {
|
|
82
|
-
return "cases" in config && "on" in config;
|
|
83
|
-
}
|
|
84
47
|
function makeBuilder() {
|
|
85
|
-
const chainSteps = /* @__PURE__ */ new Map();
|
|
86
48
|
function task(config) {
|
|
87
49
|
const def = {
|
|
88
50
|
kind: "task",
|
|
@@ -115,30 +77,28 @@ function makeBuilder() {
|
|
|
115
77
|
};
|
|
116
78
|
return attachDef({ kind: "signal", id: "" }, def);
|
|
117
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
|
+
}
|
|
118
96
|
function match(config) {
|
|
119
|
-
const needs =
|
|
120
|
-
if (isDiscriminator(config)) {
|
|
121
|
-
const arms2 = {};
|
|
122
|
-
for (const [caseKey, build] of Object.entries(config.cases)) {
|
|
123
|
-
const nested = resolveBuildResult(
|
|
124
|
-
build(makeBuilder())
|
|
125
|
-
);
|
|
126
|
-
arms2[caseKey] = { id: caseKey, stepIds: [], _nested: nested };
|
|
127
|
-
}
|
|
128
|
-
const def2 = {
|
|
129
|
-
kind: "match",
|
|
130
|
-
mode: "discriminator",
|
|
131
|
-
needs,
|
|
132
|
-
on: config.on,
|
|
133
|
-
arms: arms2
|
|
134
|
-
};
|
|
135
|
-
return attachDef({ kind: "match", id: "" }, def2);
|
|
136
|
-
}
|
|
137
|
-
const guardConfig = config;
|
|
97
|
+
const needs = config.needs ?? {};
|
|
138
98
|
const arms = [];
|
|
139
|
-
for (let i = 0; i <
|
|
140
|
-
const arm =
|
|
141
|
-
const nested =
|
|
99
|
+
for (let i = 0; i < config.arms.length; i++) {
|
|
100
|
+
const arm = config.arms[i];
|
|
101
|
+
const nested = arm.build(makeBuilder());
|
|
142
102
|
const armId = arm.otherwise ? "otherwise" : `arm${i}`;
|
|
143
103
|
arms.push({
|
|
144
104
|
id: armId,
|
|
@@ -146,80 +106,25 @@ function makeBuilder() {
|
|
|
146
106
|
when: arm.when
|
|
147
107
|
} : {},
|
|
148
108
|
...arm.otherwise ? { otherwise: true } : {},
|
|
149
|
-
|
|
150
|
-
_nested: nested
|
|
109
|
+
nested
|
|
151
110
|
});
|
|
152
111
|
}
|
|
153
|
-
const def = {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
};
|
|
159
|
-
return attachDef({ kind: "match", id: "" }, def);
|
|
160
|
-
}
|
|
161
|
-
function step(key, config) {
|
|
162
|
-
if (chainSteps.has(key)) {
|
|
163
|
-
throw new Error(
|
|
164
|
-
`b.step: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
const shell = { kind: "task", id: "" };
|
|
168
|
-
const needs = {};
|
|
169
|
-
if (config.needs) {
|
|
170
|
-
for (const sibKey of config.needs) {
|
|
171
|
-
const sibling = chainSteps.get(sibKey);
|
|
172
|
-
if (sibling === void 0) {
|
|
173
|
-
throw new Error(
|
|
174
|
-
`b.step("${key}"): unknown sibling "${sibKey}". Available keys so far: ${[...chainSteps.keys()].join(", ") || "<none>"}.`
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
needs[sibKey] = sibling;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
const def = {
|
|
181
|
-
kind: "task",
|
|
182
|
-
needs,
|
|
183
|
-
...config.retry !== void 0 ? { retry: config.retry } : {},
|
|
184
|
-
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
185
|
-
...config.when !== void 0 ? {
|
|
186
|
-
when: config.when
|
|
187
|
-
} : {},
|
|
188
|
-
run: config.run,
|
|
189
|
-
...config.onStart !== void 0 ? { onStart: config.onStart } : {},
|
|
190
|
-
...config.onComplete !== void 0 ? {
|
|
191
|
-
onComplete: config.onComplete
|
|
192
|
-
} : {},
|
|
193
|
-
...config.onError !== void 0 ? { onError: config.onError } : {},
|
|
194
|
-
...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
|
|
195
|
-
};
|
|
196
|
-
attachDefMut(shell, def);
|
|
197
|
-
chainSteps.set(key, shell);
|
|
198
|
-
return builder;
|
|
199
|
-
}
|
|
200
|
-
function include(key, s) {
|
|
201
|
-
if (chainSteps.has(key)) {
|
|
202
|
-
throw new Error(
|
|
203
|
-
`b.include: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
chainSteps.set(key, s);
|
|
207
|
-
return builder;
|
|
112
|
+
const def = { kind: "match", needs, arms };
|
|
113
|
+
return attachDef(
|
|
114
|
+
{ kind: "match", id: "" },
|
|
115
|
+
def
|
|
116
|
+
);
|
|
208
117
|
}
|
|
209
|
-
|
|
118
|
+
return {
|
|
210
119
|
task,
|
|
211
120
|
signal,
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
include,
|
|
215
|
-
[BUILDER_BRAND]: true,
|
|
216
|
-
__steps: chainSteps
|
|
121
|
+
subflow,
|
|
122
|
+
match
|
|
217
123
|
};
|
|
218
|
-
return builder;
|
|
219
124
|
}
|
|
220
125
|
function flow(config) {
|
|
221
126
|
const builder = makeBuilder();
|
|
222
|
-
const built =
|
|
127
|
+
const built = config.build(builder);
|
|
223
128
|
const idByIdentity = /* @__PURE__ */ new Map();
|
|
224
129
|
collectIds(built, "", idByIdentity);
|
|
225
130
|
const finalSteps = {};
|
|
@@ -251,10 +156,9 @@ function collectIds(map, prefix, idByIdentity) {
|
|
|
251
156
|
idByIdentity.set(step, id);
|
|
252
157
|
const def = step.__def;
|
|
253
158
|
if (def?.kind === "match") {
|
|
254
|
-
const
|
|
255
|
-
for (const arm of arms) {
|
|
256
|
-
|
|
257
|
-
collectIds(arm._nested, `${id}.${arm.id}`, idByIdentity);
|
|
159
|
+
const pending = def;
|
|
160
|
+
for (const arm of pending.arms) {
|
|
161
|
+
collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
|
|
258
162
|
}
|
|
259
163
|
}
|
|
260
164
|
}
|
|
@@ -286,24 +190,22 @@ function walkAndRewrite(args) {
|
|
|
286
190
|
rewrittenNeeds[localKey] = { ...upstream, id: upstreamId };
|
|
287
191
|
}
|
|
288
192
|
if (def.kind === "match") {
|
|
289
|
-
const
|
|
193
|
+
const pending = def;
|
|
290
194
|
const finalizedArms = [];
|
|
291
|
-
for (const arm of
|
|
195
|
+
for (const arm of pending.arms) {
|
|
292
196
|
const armPrefix = `${id}.${arm.id}`;
|
|
293
197
|
const nestedStepIds = [];
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
nestedStepIds.push(`${armPrefix}.${nestedKey}`);
|
|
297
|
-
}
|
|
298
|
-
walkAndRewrite({
|
|
299
|
-
flowId,
|
|
300
|
-
map: arm._nested,
|
|
301
|
-
prefix: armPrefix,
|
|
302
|
-
parentMatch: { matchId: id, armId: arm.id },
|
|
303
|
-
idByIdentity,
|
|
304
|
-
out
|
|
305
|
-
});
|
|
198
|
+
for (const nestedKey of Object.keys(arm.nested)) {
|
|
199
|
+
nestedStepIds.push(`${armPrefix}.${nestedKey}`);
|
|
306
200
|
}
|
|
201
|
+
walkAndRewrite({
|
|
202
|
+
flowId,
|
|
203
|
+
map: arm.nested,
|
|
204
|
+
prefix: armPrefix,
|
|
205
|
+
parentMatch: { matchId: id, armId: arm.id },
|
|
206
|
+
idByIdentity,
|
|
207
|
+
out
|
|
208
|
+
});
|
|
307
209
|
finalizedArms.push({
|
|
308
210
|
id: arm.id,
|
|
309
211
|
...arm.when !== void 0 ? { when: arm.when } : {},
|
|
@@ -311,16 +213,8 @@ function walkAndRewrite(args) {
|
|
|
311
213
|
stepIds: nestedStepIds
|
|
312
214
|
});
|
|
313
215
|
}
|
|
314
|
-
const finalizedDef2 =
|
|
216
|
+
const finalizedDef2 = {
|
|
315
217
|
kind: "match",
|
|
316
|
-
mode: "discriminator",
|
|
317
|
-
needs: rewrittenNeeds,
|
|
318
|
-
on: def.on,
|
|
319
|
-
arms: Object.fromEntries(finalizedArms.map((a) => [a.id, a])),
|
|
320
|
-
...parentMatch ? { parentMatch } : {}
|
|
321
|
-
} : {
|
|
322
|
-
kind: "match",
|
|
323
|
-
mode: "guard",
|
|
324
218
|
needs: rewrittenNeeds,
|
|
325
219
|
arms: finalizedArms,
|
|
326
220
|
...parentMatch ? { parentMatch } : {}
|
|
@@ -366,7 +260,7 @@ function warnSourceHashOnce() {
|
|
|
366
260
|
if (warnedAboutSourceHash) return;
|
|
367
261
|
warnedAboutSourceHash = true;
|
|
368
262
|
console.warn(
|
|
369
|
-
"[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.
|
|
263
|
+
"[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."
|
|
370
264
|
);
|
|
371
265
|
}
|
|
372
266
|
async function canonicalize(flow2) {
|
|
@@ -388,6 +282,7 @@ async function canonicalizeStep(id, def) {
|
|
|
388
282
|
const base = { id, kind: def.kind, needs };
|
|
389
283
|
if (def.kind === "task") return canonicalizeTask(base, def);
|
|
390
284
|
if (def.kind === "signal") return canonicalizeSignal(base, def);
|
|
285
|
+
if (def.kind === "subflow") return canonicalizeSubflow(base, def);
|
|
391
286
|
return canonicalizeMatch(base, def);
|
|
392
287
|
}
|
|
393
288
|
async function canonicalizeTask(base, def) {
|
|
@@ -407,14 +302,18 @@ async function canonicalizeSignal(base, def) {
|
|
|
407
302
|
}
|
|
408
303
|
return out;
|
|
409
304
|
}
|
|
305
|
+
async function canonicalizeSubflow(base, def) {
|
|
306
|
+
const out = { ...base };
|
|
307
|
+
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
308
|
+
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
309
|
+
out.childFlowId = def.childFlowId;
|
|
310
|
+
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
410
313
|
async function canonicalizeMatch(base, def) {
|
|
411
314
|
const out = { ...base };
|
|
412
|
-
out.matchMode = def.mode;
|
|
413
|
-
if (def.mode === "discriminator") {
|
|
414
|
-
out.matchOnHash = await hashFnSource(def.on);
|
|
415
|
-
}
|
|
416
315
|
const arms = [];
|
|
417
|
-
for (const arm of
|
|
316
|
+
for (const arm of def.arms) {
|
|
418
317
|
arms.push(await canonicalizeArm(arm));
|
|
419
318
|
}
|
|
420
319
|
out.matchArms = arms;
|
|
@@ -555,12 +454,6 @@ function diffFields(before, after, out) {
|
|
|
555
454
|
if (!schemaEq(before.signalSchema, after.signalSchema)) {
|
|
556
455
|
out.push({ stepId: id, field: "signalSchema" });
|
|
557
456
|
}
|
|
558
|
-
if (before.matchMode !== after.matchMode) {
|
|
559
|
-
out.push({ stepId: id, field: "matchMode" });
|
|
560
|
-
}
|
|
561
|
-
if (before.matchOnHash !== after.matchOnHash) {
|
|
562
|
-
out.push({ stepId: id, field: "matchOn" });
|
|
563
|
-
}
|
|
564
457
|
if (!armsEq(before.matchArms, after.matchArms)) {
|
|
565
458
|
out.push({ stepId: id, field: "matchArms" });
|
|
566
459
|
}
|
|
@@ -607,14 +500,10 @@ var InMemoryStore = class {
|
|
|
607
500
|
snapshots = /* @__PURE__ */ new Map();
|
|
608
501
|
refs = /* @__PURE__ */ new Map();
|
|
609
502
|
globalFacts = [];
|
|
610
|
-
/**
|
|
611
|
-
* The runId currently holding the active slot for `flowId::concurrencyKey`.
|
|
612
|
-
* Updated on `tryStartRun` (set when concurrency is supplied) and on
|
|
613
|
-
* terminal facts (cleared via {@link keyByActiveRun}).
|
|
614
|
-
*/
|
|
615
503
|
activeByKey = /* @__PURE__ */ new Map();
|
|
616
|
-
/** Reverse lookup so terminal facts can free the slot in O(1). */
|
|
617
504
|
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
505
|
+
childrenByParent = /* @__PURE__ */ new Map();
|
|
506
|
+
summaries = /* @__PURE__ */ new Map();
|
|
618
507
|
leaseMs;
|
|
619
508
|
constructor(opts = {}) {
|
|
620
509
|
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
@@ -641,7 +530,7 @@ var InMemoryStore = class {
|
|
|
641
530
|
}
|
|
642
531
|
}
|
|
643
532
|
async tryStartRun(runId, fact, concurrency) {
|
|
644
|
-
if (this.facts.has(runId)) {
|
|
533
|
+
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
645
534
|
return { started: false, canceled: [] };
|
|
646
535
|
}
|
|
647
536
|
const canceled = [];
|
|
@@ -651,6 +540,7 @@ var InMemoryStore = class {
|
|
|
651
540
|
if (priorRunId !== void 0) {
|
|
652
541
|
const cancelFact = {
|
|
653
542
|
kind: "flow.canceled",
|
|
543
|
+
cause: "concurrency",
|
|
654
544
|
runId: priorRunId,
|
|
655
545
|
at: fact.at,
|
|
656
546
|
canceledByRunId: runId,
|
|
@@ -663,8 +553,18 @@ var InMemoryStore = class {
|
|
|
663
553
|
this.keyByActiveRun.set(runId, slot);
|
|
664
554
|
}
|
|
665
555
|
this.facts.set(runId, [fact]);
|
|
556
|
+
if (fact.parentRunId !== void 0) {
|
|
557
|
+
const set = this.childrenByParent.get(fact.parentRunId) ?? /* @__PURE__ */ new Set();
|
|
558
|
+
set.add(runId);
|
|
559
|
+
this.childrenByParent.set(fact.parentRunId, set);
|
|
560
|
+
}
|
|
666
561
|
return { started: true, canceled };
|
|
667
562
|
}
|
|
563
|
+
async listChildren(parentRunId) {
|
|
564
|
+
const set = this.childrenByParent.get(parentRunId);
|
|
565
|
+
if (set === void 0) return [];
|
|
566
|
+
return Array.from(set);
|
|
567
|
+
}
|
|
668
568
|
async loadRunState(runId) {
|
|
669
569
|
return projectRunState(runId, this.facts.get(runId) ?? []);
|
|
670
570
|
}
|
|
@@ -699,8 +599,10 @@ var InMemoryStore = class {
|
|
|
699
599
|
const result = await body(void 0);
|
|
700
600
|
if (result.fact.kind === "step.completed") {
|
|
701
601
|
await this.completeStep(runId, stepId, result.output, result.fact);
|
|
702
|
-
} else {
|
|
602
|
+
} else if (result.fact.kind === "step.failed") {
|
|
703
603
|
await this.failStep(runId, stepId, result.fact.error, result.fact);
|
|
604
|
+
} else {
|
|
605
|
+
await this.appendFact(runId, result.fact);
|
|
704
606
|
}
|
|
705
607
|
return result.output;
|
|
706
608
|
}
|
|
@@ -720,24 +622,29 @@ var InMemoryStore = class {
|
|
|
720
622
|
async appendGlobalFact(fact) {
|
|
721
623
|
this.globalFacts.push(fact);
|
|
722
624
|
}
|
|
723
|
-
/** Test-only: peek at the in-memory global fact log. */
|
|
724
625
|
readGlobalFacts() {
|
|
725
626
|
return this.globalFacts;
|
|
726
627
|
}
|
|
727
628
|
async queryRuns(opts) {
|
|
728
629
|
const where = opts.where ?? {};
|
|
729
630
|
const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
|
|
631
|
+
const matches = (summary) => {
|
|
632
|
+
if (where.flowId !== void 0 && summary.flowId !== where.flowId)
|
|
633
|
+
return false;
|
|
634
|
+
if (statuses !== void 0 && !statuses.includes(summary.status))
|
|
635
|
+
return false;
|
|
636
|
+
if (where.input !== void 0 && !containsJson(summary.input, where.input))
|
|
637
|
+
return false;
|
|
638
|
+
return true;
|
|
639
|
+
};
|
|
730
640
|
const summaries = [];
|
|
731
641
|
for (const [runId, factList] of this.facts) {
|
|
732
642
|
const summary = summarize(runId, factList);
|
|
733
643
|
if (summary === null) continue;
|
|
734
|
-
if (
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
if (where.input !== void 0 && !containsJson(summary.input, where.input))
|
|
739
|
-
continue;
|
|
740
|
-
summaries.push(summary);
|
|
644
|
+
if (matches(summary)) summaries.push(summary);
|
|
645
|
+
}
|
|
646
|
+
for (const summary of this.summaries.values()) {
|
|
647
|
+
if (matches(summary)) summaries.push(summary);
|
|
741
648
|
}
|
|
742
649
|
summaries.sort((a, b) => {
|
|
743
650
|
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
@@ -762,7 +669,57 @@ var InMemoryStore = class {
|
|
|
762
669
|
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
763
670
|
return { runs: page, cursor };
|
|
764
671
|
}
|
|
672
|
+
async pruneFacts(opts) {
|
|
673
|
+
const olderThanMs = opts.olderThan.getTime();
|
|
674
|
+
const statusSet = new Set(opts.statuses);
|
|
675
|
+
const victims = [];
|
|
676
|
+
for (const [runId, factList] of this.facts) {
|
|
677
|
+
const summary = summarize(runId, factList);
|
|
678
|
+
if (summary === null) continue;
|
|
679
|
+
if (summary.completedAt === null) continue;
|
|
680
|
+
if (!statusSet.has(summary.status)) continue;
|
|
681
|
+
if (summary.completedAt.getTime() >= olderThanMs) continue;
|
|
682
|
+
const first = factList[0];
|
|
683
|
+
const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parentRunId : void 0;
|
|
684
|
+
victims.push({
|
|
685
|
+
runId,
|
|
686
|
+
summary,
|
|
687
|
+
factCount: factList.length,
|
|
688
|
+
parentRunId
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
let runsPruned = 0;
|
|
692
|
+
let factsPruned = 0;
|
|
693
|
+
for (const v of victims) {
|
|
694
|
+
this.facts.delete(v.runId);
|
|
695
|
+
deleteByRunPrefix(this.outputs, v.runId);
|
|
696
|
+
deleteByRunPrefix(this.onces, v.runId);
|
|
697
|
+
deleteByRunPrefix(this.leases, v.runId);
|
|
698
|
+
this.childrenByParent.delete(v.runId);
|
|
699
|
+
if (v.parentRunId !== void 0) {
|
|
700
|
+
const siblings = this.childrenByParent.get(v.parentRunId);
|
|
701
|
+
if (siblings !== void 0) {
|
|
702
|
+
siblings.delete(v.runId);
|
|
703
|
+
if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (opts.keepSummary) {
|
|
707
|
+
this.summaries.set(v.runId, v.summary);
|
|
708
|
+
} else {
|
|
709
|
+
this.summaries.delete(v.runId);
|
|
710
|
+
}
|
|
711
|
+
runsPruned += 1;
|
|
712
|
+
factsPruned += v.factCount;
|
|
713
|
+
}
|
|
714
|
+
return { runsPruned, factsPruned };
|
|
715
|
+
}
|
|
765
716
|
};
|
|
717
|
+
function deleteByRunPrefix(map, runId) {
|
|
718
|
+
const prefix = `${runId}::`;
|
|
719
|
+
for (const key of map.keys()) {
|
|
720
|
+
if (key.startsWith(prefix)) map.delete(key);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
766
723
|
function summarize(runId, facts) {
|
|
767
724
|
const first = facts[0];
|
|
768
725
|
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
@@ -877,6 +834,14 @@ function projectRunState(runId, facts) {
|
|
|
877
834
|
error: fact.error
|
|
878
835
|
};
|
|
879
836
|
break;
|
|
837
|
+
case "step.canceled":
|
|
838
|
+
steps[fact.stepId] = {
|
|
839
|
+
stepId: fact.stepId,
|
|
840
|
+
status: "canceled",
|
|
841
|
+
attempts: fact.attempt,
|
|
842
|
+
...fact.error !== void 0 ? { error: fact.error } : {}
|
|
843
|
+
};
|
|
844
|
+
break;
|
|
880
845
|
case "step.skipped":
|
|
881
846
|
steps[fact.stepId] = {
|
|
882
847
|
stepId: fact.stepId,
|
|
@@ -990,7 +955,6 @@ var InMemoryClock = class {
|
|
|
990
955
|
}, delay);
|
|
991
956
|
this.timers.set(key, handle);
|
|
992
957
|
}
|
|
993
|
-
/** Clear any pending scheduled timers. Call from test teardown. */
|
|
994
958
|
dispose() {
|
|
995
959
|
for (const t of this.timers.values()) clearTimeout(t);
|
|
996
960
|
this.timers.clear();
|
|
@@ -1004,10 +968,6 @@ var InMemoryTrigger = class {
|
|
|
1004
968
|
this.handlers = this.handlers.filter((h) => h !== handler);
|
|
1005
969
|
};
|
|
1006
970
|
}
|
|
1007
|
-
/**
|
|
1008
|
-
* Test-only: synchronously dispatch a wake-up to all subscribers.
|
|
1009
|
-
* Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
|
|
1010
|
-
*/
|
|
1011
971
|
fire(runId) {
|
|
1012
972
|
for (const h of this.handlers) h(runId);
|
|
1013
973
|
}
|
|
@@ -1067,19 +1027,31 @@ function nextRunnable(args) {
|
|
|
1067
1027
|
}
|
|
1068
1028
|
function checkUpstream(def, runState) {
|
|
1069
1029
|
for (const upstream of Object.values(def.needs)) {
|
|
1070
|
-
if (!upstream || typeof upstream !== "object" || !("id" in upstream) || typeof upstream.id !== "string") {
|
|
1071
|
-
continue;
|
|
1072
|
-
}
|
|
1073
1030
|
const upstreamState = runState.steps[upstream.id];
|
|
1074
1031
|
if (upstreamState === void 0) return "blocked";
|
|
1075
1032
|
if (upstreamState.status === "completed") continue;
|
|
1076
|
-
if (upstreamState.status === "skipped"
|
|
1033
|
+
if (upstreamState.status === "skipped") {
|
|
1034
|
+
if (manualSkipCascade(upstream.id, runState) === "continue") continue;
|
|
1035
|
+
return "transitive-skip";
|
|
1036
|
+
}
|
|
1037
|
+
if (upstreamState.status === "failed") {
|
|
1077
1038
|
return "transitive-skip";
|
|
1078
1039
|
}
|
|
1079
1040
|
return "blocked";
|
|
1080
1041
|
}
|
|
1081
1042
|
return "ready";
|
|
1082
1043
|
}
|
|
1044
|
+
function manualSkipCascade(stepId, runState) {
|
|
1045
|
+
for (let i = runState.facts.length - 1; i >= 0; i--) {
|
|
1046
|
+
const f = runState.facts[i];
|
|
1047
|
+
if (f === void 0) continue;
|
|
1048
|
+
if (f.kind !== "step.skipped") continue;
|
|
1049
|
+
if (f.stepId !== stepId) continue;
|
|
1050
|
+
if (f.reason !== "manual") return "skip";
|
|
1051
|
+
return f.cascade ?? "skip";
|
|
1052
|
+
}
|
|
1053
|
+
return "skip";
|
|
1054
|
+
}
|
|
1083
1055
|
function checkParentMatch(def, runState) {
|
|
1084
1056
|
if (!def.parentMatch) return "ready";
|
|
1085
1057
|
const { matchId, armId } = def.parentMatch;
|
|
@@ -1098,7 +1070,7 @@ function aggregateMatch(matchId, flow2, runState) {
|
|
|
1098
1070
|
if (def.kind !== "match") return { kind: "pending" };
|
|
1099
1071
|
const selected = readSelectedArm(matchId, runState);
|
|
1100
1072
|
if (selected === null) return { kind: "pending" };
|
|
1101
|
-
const arm = def.
|
|
1073
|
+
const arm = def.arms.find((a) => a.id === selected);
|
|
1102
1074
|
if (!arm) return { kind: "pending" };
|
|
1103
1075
|
const output = {};
|
|
1104
1076
|
let allTerminal = true;
|
|
@@ -1131,6 +1103,75 @@ function flowTermination(flow2, runState) {
|
|
|
1131
1103
|
}
|
|
1132
1104
|
return { done, failed };
|
|
1133
1105
|
}
|
|
1106
|
+
function nextTransition(flow2, runState) {
|
|
1107
|
+
const promotions = readyPromotions(flow2, runState);
|
|
1108
|
+
if (promotions.length > 0) return { kind: "promote-match", promotions };
|
|
1109
|
+
const term = flowTermination(flow2, runState);
|
|
1110
|
+
if (term.done) {
|
|
1111
|
+
if (isFlowTerminal(runState.facts)) return { kind: "settled" };
|
|
1112
|
+
if (term.failed) return { kind: "fail", error: flowFailureError(runState) };
|
|
1113
|
+
return { kind: "complete", output: computeFlowOutput(flow2, runState) };
|
|
1114
|
+
}
|
|
1115
|
+
const input = extractInput(runState);
|
|
1116
|
+
const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
|
|
1117
|
+
if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
|
|
1118
|
+
if (skip.length > 0) return { kind: "skip", skip };
|
|
1119
|
+
return { kind: "waiting" };
|
|
1120
|
+
}
|
|
1121
|
+
function readyPromotions(flow2, runState) {
|
|
1122
|
+
const out = [];
|
|
1123
|
+
for (const [matchId, step] of Object.entries(flow2.steps)) {
|
|
1124
|
+
const def = getDef(step);
|
|
1125
|
+
if (def.kind !== "match") continue;
|
|
1126
|
+
const state = runState.steps[matchId];
|
|
1127
|
+
if (state?.status !== "running") continue;
|
|
1128
|
+
const agg = aggregateMatch(matchId, flow2, runState);
|
|
1129
|
+
if (agg.kind === "pending") continue;
|
|
1130
|
+
const attempt = state.attempts > 0 ? state.attempts : 1;
|
|
1131
|
+
if (agg.kind === "fail-fast") {
|
|
1132
|
+
const failedNested = runState.steps[agg.failedStepId];
|
|
1133
|
+
const error = failedNested?.error ?? {
|
|
1134
|
+
name: "Error",
|
|
1135
|
+
message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
|
|
1136
|
+
};
|
|
1137
|
+
out.push({
|
|
1138
|
+
matchId,
|
|
1139
|
+
attempt,
|
|
1140
|
+
result: { kind: "fail", error }
|
|
1141
|
+
});
|
|
1142
|
+
} else {
|
|
1143
|
+
out.push({
|
|
1144
|
+
matchId,
|
|
1145
|
+
attempt,
|
|
1146
|
+
result: { kind: "complete", output: agg.output }
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
return out;
|
|
1151
|
+
}
|
|
1152
|
+
function flowFailureError(runState) {
|
|
1153
|
+
const failedStep = Object.values(runState.steps).find(
|
|
1154
|
+
(s) => s.status === "failed"
|
|
1155
|
+
);
|
|
1156
|
+
return failedStep?.error ?? { name: "Error", message: "step failed" };
|
|
1157
|
+
}
|
|
1158
|
+
function isFlowTerminal(facts) {
|
|
1159
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1160
|
+
const f = facts[i];
|
|
1161
|
+
if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
|
|
1162
|
+
return true;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return false;
|
|
1166
|
+
}
|
|
1167
|
+
function computeFlowOutput(flow2, runState) {
|
|
1168
|
+
if (flow2.output === void 0) return null;
|
|
1169
|
+
const stepOutputs = {};
|
|
1170
|
+
for (const [sid, sstate] of Object.entries(runState.steps)) {
|
|
1171
|
+
if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
|
|
1172
|
+
}
|
|
1173
|
+
return flow2.output(stepOutputs);
|
|
1174
|
+
}
|
|
1134
1175
|
function descendantsOf(flow2, stepId) {
|
|
1135
1176
|
const children = /* @__PURE__ */ new Map();
|
|
1136
1177
|
const addEdge = (from, to) => {
|
|
@@ -1142,7 +1183,7 @@ function descendantsOf(flow2, stepId) {
|
|
|
1142
1183
|
const def = getDef(step);
|
|
1143
1184
|
for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
|
|
1144
1185
|
if (def.kind === "match") {
|
|
1145
|
-
for (const arm of
|
|
1186
|
+
for (const arm of def.arms) {
|
|
1146
1187
|
for (const armStepId of arm.stepIds) addEdge(id, armStepId);
|
|
1147
1188
|
}
|
|
1148
1189
|
}
|
|
@@ -1225,7 +1266,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1225
1266
|
attempt,
|
|
1226
1267
|
at: clock.now()
|
|
1227
1268
|
});
|
|
1228
|
-
const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1269
|
+
const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1229
1270
|
const startEvent = {
|
|
1230
1271
|
runId,
|
|
1231
1272
|
flowId: flow2.id,
|
|
@@ -1241,7 +1282,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1241
1282
|
const startedAt = Date.now();
|
|
1242
1283
|
try {
|
|
1243
1284
|
if (def.kind === "task") {
|
|
1244
|
-
const output = await executeTask({
|
|
1285
|
+
const { output, skipAdvance } = await executeTask({
|
|
1245
1286
|
deps,
|
|
1246
1287
|
message,
|
|
1247
1288
|
def,
|
|
@@ -1249,6 +1290,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1249
1290
|
stepId,
|
|
1250
1291
|
attempt
|
|
1251
1292
|
});
|
|
1293
|
+
if (skipAdvance) return;
|
|
1252
1294
|
const completeEvent = {
|
|
1253
1295
|
runId,
|
|
1254
1296
|
flowId: flow2.id,
|
|
@@ -1273,6 +1315,10 @@ async function dispatchMessage(deps, message) {
|
|
|
1273
1315
|
} else if (def.kind === "match") {
|
|
1274
1316
|
await executeMatch({ deps, message, def, runId, stepId, attempt });
|
|
1275
1317
|
await advance(deps, runId);
|
|
1318
|
+
} else if (def.kind === "subflow") {
|
|
1319
|
+
await executeSubflow({ deps, message, def, runId, stepId });
|
|
1320
|
+
await queue.ack(message.receipt);
|
|
1321
|
+
return;
|
|
1276
1322
|
}
|
|
1277
1323
|
} catch (err) {
|
|
1278
1324
|
await handleStepError({
|
|
@@ -1296,35 +1342,144 @@ async function executeTask(args) {
|
|
|
1296
1342
|
const runState = await store.loadRunState(runId);
|
|
1297
1343
|
const input = extractInput(runState);
|
|
1298
1344
|
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1299
|
-
const
|
|
1345
|
+
const ac = new AbortController();
|
|
1346
|
+
const watcher = startCancelWatcher({
|
|
1347
|
+
store,
|
|
1300
1348
|
runId,
|
|
1301
1349
|
stepId,
|
|
1302
1350
|
attempt,
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1351
|
+
ac,
|
|
1352
|
+
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
1353
|
+
});
|
|
1354
|
+
try {
|
|
1355
|
+
let stepAbortedHere = false;
|
|
1356
|
+
const output = await store.runStep(
|
|
1357
|
+
runId,
|
|
1358
|
+
stepId,
|
|
1359
|
+
attempt,
|
|
1360
|
+
async (tx) => {
|
|
1361
|
+
const ctx = makeStepCtx({
|
|
1362
|
+
runId,
|
|
1363
|
+
stepId,
|
|
1364
|
+
attempt,
|
|
1365
|
+
input,
|
|
1366
|
+
store,
|
|
1367
|
+
clock,
|
|
1368
|
+
tx,
|
|
1369
|
+
signal: ac.signal,
|
|
1370
|
+
...deps.logger !== void 0 ? { logger: deps.logger } : {}
|
|
1371
|
+
});
|
|
1372
|
+
const out = await def.run({ input, needs, ctx });
|
|
1373
|
+
const postState = await store.loadRunState(runId);
|
|
1374
|
+
if (postState.status === "canceled") {
|
|
1375
|
+
const canceledFact = {
|
|
1376
|
+
kind: "step.canceled",
|
|
1377
|
+
runId,
|
|
1378
|
+
stepId,
|
|
1379
|
+
attempt,
|
|
1380
|
+
at: clock.now()
|
|
1381
|
+
};
|
|
1382
|
+
return { output: out, fact: canceledFact };
|
|
1383
|
+
}
|
|
1384
|
+
if (hasAbortRequest(postState.facts, stepId, attempt)) {
|
|
1385
|
+
stepAbortedHere = true;
|
|
1386
|
+
const canceledFact = {
|
|
1387
|
+
kind: "step.canceled",
|
|
1388
|
+
runId,
|
|
1389
|
+
stepId,
|
|
1390
|
+
attempt,
|
|
1391
|
+
at: clock.now()
|
|
1392
|
+
};
|
|
1393
|
+
return { output: out, fact: canceledFact };
|
|
1394
|
+
}
|
|
1395
|
+
const fact = {
|
|
1396
|
+
kind: "step.completed",
|
|
1397
|
+
runId,
|
|
1398
|
+
stepId,
|
|
1399
|
+
attempt,
|
|
1400
|
+
output: out,
|
|
1401
|
+
at: clock.now()
|
|
1402
|
+
};
|
|
1403
|
+
return { output: out, fact };
|
|
1404
|
+
}
|
|
1405
|
+
);
|
|
1406
|
+
await queue.ack(message.receipt);
|
|
1407
|
+
return { output, skipAdvance: stepAbortedHere };
|
|
1408
|
+
} finally {
|
|
1409
|
+
watcher.stop();
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1413
|
+
function startCancelWatcher(args) {
|
|
1414
|
+
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
1415
|
+
let stopped = false;
|
|
1416
|
+
void (async () => {
|
|
1417
|
+
while (!stopped) {
|
|
1418
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
1419
|
+
if (stopped) return;
|
|
1420
|
+
try {
|
|
1421
|
+
const s = await store.loadRunState(runId);
|
|
1422
|
+
if (s.status === "canceled" || s.status === "failed" || s.status === "completed") {
|
|
1423
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
if (hasAbortRequest(s.facts, stepId, attempt)) {
|
|
1427
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
} catch {
|
|
1431
|
+
}
|
|
1324
1432
|
}
|
|
1325
|
-
);
|
|
1326
|
-
|
|
1327
|
-
|
|
1433
|
+
})();
|
|
1434
|
+
return {
|
|
1435
|
+
stop: () => {
|
|
1436
|
+
stopped = true;
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
function hasAbortRequest(facts, stepId, attempt) {
|
|
1441
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1442
|
+
const f = facts[i];
|
|
1443
|
+
if (f === void 0) continue;
|
|
1444
|
+
if (f.kind === "step.reset" && f.stepId === stepId) return false;
|
|
1445
|
+
if (f.kind === "step.abort-requested" && f.stepId === stepId && f.attempt === attempt) {
|
|
1446
|
+
return true;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
return false;
|
|
1450
|
+
}
|
|
1451
|
+
var NagiAbortError = class extends Error {
|
|
1452
|
+
runId;
|
|
1453
|
+
scope;
|
|
1454
|
+
constructor(runId, scope) {
|
|
1455
|
+
super(
|
|
1456
|
+
scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
1457
|
+
);
|
|
1458
|
+
this.name = "NagiAbortError";
|
|
1459
|
+
this.runId = runId;
|
|
1460
|
+
this.scope = scope;
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
async function executeSubflow(args) {
|
|
1464
|
+
const { deps, message, def, runId, stepId } = args;
|
|
1465
|
+
const { store } = deps;
|
|
1466
|
+
const child = deps.lookupFlow(def.childFlowId);
|
|
1467
|
+
if (child === void 0) {
|
|
1468
|
+
throw new Error(
|
|
1469
|
+
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
const runState = await store.loadRunState(runId);
|
|
1473
|
+
const parentInput = extractInput(runState);
|
|
1474
|
+
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1475
|
+
const childInput = def.buildInput({ input: parentInput, needs });
|
|
1476
|
+
await deps.startChildRun({
|
|
1477
|
+
child,
|
|
1478
|
+
childInput,
|
|
1479
|
+
parentRunId: runId,
|
|
1480
|
+
parentStepId: stepId,
|
|
1481
|
+
parentStepAttempt: message.attempt
|
|
1482
|
+
});
|
|
1328
1483
|
}
|
|
1329
1484
|
async function executeMatch(args) {
|
|
1330
1485
|
const { deps, message, def, runId, stepId } = args;
|
|
@@ -1346,6 +1501,24 @@ async function handleStepError(args) {
|
|
|
1346
1501
|
const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
|
|
1347
1502
|
const { store, queue, clock } = deps;
|
|
1348
1503
|
const error = serializeError(err);
|
|
1504
|
+
const postState = await store.loadRunState(runId);
|
|
1505
|
+
const runIsCanceled = postState.status === "canceled";
|
|
1506
|
+
const stepAborted = hasAbortRequest(postState.facts, stepId, attempt);
|
|
1507
|
+
if (runIsCanceled || stepAborted) {
|
|
1508
|
+
const isAbort = err instanceof NagiAbortError || err instanceof Error && err.name === "AbortError";
|
|
1509
|
+
const canceledFact = {
|
|
1510
|
+
kind: "step.canceled",
|
|
1511
|
+
runId,
|
|
1512
|
+
stepId,
|
|
1513
|
+
attempt,
|
|
1514
|
+
...isAbort ? { error } : {},
|
|
1515
|
+
at: clock.now()
|
|
1516
|
+
};
|
|
1517
|
+
await store.appendFact(runId, canceledFact);
|
|
1518
|
+
await queue.ack(message.receipt);
|
|
1519
|
+
if (!stepAborted) await advance(deps, runId);
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1349
1522
|
const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
|
|
1350
1523
|
const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
|
|
1351
1524
|
if (shouldRetry) {
|
|
@@ -1401,46 +1574,31 @@ async function handleStepError(args) {
|
|
|
1401
1574
|
}
|
|
1402
1575
|
var MAX_ADVANCE_ITERS = 1024;
|
|
1403
1576
|
async function advance(deps, runId) {
|
|
1404
|
-
const { store, queue
|
|
1577
|
+
const { store, queue } = deps;
|
|
1405
1578
|
const flow2 = await deps.flowFor(runId);
|
|
1406
1579
|
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
1407
1580
|
const runState = await store.loadRunState(runId);
|
|
1408
|
-
const
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
if (decision.skip.length === 0 && decision.runnable.length === 0) return;
|
|
1430
|
-
for (const { stepId, reason } of decision.skip) {
|
|
1431
|
-
await store.appendFact(runId, {
|
|
1432
|
-
kind: "step.skipped",
|
|
1433
|
-
runId,
|
|
1434
|
-
stepId,
|
|
1435
|
-
reason,
|
|
1436
|
-
at: clock.now()
|
|
1437
|
-
});
|
|
1438
|
-
}
|
|
1439
|
-
for (const stepId of decision.runnable) {
|
|
1440
|
-
await queue.enqueue(runId, stepId);
|
|
1441
|
-
}
|
|
1442
|
-
if (decision.runnable.length > 0) {
|
|
1443
|
-
return;
|
|
1581
|
+
const t = nextTransition(flow2, runState);
|
|
1582
|
+
switch (t.kind) {
|
|
1583
|
+
case "settled":
|
|
1584
|
+
case "waiting":
|
|
1585
|
+
return;
|
|
1586
|
+
case "complete":
|
|
1587
|
+
await finalizeFlowCompletion({ deps, flow: flow2, runId, output: t.output });
|
|
1588
|
+
return;
|
|
1589
|
+
case "fail":
|
|
1590
|
+
await finalizeFlowFailure({ deps, flow: flow2, runId, error: t.error });
|
|
1591
|
+
return;
|
|
1592
|
+
case "dispatch":
|
|
1593
|
+
await recordSkips(deps, runId, t.skip);
|
|
1594
|
+
for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
|
|
1595
|
+
return;
|
|
1596
|
+
case "skip":
|
|
1597
|
+
await recordSkips(deps, runId, t.skip);
|
|
1598
|
+
continue;
|
|
1599
|
+
case "promote-match":
|
|
1600
|
+
await applyPromotions(deps, flow2, runState, t.promotions);
|
|
1601
|
+
continue;
|
|
1444
1602
|
}
|
|
1445
1603
|
}
|
|
1446
1604
|
const cycleError = {
|
|
@@ -1452,93 +1610,92 @@ async function advance(deps, runId) {
|
|
|
1452
1610
|
await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
|
|
1453
1611
|
}
|
|
1454
1612
|
}
|
|
1455
|
-
async function
|
|
1456
|
-
const { deps, flow: flow2, runState } = args;
|
|
1613
|
+
async function recordSkips(deps, runId, skip) {
|
|
1457
1614
|
const { store, clock } = deps;
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1615
|
+
for (const { stepId, reason } of skip) {
|
|
1616
|
+
await store.appendFact(runId, {
|
|
1617
|
+
kind: "step.skipped",
|
|
1618
|
+
runId,
|
|
1619
|
+
stepId,
|
|
1620
|
+
reason,
|
|
1621
|
+
at: clock.now()
|
|
1622
|
+
});
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
async function markStepComplete(args) {
|
|
1626
|
+
const { deps, flow: flow2, runId, stepId, attempt, kind, output } = args;
|
|
1627
|
+
const at = deps.clock.now();
|
|
1628
|
+
const fact = {
|
|
1629
|
+
kind: "step.completed",
|
|
1630
|
+
runId,
|
|
1631
|
+
stepId,
|
|
1632
|
+
attempt,
|
|
1633
|
+
output,
|
|
1634
|
+
at
|
|
1635
|
+
};
|
|
1636
|
+
await deps.store.completeStep(runId, stepId, output, fact);
|
|
1637
|
+
await fireHook(
|
|
1638
|
+
deps.hooks?.onStepComplete,
|
|
1639
|
+
{
|
|
1640
|
+
runId,
|
|
1641
|
+
flowId: flow2.id,
|
|
1642
|
+
stepId,
|
|
1643
|
+
attempt,
|
|
1644
|
+
kind,
|
|
1645
|
+
output,
|
|
1646
|
+
durationMs: 0,
|
|
1647
|
+
at
|
|
1648
|
+
},
|
|
1649
|
+
"onStepComplete",
|
|
1650
|
+
deps
|
|
1651
|
+
);
|
|
1652
|
+
}
|
|
1653
|
+
async function markStepFail(args) {
|
|
1654
|
+
const { deps, flow: flow2, runId, stepId, attempt, kind, error } = args;
|
|
1655
|
+
const at = deps.clock.now();
|
|
1656
|
+
const fact = { kind: "step.failed", runId, stepId, attempt, error, at };
|
|
1657
|
+
await deps.store.failStep(runId, stepId, error, fact);
|
|
1658
|
+
await fireHook(
|
|
1659
|
+
deps.hooks?.onStepError,
|
|
1660
|
+
{ runId, flowId: flow2.id, stepId, attempt, kind, error, at },
|
|
1661
|
+
"onStepError",
|
|
1662
|
+
deps
|
|
1663
|
+
);
|
|
1664
|
+
}
|
|
1665
|
+
async function applyPromotions(deps, flow2, runState, promotions) {
|
|
1666
|
+
for (const { matchId, attempt, result } of promotions) {
|
|
1667
|
+
if (result.kind === "fail") {
|
|
1668
|
+
await markStepFail({
|
|
1669
|
+
deps,
|
|
1670
|
+
flow: flow2,
|
|
1475
1671
|
runId: runState.runId,
|
|
1476
1672
|
stepId: matchId,
|
|
1477
1673
|
attempt,
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
};
|
|
1481
|
-
|
|
1482
|
-
await
|
|
1483
|
-
deps
|
|
1484
|
-
|
|
1485
|
-
runId: runState.runId,
|
|
1486
|
-
flowId: flow2.id,
|
|
1487
|
-
stepId: matchId,
|
|
1488
|
-
attempt,
|
|
1489
|
-
kind: "match",
|
|
1490
|
-
error,
|
|
1491
|
-
at: clock.now()
|
|
1492
|
-
},
|
|
1493
|
-
"onStepError",
|
|
1494
|
-
deps
|
|
1495
|
-
);
|
|
1496
|
-
promoted = true;
|
|
1497
|
-
continue;
|
|
1498
|
-
}
|
|
1499
|
-
const fact = {
|
|
1500
|
-
kind: "step.completed",
|
|
1501
|
-
runId: runState.runId,
|
|
1502
|
-
stepId: matchId,
|
|
1503
|
-
attempt,
|
|
1504
|
-
output: agg.output,
|
|
1505
|
-
at: clock.now()
|
|
1506
|
-
};
|
|
1507
|
-
await store.completeStep(runState.runId, matchId, agg.output, fact);
|
|
1508
|
-
await fireHook(
|
|
1509
|
-
deps.hooks?.onStepComplete,
|
|
1510
|
-
{
|
|
1674
|
+
kind: "match",
|
|
1675
|
+
error: result.error
|
|
1676
|
+
});
|
|
1677
|
+
} else {
|
|
1678
|
+
await markStepComplete({
|
|
1679
|
+
deps,
|
|
1680
|
+
flow: flow2,
|
|
1511
1681
|
runId: runState.runId,
|
|
1512
|
-
flowId: flow2.id,
|
|
1513
1682
|
stepId: matchId,
|
|
1514
1683
|
attempt,
|
|
1515
1684
|
kind: "match",
|
|
1516
|
-
output:
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
},
|
|
1520
|
-
"onStepComplete",
|
|
1521
|
-
deps
|
|
1522
|
-
);
|
|
1523
|
-
promoted = true;
|
|
1685
|
+
output: result.output
|
|
1686
|
+
});
|
|
1687
|
+
}
|
|
1524
1688
|
}
|
|
1525
|
-
return promoted;
|
|
1526
1689
|
}
|
|
1527
1690
|
function makeStepCtx(args) {
|
|
1528
|
-
const { runId, stepId, attempt, input, store, clock, tx } = args;
|
|
1529
|
-
const ac = new AbortController();
|
|
1691
|
+
const { runId, stepId, attempt, input, store, clock, tx, signal } = args;
|
|
1530
1692
|
return {
|
|
1531
1693
|
input,
|
|
1532
1694
|
runId,
|
|
1533
1695
|
stepId,
|
|
1534
1696
|
attempt,
|
|
1535
|
-
signal
|
|
1697
|
+
signal,
|
|
1536
1698
|
now: () => clock.now(),
|
|
1537
|
-
// `tx` is supplied by `Store.runStep` — for adapters with no real
|
|
1538
|
-
// transaction (in-memory) it is `undefined as Tx`, and handlers that
|
|
1539
|
-
// touch `ctx.tx` will throw on the first call. Adapters that need
|
|
1540
|
-
// typed transactional clients (e.g. `@nagi-js/postgres`) augment
|
|
1541
|
-
// `Register.tx` and pass a real Kysely transaction here.
|
|
1542
1699
|
tx,
|
|
1543
1700
|
logger: args.logger ?? consoleLogger(),
|
|
1544
1701
|
once: makeOnce({ runId, stepId, store }),
|
|
@@ -1569,15 +1726,6 @@ function retryAllows(policy, err) {
|
|
|
1569
1726
|
if (!policy.retryOn) return true;
|
|
1570
1727
|
return policy.retryOn(err);
|
|
1571
1728
|
}
|
|
1572
|
-
function isFlowTerminal(facts) {
|
|
1573
|
-
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1574
|
-
const f = facts[i];
|
|
1575
|
-
if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
|
|
1576
|
-
return true;
|
|
1577
|
-
}
|
|
1578
|
-
}
|
|
1579
|
-
return false;
|
|
1580
|
-
}
|
|
1581
1729
|
async function finalizeFlowFailure(args) {
|
|
1582
1730
|
const { deps, flow: flow2, runId, error } = args;
|
|
1583
1731
|
const { store, clock } = deps;
|
|
@@ -1590,11 +1738,11 @@ async function finalizeFlowFailure(args) {
|
|
|
1590
1738
|
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
1591
1739
|
await fireHook(flow2.onError, event, "flow.onError", deps);
|
|
1592
1740
|
await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
|
|
1741
|
+
await propagateToParent(deps, runId, { kind: "failed", error });
|
|
1593
1742
|
}
|
|
1594
1743
|
async function finalizeFlowCompletion(args) {
|
|
1595
|
-
const { deps, flow: flow2, runId,
|
|
1744
|
+
const { deps, flow: flow2, runId, output } = args;
|
|
1596
1745
|
const { store, clock } = deps;
|
|
1597
|
-
const output = computeFlowOutput(flow2, runState);
|
|
1598
1746
|
await store.appendFact(runId, {
|
|
1599
1747
|
kind: "flow.completed",
|
|
1600
1748
|
runId,
|
|
@@ -1604,14 +1752,68 @@ async function finalizeFlowCompletion(args) {
|
|
|
1604
1752
|
const event = { runId, flowId: flow2.id, output, at: clock.now() };
|
|
1605
1753
|
await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
|
|
1606
1754
|
await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
|
|
1755
|
+
await propagateToParent(deps, runId, { kind: "completed", output });
|
|
1607
1756
|
}
|
|
1608
|
-
function
|
|
1609
|
-
|
|
1610
|
-
const
|
|
1611
|
-
|
|
1612
|
-
|
|
1757
|
+
async function propagateToParent(deps, childRunId, outcome) {
|
|
1758
|
+
const { store } = deps;
|
|
1759
|
+
const childState = await store.loadRunState(childRunId);
|
|
1760
|
+
const startedFact = childState.facts.find((f) => f.kind === "flow.started");
|
|
1761
|
+
if (startedFact?.parentRunId === void 0 || startedFact?.parentStepId === void 0) {
|
|
1762
|
+
return;
|
|
1613
1763
|
}
|
|
1614
|
-
|
|
1764
|
+
const parentRunId = startedFact.parentRunId;
|
|
1765
|
+
const parentStepId = startedFact.parentStepId;
|
|
1766
|
+
const parentState = await store.loadRunState(parentRunId);
|
|
1767
|
+
if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
|
|
1768
|
+
deps.logger?.info(
|
|
1769
|
+
"nagi: subflow wake skipped \u2014 parent run already terminal",
|
|
1770
|
+
{
|
|
1771
|
+
parentRunId,
|
|
1772
|
+
parentStepId,
|
|
1773
|
+
childRunId,
|
|
1774
|
+
parentStatus: parentState.status
|
|
1775
|
+
}
|
|
1776
|
+
);
|
|
1777
|
+
return;
|
|
1778
|
+
}
|
|
1779
|
+
const parentStep = parentState.steps[parentStepId];
|
|
1780
|
+
if (parentStep?.status !== "running") {
|
|
1781
|
+
deps.logger?.info("nagi: subflow wake skipped \u2014 parent step not running", {
|
|
1782
|
+
parentRunId,
|
|
1783
|
+
parentStepId,
|
|
1784
|
+
childRunId,
|
|
1785
|
+
parentStepStatus: parentStep?.status ?? "missing"
|
|
1786
|
+
});
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
const attempt = parentStep.attempts > 0 ? parentStep.attempts : 1;
|
|
1790
|
+
const parentFlow = await deps.flowFor(parentRunId);
|
|
1791
|
+
if (outcome.kind === "completed") {
|
|
1792
|
+
const subflowOutput = {
|
|
1793
|
+
childRunId,
|
|
1794
|
+
output: outcome.output
|
|
1795
|
+
};
|
|
1796
|
+
await markStepComplete({
|
|
1797
|
+
deps,
|
|
1798
|
+
flow: parentFlow,
|
|
1799
|
+
runId: parentRunId,
|
|
1800
|
+
stepId: parentStepId,
|
|
1801
|
+
attempt,
|
|
1802
|
+
kind: "subflow",
|
|
1803
|
+
output: subflowOutput
|
|
1804
|
+
});
|
|
1805
|
+
} else {
|
|
1806
|
+
await markStepFail({
|
|
1807
|
+
deps,
|
|
1808
|
+
flow: parentFlow,
|
|
1809
|
+
runId: parentRunId,
|
|
1810
|
+
stepId: parentStepId,
|
|
1811
|
+
attempt,
|
|
1812
|
+
kind: "subflow",
|
|
1813
|
+
error: outcome.error
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
await advance(deps, parentRunId);
|
|
1615
1817
|
}
|
|
1616
1818
|
function serializeError(err) {
|
|
1617
1819
|
if (err instanceof Error) {
|
|
@@ -1811,8 +2013,204 @@ async function nagi(config) {
|
|
|
1811
2013
|
}
|
|
1812
2014
|
return flow2;
|
|
1813
2015
|
}
|
|
2016
|
+
function lookupFlow(flowId) {
|
|
2017
|
+
return flowsById.get(flowId);
|
|
2018
|
+
}
|
|
2019
|
+
async function startRunInternal(args) {
|
|
2020
|
+
const {
|
|
2021
|
+
flow: flow2,
|
|
2022
|
+
validatedInput,
|
|
2023
|
+
runId,
|
|
2024
|
+
parentRunId,
|
|
2025
|
+
parentStepId,
|
|
2026
|
+
parentStepAttempt
|
|
2027
|
+
} = args;
|
|
2028
|
+
const startedAt = clock.now();
|
|
2029
|
+
const flowHash = flowHashById.get(flow2.id);
|
|
2030
|
+
const fact = {
|
|
2031
|
+
kind: "flow.started",
|
|
2032
|
+
runId,
|
|
2033
|
+
flowId: flow2.id,
|
|
2034
|
+
input: validatedInput,
|
|
2035
|
+
at: startedAt,
|
|
2036
|
+
...flowHash !== void 0 ? { flowHash } : {},
|
|
2037
|
+
codeVersion,
|
|
2038
|
+
...parentRunId !== void 0 ? { parentRunId } : {},
|
|
2039
|
+
...parentStepId !== void 0 ? { parentStepId } : {}
|
|
2040
|
+
};
|
|
2041
|
+
let concurrencyArg;
|
|
2042
|
+
if (flow2.concurrency !== void 0) {
|
|
2043
|
+
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
2044
|
+
if (typeof derived !== "string" || derived.length === 0) {
|
|
2045
|
+
throw new NagiValidationError([
|
|
2046
|
+
{
|
|
2047
|
+
message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
2048
|
+
path: ["concurrency", "keyFn"]
|
|
2049
|
+
}
|
|
2050
|
+
]);
|
|
2051
|
+
}
|
|
2052
|
+
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
2053
|
+
}
|
|
2054
|
+
const { started, canceled } = await config.store.tryStartRun(
|
|
2055
|
+
runId,
|
|
2056
|
+
fact,
|
|
2057
|
+
concurrencyArg
|
|
2058
|
+
);
|
|
2059
|
+
if (!started) return { started: false };
|
|
2060
|
+
for (const c of canceled) {
|
|
2061
|
+
const cancelError = new NagiCanceledError({
|
|
2062
|
+
runId: c.runId,
|
|
2063
|
+
canceledByRunId: runId,
|
|
2064
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2065
|
+
});
|
|
2066
|
+
const serialized = {
|
|
2067
|
+
...serializeError(cancelError),
|
|
2068
|
+
cause: {
|
|
2069
|
+
canceledByRunId: runId,
|
|
2070
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
const errorEvent = {
|
|
2074
|
+
runId: c.runId,
|
|
2075
|
+
flowId: flow2.id,
|
|
2076
|
+
error: serialized,
|
|
2077
|
+
at: c.fact.at
|
|
2078
|
+
};
|
|
2079
|
+
await fireHook(
|
|
2080
|
+
flow2.onError,
|
|
2081
|
+
errorEvent,
|
|
2082
|
+
"flow.onError",
|
|
2083
|
+
dispatchDeps
|
|
2084
|
+
);
|
|
2085
|
+
await fireHook(
|
|
2086
|
+
config.hooks?.onFlowError,
|
|
2087
|
+
errorEvent,
|
|
2088
|
+
"onFlowError",
|
|
2089
|
+
dispatchDeps
|
|
2090
|
+
);
|
|
2091
|
+
await propagateToParent(dispatchDeps, c.runId, {
|
|
2092
|
+
kind: "canceled",
|
|
2093
|
+
error: serialized
|
|
2094
|
+
});
|
|
2095
|
+
}
|
|
2096
|
+
const startEvent = parentRunId !== void 0 && parentStepId !== void 0 && parentStepAttempt !== void 0 ? {
|
|
2097
|
+
runId,
|
|
2098
|
+
flowId: flow2.id,
|
|
2099
|
+
input: validatedInput,
|
|
2100
|
+
at: startedAt,
|
|
2101
|
+
parent: {
|
|
2102
|
+
runId: parentRunId,
|
|
2103
|
+
stepId: parentStepId,
|
|
2104
|
+
attempt: parentStepAttempt
|
|
2105
|
+
}
|
|
2106
|
+
} : {
|
|
2107
|
+
runId,
|
|
2108
|
+
flowId: flow2.id,
|
|
2109
|
+
input: validatedInput,
|
|
2110
|
+
at: startedAt
|
|
2111
|
+
};
|
|
2112
|
+
await fireHook(
|
|
2113
|
+
flow2.onStart,
|
|
2114
|
+
startEvent,
|
|
2115
|
+
"flow.onStart",
|
|
2116
|
+
dispatchDeps
|
|
2117
|
+
);
|
|
2118
|
+
await fireHook(
|
|
2119
|
+
config.hooks?.onFlowStart,
|
|
2120
|
+
startEvent,
|
|
2121
|
+
"onFlowStart",
|
|
2122
|
+
dispatchDeps
|
|
2123
|
+
);
|
|
2124
|
+
await advance(dispatchDeps, runId);
|
|
2125
|
+
return { started: true };
|
|
2126
|
+
}
|
|
2127
|
+
async function startChildRun(args) {
|
|
2128
|
+
const { child, childInput, parentRunId, parentStepId, parentStepAttempt } = args;
|
|
2129
|
+
if (!flowsById.has(child.id)) {
|
|
2130
|
+
throw new NagiRuntimeError(
|
|
2131
|
+
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
2132
|
+
);
|
|
2133
|
+
}
|
|
2134
|
+
const validated = await validate(child.input, childInput);
|
|
2135
|
+
const childRunId = mintRunId();
|
|
2136
|
+
const { started } = await startRunInternal({
|
|
2137
|
+
flow: child,
|
|
2138
|
+
validatedInput: validated,
|
|
2139
|
+
runId: childRunId,
|
|
2140
|
+
parentRunId,
|
|
2141
|
+
parentStepId,
|
|
2142
|
+
parentStepAttempt
|
|
2143
|
+
});
|
|
2144
|
+
if (!started) {
|
|
2145
|
+
throw new NagiRuntimeError(
|
|
2146
|
+
`startChildRun: minted child runId collided with an existing run (${childRunId})`
|
|
2147
|
+
);
|
|
2148
|
+
}
|
|
2149
|
+
return childRunId;
|
|
2150
|
+
}
|
|
2151
|
+
async function cancelRunRecursive(runId, args) {
|
|
2152
|
+
const state = await config.store.loadRunState(runId);
|
|
2153
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2154
|
+
config.logger?.info("nagi: cancel skipped \u2014 run already terminal", {
|
|
2155
|
+
runId,
|
|
2156
|
+
status: state.status
|
|
2157
|
+
});
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
const flow2 = flowsById.get(state.flowId);
|
|
2161
|
+
const canceledFact = args.cause === "operator" ? {
|
|
2162
|
+
kind: "flow.canceled",
|
|
2163
|
+
cause: "operator",
|
|
2164
|
+
runId,
|
|
2165
|
+
at: clock.now(),
|
|
2166
|
+
actor: args.actor,
|
|
2167
|
+
reason: args.reason,
|
|
2168
|
+
...args.note !== void 0 ? { note: args.note } : {}
|
|
2169
|
+
} : {
|
|
2170
|
+
kind: "flow.canceled",
|
|
2171
|
+
cause: "explicit",
|
|
2172
|
+
runId,
|
|
2173
|
+
at: clock.now(),
|
|
2174
|
+
reason: args.reason,
|
|
2175
|
+
...args.note !== void 0 ? { note: args.note } : {}
|
|
2176
|
+
};
|
|
2177
|
+
await config.store.appendFact(runId, canceledFact);
|
|
2178
|
+
const cancelError = {
|
|
2179
|
+
name: "NagiCanceledError",
|
|
2180
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2181
|
+
};
|
|
2182
|
+
if (flow2 !== void 0) {
|
|
2183
|
+
const event = {
|
|
2184
|
+
runId,
|
|
2185
|
+
flowId: flow2.id,
|
|
2186
|
+
error: cancelError,
|
|
2187
|
+
at: clock.now()
|
|
2188
|
+
};
|
|
2189
|
+
await fireHook(flow2.onError, event, "flow.onError", dispatchDeps);
|
|
2190
|
+
await fireHook(
|
|
2191
|
+
config.hooks?.onFlowError,
|
|
2192
|
+
event,
|
|
2193
|
+
"onFlowError",
|
|
2194
|
+
dispatchDeps
|
|
2195
|
+
);
|
|
2196
|
+
}
|
|
2197
|
+
const children = await config.store.listChildren(runId);
|
|
2198
|
+
for (const childId of children) {
|
|
2199
|
+
await cancelRunRecursive(childId, {
|
|
2200
|
+
cause: "explicit",
|
|
2201
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2202
|
+
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
await propagateToParent(dispatchDeps, runId, {
|
|
2206
|
+
kind: "canceled",
|
|
2207
|
+
error: cancelError
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
1814
2210
|
const dispatchDeps = {
|
|
1815
2211
|
flowFor,
|
|
2212
|
+
lookupFlow,
|
|
2213
|
+
startChildRun,
|
|
1816
2214
|
store: config.store,
|
|
1817
2215
|
queue: config.queue,
|
|
1818
2216
|
clock,
|
|
@@ -1820,11 +2218,15 @@ async function nagi(config) {
|
|
|
1820
2218
|
...config.logger !== void 0 ? { logger: config.logger } : {},
|
|
1821
2219
|
...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
|
|
1822
2220
|
};
|
|
1823
|
-
|
|
2221
|
+
const wf = {
|
|
1824
2222
|
async start(flow2, input, opts) {
|
|
1825
|
-
|
|
2223
|
+
return wf.startById(flow2.id, input, opts);
|
|
2224
|
+
},
|
|
2225
|
+
async startById(flowId, input, opts) {
|
|
2226
|
+
const flow2 = flowsById.get(flowId);
|
|
2227
|
+
if (!flow2) {
|
|
1826
2228
|
throw new NagiRuntimeError(
|
|
1827
|
-
`Flow "${
|
|
2229
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1828
2230
|
);
|
|
1829
2231
|
}
|
|
1830
2232
|
let runId;
|
|
@@ -1842,91 +2244,7 @@ async function nagi(config) {
|
|
|
1842
2244
|
runId = mintRunId();
|
|
1843
2245
|
}
|
|
1844
2246
|
const validated = await validate(flow2.input, input);
|
|
1845
|
-
|
|
1846
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
1847
|
-
const fact = {
|
|
1848
|
-
kind: "flow.started",
|
|
1849
|
-
runId,
|
|
1850
|
-
flowId: flow2.id,
|
|
1851
|
-
input: validated,
|
|
1852
|
-
at: startedAt,
|
|
1853
|
-
...flowHash !== void 0 ? { flowHash } : {},
|
|
1854
|
-
codeVersion
|
|
1855
|
-
};
|
|
1856
|
-
let concurrencyArg;
|
|
1857
|
-
if (flow2.concurrency !== void 0) {
|
|
1858
|
-
const derived = flow2.concurrency.keyFn(validated);
|
|
1859
|
-
if (typeof derived !== "string" || derived.length === 0) {
|
|
1860
|
-
throw new NagiValidationError([
|
|
1861
|
-
{
|
|
1862
|
-
message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
1863
|
-
path: ["concurrency", "keyFn"]
|
|
1864
|
-
}
|
|
1865
|
-
]);
|
|
1866
|
-
}
|
|
1867
|
-
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
1868
|
-
}
|
|
1869
|
-
const { started, canceled } = await config.store.tryStartRun(
|
|
1870
|
-
runId,
|
|
1871
|
-
fact,
|
|
1872
|
-
concurrencyArg
|
|
1873
|
-
);
|
|
1874
|
-
if (!started) {
|
|
1875
|
-
return runId;
|
|
1876
|
-
}
|
|
1877
|
-
for (const c of canceled) {
|
|
1878
|
-
const cancelError = new NagiCanceledError({
|
|
1879
|
-
runId: c.runId,
|
|
1880
|
-
canceledByRunId: runId,
|
|
1881
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
1882
|
-
});
|
|
1883
|
-
const serialized = {
|
|
1884
|
-
name: cancelError.name,
|
|
1885
|
-
message: cancelError.message,
|
|
1886
|
-
...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
|
|
1887
|
-
cause: {
|
|
1888
|
-
canceledByRunId: runId,
|
|
1889
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
1890
|
-
}
|
|
1891
|
-
};
|
|
1892
|
-
const errorEvent = {
|
|
1893
|
-
runId: c.runId,
|
|
1894
|
-
flowId: flow2.id,
|
|
1895
|
-
error: serialized,
|
|
1896
|
-
at: c.fact.at
|
|
1897
|
-
};
|
|
1898
|
-
await fireHook(
|
|
1899
|
-
flow2.onError,
|
|
1900
|
-
errorEvent,
|
|
1901
|
-
"flow.onError",
|
|
1902
|
-
dispatchDeps
|
|
1903
|
-
);
|
|
1904
|
-
await fireHook(
|
|
1905
|
-
config.hooks?.onFlowError,
|
|
1906
|
-
errorEvent,
|
|
1907
|
-
"onFlowError",
|
|
1908
|
-
dispatchDeps
|
|
1909
|
-
);
|
|
1910
|
-
}
|
|
1911
|
-
const startEvent = {
|
|
1912
|
-
runId,
|
|
1913
|
-
flowId: flow2.id,
|
|
1914
|
-
input: validated,
|
|
1915
|
-
at: startedAt
|
|
1916
|
-
};
|
|
1917
|
-
await fireHook(
|
|
1918
|
-
flow2.onStart,
|
|
1919
|
-
startEvent,
|
|
1920
|
-
"flow.onStart",
|
|
1921
|
-
dispatchDeps
|
|
1922
|
-
);
|
|
1923
|
-
await fireHook(
|
|
1924
|
-
config.hooks?.onFlowStart,
|
|
1925
|
-
startEvent,
|
|
1926
|
-
"onFlowStart",
|
|
1927
|
-
dispatchDeps
|
|
1928
|
-
);
|
|
1929
|
-
await advance(dispatchDeps, runId);
|
|
2247
|
+
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
1930
2248
|
return runId;
|
|
1931
2249
|
},
|
|
1932
2250
|
async signal(runId, signalName, payload) {
|
|
@@ -2012,6 +2330,21 @@ async function nagi(config) {
|
|
|
2012
2330
|
);
|
|
2013
2331
|
await advance(dispatchDeps, runId);
|
|
2014
2332
|
},
|
|
2333
|
+
async cancel(runId, opts) {
|
|
2334
|
+
await cancelRunRecursive(runId, {
|
|
2335
|
+
cause: "explicit",
|
|
2336
|
+
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
2337
|
+
});
|
|
2338
|
+
},
|
|
2339
|
+
operator() {
|
|
2340
|
+
return makeOperator({
|
|
2341
|
+
deps: dispatchDeps,
|
|
2342
|
+
clock,
|
|
2343
|
+
flowsById,
|
|
2344
|
+
cancelRunRecursive,
|
|
2345
|
+
...config.logger !== void 0 ? { logger: config.logger } : {}
|
|
2346
|
+
});
|
|
2347
|
+
},
|
|
2015
2348
|
worker(workerConfig) {
|
|
2016
2349
|
if (config.flows.length === 0) {
|
|
2017
2350
|
throw new NagiRuntimeError(
|
|
@@ -2105,8 +2438,54 @@ async function nagi(config) {
|
|
|
2105
2438
|
}
|
|
2106
2439
|
}
|
|
2107
2440
|
return config.store.queryRuns(opts);
|
|
2441
|
+
},
|
|
2442
|
+
async pruneFacts(opts) {
|
|
2443
|
+
if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
|
|
2444
|
+
throw new NagiValidationError([
|
|
2445
|
+
{
|
|
2446
|
+
message: "pruneFacts: `olderThan` must be a valid Date.",
|
|
2447
|
+
path: ["olderThan"]
|
|
2448
|
+
}
|
|
2449
|
+
]);
|
|
2450
|
+
}
|
|
2451
|
+
const statuses = opts.statuses ?? [
|
|
2452
|
+
"completed"
|
|
2453
|
+
];
|
|
2454
|
+
for (const s of statuses) {
|
|
2455
|
+
if (s !== "completed" && s !== "failed" && s !== "canceled") {
|
|
2456
|
+
throw new NagiValidationError([
|
|
2457
|
+
{
|
|
2458
|
+
message: `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
|
|
2459
|
+
path: ["statuses"]
|
|
2460
|
+
}
|
|
2461
|
+
]);
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
const batchSize = opts.batchSize ?? 1e3;
|
|
2465
|
+
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
2466
|
+
throw new NagiValidationError([
|
|
2467
|
+
{
|
|
2468
|
+
message: "pruneFacts: `batchSize` must be a positive integer.",
|
|
2469
|
+
path: ["batchSize"]
|
|
2470
|
+
}
|
|
2471
|
+
]);
|
|
2472
|
+
}
|
|
2473
|
+
const keepSummary = opts.keepSummary ?? true;
|
|
2474
|
+
return config.store.pruneFacts({
|
|
2475
|
+
olderThan: opts.olderThan,
|
|
2476
|
+
statuses,
|
|
2477
|
+
batchSize,
|
|
2478
|
+
keepSummary
|
|
2479
|
+
});
|
|
2108
2480
|
}
|
|
2109
2481
|
};
|
|
2482
|
+
Object.defineProperty(wf, "__dispatchDeps", {
|
|
2483
|
+
value: dispatchDeps,
|
|
2484
|
+
enumerable: false,
|
|
2485
|
+
writable: false,
|
|
2486
|
+
configurable: false
|
|
2487
|
+
});
|
|
2488
|
+
return wf;
|
|
2110
2489
|
}
|
|
2111
2490
|
function mintRunId() {
|
|
2112
2491
|
return `run-${crypto.randomUUID()}`;
|
|
@@ -2119,6 +2498,161 @@ async function drainInline(deps) {
|
|
|
2119
2498
|
for (const msg of messages) await dispatchMessage(deps, msg);
|
|
2120
2499
|
}
|
|
2121
2500
|
}
|
|
2501
|
+
function makeOperator(o) {
|
|
2502
|
+
const { deps, clock, flowsById, cancelRunRecursive } = o;
|
|
2503
|
+
const store = deps.store;
|
|
2504
|
+
function resolveFlow(flowId, runId) {
|
|
2505
|
+
const flow2 = flowsById.get(flowId);
|
|
2506
|
+
if (!flow2) {
|
|
2507
|
+
throw new NagiRuntimeError(
|
|
2508
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
2509
|
+
);
|
|
2510
|
+
}
|
|
2511
|
+
return flow2;
|
|
2512
|
+
}
|
|
2513
|
+
async function skip(runId, stepId, opts) {
|
|
2514
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2515
|
+
throw new NagiValidationError([
|
|
2516
|
+
{
|
|
2517
|
+
message: "operator.skip: opts.actor must be a non-empty string",
|
|
2518
|
+
path: ["actor"]
|
|
2519
|
+
}
|
|
2520
|
+
]);
|
|
2521
|
+
}
|
|
2522
|
+
const cascade = opts.cascade ?? "skip";
|
|
2523
|
+
const state = await store.loadRunState(runId);
|
|
2524
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2525
|
+
if (!(stepId in flow2.steps)) {
|
|
2526
|
+
throw new NagiValidationError([
|
|
2527
|
+
{
|
|
2528
|
+
message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2529
|
+
path: ["stepId"]
|
|
2530
|
+
}
|
|
2531
|
+
]);
|
|
2532
|
+
}
|
|
2533
|
+
const stepState = state.steps[stepId];
|
|
2534
|
+
if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
|
|
2535
|
+
o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
|
|
2536
|
+
runId,
|
|
2537
|
+
stepId,
|
|
2538
|
+
status: stepState.status
|
|
2539
|
+
});
|
|
2540
|
+
return;
|
|
2541
|
+
}
|
|
2542
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2543
|
+
throw new NagiRuntimeError(
|
|
2544
|
+
`operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
|
|
2545
|
+
);
|
|
2546
|
+
}
|
|
2547
|
+
const fact = {
|
|
2548
|
+
kind: "step.skipped",
|
|
2549
|
+
runId,
|
|
2550
|
+
at: clock.now(),
|
|
2551
|
+
stepId,
|
|
2552
|
+
reason: "manual",
|
|
2553
|
+
actor: opts.actor,
|
|
2554
|
+
cascade,
|
|
2555
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2556
|
+
};
|
|
2557
|
+
await store.appendFact(runId, fact);
|
|
2558
|
+
await advance(deps, runId);
|
|
2559
|
+
}
|
|
2560
|
+
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
2561
|
+
const start = Date.now();
|
|
2562
|
+
while (Date.now() - start < deadlineMs) {
|
|
2563
|
+
const s = await store.loadRunState(runId);
|
|
2564
|
+
const ss = s.steps[stepId];
|
|
2565
|
+
if (ss === void 0) return;
|
|
2566
|
+
if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
|
|
2567
|
+
return;
|
|
2568
|
+
}
|
|
2569
|
+
if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
|
|
2570
|
+
return;
|
|
2571
|
+
}
|
|
2572
|
+
if (ss.attempts > attempt) return;
|
|
2573
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
2574
|
+
}
|
|
2575
|
+
throw new NagiRuntimeError(
|
|
2576
|
+
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
2577
|
+
);
|
|
2578
|
+
}
|
|
2579
|
+
async function retry(runId, stepId, opts) {
|
|
2580
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2581
|
+
throw new NagiValidationError([
|
|
2582
|
+
{
|
|
2583
|
+
message: "operator.retry: opts.actor must be a non-empty string",
|
|
2584
|
+
path: ["actor"]
|
|
2585
|
+
}
|
|
2586
|
+
]);
|
|
2587
|
+
}
|
|
2588
|
+
const state = await store.loadRunState(runId);
|
|
2589
|
+
if (state.status === "canceled") {
|
|
2590
|
+
throw new NagiRuntimeError(
|
|
2591
|
+
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
2592
|
+
);
|
|
2593
|
+
}
|
|
2594
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2595
|
+
if (!(stepId in flow2.steps)) {
|
|
2596
|
+
throw new NagiValidationError([
|
|
2597
|
+
{
|
|
2598
|
+
message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2599
|
+
path: ["stepId"]
|
|
2600
|
+
}
|
|
2601
|
+
]);
|
|
2602
|
+
}
|
|
2603
|
+
const stepState = state.steps[stepId];
|
|
2604
|
+
if (stepState !== void 0 && stepState.status === "running") {
|
|
2605
|
+
const abortFact = {
|
|
2606
|
+
kind: "step.abort-requested",
|
|
2607
|
+
runId,
|
|
2608
|
+
at: clock.now(),
|
|
2609
|
+
stepId,
|
|
2610
|
+
attempt: stepState.attempts,
|
|
2611
|
+
actor: opts.actor,
|
|
2612
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2613
|
+
};
|
|
2614
|
+
await store.appendFact(runId, abortFact);
|
|
2615
|
+
await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
|
|
2616
|
+
}
|
|
2617
|
+
const cascade = descendantsOf(flow2, stepId);
|
|
2618
|
+
const at = clock.now();
|
|
2619
|
+
for (const id of cascade) {
|
|
2620
|
+
const fact = id === stepId ? {
|
|
2621
|
+
kind: "step.reset",
|
|
2622
|
+
runId,
|
|
2623
|
+
at,
|
|
2624
|
+
stepId: id,
|
|
2625
|
+
actor: opts.actor,
|
|
2626
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2627
|
+
} : {
|
|
2628
|
+
kind: "step.reset",
|
|
2629
|
+
runId,
|
|
2630
|
+
at,
|
|
2631
|
+
stepId: id,
|
|
2632
|
+
cascadedFrom: stepId
|
|
2633
|
+
};
|
|
2634
|
+
await store.appendFact(runId, fact);
|
|
2635
|
+
}
|
|
2636
|
+
await advance(deps, runId);
|
|
2637
|
+
}
|
|
2638
|
+
async function abort(runId, opts) {
|
|
2639
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2640
|
+
throw new NagiValidationError([
|
|
2641
|
+
{
|
|
2642
|
+
message: "operator.abort: opts.actor must be a non-empty string",
|
|
2643
|
+
path: ["actor"]
|
|
2644
|
+
}
|
|
2645
|
+
]);
|
|
2646
|
+
}
|
|
2647
|
+
await cancelRunRecursive(runId, {
|
|
2648
|
+
cause: "operator",
|
|
2649
|
+
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
2650
|
+
actor: opts.actor,
|
|
2651
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2652
|
+
});
|
|
2653
|
+
}
|
|
2654
|
+
return { skip, retry, abort };
|
|
2655
|
+
}
|
|
2122
2656
|
async function validate(schema, value) {
|
|
2123
2657
|
const result = await schema["~standard"].validate(value);
|
|
2124
2658
|
if ("issues" in result && result.issues !== void 0) {
|