# 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`: ```typescript 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: ```typescript .step("name", { agent: "agent-name", prompt: "Task description" | ((ctx) => string), output: z.object({ ... }), }) ``` ### Gates Add approval or validation checkpoints: ```typescript .gate("approval", { agent: "reviewer", // optional expect: z.object({ approved: z.boolean() }), }) ``` ### Conditionals & Loops Branch based on context: ```typescript .when((ctx) => !ctx.approval.approved) .loop("plan") // loop back to "plan" step ``` ### Parallel Execution Run multiple agents concurrently: ```typescript .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: ```typescript .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](#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 ```typescript .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: 1. The timed-out session is automatically deleted (best-effort cleanup) 2. The error is classified as `agent_timeout` (retryable if configured) 3. If the step has a retry policy, it may be retried ### Combining with Retry Timeout and retry work together naturally: ```typescript .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: ```typescript 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: ```typescript 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: ```typescript 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 | | `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 1. A step, gate, or parallel phase throws an error during execution 2. The executor catches the error and records it in the phase state 3. If the step has a retry policy and the error type matches `retryOn`, the step is retried 4. If all retries are exhausted, the step is marked as `failed` 5. 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 ```typescript .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: 1. The gate's phase state is marked as `failed` 2. A warning is logged: `Chef: Gate "approval" failed, looping back to "plan"` 3. Execution resumes at the named step ("plan") 4. The loop iteration counter increments ### Combining with `.when()` / `.loop()` The `onFail` option and `.when()` / `.loop()` can be used together or independently: ```typescript // 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 name - `input` (any, optional): Input data **Returns:** ```json { "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 ID - `input` (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) ↳ schema_version (version tracking) ↳ pipeline_instance ↳ phase_state ``` ## Schema Migrations Chef uses a versioned migration system to manage database schema changes. The `schema_version` table tracks which migrations have been applied. - Migrations run automatically on startup - Each migration has a version number, description, and array of SQL statements - Only migrations newer than the current version are applied - Applied migrations are logged: `Chef: Applied schema migration v2: Remove unused step_state table` Current schema version: **2** (removed unused `step_state` table from initial schema). ## Example Pipeline See `pipelines/feature.ts` for a complete example with: - Research phase - Planning phase - Approval gate with `onFail` loop-back to "plan" - Conditional loop via `.when()` / `.loop()` - Implementation phase with retry policy (3 attempts, filtered to `agent_error` and `agent_timeout`) - Reusable review fragment via `fragment()` and `.use()` - Per-step timeouts on review steps ## Status **Phase 1: Core Infrastructure** ✅ - [x] SQLite state management - [x] Pipeline builder DSL - [x] Step execution with structured output - [x] Context injection - [x] Basic tools (start, status, continue, abort, list) **Phase 2: Execution Engine** ✅ - [x] Enhanced error handling (error taxonomy) - [x] Gate evaluation - [x] Parallel execution - [x] Conditional loops **Phase 3: Advanced Features** ✅ - [x] Pipeline validation on startup - [x] Reusable fragments - [x] Retry policies - [x] Timeout handling ## Development ```bash # Run tests bun test # Type checking bunx tsc --noEmit ``` ## References - [PLAN.md](./PLAN.md) - Design documentation - [PLUGIN_SDK.md](./PLUGIN_SDK.md) - SDK capabilities research