@psimona/darkf 0.7.1 → 0.8.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/src/engine/run.ts CHANGED
@@ -4,11 +4,14 @@ import {
4
4
  AgentFailure,
5
5
  type AgentProgress,
6
6
  type AgentRunner,
7
+ type AgentRunnerKind,
8
+ type AgentStateDef,
7
9
  buildRegistry,
8
10
  type CrashReason,
9
11
  type DispatchInfo,
10
12
  DONE,
11
13
  DuplicateStateIdError,
14
+ effectiveAgent,
12
15
  enter,
13
16
  FAILED,
14
17
  isComposite,
@@ -93,7 +96,10 @@ export interface RunOptions {
93
96
  workflow: WorkflowDef;
94
97
  /** 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 `{}`. */
95
98
  input?: NodeResult;
99
+ /** Default runner, for agent states that name none. */
96
100
  agentRunner?: AgentRunner;
101
+ /** Runners an agent state selects by name through `AgentStateDef.runner`. */
102
+ agentRunners?: Record<string, AgentRunner>;
97
103
  scriptRunner?: ScriptRunner;
98
104
  /** Live-runtime heartbeat cadence for open dispatches (default 30s, 0 disables). */
99
105
  heartbeatMs?: number;
@@ -154,7 +160,10 @@ export async function run(opts: RunOptions): Promise<RunResult> {
154
160
  throw err;
155
161
  }
156
162
 
157
- const validationErrors = validateWorkflow(registry, opts.workflow.initial);
163
+ const validationErrors = validateWorkflow(registry, opts.workflow, {
164
+ names: Object.keys(opts.agentRunners ?? {}),
165
+ hasDefault: opts.agentRunner !== undefined,
166
+ });
158
167
  if (validationErrors.length > 0) {
159
168
  return crashed(
160
169
  { kind: "invalid-workflow", errors: validationErrors },
@@ -220,6 +229,8 @@ export async function run(opts: RunOptions): Promise<RunResult> {
220
229
  // this visit (docs/specs/_built/usage-limit-backoff/spec.md).
221
230
  let limitWaitedMs = 0;
222
231
  let limitProbes = 0;
232
+ // What each `running` status records about the harness. Fixed for the visit.
233
+ const runnerRecord = def.type === "agent" ? describeRunner(opts, def) : {};
223
234
 
224
235
  attemptLoop: for (attempt = 1; attempt <= maxAttempts; attempt++) {
225
236
  // Fixed once per outer attempt: every dispatch this attempt makes — the
@@ -264,6 +275,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
264
275
  startedAt,
265
276
  lastHeartbeat,
266
277
  agentSessionId,
278
+ ...runnerRecord,
267
279
  ...(latestProgress
268
280
  ? {
269
281
  agentStepCount: latestProgress.stepCount,
@@ -287,7 +299,14 @@ export async function run(opts: RunOptions): Promise<RunResult> {
287
299
  try {
288
300
  const dispatch =
289
301
  def.type === "agent"
290
- ? requireAgentRunner(opts.agentRunner).run(current, def, handoff, info, onProgress)
302
+ ? requireAgentRunner(opts, def).run(
303
+ current,
304
+ // A copy: the runner never writes into the workflow.
305
+ { ...def, agent: effectiveAgent(def, opts.workflow.agent) },
306
+ handoff,
307
+ info,
308
+ onProgress,
309
+ )
291
310
  : scriptRunner.run(current, def, handoff, baseDir, info);
292
311
  const raw = await withTimeout(dispatch, Math.max(0, deadline - Date.now()));
293
312
  heartbeat && clearInterval(heartbeat);
@@ -457,9 +476,33 @@ export async function run(opts: RunOptions): Promise<RunResult> {
457
476
  }
458
477
  }
459
478
 
460
- function requireAgentRunner(agentRunner: AgentRunner | undefined): AgentRunner {
461
- if (!agentRunner) {
462
- throw new Error("Workflow contains an agent node but no agentRunner was provided");
463
- }
464
- return agentRunner;
479
+ /** A named runner never falls back to the default one. */
480
+ export function selectRunner(
481
+ opts: Pick<RunOptions, "agentRunner" | "agentRunners">,
482
+ def: AgentStateDef,
483
+ ): AgentRunner | undefined {
484
+ if (def.runner === undefined) return opts.agentRunner;
485
+ const { agentRunners = {} } = opts;
486
+ return Object.hasOwn(agentRunners, def.runner) ? agentRunners[def.runner] : undefined;
487
+ }
488
+
489
+ function requireAgentRunner(opts: RunOptions, def: AgentStateDef): AgentRunner {
490
+ const runner = selectRunner(opts, def);
491
+ if (runner) return runner;
492
+ throw new Error(
493
+ def.runner === undefined
494
+ ? "Workflow contains an agent node but no agentRunner was provided"
495
+ : `Agent node names runner "${def.runner}" but agentRunners has no such entry`,
496
+ );
497
+ }
498
+
499
+ function describeRunner(
500
+ opts: RunOptions,
501
+ def: AgentStateDef,
502
+ ): { runner?: string; runnerKind?: AgentRunnerKind } {
503
+ const kind = selectRunner(opts, def)?.kind;
504
+ return {
505
+ ...(def.runner === undefined ? {} : { runner: def.runner }),
506
+ ...(kind === undefined ? {} : { runnerKind: kind }),
507
+ };
465
508
  }
@@ -1,5 +1,6 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { parseClaudeUsage } from "./claude-code.ts";
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import type { AgentStateDef } from "../../core/index.ts";
3
+ import { claudeCodeRunner, parseClaudeUsage } from "./claude-code.ts";
3
4
 
4
5
  describe("parseClaudeUsage", () => {
5
6
  test("parses a full claude -p json envelope", () => {
@@ -35,3 +36,38 @@ describe("parseClaudeUsage", () => {
35
36
  expect(junk.outputTokens).toBe(0);
36
37
  });
37
38
  });
39
+
40
+ describe("claudeCodeRunner", () => {
41
+ test("warns only about ids that are neither an alias nor a claude- id", async () => {
42
+ const known = ["sonnet", "opus[1m]", "haiku", "claude-sonnet-5-5", "claude-opus-5-5[1m]"];
43
+ const foreign = ["zai-coding-plan/glm-5.3", "sonet"];
44
+
45
+ const warnings = await claudeCodeRunner.checkModels!([...known, ...foreign], "/nonexistent");
46
+
47
+ expect(warnings.map((w) => w.model)).toEqual(foreign);
48
+ expect(warnings[0]!.message).toContain('"zai-coding-plan/glm-5.3"');
49
+ });
50
+
51
+ test.each([undefined, {}, { model: "" }, { model: 7 }])(
52
+ "rejects a dispatch with agent %p without starting the CLI",
53
+ async (agent) => {
54
+ const spawn = spyOn(Bun, "spawn");
55
+ const def: AgentStateDef = { type: "agent", prompt: "p", agent };
56
+ const info = {
57
+ runId: "r",
58
+ validEvents: [],
59
+ hasFallback: true,
60
+ attempt: 1,
61
+ step: 1,
62
+ // Never created: the rejection comes before any file or process.
63
+ rootDir: "/nonexistent",
64
+ };
65
+
66
+ await expect(claudeCodeRunner.run("N", def, {}, info)).rejects.toThrow(
67
+ 'agent state "N" has no model pin',
68
+ );
69
+ expect(spawn).not.toHaveBeenCalled();
70
+ spawn.mockRestore();
71
+ },
72
+ );
73
+ });
@@ -62,16 +62,37 @@ function parseAgentSessionId(stdout: string): string | undefined {
62
62
  }
63
63
  }
64
64
 
65
+ // Claude Code has no command that lists models, so this is a check on the id's
66
+ // shape only: an alias or a `claude-` name, optionally with the `[1m]` suffix.
67
+ // It catches another harness's id, not a misspelled version.
68
+ const CLAUDE_MODEL = /^(claude-.+|default|fable|haiku|opus|opusplan|sonnet)(\[1m\])?$/;
69
+
65
70
  export const claudeCodeRunner: AgentRunner = {
66
71
  kind: "claude-code",
72
+ async checkModels(models) {
73
+ return models
74
+ .filter((model) => !CLAUDE_MODEL.test(model))
75
+ .map((model) => ({
76
+ model,
77
+ message: `model "${model}" is neither a Claude Code alias nor a "claude-" id`,
78
+ }));
79
+ },
67
80
  async run(id, def, handoff, info) {
81
+ const agentConfig = def.agent ?? {};
82
+ // No default model, as in opencodeRunner: the CLI's own default would
83
+ // otherwise be picked silently.
84
+ const model = agentConfig.model;
85
+ if (typeof model !== "string" || model === "") {
86
+ throw new Error(
87
+ `agent state "${id}" has no model pin — pin agent: { model } in the workflow.`,
88
+ );
89
+ }
90
+
68
91
  const path = handoffPath(info.rootDir, info.runId, info.step, id);
69
92
  await mkdir(dirname(path), { recursive: true });
70
93
 
71
- const agentConfig = def.agent ?? {};
72
94
  const permissionMode =
73
95
  (agentConfig.permissionMode as string | undefined) ?? "bypassPermissions";
74
- const model = agentConfig.model as string | undefined;
75
96
  // Same-session nudge (docs/specs/_built/session-nudge/spec.md): when the
76
97
  // previous attempt failed in a repairable way and we have its session
77
98
  // id, send a short corrective message into that session instead of
@@ -84,7 +105,7 @@ export const claudeCodeRunner: AgentRunner = {
84
105
  // Resolve once: spawn can miss PATH lookups in daemonized workers.
85
106
  const bin = Bun.which("claude") ?? "claude";
86
107
  const args = [bin, "-p", "--output-format", "json", "--permission-mode", permissionMode];
87
- if (model) args.push("--model", model);
108
+ args.push("--model", model);
88
109
  if (info.agentSessionId) args.push("--resume", info.agentSessionId);
89
110
  args.push(prompt);
90
111
 
@@ -170,8 +170,38 @@ export function matchUsageLimit(stderr: string, stdout: string): string | undefi
170
170
  return undefined;
171
171
  }
172
172
 
173
+ // `opencode models` answers in about a second; this only bounds a hung one.
174
+ const MODEL_LIST_TIMEOUT_MS = 20_000;
175
+
176
+ /** The ids `opencode models` lists for `rootDir`, so project config counts. */
177
+ async function listModels(rootDir: string): Promise<Set<string>> {
178
+ const bin = Bun.which("opencode") ?? "opencode";
179
+ const proc = Bun.spawn([bin, "models"], {
180
+ cwd: rootDir,
181
+ stdout: "pipe",
182
+ stderr: "pipe",
183
+ timeout: MODEL_LIST_TIMEOUT_MS,
184
+ });
185
+ const [stdout, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
186
+ const ids = stdout
187
+ .split("\n")
188
+ .map((line) => line.trim())
189
+ .filter(Boolean);
190
+ if (exitCode !== 0 || ids.length === 0) {
191
+ throw new Error(`\`opencode models\` exited ${exitCode} with ${ids.length} models`);
192
+ }
193
+ return new Set(ids);
194
+ }
195
+
173
196
  export const opencodeRunner: AgentRunner = {
174
197
  kind: "opencode",
198
+ async checkModels(models, rootDir) {
199
+ const listed = await listModels(rootDir);
200
+ // `-m` takes provider/model#variant; the list holds provider/model.
201
+ return models
202
+ .filter((model) => !listed.has(model.split("#")[0]!))
203
+ .map((model) => ({ model, message: `model "${model}" is not in \`opencode models\`` }));
204
+ },
175
205
  async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
176
206
  const path = handoffPath(info.rootDir, info.runId, info.step, id);
177
207
  await mkdir(dirname(path), { recursive: true });
@@ -478,6 +478,30 @@ describe("foldReport", () => {
478
478
  expect(report.visits).toEqual({ Implement: 1, Verify: 1 });
479
479
  });
480
480
 
481
+ test("copies the running event's runner fields onto succeeded and crashed rows", () => {
482
+ const ran = (state: string, ts: number, fields: { runner?: string; runnerKind?: string }) => {
483
+ const event = running(state, ts);
484
+ return { ...event, status: { ...event.status, ...fields } } as NodeEvent;
485
+ };
486
+ const journal = journalText([
487
+ begin(),
488
+ ran("Plan", 100, { runner: "claude", runnerKind: "claude-code" }),
489
+ succeeded("Plan", 200),
490
+ ran("Build", 200, { runnerKind: "opencode" }),
491
+ succeeded("Build", 300),
492
+ ran("Review", 300, { runner: "custom" }),
493
+ crashed("Review", 400, { kind: "malformed-result" }),
494
+ ]);
495
+
496
+ expect(
497
+ foldReport(journal).dispatches.map((d) => [d.state, d.runner, d.runnerKind, d.durationMs]),
498
+ ).toEqual([
499
+ ["Plan", "claude", "claude-code", 100],
500
+ ["Build", undefined, "opencode", 100],
501
+ ["Review", "custom", undefined, 100],
502
+ ]);
503
+ });
504
+
481
505
  test("a FAILED-tagged end marker is its own dispatch row, not silently dropped", () => {
482
506
  const journal = journalText([
483
507
  begin(),
package/src/kit/status.ts CHANGED
@@ -197,6 +197,10 @@ export interface ReportDispatch {
197
197
  phase: "succeeded" | "failed" | "crashed";
198
198
  event?: string;
199
199
  reason?: unknown;
200
+ /** The runner name the state selected; absent for the default runner. */
201
+ runner?: string;
202
+ /** The resolved agent runner's `kind`; absent when it declares none. */
203
+ runnerKind?: string;
200
204
  }
201
205
 
202
206
  export interface ReportDigest {
@@ -215,7 +219,12 @@ export function foldReport(journalText: string): ReportDigest {
215
219
  if (events.length === 0) return digest;
216
220
 
217
221
  digest.spanMs = events.at(-1)!.timestamp - events[0]!.timestamp;
218
- const openAt = new Map<string, number>();
222
+ // The opening `running` event's timestamp and runner fields, until its
223
+ // terminal event turns them into a row.
224
+ const openAt = new Map<
225
+ string,
226
+ { startedAt: number } & Pick<ReportDispatch, "runner" | "runnerKind">
227
+ >();
219
228
  for (const e of events) {
220
229
  // DONE's begin/end markers are skipped — neither is a real node's
221
230
  // dispatch. FAILED's end marker is NOT skipped: it is `run_failure`'s
@@ -236,24 +245,32 @@ export function foldReport(journalText: string): ReportDigest {
236
245
  // a dispatch opens (first attempt or retry): count attempt-1 opens as
237
246
  // visits and start the duration clock
238
247
  if (attempt === 1) digest.visits[e.state] = (digest.visits[e.state] ?? 0) + 1;
239
- openAt.set(key, e.timestamp);
248
+ openAt.set(key, {
249
+ startedAt: e.timestamp,
250
+ ...(st.runner === undefined ? {} : { runner: st.runner }),
251
+ ...(st.runnerKind === undefined ? {} : { runnerKind: st.runnerKind }),
252
+ });
240
253
  } else if (st.phase === "succeeded") {
241
- const started = openAt.get(key);
242
- if (started === undefined) continue;
254
+ const open = openAt.get(key);
255
+ if (open === undefined) continue;
243
256
  openAt.delete(key);
257
+ const { startedAt, ...ran } = open;
244
258
  digest.dispatches.push({
259
+ ...ran,
245
260
  state: e.state,
246
- durationMs: e.timestamp - started,
261
+ durationMs: e.timestamp - startedAt,
247
262
  phase: "succeeded",
248
263
  event: st.result?.event,
249
264
  });
250
265
  } else if (st.phase === "crashed") {
251
- const started = openAt.get(key);
252
- if (started === undefined) continue;
266
+ const open = openAt.get(key);
267
+ if (open === undefined) continue;
253
268
  openAt.delete(key);
269
+ const { startedAt, ...ran } = open;
254
270
  digest.dispatches.push({
271
+ ...ran,
255
272
  state: e.state,
256
- durationMs: e.timestamp - started,
273
+ durationMs: e.timestamp - startedAt,
257
274
  phase: "crashed",
258
275
  reason: st.reason,
259
276
  });
@@ -52,6 +52,7 @@ Write your result per the handoff instructions: event "done" if it matches the s
52
52
 
53
53
  export const workflow: WorkflowDef = {
54
54
  initial: "Fix",
55
+ agent: { model: "claude-sonnet-5-5" },
55
56
  states: {
56
57
  Fix: {
57
58
  initial: "Implement",