# Chef Orchestrator Plugin - Design Plan > Persistent planning document for the chef orchestrator plugin. --- ## Status **Phase 3 Complete** - Advanced features implemented. --- ## Overview Chef is an orchestrator plugin for opencode that provides a declarative pipeline system for coordinating multiple agents in structured workflows. It leverages the OpenCode SDK's structured output and message injection capabilities for robust agent orchestration. --- ## Architecture ``` ┌─────────────────────────────────────────────────────────────┐ │ ENTRY POINT │ │ (Any Agent) │ │ │ │ User works naturally, says "start pipeline" │ │ Agent calls pipeline tool │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ KERNEL (Plugin) │ │ │ │ Tools: │ │ - pipeline.start(name, input) │ │ - pipeline.status(id?) │ │ - pipeline.continue(id, input) │ │ - pipeline.abort(id) │ │ - pipeline.list() │ │ │ │ Responsibilities: │ │ - Read pipeline definitions (TypeScript DSL) │ │ - Execute phases deterministically │ │ - Call agents via SDK (session.create + prompt) │ │ - Inject context via noReply: true │ │ - Use SDK structured output for validation │ │ - Handle retries (max iterations, policy-based) │ │ - Manage state (SQLite) │ │ - Return "needs_input" status for human questions │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ STORAGE │ │ │ │ .opencode/chef/ │ │ ├── chef.db # SQLite database (WAL mode) │ │ ├── chef.db-wal │ │ └── pipelines/ # Pipeline definitions │ │ ├── feature.ts │ │ └── bugfix.ts │ │ │ │ Schema: │ │ - pipeline_instance (id, status, context, current_phase) │ │ - phase_state (pipeline_id, name, status, output) │ │ - step_state (phase_id, agent, status, output, attempts) │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ PIPELINE DSL (TypeScript + Zod) │ │ │ │ Fluent chaining style with object configs: │ │ - Steps as declarative objects (no side effects) │ │ - Zod schemas for pipeline definition (author-time) │ │ - SDK structured output for runtime validation │ │ - Gates defined with expect() │ │ - Parallel execution via parallel([]) │ │ - Loops via when().loop() │ └─────────────────────────────────────────────────────────────┘ ``` --- ## Design Decisions ### Storage | Decision | Choice | | --------------------- | -------------------------------------------- | | **Database** | SQLite with `bun:sqlite` (built into Bun) | | **Location** | `.opencode/chef/chef.db` | | **Concurrency** | WAL mode for concurrent reads, single writer | | **Schema migrations** | Versioned (schema_version table, sequential) | ### State Schema (Draft) ```typescript interface PipelineInstance { id: string; definition: string; // Pipeline name/path status: PipelineStatus; input: unknown; // Original user input context: unknown; // Accumulated outputs current_phase: number; created_at: number; updated_at: number; } interface PhaseState { id: string; pipeline_id: string; name: string; status: PhaseStatus; output: unknown; error: string | null; attempts: number; started_at: number | null; completed_at: number | null; } ``` ### Pipeline DSL | Decision | Choice | | ------------------- | -------------------------------------------------------------- | | **Style** | Fluent chaining (`.step().gate().when().loop()`) | | **Step definition** | Object config (`{ agent, input, output, expect }`) | | **Gate syntax** | Expect-based (`expect: z.object({ approved: true })`) | | **Validation** | Zod for pipeline definition, SDK structured output for runtime | | **Reusable steps** | Via composable pipeline fragments | ### DSL Syntax (Draft) ```typescript import { gate, parallel, pipeline, step, when } from "@opencode/chef"; import { z } from "zod"; export default pipeline("feature") .step("research", { agent: "researcher", prompt: "Research the codebase", output: z.object({ findings: z.string() }), }) .step("plan", { agent: "planner", prompt: (ctx) => `Create a plan based on: ${ctx.research.findings}`, output: z.object({ tasks: z.array(z.string()) }), }) .gate("approval", { agent: "devil", expect: z.object({ approved: z.boolean() }), }) .when((ctx) => !ctx.approval.approved) .loop("plan") .step("implement", { agent: "programmer", prompt: "Implement the approved plan", }) .parallel([ step("review_security", { agent: "security" }), step("review_perf", { agent: "profiler" }), step("review_code", { agent: "reviewer" }), ]) .gate("all_passed", { check: (ctx) => ctx.review_security.passed && ctx.review_perf.passed && ctx.review_code.passed, }) .step("ship", { agent: "shipper" }); ``` ### Agent Execution Strategy | Aspect | Implementation | | --------------------- | ------------------------------------------------------------ | | **Session Creation** | `client.session.create({ body: { agent, title } })` | | **Context Injection** | `client.session.prompt({ body: { noReply: true, parts } })` | | **Agent Prompting** | `client.session.prompt({ body: { parts, format } })` | | **Output Validation** | SDK structured output with `format: { type: "json_schema" }` | | **Schema Conversion** | Zod → JSON Schema via `zodToJsonSchema()` | | **Error Handling** | SDK automatic retries (retryCount: 2) | ### Error Taxonomy | Failure Type | Recoverable? | Handling | | ------------------------- | ------------ | ------------------------------------ | | Agent timeout | Yes | Retry or fail phase | | Agent error | Maybe | Retry with feedback | | Gate failure | Yes | Loop back to appropriate phase | | Max iterations reached | No | Fail pipeline, escalate | | SDK error | No | Fail immediately (plugin bug) | | User cancellation | No | Abort, preserve state | | Pipeline definition error | No | Fail immediately (caught at startup) | | Agent not found | No | Fail immediately (caught at startup) | ### Pipeline Tools API ```typescript // Start a new pipeline pipeline.start({ name: "feature", input: "Add dark mode toggle", }); // Check status of current/all pipelines pipeline.status(); pipeline.status({ id: "abc-123" }); // Continue after needs_input pipeline.continue({ id: "abc-123", input: { answer: "PostgreSQL" }, }); // Cancel a running pipeline pipeline.abort({ id: "abc-123" }); // List available pipelines pipeline.list(); ``` --- ## Implementation Plan ### Phase 1: Core Infrastructure (Current) - [x] Update PLUGIN_SDK.md with correct capabilities - [x] Update PLAN.md with revised architecture - [x] Create `package.json` with dependencies - [x] Create `store.ts` - SQLite setup and state management - [x] Create `chef.ts` - Plugin entry point with tools - [x] Create `pipeline/builder.ts` - Basic pipeline builder ### Phase 2: Execution Engine - [x] Create `executor.ts` - Step execution logic - [x] Implement context injection via `noReply: true` - [x] Implement structured output with schema conversion - [x] Add error taxonomy (ChefError, AgentTimeoutError, AgentError, GateFailureError, MaxIterationsError, SchemaValidationError) - [x] Add configurable retry policies with exponential backoff - [x] Add session cleanup with try/finally blocks - [x] Add max loop iteration guard (default: 10) - [x] Add per-step timeout with Promise.race ### Phase 3: Advanced Features - [x] Add pipeline validation on startup (agents, schemas, loop targets) - [x] Add builder validate() method for structural validation - [x] Add reusable fragments (fragment() function + use() method) - [x] Add gate onFail loop-back handling - [x] Add abort checking in executor loop ### Phase 4: Polish - [x] Test suite - [x] DSL ergonomics improvements (typed context) - [ ] Documentation improvements --- ## Open Questions ### Resolved - [x] Storage: SQLite with bun:sqlite - [x] DSL style: Fluent chaining - [x] Step definition: Object config - [x] Gate syntax: Expect-based with Zod - [x] Reusable steps: Via pipeline fragments - [x] State location: `.opencode/chef/` - [x] Concurrent pipelines: Supported from day one - [x] Schema validation: Zod for definition, SDK structured output for runtime - [x] Message injection: Works via `noReply: true` - [x] Agent spawning: Works via SDK `session.create()` and `session.prompt()` ### Unresolved - [ ] Parallel result access syntax (by step name? by array?) - [ ] Exact Zod schema for pipeline definition - [ ] How chef agent integrates (if at all) ### Resolved - [x] Reusable step/fragment syntax: fragment() function + use() method - [x] Loop target syntax: by step name - [x] Pipeline validation on startup: validate() + startup check - [x] Parallel result access syntax (by step name? by array?) — resolved: nested context by step name - [x] Exact Zod schema for pipeline definition — resolved: Zod schemas in step definitions --- ## Directory Structure (Planned) ``` .opencode/chef/ ├── package.json # Dependencies (zod, zod-to-json-schema) ├── chef.ts # Main plugin entry point ├── store.ts # SQLite state management ├── executor.ts # Step execution engine ├── pipeline/ │ ├── mod.ts # Pipeline DSL exports │ ├── builder.ts # Pipeline builder │ ├── step.ts # Step definition │ ├── gate.ts # Gate definition │ └── context.ts # Context/interpolation ├── tools/ │ ├── start.ts # Start tool │ ├── status.ts # Status tool │ ├── continue.ts # Continue tool │ ├── abort.ts # Abort tool │ └── list.ts # List tool ├── test/ │ ├── pipeline.test.ts # Pipeline DSL tests │ ├── executor.test.ts # Executor tests │ └── store.test.ts # State tests └── pipelines/ # User pipeline definitions ├── feature.ts └── bugfix.ts ``` --- ## Key Implementation Details ### 1. Context Injection Pattern ```typescript // Inject previous step outputs before prompting agent async function injectContext( sessionId: string, context: any, client: SDKClient, ) { await client.session.prompt({ path: { id: sessionId }, body: { noReply: true, // Don't trigger AI response parts: [ { type: "text", text: `Previous context:\n${JSON.stringify(context, null, 2)}`, }, ], }, }); } ``` ### 2. Structured Output Pattern ```typescript // Convert Zod schema to JSON Schema for SDK import { zodToJsonSchema } from "zod-to-json-schema"; async function executeStep(step: Step, context: any, client: SDKClient) { const jsonSchema = zodToJsonSchema(step.output); const result = await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: step.prompt }], format: { type: "json_schema", schema: jsonSchema, retryCount: 2, }, }, }); // Already validated by SDK! return result.data.info.structured_output; } ``` ### 3. Session Management Pattern ```typescript // Create dedicated session for each step const session = await client.session.create({ body: { title: `Chef: ${step.name}`, agent: step.agent, }, }); try { await injectContext(session.id, context, client); const output = await executeStep(step, context, client); return output; } finally { // Optional: Clean up session await client.session.delete({ path: { id: session.id } }); } ``` --- ## Validated By - **@devil** - Challenged assumptions about LLM self-control, gate enforcement, schema injection - **@architect** - Identified missing specs (error taxonomy, state schema, concurrency, cancellation, observability) - **@simplify** - Challenged complexity (mostly rejected as our use cases require the complexity) - **@researcher** - Confirmed testability (Bun test patterns exist), storage options (bun:sqlite is standard) - **OpenCode SDK Docs** - Validated message injection and structured output capabilities --- ## References - OpenCode SDK Documentation - Structured output and message injection - Temporal.io workflow SDK - Orchestration patterns - Inngest step functions - Step execution model - Mastra workflow DSL - Fluent API design - Zod schema validation - Type-safe pipeline definitions - bun:sqlite documentation - State persistence - zod-to-json-schema - Schema conversion --- _Last updated: 2026-04-01_