Chef Orchestrator Plugin
Declarative pipeline orchestration for OpenCode multi-agent workflows.
Overview
Chef provides a TypeScript DSL for defining structured workflows that coordinate multiple agents. It leverages OpenCode's SDK capabilities for:
- Message Injection: Pass context between agents via
noReply: true - Structured Output: Automatic JSON schema validation with retries
- State Persistence: SQLite-backed state management
- Fluent API: Chaining syntax for pipeline definitions
- Retry Policies: Configurable retry with exponential backoff
- Timeout Handling: Per-step timeouts with automatic session cleanup
- Reusable Fragments: Composable sub-pipelines via
fragment()and.use() - Pipeline Validation: Startup checks for schemas, agents, and loop targets
- Error Taxonomy: Classified errors for targeted retry and debugging
Installation
The plugin is automatically loaded from .opencode/plugins/chef/ directory.
Dependencies are installed automatically via bun install.
Quick Start
1. Create a Pipeline
Create .opencode/chef/pipelines/feature.ts:
import { pipeline } from "@opencode-ai/chef";
import { z } from "zod";
export default pipeline("feature")
.step("research", {
agent: "researcher",
prompt: "Research the codebase",
output: z.object({
findings: z.string(),
files: z.array(z.string()),
}),
})
.step("plan", {
agent: "planner",
prompt: (ctx) => `Create plan based on: ${ctx.research.findings}`,
output: z.object({
tasks: z.array(z.string()),
}),
})
.build();
2. Start a Pipeline
In OpenCode:
Use the pipeline.start tool:
- name: "feature"
- input: { feature: "dark mode toggle" }
Or say: "Start the feature pipeline to add dark mode toggle"
3. Check Status
Use pipeline.status tool
Pipeline DSL
Steps
Define agent tasks with structured outputs:
.step("name", {
agent: "agent-name",
prompt: "Task description" | ((ctx) => string),
output: z.object({ ... }),
})
Gates
Add approval or validation checkpoints:
.gate("approval", {
agent: "reviewer", // optional
expect: z.object({ approved: z.boolean() }),
})
Conditionals & Loops
Branch based on context:
.when((ctx) => !ctx.approval.approved)
.loop("plan") // loop back to "plan" step
Parallel Execution
Run multiple agents concurrently:
.parallel([
step("review_security", { agent: "security", ... }),
step("review_perf", { agent: "profiler", ... }),
])
Retry Policies
Steps support configurable retry behavior. When a step fails, Chef automatically retries with exponential backoff before marking the step as failed.
Configuration
Add a retry option to any step:
.step("implement", {
agent: "programmer",
prompt: "Implement the feature",
output: z.object({ summary: z.string() }),
retry: {
maxAttempts: 3,
backoffMs: 2000,
retryOn: ["agent_error", "agent_timeout"],
},
})
Fields:
| Field | Type | Default | Description |
|---|---|---|---|
maxAttempts |
number |
1 |
Maximum number of attempts (including the first run) |
backoffMs |
number |
1000 |
Base delay in milliseconds before the first retry |
retryOn |
string[] | undefined |
undefined |
Error types that trigger a retry |
Backoff Behavior
Delays use exponential backoff: backoffMs * 2^attempt. For backoffMs: 2000 with 3 attempts:
- Attempt 1: immediate
- Attempt 2: waits 2000ms
- Attempt 3: waits 4000ms
Filtering Retries by Error Type
The retryOn field controls which errors trigger a retry:
undefined(default): Retry on any error["agent_error", "agent_timeout"]: Only retry on matching error types["all"]: Explicitly retry on all errors
See Error Handling for the full list of error types.
Retry Feedback
On retry, Chef injects the previous error message into the agent's context so it can correct its behavior:
Previous attempt failed with: Step "implement" timed out after 30000ms.
Please correct this and try again.
Timeout Handling
Steps support a timeout option (in milliseconds) that limits how long an agent can run. If the agent exceeds the deadline, the step fails with an AgentTimeoutError.
Usage
.step("review_security", {
agent: "security",
prompt: "Review for security vulnerabilities",
output: z.object({ passed: z.boolean(), findings: z.array(z.string()) }),
timeout: 60000, // 60 seconds
})
When a timeout occurs:
- The timed-out session is automatically deleted (best-effort cleanup)
- The error is classified as
agent_timeout(retryable if configured) - If the step has a retry policy, it may be retried
Combining with Retry
Timeout and retry work together naturally:
.step("analyze", {
agent: "analyst",
prompt: "Analyze the dataset",
output: z.object({ results: z.array(z.string()) }),
timeout: 30000,
retry: {
maxAttempts: 3,
backoffMs: 1000,
retryOn: ["agent_timeout"],
},
})
This retries up to 3 times but only when the agent times out.
Reusable Fragments
Fragments let you define reusable sequences of steps that can be included in multiple pipelines. This avoids duplicating common step definitions.
Defining a Fragment
Use the fragment() function with the step() helper:
import { fragment, step } from "@opencode-ai/chef";
import { z } from "zod";
const reviewFragment = fragment("review", [
step("review_security", {
agent: "security",
prompt: "Review for security vulnerabilities",
output: z.object({
passed: z.boolean(),
findings: z.array(z.string()),
}),
timeout: 60000,
}),
step("review_quality", {
agent: "reviewer",
prompt: (ctx) => `Review code quality for:\n${ctx.implement.summary}`,
output: z.object({
passed: z.boolean(),
feedback: z.array(z.string()),
}),
timeout: 60000,
}),
]);
Including a Fragment
Use the .use() method on a pipeline builder to include all steps from a fragment:
export default pipeline("feature")
.step("research", { ... })
.step("implement", { ... })
.use(reviewFragment) // Adds review_security and review_quality steps
.build();
The .use() method adds each step from the fragment as an individual phase in the pipeline, preserving their order.
Pipeline Validation
Chef validates pipeline definitions at startup when pipelines are loaded from disk. This catches configuration errors early, before any execution begins.
How It Works
When the plugin loads pipeline files, it calls the builder's validate() method automatically. Validation warnings appear in the console:
Chef: Pipeline "feature" has validation errors:
- Gate "approval" onFail target "unknown_step" not found in pipeline
Manual Validation
You can also call validate() explicitly before building:
const builder = pipeline("feature")
.step("research", { ... })
.gate("approval", { ... });
const result = builder.validate();
if (!result.valid) {
for (const err of result.errors) {
console.error(`Validation error: ${err}`);
}
}
const definition = builder.build();
What Gets Validated
| Check | Description |
|---|---|
| Output schema | Each step must have a valid Zod schema (parse is a function) |
| Agent name | Each step must have a non-empty string agent |
| Gate expect schema | Each gate must have a valid Zod schema for expect |
Gate onFail target |
If set, must reference a step that exists earlier in the pipeline |
when loop target |
If set, must reference a step that exists in the pipeline |
when condition |
Must be a function |
| Parallel step schemas | Each parallel sub-step must have valid output and agent |
Agent Name Checks
In addition to structural validation, Chef checks that referenced agent names exist at startup. Unknown agents produce warnings:
Chef: Pipeline "feature" step "research" references unknown agent "unknown_agent"
Error Handling
Chef classifies errors into a taxonomy so that retry policies and debugging can target specific failure modes.
Error Types
| Error Class | Type String | Cause |
|---|---|---|
AgentTimeoutError |
agent_timeout |
Step exceeded its timeout deadline |
AgentError |
agent_error |
Agent returned an error during execution |
GateFailureError |
gate_failure |
Gate validation or agent evaluation failed |
SchemaValidationError |
schema_validation |
Agent output did not match the Zod schema |
MaxIterationsError |
max_iterations |
A loop exceeded the maximum iteration count (default: 10) |
All errors extend ChefError, which carries a type string for programmatic handling.
Error Flow
- A step, gate, or parallel phase throws an error during execution
- The executor catches the error and records it in the phase state
- If the step has a retry policy and the error type matches
retryOn, the step is retried - If all retries are exhausted, the step is marked as
failed - The pipeline status is updated to
failed
Loop Iteration Guard
Loops (via .when() / .loop() or gate onFail) are bounded by a maximum iteration count (default: 10). If a loop exceeds this limit, the pipeline fails with a MaxIterationsError to prevent infinite cycles.
Gate onFail
Gates support an onFail option that creates a loop-back when the gate fails. Instead of failing the entire pipeline, execution jumps back to the specified step.
Usage
.gate("approval", {
agent: "devil",
expect: z.object({
approved: z.boolean(),
feedback: z.string().optional(),
}),
onFail: "plan", // Loop back to "plan" step on failure
})
When the gate fails:
- The gate's phase state is marked as
failed - A warning is logged:
Chef: Gate "approval" failed, looping back to "plan" - Execution resumes at the named step ("plan")
- The loop iteration counter increments
Combining with .when() / .loop()
The onFail option and .when() / .loop() can be used together or independently:
// Gate onFail: automatic loop-back on gate failure
.gate("approval", {
agent: "devil",
expect: z.object({ approved: z.boolean() }),
onFail: "plan",
})
// when/loop: conditional loop based on context
.when((ctx) => !ctx.approval.approved)
.loop("plan")
The onFail handles gate evaluation failures (e.g., the agent returns { approved: false }). The .when() / .loop() handles the conditional branch after a successful gate evaluation that returns a negative result.
Validation
The onFail target is validated at startup. If the target step does not exist in the pipeline, a validation error is reported.
Tools
pipeline.start
Start a new pipeline execution.
Arguments:
name(string): Pipeline nameinput(any, optional): Input data
Returns:
{
"pipeline_id": "uuid",
"status": "running" | "completed" | "failed" | "needs_input",
"context": { ... }
}
pipeline.status
Check pipeline status.
Arguments:
id(string, optional): Pipeline ID (defaults to all running)
pipeline.continue
Continue after needs_input status.
Arguments:
id(string): Pipeline IDinput(any): Input data for next phase
pipeline.abort
Cancel a running pipeline.
Arguments:
id(string): Pipeline ID
pipeline.list
List available pipelines.
Architecture
User → pipeline.start()
↓
Chef Plugin (chef.ts)
↓
Load & Validate Pipelines (builder.ts validate())
↓
Executor (executor.ts)
↓
SDK Client → session.create()
↓
Context Injection → prompt({ noReply: true })
↓
Agent Execution → prompt({ format: { type: "json_schema" } })
↓
Retry/Timeout → exponential backoff + Promise.race
↓
State Persistence → SQLite (store.ts)
Example Pipeline
See pipelines/feature.ts for a complete example with:
- Research phase
- Planning phase
- Approval gate with
onFailloop-back to "plan" - Conditional loop via
.when()/.loop() - Implementation phase with retry policy (3 attempts, filtered to
agent_errorandagent_timeout) - Reusable review fragment via
fragment()and.use() - Per-step timeouts on review steps
Status
Phase 1: Core Infrastructure ✅
- SQLite state management
- Pipeline builder DSL
- Step execution with structured output
- Context injection
- Basic tools (start, status, continue, abort, list)
Phase 2: Execution Engine ✅
- Enhanced error handling (error taxonomy)
- Gate evaluation
- Parallel execution
- Conditional loops
Phase 3: Advanced Features ✅
- Pipeline validation on startup
- Reusable fragments
- Retry policies
- Timeout handling
Development
# Run tests (when available)
bun test
# Type checking
bunx tsc --noEmit
References
- PLAN.md - Design documentation
- PLUGIN_SDK.md - SDK capabilities research