@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
@@ -11,7 +11,8 @@ executing."
11
11
  ```ts
12
12
  export type NodeStatus =
13
13
  | { phase: "pending" }
14
- | { phase: "running"; attempt: number; startedAt: number; lastHeartbeat: number; sessionId?: string;
14
+ | { phase: "running"; attempt: number; startedAt: number; lastHeartbeat: number; agentSessionId?: string;
15
+ runner?: string; runnerKind?: AgentRunnerKind;
15
16
  limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number } }
16
17
  | { phase: "succeeded"; result: NodeResult }
17
18
  | { phase: "crashed"; reason: CrashReason; attempt: number };
@@ -26,7 +27,9 @@ all of them are required:
26
27
  | `running` | `attempt` | Yes | Which attempt number is in flight — `1` for the first try. |
27
28
  | `running` | `startedAt` | Yes | Timestamp this attempt began. |
28
29
  | `running` | `lastHeartbeat` | Yes | Timestamp of the latest heartbeat, updated every 30s. |
29
- | `running` | `sessionId` | No | Only present once some earlier attempt's runner returned one. |
30
+ | `running` | `agentSessionId` | No | Only present once some earlier attempt's runner returned one. |
31
+ | `running` | `runner` | No | The runner name an agent state selected. Absent for the default runner and for script dispatches. |
32
+ | `running` | `runnerKind` | No | The resolved agent runner's `kind`. Absent when it declares none, and for script dispatches. |
30
33
  | `running` | `limitBackoff` | No | Present only while the engine is waiting out a provider usage limit — which probe this is, when the next one fires, and the total waited so far. |
31
34
  | `crashed` | `reason` | Yes | A `CrashReason` — which of the ten shapes below. |
32
35
  | `crashed` | `attempt` | Yes | Which attempt number crashed. |
@@ -57,13 +60,19 @@ of each variant's payload is required too, with one exception:
57
60
  | `usage-limit` | `detail` (required) | The provider's usage limit stayed exhausted until the leaf's wait budget ran out — `detail` is the provider line that matched. |
58
61
  | `timeout` | `elapsedMs` (required) | The dispatch outran its `timeoutMs`. |
59
62
  | `malformed-result` | none | The reply didn't parse as a well-formed `NodeResult`. |
60
- | `validation-failed` | `message` (required) | The state's `validate` returned a rejection string. |
63
+ | `validation-failed` | `message` (required) | An agent leaf's `outputType` failed its shape check, or the state's `validate` returned a rejection string. |
61
64
  | `no-transition` | `state` (required), `event` (optional) | Nothing in `on`/`next` matched the returned event — `event` is absent if the result didn't carry one either. |
62
65
  | `unresolved-target` | `from` (required), `target` (required) | An edge named a state id that doesn't exist anywhere in the workflow. |
63
66
  | `duplicate-id` | `id` (required) | `buildRegistry` found two states sharing an id. |
64
67
  | `max-steps` | `steps` (required), `state` (required) | The engine-wide `maxSteps` backstop tripped. |
65
68
  | `cycle-limit` | `composite` (required), `cycles` (required) | A composite's own `maxCycles` tripped. |
66
69
 
70
+ `validation-failed` nudges before it retries. When a result fails one
71
+ of these checks, the engine keeps the same session alive and sends a
72
+ short corrective prompt quoting `message` — up to three times per leaf
73
+ visit, none costing a retry — and only then falls back to a fresh
74
+ attempt.
75
+
67
76
  A runner that throws, times out, returns something malformed, or fails
68
77
  its state's `validate` hook produces a crash. It never produces a
69
78
  routed transition.
@@ -95,6 +104,12 @@ attempt — retry count untouched — for up to `usageLimitMaxWaitMs`
95
104
  `timeoutMs`: each re-probe starts with a fresh per-attempt budget. At
96
105
  the cap the run ends in a terminal `usage-limit` crash.
97
106
 
107
+ A second exception: the `validation-failed` nudges above consume no
108
+ attempt either. Each nudge resumes the live session with a corrective
109
+ prompt; only when the three-nudge budget runs out does the crash fall
110
+ back to a fresh attempt — the attempt that finally counts against
111
+ `retries`.
112
+
98
113
  **`maxCycles`** (per composite, opt-in) bounds a *multi-leaf loop*: two
99
114
  nodes handing back and forth indefinitely, never tripping any single
100
115
  dispatch's timeout or retry count. Each full pass through the composite
@@ -110,10 +125,11 @@ exhausted and the run ends with a terminal `crashed` status, or a
110
125
  bound still has budget and the *same* leaf is dispatched again from
111
126
  scratch — not resumed. The next attempt's `DispatchInfo.previousFailure`
112
127
  carries what went wrong, so an agent runner can tell the model what to
113
- fix. The usage-limit wait is the one exception to "from scratch": when
114
- the failed attempt left session evidence, the post-wait re-dispatch
115
- resumes that session with a short continuation prompt instead of
116
- replaying the full fresh prompt, so work done before the limit is kept.
128
+ fix. Two exceptions to "from scratch", both resuming session evidence
129
+ instead of replaying the full fresh prompt: the usage-limit wait's
130
+ post-wait re-dispatch sends a short continuation prompt, and a
131
+ `validation-failed` nudge sends a short corrective one quoting
132
+ `message` — so work already done is kept.
117
133
 
118
134
  ## What you observe
119
135
 
@@ -44,7 +44,7 @@ export interface DispatchInfo {
44
44
  validEvents: string[];
45
45
  hasFallback: boolean;
46
46
  attempt: number;
47
- sessionId?: string;
47
+ agentSessionId?: string;
48
48
  previousFailure?: CrashReason;
49
49
  step: number;
50
50
  rootDir: string;
@@ -57,7 +57,7 @@ export interface DispatchInfo {
57
57
  | `validEvents` | Yes | Derived straight from this state's own `on` keys — the events it can route on. |
58
58
  | `hasFallback` | Yes | Whether `next` is also set, meaning the node may omit `event` entirely and still route. |
59
59
  | `attempt` | Yes | Which attempt of this dispatch is in flight — `1` the first time. |
60
- | `sessionId` | No | Only present once a prior attempt's own `NodeResult` returned one. |
60
+ | `agentSessionId` | No | Only present once a prior attempt's own `NodeResult` returned one. |
61
61
  | `previousFailure` | No | Only present on a retry — the [`CrashReason`](../failure-modes/) that rejected the attempt before this one. |
62
62
  | `step` | Yes | The engine's own step counter for this node's current visit, constant across every retry attempt of that visit. |
63
63
  | `rootDir` | Yes | The run's root directory — the base a runner resolves its own `.darkf/run/<runId>/...` paths against. |
@@ -82,7 +82,7 @@ one, or either into a composite's first child.
82
82
  `DispatchInfo` is automatic too. `step`/`attempt`/`runId` are the
83
83
  engine's own bookkeeping. `validEvents`/`hasFallback` are derived
84
84
  straight from that state's own `on`/`next` — nothing to redeclare.
85
- `sessionId`/`previousFailure` only appear once a retry has actually
85
+ `agentSessionId`/`previousFailure` only appear once a retry has actually
86
86
  happened.
87
87
 
88
88
  The gap in between is deliberate. Anything durable for the whole run
@@ -3,8 +3,22 @@ title: Node types
3
3
  description: Every leaf is agent or script, dispatched the same way.
4
4
  ---
5
5
 
6
- A `WorkflowDef` is a plain object. It has one `initial` state and a
7
- `states` map.
6
+ A `WorkflowDef` is a plain object. It has one `initial` state, a
7
+ `states` map, and an optional default `agent` bag.
8
+
9
+ ```ts
10
+ export interface WorkflowDef {
11
+ initial: string;
12
+ states: Record<string, StateDef>;
13
+ agent?: Record<string, unknown>;
14
+ }
15
+ ```
16
+
17
+ | Field | Required | Default | What it does |
18
+ |---|---|---|---|
19
+ | `initial` | Yes | — | The state the run starts in. |
20
+ | `states` | Yes | — | The top-level state map. |
21
+ | `agent` | No | `{}` | Default `agent` bag for agent states on the default runner. A state with no `runner` receives this bag with its own `agent` keys on top. The merge is shallow: each state key replaces the default key. A state that sets `runner` never receives it. Composites have no such field. |
8
22
 
9
23
  Every state is one of three shapes: `agent`, `script`, or `composite`.
10
24
  The first two are leaves — the engine actually dispatches them. The
@@ -17,6 +31,8 @@ export interface AgentStateDef {
17
31
  type: "agent";
18
32
  prompt: string;
19
33
  agent?: Record<string, unknown>;
34
+ runner?: string;
35
+ outputType?: OutputSchema;
20
36
  on?: Record<string, string>;
21
37
  next?: string;
22
38
  retries?: number;
@@ -31,16 +47,18 @@ export interface AgentStateDef {
31
47
  |---|---|---|---|
32
48
  | `type` | Yes | — | `"agent"`. The discriminant — how darkf tells this state apart from a `script` or a `composite`. |
33
49
  | `prompt` | Yes | — | darkf builds the full prompt a runner sees by combining it with the incoming handoff and `validEvents` — computed straight from `on`'s own keys, so there's nothing to keep in sync by hand. |
34
- | `agent` | No | `{}` | An untyped bag core never reads itself. Each runner interprets it its own way: `claudeCodeRunner` reads `model`/`permissionMode`, `opencodeRunner` reads `model`/`auto`. Unset, a runner falls back to its own defaults. |
50
+ | `agent` | No | `{}` | An untyped bag each runner interprets its own way: `claudeCodeRunner` reads `model`/`permissionMode`, `opencodeRunner` reads `model`/`auto`. The engine reads one key itself: the effective bag (after the `WorkflowDef.agent` merge) must hold a non-empty string `model`, whatever the runner, custom runners included. A state without one fails `darkf validate` and run start as `missing-model`. |
51
+ | `runner` | No | the default `agentRunner` | Key into the workflow's `agentRunners` export, selecting the harness for this state. The name is the workflow's own, not the runner's `kind`. An unknown name fails `darkf validate` and run start as `unknown-runner`; it never falls back to the default. See [Pick an agent runner](../../guides/pick-an-agent-runner/). |
35
52
  | `on` | No | — | Routes by the reply's event — `{ approved: "Next" }` means "go to `Next` when the event is `approved`." |
36
53
  | `next` | No | — | Unconditional alternative to `on`: always go there, regardless of what event comes back. Also sets `DispatchInfo.hasFallback`, telling the agent it may omit `event` entirely. |
37
54
  | `retries` | No | `0` | Reattempts of this one dispatch after a crash — a malformed reply, a failed `validate`, a runner throwing. Each retry's prompt includes `DispatchInfo.previousFailure`, naming what went wrong last time. |
38
55
  | `timeoutMs` | No | 1 hour | Ceiling on a single dispatch attempt. Exceeding it is a `timeout` crash, consuming a retry attempt like any other. |
39
56
  | `usageLimitRetryMs` | No | 30 minutes | Interval between re-probes after a dispatch fails on the provider's usage limit. The wait runs outside `timeoutMs` — each re-probe starts with a fresh per-attempt budget — and consumes no retry attempt. |
40
57
  | `usageLimitMaxWaitMs` | No | 24 hours | Total wait budget per node visit for usage-limit backoff. Spending it crashes the run with a `usage-limit` crash — see [Failure modes](../failure-modes/). |
41
- | `validate` | No | — | `(result, handoff) => string \| undefined`, run after the reply already parses as a well-formed `NodeResult`. Return a string to reject it — consuming a retry, exactly like a crash — or `undefined` to accept. |
58
+ | `outputType` | No | — | Shape check on the reply's `output`, run before `validate`. Any object with a `safeParse(value)` method returning `{ success: true }` or `{ success: false, message }` — build one from a Zod schema with `zodOutputType()` (`src/kit/validation/zod.ts`) and import only that built value, never Zod itself. Agent leaves only — an agent's `output` comes from text an LLM wrote, a script's from code you already control. A failure rejects the dispatch exactly like a failed `validate` — see [Failure modes](../failure-modes/). |
59
+ | `validate` | No | — | `(result, handoff) => string \| undefined`, run after the reply already parses as a well-formed `NodeResult` — and after `outputType`, when set. Return a string to reject it as `validation-failed`, or `undefined` to accept. A rejection nudges before it retries — up to three corrective prompts in the live session, none costing a retry — then falls back to a fresh attempt like any crash; see [Failure modes](../failure-modes/). |
42
60
 
43
- Only `prompt` has no default and no fallback behavior — it's the one field a workflow author must always supply. Everything else is safe to omit.
61
+ A workflow author must always supply `prompt`, and a `model` — in the state's own `agent` bag or, for a state with no `runner`, in `WorkflowDef.agent`. Everything else is safe to omit.
44
62
 
45
63
  ## Script
46
64
 
@@ -66,8 +84,8 @@ export interface ScriptStateDef {
66
84
  | `next` | No | — | Same as the agent case: unconditional alternative to `on`. |
67
85
  | `retries` | No | `0` | Reattempts after a crash — the function throwing, returning something malformed, or failing `validate`. Each retry calls the function again from scratch; no conversation to repair, but `DispatchInfo.previousFailure` still carries what went wrong, if the script wants to branch on it. |
68
86
  | `timeoutMs` | No | 1 hour | Same as the agent case — a hang past this is a `timeout` crash. |
69
- | `usageLimitRetryMs` / `usageLimitMaxWaitMs` | No | 30 min / 24 h | Present on both leaf kinds, but only a failure classified as `usage-limit` starts a wait — the built-in agent runners do that classification, and a script's own throws are `runner-error`. A script that calls an LLM itself owns its error handling. |
70
- | `validate` | No | — | Same contract as the agent case. Rarely needed, since a script's own result is usually correct by construction — but useful for confirming a side effect (a file actually got written) before the dispatch counts as done. |
87
+ | `usageLimitRetryMs` / `usageLimitMaxWaitMs` | No | 30 min / 24 h | Present on both leaf kinds, but only a failure classified as `usage-limit` starts a wait — only `opencodeRunner` does that classification (`claudeCodeRunner` does not, so its quota failures are `runner-error`), and a script's own throws are `runner-error`. A script that calls an LLM itself owns its error handling. |
88
+ | `validate` | No | — | Same contract as the agent case, minus the nudging — a script has no session to resume, so a rejection spends a retry attempt directly. Rarely needed, since a script's own result is usually correct by construction — but useful for confirming a side effect (a file actually got written) before the dispatch counts as done. |
71
89
 
72
90
  `type` and `file` are the only two a script state can't do without. Both leaf kinds leave every other field optional.
73
91
 
@@ -101,19 +119,25 @@ a top-level state. `Implement` is nested inside `Fix`. `Review`'s
101
119
  `changes_requested` edge still names `Implement` directly:
102
120
 
103
121
  ```ts
