@psimona/darkf 0.6.0 → 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.
Files changed (49) hide show
  1. package/docs/concepts/failure-modes.md +23 -7
  2. package/docs/concepts/handoff.md +3 -3
  3. package/docs/concepts/node-types.md +44 -20
  4. package/docs/guides/pick-an-agent-runner.md +122 -4
  5. package/docs/guides/plan-with-a-task-queue.md +9 -7
  6. package/docs/guides/run-detached-and-monitor.md +3 -3
  7. package/docs/guides/write-your-first-workflow.md +14 -5
  8. package/docs/index.mdx +4 -0
  9. package/docs/reference/cli-commands.md +22 -6
  10. package/docs/reference/core-types.md +29 -4
  11. package/docs/reference/package-map.md +12 -8
  12. package/docs/start-here/quickstart.md +15 -7
  13. package/package.json +9 -2
  14. package/skills/darkf-writing-workflows/SKILL.md +141 -7
  15. package/src/cli/detached.test.ts +88 -2
  16. package/src/cli/doctor.test.ts +225 -10
  17. package/src/cli/index.ts +106 -27
  18. package/src/cli/setup.ts +4 -9
  19. package/src/cli/state-file.ts +14 -0
  20. package/src/cli/tarball.test.ts +3 -1
  21. package/src/cli/update.ts +4 -9
  22. package/src/core/graph.test.ts +124 -19
  23. package/src/core/graph.ts +51 -3
  24. package/src/core/tasks.ts +1 -1
  25. package/src/core/types.test.ts +52 -0
  26. package/src/core/types.ts +48 -18
  27. package/src/engine/run.test.ts +708 -18
  28. package/src/engine/run.ts +101 -16
  29. package/src/exports.ts +4 -0
  30. package/src/kit/agents/claude-code.test.ts +38 -2
  31. package/src/kit/agents/claude-code.ts +28 -37
  32. package/src/kit/agents/handoff.test.ts +12 -0
  33. package/src/kit/agents/handoff.ts +32 -8
  34. package/src/kit/agents/opencode.test.ts +1 -1
  35. package/src/kit/agents/opencode.ts +44 -28
  36. package/src/kit/specs.test.ts +247 -0
  37. package/src/kit/specs.ts +344 -0
  38. package/src/kit/status.test.ts +24 -0
  39. package/src/kit/status.ts +31 -14
  40. package/src/kit/validation/zod.test.ts +42 -0
  41. package/src/kit/validation/zod.ts +20 -0
  42. package/workflows/dev-loop/scripts/begin.ts +9 -6
  43. package/workflows/dev-loop/scripts/dispatch.ts +50 -0
  44. package/workflows/dev-loop/scripts/finish.ts +23 -21
  45. package/workflows/dev-loop/scripts/mark-done.ts +22 -0
  46. package/workflows/dev-loop/scripts/validate-plan.ts +30 -0
  47. package/workflows/dev-loop/workflow.ts +164 -68
  48. package/workflows/series-ordering/workflow.ts +1 -0
  49. /package/workflows/dev-loop/scripts/{check.ts → test.ts} +0 -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,
@@ -29,7 +32,7 @@ import { createJsonlEventLogger } from "./eventLog.ts";
29
32
  const DEFAULT_HEARTBEAT_MS = 30_000;
30
33
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000; // 1h — high default ceiling, not a tuning knob
31
34
  const DEFAULT_MAX_STEPS = 1000;
32
- // Usage-limit backoff defaults (docs/specs/usage-limit-backoff/spec.md) —
35
+ // Usage-limit backoff defaults (docs/specs/_built/usage-limit-backoff/spec.md) —
33
36
  // the leaf-config fields on BaseLeafDef fall back to these. Fixed 30-min
34
37
  // probe interval, deliberately not the provider message's quoted reset time
35
38
  // (its timezone is not the supervisor's); 24h bounds the total wait per
@@ -37,13 +40,14 @@ const DEFAULT_MAX_STEPS = 1000;
37
40
  const DEFAULT_USAGE_LIMIT_RETRY_MS = 30 * 60 * 1000;
38
41
  const DEFAULT_USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60 * 1000;
39
42
  // Bounded in-session repair attempts per outer attempt (see
