@psimona/darkf 0.5.0 → 0.6.0
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/docs/concepts/failure-modes.md +164 -0
- package/docs/concepts/handoff.md +91 -0
- package/docs/concepts/journal.md +92 -0
- package/docs/concepts/node-types.md +175 -0
- package/docs/guides/pick-an-agent-runner.md +57 -0
- package/docs/guides/plan-with-a-task-queue.md +410 -0
- package/docs/guides/render-to-mermaid.md +22 -0
- package/docs/guides/run-detached-and-monitor.md +76 -0
- package/docs/guides/test-your-workflow.md +20 -0
- package/docs/guides/write-your-first-workflow.md +95 -0
- package/docs/index.mdx +64 -0
- package/docs/reference/cli-commands.md +105 -0
- package/docs/reference/core-types.md +123 -0
- package/docs/reference/package-map.md +35 -0
- package/docs/start-here/install.md +71 -0
- package/docs/start-here/quickstart.md +241 -0
- package/package.json +7 -1
- package/skills/darkf-usage/SKILL.md +92 -0
- package/skills/darkf-writing-workflows/SKILL.md +88 -0
- package/src/cli/doctor.test.ts +338 -0
- package/src/cli/index.ts +123 -9
- package/src/cli/setup.test.ts +384 -0
- package/src/cli/setup.ts +286 -0
- package/src/cli/tarball.test.ts +125 -0
- package/src/cli/update.test.ts +82 -0
- package/src/cli/update.ts +20 -0
- package/src/core/types.ts +8 -0
- package/src/engine/run.test.ts +177 -0
- package/src/engine/run.ts +66 -2
- package/src/kit/agents/opencode.test.ts +232 -2
- package/src/kit/agents/opencode.ts +69 -6
- package/src/kit/status.test.ts +67 -0
- package/src/kit/status.ts +25 -0
- package/workflows/dev-loop/scripts/begin.ts +1 -1
- package/workflows/dev-loop/scripts/finish.ts +4 -1
- package/workflows/dev-loop/workflow.ts +30 -19
- package/bunfig.toml +0 -13
- package/examples/article-classifier/data/articles.ts +0 -38
- package/examples/article-classifier/scripts/next.ts +0 -7
- package/examples/article-classifier/scripts/queue.ts +0 -33
- package/examples/article-classifier/scripts/record.ts +0 -9
- package/examples/article-classifier/workflow.ts +0 -44
- package/examples/haiku-commit/scripts/check.ts +0 -24
- package/examples/haiku-commit/workflow.ts +0 -28
- package/examples/haiku-readme/scripts/test.ts +0 -13
- package/examples/haiku-readme/scripts/write.ts +0 -10
- package/examples/haiku-readme/workflow.ts +0 -41
- package/examples/task-queue/scripts/next.ts +0 -20
- package/examples/task-queue/scripts/record.ts +0 -20
- package/examples/task-queue/supervise.ts +0 -57
- package/examples/task-queue/workflow.ts +0 -33
- package/feedback/2026-10-30-self-update.md +0 -29
- package/feedback/2026-10-31-task-list-json.md +0 -26
- package/tsconfig.json +0 -4
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { todayLocal, writeProbeState } from "./setup.ts";
|
|
6
|
+
|
|
7
|
+
// Tarball smoke test (skill-setup spec: Testing): npm pack the package, then
|
|
8
|
+
// install the tarball into a temp prefix and run the installed CLI — proving
|
|
9
|
+
// the files allowlist ships every runtime dir (src, workflows, skills, docs)
|
|
10
|
+
// and nothing the CLI reads was dropped. Skipped when npm is absent.
|
|
11
|
+
|
|
12
|
+
const pkgDir = resolve(import.meta.dir, "..", "..");
|
|
13
|
+
|
|
14
|
+
test("tarball smoke: allowlist ships the runtime dirs and the installed CLI works", async () => {
|
|
15
|
+
const npm = Bun.which("npm");
|
|
16
|
+
if (!npm) {
|
|
17
|
+
console.warn("npm not on PATH — skipping tarball smoke test");
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const root = mkdtempSync(join(tmpdir(), "darkf-tarball-"));
|
|
22
|
+
try {
|
|
23
|
+
// Pack and inspect the tarball's contents.
|
|
24
|
+
const pack = Bun.spawnSync([npm, "pack", "--json", "--pack-destination", root], {
|
|
25
|
+
cwd: pkgDir,
|
|
26
|
+
stdout: "pipe",
|
|
27
|
+
stderr: "pipe",
|
|
28
|
+
});
|
|
29
|
+
expect(pack.exitCode).toBe(0);
|
|
30
|
+
const filename = (
|
|
31
|
+
JSON.parse(new TextDecoder().decode(pack.stdout)) as Array<{ filename: string }>
|
|
32
|
+
)[0]?.filename;
|
|
33
|
+
expect(filename).toBeTruthy();
|
|
34
|
+
const tgz = join(root, filename!);
|
|
35
|
+
const list = Bun.spawnSync(["tar", "-tzf", tgz], { stdout: "pipe", stderr: "pipe" });
|
|
36
|
+
expect(list.exitCode).toBe(0);
|
|
37
|
+
const entries = new TextDecoder()
|
|
38
|
+
.decode(list.stdout)
|
|
39
|
+
.split("\n")
|
|
40
|
+
.filter((l) => l.startsWith("package/"));
|
|
41
|
+
const top = new Set(entries.map((l) => l.split("/")[1]).filter(Boolean));
|
|
42
|
+
// Exactly the allowlist plus the auto-included package.json and README.
|
|
43
|
+
expect(top).toEqual(
|
|
44
|
+
new Set(["README.md", "docs", "package.json", "skills", "src", "workflows"]),
|
|
45
|
+
);
|
|
46
|
+
const all = entries.join("\n");
|
|
47
|
+
expect(all).not.toContain("package/examples/");
|
|
48
|
+
expect(all).not.toContain("bunfig.toml");
|
|
49
|
+
expect(all).not.toContain("tsconfig.json");
|
|
50
|
+
expect(all).not.toContain("package/feedback/");
|
|
51
|
+
|
|
52
|
+
// Install into a temp prefix — the offline global-install shape.
|
|
53
|
+
const prefix = join(root, "prefix");
|
|
54
|
+
const install = Bun.spawnSync(
|
|
55
|
+
[npm, "install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", tgz],
|
|
56
|
+
{ stdout: "pipe", stderr: "pipe" },
|
|
57
|
+
);
|
|
58
|
+
expect(install.exitCode).toBe(0);
|
|
59
|
+
const libRoot = join(prefix, "lib", "node_modules", "@psimona", "darkf");
|
|
60
|
+
expect(existsSync(join(libRoot, "src", "cli", "index.ts"))).toBe(true);
|
|
61
|
+
expect(existsSync(join(prefix, "bin", "darkf"))).toBe(true);
|
|
62
|
+
|
|
63
|
+
// Temp HOME and state; the probe stamped so its block stays out of the way.
|
|
64
|
+
const home = join(root, "home");
|
|
65
|
+
mkdirSync(home);
|
|
66
|
+
const stateHome = join(root, "state");
|
|
67
|
+
mkdirSync(stateHome, { recursive: true });
|
|
68
|
+
writeProbeState(join(stateHome, "darkf", "last-skills-check.json"), {
|
|
69
|
+
lastProbe: todayLocal(),
|
|
70
|
+
});
|
|
71
|
+
const env = {
|
|
72
|
+
...process.env,
|
|
73
|
+
HOME: home,
|
|
74
|
+
XDG_STATE_HOME: stateHome,
|
|
75
|
+
DARKF_NO_UPDATE_CHECK: "1",
|
|
76
|
+
};
|
|
77
|
+
const runBin = (args: string[]) => {
|
|
78
|
+
const proc = Bun.spawnSync(
|
|
79
|
+
[process.execPath, join(libRoot, "src", "cli", "index.ts"), ...args],
|
|
80
|
+
{
|
|
81
|
+
cwd: root,
|
|
82
|
+
stdout: "pipe",
|
|
83
|
+
stderr: "pipe",
|
|
84
|
+
env,
|
|
85
|
+
},
|
|
86
|
+
);
|
|
87
|
+
return {
|
|
88
|
+
code: proc.exitCode,
|
|
89
|
+
out: new TextDecoder().decode(proc.stdout),
|
|
90
|
+
err: new TextDecoder().decode(proc.stderr),
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// `setup` installs both skills into a detected host.
|
|
95
|
+
const setup = runBin(["setup"]);
|
|
96
|
+
expect(setup.code).toBe(0);
|
|
97
|
+
expect(setup.out).toContain("host claude (~/.claude/skills)");
|
|
98
|
+
expect(existsSync(join(home, ".claude", "skills", "darkf-usage", "SKILL.md"))).toBe(true);
|
|
99
|
+
expect(existsSync(join(home, ".claude", "skills", "darkf-writing-workflows", "SKILL.md"))).toBe(
|
|
100
|
+
true,
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
// `doctor` renders the skills section from the installed package's bundle.
|
|
104
|
+
const doctor = runBin(["doctor"]);
|
|
105
|
+
expect(doctor.out).toContain("skills (claude) — 2/2 installed");
|
|
106
|
+
|
|
107
|
+
// `render` loads a built-in workflow from the packaged workflows/.
|
|
108
|
+
const render = runBin(["render", "series-ordering"]);
|
|
109
|
+
expect(render.code).toBe(0);
|
|
110
|
+
expect(render.out).toContain("stateDiagram-v2");
|
|
111
|
+
|
|
112
|
+
// Every skill-referenced docs path resolves inside the installed package,
|
|
113
|
+
// offline — the deep-reference pointers work for a global install.
|
|
114
|
+
for (const skill of ["darkf-usage", "darkf-writing-workflows"]) {
|
|
115
|
+
const text = readFileSync(join(libRoot, "skills", skill, "SKILL.md"), "utf8");
|
|
116
|
+
const refs = [...text.matchAll(/docs\/[A-Za-z0-9][A-Za-z0-9/._-]*\.md/g)].map((m) => m[0]!);
|
|
117
|
+
expect(refs.length).toBeGreaterThan(0);
|
|
118
|
+
for (const ref of refs) {
|
|
119
|
+
expect(existsSync(join(libRoot, ref))).toBe(true);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
rmSync(root, { recursive: true, force: true });
|
|
124
|
+
}
|
|
125
|
+
}, 240_000);
|
package/src/cli/update.test.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { afterAll, expect, test } from "bun:test";
|
|
|
2
2
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import type { SkillsDeps } from "./setup.ts";
|
|
5
6
|
import {
|
|
6
7
|
checkRegistry,
|
|
7
8
|
isDue,
|
|
@@ -10,6 +11,7 @@ import {
|
|
|
10
11
|
type UpdateDeps,
|
|
11
12
|
updateGate,
|
|
12
13
|
upgradeCmd,
|
|
14
|
+
upgradeWithSkills,
|
|
13
15
|
writeState,
|
|
14
16
|
} from "./update.ts";
|
|
15
17
|
|
|
@@ -484,3 +486,83 @@ test("real CLI with a fresh not-due record: the notice is the first stdout line,
|
|
|
484
486
|
`darkf 99.0.0 available (installed ${installedVersion}) — run 'darkf upgrade'`,
|
|
485
487
|
);
|
|
486
488
|
});
|
|
489
|
+
|
|
490
|
+
// --- upgrade + skills sync (skill-setup spec) ---
|
|
491
|
+
|
|
492
|
+
const SKILL_BUNDLED = "bundled skill body\n";
|
|
493
|
+
const SKILL_STALE = "a stale installed copy\n";
|
|
494
|
+
|
|
495
|
+
/** Fixture skills bundle + a home with a stale claude copy installed. */
|
|
496
|
+
function skillsFixture(): { skills: SkillsDeps; installed: string } {
|
|
497
|
+
const bundledDir = tempDir();
|
|
498
|
+
mkdirSync(join(bundledDir, "darkf-usage"), { recursive: true });
|
|
499
|
+
writeFileSync(join(bundledDir, "darkf-usage", "SKILL.md"), SKILL_BUNDLED);
|
|
500
|
+
const home = tempDir();
|
|
501
|
+
const installed = join(home, ".claude", "skills", "darkf-usage", "SKILL.md");
|
|
502
|
+
mkdirSync(dirname(installed), { recursive: true });
|
|
503
|
+
writeFileSync(installed, SKILL_STALE);
|
|
504
|
+
return {
|
|
505
|
+
installed,
|
|
506
|
+
skills: { home, bundledDir, existsBinary: () => false },
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
test("upgrade runs the sync after the install, under the skills: header", async () => {
|
|
511
|
+
const file = tempStateFile();
|
|
512
|
+
const { skills, installed } = skillsFixture();
|
|
513
|
+
const { spawnImpl } = spawnStub((cmd) => {
|
|
514
|
+
if (cmd[1] === "pm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
|
|
515
|
+
if (cmd[1] === "install") return { exitCode: 0 };
|
|
516
|
+
return undefined;
|
|
517
|
+
});
|
|
518
|
+
const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
|
|
519
|
+
|
|
520
|
+
const { result, out } = await captured(() =>
|
|
521
|
+
upgradeWithSkills(deps({ stateFile: file, spawnImpl, fetchImpl }), skills),
|
|
522
|
+
);
|
|
523
|
+
|
|
524
|
+
expect(result).toBe(0);
|
|
525
|
+
const skillsIdx = out.indexOf("skills:");
|
|
526
|
+
expect(skillsIdx).toBeGreaterThanOrEqual(0);
|
|
527
|
+
expect(out.slice(skillsIdx).some((l) => l.includes("updated (was stale)"))).toBe(true);
|
|
528
|
+
expect(readFileSync(installed, "utf8")).toBe(SKILL_BUNDLED); // stale copy replaced
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
test("a failed upgrade skips the sync — never a skills: block, stale copy untouched", async () => {
|
|
532
|
+
const { skills, installed } = skillsFixture();
|
|
533
|
+
const { spawnImpl } = spawnStub((cmd) => {
|
|
534
|
+
if (cmd[1] === "pm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
|
|
535
|
+
if (cmd[1] === "install") return { exitCode: 7 };
|
|
536
|
+
return undefined;
|
|
537
|
+
});
|
|
538
|
+
const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
|
|
539
|
+
|
|
540
|
+
const { result, out } = await captured(() =>
|
|
541
|
+
upgradeWithSkills(deps({ spawnImpl, fetchImpl }), skills),
|
|
542
|
+
);
|
|
543
|
+
|
|
544
|
+
expect(result).toBe(7); // the upgrade's own exit code, unmasked
|
|
545
|
+
expect(out).not.toContain("skills:");
|
|
546
|
+
expect(readFileSync(installed, "utf8")).toBe(SKILL_STALE);
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
test("a sync failure after a good upgrade is reported and exits non-zero", async () => {
|
|
550
|
+
const { skills } = skillsFixture();
|
|
551
|
+
// The claude skills "dir" is a file — the sync cannot write.
|
|
552
|
+
rmSync(join(skills.home, ".claude", "skills"), { recursive: true });
|
|
553
|
+
writeFileSync(join(skills.home, ".claude", "skills"), "a file, not a dir");
|
|
554
|
+
const { spawnImpl } = spawnStub((cmd) => {
|
|
555
|
+
if (cmd[1] === "pm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
|
|
556
|
+
if (cmd[1] === "install") return { exitCode: 0 };
|
|
557
|
+
return undefined;
|
|
558
|
+
});
|
|
559
|
+
const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
|
|
560
|
+
|
|
561
|
+
const { result, out, err } = await captured(() =>
|
|
562
|
+
upgradeWithSkills(deps({ spawnImpl, fetchImpl }), skills),
|
|
563
|
+
);
|
|
564
|
+
|
|
565
|
+
expect(result).toBe(1); // best-effort: reported, non-zero, upgrade unmasked
|
|
566
|
+
expect(out).toContain("skills:");
|
|
567
|
+
expect(err.join("\n")).not.toContain("skills"); // the failure is in the sync lines, not stderr noise
|
|
568
|
+
});
|
package/src/cli/update.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// manager. No module-level mutable state.
|
|
5
5
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
|
+
import { type SkillsDeps, syncAll } from "./setup.ts";
|
|
7
8
|
|
|
8
9
|
const PACKAGE_SPEC = "@psimona/darkf";
|
|
9
10
|
const REGISTRY_URL = "https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags";
|
|
@@ -189,3 +190,22 @@ export async function upgradeCmd(deps: UpdateDeps): Promise<number> {
|
|
|
189
190
|
}
|
|
190
191
|
return code;
|
|
191
192
|
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* `darkf upgrade` end-to-end (skill-setup spec): install the new package
|
|
196
|
+
* version, then sync the skills it now ships — after the install, the
|
|
197
|
+
* running process resolves the new bundled copies on disk, so skills can
|
|
198
|
+
* never be stale relative to the engine they teach. Same code path as
|
|
199
|
+
* `darkf setup`. Best-effort: a sync failure is reported and exits non-zero,
|
|
200
|
+
* but never masks the upgrade's own exit code.
|
|
201
|
+
*/
|
|
202
|
+
export async function upgradeWithSkills(
|
|
203
|
+
update: UpdateDeps,
|
|
204
|
+
skills: SkillsDeps,
|
|
205
|
+
log: (line: string) => void = console.log,
|
|
206
|
+
): Promise<number> {
|
|
207
|
+
const code = await upgradeCmd(update);
|
|
208
|
+
if (code !== 0) return code;
|
|
209
|
+
log("skills:");
|
|
210
|
+
return syncAll({ ...skills, log });
|
|
211
|
+
}
|
package/src/core/types.ts
CHANGED
|
@@ -53,6 +53,10 @@ export interface BaseLeafDef {
|
|
|
53
53
|
retries?: number;
|
|
54
54
|
/** Engine-enforced ceiling on one dispatch attempt. Default 1h. */
|
|
55
55
|
timeoutMs?: number;
|
|
56
|
+
/** Fixed interval between usage-limit re-probes after a provider quota wall. Default 30 min. See docs/specs/usage-limit-backoff/spec.md. */
|
|
57
|
+
usageLimitRetryMs?: number;
|
|
58
|
+
/** Total wait budget per node visit for usage-limit backoff. At the cap the run crashes with the last usage-limit reason. Default 24h. */
|
|
59
|
+
usageLimitMaxWaitMs?: number;
|
|
56
60
|
/**
|
|
57
61
|
* Plain code check run against a well-formed NodeResult before it's accepted
|
|
58
62
|
* as `succeeded`. Return a failure message to reject it, or undefined to
|
|
@@ -216,6 +220,9 @@ export type NodeStatus =
|
|
|
216
220
|
nudgeAttempt?: number;
|
|
217
221
|
/** The nudgeable `CrashReason` kind that triggered this nudge. */
|
|
218
222
|
nudgeReason?: CrashReason["kind"];
|
|
223
|
+
/** Present only while the engine is waiting out a provider usage-limit
|
|
224
|
+
* backoff for this attempt — see docs/specs/usage-limit-backoff/spec.md. */
|
|
225
|
+
limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number };
|
|
219
226
|
}
|
|
220
227
|
| { phase: "succeeded"; result: NodeResult }
|
|
221
228
|
| { phase: "failed"; result: NodeResult }
|
|
@@ -223,6 +230,7 @@ export type NodeStatus =
|
|
|
223
230
|
|
|
224
231
|
export type CrashReason =
|
|
225
232
|
| { kind: "runner-error"; error: string }
|
|
233
|
+
| { kind: "usage-limit"; detail: string }
|
|
226
234
|
| { kind: "timeout"; elapsedMs: number }
|
|
227
235
|
| { kind: "handoff-missing" }
|
|
228
236
|
| { kind: "handoff-unparseable"; parseError: string }
|
package/src/engine/run.test.ts
CHANGED
|
@@ -1066,3 +1066,180 @@ test("FAILED's terminal journal entry carries the failing node's result as its e
|
|
|
1066
1066
|
expect(last.status.result.output).toEqual({ kind: "cap_exceeded" });
|
|
1067
1067
|
}
|
|
1068
1068
|
});
|
|
1069
|
+
|
|
1070
|
+
// --- usage-limit-backoff (docs/specs/usage-limit-backoff/spec.md) ---
|
|
1071
|
+
|
|
1072
|
+
const usageLimitFailure = () =>
|
|
1073
|
+
new AgentFailure("Usage limit reached for 5 hour.", {
|
|
1074
|
+
agentSessionId: "sess-limit",
|
|
1075
|
+
crashReason: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
test("a usage-limit failure waits the interval, then re-dispatches the SAME attempt without consuming a retry", async () => {
|
|
1079
|
+
const workflow: WorkflowDef = {
|
|
1080
|
+
initial: "Agentic",
|
|
1081
|
+
states: {
|
|
1082
|
+
Agentic: { type: "agent", prompt: "do it", usageLimitRetryMs: 100, on: { ok: EXIT } },
|
|
1083
|
+
},
|
|
1084
|
+
};
|
|
1085
|
+
|
|
1086
|
+
const infos: DispatchInfo[] = [];
|
|
1087
|
+
const dispatchTimes: number[] = [];
|
|
1088
|
+
const agentRunner: AgentRunner = {
|
|
1089
|
+
run: async (_id, _def, _handoff, info) => {
|
|
1090
|
+
infos.push(info);
|
|
1091
|
+
dispatchTimes.push(Date.now());
|
|
1092
|
+
if (infos.length === 1) throw usageLimitFailure();
|
|
1093
|
+
return { event: "ok" };
|
|
1094
|
+
},
|
|
1095
|
+
};
|
|
1096
|
+
|
|
1097
|
+
const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
|
|
1098
|
+
|
|
1099
|
+
expect(result.node.phase).toBe("succeeded");
|
|
1100
|
+
expect(infos.length).toBe(2);
|
|
1101
|
+
// Same outer attempt (retries: 0 default — success itself proves none was
|
|
1102
|
+
// consumed), with the session id and the wall forwarded unchanged.
|
|
1103
|
+
expect(infos[1]).toMatchObject({
|
|
1104
|
+
attempt: 1,
|
|
1105
|
+
agentSessionId: "sess-limit",
|
|
1106
|
+
previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
|
|
1107
|
+
});
|
|
1108
|
+
// The retry fired after the shortened interval — not the 30-min default.
|
|
1109
|
+
const waited = dispatchTimes[1]! - dispatchTimes[0]!;
|
|
1110
|
+
expect(waited).toBeGreaterThanOrEqual(90);
|
|
1111
|
+
expect(waited).toBeLessThan(2000);
|
|
1112
|
+
});
|
|
1113
|
+
|
|
1114
|
+
test("while waiting, running heartbeats carry limitBackoff (probe, nextAttemptAt, waitedMs)", async () => {
|
|
1115
|
+
const workflow: WorkflowDef = {
|
|
1116
|
+
initial: "Agentic",
|
|
1117
|
+
states: {
|
|
1118
|
+
Agentic: { type: "agent", prompt: "do it", usageLimitRetryMs: 100, on: { ok: EXIT } },
|
|
1119
|
+
},
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
let calls = 0;
|
|
1123
|
+
const agentRunner: AgentRunner = {
|
|
1124
|
+
run: async () => {
|
|
1125
|
+
calls++;
|
|
1126
|
+
if (calls === 1) throw usageLimitFailure();
|
|
1127
|
+
return { event: "ok" };
|
|
1128
|
+
},
|
|
1129
|
+
};
|
|
1130
|
+
|
|
1131
|
+
const result = await run({
|
|
1132
|
+
workflow,
|
|
1133
|
+
agentRunner,
|
|
1134
|
+
scriptRunner: noopScript,
|
|
1135
|
+
heartbeatMs: 20,
|
|
1136
|
+
});
|
|
1137
|
+
expect(result.node.phase).toBe("succeeded");
|
|
1138
|
+
|
|
1139
|
+
const journalPath = join(testRootDir, ".darkf", "run", result.runId, "journal.jsonl");
|
|
1140
|
+
const events = readFileSync(journalPath, "utf8")
|
|
1141
|
+
.trim()
|
|
1142
|
+
.split("\n")
|
|
1143
|
+
.map((l) => JSON.parse(l) as NodeEvent);
|
|
1144
|
+
const waiting = events.filter(
|
|
1145
|
+
(e) => e.status.phase === "running" && e.status.limitBackoff !== undefined,
|
|
1146
|
+
);
|
|
1147
|
+
// Wait-start emit (immediate, nudge-start precedent) + interval heartbeats
|
|
1148
|
+
// during the 100ms sleep at 20ms cadence.
|
|
1149
|
+
expect(waiting.length).toBeGreaterThanOrEqual(2);
|
|
1150
|
+
const first = waiting[0]!;
|
|
1151
|
+
if (first.status.phase === "running") {
|
|
1152
|
+
expect(first.status.limitBackoff).toEqual({
|
|
1153
|
+
probe: 1,
|
|
1154
|
+
nextAttemptAt: expect.any(Number),
|
|
1155
|
+
waitedMs: 100,
|
|
1156
|
+
});
|
|
1157
|
+
expect(first.status.limitBackoff!.nextAttemptAt).toBeGreaterThan(first.status.lastHeartbeat);
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
1160
|
+
|
|
1161
|
+
test("exhausting usageLimitMaxWaitMs crashes with the last usage-limit reason; probe count and total wait journaled", async () => {
|
|
1162
|
+
const workflow: WorkflowDef = {
|
|
1163
|
+
initial: "Agentic",
|
|
1164
|
+
states: {
|
|
1165
|
+
Agentic: {
|
|
1166
|
+
type: "agent",
|
|
1167
|
+
prompt: "do it",
|
|
1168
|
+
usageLimitRetryMs: 50,
|
|
1169
|
+
usageLimitMaxWaitMs: 120,
|
|
1170
|
+
on: { ok: EXIT },
|
|
1171
|
+
},
|
|
1172
|
+
},
|
|
1173
|
+
};
|
|
1174
|
+
|
|
1175
|
+
let calls = 0;
|
|
1176
|
+
const agentRunner: AgentRunner = {
|
|
1177
|
+
run: async () => {
|
|
1178
|
+
calls++;
|
|
1179
|
+
throw usageLimitFailure();
|
|
1180
|
+
},
|
|
1181
|
+
};
|
|
1182
|
+
|
|
1183
|
+
const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
|
|
1184
|
+
|
|
1185
|
+
// Waits: 50 (probe 1), then 100 <= 120 (probe 2); the third failure sees
|
|
1186
|
+
// 100 + 50 > 120 and takes the crashed() path. Never a fourth dispatch.
|
|
1187
|
+
expect(calls).toBe(3);
|
|
1188
|
+
expect(result.node.phase).toBe("crashed");
|
|
1189
|
+
if (result.node.phase === "crashed") {
|
|
1190
|
+
expect(result.node.reason).toEqual({
|
|
1191
|
+
kind: "usage-limit",
|
|
1192
|
+
detail: "Usage limit reached for 5 hour.",
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
const journalPath = join(testRootDir, ".darkf", "run", result.runId, "journal.jsonl");
|
|
1197
|
+
const events = readFileSync(journalPath, "utf8")
|
|
1198
|
+
.trim()
|
|
1199
|
+
.split("\n")
|
|
1200
|
+
.map((l) => JSON.parse(l) as NodeEvent);
|
|
1201
|
+
const lastWait = events
|
|
1202
|
+
.filter((e) => e.status.phase === "running" && e.status.limitBackoff !== undefined)
|
|
1203
|
+
.at(-1);
|
|
1204
|
+
expect(lastWait).toBeDefined();
|
|
1205
|
+
if (lastWait!.status.phase === "running") {
|
|
1206
|
+
expect(lastWait!.status.limitBackoff).toEqual({
|
|
1207
|
+
probe: 2,
|
|
1208
|
+
nextAttemptAt: expect.any(Number),
|
|
1209
|
+
waitedMs: 100,
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
});
|
|
1213
|
+
|
|
1214
|
+
test("the attempt deadline is recomputed after each usage-limit wait, so a slept interval never eats the next dispatch's timeout", async () => {
|
|
1215
|
+
const workflow: WorkflowDef = {
|
|
1216
|
+
initial: "Agentic",
|
|
1217
|
+
states: {
|
|
1218
|
+
Agentic: {
|
|
1219
|
+
type: "agent",
|
|
1220
|
+
prompt: "do it",
|
|
1221
|
+
timeoutMs: 80,
|
|
1222
|
+
usageLimitRetryMs: 50,
|
|
1223
|
+
on: { ok: EXIT },
|
|
1224
|
+
},
|
|
1225
|
+
},
|
|
1226
|
+
};
|
|
1227
|
+
|
|
1228
|
+
let calls = 0;
|
|
1229
|
+
const agentRunner: AgentRunner = {
|
|
1230
|
+
run: async () => {
|
|
1231
|
+
calls++;
|
|
1232
|
+
if (calls === 1) throw usageLimitFailure();
|
|
1233
|
+
// Longer than the ORIGINAL budget's remainder (80ms - ~50ms slept) but
|
|
1234
|
+
// shorter than a recomputed one — without the recompute this surfaces
|
|
1235
|
+
// as `timeout`, with it the dispatch succeeds.
|
|
1236
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
1237
|
+
return { event: "ok" };
|
|
1238
|
+
},
|
|
1239
|
+
};
|
|
1240
|
+
|
|
1241
|
+
const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
|
|
1242
|
+
|
|
1243
|
+
expect(calls).toBe(2);
|
|
1244
|
+
expect(result.node.phase).toBe("succeeded");
|
|
1245
|
+
});
|
package/src/engine/run.ts
CHANGED
|
@@ -29,6 +29,13 @@ import { createJsonlEventLogger } from "./eventLog.ts";
|
|
|
29
29
|
const DEFAULT_HEARTBEAT_MS = 30_000;
|
|
30
30
|
const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000; // 1h — high default ceiling, not a tuning knob
|
|
31
31
|
const DEFAULT_MAX_STEPS = 1000;
|
|
32
|
+
// Usage-limit backoff defaults (docs/specs/usage-limit-backoff/spec.md) —
|
|
33
|
+
// the leaf-config fields on BaseLeafDef fall back to these. Fixed 30-min
|
|
34
|
+
// probe interval, deliberately not the provider message's quoted reset time
|
|
35
|
+
// (its timezone is not the supervisor's); 24h bounds the total wait per
|
|
36
|
+
// node visit before the run crashes with the last usage-limit reason.
|
|
37
|
+
const DEFAULT_USAGE_LIMIT_RETRY_MS = 30 * 60 * 1000;
|
|
38
|
+
const DEFAULT_USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60 * 1000;
|
|
32
39
|
// Bounded in-session repair attempts per outer attempt (see
|
|
33
40
|
// docs/specs/session-nudge/spec.md) — not a `def.retries`-style tuning
|
|
34
41
|
// knob, deliberately fixed.
|
|
@@ -63,6 +70,10 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
|
|
63
70
|
});
|
|
64
71
|
}
|
|
65
72
|
|
|
73
|
+
function sleep(ms: number): Promise<void> {
|
|
74
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
75
|
+
}
|
|
76
|
+
|
|
66
77
|
const defaultScriptRunner: ScriptRunner = {
|
|
67
78
|
async run(_id, def, handoff, baseDir, info) {
|
|
68
79
|
const url = pathToFileURL(`${baseDir}/${def.file}`).href;
|
|
@@ -203,6 +214,11 @@ export async function run(opts: RunOptions): Promise<RunResult> {
|
|
|
203
214
|
let reason: CrashReason | undefined;
|
|
204
215
|
let agentSessionId: string | undefined;
|
|
205
216
|
let attempt = 0;
|
|
217
|
+
// Usage-limit wait bookkeeping — per node visit, never per attempt:
|
|
218
|
+
// waits consume no retry, so the wait budget spans every attempt of
|
|
219
|
+
// this visit (docs/specs/usage-limit-backoff/spec.md).
|
|
220
|
+
let limitWaitedMs = 0;
|
|
221
|
+
let limitProbes = 0;
|
|
206
222
|
|
|
207
223
|
attemptLoop: for (attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
208
224
|
// Fixed once per outer attempt: every dispatch this attempt makes — the
|
|
@@ -210,7 +226,12 @@ export async function run(opts: RunOptions): Promise<RunResult> {
|
|
|
210
226
|
// SAME remaining budget, so a nudge sequence can't multiply the
|
|
211
227
|
// configured per-attempt timeout (docs/specs/session-nudge/spec.md,
|
|
212
228
|
// "Dispatch loop change").
|
|
213
|
-
|
|
229
|
+
//
|
|
230
|
+
// Usage-limit exception (same spec family, usage-limit-backoff D-7):
|
|
231
|
+
// recomputed after every usage-limit wait, so a slept interval never
|
|
232
|
+
// eats into the next dispatch's timeout — `timeoutMs` bounds a single
|
|
233
|
+
// dispatch, never a wait.
|
|
234
|
+
let deadline = Date.now() + timeoutMs;
|
|
214
235
|
let nudgeAttempt = 0;
|
|
215
236
|
|
|
216
237
|
for (;;) {
|
|
@@ -233,7 +254,10 @@ export async function run(opts: RunOptions): Promise<RunResult> {
|
|
|
233
254
|
const onProgress = (p: AgentProgress) => {
|
|
234
255
|
latestProgress = p;
|
|
235
256
|
};
|
|
236
|
-
const runningStatus = (
|
|
257
|
+
const runningStatus = (
|
|
258
|
+
lastHeartbeat: number,
|
|
259
|
+
limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number },
|
|
260
|
+
): NodeStatus => ({
|
|
237
261
|
phase: "running",
|
|
238
262
|
attempt,
|
|
239
263
|
startedAt,
|
|
@@ -246,6 +270,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
|
|
|
246
270
|
}
|
|
247
271
|
: {}),
|
|
248
272
|
...(nudgeAttempt > 0 ? { nudgeAttempt, nudgeReason } : {}),
|
|
273
|
+
...(limitBackoff ? { limitBackoff } : {}),
|
|
249
274
|
});
|
|
250
275
|
emit(runningStatus(startedAt), current, scopePath);
|
|
251
276
|
// Live-runtime heartbeats: journal a refreshed `running` status while the
|
|
@@ -309,6 +334,45 @@ export async function run(opts: RunOptions): Promise<RunResult> {
|
|
|
309
334
|
nudgeAttempt++;
|
|
310
335
|
continue;
|
|
311
336
|
}
|
|
337
|
+
// Usage-limit (docs/specs/usage-limit-backoff/spec.md, Wait and
|
|
338
|
+
// resume): a quota wall is not a failed attempt — it consumes no
|
|
339
|
+
// retry. Sleep usageLimitRetryMs (heartbeating the wait), then
|
|
340
|
+
// re-dispatch this same attempt; the existing
|
|
341
|
+
// previousFailure/agentSessionId threading below is what makes the
|
|
342
|
+
// runner resume the interrupted session. At the cap, the existing
|
|
343
|
+
// crashed() path after the attempt loop records the last
|
|
344
|
+
// usage-limit reason — attempt untouched, so the crash shows no
|
|
345
|
+
// retry consumed.
|
|
346
|
+
if (reason.kind === "usage-limit") {
|
|
347
|
+
const retryMs = def.usageLimitRetryMs ?? DEFAULT_USAGE_LIMIT_RETRY_MS;
|
|
348
|
+
const maxWaitMs = def.usageLimitMaxWaitMs ?? DEFAULT_USAGE_LIMIT_MAX_WAIT_MS;
|
|
349
|
+
if (limitWaitedMs + retryMs > maxWaitMs) {
|
|
350
|
+
break attemptLoop;
|
|
351
|
+
}
|
|
352
|
+
limitWaitedMs += retryMs;
|
|
353
|
+
limitProbes++;
|
|
354
|
+
const limitBackoff = {
|
|
355
|
+
probe: limitProbes,
|
|
356
|
+
nextAttemptAt: Date.now() + retryMs,
|
|
357
|
+
waitedMs: limitWaitedMs,
|
|
358
|
+
};
|
|
359
|
+
// Journal the wait immediately (nudge-start precedent: not gated
|
|
360
|
+
// behind a heartbeat cadence), then heartbeat it for as long as
|
|
361
|
+
// it lasts, so status/monitor show the wait instead of silence.
|
|
362
|
+
emit(runningStatus(Date.now(), limitBackoff), current, scopePath);
|
|
363
|
+
const waitHeartbeat =
|
|
364
|
+
heartbeatMs > 0
|
|
365
|
+
? setInterval(
|
|
366
|
+
() => emit(runningStatus(Date.now(), limitBackoff), current, scopePath),
|
|
367
|
+
heartbeatMs,
|
|
368
|
+
)
|
|
369
|
+
: undefined;
|
|
370
|
+
waitHeartbeat?.unref?.();
|
|
371
|
+
await sleep(retryMs);
|
|
372
|
+
waitHeartbeat && clearInterval(waitHeartbeat);
|
|
373
|
+
deadline = Date.now() + timeoutMs;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
312
376
|
continue attemptLoop;
|
|
313
377
|
}
|
|
314
378
|
}
|