104
- // darkf/workflows/series-ordering/workflow.ts (prompts omitted)
105
- Fix: {
106
- initial: "Implement",
107
- maxCycles: 8,
122
+ // darkf/workflows/series-ordering/workflow.ts (prompts and retries omitted)
123
+ export const workflow: WorkflowDef = {
124
+ initial: "Fix",
125
+ agent: { model: "claude-sonnet-5-5" },
108
126
  states: {
109
- Implement: { type: "agent", on: { implemented: "Verify", blocked: EXIT, disputed: EXIT } },
110
- Verify: { type: "script", file: "verify.ts", on: { green: "Review", red: "Implement" } },
127
+ Fix: {
128
+ initial: "Implement",
129
+ maxCycles: 8,
130
+ states: {
131
+ Implement: { type: "agent", on: { implemented: "Verify", blocked: DONE, disputed: DONE } },
132
+ Verify: { type: "script", file: "verify.ts", on: { green: "Review", red: "Implement" } },
133
+ },
134
+ },
135
+ Review: {
136
+ type: "agent",
137
+ on: { done: DONE, changes_requested: "Implement" },
138
+ },
111
139
  },
112
- },
113
- Review: {
114
- type: "agent",
115
- on: { done: EXIT, changes_requested: "Implement" },
116
- },
140
+ };
117
141
  ```
118
142
 
119
143
  `Review` doesn't name `Fix`. It doesn't need to know `Implement` is
@@ -150,7 +174,7 @@ Both leaf kinds return the same shape:
150
174
  export interface NodeResult {
151
175
  event?: string;
152
176
  output?: unknown;
153
- sessionId?: string;
177
+ agentSessionId?: string;
154
178
  }
155
179
  ```
