@psimona/darkf 0.7.1 → 0.9.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.
Files changed (35) hide show
  1. package/docs/concepts/failure-modes.md +18 -5
  2. package/docs/concepts/handoff.md +8 -4
  3. package/docs/concepts/node-types.md +45 -21
  4. package/docs/guides/pick-an-agent-runner.md +143 -4
  5. package/docs/guides/plan-with-a-task-queue.md +18 -2
  6. package/docs/guides/run-detached-and-monitor.md +4 -3
  7. package/docs/guides/write-your-first-workflow.md +24 -5
  8. package/docs/reference/cli-commands.md +24 -6
  9. package/docs/reference/core-types.md +41 -6
  10. package/docs/start-here/quickstart.md +22 -2
  11. package/package.json +1 -1
  12. package/skills/darkf-usage/SKILL.md +17 -0
  13. package/skills/darkf-writing-workflows/SKILL.md +25 -18
  14. package/src/cli/detached.test.ts +92 -2
  15. package/src/cli/doctor.test.ts +224 -9
  16. package/src/cli/index.ts +83 -12
  17. package/src/cli/tarball.test.ts +8 -2
  18. package/src/core/graph.test.ts +266 -20
  19. package/src/core/graph.ts +61 -3
  20. package/src/core/types.ts +21 -0
  21. package/src/engine/run.test.ts +581 -17
  22. package/src/engine/run.ts +50 -7
  23. package/src/kit/agents/claude-code.test.ts +38 -2
  24. package/src/kit/agents/claude-code.ts +24 -3
  25. package/src/kit/agents/opencode.test.ts +89 -12
  26. package/src/kit/agents/opencode.ts +103 -8
  27. package/src/kit/status.test.ts +24 -0
  28. package/src/kit/status.ts +25 -8
  29. package/src/test/ok-output.ts +11 -0
  30. package/workflows/dev-loop/output-types.ts +43 -0
  31. package/workflows/dev-loop/scripts/begin.ts +2 -2
  32. package/workflows/dev-loop/scripts/finish.ts +2 -36
  33. package/workflows/dev-loop/workflow.ts +18 -4
  34. package/workflows/series-ordering/output-types.ts +9 -0
  35. package/workflows/series-ordering/workflow.ts +4 -0
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
 