40
- // docs/specs/session-nudge/spec.md) — not a `def.retries`-style tuning
43
+ // docs/specs/_built/session-nudge/spec.md) — not a `def.retries`-style tuning
41
44
  // knob, deliberately fixed.
42
45
  const NUDGE_LIMIT = 3;
43
46
  const NUDGEABLE_KINDS = new Set<CrashReason["kind"]>([
44
47
  "handoff-missing",
45
48
  "handoff-unparseable",
46
49
  "no-transition",
50
+ "validation-failed",
47
51
  ]);
48
52
  function isNudgeable(reason: CrashReason): boolean {
49
53
  return NUDGEABLE_KINDS.has(reason.kind);
@@ -92,7 +96,10 @@ export interface RunOptions {
92
96
  workflow: WorkflowDef;
93
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 `{}`. */
94
98
  input?: NodeResult;
99
+ /** Default runner, for agent states that name none. */
95
100
  agentRunner?: AgentRunner;
101
+ /** Runners an agent state selects by name through `AgentStateDef.runner`. */
102
+ agentRunners?: Record<string, AgentRunner>;
96
103
  scriptRunner?: ScriptRunner;
97
104
  /** Live-runtime heartbeat cadence for open dispatches (default 30s, 0 disables). */
98
105
  heartbeatMs?: number;
@@ -153,7 +160,10 @@ export async function run(opts: RunOptions): Promise<RunResult> {
153
160
  throw err;
154
161
  }
155
162
 
156
- 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
+ });
157
167
  if (validationErrors.length > 0) {
158
168
  return crashed(
159
169
  { kind: "invalid-workflow", errors: validationErrors },
@@ -216,15 +226,17 @@ export async function run(opts: RunOptions): Promise<RunResult> {
216
226
  let attempt = 0;
217
227
  // Usage-limit wait bookkeeping — per node visit, never per attempt:
218
228
  // waits consume no retry, so the wait budget spans every attempt of
219
- // this visit (docs/specs/usage-limit-backoff/spec.md).
229
+ // this visit (docs/specs/_built/usage-limit-backoff/spec.md).
220
230
  let limitWaitedMs = 0;
221
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) : {};
222
234
 
223
235
  attemptLoop: for (attempt = 1; attempt <= maxAttempts; attempt++) {
224
236
  // Fixed once per outer attempt: every dispatch this attempt makes — the
225
237
  // first call and up to NUDGE_LIMIT nudges after it — spends down the
226
238
  // SAME remaining budget, so a nudge sequence can't multiply the
227
- // configured per-attempt timeout (docs/specs/session-nudge/spec.md,
239
+ // configured per-attempt timeout (docs/specs/_built/session-nudge/spec.md,
228
240
  // "Dispatch loop change").
229
241
  //
230
242
  // Usage-limit exception (same spec family, usage-limit-backoff D-7):
@@ -249,7 +261,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
249
261
  const startedAt = Date.now();
250
262
  // Reset fresh per dispatch attempt (including each nudge) — a new
251
263
  // process gets a new progress snapshot, never carried over from a
252
- // previous attempt. See docs/specs/agent-liveness/spec.md.
264
+ // previous attempt. See docs/specs/_built/agent-liveness/spec.md.
253
265
  let latestProgress: AgentProgress | undefined;
254
266
  const onProgress = (p: AgentProgress) => {
255
267
  latestProgress = p;
@@ -263,6 +275,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
263
275
  startedAt,
264
276
  lastHeartbeat,
265
277
  agentSessionId,
278
+ ...runnerRecord,
266
279
  ...(latestProgress
267
280
  ? {
268
281
  agentStepCount: latestProgress.stepCount,
@@ -275,7 +288,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
275
288
  emit(runningStatus(startedAt), current, scopePath);
276
289
  // Live-runtime heartbeats: journal a refreshed `running` status while the
277
290
  // dispatch is open, so status/monitor can advance runtime and prove
278
- // liveness (spec: darkf-cli/docs/specs/live-runtime). unref'd — a pending
291
+ // liveness (spec: docs/specs/_built/live-runtime). unref'd — a pending
279
292
  // timer must never keep the process alive past the run's own exit.
280
293
  const heartbeat =
281
294
  heartbeatMs > 0
@@ -286,7 +299,14 @@ export async function run(opts: RunOptions): Promise<RunResult> {
286
299
  try {
287
300
  const dispatch =
288
301
  def.type === "agent"
289
- ? 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
+ )
290
310
  : scriptRunner.run(current, def, handoff, baseDir, info);
291
311
  const raw = await withTimeout(dispatch, Math.max(0, deadline - Date.now()));
292
312
  heartbeat && clearInterval(heartbeat);
@@ -296,9 +316,50 @@ export async function run(opts: RunOptions): Promise<RunResult> {
296
316
  continue attemptLoop;
297
317
  }
298
318
  agentSessionId = raw.agentSessionId ?? agentSessionId;
299
- const validationError = def.validate?.(raw, handoff);
319
+ // Bare-payload coercion (agent nodes only). A result without an
320
+ // `event` field is the agent's raw payload, not an envelope —
321
+ // wrap it so the payload always rides the reserved `output`
322
+ // channel. Without this, a payload that itself carries an
323
+ // `output` key hijacks the channel downstream (run 0a1b2ca3: a
324
+ // hybrid `{behavior_ok, gaps, output: {summary}}` shipped the
325
+ // summary as the payload and shadowed the passing verdict).
326
+ // Routing is untouched: `resolveTarget` still reads `raw.event`,
327
+ // and event-less results keep falling through `def.next`.
328
+ const result_ =
329
+ def.type === "agent" && raw.event === undefined ? ({ output: raw } as NodeResult) : raw;
330
+ // outputType (agent leaves only) — a shape check on the payload,
331
+ // run before `validate` so a validate script can read the output
332
+ // without re-checking its shape
333
+ // (docs/specs/output-validation/spec.md, "Order"). Same inline
334
+ // nudge form as no-transition below: this reason comes from a
335
+ // return value, not a thrown AgentFailure, so the catch block's
336
+ // isNudgeable path never sees it.
337
+ const typeResult =
338
+ def.type === "agent" && def.outputType
339
+ ? def.outputType.safeParse(result_.output)
340
+ : undefined;
341
+ if (typeResult && !typeResult.success) {
342
+ reason = { kind: "validation-failed", message: typeResult.message };
343
+ if (agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
344
+ nudgeAttempt++;
345
+ continue;
346
+ }
347
+ continue attemptLoop;
348
+ }
349
+ const validationError = def.validate?.(result_, handoff);
300
350
  if (validationError !== undefined) {
301
351
  reason = { kind: "validation-failed", message: validationError };
352
+ // A validate rejection now nudges in-session first, same inline
353
+ // form as the checks beside it — a return-value reason, so the
354
+ // catch block's isNudgeable path never sees it. Up to
355
+ // NUDGE_LIMIT nudges consume no retry; only the fallback to a
356
+ // fresh attempt does
357
+ // (docs/specs/output-validation/spec.md, "Where this plugs
358
+ // into the dispatch loop").
359
+ if (agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
360
+ nudgeAttempt++;
361
+ continue;
362
+ }
302
363
  continue attemptLoop;
303
364
  }
304
365
  const resolved = resolveTarget(def, raw.event);
@@ -311,7 +372,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
311
372
  continue attemptLoop;
312
373
  }
313
374
 
314
- result = raw;
375
+ result = result_;
315
376
  target = resolved;
316
377
  reason = undefined;
317
378
  break attemptLoop;
@@ -334,7 +395,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
334
395
  nudgeAttempt++;
335
396
  continue;
336
397
  }
337
- // Usage-limit (docs/specs/usage-limit-backoff/spec.md, Wait and
398
+ // Usage-limit (docs/specs/_built/usage-limit-backoff/spec.md, Wait and
338
399
  // resume): a quota wall is not a failed attempt — it consumes no
339
400
  // retry. Sleep usageLimitRetryMs (heartbeating the wait), then
340
401
  // re-dispatch this same attempt; the existing
@@ -415,9 +476,33 @@ export async function run(opts: RunOptions): Promise<RunResult> {
415
476
  }
416
477
  }
417
478
 
418
- function requireAgentRunner(agentRunner: AgentRunner | undefined): AgentRunner {
419
- if (!agentRunner) {
420
- throw new Error("Workflow contains an agent node but no agentRunner was provided");
421
- }
422
- 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
+ };
423
508
  }
package/src/exports.ts CHANGED
@@ -1,2 +1,6 @@
1
+ // Workflow discovery (opencode-overlay-tabs r9): the same two-root scan
2
+ // `darkf run`/`render` resolve against, reused instead of re-scanned.
3
+ export { listWorkflows, type WorkflowListing } from "./cli/index.ts";
1
4
  export * from "./kit/registry.ts";
5
+ export * from "./kit/specs.ts";
2
6
  export * from "./kit/status.ts";
@@ -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
+ });
@@ -1,44 +1,14 @@
1
1
  import { mkdir } from "node:fs/promises";
2
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";
3
+ import { AgentFailure, type AgentRunner, type NodeResult } from "../../core/index.ts";
4
+ import { buildPrompt, handoffPath, nudgeMessage, readHandoff, usagePath } from "./handoff.ts";
16
5
 
17
6
  // Mirrors darkf-engine's own DEFAULT_TIMEOUT_MS (run.ts) so this runner can
18
7
  // kill its own subprocess in step with the engine's timeout instead of
19
8
  // 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.
9
+ // docs/specs/_built/agent-handoff/spec.md's retry-overwrite race note.
21
10
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
22
11
 
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
12
  interface ClaudeCodeStdout {
43
13
  session_id?: string;
44
14
  total_cost_usd?: number;
@@ -92,17 +62,38 @@ function parseAgentSessionId(stdout: string): string | undefined {
92
62
  }
93
63
  }
94
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
+
95
70
  export const claudeCodeRunner: AgentRunner = {
96
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
+ },
97
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
+
98
91
  const path = handoffPath(info.rootDir, info.runId, info.step, id);
99
92
  await mkdir(dirname(path), { recursive: true });
100
93
 
101
- const agentConfig = def.agent ?? {};
102
94
  const permissionMode =
103
95
  (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
96
+ // Same-session nudge (docs/specs/_built/session-nudge/spec.md): when the
106
97
  // previous attempt failed in a repairable way and we have its session
107
98
  // id, send a short corrective message into that session instead of
108
99
  // replaying the full prompt. `--resume` itself is unconditional on
@@ -114,7 +105,7 @@ export const claudeCodeRunner: AgentRunner = {
114
105
  // Resolve once: spawn can miss PATH lookups in daemonized workers.
115
106
  const bin = Bun.which("claude") ?? "claude";
116
107
  const args = [bin, "-p", "--output-format", "json", "--permission-mode", permissionMode];
117
- if (model) args.push("--model", model);
108
+ args.push("--model", model);
118
109
  if (info.agentSessionId) args.push("--resume", info.agentSessionId);
119
110
  args.push(prompt);
120
111
 
@@ -126,3 +126,15 @@ test("nudgeMessage builds the no-transition repair text, naming the bad event an
126
126
  expect(msg).toContain("ok, changes_requested");
127
127
  expect(msg).toContain("routable event");
128
128
  });
129
+
130
+ test("nudgeMessage builds the validation-failed repair text, quoting the message", () => {
131
+ const info = baseInfo({
132
+ agentSessionId: "sess-1",
133
+ previousFailure: { kind: "validation-failed", message: "tasks[2].title: required" },
134
+ });
135
+ const msg = nudgeMessage(info, "/root/.darkf/run/run-1/handoff/0001-Plan.json")!;
136
+ expect(msg).toContain("failed validation");
137
+ expect(msg).toContain("tasks[2].title: required");
138
+ expect(msg).toContain('Rewrite the handoff\'s "output" field');
139
+ expect(msg).toContain("/root/.darkf/run/run-1/handoff/0001-Plan.json");
140
+ });
@@ -1,9 +1,9 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import type { DispatchInfo } from "../../core/index.ts";
3
+ import type { AgentStateDef, DispatchInfo, NodeResult } from "../../core/index.ts";
4
4
 
5
5
  // Shared, harness-agnostic half of the agent-handoff contract. See
6
- // docs/specs/agent-handoff/spec.md. Per-harness runners own everything else
6
+ // docs/specs/_built/agent-handoff/spec.md. Per-harness runners own everything else
7
7
  // (invocation, native structured-output vs. prompt fallback, agentSessionId,
8
8
  // subprocess lifecycle).
9
9
 
@@ -35,13 +35,35 @@ export async function readHandoff(path: string): Promise<unknown> {
35
35
  return JSON.parse(text);
36
36
  }
37
37
 
38
+ /** Builds one agent's prompt from its state def, the previous step's
39
+ * handoff, and the valid outgoing events — identical for every harness,
40
+ * so each runner calls this instead of building its own. */
41
+ export function buildPrompt(
42
+ def: AgentStateDef,
43
+ handoff: NodeResult,
44
+ info: { validEvents: string[]; hasFallback: boolean },
45
+ path: string,
46
+ ): string {
47
+ const parts = [def.prompt, `Input from the previous step:\n${JSON.stringify(handoff)}`];
48
+
49
+ if (info.validEvents.length > 0) {
50
+ const fallbackNote = info.hasFallback ? ` If none apply, you may omit "event" instead.` : "";
51
+ parts.push(
52
+ `Your "event" must be exactly one of: ${info.validEvents.join(", ")}.${fallbackNote}`,
53
+ );
54
+ }
55
+
56
+ parts.push(handoffContractText(path));
57
+ return parts.join("\n\n");
58
+ }
59
+
38
60
  /**
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.
61
+ * Shared same-session repair text for the nudgeable `CrashReason` kinds
62
+ * (docs/specs/_built/session-nudge/spec.md, docs/specs/output-validation/spec.md).
63
+ * `undefined` means "don't nudge" — either there's no `previousFailure`, no
64
+ * `agentSessionId` to resume, or the failure isn't one of the repairable
65
+ * kinds. Both runners call this identically; only the CLI invocation that
66
+ * sends the message differs per harness.
45
67
  */
46
68
  export function nudgeMessage(info: DispatchInfo, path: string): string | undefined {
47
69
  const failure = info.previousFailure;
@@ -54,6 +76,8 @@ export function nudgeMessage(info: DispatchInfo, path: string): string | undefin
54
76
  return `The JSON at ${path} failed to parse (${failure.parseError}). Rewrite it as a single valid JSON object with the contract fields.`;
55
77
  case "no-transition":
56
78
  return `You reported event ${failure.event}; this state only routes ${validEvents}. Re-issue the handoff with a routable event.`;
79
+ case "validation-failed":
80
+ return `Your output failed validation: ${failure.message}\n\nRewrite the handoff's "output" field to fix this and write it again to ${path}.`;
57
81
  default:
58
82
  return undefined;
59
83
  }
@@ -140,7 +140,7 @@ describe("readIncrementally", () => {
140
140
  });
141
141
  });