156
180
 
@@ -158,7 +182,7 @@ export interface NodeResult {
158
182
  |---|---|---|
159
183
  | `event` | No | What `on`/`next` route on. Omit it and only `next` can match. |
160
184
  | `output` | No | This node's payload for whatever node runs next. See [Handoff](../handoff/) for the rule governing it — nothing carries further than one hop unless a node re-emits it. |
161
- | `sessionId` | No | Opaque, runner-native session id, relayed back into `DispatchInfo` on this same node's next retry attempt, so a stateless runner can resume instead of starting cold. core never interprets it. |
185
+ | `agentSessionId` | No | Opaque, runner-native session id, relayed back into `DispatchInfo` on this same node's next retry attempt, so a stateless runner can resume instead of starting cold. core never interprets it. |
162
186
 
163
187
  All three are optional — every field on `NodeResult` carries a `?`. A leaf can return `{}` and still be valid, as long as some edge's `next` is there to catch it.
164
188
 
@@ -3,7 +3,7 @@ title: Pick an agent runner
3
3
  description: The two built-in AgentRunner adapters, and the contract they implement.
4
4
  ---
5
5
 
6
- Any `agent` state needs a workflow-supplied `AgentRunner`:
6
+ Any `agent` state needs a workflow-supplied `AgentRunner` and a model:
7
7
 
8
8
  ```ts
9
9
  export interface AgentRunner {
@@ -12,7 +12,13 @@ export interface AgentRunner {
12
12
  }
13
13
  ```
14
14
 
15
- darkf ships two concrete adapters in @psimona/darkf/src/kit/agents/`.
15
+ darkf ships two concrete adapters in `@psimona/darkf/src/kit/agents/`.
16
+ Both read the model from the state's effective `agent` bag and reject a
17
+ dispatch without one. There is no fallback to the CLI's own default model.
18
+ A model id belongs to its harness: `claude-sonnet-5-5` is a Claude Code id,
19
+ `zai-coding-plan/glm-5.3-flash` an opencode id. `darkf validate` warns about
20
+ an id its runner does not recognize (see [Model warnings](#model-warnings)).
21
+ A run does not check it.
16
22
 
17
23
  ### `claudeCodeRunner`
18
24
 
@@ -20,12 +26,21 @@ Shells out to the `claude` CLI. Builds a prompt from the state's `prompt`,
20
26
  the handoff, and the set of valid events, writes a handoff-file contract
21
27
  the agent is instructed to fill in, and reads that file back as the
22
28
  `NodeResult`. Reuses the CLI's own `session_id` across retries via
23
- `sessionId` so a repair turn resumes context instead of starting cold.
29
+ `agentSessionId` so a repair turn resumes context instead of starting cold.
24
30
 
25
31
  ```ts
32
+ import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
26
33
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
27
34
 
28
35
  export const agentRunner = claudeCodeRunner;
36
+
37
+ export const workflow: WorkflowDef = {
38
+ initial: "Greet",
39
+ agent: { model: "claude-sonnet-5-5" },
40
+ states: {
41
+ Greet: { type: "agent", prompt: "Write a one-sentence greeting.", next: DONE },
42
+ },
43
+ };
29
44
  ```
30
45
 
31
46
  ### `opencodeRunner`
@@ -39,11 +54,113 @@ rather than letting a silently-incomplete turn look like a clean exit with
39
54
  a missing handoff file.
40
55
 
41
56
  ```ts
57
+ import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
42
58
  import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
43
59
 
44
60
  export const agentRunner = opencodeRunner;
61
+
62
+ export const workflow: WorkflowDef = {
63
+ initial: "Greet",
64
+ agent: { model: "zai-coding-plan/glm-5.3-flash" },
65
+ states: {
66
+ Greet: { type: "agent", prompt: "Write a one-sentence greeting.", next: DONE },
67
+ },
68
+ };
45
69
  ```
46
70
 
71
+ ## Per-state selection
72
+
73
+ The `agentRunner` export is the default harness. To run some states on
74
+ another one, register it by name in an `agentRunners` export and set
75
+ `runner` on those states:
76
+
77
+ ```ts
78
+ import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
79
+ import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
80
+ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
81
+
82
+ export const agentRunner = opencodeRunner; // default
83
+ export const agentRunners = { claude: claudeCodeRunner }; // selectable by name
84
+
85
+ export const workflow: WorkflowDef = {
86
+ initial: "plan",
87
+ agent: { model: "zai-coding-plan/glm-5.3-flash", auto: true }, // default
88
+ states: {
89
+ plan: {
90
+ type: "agent",
91
+ runner: "claude",
92
+ agent: { model: "claude-sonnet-5-5" },
93
+ prompt: "Plan the change.",
94
+ next: "build",
95
+ },
96
+ build: {
97
+ type: "agent", // inherits the default runner, model and auto
98
+ prompt: "Implement the plan.",
99
+ next: "review",
100
+ },
101
+ review: {
102
+ type: "agent",
103
+ agent: { model: "zai-coding-plan/glm-5.3" }, // new model, keeps auto
104
+ prompt: "Review the change.",
105
+ next: DONE,
106
+ },
107
+ },
108
+ };
109
+ ```
110
+
111
+ The name is your own key in `agentRunners`, not the runner's `kind`, so you
112
+ can register two configurations of one harness. Only leaf states take
113
+ `runner`; composites pass nothing down.
114
+
115
+ ### Which bag a state receives
116
+
117
+ - No `runner`: `{ ...workflow.agent, ...state.agent }`. The merge is
118
+ shallow, so each state key replaces the default key.
119
+ - `runner` set: the state's own `agent` bag only, even when the named runner
120
+ is the same object as the default. `model`, `auto` and `permissionMode`
121
+ never carry over to another harness, so such a state pins its own `model`.
122
+
123
+ Permission settings differ between the built-in runners.
124
+ `claudeCodeRunner` defaults to `permissionMode: "bypassPermissions"`, while
125
+ `opencodeRunner` approves asks only with `auto: true`. Moving a state to
126
+ another runner can change what its agent may do.
127
+
128
+ ### What fails before any dispatch
129
+
130
+ `darkf validate` and run start both reject:
131
+
132
+ | Error | Cause |
133
+ |---|---|
134
+ | `unknown-runner` | A state names a runner that is not an own key of `agentRunners`. It never falls back to the default. |
135
+ | `missing-runner` | A state names no runner and the workflow has no `agentRunner`. A workflow whose agent states all name one needs no default. |
136
+ | `missing-model` | A state's effective bag has no non-empty string `model`. This applies to custom runners too. |
137
+
138
+ `darkf validate` also fails on an `agentRunner` or `agentRunners` entry with
139
+ no `run` function. If you call `run()` yourself, pass both as
140
+ `RunOptions.agentRunner` and `RunOptions.agentRunners`.
141
+
142
+ ### Model warnings
143
+
144
+ `darkf validate` prints a `warn agent models` line for each state whose model
145
+ its runner does not recognize. The exit code is unchanged.
146
+
147
+ | Runner | Warns when |
148
+ |---|---|
149
+ | `opencodeRunner` | `opencode models` does not list the id (a `#variant` suffix is ignored), or the list cannot be read. |
150
+ | `claudeCodeRunner` | The id is neither a Claude Code alias nor starts with `claude-`. A misspelled `claude-` id passes. |
151
+
152
+ A custom runner opts in with the optional
153
+ `checkModels(models, rootDir)` method, returning `{ model, message }` for each
154
+ id it does not recognize. It must not call a model.
155
+
156
+ ### What a run records
157
+
158
+ Each agent dispatch's `running` status in the journal carries `runner` (the
159
+ selected name, absent for the default) and `runnerKind` (the resolved
160
+ runner's `kind`, absent when it declares none). `darkf report` prints both.
161
+ Session ids stay inside one node visit, and a state keeps its runner for the
162
+ whole visit, so one harness never receives another's session id.
163
+
47
164
  ### Writing your own
48
165
 
49
166
  Both adapters follow the same two moves: build a prompt that includes the
@@ -54,4 +171,5 @@ in core or engine is specific to either shipped adapter.
54
171
 
55
172
  For demos and tests, skip a real harness entirely — a plain object
56
173
  satisfying `AgentRunner` is enough, as the `haiku-readme` example's stub
57
- runner shows (see [Quickstart](../../start-here/quickstart/)).
174
+ runner shows (see [Quickstart](../../start-here/quickstart/)). Its states still
175
+ need a `model` value, such as `agent: { model: "stub" }`.
@@ -42,6 +42,7 @@ export const agentRunner = claudeCodeRunner;
42
42
 
43
43
  export const workflow: WorkflowDef = {
44
44
  initial: "Next",
45
+ agent: { model: "claude-haiku-5-5" },
45
46
  states: {
46
47
  Next: {
47
48
  type: "script",
@@ -71,11 +72,12 @@ handed out, that `Record` hasn't closed out yet" — so a crash between the
71
72
  two is visible as a stuck `in-progress` row, not a silently lost item.
72
73
 
73
74
  This project-level `tasks.json` is the workflow's own durable, committed
74
- queue. It is not the file the OpenCode plugin's tasks tab renders. That tab
75
- reads `.darkf/run/<runId>/tasks.json`, colocated with the run's journal.
76
- If you want the tab, have `Record` write a copy there too — `info.runId`
77
- carries the run id. The plugin is experimental: bundled in this repo, no
78
- public release.
75
+ queue. It is not the file the OpenCode plugin renders. The plugin's runs
76
+ tab reads `.darkf/run/<runId>/tasks.json`, colocated with the run's
77
+ journal, and shows it as the run detail view's task pane once the file
78
+ exists. If you want that pane, have `Record` write a copy there too —
79
+ `info.runId` carries the run id. The plugin is experimental: bundled in
80
+ this repo, no public release.
79
81
 
80
82
  ```ts
81
83
  // scripts/next.ts
@@ -278,10 +280,10 @@ visits: {"Next":3,"Work":2,"Record":2}
278
280
 
279
281
  dispatches:
280
282
  Next 0.0s -> found
281
- Work 20.1s -> done
283
+ Work 20.1s -> done kind=claude-code
282
284
  Record 0.0s -> recorded
283
285
  Next 0.0s -> found
284
- Work 17.8s -> done
286
+ Work 17.8s -> done kind=claude-code
285
287
  Record 0.0s -> recorded
286
288
  Next 0.0s -> empty
287
289
  usage (2 agent dispatches): $0.22, 369441 in (334480 cache-read, 34941 cache-write), 1724 out
@@ -67,9 +67,9 @@ succeeded or crashed.
67
67
  bunx darkf validate my-workflow
68
68
  ```
69
69
 
70
- Checks that the workflow resolves and that `workflow.ts` loads and exports
71
- `workflow` (and `agentRunner`, if any state needs one). For the machine
72
- side, run `bunx darkf doctor`: the `claude` and `opencode` binaries on
70
+ Checks that the workflow resolves, that `workflow.ts` loads and exports
71
+ `workflow`, that the state graph is sound, and that every agent state
72
+ resolves to a runner and a model. For the machine side, run `bunx darkf doctor`: the `claude` and `opencode` binaries on
73
73
  `PATH`, and that you're not accidentally running from inside the darkf
74
74
  checkout itself (a workflow's agent runner uses the invocation `cwd` as
75
75
  its working directory — a common mistake when first wiring a workflow
@@ -51,17 +51,20 @@ bunx darkf run my-workflow
51
51
  ```
52
52
 
53
53
  A workflow module can also export `input` (the seed `NodeResult` for the
54
- first dispatch), `agentRunner` (required if any state is `type: "agent"`),
54
+ first dispatch), `agentRunner` (the default runner, required if any
55
+ `type: "agent"` state names no `runner`), `agentRunners` (runners a state
56
+ selects by name),
55
57
  and `scriptRunner` (optional — only needed if a script needs run-aware
56
58
  `DispatchInfo`, not just the plain handoff).
57
59
 
58
60
  ### Adding an agent state
59
61
 
60
- An `agent` state needs a `prompt` and a configured `agentRunner`:
62
+ An `agent` state needs a `prompt`, a model, and a configured `agentRunner`:
61
63
 
62
64
  ```ts
63
65
  Greet: {
64
66
  type: "agent",
67
+ agent: { model: "claude-haiku-5-5" }, // required: every agent state needs a model
65
68
  prompt: "Write a one-sentence greeting.",
66
69
  on: { done: EXIT },
67
70
  },
@@ -72,7 +75,7 @@ export const agentRunner: AgentRunner = claudeCodeRunner; // or opencodeRunner
72
75
  ```
73
76
 
74
77
  See [Pick an agent runner](../pick-an-agent-runner/) for the two
75
- built-in options.
78
+ built-in options and for choosing a runner per state.
76
79
 
77
80
  ### Branching and retrying
78
81
 
@@ -86,9 +89,15 @@ built-in options.
86
89
  a provider usage limit (defaults: re-probe every 30 minutes, give up
87
90
  after 24 hours). A wait consumes no retry attempt and no `timeoutMs`
88
91
  budget; see [Failure modes](../../concepts/failure-modes/).
92
+ - `outputType` checks the shape of an agent's `output` payload before
93
+ `validate` runs — build one from a Zod schema with `zodOutputType()`
94
+ (`@psimona/darkf/src/kit/validation/zod.ts`); see
95
+ [Node types](../../concepts/node-types/).
89
96
  - `validate(result, handoff)` runs a plain code check against a result
90
- before it's accepted as `succeeded`; returning a string rejects it as a
91
- crash, consuming a retry attempt exactly like a runner throwing would.
97
+ before it's accepted as `succeeded`; returning a string rejects it as
98
+ `validation-failed` — an agent leaf gets up to three corrective nudges
99
+ in its live session before a fresh attempt spends a retry; see
100
+ [Failure modes](../../concepts/failure-modes/).
92
101
 
93
102
  There is no condition-expression or YAML config layer here on purpose — see
94
103
  the repo's `PHILOSOPHY.md` for why. Anything more conditional than a plain
package/docs/index.mdx CHANGED
@@ -35,6 +35,10 @@ and a skill writes the workflow for you — best practices included. Every
35
35
  workflow shows as a diagram, so the whole path stays visible and you
36
36
  stay in control.
37
37
 
38
+ Lights out when a run is clean. Lights on the moment it isn't — the
39
+ same stop-the-line principle (jidoka) a lean factory runs on, applied
40
+ to agent steps.
41
+
38
42
  Start with one workflow. Grow it into your dark factory.
39
43
 
40
44
  <CardGrid>
@@ -18,7 +18,9 @@ anything.
18
18
 
19
19
  ### `darkf run <dir> [message]`
20
20
 
21
- Runs the workflow in-process, blocking until it finishes. `message`
21
+ Runs the workflow in-process, blocking until it finishes. Agent states
22
+ dispatch to the module's `agentRunner` export, or to the `agentRunners`
23
+ entry their `runner` field names. `start` does the same. `message`
22
24
  overrides the workflow module's own `input` export, becoming
23
25
  `{ output: { message } }` for the first dispatch. Prints each dispatch's
24
26
  event, the final status, and the journal path. Writes `.darkf/last-run.mmd`.
@@ -60,9 +62,11 @@ without the run finishing; otherwise the same exit codes as `status`.
60
62
 
61
63
  ### `darkf report [--run <runId>]`
62
64
 
63
- Prints a full dispatch timeline (state, duration, outcome per step), visit
65
+ Prints a full dispatch timeline (state, duration, outcome per step, and
66
+ for an agent dispatch `runner=<name>` and `kind=<runnerKind>`), visit
64
67
  counts, crash reasons, and a token/cost summary if any agent dispatch
65
- wrote a usage sidecar. Works on any resolvable run, finished or not — but,
68
+ wrote a usage sidecar. `runner=` is absent for the default runner, and
69
+ `kind=` for a runner that declares no `kind`. Works on any resolvable run, finished or not — but,
66
70
  like `status`, needs `--run <runId>` once that run is no longer cached as
67
71
  `running`.
68
72
 
@@ -82,9 +86,21 @@ check passes, `1` otherwise.
82
86
  ### `darkf validate <ref>`
83
87
 
84
88
  Workflow checks, no environment: the workflow resolves, `workflow.ts`
85
- loads, it exports `workflow` and (if needed) `agentRunner`, and the state
86
- graph structure validates. Exits `0` if every check passes, `1`
87
- otherwise.
89
+ loads, it exports `workflow`, every `agentRunner` or `agentRunners` entry
90
+ it exports has a `run` function (the `agent runners` check), and the state
91
+ graph structure validates. Structure includes, for each agent state:
92
+
93
+ - its `runner` is a key of `agentRunners`
94
+ - without a `runner`, the module exports `agentRunner`
95
+ - its effective `agent` bag has a non-empty string `model`
96
+
97
+ A runner can also report models it does not recognize, as `warn agent models`
98
+ lines. Warnings never change the exit code. `opencodeRunner` compares against
99
+ `opencode models`; `claudeCodeRunner` only checks that the id is an alias or
100
+ starts with `claude-`.
101
+
102
+ See [Pick an agent runner](../../guides/pick-an-agent-runner/). Exits `0`
103
+ if every check passes, `1` otherwise.
88
104
 
89
105
  ### `darkf setup`
90
106
 
@@ -10,7 +10,7 @@ the repo is built on top of them.
10
10
  export interface NodeResult {
11
11
  event?: string;
12
12
  output?: unknown;
13
- sessionId?: string;
13
+ agentSessionId?: string;
14
14
  }
15
15
 
16
16
  export const EXIT = "[*]" as const;
@@ -19,6 +19,8 @@ export interface AgentStateDef {
19
19
  type: "agent";
20
20
  prompt: string;
21
21
  agent?: Record<string, unknown>;
22
+ runner?: string; // key into the workflow's `agentRunners`; absent: the default `agentRunner`
23
+ outputType?: OutputSchema; // checks result.output, before `validate` runs
22
24
  on?: Record<string, string>;
23
25
  next?: string;
24
26
  retries?: number;
@@ -28,6 +30,10 @@ export interface AgentStateDef {
28
30
  validate?: (result: NodeResult, handoff: NodeResult) => string | undefined;
29
31
  }
30
32
 
33
+ export interface OutputSchema {
34
+ safeParse(value: unknown): { success: true } | { success: false; message: string };
35
+ }
36
+
31
37
  export interface ScriptStateDef {
32
38
  type: "script";
33
39
  file: string;
@@ -51,6 +57,7 @@ export type StateDef = AgentStateDef | ScriptStateDef | CompositeStateDef;
51
57
  export interface WorkflowDef {
52
58
  initial: string;
53
59
  states: Record<string, StateDef>;
60
+ agent?: Record<string, unknown>; // default `agent` bag for states on the default runner
54
61
  }
55
62
 
56
63
  export interface DispatchInfo {
@@ -58,14 +65,22 @@ export interface DispatchInfo {
58
65
  validEvents: string[];
59
66
  hasFallback: boolean;
60
67
  attempt: number;
61
- sessionId?: string;
68
+ agentSessionId?: string;
62
69
  previousFailure?: CrashReason;
63
70
  step: number;
64
71
  rootDir: string;
65
72
  }
66
73
 
74
+ export type AgentRunnerKind = "claude-code" | "opencode" | (string & {});
75
+
76
+ export interface ModelWarning {
77
+ model: string;
78
+ message: string;
79
+ }
80
+
67
81
  export interface AgentRunner {
68
- kind?: string;
82
+ kind?: AgentRunnerKind;
83
+ checkModels?(models: string[], rootDir: string): Promise<ModelWarning[]>; // `darkf validate` only
69
84
  run(id: string, def: AgentStateDef, handoff: NodeResult, info: DispatchInfo): Promise<NodeResult>;
70
85
  }
71
86
 
@@ -75,7 +90,8 @@ export interface ScriptRunner {
75
90
 
76
91
  export type NodeStatus =
77
92
  | { phase: "pending" }
78
- | { phase: "running"; attempt: number; startedAt: number; lastHeartbeat: number; sessionId?: string;
93
+ | { phase: "running"; attempt: number; startedAt: number; lastHeartbeat: number; agentSessionId?: string;
94
+ runner?: string; runnerKind?: AgentRunnerKind;
79
95
  limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number } }
80
96
  | { phase: "succeeded"; result: NodeResult }
81
97
  | { phase: "crashed"; reason: CrashReason; attempt: number };
@@ -114,6 +130,15 @@ export interface RunResult {
114
130
  }
115
131
  ```
116
132
 
133
+ On a `running` agent dispatch, `runner` is the name the state selected
134
+ (absent for the default runner) and `runnerKind` is the resolved runner's
135
+ `kind` (absent when it declares none). Script dispatches carry neither.
136
+
137
+ The runner objects are not part of a `WorkflowDef`. A workflow module
138
+ exports them, and `run()` takes them as `RunOptions.agentRunner` (the
139
+ default) and `RunOptions.agentRunners?: Record<string, AgentRunner>` (the
140
+ ones a state selects by name). `RunOptions` belongs to `engine`.
141
+
117
142
  `NodeEvent` is the journal's own line shape — see [Journal](../../concepts/journal/).
118
143
  `StepTrace` is narrower: one entry per succeeded leaf dispatch, used
119
144
  for routing and debugging rather than the full transition history.