@@ -54,7 +54,7 @@ describe("scanStepFinish", () => {
54
54
  test("ignores lines that aren't step-finish or aren't parseable JSON", () => {
55
55
  const stdout = ndjson([
56
56
  { type: "message", part: { sessionID: "sess-x" } },
57
- { type: "step-finish", part: { reason: "stop", sessionID: "sess-1" } },
57
+ { type: "step_finish", part: { reason: "stop", sessionID: "sess-1" } },
58
58
  ]);
59
59
  const scan = scanStepFinish(`not json\n${stdout}\n`);
60
60
  expect(scan.stepCount).toBe(1);
@@ -64,9 +64,9 @@ describe("scanStepFinish", () => {
64
64
 
65
65
  test("counts every step-finish event and keeps the LAST reason/sessionID seen", () => {
66
66
  const stdout = ndjson([
67
- { type: "step-finish", part: { reason: "tool-calls", sessionID: "sess-1" } },
68
- { type: "step-finish", part: { reason: "stop", sessionID: "sess-1" } },
69
- { type: "step-finish", part: { reason: "length" } }, // no sessionID on this one
67
+ { type: "step_finish", part: { reason: "tool-calls", sessionID: "sess-1" } },
68
+ { type: "step_finish", part: { reason: "stop", sessionID: "sess-1" } },
69
+ { type: "step_finish", part: { reason: "length" } }, // no sessionID on this one
70
70
  ]);
71
71
  const scan = scanStepFinish(stdout);
72
72
  expect(scan.stepCount).toBe(3);
@@ -75,11 +75,13 @@ describe("scanStepFinish", () => {
75
75
  expect(scan.sessionId).toBe("sess-1");
76
76
  });
77
77
 
78
- test("does not match the underscore spelling step_finish", () => {
79
- const stdout = ndjson([{ type: "step_finish", part: { reason: "stop", sessionID: "sess-1" } }]);
80
- const scan = scanStepFinish(stdout);
81
- expect(scan.stepCount).toBe(0);
82
- expect(scan.sessionId).toBeUndefined();
78
+ test("reads a captured opencode 2.3.0 event: outer step_finish, inner part.type step-finish", () => {
79
+ const captured =
80
+ '{"type":"step_finish","timestamp":1795852863406,"sessionID":"ses_dded41c03ffe0K2HQarugg1jY8","part":{"id":"prt_2212c07ae001VpNCu4zfPKY2pA","sessionID":"ses_dded41c03ffe0K2HQarugg1jY8","messageID":"msg_2212be8c80010pl7Mc2TCmrkp5","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":11196,"output":106,"reasoning":93,"cache":{"read":0,"write":0}}}}';
81
+ const scan = scanStepFinish(captured);
82
+ expect(scan.stepCount).toBe(1);
83
+ expect(scan.sessionId).toBe("ses_dded41c03ffe0K2HQarugg1jY8");
84
+ expect(scan.reason).toBe("tool-calls");
83
85
  });
84
86
 
85
87
  test("stepCount is the positive-evidence gate: zero means no session id should ever be attached", () => {
@@ -181,7 +183,7 @@ describe("matchUsageLimit", () => {
181
183
 
182
184
  test("an ordinary non-limit API error does not match", () => {
183
185
  expect(matchUsageLimit("opencode: API error 500: backend exploded\n", "")).toBeUndefined();
184
- expect(matchUsageLimit("", '{"type":"step-finish","part":{"reason":"stop"}}')).toBeUndefined();
186
+ expect(matchUsageLimit("", '{"type":"step_finish","part":{"reason":"stop"}}')).toBeUndefined();
185
187
  });
186
188
  });
187
189
 
@@ -250,7 +252,7 @@ describe("opencodeRunner usage-limit classification + resume", () => {
250
252
  const handoffFile = handoffPath(rootDir, RUN_ID, 1, "N");
251
253
  return [
252
254
  `printf '%s\\0' "$@" > "${argvFile}"`,
253
- `echo '{"type":"step-finish","part":{"reason":"stop","sessionID":"${sessionId}"}}'`,
255
+ `echo '{"type":"step_finish","part":{"reason":"stop","sessionID":"${sessionId}"}}'`,
254
256
  `mkdir -p "$(dirname "${handoffFile}")"`,
255
257
  `echo '{"event":"ok"}' > "${handoffFile}"`,
256
258
  ].join("\n");
@@ -260,7 +262,7 @@ describe("opencodeRunner usage-limit classification + resume", () => {
260
262
  const { rootDir } = install((_rootDir, _argvFile) =>
261
263
  [
262
264
  `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"}}'`,
265
+ `echo '{"type":"step_finish","part":{"reason":"stop","sessionID":"sess-wall"}}'`,
264
266
  `exit 3`,
265
267
  ].join("\n"),
266
268
  );
@@ -303,6 +305,81 @@ describe("opencodeRunner usage-limit classification + resume", () => {
303
305
  rmSync(rootDir, { recursive: true, force: true });
304
306
  });
305
307
 
308
+ async function failWith(script: string): Promise<AgentFailure> {
309
+ const { rootDir } = install(() => script);
310
+ let thrown: unknown;
311
+ try {
312
+ await opencodeRunner.run("N", def, {}, info(rootDir));
313
+ } catch (err) {
314
+ thrown = err;
315
+ }
316
+ rmSync(rootDir, { recursive: true, force: true });
317
+ expect(thrown).toBeInstanceOf(AgentFailure);
318
+ return thrown as AgentFailure;
319
+ }
320
+
321
+ const errorEvent = (type: string, message: string, status?: number) =>
322
+ `echo '${JSON.stringify({ type: "error", sessionID: "ses_1", error: { type, message, ...(status ? { status } : {}) } })}'\nexit 1`;
323
+
324
+ test("captured provider.auth event: message in the crash reason, runner-error", async () => {
325
+ const failure = await failWith(
326
+ `echo '{"type":"step_start"}'\n${errorEvent("provider.auth", "This API key has expired.", 401)}`,
327
+ );
328
+ expect(failure.crashReason).toEqual({
329
+ kind: "runner-error",
330
+ error: "opencode exited 1: provider.auth (401): This API key has expired.",
331
+ });
332
+ });
333
+
334
+ test("captured provider.no-route event: message in the crash reason, runner-error", async () => {
335
+ const failure = await failWith(errorEvent("provider.no-route", "Model unavailable: foo"));
336
+ expect(failure.crashReason).toEqual({
337
+ kind: "runner-error",
338
+ error: "opencode exited 1: provider.no-route: Model unavailable: foo",
339
+ });
340
+ });
341
+
342
+ for (const type of [
343
+ "provider.quota",
344
+ "provider.rate-limit",
345
+ "provider.go-limit",
346
+ "provider.chatgpt-limit",
347
+ "provider.chatgpt-workspace-limit",
348
+ "provider.budget-limit",
349
+ ]) {
350
+ test(`${type} error event classifies usage-limit`, async () => {
351
+ const failure = await failWith(
352
+ `echo '{"type":"step_finish","part":{"reason":"stop","sessionID":"sess-q"}}'\n${errorEvent(type, "Plan exhausted, wait.")}`,
353
+ );
354
+ expect(failure.crashReason).toEqual({ kind: "usage-limit", detail: "Plan exhausted, wait." });
355
+ expect(failure.agentSessionId).toBe("sess-q");
356
+ });
357
+ }
358
+
359
+ for (const type of ["provider.free-limit", "provider.model-budget-limit", "provider.mystery"]) {
360
+ test(`${type} error event does not wait`, async () => {
361
+ const failure = await failWith(errorEvent(type, "usage limit hit, switch models"));
362
+ expect(failure.crashReason?.kind).toBe("runner-error");
363
+ });
364
+ }
365
+
366
+ test("an untyped error event with a limit marker classifies usage-limit", async () => {
367
+ const failure = await failWith(
368
+ `echo '{"type":"error","error":{"message":"Usage limit reached for 5 hour."}}'\nexit 1`,
369
+ );
370
+ expect(failure.crashReason).toEqual({
371
+ kind: "usage-limit",
372
+ detail: "Usage limit reached for 5 hour.",
373
+ });
374
+ });
375
+
376
+ test("a non-error JSON event mentioning a limit never matches on a non-zero exit", async () => {
377
+ const failure = await failWith(
378
+ `echo '{"type":"text","part":{"text":"usage limit reached"}}'\nexit 1`,
379
+ );
380
+ expect(failure.crashReason?.kind).toBe("runner-error");
381
+ });
382
+
306
383
  test("an exit-0 + missing-handoff output with a limit string inside an agent JSON line stays handoff-missing", async () => {
307
384
  const { rootDir } = install((_rootDir, _argvFile) =>
308
385
  [
@@ -35,10 +35,10 @@ export interface StepFinishScan {
35
35
  // mid-turn death) all surfaced as `exit 0` + missing handoff → a bare
36
36
  // ENOENT minutes after the real failure. Capture the reason and make a
37
37
  // missing handoff fail loudly with it, so retries and RCA start from facts.
38
- // NB: the type discriminator is hyphenated ("step-finish"), confirmed against
39
- // both @opencode-ai/sdk's generated types and strings pulled from the
40
- // installed opencode binary — matching on "step_finish" (underscore) here
41
- // silently never matched, so this capture never actually fired.
38
+ // NB: the stream's outer `type` is `step_finish` (underscore). The
39
+ // hyphenated "step-finish" appears only one level down, in `part.type`
40
+ // (captured from opencode 2.3.0, 2026-11-28). The SDK's part types use the
41
+ // hyphen, which is not what `run --format json` puts on the outer event.
42
42
  //
43
43
  // Extended (docs/specs/_built/session-nudge/spec.md) to also pull `part.sessionID`
44
44
  // and a count of step-finish events seen, in the same single pass:
@@ -58,7 +58,7 @@ export function scanStepFinish(stdout: string): StepFinishScan {
58
58
  type?: string;
59
59
  part?: { reason?: string; sessionID?: string };
60
60
  };
61
- if (event.type === "step-finish") {
61
+ if (event.type === "step_finish") {
62
62
  stepCount++;
63
63
  if (event.part?.reason) reason = event.part.reason;
64
64
  if (event.part?.sessionID) sessionId = event.part.sessionID;
@@ -170,8 +170,97 @@ export function matchUsageLimit(stderr: string, stdout: string): string | undefi
170
170
  return undefined;
171
171
  }
172
172
 
173
+ // Provider errors (docs/roadmap/run-resilience/tickets/opencode-provider-error-lost.md):
174
+ // with `--format json`, opencode reports a provider failure as a top-level
175
+ // `error` event on stdout, exits 1 and writes nothing to stderr. The event is
176
+ // opencode's own, not agent-authored, so reading it does not reopen the
177
+ // false-positive hazard `matchUsageLimit` guards against. Re-check the type
178
+ // table against opencode's source (core/src/session/to-session-error.ts)
179
+ // when upgrading the supported version.
180
+ export interface ProviderError {
181
+ type?: string;
182
+ message?: string;
183
+ status?: number;
184
+ }
185
+
186
+ const WAITING_ERROR_TYPES = new Set([
187
+ "provider.quota",
188
+ "provider.rate-limit",
189
+ "provider.go-limit",
190
+ "provider.chatgpt-limit",
191
+ "provider.chatgpt-workspace-limit",
192
+ "provider.budget-limit",
193
+ ]);
194
+
195
+ /** The last top-level `error` event on stdout, if any. */
196
+ export function scanProviderError(stdout: string): ProviderError | undefined {
197
+ let found: ProviderError | undefined;
198
+ for (const line of stdout.split("\n")) {
199
+ if (!line.trim()) continue;
200
+ try {
201
+ const event = JSON.parse(line) as { type?: unknown; error?: unknown };
202
+ if (event.type !== "error" || event.error === null || typeof event.error !== "object") {
203
+ continue;
204
+ }
205
+ const err = event.error as Record<string, unknown>;
206
+ found = {
207
+ type: typeof err.type === "string" ? err.type : undefined,
208
+ message: typeof err.message === "string" ? err.message : undefined,
209
+ status: typeof err.status === "number" ? err.status : undefined,
210
+ };
211
+ } catch {
212
+ // ignore: not every line is guaranteed parseable
213
+ }
214
+ }
215
+ return found;
216
+ }
217
+
218
+ function describeProviderError(err: ProviderError): string {
219
+ const head = `${err.type ?? "error"}${err.status !== undefined ? ` (${err.status})` : ""}`;
220
+ return err.message ? `${head}: ${err.message}` : head;
221
+ }
222
+
223
+ /** A waiting limit: a known waiting type, or an untyped error whose message
224
+ * holds one of the plain-text markers. Everything else is not waited on. */
225
+ function providerLimitDetail(err: ProviderError): string | undefined {
226
+ const text = err.message ?? describeProviderError(err);
227
+ if (err.type !== undefined) return WAITING_ERROR_TYPES.has(err.type) ? text : undefined;
228
+ const lowered = text.toLowerCase();
229
+ return USAGE_LIMIT_MARKERS.some((marker) => lowered.includes(marker)) ? text : undefined;
230
+ }
231
+
232
+ // `opencode models` answers in about a second; this only bounds a hung one.
233
+ const MODEL_LIST_TIMEOUT_MS = 20_000;
234
+
235
+ /** The ids `opencode models` lists for `rootDir`, so project config counts. */
236
+ async function listModels(rootDir: string): Promise<Set<string>> {
237
+ const bin = Bun.which("opencode") ?? "opencode";
238
+ const proc = Bun.spawn([bin, "models"], {
239
+ cwd: rootDir,
240
+ stdout: "pipe",
241
+ stderr: "pipe",
242
+ timeout: MODEL_LIST_TIMEOUT_MS,
243
+ });
244
+ const [stdout, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
245
+ const ids = stdout
246
+ .split("\n")
247
+ .map((line) => line.trim())
248
+ .filter(Boolean);
249
+ if (exitCode !== 0 || ids.length === 0) {
250
+ throw new Error(`\`opencode models\` exited ${exitCode} with ${ids.length} models`);
251
+ }
252
+ return new Set(ids);
253
+ }
254
+
173
255
  export const opencodeRunner: AgentRunner = {
174
256
  kind: "opencode",
257
+ async checkModels(models, rootDir) {
258
+ const listed = await listModels(rootDir);
259
+ // `-m` takes provider/model#variant; the list holds provider/model.
260
+ return models
261
+ .filter((model) => !listed.has(model.split("#")[0]!))
262
+ .map((model) => ({ model, message: `model "${model}" is not in \`opencode models\`` }));
263
+ },
175
264
  async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
176
265
  const path = handoffPath(info.rootDir, info.runId, info.step, id);
177
266
  await mkdir(dirname(path), { recursive: true });
@@ -299,7 +388,7 @@ export const opencodeRunner: AgentRunner = {
299
388
  try {
300
389
  const event = JSON.parse(line) as { type?: string };
301
390
  if (event.type) lastEvent = event.type;
302
- if (event.type === "step-finish") stepCount++;
391
+ if (event.type === "step_finish") stepCount++;
303
392
  } catch {
304
393
  // ignore: not every line is guaranteed parseable (same tolerance
305
394
  // scanStepFinish's final pass already has)
@@ -318,7 +407,11 @@ export const opencodeRunner: AgentRunner = {
318
407
 
319
408
  if (exitCode !== 0) {
320
409
  const stderr = await new Response(proc.stderr).text();
321
- const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
410
+ const providerError = scanProviderError(stdout);
411
+ const detailText = [stderr.trim(), providerError ? describeProviderError(providerError) : ""]
412
+ .filter(Boolean)
413
+ .join("\n");
414
+ const reason = `opencode exited ${exitCode}: ${detailText.slice(-400)}`;
322
415
  lastFailures.set(dispatchKey, reason);
323
416
  const scan = scanStepFinish(stdout);
324
417
  // Usage-limit classification (docs/specs/_built/usage-limit-backoff/spec.md):
@@ -327,7 +420,9 @@ export const opencodeRunner: AgentRunner = {
327
420
  // waits it out instead of burning retries against it. The session id
328
421
  // stays evidence-gated (stepCount > 0) exactly as below. No match
329
422
  // keeps the existing runner-error throw unchanged.
330
- const limitLine = matchUsageLimit(stderr, stdout);
423
+ const limitLine =
424
+ matchUsageLimit(stderr, stdout) ??
425
+ (providerError ? providerLimitDetail(providerError) : undefined);
331
426
  if (limitLine !== undefined) {
332
427
  throw new AgentFailure(reason, {
333
428
  agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
@@ -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
  });
@@ -0,0 +1,11 @@
1
+ import type { OutputSchema } from "../core/index.ts";
2
+
3
+ // The minimal schema every test fixture's agent leaf declares once
4
+ // validateWorkflow rejects a missing outputType
5
+ // (docs/specs/mandatory-agent-output-types/). Fixtures exercise routing,
6
+ // retries, nudges, and the journal — never their output shape — so the
7
+ // declaration is deliberately the most permissive one the rule accepts
8
+ // (a schema that rejects nothing). A test-local convenience, not kit API.
9
+ export const okOutputType: OutputSchema = {
10
+ safeParse: () => ({ success: true }),
11
+ };
@@ -0,0 +1,43 @@
1
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
2
+ import { z } from "zod";
3
+
4
+ // Plan's handoff output is the one dev-loop claim a consumer actually
5
+ // reads: ValidatePlan runs parseTaskList on it and persists tasks.json.
6
+ // This schema mirrors that narrowing
7
+ // (docs/specs/_built/task-list-json/spec.md), so a malformed list costs an
8
+ // in-session nudge instead of a full Plan/ValidatePlan loop round.
9
+ const priority = z.enum(["must", "should", "could", "won't"]);
10
+ const taskList = z.object({
11
+ id: z.string(),
12
+ spec: z.object({ prd: z.string().optional(), design: z.string().optional() }).optional(),
13
+ requirements: z
14
+ .array(
15
+ z.object({
16
+ id: z.string(),
17
+ kind: z.enum(["req", "nfr", "ng"]),
18
+ text: z.string(),
19
+ priority: priority.optional(),
20
+ }),
21
+ )
22
+ .optional(),
23
+ tasks: z.array(
24
+ z.object({
25
+ id: z.string(),
26
+ title: z.string(),
27
+ status: z.enum(["pending", "in-progress", "done", "failed"]),
28
+ satisfies: z.array(z.string()).optional(),
29
+ priority: priority.optional(),
30
+ }),
31
+ ),
32
+ });
33
+ export const planOutput = zodOutputType(taskList);
34
+
35
+ // The other agent leaves route by event; their consumers (Test, MarkDone,
36
+ // Finish) read the working tree and tasks.json, never the handoff output.
37
+ // Their declarations stay permissive — the rule guarantees a declaration,
38
+ // not a good one (docs/specs/mandatory-agent-output-types/, NG-1).
39
+ export const implementOutput = zodOutputType(z.unknown());
40
+ export const fixOutput = zodOutputType(z.unknown());
41
+ export const reviewOutput = zodOutputType(z.unknown());
42
+ export const documentOutput = zodOutputType(z.unknown());
43
+ export const feedbackOutput = zodOutputType(z.unknown());