142
142
 
143
- // --- usage-limit-backoff (docs/specs/usage-limit-backoff/spec.md) ---
143
+ // --- usage-limit-backoff (docs/specs/_built/usage-limit-backoff/spec.md) ---
144
144
 
145
145
  describe("matchUsageLimit", () => {
146
146
  test("matches the captured usage-limit line, case-insensitively, returning the line itself", () => {
@@ -5,36 +5,22 @@ import {
5
5
  AgentFailure,
6
6
  type AgentProgress,
7
7
  type AgentRunner,
8
- type AgentStateDef,
9
8
  type DispatchInfo,
10
9
  type NodeResult,
11
10
  } from "../../core/index.ts";
12
- import { handoffContractText, handoffPath, nudgeMessage, readHandoff } from "./handoff.ts";
11
+ import {
12
+ buildPrompt,
13
+ handoffContractText,
14
+ handoffPath,
15
+ nudgeMessage,
16
+ readHandoff,
17
+ } from "./handoff.ts";
13
18
 
14
19
  // Mirrors darkf-engine's own DEFAULT_TIMEOUT_MS (run.ts), same reason
15
20
  // claude-code.ts does: kill the subprocess in step with the engine's own
16
21
  // timeout instead of leaving it running past the point the engine moved on.
17
22
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
18
23
 
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
24
  export interface StepFinishScan {
39
25
  reason?: string;
40
26
  sessionId?: string;
@@ -54,7 +40,7 @@ export interface StepFinishScan {
54
40
  // installed opencode binary — matching on "step_finish" (underscore) here
55
41
  // silently never matched, so this capture never actually fired.
56
42
  //
57
- // Extended (docs/specs/session-nudge/spec.md) to also pull `part.sessionID`
43
+ // Extended (docs/specs/_built/session-nudge/spec.md) to also pull `part.sessionID`
58
44
  // and a count of step-finish events seen, in the same single pass:
59
45
  // `stepCount` is the positive-evidence gate for ever reporting a session id
60
46
  // at all — this is the resumability fix for the session that hung 15
@@ -84,7 +70,7 @@ export function scanStepFinish(stdout: string): StepFinishScan {
84
70
  return { reason, sessionId, stepCount };
85
71
  }
86
72
 
87
- // Agent-liveness (docs/specs/agent-liveness/spec.md): a stalled LLM backend
73
+ // Agent-liveness (docs/specs/_built/agent-liveness/spec.md): a stalled LLM backend
88
74
  // still produces a healthy engine heartbeat, because the engine only knows
89
75
  // the process is alive, not whether the agent is making progress. Reading
90
76
  // stdout incrementally (rather than once, at exit, as `scanStepFinish`'s
@@ -132,7 +118,7 @@ export async function readIncrementally(
132
118
  // dispatch's failure reason; if the same dispatch key runs again, the
133
119
  // retry's prompt opens with the reason so it can correct course (e.g.
134
120
  // "handoff not written", "handoff unparseable", exit stderr tail).
135
- // Unaffected by same-session nudging (docs/specs/session-nudge/spec.md):
121
+ // Unaffected by same-session nudging (docs/specs/_built/session-nudge/spec.md):
136
122
  // this cache covers the fresh-session case, nudging covers the
137
123
  // same-session case, and the two never fire on the same attempt.
138
124
  const lastFailures = new Map<string, string>();
@@ -152,7 +138,7 @@ function contextBlock(rootDir: string, runId: string): string {
152
138
  }
153
139
  }
154
140
 
155
- // Usage-limit detection (docs/specs/usage-limit-backoff/spec.md, Detection):
141
+ // Usage-limit detection (docs/specs/_built/usage-limit-backoff/spec.md, Detection):
156
142
  // a provider quota wall surfaces as an API-level error — opencode exits
157
143
  // non-zero with the provider's message in its output. Scan stderr and
158
144
  // non-JSON stdout lines ONLY: stdout's NDJSON lines are event objects, i.e.
@@ -184,8 +170,38 @@ export function matchUsageLimit(stderr: string, stdout: string): string | undefi
184
170
  return undefined;
185
171
  }
186
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
+
187
196
  export const opencodeRunner: AgentRunner = {
188
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
+ },
189
205
  async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
190
206
  const path = handoffPath(info.rootDir, info.runId, info.step, id);
191
207
  await mkdir(dirname(path), { recursive: true });
@@ -211,14 +227,14 @@ export const opencodeRunner: AgentRunner = {
211
227
 
212
228
  const dispatchKey = `${info.runId}:${info.step}:${id}`;
213
229
 
214
- // Same-session nudge (docs/specs/session-nudge/spec.md): when the
230
+ // Same-session nudge (docs/specs/_built/session-nudge/spec.md): when the
215
231
  // previous attempt failed in a repairable way and we have its session
216
232
  // id, send a short corrective message into that session instead of a
217
233
  // fresh prompt. `-s` resume is scoped strictly to this case — see the
218
234
  // "No -s outside a nudge" note below.
219
235
  const nudge = nudgeMessage(info, path);
220
236
 
221
- // Post-limit continuation (docs/specs/usage-limit-backoff/spec.md, Wait
237
+ // Post-limit continuation (docs/specs/_built/usage-limit-backoff/spec.md, Wait
222
238
  // and resume): when the engine re-dispatches this attempt after waiting
223
239
  // out a usage limit, resume the interrupted session with a short
224
240
  // continuation prompt instead of replaying the full fresh prompt — the
@@ -335,7 +351,7 @@ export const opencodeRunner: AgentRunner = {
335
351
  const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
336
352
  lastFailures.set(dispatchKey, reason);
337
353
  const scan = scanStepFinish(stdout);
338
- // Usage-limit classification (docs/specs/usage-limit-backoff/spec.md):
354
+ // Usage-limit classification (docs/specs/_built/usage-limit-backoff/spec.md):
339
355
  // consulted on this non-zero-exit branch ONLY, before the generic
340
356
  // throw — a quota wall is a known temporary condition, and the engine
341
357
  // waits it out instead of burning retries against it. The session id