@psimona/darkf 0.0.0-stage → 0.4.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/README.md +28 -2
- package/bunfig.toml +13 -0
- package/examples/article-classifier/data/articles.ts +38 -0
- package/examples/article-classifier/scripts/next.ts +7 -0
- package/examples/article-classifier/scripts/queue.ts +33 -0
- package/examples/article-classifier/scripts/record.ts +9 -0
- package/examples/article-classifier/workflow.ts +44 -0
- package/examples/haiku-commit/scripts/check.ts +24 -0
- package/examples/haiku-commit/workflow.ts +28 -0
- package/examples/haiku-readme/scripts/test.ts +13 -0
- package/examples/haiku-readme/scripts/write.ts +10 -0
- package/examples/haiku-readme/workflow.ts +41 -0
- package/examples/task-queue/scripts/next.ts +20 -0
- package/examples/task-queue/scripts/record.ts +20 -0
- package/examples/task-queue/supervise.ts +57 -0
- package/examples/task-queue/workflow.ts +33 -0
- package/feedback/2026-10-30-self-update.md +29 -0
- package/package.json +30 -4
- package/src/cli/detached.test.ts +560 -0
- package/src/cli/index.ts +1040 -0
- package/src/cli/update.test.ts +486 -0
- package/src/cli/update.ts +191 -0
- package/src/core/graph.test.ts +172 -0
- package/src/core/graph.ts +148 -0
- package/src/core/index.ts +4 -0
- package/src/core/journal.ts +21 -0
- package/src/core/mermaid.test.ts +34 -0
- package/src/core/mermaid.ts +95 -0
- package/src/core/types.ts +279 -0
- package/src/engine/eventLog.ts +17 -0
- package/src/engine/index.ts +2 -0
- package/src/engine/run.test.ts +1068 -0
- package/src/engine/run.ts +359 -0
- package/src/exports.ts +2 -0
- package/src/kit/agents/claude-code.test.ts +37 -0
- package/src/kit/agents/claude-code.ts +180 -0
- package/src/kit/agents/handoff.test.ts +128 -0
- package/src/kit/agents/handoff.ts +69 -0
- package/src/kit/agents/opencode.test.ts +136 -0
- package/src/kit/agents/opencode.ts +327 -0
- package/src/kit/registry.test.ts +386 -0
- package/src/kit/registry.ts +296 -0
- package/src/kit/status.test.ts +423 -0
- package/src/kit/status.ts +282 -0
- package/tsconfig.json +4 -0
- package/workflows/dev-loop/scripts/begin.ts +22 -0
- package/workflows/dev-loop/scripts/check.ts +19 -0
- package/workflows/dev-loop/scripts/finish.ts +114 -0
- package/workflows/dev-loop/workflow.ts +135 -0
- package/workflows/series-ordering/scripts/verify.ts +18 -0
- package/workflows/series-ordering/workflow.ts +80 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { afterAll, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { DispatchInfo } from "../../core/index.ts";
|
|
6
|
+
import { handoffContractText, handoffPath, nudgeMessage, readHandoff } from "./handoff.ts";
|
|
7
|
+
|
|
8
|
+
const testRootDir = await mkdtemp(join(tmpdir(), "darkf-cli-handoff-test-"));
|
|
9
|
+
afterAll(() => rm(testRootDir, { recursive: true, force: true }));
|
|
10
|
+
|
|
11
|
+
test("handoffPath zero-pads step to 4 digits under the run's handoff dir", () => {
|
|
12
|
+
expect(handoffPath("/root", "run-1", 1, "Plan")).toBe(
|
|
13
|
+
join("/root", ".darkf", "run", "run-1", "handoff", "0001-Plan.json"),
|
|
14
|
+
);
|
|
15
|
+
expect(handoffPath("/root", "run-1", 42, "Review")).toBe(
|
|
16
|
+
join("/root", ".darkf", "run", "run-1", "handoff", "0042-Review.json"),
|
|
17
|
+
);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("handoffPath disambiguates the same nodeId revisited at different steps", () => {
|
|
21
|
+
const first = handoffPath("/root", "run-1", 2, "Write");
|
|
22
|
+
const second = handoffPath("/root", "run-1", 4, "Write");
|
|
23
|
+
expect(first).not.toBe(second);
|
|
24
|
+
expect(first).toBe(join("/root", ".darkf", "run", "run-1", "handoff", "0002-Write.json"));
|
|
25
|
+
expect(second).toBe(join("/root", ".darkf", "run", "run-1", "handoff", "0004-Write.json"));
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("handoffContractText names the exact path the agent must write to", () => {
|
|
29
|
+
const text = handoffContractText("/some/path/0001-Plan.json");
|
|
30
|
+
expect(text).toContain("/some/path/0001-Plan.json");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("readHandoff parses a well-formed handoff file", async () => {
|
|
34
|
+
const path = join(testRootDir, "0001-Plan.json");
|
|
35
|
+
await writeFile(path, JSON.stringify({ event: "approved", output: { plan: "x" } }));
|
|
36
|
+
|
|
37
|
+
await expect(readHandoff(path)).resolves.toEqual({ event: "approved", output: { plan: "x" } });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("readHandoff throws when the file is missing", async () => {
|
|
41
|
+
const path = join(testRootDir, "missing", "0002-Nope.json");
|
|
42
|
+
await expect(readHandoff(path)).rejects.toThrow();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("readHandoff throws on malformed JSON, un-validated otherwise", async () => {
|
|
46
|
+
const dir = join(testRootDir, "malformed");
|
|
47
|
+
await mkdir(dir, { recursive: true });
|
|
48
|
+
const path = join(dir, "0003-Bad.json");
|
|
49
|
+
await writeFile(path, "{not json");
|
|
50
|
+
|
|
51
|
+
await expect(readHandoff(path)).rejects.toThrow();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("readHandoff returns whatever parses, with no shape check of its own", async () => {
|
|
55
|
+
const path = join(testRootDir, "0004-Anything.json");
|
|
56
|
+
await writeFile(path, JSON.stringify({ notAtAllANodeResult: true, count: 3 }));
|
|
57
|
+
|
|
58
|
+
await expect(readHandoff(path)).resolves.toEqual({ notAtAllANodeResult: true, count: 3 });
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("readHandoff round-trips a plain array or primitive without objecting", async () => {
|
|
62
|
+
const path = join(testRootDir, "0005-Primitive.json");
|
|
63
|
+
await writeFile(path, "42");
|
|
64
|
+
|
|
65
|
+
await expect(readHandoff(path)).resolves.toBe(42);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
function baseInfo(overrides: Partial<DispatchInfo> = {}): DispatchInfo {
|
|
69
|
+
return {
|
|
70
|
+
runId: "run-1",
|
|
71
|
+
validEvents: ["ok", "changes_requested"],
|
|
72
|
+
hasFallback: false,
|
|
73
|
+
attempt: 1,
|
|
74
|
+
step: 1,
|
|
75
|
+
rootDir: "/root",
|
|
76
|
+
...overrides,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
test("nudgeMessage is undefined with no previousFailure, even with a session id", () => {
|
|
81
|
+
expect(nudgeMessage(baseInfo({ agentSessionId: "sess-1" }), "/path")).toBeUndefined();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("nudgeMessage is undefined with a nudgeable failure but no session id", () => {
|
|
85
|
+
const info = baseInfo({ previousFailure: { kind: "handoff-missing" } });
|
|
86
|
+
expect(nudgeMessage(info, "/path")).toBeUndefined();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("nudgeMessage is undefined for a non-nudgeable failure, even with a session id", () => {
|
|
90
|
+
const info = baseInfo({
|
|
91
|
+
agentSessionId: "sess-1",
|
|
92
|
+
previousFailure: { kind: "runner-error", error: "boom" },
|
|
93
|
+
});
|
|
94
|
+
expect(nudgeMessage(info, "/path")).toBeUndefined();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("nudgeMessage builds the handoff-missing repair text", () => {
|
|
98
|
+
const info = baseInfo({
|
|
99
|
+
agentSessionId: "sess-1",
|
|
100
|
+
previousFailure: { kind: "handoff-missing" },
|
|
101
|
+
});
|
|
102
|
+
const msg = nudgeMessage(info, "/root/.darkf/run/run-1/handoff/0001-Plan.json")!;
|
|
103
|
+
expect(msg).toContain("without writing the result file");
|
|
104
|
+
expect(msg).toContain("/root/.darkf/run/run-1/handoff/0001-Plan.json");
|
|
105
|
+
expect(msg).toContain("ok, changes_requested");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("nudgeMessage builds the handoff-unparseable repair text, quoting the parse error", () => {
|
|
109
|
+
const info = baseInfo({
|
|
110
|
+
agentSessionId: "sess-1",
|
|
111
|
+
previousFailure: { kind: "handoff-unparseable", parseError: "Unexpected token x" },
|
|
112
|
+
});
|
|
113
|
+
const msg = nudgeMessage(info, "/path/0001-Plan.json")!;
|
|
114
|
+
expect(msg).toContain("failed to parse");
|
|
115
|
+
expect(msg).toContain("Unexpected token x");
|
|
116
|
+
expect(msg).toContain("/path/0001-Plan.json");
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("nudgeMessage builds the no-transition repair text, naming the bad event and valid ones", () => {
|
|
120
|
+
const info = baseInfo({
|
|
121
|
+
agentSessionId: "sess-1",
|
|
122
|
+
previousFailure: { kind: "no-transition", state: "Review", event: "maybe" },
|
|
123
|
+
});
|
|
124
|
+
const msg = nudgeMessage(info, "/path")!;
|
|
125
|
+
expect(msg).toContain("maybe");
|
|
126
|
+
expect(msg).toContain("ok, changes_requested");
|
|
127
|
+
expect(msg).toContain("routable event");
|
|
128
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { DispatchInfo } from "../../core/index.ts";
|
|
4
|
+
|
|
5
|
+
// Shared, harness-agnostic half of the agent-handoff contract. See
|
|
6
|
+
// docs/specs/agent-handoff/spec.md. Per-harness runners own everything else
|
|
7
|
+
// (invocation, native structured-output vs. prompt fallback, agentSessionId,
|
|
8
|
+
// subprocess lifecycle).
|
|
9
|
+
|
|
10
|
+
/** `.darkf/run/<runId>/handoff/<step, zero-padded to 4 digits>-<nodeId>.json` */
|
|
11
|
+
export function handoffPath(rootDir: string, runId: string, step: number, nodeId: string): string {
|
|
12
|
+
const padded = String(step).padStart(4, "0");
|
|
13
|
+
return join(rootDir, ".darkf", "run", runId, "handoff", `${padded}-${nodeId}.json`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Fixed instruction block for harnesses with no native "write structured
|
|
18
|
+
* output to this path" flag. Appended to the node's own prompt; tells the
|
|
19
|
+
* agent exactly what to write and where.
|
|
20
|
+
*/
|
|
21
|
+
export function handoffContractText(path: string): string {
|
|
22
|
+
return `When you are done, write your result as JSON to this exact path: ${path}
|
|
23
|
+
|
|
24
|
+
The JSON object may have any of these optional fields:
|
|
25
|
+
- "event": a string naming the outcome (omit if this step has no outgoing choice to make)
|
|
26
|
+
- "output": any JSON value to hand to the next step
|
|
27
|
+
- "agentSessionId": omit unless you have a specific reason to set it
|
|
28
|
+
|
|
29
|
+
Write nothing else to that path. Create the file's parent directories if they don't exist yet.`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Read + `JSON.parse`, nothing else. Shape validation is the engine's job (`isNodeResult`), not this file's. */
|
|
33
|
+
export async function readHandoff(path: string): Promise<unknown> {
|
|
34
|
+
const text = await readFile(path, "utf8");
|
|
35
|
+
return JSON.parse(text);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Shared same-session repair text for the three nudgeable `CrashReason`
|
|
40
|
+
* kinds (docs/specs/session-nudge/spec.md). `undefined` means "don't
|
|
41
|
+
* nudge" — either there's no `previousFailure`, no `agentSessionId` to
|
|
42
|
+
* resume, or the failure isn't one of the three repairable kinds. Both
|
|
43
|
+
* runners call this identically; only the CLI invocation that sends the
|
|
44
|
+
* message differs per harness.
|
|
45
|
+
*/
|
|
46
|
+
export function nudgeMessage(info: DispatchInfo, path: string): string | undefined {
|
|
47
|
+
const failure = info.previousFailure;
|
|
48
|
+
if (!failure || !info.agentSessionId) return undefined;
|
|
49
|
+
const validEvents = info.validEvents.join(", ");
|
|
50
|
+
switch (failure.kind) {
|
|
51
|
+
case "handoff-missing":
|
|
52
|
+
return `Your previous turn ended without writing the result file. Ignore any blocked tool calls and write the JSON handoff to ${path} now. Valid events: ${validEvents}.`;
|
|
53
|
+
case "handoff-unparseable":
|
|
54
|
+
return `The JSON at ${path} failed to parse (${failure.parseError}). Rewrite it as a single valid JSON object with the contract fields.`;
|
|
55
|
+
case "no-transition":
|
|
56
|
+
return `You reported event ${failure.event}; this state only routes ${validEvents}. Re-issue the handoff with a routable event.`;
|
|
57
|
+
default:
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `.darkf/run/<runId>/usage/<step, zero-padded to 4 digits>-<nodeId>.json` — the
|
|
63
|
+
* per-dispatch usage sidecar (cost/tokens), written by runners, read by
|
|
64
|
+
* `status`/`report`. Usage is deliberately NOT part of the NodeResult data
|
|
65
|
+
* flow: it is telemetry about a dispatch, not data for the next node. */
|
|
66
|
+
export function usagePath(rootDir: string, runId: string, step: number, nodeId: string): string {
|
|
67
|
+
const padded = String(step).padStart(4, "0");
|
|
68
|
+
return join(rootDir, ".darkf", "run", runId, "usage", `${padded}-${nodeId}.json`);
|
|
69
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { readIncrementally, scanStepFinish } from "./opencode.ts";
|
|
3
|
+
|
|
4
|
+
function ndjson(events: unknown[]): string {
|
|
5
|
+
return events.map((e) => JSON.stringify(e)).join("\n");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** A stream that yields exactly `chunks`, as given — lets a test control
|
|
9
|
+
* chunk boundaries precisely (mid-line). */
|
|
10
|
+
function streamOf(chunks: string[]): ReadableStream<Uint8Array> {
|
|
11
|
+
const encoder = new TextEncoder();
|
|
12
|
+
let i = 0;
|
|
13
|
+
return new ReadableStream({
|
|
14
|
+
pull(controller) {
|
|
15
|
+
if (i >= chunks.length) {
|
|
16
|
+
controller.close();
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
controller.enqueue(encoder.encode(chunks[i++]));
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Same, but splits raw bytes at `splitAt` — lets a test put a chunk
|
|
25
|
+
* boundary in the middle of a multi-byte UTF-8 character. */
|
|
26
|
+
function streamOfBytesSplitAt(text: string, splitAt: number): ReadableStream<Uint8Array> {
|
|
27
|
+
const bytes = new TextEncoder().encode(text);
|
|
28
|
+
const chunks = [bytes.slice(0, splitAt), bytes.slice(splitAt)];
|
|
29
|
+
let i = 0;
|
|
30
|
+
return new ReadableStream({
|
|
31
|
+
pull(controller) {
|
|
32
|
+
if (i >= chunks.length) {
|
|
33
|
+
controller.close();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
controller.enqueue(chunks[i++]!);
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe("scanStepFinish", () => {
|
|
42
|
+
test("reports stepCount 0 and no session id on an empty stream", () => {
|
|
43
|
+
const scan = scanStepFinish("");
|
|
44
|
+
expect(scan.stepCount).toBe(0);
|
|
45
|
+
expect(scan.sessionId).toBeUndefined();
|
|
46
|
+
expect(scan.reason).toBeUndefined();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("ignores lines that aren't step-finish or aren't parseable JSON", () => {
|
|
50
|
+
const stdout = ndjson([
|
|
51
|
+
{ type: "message", part: { sessionID: "sess-x" } },
|
|
52
|
+
{ type: "step-finish", part: { reason: "stop", sessionID: "sess-1" } },
|
|
53
|
+
]);
|
|
54
|
+
const scan = scanStepFinish(`not json\n${stdout}\n`);
|
|
55
|
+
expect(scan.stepCount).toBe(1);
|
|
56
|
+
expect(scan.sessionId).toBe("sess-1");
|
|
57
|
+
expect(scan.reason).toBe("stop");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("counts every step-finish event and keeps the LAST reason/sessionID seen", () => {
|
|
61
|
+
const stdout = ndjson([
|
|
62
|
+
{ type: "step-finish", part: { reason: "tool-calls", sessionID: "sess-1" } },
|
|
63
|
+
{ type: "step-finish", part: { reason: "stop", sessionID: "sess-1" } },
|
|
64
|
+
{ type: "step-finish", part: { reason: "length" } }, // no sessionID on this one
|
|
65
|
+
]);
|
|
66
|
+
const scan = scanStepFinish(stdout);
|
|
67
|
+
expect(scan.stepCount).toBe(3);
|
|
68
|
+
expect(scan.reason).toBe("length");
|
|
69
|
+
// sessionID carries forward from the last event that had one.
|
|
70
|
+
expect(scan.sessionId).toBe("sess-1");
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("does not match the underscore spelling step_finish", () => {
|
|
74
|
+
const stdout = ndjson([{ type: "step_finish", part: { reason: "stop", sessionID: "sess-1" } }]);
|
|
75
|
+
const scan = scanStepFinish(stdout);
|
|
76
|
+
expect(scan.stepCount).toBe(0);
|
|
77
|
+
expect(scan.sessionId).toBeUndefined();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("stepCount is the positive-evidence gate: zero means no session id should ever be attached", () => {
|
|
81
|
+
// No step-finish at all — e.g. the process died before any turn
|
|
82
|
+
// completed. A caller must not attach `sessionId` in this case even if
|
|
83
|
+
// one happened to be present on a non-step-finish event.
|
|
84
|
+
const stdout = ndjson([{ type: "message", part: { sessionID: "sess-ghost" } }]);
|
|
85
|
+
const scan = scanStepFinish(stdout);
|
|
86
|
+
expect(scan.stepCount).toBe(0);
|
|
87
|
+
expect(scan.sessionId).toBeUndefined();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
describe("readIncrementally", () => {
|
|
92
|
+
test("returns the full text unchanged, equivalent to reading the stream whole", async () => {
|
|
93
|
+
const text = "line one\nline two\nline three\n";
|
|
94
|
+
const full = await readIncrementally(streamOf([text]), () => {});
|
|
95
|
+
expect(full).toBe(text);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("calls onLine once per line, in order, as they arrive — not all at once at the end", async () => {
|
|
99
|
+
const seen: string[] = [];
|
|
100
|
+
const full = await readIncrementally(
|
|
101
|
+
streamOf(["line one\nli", "ne two\n", "line three\n"]),
|
|
102
|
+
(line) => seen.push(line),
|
|
103
|
+
);
|
|
104
|
+
expect(seen).toEqual(["line one", "line two", "line three"]);
|
|
105
|
+
expect(full).toBe("line one\nline two\nline three\n");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("flushes an unterminated trailing line once the stream ends", async () => {
|
|
109
|
+
const seen: string[] = [];
|
|
110
|
+
const full = await readIncrementally(streamOf(["line one\nno newline here"]), (line) =>
|
|
111
|
+
seen.push(line),
|
|
112
|
+
);
|
|
113
|
+
expect(seen).toEqual(["line one", "no newline here"]);
|
|
114
|
+
expect(full).toBe("line one\nno newline here");
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("an empty stream produces no lines and empty text", async () => {
|
|
118
|
+
const seen: string[] = [];
|
|
119
|
+
const full = await readIncrementally(streamOf([]), (line) => seen.push(line));
|
|
120
|
+
expect(seen).toEqual([]);
|
|
121
|
+
expect(full).toBe("");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("decodes a multi-byte UTF-8 character split across a chunk boundary", async () => {
|
|
125
|
+
// "café\n" — "é" is 2 bytes (0xC3 0xA9); split the stream mid-character.
|
|
126
|
+
const text = "café\n";
|
|
127
|
+
const bytes = new TextEncoder().encode(text);
|
|
128
|
+
const splitAt = bytes.length - 2; // inside "é"'s 2-byte sequence
|
|
129
|
+
const seen: string[] = [];
|
|
130
|
+
const full = await readIncrementally(streamOfBytesSplitAt(text, splitAt), (line) =>
|
|
131
|
+
seen.push(line),
|
|
132
|
+
);
|
|
133
|
+
expect(full).toBe(text);
|
|
134
|
+
expect(seen).toEqual(["café"]);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
AgentFailure,
|
|
6
|
+
type AgentProgress,
|
|
7
|
+
type AgentRunner,
|
|
8
|
+
type AgentStateDef,
|
|
9
|
+
type DispatchInfo,
|
|
10
|
+
type NodeResult,
|
|
11
|
+
} from "../../core/index.ts";
|
|
12
|
+
import { handoffContractText, handoffPath, nudgeMessage, readHandoff } from "./handoff.ts";
|
|
13
|
+
|
|
14
|
+
// Mirrors darkf-engine's own DEFAULT_TIMEOUT_MS (run.ts), same reason
|
|
15
|
+
// claude-code.ts does: kill the subprocess in step with the engine's own
|
|
16
|
+
// timeout instead of leaving it running past the point the engine moved on.
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
function buildPrompt(
|
|
20
|
+
def: AgentStateDef,
|
|
21
|
+
handoff: NodeResult,
|
|
22
|
+
info: { validEvents: string[]; hasFallback: boolean },
|
|
23
|
+
path: string,
|
|
24
|
+
): string {
|
|
25
|
+
const parts = [def.prompt, `Input from the previous step:\n${JSON.stringify(handoff)}`];
|
|
26
|
+
|
|
27
|
+
if (info.validEvents.length > 0) {
|
|
28
|
+
const fallbackNote = info.hasFallback ? ` If none apply, you may omit "event" instead.` : "";
|
|
29
|
+
parts.push(
|
|
30
|
+
`Your "event" must be exactly one of: ${info.validEvents.join(", ")}.${fallbackNote}`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
parts.push(handoffContractText(path));
|
|
35
|
+
return parts.join("\n\n");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface StepFinishScan {
|
|
39
|
+
reason?: string;
|
|
40
|
+
sessionId?: string;
|
|
41
|
+
stepCount: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// opencode's `--format json` is NDJSON (one event object per line). The
|
|
45
|
+
// step-finish event carries `part.reason` — the terminal reason for the
|
|
46
|
+
// turn: "stop" (clean), "tool-calls" (ended between tool calls), "length"
|
|
47
|
+
// (output budget exhausted). Unattended runs 2026-10-09: THREE crash classes
|
|
48
|
+
// (silent resume hang, finish=length authoring abort, finish=tool-calls
|
|
49
|
+
// mid-turn death) all surfaced as `exit 0` + missing handoff → a bare
|
|
50
|
+
// ENOENT minutes after the real failure. Capture the reason and make a
|
|
51
|
+
// missing handoff fail loudly with it, so retries and RCA start from facts.
|
|
52
|
+
// NB: the type discriminator is hyphenated ("step-finish"), confirmed against
|
|
53
|
+
// both @opencode-ai/sdk's generated types and strings pulled from the
|
|
54
|
+
// installed opencode binary — matching on "step_finish" (underscore) here
|
|
55
|
+
// silently never matched, so this capture never actually fired.
|
|
56
|
+
//
|
|
57
|
+
// Extended (docs/specs/session-nudge/spec.md) to also pull `part.sessionID`
|
|
58
|
+
// and a count of step-finish events seen, in the same single pass:
|
|
59
|
+
// `stepCount` is the positive-evidence gate for ever reporting a session id
|
|
60
|
+
// at all — this is the resumability fix for the session that hung 15
|
|
61
|
+
// minutes on zero persisted messages (2026-10-08):
|
|
62
|
+
// 2026-10-08): the hang's root cause was resuming a session with no
|
|
63
|
+
// evidence it had done anything, not resuming as such.
|
|
64
|
+
export function scanStepFinish(stdout: string): StepFinishScan {
|
|
65
|
+
let reason: string | undefined;
|
|
66
|
+
let sessionId: string | undefined;
|
|
67
|
+
let stepCount = 0;
|
|
68
|
+
for (const line of stdout.split("\n")) {
|
|
69
|
+
if (!line.trim()) continue;
|
|
70
|
+
try {
|
|
71
|
+
const event = JSON.parse(line) as {
|
|
72
|
+
type?: string;
|
|
73
|
+
part?: { reason?: string; sessionID?: string };
|
|
74
|
+
};
|
|
75
|
+
if (event.type === "step-finish") {
|
|
76
|
+
stepCount++;
|
|
77
|
+
if (event.part?.reason) reason = event.part.reason;
|
|
78
|
+
if (event.part?.sessionID) sessionId = event.part.sessionID;
|
|
79
|
+
}
|
|
80
|
+
} catch {
|
|
81
|
+
// ignore: not every line is guaranteed parseable
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { reason, sessionId, stepCount };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Agent-liveness (docs/specs/agent-liveness/spec.md): a stalled LLM backend
|
|
88
|
+
// still produces a healthy engine heartbeat, because the engine only knows
|
|
89
|
+
// the process is alive, not whether the agent is making progress. Reading
|
|
90
|
+
// stdout incrementally (rather than once, at exit, as `scanStepFinish`'s
|
|
91
|
+
// caller used to) gives a real per-event liveness signal to fold into the
|
|
92
|
+
// heartbeat. No polyfill: Bun's stream primitives are enough for a line
|
|
93
|
+
// splitter this small.
|
|
94
|
+
const PROGRESS_THROTTLE_MS = 30_000;
|
|
95
|
+
|
|
96
|
+
/** Reads `stream` to completion, decoding incrementally and calling `onLine`
|
|
97
|
+
* for each newline-delimited line as it arrives (unterminated trailing
|
|
98
|
+
* content, if any, is flushed as a final line). Returns the full decoded
|
|
99
|
+
* text — the same value `await new Response(stream).text()` would have
|
|
100
|
+
* produced — so existing full-text parsing (`scanStepFinish`) keeps
|
|
101
|
+
* working unchanged. */
|
|
102
|
+
export async function readIncrementally(
|
|
103
|
+
stream: ReadableStream<Uint8Array>,
|
|
104
|
+
onLine: (line: string) => void,
|
|
105
|
+
): Promise<string> {
|
|
106
|
+
const reader = stream.getReader();
|
|
107
|
+
const decoder = new TextDecoder();
|
|
108
|
+
let full = "";
|
|
109
|
+
let buffered = "";
|
|
110
|
+
for (;;) {
|
|
111
|
+
const { done, value } = await reader.read();
|
|
112
|
+
if (done) break;
|
|
113
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
114
|
+
full += chunk;
|
|
115
|
+
buffered += chunk;
|
|
116
|
+
for (;;) {
|
|
117
|
+
const newlineAt = buffered.indexOf("\n");
|
|
118
|
+
if (newlineAt === -1) break;
|
|
119
|
+
onLine(buffered.slice(0, newlineAt));
|
|
120
|
+
buffered = buffered.slice(newlineAt + 1);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const tail = decoder.decode();
|
|
124
|
+
full += tail;
|
|
125
|
+
buffered += tail;
|
|
126
|
+
if (buffered.length > 0) onLine(buffered);
|
|
127
|
+
return full;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Retry-with-feedback (P0): the engine replays the identical prompt on
|
|
131
|
+
// retry — attempt 2 had no idea why attempt 1 failed. Record this
|
|
132
|
+
// dispatch's failure reason; if the same dispatch key runs again, the
|
|
133
|
+
// retry's prompt opens with the reason so it can correct course (e.g.
|
|
134
|
+
// "handoff not written", "handoff unparseable", exit stderr tail).
|
|
135
|
+
// Unaffected by same-session nudging (docs/specs/session-nudge/spec.md):
|
|
136
|
+
// this cache covers the fresh-session case, nudging covers the
|
|
137
|
+
// same-session case, and the two never fire on the same attempt.
|
|
138
|
+
const lastFailures = new Map<string, string>();
|
|
139
|
+
|
|
140
|
+
// Run-context digest (P1): the planning phase may publish a digest at
|
|
141
|
+
// .darkf/run/<runId>/context.md (the consumer repo's next_task builds it).
|
|
142
|
+
// Fresh-session-per-dispatch means every agent re-reads prd/design via tool
|
|
143
|
+
// calls (1–3 min each dispatch); a pre-extracted digest appended to the
|
|
144
|
+
// prompt replaces most of those round-trips. Absent file → empty string.
|
|
145
|
+
function contextBlock(rootDir: string, runId: string): string {
|
|
146
|
+
const path = join(rootDir, ".darkf", "run", runId, "context.md");
|
|
147
|
+
if (!existsSync(path)) return "";
|
|
148
|
+
try {
|
|
149
|
+
return readFileSync(path, "utf8");
|
|
150
|
+
} catch {
|
|
151
|
+
return "";
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const opencodeRunner: AgentRunner = {
|
|
156
|
+
kind: "opencode",
|
|
157
|
+
async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
|
|
158
|
+
const path = handoffPath(info.rootDir, info.runId, info.step, id);
|
|
159
|
+
await mkdir(dirname(path), { recursive: true });
|
|
160
|
+
|
|
161
|
+
const agentConfig = def.agent ?? {};
|
|
162
|
+
// No default model: silent-model-fallback (run-resilience fog ticket)
|
|
163
|
+
// moved silent → warn over time; shipping publicly finishes the arc.
|
|
164
|
+
// The workflow's pins are the contract — their absence is a crash.
|
|
165
|
+
const model = agentConfig.model as string | undefined;
|
|
166
|
+
if (!model) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`agent state "${id}" has no model pin — pin agent: { model } in the workflow.`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
// Opt-in per agent state: agent: { auto: true } passes opencode's --auto,
|
|
172
|
+
// which approves every ask-level permission for the dispatch (explicit
|
|
173
|
+
// deny rules still hold). Deliberately NOT a runner default — an
|
|
174
|
+
// unattended run (2026-10-13) crashed twice on `rm -rf *` asks that
|
|
175
|
+
// headless mode auto-rejects (finish=tool-calls, handoff not written),
|
|
176
|
+
// but blanket --auto would also silently approve force-push asks in
|
|
177
|
+
// unattended runs. Each workflow chooses.
|
|
178
|
+
const auto = agentConfig.auto === true;
|
|
179
|
+
|
|
180
|
+
const dispatchKey = `${info.runId}:${info.step}:${id}`;
|
|
181
|
+
|
|
182
|
+
// Same-session nudge (docs/specs/session-nudge/spec.md): when the
|
|
183
|
+
// previous attempt failed in a repairable way and we have its session
|
|
184
|
+
// id, send a short corrective message into that session instead of a
|
|
185
|
+
// fresh prompt. `-s` resume is scoped strictly to this case — see the
|
|
186
|
+
// "No -s outside a nudge" note below.
|
|
187
|
+
const nudge = nudgeMessage(info, path);
|
|
188
|
+
|
|
189
|
+
let prompt: string;
|
|
190
|
+
if (nudge) {
|
|
191
|
+
prompt = nudge;
|
|
192
|
+
} else {
|
|
193
|
+
const promptParts: string[] = [];
|
|
194
|
+
|
|
195
|
+
const feedback = lastFailures.get(dispatchKey);
|
|
196
|
+
if (feedback) {
|
|
197
|
+
promptParts.push(
|
|
198
|
+
`Your previous attempt at this step failed: ${feedback}. Avoid that failure; if your output contract was the problem, follow it exactly.`,
|
|
199
|
+
);
|
|
200
|
+
lastFailures.delete(dispatchKey);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const digest = contextBlock(info.rootDir, info.runId);
|
|
204
|
+
if (digest) {
|
|
205
|
+
promptParts.push(
|
|
206
|
+
`Run context digest (pre-extracted from the spec documents — use it to orient; consult the full docs only for depth):\n\n${digest}`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
promptParts.push(buildPrompt(def, handoff, info, path));
|
|
211
|
+
prompt = promptParts.join("\n\n");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// --auto is opt-in per agent state (see `auto` above): the global
|
|
215
|
+
// ~/.config/opencode/opencode.json policy ("*": "allow", with
|
|
216
|
+
// rm -rf/force-push asking, "question": "deny") is normally enough for
|
|
217
|
+
// headless runs, but any ask a workflow's agents can plausibly hit
|
|
218
|
+
// (e.g. scratch-dir `rm -rf`) needs --auto or a narrower config allow.
|
|
219
|
+
// Resolve once: spawn can miss PATH lookups in daemonized workers.
|
|
220
|
+
//
|
|
221
|
+
// No -s outside a nudge: an unattended run (2026-10-08) — the
|
|
222
|
+
// task_plan dispatch resumed req_gate's session via `-s` and hung 15
|
|
223
|
+
// minutes with ZERO messages persisted (opencode.db: session's last row
|
|
224
|
+
// predates the dispatch), then exited 0 without writing the handoff →
|
|
225
|
+
// terminal runner crash. `scanStepFinish`'s `stepCount` guard (above) is
|
|
226
|
+
// what makes `-s` safe again — the hang's root cause was resuming a
|
|
227
|
+
// session with no evidence it had done anything, not resuming as such —
|
|
228
|
+
// but it's deliberately only ever used for the one case this spec
|
|
229
|
+
// scoped it to (a nudge, immediately after a nudgeable failure in the
|
|
230
|
+
// same outer attempt). A fresh or exhausted-nudge dispatch always
|
|
231
|
+
// starts a brand-new session, exactly as today, even when
|
|
232
|
+
// `info.agentSessionId` happens to be set.
|
|
233
|
+
const bin = Bun.which("opencode") ?? "opencode";
|
|
234
|
+
const args = [
|
|
235
|
+
bin,
|
|
236
|
+
"run",
|
|
237
|
+
...(nudge ? ["-s", info.agentSessionId!] : []),
|
|
238
|
+
...(auto ? ["--auto"] : []),
|
|
239
|
+
"-m",
|
|
240
|
+
model,
|
|
241
|
+
"--format",
|
|
242
|
+
"json",
|
|
243
|
+
];
|
|
244
|
+
args.push(prompt);
|
|
245
|
+
|
|
246
|
+
// No --dir: verified live that opencode resolves relative paths against
|
|
247
|
+
// the spawned process's actual OS cwd when --dir is omitted — Bun.spawn's
|
|
248
|
+
// own `cwd` option (same mechanism claude-code.ts already uses) is
|
|
249
|
+
// sufficient, no extra flag needed.
|
|
250
|
+
const proc = Bun.spawn(args, { cwd: info.rootDir, stdout: "pipe", stderr: "pipe" });
|
|
251
|
+
const timeoutMs = def.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
252
|
+
const killTimer = setTimeout(() => proc.kill(), timeoutMs);
|
|
253
|
+
|
|
254
|
+
let stdout = "";
|
|
255
|
+
let exitCode: number;
|
|
256
|
+
let stepCount = 0;
|
|
257
|
+
let lastEventAt = Date.now();
|
|
258
|
+
let lastEvent = "";
|
|
259
|
+
let lastProgressAt = 0;
|
|
260
|
+
const onLine = (line: string) => {
|
|
261
|
+
if (!line.trim()) return;
|
|
262
|
+
lastEventAt = Date.now();
|
|
263
|
+
try {
|
|
264
|
+
const event = JSON.parse(line) as { type?: string };
|
|
265
|
+
if (event.type) lastEvent = event.type;
|
|
266
|
+
if (event.type === "step-finish") stepCount++;
|
|
267
|
+
} catch {
|
|
268
|
+
// ignore: not every line is guaranteed parseable (same tolerance
|
|
269
|
+
// scanStepFinish's final pass already has)
|
|
270
|
+
}
|
|
271
|
+
if (onProgress && lastEventAt - lastProgressAt >= PROGRESS_THROTTLE_MS) {
|
|
272
|
+
lastProgressAt = lastEventAt;
|
|
273
|
+
onProgress({ at: lastEventAt, stepCount, lastEvent });
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
try {
|
|
277
|
+
stdout = await readIncrementally(proc.stdout, onLine);
|
|
278
|
+
exitCode = await proc.exited;
|
|
279
|
+
} finally {
|
|
280
|
+
clearTimeout(killTimer);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (exitCode !== 0) {
|
|
284
|
+
const stderr = await new Response(proc.stderr).text();
|
|
285
|
+
const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
|
|
286
|
+
lastFailures.set(dispatchKey, reason);
|
|
287
|
+
const scan = scanStepFinish(stdout);
|
|
288
|
+
throw new AgentFailure(reason, {
|
|
289
|
+
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
290
|
+
crashReason: { kind: "runner-error", error: reason },
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// agentSessionId is only ever attached — on the returned NodeResult
|
|
295
|
+
// below or on a thrown AgentFailure above — when `stepCount > 0`;
|
|
296
|
+
// absent that evidence, the engine runs the next attempt fresh exactly
|
|
297
|
+
// as it does for a runner that never resumes.
|
|
298
|
+
if (!existsSync(path)) {
|
|
299
|
+
const scan = scanStepFinish(stdout);
|
|
300
|
+
const reason = `handoff not written (opencode finish=${scan.reason ?? "unknown"})`;
|
|
301
|
+
lastFailures.set(dispatchKey, reason);
|
|
302
|
+
throw new AgentFailure(reason, {
|
|
303
|
+
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
304
|
+
crashReason: { kind: "handoff-missing" },
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
try {
|
|
308
|
+
const raw = await readHandoff(path);
|
|
309
|
+
lastFailures.delete(dispatchKey);
|
|
310
|
+
const scan = scanStepFinish(stdout);
|
|
311
|
+
if (scan.stepCount > 0 && raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
312
|
+
const result = raw as Record<string, unknown>;
|
|
313
|
+
if (result.agentSessionId === undefined) result.agentSessionId = scan.sessionId;
|
|
314
|
+
}
|
|
315
|
+
return raw as NodeResult;
|
|
316
|
+
} catch (e) {
|
|
317
|
+
const parseError = e instanceof Error ? e.message : String(e);
|
|
318
|
+
const reason = `handoff unparseable: ${parseError}`;
|
|
319
|
+
lastFailures.set(dispatchKey, reason);
|
|
320
|
+
const scan = scanStepFinish(stdout);
|
|
321
|
+
throw new AgentFailure(reason, {
|
|
322
|
+
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
323
|
+
crashReason: { kind: "handoff-unparseable", parseError },
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
};
|