@nagi-js/core 0.1.1-rc.6 → 0.1.1-rc.7
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 +383 -18
- package/dist/index.js +803 -126
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -115,6 +115,22 @@ function makeBuilder() {
|
|
|
115
115
|
};
|
|
116
116
|
return attachDef({ kind: "signal", id: "" }, def);
|
|
117
117
|
}
|
|
118
|
+
function subflow(child, config) {
|
|
119
|
+
const def = {
|
|
120
|
+
kind: "subflow",
|
|
121
|
+
needs: config.needs ?? {},
|
|
122
|
+
childFlowId: child.id,
|
|
123
|
+
buildInput: config.input,
|
|
124
|
+
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
125
|
+
...config.when !== void 0 ? {
|
|
126
|
+
when: config.when
|
|
127
|
+
} : {}
|
|
128
|
+
};
|
|
129
|
+
return attachDef(
|
|
130
|
+
{ kind: "subflow", id: "" },
|
|
131
|
+
def
|
|
132
|
+
);
|
|
133
|
+
}
|
|
118
134
|
function match(config) {
|
|
119
135
|
const needs = "needs" in config && config.needs ? config.needs : {};
|
|
120
136
|
if (isDiscriminator(config)) {
|
|
@@ -209,6 +225,7 @@ function makeBuilder() {
|
|
|
209
225
|
const builder = {
|
|
210
226
|
task,
|
|
211
227
|
signal,
|
|
228
|
+
subflow,
|
|
212
229
|
match,
|
|
213
230
|
step,
|
|
214
231
|
include,
|
|
@@ -388,6 +405,7 @@ async function canonicalizeStep(id, def) {
|
|
|
388
405
|
const base = { id, kind: def.kind, needs };
|
|
389
406
|
if (def.kind === "task") return canonicalizeTask(base, def);
|
|
390
407
|
if (def.kind === "signal") return canonicalizeSignal(base, def);
|
|
408
|
+
if (def.kind === "subflow") return canonicalizeSubflow(base, def);
|
|
391
409
|
return canonicalizeMatch(base, def);
|
|
392
410
|
}
|
|
393
411
|
async function canonicalizeTask(base, def) {
|
|
@@ -407,6 +425,14 @@ async function canonicalizeSignal(base, def) {
|
|
|
407
425
|
}
|
|
408
426
|
return out;
|
|
409
427
|
}
|
|
428
|
+
async function canonicalizeSubflow(base, def) {
|
|
429
|
+
const out = { ...base };
|
|
430
|
+
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
431
|
+
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
432
|
+
out.childFlowId = def.childFlowId;
|
|
433
|
+
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
410
436
|
async function canonicalizeMatch(base, def) {
|
|
411
437
|
const out = { ...base };
|
|
412
438
|
out.matchMode = def.mode;
|
|
@@ -615,6 +641,20 @@ var InMemoryStore = class {
|
|
|
615
641
|
activeByKey = /* @__PURE__ */ new Map();
|
|
616
642
|
/** Reverse lookup so terminal facts can free the slot in O(1). */
|
|
617
643
|
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
644
|
+
/**
|
|
645
|
+
* Index: parentRunId → set of child run ids spawned by `b.subflow()`.
|
|
646
|
+
* Populated in `tryStartRun` when `fact.parentRunId` is set. Used by
|
|
647
|
+
* `listChildren()` to power transitive cancel cascade in O(children).
|
|
648
|
+
*/
|
|
649
|
+
childrenByParent = /* @__PURE__ */ new Map();
|
|
650
|
+
/**
|
|
651
|
+
* Pruned-but-kept summaries. Populated by `pruneFacts` when `keepSummary`
|
|
652
|
+
* is true so that `queryRuns` still surfaces runs whose facts were dropped.
|
|
653
|
+
* Mirrors the postgres adapter's retained `workflow_run` row after a prune.
|
|
654
|
+
* Also blocks `tryStartRun` from reusing a pruned runId — matching the
|
|
655
|
+
* postgres `INSERT ... ON CONFLICT DO NOTHING` semantic on `run_id`.
|
|
656
|
+
*/
|
|
657
|
+
summaries = /* @__PURE__ */ new Map();
|
|
618
658
|
leaseMs;
|
|
619
659
|
constructor(opts = {}) {
|
|
620
660
|
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
@@ -641,7 +681,7 @@ var InMemoryStore = class {
|
|
|
641
681
|
}
|
|
642
682
|
}
|
|
643
683
|
async tryStartRun(runId, fact, concurrency) {
|
|
644
|
-
if (this.facts.has(runId)) {
|
|
684
|
+
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
645
685
|
return { started: false, canceled: [] };
|
|
646
686
|
}
|
|
647
687
|
const canceled = [];
|
|
@@ -663,8 +703,18 @@ var InMemoryStore = class {
|
|
|
663
703
|
this.keyByActiveRun.set(runId, slot);
|
|
664
704
|
}
|
|
665
705
|
this.facts.set(runId, [fact]);
|
|
706
|
+
if (fact.parentRunId !== void 0) {
|
|
707
|
+
const set = this.childrenByParent.get(fact.parentRunId) ?? /* @__PURE__ */ new Set();
|
|
708
|
+
set.add(runId);
|
|
709
|
+
this.childrenByParent.set(fact.parentRunId, set);
|
|
710
|
+
}
|
|
666
711
|
return { started: true, canceled };
|
|
667
712
|
}
|
|
713
|
+
async listChildren(parentRunId) {
|
|
714
|
+
const set = this.childrenByParent.get(parentRunId);
|
|
715
|
+
if (set === void 0) return [];
|
|
716
|
+
return Array.from(set);
|
|
717
|
+
}
|
|
668
718
|
async loadRunState(runId) {
|
|
669
719
|
return projectRunState(runId, this.facts.get(runId) ?? []);
|
|
670
720
|
}
|
|
@@ -699,8 +749,10 @@ var InMemoryStore = class {
|
|
|
699
749
|
const result = await body(void 0);
|
|
700
750
|
if (result.fact.kind === "step.completed") {
|
|
701
751
|
await this.completeStep(runId, stepId, result.output, result.fact);
|
|
702
|
-
} else {
|
|
752
|
+
} else if (result.fact.kind === "step.failed") {
|
|
703
753
|
await this.failStep(runId, stepId, result.fact.error, result.fact);
|
|
754
|
+
} else {
|
|
755
|
+
await this.appendFact(runId, result.fact);
|
|
704
756
|
}
|
|
705
757
|
return result.output;
|
|
706
758
|
}
|
|
@@ -727,17 +779,23 @@ var InMemoryStore = class {
|
|
|
727
779
|
async queryRuns(opts) {
|
|
728
780
|
const where = opts.where ?? {};
|
|
729
781
|
const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
|
|
782
|
+
const matches = (summary) => {
|
|
783
|
+
if (where.flowId !== void 0 && summary.flowId !== where.flowId)
|
|
784
|
+
return false;
|
|
785
|
+
if (statuses !== void 0 && !statuses.includes(summary.status))
|
|
786
|
+
return false;
|
|
787
|
+
if (where.input !== void 0 && !containsJson(summary.input, where.input))
|
|
788
|
+
return false;
|
|
789
|
+
return true;
|
|
790
|
+
};
|
|
730
791
|
const summaries = [];
|
|
731
792
|
for (const [runId, factList] of this.facts) {
|
|
732
793
|
const summary = summarize(runId, factList);
|
|
733
794
|
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);
|
|
795
|
+
if (matches(summary)) summaries.push(summary);
|
|
796
|
+
}
|
|
797
|
+
for (const summary of this.summaries.values()) {
|
|
798
|
+
if (matches(summary)) summaries.push(summary);
|
|
741
799
|
}
|
|
742
800
|
summaries.sort((a, b) => {
|
|
743
801
|
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
@@ -762,7 +820,57 @@ var InMemoryStore = class {
|
|
|
762
820
|
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
763
821
|
return { runs: page, cursor };
|
|
764
822
|
}
|
|
823
|
+
async pruneFacts(opts) {
|
|
824
|
+
const olderThanMs = opts.olderThan.getTime();
|
|
825
|
+
const statusSet = new Set(opts.statuses);
|
|
826
|
+
const victims = [];
|
|
827
|
+
for (const [runId, factList] of this.facts) {
|
|
828
|
+
const summary = summarize(runId, factList);
|
|
829
|
+
if (summary === null) continue;
|
|
830
|
+
if (summary.completedAt === null) continue;
|
|
831
|
+
if (!statusSet.has(summary.status)) continue;
|
|
832
|
+
if (summary.completedAt.getTime() >= olderThanMs) continue;
|
|
833
|
+
const first = factList[0];
|
|
834
|
+
const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parentRunId : void 0;
|
|
835
|
+
victims.push({
|
|
836
|
+
runId,
|
|
837
|
+
summary,
|
|
838
|
+
factCount: factList.length,
|
|
839
|
+
parentRunId
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
let runsPruned = 0;
|
|
843
|
+
let factsPruned = 0;
|
|
844
|
+
for (const v of victims) {
|
|
845
|
+
this.facts.delete(v.runId);
|
|
846
|
+
deleteByRunPrefix(this.outputs, v.runId);
|
|
847
|
+
deleteByRunPrefix(this.onces, v.runId);
|
|
848
|
+
deleteByRunPrefix(this.leases, v.runId);
|
|
849
|
+
this.childrenByParent.delete(v.runId);
|
|
850
|
+
if (v.parentRunId !== void 0) {
|
|
851
|
+
const siblings = this.childrenByParent.get(v.parentRunId);
|
|
852
|
+
if (siblings !== void 0) {
|
|
853
|
+
siblings.delete(v.runId);
|
|
854
|
+
if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
if (opts.keepSummary) {
|
|
858
|
+
this.summaries.set(v.runId, v.summary);
|
|
859
|
+
} else {
|
|
860
|
+
this.summaries.delete(v.runId);
|
|
861
|
+
}
|
|
862
|
+
runsPruned += 1;
|
|
863
|
+
factsPruned += v.factCount;
|
|
864
|
+
}
|
|
865
|
+
return { runsPruned, factsPruned };
|
|
866
|
+
}
|
|
765
867
|
};
|
|
868
|
+
function deleteByRunPrefix(map, runId) {
|
|
869
|
+
const prefix = `${runId}::`;
|
|
870
|
+
for (const key of map.keys()) {
|
|
871
|
+
if (key.startsWith(prefix)) map.delete(key);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
766
874
|
function summarize(runId, facts) {
|
|
767
875
|
const first = facts[0];
|
|
768
876
|
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
@@ -877,6 +985,14 @@ function projectRunState(runId, facts) {
|
|
|
877
985
|
error: fact.error
|
|
878
986
|
};
|
|
879
987
|
break;
|
|
988
|
+
case "step.canceled":
|
|
989
|
+
steps[fact.stepId] = {
|
|
990
|
+
stepId: fact.stepId,
|
|
991
|
+
status: "canceled",
|
|
992
|
+
attempts: fact.attempt,
|
|
993
|
+
...fact.error !== void 0 ? { error: fact.error } : {}
|
|
994
|
+
};
|
|
995
|
+
break;
|
|
880
996
|
case "step.skipped":
|
|
881
997
|
steps[fact.stepId] = {
|
|
882
998
|
stepId: fact.stepId,
|
|
@@ -1073,13 +1189,28 @@ function checkUpstream(def, runState) {
|
|
|
1073
1189
|
const upstreamState = runState.steps[upstream.id];
|
|
1074
1190
|
if (upstreamState === void 0) return "blocked";
|
|
1075
1191
|
if (upstreamState.status === "completed") continue;
|
|
1076
|
-
if (upstreamState.status === "skipped"
|
|
1192
|
+
if (upstreamState.status === "skipped") {
|
|
1193
|
+
if (manualSkipCascade(upstream.id, runState) === "continue") continue;
|
|
1194
|
+
return "transitive-skip";
|
|
1195
|
+
}
|
|
1196
|
+
if (upstreamState.status === "failed") {
|
|
1077
1197
|
return "transitive-skip";
|
|
1078
1198
|
}
|
|
1079
1199
|
return "blocked";
|
|
1080
1200
|
}
|
|
1081
1201
|
return "ready";
|
|
1082
1202
|
}
|
|
1203
|
+
function manualSkipCascade(stepId, runState) {
|
|
1204
|
+
for (let i = runState.facts.length - 1; i >= 0; i--) {
|
|
1205
|
+
const f = runState.facts[i];
|
|
1206
|
+
if (f === void 0) continue;
|
|
1207
|
+
if (f.kind !== "step.skipped") continue;
|
|
1208
|
+
if (f.stepId !== stepId) continue;
|
|
1209
|
+
if (f.reason !== "manual") return "skip";
|
|
1210
|
+
return f.cascade ?? "skip";
|
|
1211
|
+
}
|
|
1212
|
+
return "skip";
|
|
1213
|
+
}
|
|
1083
1214
|
function checkParentMatch(def, runState) {
|
|
1084
1215
|
if (!def.parentMatch) return "ready";
|
|
1085
1216
|
const { matchId, armId } = def.parentMatch;
|
|
@@ -1225,7 +1356,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1225
1356
|
attempt,
|
|
1226
1357
|
at: clock.now()
|
|
1227
1358
|
});
|
|
1228
|
-
const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1359
|
+
const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1229
1360
|
const startEvent = {
|
|
1230
1361
|
runId,
|
|
1231
1362
|
flowId: flow2.id,
|
|
@@ -1241,7 +1372,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1241
1372
|
const startedAt = Date.now();
|
|
1242
1373
|
try {
|
|
1243
1374
|
if (def.kind === "task") {
|
|
1244
|
-
const output = await executeTask({
|
|
1375
|
+
const { output, skipAdvance } = await executeTask({
|
|
1245
1376
|
deps,
|
|
1246
1377
|
message,
|
|
1247
1378
|
def,
|
|
@@ -1249,6 +1380,7 @@ async function dispatchMessage(deps, message) {
|
|
|
1249
1380
|
stepId,
|
|
1250
1381
|
attempt
|
|
1251
1382
|
});
|
|
1383
|
+
if (skipAdvance) return;
|
|
1252
1384
|
const completeEvent = {
|
|
1253
1385
|
runId,
|
|
1254
1386
|
flowId: flow2.id,
|
|
@@ -1273,6 +1405,10 @@ async function dispatchMessage(deps, message) {
|
|
|
1273
1405
|
} else if (def.kind === "match") {
|
|
1274
1406
|
await executeMatch({ deps, message, def, runId, stepId, attempt });
|
|
1275
1407
|
await advance(deps, runId);
|
|
1408
|
+
} else if (def.kind === "subflow") {
|
|
1409
|
+
await executeSubflow({ deps, message, def, runId, stepId });
|
|
1410
|
+
await queue.ack(message.receipt);
|
|
1411
|
+
return;
|
|
1276
1412
|
}
|
|
1277
1413
|
} catch (err) {
|
|
1278
1414
|
await handleStepError({
|
|
@@ -1296,35 +1432,148 @@ async function executeTask(args) {
|
|
|
1296
1432
|
const runState = await store.loadRunState(runId);
|
|
1297
1433
|
const input = extractInput(runState);
|
|
1298
1434
|
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1299
|
-
const
|
|
1435
|
+
const ac = new AbortController();
|
|
1436
|
+
const watcher = startCancelWatcher({
|
|
1437
|
+
store,
|
|
1300
1438
|
runId,
|
|
1301
1439
|
stepId,
|
|
1302
1440
|
attempt,
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1441
|
+
ac,
|
|
1442
|
+
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
1443
|
+
});
|
|
1444
|
+
try {
|
|
1445
|
+
let stepAbortedHere = false;
|
|
1446
|
+
const output = await store.runStep(
|
|
1447
|
+
runId,
|
|
1448
|
+
stepId,
|
|
1449
|
+
attempt,
|
|
1450
|
+
async (tx) => {
|
|
1451
|
+
const ctx = makeStepCtx({
|
|
1452
|
+
runId,
|
|
1453
|
+
stepId,
|
|
1454
|
+
attempt,
|
|
1455
|
+
input,
|
|
1456
|
+
store,
|
|
1457
|
+
clock,
|
|
1458
|
+
tx,
|
|
1459
|
+
signal: ac.signal,
|
|
1460
|
+
...deps.logger !== void 0 ? { logger: deps.logger } : {}
|
|
1461
|
+
});
|
|
1462
|
+
const out = await def.run({ input, needs, ctx });
|
|
1463
|
+
const postState = await store.loadRunState(runId);
|
|
1464
|
+
if (postState.status === "canceled") {
|
|
1465
|
+
const canceledFact = {
|
|
1466
|
+
kind: "step.canceled",
|
|
1467
|
+
runId,
|
|
1468
|
+
stepId,
|
|
1469
|
+
attempt,
|
|
1470
|
+
at: clock.now()
|
|
1471
|
+
};
|
|
1472
|
+
return { output: out, fact: canceledFact };
|
|
1473
|
+
}
|
|
1474
|
+
if (hasAbortRequest(postState.facts, stepId, attempt)) {
|
|
1475
|
+
stepAbortedHere = true;
|
|
1476
|
+
const canceledFact = {
|
|
1477
|
+
kind: "step.canceled",
|
|
1478
|
+
runId,
|
|
1479
|
+
stepId,
|
|
1480
|
+
attempt,
|
|
1481
|
+
at: clock.now()
|
|
1482
|
+
};
|
|
1483
|
+
return { output: out, fact: canceledFact };
|
|
1484
|
+
}
|
|
1485
|
+
const fact = {
|
|
1486
|
+
kind: "step.completed",
|
|
1487
|
+
runId,
|
|
1488
|
+
stepId,
|
|
1489
|
+
attempt,
|
|
1490
|
+
output: out,
|
|
1491
|
+
at: clock.now()
|
|
1492
|
+
};
|
|
1493
|
+
return { output: out, fact };
|
|
1494
|
+
}
|
|
1495
|
+
);
|
|
1496
|
+
await queue.ack(message.receipt);
|
|
1497
|
+
return { output, skipAdvance: stepAbortedHere };
|
|
1498
|
+
} finally {
|
|
1499
|
+
watcher.stop();
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1503
|
+
function startCancelWatcher(args) {
|
|
1504
|
+
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
1505
|
+
let stopped = false;
|
|
1506
|
+
void (async () => {
|
|
1507
|
+
while (!stopped) {
|
|
1508
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
1509
|
+
if (stopped) return;
|
|
1510
|
+
try {
|
|
1511
|
+
const s = await store.loadRunState(runId);
|
|
1512
|
+
if (s.status === "canceled" || s.status === "failed" || s.status === "completed") {
|
|
1513
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
if (hasAbortRequest(s.facts, stepId, attempt)) {
|
|
1517
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
} catch {
|
|
1521
|
+
}
|
|
1324
1522
|
}
|
|
1325
|
-
);
|
|
1326
|
-
|
|
1327
|
-
|
|
1523
|
+
})();
|
|
1524
|
+
return {
|
|
1525
|
+
stop: () => {
|
|
1526
|
+
stopped = true;
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
function hasAbortRequest(facts, stepId, attempt) {
|
|
1531
|
+
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1532
|
+
const f = facts[i];
|
|
1533
|
+
if (f === void 0) continue;
|
|
1534
|
+
if (f.kind === "step.reset" && f.stepId === stepId) return false;
|
|
1535
|
+
if (f.kind === "step.abort-requested" && f.stepId === stepId && f.attempt === attempt) {
|
|
1536
|
+
return true;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
return false;
|
|
1540
|
+
}
|
|
1541
|
+
var NagiAbortError = class extends Error {
|
|
1542
|
+
runId;
|
|
1543
|
+
scope;
|
|
1544
|
+
constructor(runId, scope) {
|
|
1545
|
+
super(
|
|
1546
|
+
scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
1547
|
+
);
|
|
1548
|
+
this.name = "NagiAbortError";
|
|
1549
|
+
this.runId = runId;
|
|
1550
|
+
this.scope = scope;
|
|
1551
|
+
}
|
|
1552
|
+
};
|
|
1553
|
+
async function executeSubflow(args) {
|
|
1554
|
+
const { deps, def, runId, stepId } = args;
|
|
1555
|
+
const { store } = deps;
|
|
1556
|
+
if (deps.lookupFlow === void 0 || deps.startChildRun === void 0) {
|
|
1557
|
+
throw new Error(
|
|
1558
|
+
`subflow dispatch requires DispatchDeps.lookupFlow + .startChildRun (step "${stepId}" referenced child "${def.childFlowId}")`
|
|
1559
|
+
);
|
|
1560
|
+
}
|
|
1561
|
+
const child = deps.lookupFlow(def.childFlowId);
|
|
1562
|
+
if (child === void 0) {
|
|
1563
|
+
throw new Error(
|
|
1564
|
+
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
1565
|
+
);
|
|
1566
|
+
}
|
|
1567
|
+
const runState = await store.loadRunState(runId);
|
|
1568
|
+
const parentInput = extractInput(runState);
|
|
1569
|
+
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1570
|
+
const childInput = def.buildInput({ input: parentInput, needs });
|
|
1571
|
+
await deps.startChildRun({
|
|
1572
|
+
child,
|
|
1573
|
+
childInput,
|
|
1574
|
+
parentRunId: runId,
|
|
1575
|
+
parentStepId: stepId
|
|
1576
|
+
});
|
|
1328
1577
|
}
|
|
1329
1578
|
async function executeMatch(args) {
|
|
1330
1579
|
const { deps, message, def, runId, stepId } = args;
|
|
@@ -1346,6 +1595,24 @@ async function handleStepError(args) {
|
|
|
1346
1595
|
const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
|
|
1347
1596
|
const { store, queue, clock } = deps;
|
|
1348
1597
|
const error = serializeError(err);
|
|
1598
|
+
const postState = await store.loadRunState(runId);
|
|
1599
|
+
const runIsCanceled = postState.status === "canceled";
|
|
1600
|
+
const stepAborted = hasAbortRequest(postState.facts, stepId, attempt);
|
|
1601
|
+
if (runIsCanceled || stepAborted) {
|
|
1602
|
+
const isAbort = err instanceof Error && (err.name === "AbortError" || err.name === "NagiAbortError");
|
|
1603
|
+
const canceledFact = {
|
|
1604
|
+
kind: "step.canceled",
|
|
1605
|
+
runId,
|
|
1606
|
+
stepId,
|
|
1607
|
+
attempt,
|
|
1608
|
+
...isAbort ? { error } : {},
|
|
1609
|
+
at: clock.now()
|
|
1610
|
+
};
|
|
1611
|
+
await store.appendFact(runId, canceledFact);
|
|
1612
|
+
await queue.ack(message.receipt);
|
|
1613
|
+
if (!stepAborted) await advance(deps, runId);
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1349
1616
|
const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
|
|
1350
1617
|
const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
|
|
1351
1618
|
if (shouldRetry) {
|
|
@@ -1525,14 +1792,13 @@ async function promoteMatches(args) {
|
|
|
1525
1792
|
return promoted;
|
|
1526
1793
|
}
|
|
1527
1794
|
function makeStepCtx(args) {
|
|
1528
|
-
const { runId, stepId, attempt, input, store, clock, tx } = args;
|
|
1529
|
-
const ac = new AbortController();
|
|
1795
|
+
const { runId, stepId, attempt, input, store, clock, tx, signal } = args;
|
|
1530
1796
|
return {
|
|
1531
1797
|
input,
|
|
1532
1798
|
runId,
|
|
1533
1799
|
stepId,
|
|
1534
1800
|
attempt,
|
|
1535
|
-
signal
|
|
1801
|
+
signal,
|
|
1536
1802
|
now: () => clock.now(),
|
|
1537
1803
|
// `tx` is supplied by `Store.runStep` — for adapters with no real
|
|
1538
1804
|
// transaction (in-memory) it is `undefined as Tx`, and handlers that
|
|
@@ -1590,6 +1856,7 @@ async function finalizeFlowFailure(args) {
|
|
|
1590
1856
|
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
1591
1857
|
await fireHook(flow2.onError, event, "flow.onError", deps);
|
|
1592
1858
|
await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
|
|
1859
|
+
await propagateToParent(deps, runId, { kind: "failed", error });
|
|
1593
1860
|
}
|
|
1594
1861
|
async function finalizeFlowCompletion(args) {
|
|
1595
1862
|
const { deps, flow: flow2, runId, runState } = args;
|
|
@@ -1604,6 +1871,102 @@ async function finalizeFlowCompletion(args) {
|
|
|
1604
1871
|
const event = { runId, flowId: flow2.id, output, at: clock.now() };
|
|
1605
1872
|
await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
|
|
1606
1873
|
await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
|
|
1874
|
+
await propagateToParent(deps, runId, { kind: "completed", output });
|
|
1875
|
+
}
|
|
1876
|
+
async function propagateToParent(deps, childRunId, outcome) {
|
|
1877
|
+
const { store, clock } = deps;
|
|
1878
|
+
const childState = await store.loadRunState(childRunId);
|
|
1879
|
+
const startedFact = childState.facts.find((f) => f.kind === "flow.started");
|
|
1880
|
+
if (startedFact?.parentRunId === void 0 || startedFact?.parentStepId === void 0) {
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
const parentRunId = startedFact.parentRunId;
|
|
1884
|
+
const parentStepId = startedFact.parentStepId;
|
|
1885
|
+
const parentState = await store.loadRunState(parentRunId);
|
|
1886
|
+
if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
|
|
1887
|
+
deps.logger?.info(
|
|
1888
|
+
"nagi: subflow wake skipped \u2014 parent run already terminal",
|
|
1889
|
+
{
|
|
1890
|
+
parentRunId,
|
|
1891
|
+
parentStepId,
|
|
1892
|
+
childRunId,
|
|
1893
|
+
parentStatus: parentState.status
|
|
1894
|
+
}
|
|
1895
|
+
);
|
|
1896
|
+
return;
|
|
1897
|
+
}
|
|
1898
|
+
const parentStep = parentState.steps[parentStepId];
|
|
1899
|
+
if (parentStep?.status !== "running") {
|
|
1900
|
+
deps.logger?.info("nagi: subflow wake skipped \u2014 parent step not running", {
|
|
1901
|
+
parentRunId,
|
|
1902
|
+
parentStepId,
|
|
1903
|
+
childRunId,
|
|
1904
|
+
parentStepStatus: parentStep?.status ?? "missing"
|
|
1905
|
+
});
|
|
1906
|
+
return;
|
|
1907
|
+
}
|
|
1908
|
+
const attempt = parentStep.attempts > 0 ? parentStep.attempts : 1;
|
|
1909
|
+
const parentFlow = await deps.flowFor(parentRunId);
|
|
1910
|
+
if (outcome.kind === "completed") {
|
|
1911
|
+
const subflowOutput = {
|
|
1912
|
+
childRunId,
|
|
1913
|
+
output: outcome.output
|
|
1914
|
+
};
|
|
1915
|
+
const completedFact = {
|
|
1916
|
+
kind: "step.completed",
|
|
1917
|
+
runId: parentRunId,
|
|
1918
|
+
stepId: parentStepId,
|
|
1919
|
+
attempt,
|
|
1920
|
+
output: subflowOutput,
|
|
1921
|
+
at: clock.now()
|
|
1922
|
+
};
|
|
1923
|
+
await store.completeStep(
|
|
1924
|
+
parentRunId,
|
|
1925
|
+
parentStepId,
|
|
1926
|
+
subflowOutput,
|
|
1927
|
+
completedFact
|
|
1928
|
+
);
|
|
1929
|
+
await fireHook(
|
|
1930
|
+
deps.hooks?.onStepComplete,
|
|
1931
|
+
{
|
|
1932
|
+
runId: parentRunId,
|
|
1933
|
+
flowId: parentFlow.id,
|
|
1934
|
+
stepId: parentStepId,
|
|
1935
|
+
attempt,
|
|
1936
|
+
kind: "subflow",
|
|
1937
|
+
output: subflowOutput,
|
|
1938
|
+
durationMs: 0,
|
|
1939
|
+
at: clock.now()
|
|
1940
|
+
},
|
|
1941
|
+
"onStepComplete",
|
|
1942
|
+
deps
|
|
1943
|
+
);
|
|
1944
|
+
} else {
|
|
1945
|
+
const failedFact = {
|
|
1946
|
+
kind: "step.failed",
|
|
1947
|
+
runId: parentRunId,
|
|
1948
|
+
stepId: parentStepId,
|
|
1949
|
+
attempt,
|
|
1950
|
+
error: outcome.error,
|
|
1951
|
+
at: clock.now()
|
|
1952
|
+
};
|
|
1953
|
+
await store.failStep(parentRunId, parentStepId, outcome.error, failedFact);
|
|
1954
|
+
await fireHook(
|
|
1955
|
+
deps.hooks?.onStepError,
|
|
1956
|
+
{
|
|
1957
|
+
runId: parentRunId,
|
|
1958
|
+
flowId: parentFlow.id,
|
|
1959
|
+
stepId: parentStepId,
|
|
1960
|
+
attempt,
|
|
1961
|
+
kind: "subflow",
|
|
1962
|
+
error: outcome.error,
|
|
1963
|
+
at: clock.now()
|
|
1964
|
+
},
|
|
1965
|
+
"onStepError",
|
|
1966
|
+
deps
|
|
1967
|
+
);
|
|
1968
|
+
}
|
|
1969
|
+
await advance(deps, parentRunId);
|
|
1607
1970
|
}
|
|
1608
1971
|
function computeFlowOutput(flow2, runState) {
|
|
1609
1972
|
if (flow2.output === void 0) return null;
|
|
@@ -1811,8 +2174,190 @@ async function nagi(config) {
|
|
|
1811
2174
|
}
|
|
1812
2175
|
return flow2;
|
|
1813
2176
|
}
|
|
2177
|
+
function lookupFlow(flowId) {
|
|
2178
|
+
return flowsById.get(flowId);
|
|
2179
|
+
}
|
|
2180
|
+
async function startRunInternal(args) {
|
|
2181
|
+
const { flow: flow2, validatedInput, runId, parentRunId, parentStepId } = args;
|
|
2182
|
+
const startedAt = clock.now();
|
|
2183
|
+
const flowHash = flowHashById.get(flow2.id);
|
|
2184
|
+
const fact = {
|
|
2185
|
+
kind: "flow.started",
|
|
2186
|
+
runId,
|
|
2187
|
+
flowId: flow2.id,
|
|
2188
|
+
input: validatedInput,
|
|
2189
|
+
at: startedAt,
|
|
2190
|
+
...flowHash !== void 0 ? { flowHash } : {},
|
|
2191
|
+
codeVersion,
|
|
2192
|
+
...parentRunId !== void 0 ? { parentRunId } : {},
|
|
2193
|
+
...parentStepId !== void 0 ? { parentStepId } : {}
|
|
2194
|
+
};
|
|
2195
|
+
let concurrencyArg;
|
|
2196
|
+
if (flow2.concurrency !== void 0) {
|
|
2197
|
+
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
2198
|
+
if (typeof derived !== "string" || derived.length === 0) {
|
|
2199
|
+
throw new NagiValidationError([
|
|
2200
|
+
{
|
|
2201
|
+
message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
2202
|
+
path: ["concurrency", "keyFn"]
|
|
2203
|
+
}
|
|
2204
|
+
]);
|
|
2205
|
+
}
|
|
2206
|
+
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
2207
|
+
}
|
|
2208
|
+
const { started, canceled } = await config.store.tryStartRun(
|
|
2209
|
+
runId,
|
|
2210
|
+
fact,
|
|
2211
|
+
concurrencyArg
|
|
2212
|
+
);
|
|
2213
|
+
if (!started) return { started: false };
|
|
2214
|
+
for (const c of canceled) {
|
|
2215
|
+
const cancelError = new NagiCanceledError({
|
|
2216
|
+
runId: c.runId,
|
|
2217
|
+
canceledByRunId: runId,
|
|
2218
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2219
|
+
});
|
|
2220
|
+
const serialized = {
|
|
2221
|
+
name: cancelError.name,
|
|
2222
|
+
message: cancelError.message,
|
|
2223
|
+
...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
|
|
2224
|
+
cause: {
|
|
2225
|
+
canceledByRunId: runId,
|
|
2226
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
2227
|
+
}
|
|
2228
|
+
};
|
|
2229
|
+
const errorEvent = {
|
|
2230
|
+
runId: c.runId,
|
|
2231
|
+
flowId: flow2.id,
|
|
2232
|
+
error: serialized,
|
|
2233
|
+
at: c.fact.at
|
|
2234
|
+
};
|
|
2235
|
+
await fireHook(
|
|
2236
|
+
flow2.onError,
|
|
2237
|
+
errorEvent,
|
|
2238
|
+
"flow.onError",
|
|
2239
|
+
dispatchDeps
|
|
2240
|
+
);
|
|
2241
|
+
await fireHook(
|
|
2242
|
+
config.hooks?.onFlowError,
|
|
2243
|
+
errorEvent,
|
|
2244
|
+
"onFlowError",
|
|
2245
|
+
dispatchDeps
|
|
2246
|
+
);
|
|
2247
|
+
await propagateToParent(dispatchDeps, c.runId, {
|
|
2248
|
+
kind: "canceled",
|
|
2249
|
+
error: serialized
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
const startEvent = {
|
|
2253
|
+
runId,
|
|
2254
|
+
flowId: flow2.id,
|
|
2255
|
+
input: validatedInput,
|
|
2256
|
+
at: startedAt
|
|
2257
|
+
};
|
|
2258
|
+
await fireHook(
|
|
2259
|
+
flow2.onStart,
|
|
2260
|
+
startEvent,
|
|
2261
|
+
"flow.onStart",
|
|
2262
|
+
dispatchDeps
|
|
2263
|
+
);
|
|
2264
|
+
await fireHook(
|
|
2265
|
+
config.hooks?.onFlowStart,
|
|
2266
|
+
startEvent,
|
|
2267
|
+
"onFlowStart",
|
|
2268
|
+
dispatchDeps
|
|
2269
|
+
);
|
|
2270
|
+
await advance(dispatchDeps, runId);
|
|
2271
|
+
return { started: true };
|
|
2272
|
+
}
|
|
2273
|
+
async function startChildRun(args) {
|
|
2274
|
+
const { child, childInput, parentRunId, parentStepId } = args;
|
|
2275
|
+
if (!flowsById.has(child.id)) {
|
|
2276
|
+
throw new NagiRuntimeError(
|
|
2277
|
+
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
2278
|
+
);
|
|
2279
|
+
}
|
|
2280
|
+
const validated = await validate(child.input, childInput);
|
|
2281
|
+
const childRunId = mintRunId();
|
|
2282
|
+
const { started } = await startRunInternal({
|
|
2283
|
+
flow: child,
|
|
2284
|
+
validatedInput: validated,
|
|
2285
|
+
runId: childRunId,
|
|
2286
|
+
parentRunId,
|
|
2287
|
+
parentStepId
|
|
2288
|
+
});
|
|
2289
|
+
if (!started) {
|
|
2290
|
+
throw new NagiRuntimeError(
|
|
2291
|
+
`startChildRun: minted child runId collided with an existing run (${childRunId})`
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
return childRunId;
|
|
2295
|
+
}
|
|
2296
|
+
async function cancelRunRecursive(runId, args) {
|
|
2297
|
+
const state = await config.store.loadRunState(runId);
|
|
2298
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2299
|
+
config.logger?.info("nagi: cancel skipped \u2014 run already terminal", {
|
|
2300
|
+
runId,
|
|
2301
|
+
status: state.status
|
|
2302
|
+
});
|
|
2303
|
+
return;
|
|
2304
|
+
}
|
|
2305
|
+
const flow2 = flowsById.get(state.flowId);
|
|
2306
|
+
const canceledFact = {
|
|
2307
|
+
kind: "flow.canceled",
|
|
2308
|
+
cause: args.cause,
|
|
2309
|
+
runId,
|
|
2310
|
+
at: clock.now(),
|
|
2311
|
+
// Explicit/operator cancels record self as canceler. Observers
|
|
2312
|
+
// discriminate via `cause` (or, for legacy facts, `canceledByRunId === runId`).
|
|
2313
|
+
canceledByRunId: runId,
|
|
2314
|
+
// Legacy carrier: explicit cancels stuff `reason` here for back-compat;
|
|
2315
|
+
// operator cancels use `note` instead and leave this empty.
|
|
2316
|
+
concurrencyKey: args.cause === "explicit" ? args.reason : "",
|
|
2317
|
+
...args.actor !== void 0 ? { actor: args.actor } : {},
|
|
2318
|
+
...args.note !== void 0 ? { note: args.note } : {}
|
|
2319
|
+
};
|
|
2320
|
+
await config.store.appendFact(runId, canceledFact);
|
|
2321
|
+
if (flow2 !== void 0) {
|
|
2322
|
+
const cancelError2 = {
|
|
2323
|
+
name: "NagiCanceledError",
|
|
2324
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2325
|
+
};
|
|
2326
|
+
const event = {
|
|
2327
|
+
runId,
|
|
2328
|
+
flowId: flow2.id,
|
|
2329
|
+
error: cancelError2,
|
|
2330
|
+
at: clock.now()
|
|
2331
|
+
};
|
|
2332
|
+
await fireHook(flow2.onError, event, "flow.onError", dispatchDeps);
|
|
2333
|
+
await fireHook(
|
|
2334
|
+
config.hooks?.onFlowError,
|
|
2335
|
+
event,
|
|
2336
|
+
"onFlowError",
|
|
2337
|
+
dispatchDeps
|
|
2338
|
+
);
|
|
2339
|
+
}
|
|
2340
|
+
const children = await config.store.listChildren(runId);
|
|
2341
|
+
for (const childId of children) {
|
|
2342
|
+
await cancelRunRecursive(childId, {
|
|
2343
|
+
cause: "explicit",
|
|
2344
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2345
|
+
note: args.cause === "operator" && args.actor !== void 0 ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
const cancelError = {
|
|
2349
|
+
name: "NagiCanceledError",
|
|
2350
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2351
|
+
};
|
|
2352
|
+
await propagateToParent(dispatchDeps, runId, {
|
|
2353
|
+
kind: "canceled",
|
|
2354
|
+
error: cancelError
|
|
2355
|
+
});
|
|
2356
|
+
}
|
|
1814
2357
|
const dispatchDeps = {
|
|
1815
2358
|
flowFor,
|
|
2359
|
+
lookupFlow,
|
|
2360
|
+
startChildRun,
|
|
1816
2361
|
store: config.store,
|
|
1817
2362
|
queue: config.queue,
|
|
1818
2363
|
clock,
|
|
@@ -1820,7 +2365,7 @@ async function nagi(config) {
|
|
|
1820
2365
|
...config.logger !== void 0 ? { logger: config.logger } : {},
|
|
1821
2366
|
...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
|
|
1822
2367
|
};
|
|
1823
|
-
|
|
2368
|
+
const wf = {
|
|
1824
2369
|
async start(flow2, input, opts) {
|
|
1825
2370
|
if (!flowsById.has(flow2.id)) {
|
|
1826
2371
|
throw new NagiRuntimeError(
|
|
@@ -1842,91 +2387,7 @@ async function nagi(config) {
|
|
|
1842
2387
|
runId = mintRunId();
|
|
1843
2388
|
}
|
|
1844
2389
|
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);
|
|
2390
|
+
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
1930
2391
|
return runId;
|
|
1931
2392
|
},
|
|
1932
2393
|
async signal(runId, signalName, payload) {
|
|
@@ -2012,6 +2473,21 @@ async function nagi(config) {
|
|
|
2012
2473
|
);
|
|
2013
2474
|
await advance(dispatchDeps, runId);
|
|
2014
2475
|
},
|
|
2476
|
+
async cancel(runId, opts) {
|
|
2477
|
+
await cancelRunRecursive(runId, {
|
|
2478
|
+
cause: "explicit",
|
|
2479
|
+
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
2480
|
+
});
|
|
2481
|
+
},
|
|
2482
|
+
operator() {
|
|
2483
|
+
return makeOperator({
|
|
2484
|
+
deps: dispatchDeps,
|
|
2485
|
+
clock,
|
|
2486
|
+
flowsById,
|
|
2487
|
+
cancelRunRecursive,
|
|
2488
|
+
...config.logger !== void 0 ? { logger: config.logger } : {}
|
|
2489
|
+
});
|
|
2490
|
+
},
|
|
2015
2491
|
worker(workerConfig) {
|
|
2016
2492
|
if (config.flows.length === 0) {
|
|
2017
2493
|
throw new NagiRuntimeError(
|
|
@@ -2105,8 +2581,54 @@ async function nagi(config) {
|
|
|
2105
2581
|
}
|
|
2106
2582
|
}
|
|
2107
2583
|
return config.store.queryRuns(opts);
|
|
2584
|
+
},
|
|
2585
|
+
async pruneFacts(opts) {
|
|
2586
|
+
if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
|
|
2587
|
+
throw new NagiValidationError([
|
|
2588
|
+
{
|
|
2589
|
+
message: "pruneFacts: `olderThan` must be a valid Date.",
|
|
2590
|
+
path: ["olderThan"]
|
|
2591
|
+
}
|
|
2592
|
+
]);
|
|
2593
|
+
}
|
|
2594
|
+
const statuses = opts.statuses ?? [
|
|
2595
|
+
"completed"
|
|
2596
|
+
];
|
|
2597
|
+
for (const s of statuses) {
|
|
2598
|
+
if (s !== "completed" && s !== "failed" && s !== "canceled") {
|
|
2599
|
+
throw new NagiValidationError([
|
|
2600
|
+
{
|
|
2601
|
+
message: `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
|
|
2602
|
+
path: ["statuses"]
|
|
2603
|
+
}
|
|
2604
|
+
]);
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
const batchSize = opts.batchSize ?? 1e3;
|
|
2608
|
+
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
2609
|
+
throw new NagiValidationError([
|
|
2610
|
+
{
|
|
2611
|
+
message: "pruneFacts: `batchSize` must be a positive integer.",
|
|
2612
|
+
path: ["batchSize"]
|
|
2613
|
+
}
|
|
2614
|
+
]);
|
|
2615
|
+
}
|
|
2616
|
+
const keepSummary = opts.keepSummary ?? true;
|
|
2617
|
+
return config.store.pruneFacts({
|
|
2618
|
+
olderThan: opts.olderThan,
|
|
2619
|
+
statuses,
|
|
2620
|
+
batchSize,
|
|
2621
|
+
keepSummary
|
|
2622
|
+
});
|
|
2108
2623
|
}
|
|
2109
2624
|
};
|
|
2625
|
+
Object.defineProperty(wf, "__dispatchDeps", {
|
|
2626
|
+
value: dispatchDeps,
|
|
2627
|
+
enumerable: false,
|
|
2628
|
+
writable: false,
|
|
2629
|
+
configurable: false
|
|
2630
|
+
});
|
|
2631
|
+
return wf;
|
|
2110
2632
|
}
|
|
2111
2633
|
function mintRunId() {
|
|
2112
2634
|
return `run-${crypto.randomUUID()}`;
|
|
@@ -2119,6 +2641,161 @@ async function drainInline(deps) {
|
|
|
2119
2641
|
for (const msg of messages) await dispatchMessage(deps, msg);
|
|
2120
2642
|
}
|
|
2121
2643
|
}
|
|
2644
|
+
function makeOperator(o) {
|
|
2645
|
+
const { deps, clock, flowsById, cancelRunRecursive } = o;
|
|
2646
|
+
const store = deps.store;
|
|
2647
|
+
function resolveFlow(flowId, runId) {
|
|
2648
|
+
const flow2 = flowsById.get(flowId);
|
|
2649
|
+
if (!flow2) {
|
|
2650
|
+
throw new NagiRuntimeError(
|
|
2651
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
2652
|
+
);
|
|
2653
|
+
}
|
|
2654
|
+
return flow2;
|
|
2655
|
+
}
|
|
2656
|
+
async function skip(runId, stepId, opts) {
|
|
2657
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2658
|
+
throw new NagiValidationError([
|
|
2659
|
+
{
|
|
2660
|
+
message: "operator.skip: opts.actor must be a non-empty string",
|
|
2661
|
+
path: ["actor"]
|
|
2662
|
+
}
|
|
2663
|
+
]);
|
|
2664
|
+
}
|
|
2665
|
+
const cascade = opts.cascade ?? "skip";
|
|
2666
|
+
const state = await store.loadRunState(runId);
|
|
2667
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2668
|
+
if (!(stepId in flow2.steps)) {
|
|
2669
|
+
throw new NagiValidationError([
|
|
2670
|
+
{
|
|
2671
|
+
message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2672
|
+
path: ["stepId"]
|
|
2673
|
+
}
|
|
2674
|
+
]);
|
|
2675
|
+
}
|
|
2676
|
+
const stepState = state.steps[stepId];
|
|
2677
|
+
if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
|
|
2678
|
+
o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
|
|
2679
|
+
runId,
|
|
2680
|
+
stepId,
|
|
2681
|
+
status: stepState.status
|
|
2682
|
+
});
|
|
2683
|
+
return;
|
|
2684
|
+
}
|
|
2685
|
+
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2686
|
+
throw new NagiRuntimeError(
|
|
2687
|
+
`operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
|
|
2688
|
+
);
|
|
2689
|
+
}
|
|
2690
|
+
const fact = {
|
|
2691
|
+
kind: "step.skipped",
|
|
2692
|
+
runId,
|
|
2693
|
+
at: clock.now(),
|
|
2694
|
+
stepId,
|
|
2695
|
+
reason: "manual",
|
|
2696
|
+
actor: opts.actor,
|
|
2697
|
+
cascade,
|
|
2698
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2699
|
+
};
|
|
2700
|
+
await store.appendFact(runId, fact);
|
|
2701
|
+
await advance(deps, runId);
|
|
2702
|
+
}
|
|
2703
|
+
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
2704
|
+
const start = Date.now();
|
|
2705
|
+
while (Date.now() - start < deadlineMs) {
|
|
2706
|
+
const s = await store.loadRunState(runId);
|
|
2707
|
+
const ss = s.steps[stepId];
|
|
2708
|
+
if (ss === void 0) return;
|
|
2709
|
+
if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
|
|
2710
|
+
return;
|
|
2711
|
+
}
|
|
2712
|
+
if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
|
|
2713
|
+
return;
|
|
2714
|
+
}
|
|
2715
|
+
if (ss.attempts > attempt) return;
|
|
2716
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
2717
|
+
}
|
|
2718
|
+
throw new NagiRuntimeError(
|
|
2719
|
+
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
2720
|
+
);
|
|
2721
|
+
}
|
|
2722
|
+
async function retry(runId, stepId, opts) {
|
|
2723
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2724
|
+
throw new NagiValidationError([
|
|
2725
|
+
{
|
|
2726
|
+
message: "operator.retry: opts.actor must be a non-empty string",
|
|
2727
|
+
path: ["actor"]
|
|
2728
|
+
}
|
|
2729
|
+
]);
|
|
2730
|
+
}
|
|
2731
|
+
const state = await store.loadRunState(runId);
|
|
2732
|
+
if (state.status === "canceled") {
|
|
2733
|
+
throw new NagiRuntimeError(
|
|
2734
|
+
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
2735
|
+
);
|
|
2736
|
+
}
|
|
2737
|
+
const flow2 = resolveFlow(state.flowId, runId);
|
|
2738
|
+
if (!(stepId in flow2.steps)) {
|
|
2739
|
+
throw new NagiValidationError([
|
|
2740
|
+
{
|
|
2741
|
+
message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2742
|
+
path: ["stepId"]
|
|
2743
|
+
}
|
|
2744
|
+
]);
|
|
2745
|
+
}
|
|
2746
|
+
const stepState = state.steps[stepId];
|
|
2747
|
+
if (stepState !== void 0 && stepState.status === "running") {
|
|
2748
|
+
const abortFact = {
|
|
2749
|
+
kind: "step.abort-requested",
|
|
2750
|
+
runId,
|
|
2751
|
+
at: clock.now(),
|
|
2752
|
+
stepId,
|
|
2753
|
+
attempt: stepState.attempts,
|
|
2754
|
+
actor: opts.actor,
|
|
2755
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2756
|
+
};
|
|
2757
|
+
await store.appendFact(runId, abortFact);
|
|
2758
|
+
await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
|
|
2759
|
+
}
|
|
2760
|
+
const cascade = descendantsOf(flow2, stepId);
|
|
2761
|
+
const at = clock.now();
|
|
2762
|
+
for (const id of cascade) {
|
|
2763
|
+
const fact = id === stepId ? {
|
|
2764
|
+
kind: "step.reset",
|
|
2765
|
+
runId,
|
|
2766
|
+
at,
|
|
2767
|
+
stepId: id,
|
|
2768
|
+
actor: opts.actor,
|
|
2769
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2770
|
+
} : {
|
|
2771
|
+
kind: "step.reset",
|
|
2772
|
+
runId,
|
|
2773
|
+
at,
|
|
2774
|
+
stepId: id,
|
|
2775
|
+
cascadedFrom: stepId
|
|
2776
|
+
};
|
|
2777
|
+
await store.appendFact(runId, fact);
|
|
2778
|
+
}
|
|
2779
|
+
await advance(deps, runId);
|
|
2780
|
+
}
|
|
2781
|
+
async function abort(runId, opts) {
|
|
2782
|
+
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2783
|
+
throw new NagiValidationError([
|
|
2784
|
+
{
|
|
2785
|
+
message: "operator.abort: opts.actor must be a non-empty string",
|
|
2786
|
+
path: ["actor"]
|
|
2787
|
+
}
|
|
2788
|
+
]);
|
|
2789
|
+
}
|
|
2790
|
+
await cancelRunRecursive(runId, {
|
|
2791
|
+
cause: "operator",
|
|
2792
|
+
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
2793
|
+
actor: opts.actor,
|
|
2794
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
return { skip, retry, abort };
|
|
2798
|
+
}
|
|
2122
2799
|
async function validate(schema, value) {
|
|
2123
2800
|
const result = await schema["~standard"].validate(value);
|
|
2124
2801
|
if ("issues" in result && result.issues !== void 0) {
|