@psimona/darkf 0.4.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/index.ts +1 -0
- package/src/core/tasks.test.ts +146 -0
- package/src/core/tasks.ts +158 -0
- package/src/core/types.ts +42 -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 +118 -1
- package/src/kit/status.ts +67 -1
- package/workflows/dev-loop/scripts/begin.ts +1 -1
- package/workflows/dev-loop/scripts/finish.ts +13 -2
- package/workflows/dev-loop/workflow.ts +57 -23
- 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/tsconfig.json +0 -4
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
|
}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import {
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
2
|
+
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { AgentFailure, type AgentStateDef, type DispatchInfo } from "../../core/index.ts";
|
|
6
|
+
import { handoffPath } from "./handoff.ts";
|
|
7
|
+
import { matchUsageLimit, opencodeRunner, readIncrementally, scanStepFinish } from "./opencode.ts";
|
|
3
8
|
|
|
4
9
|
function ndjson(events: unknown[]): string {
|
|
5
10
|
return events.map((e) => JSON.stringify(e)).join("\n");
|
|
@@ -134,3 +139,228 @@ describe("readIncrementally", () => {
|
|
|
134
139
|
expect(seen).toEqual(["café"]);
|
|
135
140
|
});
|
|
136
141
|
});
|
|
142
|
+
|
|
143
|
+
// --- usage-limit-backoff (docs/specs/usage-limit-backoff/spec.md) ---
|
|
144
|
+
|
|
145
|
+
describe("matchUsageLimit", () => {
|
|
146
|
+
test("matches the captured usage-limit line, case-insensitively, returning the line itself", () => {
|
|
147
|
+
const captured = "Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19";
|
|
148
|
+
expect(matchUsageLimit(`${captured}\n`, "")).toBe(captured);
|
|
149
|
+
expect(matchUsageLimit("", "USAGE LIMIT EXHAUSTED — retry later\n")).toBe(
|
|
150
|
+
"USAGE LIMIT EXHAUSTED — retry later",
|
|
151
|
+
);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("matches the full conservative marker set: rate limit, limit exceeded, 429", () => {
|
|
155
|
+
expect(matchUsageLimit("rate limit exceeded for org\n", "")).toBe(
|
|
156
|
+
"rate limit exceeded for org",
|
|
157
|
+
);
|
|
158
|
+
expect(matchUsageLimit("", "limit exceeded: reduce your request rate\n")).toBe(
|
|
159
|
+
"limit exceeded: reduce your request rate",
|
|
160
|
+
);
|
|
161
|
+
expect(matchUsageLimit("HTTP 429: too many requests\n", "")).toBe(
|
|
162
|
+
"HTTP 429: too many requests",
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("scans stderr first, then stdout, returning the first matched line", () => {
|
|
167
|
+
expect(matchUsageLimit("first stderr rate limit\n", "second stdout usage limit\n")).toBe(
|
|
168
|
+
"first stderr rate limit",
|
|
169
|
+
);
|
|
170
|
+
expect(matchUsageLimit("", "stdout usage limit\n")).toBe("stdout usage limit");
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("never matches an agent-authored JSON line, even when its text contains a marker", () => {
|
|
174
|
+
const json = JSON.stringify({
|
|
175
|
+
type: "message",
|
|
176
|
+
part: { text: "the agent mused about the usage limit" },
|
|
177
|
+
});
|
|
178
|
+
expect(matchUsageLimit("", json)).toBeUndefined();
|
|
179
|
+
expect(matchUsageLimit(`${json}\nplain usage limit line\n`, "")).toBe("plain usage limit line");
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test("an ordinary non-limit API error does not match", () => {
|
|
183
|
+
expect(matchUsageLimit("opencode: API error 500: backend exploded\n", "")).toBeUndefined();
|
|
184
|
+
expect(matchUsageLimit("", '{"type":"step-finish","part":{"reason":"stop"}}')).toBeUndefined();
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// Runner-level classification and resume paths. A fake `opencode` binary
|
|
189
|
+
// stands in for the real CLI: it records argv (NUL-separated, prompts contain
|
|
190
|
+
// newlines), emits NDJSON, optionally writes the handoff file, and exits with
|
|
191
|
+
// a scripted code — so `Bun.spawn` runs unmocked. `Bun.which` is mocked to
|
|
192
|
+
// resolve it: it snapshots PATH at process start, so mutating the env at
|
|
193
|
+
// test time has no effect.
|
|
194
|
+
describe("opencodeRunner usage-limit classification + resume", () => {
|
|
195
|
+
let fakeDir: string;
|
|
196
|
+
let realWhich: typeof Bun.which;
|
|
197
|
+
|
|
198
|
+
beforeAll(() => {
|
|
199
|
+
fakeDir = mkdtempSync(join(tmpdir(), "darkf-opencode-fake-"));
|
|
200
|
+
realWhich = Bun.which;
|
|
201
|
+
Bun.which = ((bin: string) =>
|
|
202
|
+
bin === "opencode" ? join(fakeDir, "opencode") : realWhich(bin)) as typeof Bun.which;
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
afterAll(() => {
|
|
206
|
+
Bun.which = realWhich;
|
|
207
|
+
rmSync(fakeDir, { recursive: true, force: true });
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const RUN_ID = "f1e2d3c4-1111-4222-8333-444455556666";
|
|
211
|
+
const def: AgentStateDef = {
|
|
212
|
+
type: "agent",
|
|
213
|
+
prompt: "FRESH-PROMPT-MARKER do the task",
|
|
214
|
+
agent: { model: "test-model" },
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
/** Installs a scripted fake binary and a per-test scratch rootDir. The
|
|
218
|
+
* builder receives the rootDir and the argv log path, both baked into the
|
|
219
|
+
* script text. */
|
|
220
|
+
function install(build: (rootDir: string, argvFile: string) => string): {
|
|
221
|
+
rootDir: string;
|
|
222
|
+
argvFile: string;
|
|
223
|
+
} {
|
|
224
|
+
const rootDir = mkdtempSync(join(tmpdir(), "darkf-opencode-run-"));
|
|
225
|
+
const argvFile = join(rootDir, "argv.bin");
|
|
226
|
+
writeFileSync(join(fakeDir, "opencode"), `#!/bin/sh\n${build(rootDir, argvFile)}\n`);
|
|
227
|
+
chmodSync(join(fakeDir, "opencode"), 0o755);
|
|
228
|
+
return { rootDir, argvFile };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function readArgv(argvFile: string): string[] {
|
|
232
|
+
return readFileSync(argvFile, "utf8")
|
|
233
|
+
.split("\0")
|
|
234
|
+
.filter((arg) => arg.length > 0);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function info(rootDir: string, over: Partial<DispatchInfo> = {}): DispatchInfo {
|
|
238
|
+
return {
|
|
239
|
+
runId: RUN_ID,
|
|
240
|
+
validEvents: ["ok"],
|
|
241
|
+
hasFallback: false,
|
|
242
|
+
attempt: 1,
|
|
243
|
+
step: 1,
|
|
244
|
+
rootDir,
|
|
245
|
+
...over,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function successScript(rootDir: string, argvFile: string, sessionId: string): string {
|
|
250
|
+
const handoffFile = handoffPath(rootDir, RUN_ID, 1, "N");
|
|
251
|
+
return [
|
|
252
|
+
`printf '%s\\0' "$@" > "${argvFile}"`,
|
|
253
|
+
`echo '{"type":"step-finish","part":{"reason":"stop","sessionID":"${sessionId}"}}'`,
|
|
254
|
+
`mkdir -p "$(dirname "${handoffFile}")"`,
|
|
255
|
+
`echo '{"event":"ok"}' > "${handoffFile}"`,
|
|
256
|
+
].join("\n");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
test("a non-zero exit with the captured limit message classifies usage-limit, with the evidence-gated session id", async () => {
|
|
260
|
+
const { rootDir } = install((_rootDir, _argvFile) =>
|
|
261
|
+
[
|
|
262
|
+
`echo 'Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19' 1>&2`,
|
|
263
|
+
`echo '{"type":"step-finish","part":{"reason":"stop","sessionID":"sess-wall"}}'`,
|
|
264
|
+
`exit 3`,
|
|
265
|
+
].join("\n"),
|
|
266
|
+
);
|
|
267
|
+
|
|
268
|
+
let thrown: unknown;
|
|
269
|
+
try {
|
|
270
|
+
await opencodeRunner.run("N", def, {}, info(rootDir));
|
|
271
|
+
} catch (err) {
|
|
272
|
+
thrown = err;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
expect(thrown).toBeInstanceOf(AgentFailure);
|
|
276
|
+
const failure = thrown as AgentFailure;
|
|
277
|
+
expect(failure.crashReason).toEqual({
|
|
278
|
+
kind: "usage-limit",
|
|
279
|
+
detail: "Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19",
|
|
280
|
+
});
|
|
281
|
+
expect(failure.agentSessionId).toBe("sess-wall");
|
|
282
|
+
rmSync(rootDir, { recursive: true, force: true });
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
test("a non-zero exit with a non-limit API error stays runner-error", async () => {
|
|
286
|
+
const { rootDir } = install((_rootDir, _argvFile) =>
|
|
287
|
+
[`echo 'API error: 500 backend exploded' 1>&2`, `exit 1`].join("\n"),
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
let thrown: unknown;
|
|
291
|
+
try {
|
|
292
|
+
await opencodeRunner.run("N", def, {}, info(rootDir));
|
|
293
|
+
} catch (err) {
|
|
294
|
+
thrown = err;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
expect(thrown).toBeInstanceOf(AgentFailure);
|
|
298
|
+
const failure = thrown as AgentFailure;
|
|
299
|
+
expect(failure.crashReason).toEqual({
|
|
300
|
+
kind: "runner-error",
|
|
301
|
+
error: expect.stringContaining("500 backend exploded"),
|
|
302
|
+
});
|
|
303
|
+
rmSync(rootDir, { recursive: true, force: true });
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("an exit-0 + missing-handoff output with a limit string inside an agent JSON line stays handoff-missing", async () => {
|
|
307
|
+
const { rootDir } = install((_rootDir, _argvFile) =>
|
|
308
|
+
[
|
|
309
|
+
`echo '{"type":"message","part":{"text":"note to self: mind the usage limit"}}'`,
|
|
310
|
+
`exit 0`,
|
|
311
|
+
].join("\n"),
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
let thrown: unknown;
|
|
315
|
+
try {
|
|
316
|
+
await opencodeRunner.run("N", def, {}, info(rootDir));
|
|
317
|
+
} catch (err) {
|
|
318
|
+
thrown = err;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
expect(thrown).toBeInstanceOf(AgentFailure);
|
|
322
|
+
expect((thrown as AgentFailure).crashReason).toEqual({ kind: "handoff-missing" });
|
|
323
|
+
rmSync(rootDir, { recursive: true, force: true });
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
test("resume: previousFailure usage-limit + agentSessionId dispatches -s and the continuation prompt, not the fresh prompt", async () => {
|
|
327
|
+
const { rootDir, argvFile } = install((dir, argv) => successScript(dir, argv, "sess-9"));
|
|
328
|
+
|
|
329
|
+
const result = await opencodeRunner.run("N", def, {}, {
|
|
330
|
+
...info(rootDir),
|
|
331
|
+
previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
|
|
332
|
+
agentSessionId: "sess-9",
|
|
333
|
+
} as DispatchInfo);
|
|
334
|
+
|
|
335
|
+
expect(result).toEqual({ event: "ok", agentSessionId: "sess-9" });
|
|
336
|
+
const argv = readArgv(argvFile);
|
|
337
|
+
expect(argv).toContain("-s");
|
|
338
|
+
expect(argv).toContain("sess-9");
|
|
339
|
+
const prompt = argv.at(-1)!;
|
|
340
|
+
expect(prompt).toContain("A provider usage limit interrupted your previous turn.");
|
|
341
|
+
expect(prompt).toContain("Continue where you left off.");
|
|
342
|
+
// The handoff contract text still closes the continuation prompt...
|
|
343
|
+
expect(prompt).toContain("write your result as JSON to this exact path");
|
|
344
|
+
// ...and the full fresh prompt is NOT replayed.
|
|
345
|
+
expect(prompt).not.toContain("FRESH-PROMPT-MARKER");
|
|
346
|
+
rmSync(rootDir, { recursive: true, force: true });
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
test("resume without a session id (no persisted evidence) dispatches fresh, without -s", async () => {
|
|
350
|
+
const { rootDir, argvFile } = install((dir, argv) => successScript(dir, argv, "sess-unused"));
|
|
351
|
+
|
|
352
|
+
const result = await opencodeRunner.run("N", def, {}, {
|
|
353
|
+
...info(rootDir),
|
|
354
|
+
previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
|
|
355
|
+
} as DispatchInfo);
|
|
356
|
+
|
|
357
|
+
expect(result).toEqual({ event: "ok", agentSessionId: "sess-unused" });
|
|
358
|
+
const argv = readArgv(argvFile);
|
|
359
|
+
expect(argv).not.toContain("-s");
|
|
360
|
+
const prompt = argv.at(-1)!;
|
|
361
|
+
// The fresh prompt path, unchanged.
|
|
362
|
+
expect(prompt).toContain("FRESH-PROMPT-MARKER");
|
|
363
|
+
expect(prompt).not.toContain("Continue where you left off");
|
|
364
|
+
rmSync(rootDir, { recursive: true, force: true });
|
|
365
|
+
});
|
|
366
|
+
});
|
|
@@ -152,6 +152,38 @@ function contextBlock(rootDir: string, runId: string): string {
|
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
+
// Usage-limit detection (docs/specs/usage-limit-backoff/spec.md, Detection):
|
|
156
|
+
// a provider quota wall surfaces as an API-level error — opencode exits
|
|
157
|
+
// non-zero with the provider's message in its output. Scan stderr and
|
|
158
|
+
// non-JSON stdout lines ONLY: stdout's NDJSON lines are event objects, i.e.
|
|
159
|
+
// agent-authored content — a limit-shaped string inside one must never match
|
|
160
|
+
// (a false positive turns a real crash into a silent hours-long wait; the
|
|
161
|
+
// worse error). Markers, case-insensitive, from the 2026-11-01 live capture
|
|
162
|
+
// ("Usage limit reached for 5 hour. Your limit will reset at ..."): the
|
|
163
|
+
// quoted reset time is display text darkf never parses — see the spec's Wait
|
|
164
|
+
// section for why a fixed interval is the honest response. Returns the first
|
|
165
|
+
// matched line; callers consult this on the non-zero-exit branch only, so a
|
|
166
|
+
// limit-shaped string on the exit-0 + missing-handoff path stays a
|
|
167
|
+
// `handoff-missing` on its existing nudge/repair path.
|
|
168
|
+
const USAGE_LIMIT_MARKERS = ["usage limit", "rate limit", "limit exceeded", "429"];
|
|
169
|
+
|
|
170
|
+
export function matchUsageLimit(stderr: string, stdout: string): string | undefined {
|
|
171
|
+
for (const text of [stderr, stdout]) {
|
|
172
|
+
for (const line of text.split("\n")) {
|
|
173
|
+
if (!line.trim()) continue;
|
|
174
|
+
try {
|
|
175
|
+
JSON.parse(line);
|
|
176
|
+
continue; // event object — agent-authored, never matched
|
|
177
|
+
} catch {
|
|
178
|
+
// not JSON — runner/provider output
|
|
179
|
+
}
|
|
180
|
+
const lowered = line.toLowerCase();
|
|
181
|
+
if (USAGE_LIMIT_MARKERS.some((marker) => lowered.includes(marker))) return line;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
|
|
155
187
|
export const opencodeRunner: AgentRunner = {
|
|
156
188
|
kind: "opencode",
|
|
157
189
|
async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
|
|
@@ -186,9 +218,26 @@ export const opencodeRunner: AgentRunner = {
|
|
|
186
218
|
// "No -s outside a nudge" note below.
|
|
187
219
|
const nudge = nudgeMessage(info, path);
|
|
188
220
|
|
|
221
|
+
// Post-limit continuation (docs/specs/usage-limit-backoff/spec.md, Wait
|
|
222
|
+
// and resume): when the engine re-dispatches this attempt after waiting
|
|
223
|
+
// out a usage limit, resume the interrupted session with a short
|
|
224
|
+
// continuation prompt instead of replaying the full fresh prompt — the
|
|
225
|
+
// dispatch itself doubles as the limit probe (a still-limited provider
|
|
226
|
+
// rejects it before processing; a lifted limit continues mid-flight with
|
|
227
|
+
// all pre-wall work intact). A present agentSessionId IS the evidence
|
|
228
|
+
// gate: the runner only ever attaches one when `scanStepFinish` counted
|
|
229
|
+
// step events (stepCount > 0), the same bar that makes `-s` safe for
|
|
230
|
+
// nudges. Without a session id the dispatch is fresh, exactly as before.
|
|
231
|
+
const continuation =
|
|
232
|
+
info.previousFailure?.kind === "usage-limit" && info.agentSessionId !== undefined
|
|
233
|
+
? `A provider usage limit interrupted your previous turn. Continue where you left off.\n\n${handoffContractText(path)}`
|
|
234
|
+
: undefined;
|
|
235
|
+
|
|
189
236
|
let prompt: string;
|
|
190
237
|
if (nudge) {
|
|
191
238
|
prompt = nudge;
|
|
239
|
+
} else if (continuation) {
|
|
240
|
+
prompt = continuation;
|
|
192
241
|
} else {
|
|
193
242
|
const promptParts: string[] = [];
|
|
194
243
|
|
|
@@ -225,16 +274,17 @@ export const opencodeRunner: AgentRunner = {
|
|
|
225
274
|
// terminal runner crash. `scanStepFinish`'s `stepCount` guard (above) is
|
|
226
275
|
// what makes `-s` safe again — the hang's root cause was resuming a
|
|
227
276
|
// session with no evidence it had done anything, not resuming as such —
|
|
228
|
-
// but it's deliberately only ever used for
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
277
|
+
// but it's deliberately only ever used for two explicitly-scoped cases:
|
|
278
|
+
// a nudge (immediately after a nudgeable failure in the same outer
|
|
279
|
+
// attempt) and the post-limit continuation (usage-limit-backoff spec —
|
|
280
|
+
// same evidence gate, same reasoning). A fresh or exhausted-nudge
|
|
281
|
+
// dispatch always starts a brand-new session, exactly as today, even
|
|
282
|
+
// when `info.agentSessionId` happens to be set.
|
|
233
283
|
const bin = Bun.which("opencode") ?? "opencode";
|
|
234
284
|
const args = [
|
|
235
285
|
bin,
|
|
236
286
|
"run",
|
|
237
|
-
...(nudge ? ["-s", info.agentSessionId!] : []),
|
|
287
|
+
...(nudge || continuation ? ["-s", info.agentSessionId!] : []),
|
|
238
288
|
...(auto ? ["--auto"] : []),
|
|
239
289
|
"-m",
|
|
240
290
|
model,
|
|
@@ -285,6 +335,19 @@ export const opencodeRunner: AgentRunner = {
|
|
|
285
335
|
const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
|
|
286
336
|
lastFailures.set(dispatchKey, reason);
|
|
287
337
|
const scan = scanStepFinish(stdout);
|
|
338
|
+
// Usage-limit classification (docs/specs/usage-limit-backoff/spec.md):
|
|
339
|
+
// consulted on this non-zero-exit branch ONLY, before the generic
|
|
340
|
+
// throw — a quota wall is a known temporary condition, and the engine
|
|
341
|
+
// waits it out instead of burning retries against it. The session id
|
|
342
|
+
// stays evidence-gated (stepCount > 0) exactly as below. No match
|
|
343
|
+
// keeps the existing runner-error throw unchanged.
|
|
344
|
+
const limitLine = matchUsageLimit(stderr, stdout);
|
|
345
|
+
if (limitLine !== undefined) {
|
|
346
|
+
throw new AgentFailure(reason, {
|
|
347
|
+
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
348
|
+
crashReason: { kind: "usage-limit", detail: limitLine },
|
|
349
|
+
});
|
|
350
|
+
}
|
|
288
351
|
throw new AgentFailure(reason, {
|
|
289
352
|
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
290
353
|
crashReason: { kind: "runner-error", error: reason },
|