@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,359 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import {
|
|
4
|
+
AgentFailure,
|
|
5
|
+
type AgentProgress,
|
|
6
|
+
type AgentRunner,
|
|
7
|
+
buildRegistry,
|
|
8
|
+
type CrashReason,
|
|
9
|
+
type DispatchInfo,
|
|
10
|
+
DONE,
|
|
11
|
+
DuplicateStateIdError,
|
|
12
|
+
enter,
|
|
13
|
+
FAILED,
|
|
14
|
+
isComposite,
|
|
15
|
+
isNodeResult,
|
|
16
|
+
type NodeEvent,
|
|
17
|
+
type NodeResult,
|
|
18
|
+
type NodeStatus,
|
|
19
|
+
type RegistryEntry,
|
|
20
|
+
type RunResult,
|
|
21
|
+
resolveTarget,
|
|
22
|
+
type ScriptRunner,
|
|
23
|
+
type StepTrace,
|
|
24
|
+
validateWorkflow,
|
|
25
|
+
type WorkflowDef,
|
|
26
|
+
} from "../core/index.ts";
|
|
27
|
+
import { createJsonlEventLogger } from "./eventLog.ts";
|
|
28
|
+
|
|
29
|
+
const DEFAULT_HEARTBEAT_MS = 30_000;
|
|
30
|
+
const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000; // 1h — high default ceiling, not a tuning knob
|
|
31
|
+
const DEFAULT_MAX_STEPS = 1000;
|
|
32
|
+
// Bounded in-session repair attempts per outer attempt (see
|
|
33
|
+
// docs/specs/session-nudge/spec.md) — not a `def.retries`-style tuning
|
|
34
|
+
// knob, deliberately fixed.
|
|
35
|
+
const NUDGE_LIMIT = 3;
|
|
36
|
+
const NUDGEABLE_KINDS = new Set<CrashReason["kind"]>([
|
|
37
|
+
"handoff-missing",
|
|
38
|
+
"handoff-unparseable",
|
|
39
|
+
"no-transition",
|
|
40
|
+
]);
|
|
41
|
+
function isNudgeable(reason: CrashReason): boolean {
|
|
42
|
+
return NUDGEABLE_KINDS.has(reason.kind);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
class TimeoutError extends Error {}
|
|
46
|
+
|
|
47
|
+
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const timer = setTimeout(
|
|
50
|
+
() => reject(new TimeoutError(`timed out after ${timeoutMs}ms`)),
|
|
51
|
+
timeoutMs,
|
|
52
|
+
);
|
|
53
|
+
promise.then(
|
|
54
|
+
(value) => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
resolve(value);
|
|
57
|
+
},
|
|
58
|
+
(err) => {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
reject(err);
|
|
61
|
+
},
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const defaultScriptRunner: ScriptRunner = {
|
|
67
|
+
async run(_id, def, handoff, baseDir, info) {
|
|
68
|
+
const url = pathToFileURL(`${baseDir}/${def.file}`).href;
|
|
69
|
+
const mod = await import(url);
|
|
70
|
+
// Scripts get the DispatchInfo too — rootDir lets a script act on the
|
|
71
|
+
// target repo (spawn builds, read files) without hardcoding its location.
|
|
72
|
+
const fn = mod.default as (
|
|
73
|
+
handoff: NodeResult,
|
|
74
|
+
info: DispatchInfo,
|
|
75
|
+
) => NodeResult | Promise<NodeResult>;
|
|
76
|
+
return await fn(handoff, info);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export interface RunOptions {
|
|
81
|
+
workflow: WorkflowDef;
|
|
82
|
+
/** Seed handed to the first node's dispatch, in place of a predecessor's result. Same shape as every other handoff — no special-casing. Default `{}`. */
|
|
83
|
+
input?: NodeResult;
|
|
84
|
+
agentRunner?: AgentRunner;
|
|
85
|
+
scriptRunner?: ScriptRunner;
|
|
86
|
+
/** Live-runtime heartbeat cadence for open dispatches (default 30s, 0 disables). */
|
|
87
|
+
heartbeatMs?: number;
|
|
88
|
+
baseDir?: string;
|
|
89
|
+
maxSteps?: number;
|
|
90
|
+
/** Fires on every transition of every node's execution machine, live, as it happens. */
|
|
91
|
+
onEvent?: (event: NodeEvent) => void;
|
|
92
|
+
/** Root for run artifacts. Default: cwd. Every run always journals to `<rootDir>/.darkf/run/<runId>/journal.jsonl` — not optional. */
|
|
93
|
+
rootDir?: string;
|
|
94
|
+
/** Run identifier. A UUID when omitted. Honored by callers that must key external state (e.g. `darkf-cli`'s registry entry) to the run's own journal directory. */
|
|
95
|
+
runId?: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function run(opts: RunOptions): Promise<RunResult> {
|
|
99
|
+
const runId = opts.runId ?? crypto.randomUUID();
|
|
100
|
+
const trace: StepTrace[] = [];
|
|
101
|
+
let handoff: NodeResult = opts.input ?? {};
|
|
102
|
+
const maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
103
|
+
const heartbeatMs = opts.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
104
|
+
const scriptRunner = opts.scriptRunner ?? defaultScriptRunner;
|
|
105
|
+
const baseDir = opts.baseDir ?? process.cwd();
|
|
106
|
+
const rootDir = opts.rootDir ?? process.cwd();
|
|
107
|
+
|
|
108
|
+
const journalPath = join(rootDir, ".darkf", "run", runId, "journal.jsonl");
|
|
109
|
+
const jsonlLogger = createJsonlEventLogger(journalPath);
|
|
110
|
+
|
|
111
|
+
function emit(status: NodeStatus, state: string, scopePath: string[]): void {
|
|
112
|
+
const event: NodeEvent = { runId, state, scopePath, status, timestamp: Date.now() };
|
|
113
|
+
jsonlLogger(event);
|
|
114
|
+
opts.onEvent?.(event);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function crashed(
|
|
118
|
+
reason: CrashReason,
|
|
119
|
+
attempt: number,
|
|
120
|
+
state: string,
|
|
121
|
+
scopePath: string[],
|
|
122
|
+
): RunResult {
|
|
123
|
+
const status: NodeStatus = { phase: "crashed", reason, attempt };
|
|
124
|
+
emit(status, state, scopePath);
|
|
125
|
+
return { runId, trace, node: status };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Run begin marker: the run machine's own first transition. Emitted before
|
|
129
|
+
// buildRegistry (not merely before the dispatch loop) so it is
|
|
130
|
+
// journal.jsonl's first line even if the registry build crashes and
|
|
131
|
+
// returns before the loop. `handoff` here is the run's seed
|
|
132
|
+
// (`opts.input ?? {}`), unchanged since it was set above.
|
|
133
|
+
emit({ phase: "succeeded", result: handoff }, DONE, []);
|
|
134
|
+
|
|
135
|
+
let registry: Map<string, RegistryEntry>;
|
|
136
|
+
try {
|
|
137
|
+
registry = buildRegistry(opts.workflow);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (err instanceof DuplicateStateIdError) {
|
|
140
|
+
return crashed({ kind: "duplicate-id", id: err.id }, 0, err.id, []);
|
|
141
|
+
}
|
|
142
|
+
throw err;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const validationErrors = validateWorkflow(registry, opts.workflow.initial);
|
|
146
|
+
if (validationErrors.length > 0) {
|
|
147
|
+
return crashed(
|
|
148
|
+
{ kind: "invalid-workflow", errors: validationErrors },
|
|
149
|
+
0,
|
|
150
|
+
opts.workflow.initial,
|
|
151
|
+
[],
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let current = enter(registry, opts.workflow.initial);
|
|
156
|
+
let steps = 0;
|
|
157
|
+
const cycleCounters = new Map<string, number>();
|
|
158
|
+
// The immediately preceding dispatch's scopePath — lets the cycle-count
|
|
159
|
+
// loop below tell "still inside the same pass through this composite"
|
|
160
|
+
// apart from "just entered it again" (a composite id present here keeps
|
|
161
|
+
// accumulating; one absent here is a fresh entry and resets to 0). Each
|
|
162
|
+
// composite id's freshness is independent of its ancestors'/descendants'
|
|
163
|
+
// — diving into a nested composite for the first time doesn't reset an
|
|
164
|
+
// outer composite that's still mid-pass, and vice versa.
|
|
165
|
+
let previousScopePath: string[] = [];
|
|
166
|
+
|
|
167
|
+
for (;;) {
|
|
168
|
+
if (steps++ >= maxSteps) {
|
|
169
|
+
return crashed({ kind: "max-steps", steps, state: current }, 0, current, []);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const entry = registry.get(current);
|
|
173
|
+
if (!entry || isComposite(entry.def)) {
|
|
174
|
+
return crashed({ kind: "unresolved-target", from: current, target: current }, 0, current, []);
|
|
175
|
+
}
|
|
176
|
+
const def = entry.def;
|
|
177
|
+
const scopePath = entry.scopePath;
|
|
178
|
+
const previousScopeSet = new Set(previousScopePath);
|
|
179
|
+
|
|
180
|
+
for (let i = scopePath.length - 1; i >= 0; i--) {
|
|
181
|
+
const compositeId = scopePath[i]!;
|
|
182
|
+
const compositeDef = registry.get(compositeId)?.def;
|
|
183
|
+
const maxCycles =
|
|
184
|
+
compositeDef && isComposite(compositeDef) ? compositeDef.maxCycles : undefined;
|
|
185
|
+
if (maxCycles === undefined) continue;
|
|
186
|
+
const count = previousScopeSet.has(compositeId) ? (cycleCounters.get(compositeId) ?? 0) : 0;
|
|
187
|
+
if (count >= maxCycles) {
|
|
188
|
+
return crashed(
|
|
189
|
+
{ kind: "cycle-limit", composite: compositeId, cycles: maxCycles },
|
|
190
|
+
0,
|
|
191
|
+
current,
|
|
192
|
+
scopePath,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
cycleCounters.set(compositeId, count + 1);
|
|
196
|
+
}
|
|
197
|
+
previousScopePath = scopePath;
|
|
198
|
+
|
|
199
|
+
const maxAttempts = (def.retries ?? 0) + 1;
|
|
200
|
+
const timeoutMs = def.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
201
|
+
let result: NodeResult | undefined;
|
|
202
|
+
let target: string | undefined;
|
|
203
|
+
let reason: CrashReason | undefined;
|
|
204
|
+
let agentSessionId: string | undefined;
|
|
205
|
+
let attempt = 0;
|
|
206
|
+
|
|
207
|
+
attemptLoop: for (attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
208
|
+
// Fixed once per outer attempt: every dispatch this attempt makes — the
|
|
209
|
+
// first call and up to NUDGE_LIMIT nudges after it — spends down the
|
|
210
|
+
// SAME remaining budget, so a nudge sequence can't multiply the
|
|
211
|
+
// configured per-attempt timeout (docs/specs/session-nudge/spec.md,
|
|
212
|
+
// "Dispatch loop change").
|
|
213
|
+
const deadline = Date.now() + timeoutMs;
|
|
214
|
+
let nudgeAttempt = 0;
|
|
215
|
+
|
|
216
|
+
for (;;) {
|
|
217
|
+
const nudgeReason = nudgeAttempt > 0 ? reason?.kind : undefined;
|
|
218
|
+
const info: DispatchInfo = {
|
|
219
|
+
runId,
|
|
220
|
+
validEvents: Object.keys(def.on ?? {}),
|
|
221
|
+
hasFallback: def.next !== undefined,
|
|
222
|
+
attempt,
|
|
223
|
+
agentSessionId,
|
|
224
|
+
previousFailure: reason,
|
|
225
|
+
step: steps,
|
|
226
|
+
rootDir,
|
|
227
|
+
};
|
|
228
|
+
const startedAt = Date.now();
|
|
229
|
+
// Reset fresh per dispatch attempt (including each nudge) — a new
|
|
230
|
+
// process gets a new progress snapshot, never carried over from a
|
|
231
|
+
// previous attempt. See docs/specs/agent-liveness/spec.md.
|
|
232
|
+
let latestProgress: AgentProgress | undefined;
|
|
233
|
+
const onProgress = (p: AgentProgress) => {
|
|
234
|
+
latestProgress = p;
|
|
235
|
+
};
|
|
236
|
+
const runningStatus = (lastHeartbeat: number): NodeStatus => ({
|
|
237
|
+
phase: "running",
|
|
238
|
+
attempt,
|
|
239
|
+
startedAt,
|
|
240
|
+
lastHeartbeat,
|
|
241
|
+
agentSessionId,
|
|
242
|
+
...(latestProgress
|
|
243
|
+
? {
|
|
244
|
+
agentStepCount: latestProgress.stepCount,
|
|
245
|
+
agentIdleMs: lastHeartbeat - latestProgress.at,
|
|
246
|
+
}
|
|
247
|
+
: {}),
|
|
248
|
+
...(nudgeAttempt > 0 ? { nudgeAttempt, nudgeReason } : {}),
|
|
249
|
+
});
|
|
250
|
+
emit(runningStatus(startedAt), current, scopePath);
|
|
251
|
+
// Live-runtime heartbeats: journal a refreshed `running` status while the
|
|
252
|
+
// dispatch is open, so status/monitor can advance runtime and prove
|
|
253
|
+
// liveness (spec: darkf-cli/docs/specs/live-runtime). unref'd — a pending
|
|
254
|
+
// timer must never keep the process alive past the run's own exit.
|
|
255
|
+
const heartbeat =
|
|
256
|
+
heartbeatMs > 0
|
|
257
|
+
? setInterval(() => emit(runningStatus(Date.now()), current, scopePath), heartbeatMs)
|
|
258
|
+
: undefined;
|
|
259
|
+
heartbeat?.unref?.();
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
const dispatch =
|
|
263
|
+
def.type === "agent"
|
|
264
|
+
? requireAgentRunner(opts.agentRunner).run(current, def, handoff, info, onProgress)
|
|
265
|
+
: scriptRunner.run(current, def, handoff, baseDir, info);
|
|
266
|
+
const raw = await withTimeout(dispatch, Math.max(0, deadline - Date.now()));
|
|
267
|
+
heartbeat && clearInterval(heartbeat);
|
|
268
|
+
|
|
269
|
+
if (!isNodeResult(raw)) {
|
|
270
|
+
reason = { kind: "malformed-result" };
|
|
271
|
+
continue attemptLoop;
|
|
272
|
+
}
|
|
273
|
+
agentSessionId = raw.agentSessionId ?? agentSessionId;
|
|
274
|
+
const validationError = def.validate?.(raw, handoff);
|
|
275
|
+
if (validationError !== undefined) {
|
|
276
|
+
reason = { kind: "validation-failed", message: validationError };
|
|
277
|
+
continue attemptLoop;
|
|
278
|
+
}
|
|
279
|
+
const resolved = resolveTarget(def, raw.event);
|
|
280
|
+
if (resolved === undefined) {
|
|
281
|
+
reason = { kind: "no-transition", state: current, event: raw.event };
|
|
282
|
+
if (agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
|
|
283
|
+
nudgeAttempt++;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
continue attemptLoop;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
result = raw;
|
|
290
|
+
target = resolved;
|
|
291
|
+
reason = undefined;
|
|
292
|
+
break attemptLoop;
|
|
293
|
+
} catch (err) {
|
|
294
|
+
heartbeat && clearInterval(heartbeat);
|
|
295
|
+
if (err instanceof TimeoutError) {
|
|
296
|
+
reason = { kind: "timeout", elapsedMs: timeoutMs };
|
|
297
|
+
continue attemptLoop;
|
|
298
|
+
}
|
|
299
|
+
if (err instanceof AgentFailure) {
|
|
300
|
+
agentSessionId = err.agentSessionId ?? agentSessionId;
|
|
301
|
+
reason = err.crashReason ?? { kind: "runner-error", error: err.message };
|
|
302
|
+
} else {
|
|
303
|
+
reason = {
|
|
304
|
+
kind: "runner-error",
|
|
305
|
+
error: err instanceof Error ? err.message : String(err),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
if (isNudgeable(reason) && agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
|
|
309
|
+
nudgeAttempt++;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
continue attemptLoop;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (!result) {
|
|
318
|
+
return crashed(reason!, attempt - 1, current, scopePath);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
emit({ phase: "succeeded", result }, current, scopePath);
|
|
322
|
+
trace.push({ state: current, scopePath, result, timestamp: Date.now() });
|
|
323
|
+
handoff = result;
|
|
324
|
+
|
|
325
|
+
// `target` is always set alongside `result` in the success branch above.
|
|
326
|
+
const nextTarget = target!;
|
|
327
|
+
if (nextTarget === DONE) {
|
|
328
|
+
// Run end marker: the run machine's terminal transition — the last
|
|
329
|
+
// journal line on success. A crashed run never reaches here, so it has
|
|
330
|
+
// no end marker; the crashing leaf's own `crashed` emit is its last.
|
|
331
|
+
emit({ phase: "succeeded", result }, DONE, []);
|
|
332
|
+
return { runId, trace, node: { phase: "succeeded", result } };
|
|
333
|
+
}
|
|
334
|
+
// Both sentinel checks must sit strictly before the unresolved-target
|
|
335
|
+
// guard below — FAILED, like DONE, has no registry entry, so checked
|
|
336
|
+
// after the guard every FAILED-routed dispatch would crash as
|
|
337
|
+
// unresolved-target instead of grading as failed.
|
|
338
|
+
if (nextTarget === FAILED) {
|
|
339
|
+
emit({ phase: "failed", result }, FAILED, []);
|
|
340
|
+
return { runId, trace, node: { phase: "failed", result } };
|
|
341
|
+
}
|
|
342
|
+
if (!registry.has(nextTarget)) {
|
|
343
|
+
return crashed(
|
|
344
|
+
{ kind: "unresolved-target", from: current, target: nextTarget },
|
|
345
|
+
attempt,
|
|
346
|
+
current,
|
|
347
|
+
scopePath,
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
current = enter(registry, nextTarget);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function requireAgentRunner(agentRunner: AgentRunner | undefined): AgentRunner {
|
|
355
|
+
if (!agentRunner) {
|
|
356
|
+
throw new Error("Workflow contains an agent node but no agentRunner was provided");
|
|
357
|
+
}
|
|
358
|
+
return agentRunner;
|
|
359
|
+
}
|
package/src/exports.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { parseClaudeUsage } from "./claude-code.ts";
|
|
3
|
+
|
|
4
|
+
describe("parseClaudeUsage", () => {
|
|
5
|
+
test("parses a full claude -p json envelope", () => {
|
|
6
|
+
const u = parseClaudeUsage(
|
|
7
|
+
JSON.stringify({
|
|
8
|
+
type: "result",
|
|
9
|
+
total_cost_usd: 0.421,
|
|
10
|
+
duration_ms: 134_000,
|
|
11
|
+
num_turns: 12,
|
|
12
|
+
session_id: "s1",
|
|
13
|
+
usage: {
|
|
14
|
+
input_tokens: 1000,
|
|
15
|
+
cache_read_input_tokens: 50_000,
|
|
16
|
+
cache_creation_input_tokens: 200,
|
|
17
|
+
output_tokens: 4_500,
|
|
18
|
+
},
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
expect(u.costUsd).toBe(0.421);
|
|
22
|
+
expect(u.durationMs).toBe(134_000);
|
|
23
|
+
expect(u.numTurns).toBe(12);
|
|
24
|
+
expect(u.inputTokens).toBe(1000);
|
|
25
|
+
expect(u.cacheReadTokens).toBe(50_000);
|
|
26
|
+
expect(u.outputTokens).toBe(4_500);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("degrades to zeros/nulls on missing fields and invalid json", () => {
|
|
30
|
+
const empty = parseClaudeUsage(JSON.stringify({}));
|
|
31
|
+
expect(empty.costUsd).toBeNull();
|
|
32
|
+
expect(empty.inputTokens).toBe(0);
|
|
33
|
+
const junk = parseClaudeUsage("not json at all");
|
|
34
|
+
expect(junk.costUsd).toBeNull();
|
|
35
|
+
expect(junk.outputTokens).toBe(0);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
AgentFailure,
|
|
5
|
+
type AgentRunner,
|
|
6
|
+
type AgentStateDef,
|
|
7
|
+
type NodeResult,
|
|
8
|
+
} from "../../core/index.ts";
|
|
9
|
+
import {
|
|
10
|
+
handoffContractText,
|
|
11
|
+
handoffPath,
|
|
12
|
+
nudgeMessage,
|
|
13
|
+
readHandoff,
|
|
14
|
+
usagePath,
|
|
15
|
+
} from "./handoff.ts";
|
|
16
|
+
|
|
17
|
+
// Mirrors darkf-engine's own DEFAULT_TIMEOUT_MS (run.ts) so this runner can
|
|
18
|
+
// kill its own subprocess in step with the engine's timeout instead of
|
|
19
|
+
// leaving it running past the point where the engine has moved on — see
|
|
20
|
+
// docs/specs/agent-handoff/spec.md's retry-overwrite race note.
|
|
21
|
+
const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
|
|
22
|
+
|
|
23
|
+
function buildPrompt(
|
|
24
|
+
def: AgentStateDef,
|
|
25
|
+
handoff: NodeResult,
|
|
26
|
+
info: { validEvents: string[]; hasFallback: boolean },
|
|
27
|
+
path: string,
|
|
28
|
+
): string {
|
|
29
|
+
const parts = [def.prompt, `Input from the previous step:\n${JSON.stringify(handoff)}`];
|
|
30
|
+
|
|
31
|
+
if (info.validEvents.length > 0) {
|
|
32
|
+
const fallbackNote = info.hasFallback ? ` If none apply, you may omit "event" instead.` : "";
|
|
33
|
+
parts.push(
|
|
34
|
+
`Your "event" must be exactly one of: ${info.validEvents.join(", ")}.${fallbackNote}`,
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
parts.push(handoffContractText(path));
|
|
39
|
+
return parts.join("\n\n");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ClaudeCodeStdout {
|
|
43
|
+
session_id?: string;
|
|
44
|
+
total_cost_usd?: number;
|
|
45
|
+
duration_ms?: number;
|
|
46
|
+
num_turns?: number;
|
|
47
|
+
usage?: {
|
|
48
|
+
input_tokens?: number;
|
|
49
|
+
cache_read_input_tokens?: number;
|
|
50
|
+
cache_creation_input_tokens?: number;
|
|
51
|
+
output_tokens?: number;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface AgentUsage {
|
|
56
|
+
costUsd: number | null;
|
|
57
|
+
durationMs: number | null;
|
|
58
|
+
numTurns: number | null;
|
|
59
|
+
inputTokens: number;
|
|
60
|
+
cacheReadTokens: number;
|
|
61
|
+
cacheCreationTokens: number;
|
|
62
|
+
outputTokens: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Parse the `claude -p --output-format json` envelope into usage telemetry.
|
|
66
|
+
* Tolerant: any missing/invalid field degrades to null/0, never throws. */
|
|
67
|
+
export function parseClaudeUsage(stdout: string): AgentUsage {
|
|
68
|
+
let parsed: ClaudeCodeStdout | undefined;
|
|
69
|
+
try {
|
|
70
|
+
parsed = JSON.parse(stdout) as ClaudeCodeStdout;
|
|
71
|
+
} catch {
|
|
72
|
+
parsed = undefined;
|
|
73
|
+
}
|
|
74
|
+
const u = parsed?.usage;
|
|
75
|
+
const n = (v: number | undefined) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
76
|
+
return {
|
|
77
|
+
costUsd: typeof parsed?.total_cost_usd === "number" ? parsed.total_cost_usd : null,
|
|
78
|
+
durationMs: typeof parsed?.duration_ms === "number" ? parsed.duration_ms : null,
|
|
79
|
+
numTurns: typeof parsed?.num_turns === "number" ? parsed.num_turns : null,
|
|
80
|
+
inputTokens: n(u?.input_tokens),
|
|
81
|
+
cacheReadTokens: n(u?.cache_read_input_tokens),
|
|
82
|
+
cacheCreationTokens: n(u?.cache_creation_input_tokens),
|
|
83
|
+
outputTokens: n(u?.output_tokens),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseAgentSessionId(stdout: string): string | undefined {
|
|
88
|
+
try {
|
|
89
|
+
return (JSON.parse(stdout) as ClaudeCodeStdout).session_id;
|
|
90
|
+
} catch {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export const claudeCodeRunner: AgentRunner = {
|
|
96
|
+
kind: "claude-code",
|
|
97
|
+
async run(id, def, handoff, info) {
|
|
98
|
+
const path = handoffPath(info.rootDir, info.runId, info.step, id);
|
|
99
|
+
await mkdir(dirname(path), { recursive: true });
|
|
100
|
+
|
|
101
|
+
const agentConfig = def.agent ?? {};
|
|
102
|
+
const permissionMode =
|
|
103
|
+
(agentConfig.permissionMode as string | undefined) ?? "bypassPermissions";
|
|
104
|
+
const model = agentConfig.model as string | undefined;
|
|
105
|
+
// Same-session nudge (docs/specs/session-nudge/spec.md): when the
|
|
106
|
+
// previous attempt failed in a repairable way and we have its session
|
|
107
|
+
// id, send a short corrective message into that session instead of
|
|
108
|
+
// replaying the full prompt. `--resume` itself is unconditional on
|
|
109
|
+
// `info.agentSessionId` either way (see below) — only the prompt text
|
|
110
|
+
// changes for a nudge.
|
|
111
|
+
const nudge = nudgeMessage(info, path);
|
|
112
|
+
const prompt = nudge ?? buildPrompt(def, handoff, info, path);
|
|
113
|
+
|
|
114
|
+
// Resolve once: spawn can miss PATH lookups in daemonized workers.
|
|
115
|
+
const bin = Bun.which("claude") ?? "claude";
|
|
116
|
+
const args = [bin, "-p", "--output-format", "json", "--permission-mode", permissionMode];
|
|
117
|
+
if (model) args.push("--model", model);
|
|
118
|
+
if (info.agentSessionId) args.push("--resume", info.agentSessionId);
|
|
119
|
+
args.push(prompt);
|
|
120
|
+
|
|
121
|
+
const proc = Bun.spawn(args, { cwd: info.rootDir, stdout: "pipe", stderr: "pipe" });
|
|
122
|
+
const timeoutMs = def.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
123
|
+
const killTimer = setTimeout(() => proc.kill(), timeoutMs);
|
|
124
|
+
|
|
125
|
+
let stdout: string;
|
|
126
|
+
let exitCode: number;
|
|
127
|
+
try {
|
|
128
|
+
stdout = await new Response(proc.stdout).text();
|
|
129
|
+
exitCode = await proc.exited;
|
|
130
|
+
} finally {
|
|
131
|
+
clearTimeout(killTimer);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (exitCode !== 0) {
|
|
135
|
+
const stderr = await new Response(proc.stderr).text();
|
|
136
|
+
const reason = `claude exited ${exitCode}: ${stderr.trim()}`;
|
|
137
|
+
// stdout is already read into memory above — a second parse against
|
|
138
|
+
// data already in hand, not new capture plumbing. There's no
|
|
139
|
+
// partial-progress signal on this path the way opencode's incremental
|
|
140
|
+
// NDJSON has one: a crash before the terminal result object prints
|
|
141
|
+
// leaves nothing parseable, and that's a plain Error, same as today.
|
|
142
|
+
const sessionId = parseAgentSessionId(stdout);
|
|
143
|
+
if (sessionId) {
|
|
144
|
+
throw new AgentFailure(reason, {
|
|
145
|
+
agentSessionId: sessionId,
|
|
146
|
+
crashReason: { kind: "runner-error", error: reason },
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
throw new Error(reason);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const usagePath_ = usagePath(info.rootDir, info.runId, info.step, id);
|
|
153
|
+
await mkdir(dirname(usagePath_), { recursive: true });
|
|
154
|
+
await Bun.write(usagePath_, JSON.stringify(parseClaudeUsage(stdout)));
|
|
155
|
+
|
|
156
|
+
const agentSessionId = parseAgentSessionId(stdout) ?? info.agentSessionId;
|
|
157
|
+
let raw: unknown;
|
|
158
|
+
try {
|
|
159
|
+
raw = await readHandoff(path);
|
|
160
|
+
} catch (e) {
|
|
161
|
+
const err = e as NodeJS.ErrnoException;
|
|
162
|
+
if (err?.code === "ENOENT") {
|
|
163
|
+
throw new AgentFailure("handoff not written", {
|
|
164
|
+
agentSessionId,
|
|
165
|
+
crashReason: { kind: "handoff-missing" },
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
const parseError = err instanceof Error ? err.message : String(err);
|
|
169
|
+
throw new AgentFailure(`handoff unparseable: ${parseError}`, {
|
|
170
|
+
agentSessionId,
|
|
171
|
+
crashReason: { kind: "handoff-unparseable", parseError },
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
175
|
+
const result = raw as Record<string, unknown>;
|
|
176
|
+
if (result.agentSessionId === undefined) result.agentSessionId = agentSessionId;
|
|
177
|
+
}
|
|
178
|
+
return raw as NodeResult;
|
|
179
|
+
},
|
|
180
|
+
};
|