repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(chef): fix bugs and implement Phase 2+3 features

f276f22b23c6ae2dd37941d395d8e69f7f81daaf

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Bug fixes:
- Fix missing GateDefinition import in executor.ts
- Fix updatePipeline parameter order swap (id/Date.now() reversed)
- Fix listPipelines .all() call for bun:sqlite typing
- Fix step() helper to properly return name field
- Add key injection protection for all store update methods

Phase 2 - Execution Engine:
- Add error taxonomy (ChefError, AgentTimeoutError, AgentError, GateFailureError, MaxIterationsError, SchemaValidationError)
- Add configurable retry policies with exponential backoff
- Add per-step timeout handling via Promise.race
- Add session cleanup in finally blocks
- Add max loop iteration guard (default: 10)
- Add abort checking in executor loop
- Add error feedback injection on retry
- Add ParallelDefinition/WhenDefinition imports

Phase 3 - Advanced Features:
- Add pipeline validation on startup (agents, schemas, loop targets)
- Add builder validate() method for structural validation
- Add reusable fragments (fragment() function + use() method)
- Add gate onFail loop-back handling
- Add database indexes for performance
- Fix pipeline loading to handle both builder and definition exports

Also updated: PLAN.md, README.md, package.json (added glob dependency)

Changed files (9)

opencode/plugins/chef/PLAN.md

Added
new file mode 100644
1 +# Chef Orchestrator Plugin - Design Plan
3 +> Persistent planning document for the chef orchestrator plugin.
5 +---
7 +## Status
9 +**Phase 3 Complete** - Advanced features implemented.
11 +---
13 +## Overview
15 +Chef is an orchestrator plugin for opencode that provides a declarative pipeline
16 +system for coordinating multiple agents in structured workflows. It leverages
17 +the OpenCode SDK's structured output and message injection capabilities for
18 +robust agent orchestration.
20 +---
22 +## Architecture
24 +```
25 +┌─────────────────────────────────────────────────────────────┐
26 +│ ENTRY POINT │
27 +│ (Any Agent) │
28 +│ │
29 +│ User works naturally, says "start pipeline" │
30 +│ Agent calls pipeline tool │
31 +└─────────────────────────────────────────────────────────────┘
32 + │
33 + ▼
34 +┌─────────────────────────────────────────────────────────────┐
35 +│ KERNEL (Plugin) │
36 +│ │
37 +│ Tools: │
38 +│ - pipeline.start(name, input) │
39 +│ - pipeline.status(id?) │
40 +│ - pipeline.continue(id, input) │
41 +│ - pipeline.abort(id) │
42 +│ - pipeline.list() │
43 +│ │
44 +│ Responsibilities: │
45 +│ - Read pipeline definitions (TypeScript DSL) │
46 +│ - Execute phases deterministically │
47 +│ - Call agents via SDK (session.create + prompt) │
48 +│ - Inject context via noReply: true │
49 +│ - Use SDK structured output for validation │
50 +│ - Handle retries (max iterations, policy-based) │
51 +│ - Manage state (SQLite) │
52 +│ - Return "needs_input" status for human questions │
53 +└─────────────────────────────────────────────────────────────┘
54 + │
55 + ▼
56 +┌─────────────────────────────────────────────────────────────┐
57 +│ STORAGE │
58 +│ │
59 +│ .opencode/chef/ │
60 +│ ├── chef.db # SQLite database (WAL mode) │
61 +│ ├── chef.db-wal │
62 +│ └── pipelines/ # Pipeline definitions │
63 +│ ├── feature.ts │
64 +│ └── bugfix.ts │
65 +│ │
66 +│ Schema: │
67 +│ - pipeline_instance (id, status, context, current_phase) │
68 +│ - phase_state (pipeline_id, name, status, output) │
69 +│ - step_state (phase_id, agent, status, output, attempts) │
70 +└─────────────────────────────────────────────────────────────┘
71 + │
72 + ▼
73 +┌─────────────────────────────────────────────────────────────┐
74 +│ PIPELINE DSL (TypeScript + Zod) │
75 +│ │
76 +│ Fluent chaining style with object configs: │
77 +│ - Steps as declarative objects (no side effects) │
78 +│ - Zod schemas for pipeline definition (author-time) │
79 +│ - SDK structured output for runtime validation │
80 +│ - Gates defined with expect() │
81 +│ - Parallel execution via parallel([]) │
82 +│ - Loops via when().loop() │
83 +└─────────────────────────────────────────────────────────────┘
84 +```
86 +---
88 +## Design Decisions
90 +### Storage
92 +| Decision | Choice |
93 +| --------------------- | -------------------------------------------- |
94 +| **Database** | SQLite with `bun:sqlite` (built into Bun) |
95 +| **Location** | `.opencode/chef/chef.db` |
96 +| **Concurrency** | WAL mode for concurrent reads, single writer |
97 +| **Schema migrations** | Manual (simple schema, can evolve later) |
99 +### State Schema (Draft)
101 +```typescript
102 +interface PipelineInstance {
103 + id: string;
104 + definition: string; // Pipeline name/path
105 + status: PipelineStatus;
106 + input: unknown; // Original user input
107 + context: unknown; // Accumulated outputs
108 + current_phase: number;
109 + created_at: number;
110 + updated_at: number;
113 +interface PhaseState {
114 + id: string;
115 + pipeline_id: string;
116 + name: string;
117 + status: PhaseStatus;
118 + output: unknown;
119 + error: string | null;
120 + attempts: number;
121 + started_at: number | null;
122 + completed_at: number | null;
125 +interface StepState {
126 + id: string;
127 + phase_id: string;
128 + name: string;
129 + agent: string;
130 + status: StepStatus;
131 + output: unknown;
132 + error: string | null;
133 + attempts: number;
135 +```
137 +### Pipeline DSL
139 +| Decision | Choice |
140 +| ------------------- | -------------------------------------------------------------- |
141 +| **Style** | Fluent chaining (`.step().gate().when().loop()`) |
142 +| **Step definition** | Object config (`{ agent, input, output, expect }`) |
143 +| **Gate syntax** | Expect-based (`expect: z.object({ approved: true })`) |
144 +| **Validation** | Zod for pipeline definition, SDK structured output for runtime |
145 +| **Reusable steps** | Via composable pipeline fragments |
147 +### DSL Syntax (Draft)
149 +```typescript
150 +import { gate, parallel, pipeline, step, when } from "@opencode/chef";
151 +import { z } from "zod";
153 +export default pipeline("feature")
154 + .step("research", {
155 + agent: "researcher",
156 + prompt: "Research the codebase",
157 + output: z.object({ findings: z.string() }),
158 + })
159 + .step("plan", {
160 + agent: "planner",
161 + prompt: (ctx) => `Create a plan based on: ${ctx.research.findings}`,
162 + output: z.object({ tasks: z.array(z.string()) }),
163 + })
164 + .gate("approval", {
165 + agent: "devil",
166 + expect: z.object({ approved: z.boolean() }),
167 + })
168 + .when((ctx) => !ctx.approval.approved)
169 + .loop("plan")
170 + .step("implement", {
171 + agent: "programmer",
172 + prompt: "Implement the approved plan",
173 + })
174 + .parallel([
175 + step("review_security", { agent: "security" }),
176 + step("review_perf", { agent: "profiler" }),
177 + step("review_code", { agent: "reviewer" }),
178 + ])
179 + .gate("all_passed", {
180 + check: (ctx) =>
181 + ctx.review_security.passed &&
182 + ctx.review_perf.passed &&
183 + ctx.review_code.passed,
184 + })
185 + .step("ship", { agent: "shipper" });
186 +```
188 +### Agent Execution Strategy
190 +| Aspect | Implementation |
191 +| --------------------- | ------------------------------------------------------------ |
192 +| **Session Creation** | `client.session.create({ body: { agent, title } })` |
193 +| **Context Injection** | `client.session.prompt({ body: { noReply: true, parts } })` |
194 +| **Agent Prompting** | `client.session.prompt({ body: { parts, format } })` |
195 +| **Output Validation** | SDK structured output with `format: { type: "json_schema" }` |
196 +| **Schema Conversion** | Zod → JSON Schema via `zodToJsonSchema()` |
197 +| **Error Handling** | SDK automatic retries (retryCount: 2) |
199 +### Error Taxonomy
201 +| Failure Type | Recoverable? | Handling |
202 +| ------------------------- | ------------ | ------------------------------------ |
203 +| Agent timeout | Yes | Retry or fail phase |
204 +| Agent error | Maybe | Retry with feedback |
205 +| Schema validation failure | Yes | SDK auto-retries (retryCount: 2) |
206 +| Gate failure | Yes | Loop back to appropriate phase |
207 +| Max iterations reached | No | Fail pipeline, escalate |
208 +| SDK error | No | Fail immediately (plugin bug) |
209 +| User cancellation | No | Abort, preserve state |
210 +| Pipeline definition error | No | Fail immediately (caught at startup) |
211 +| Agent not found | No | Fail immediately (caught at startup) |
213 +### Pipeline Tools API
215 +```typescript
216 +// Start a new pipeline
217 +pipeline.start({
218 + name: "feature",
219 + input: "Add dark mode toggle",
220 +});
222 +// Check status of current/all pipelines
223 +pipeline.status();
224 +pipeline.status({ id: "abc-123" });
226 +// Continue after needs_input
227 +pipeline.continue({
228 + id: "abc-123",
229 + input: { answer: "PostgreSQL" },
230 +});
232 +// Cancel a running pipeline
233 +pipeline.abort({ id: "abc-123" });
235 +// List available pipelines
236 +pipeline.list();
237 +```
239 +---
241 +## Implementation Plan
243 +### Phase 1: Core Infrastructure (Current)
245 +- [x] Update PLUGIN_SDK.md with correct capabilities
246 +- [x] Update PLAN.md with revised architecture
247 +- [x] Create `package.json` with dependencies
248 +- [x] Create `store.ts` - SQLite setup and state management
249 +- [x] Create `chef.ts` - Plugin entry point with tools
250 +- [x] Create `pipeline/builder.ts` - Basic pipeline builder
252 +### Phase 2: Execution Engine
254 +- [x] Create `executor.ts` - Step execution logic
255 +- [x] Implement context injection via `noReply: true`
256 +- [x] Implement structured output with schema conversion
257 +- [x] Add error taxonomy (ChefError, AgentTimeoutError, AgentError,
258 + GateFailureError, MaxIterationsError, SchemaValidationError)
259 +- [x] Add configurable retry policies with exponential backoff
260 +- [x] Add session cleanup with try/finally blocks
261 +- [x] Add max loop iteration guard (default: 10)
262 +- [x] Add per-step timeout with Promise.race
264 +### Phase 3: Advanced Features
266 +- [x] Add pipeline validation on startup (agents, schemas, loop targets)
267 +- [x] Add builder validate() method for structural validation
268 +- [x] Add reusable fragments (fragment() function + use() method)
269 +- [x] Add gate onFail loop-back handling
270 +- [x] Add abort checking in executor loop
272 +### Phase 4: Polish
274 +- [ ] Test suite
275 +- [ ] DSL ergonomics improvements (typed context)
276 +- [ ] Documentation improvements
278 +---
280 +## Open Questions
282 +### Resolved
284 +- [x] Storage: SQLite with bun:sqlite
285 +- [x] DSL style: Fluent chaining
286 +- [x] Step definition: Object config
287 +- [x] Gate syntax: Expect-based with Zod
288 +- [x] Reusable steps: Via pipeline fragments
289 +- [x] State location: `.opencode/chef/`
290 +- [x] Concurrent pipelines: Supported from day one
291 +- [x] Schema validation: Zod for definition, SDK structured output for runtime
292 +- [x] Message injection: Works via `noReply: true`
293 +- [x] Agent spawning: Works via SDK `session.create()` and `session.prompt()`
295 +### Unresolved
297 +- [ ] Parallel result access syntax (by step name? by array?)
298 +- [ ] Exact Zod schema for pipeline definition
299 +- [ ] How chef agent integrates (if at all)
301 +### Resolved
303 +- [x] Reusable step/fragment syntax: fragment() function + use() method
304 +- [x] Loop target syntax: by step name
305 +- [x] Pipeline validation on startup: validate() + startup check
307 +---
309 +## Directory Structure (Planned)
311 +```
312 +.opencode/chef/
313 +├── package.json # Dependencies (zod, zod-to-json-schema)
314 +├── chef.ts # Main plugin entry point
315 +├── store.ts # SQLite state management
316 +├── executor.ts # Step execution engine
317 +├── pipeline/
318 +│ ├── mod.ts # Pipeline DSL exports
319 +│ ├── builder.ts # Pipeline builder
320 +│ ├── step.ts # Step definition
321 +│ ├── gate.ts # Gate definition
322 +│ └── context.ts # Context/interpolation
323 +├── tools/
324 +│ ├── start.ts # Start tool
325 +│ ├── status.ts # Status tool
326 +│ ├── continue.ts # Continue tool
327 +│ ├── abort.ts # Abort tool
328 +│ └── list.ts # List tool
329 +├── test/
330 +│ ├── pipeline.test.ts # Pipeline DSL tests
331 +│ ├── executor.test.ts # Executor tests
332 +│ └── store.test.ts # State tests
333 +└── pipelines/ # User pipeline definitions
334 + ├── feature.ts
335 + └── bugfix.ts
336 +```
338 +---
340 +## Key Implementation Details
342 +### 1. Context Injection Pattern
344 +```typescript
345 +// Inject previous step outputs before prompting agent
346 +async function injectContext(
347 + sessionId: string,
348 + context: any,
349 + client: SDKClient,
350 +) {
351 + await client.session.prompt({
352 + path: { id: sessionId },
353 + body: {
354 + noReply: true, // Don't trigger AI response
355 + parts: [
357 + type: "text",
358 + text: `Previous context:\n${JSON.stringify(context, null, 2)}`,
359 + },
360 + ],
361 + },
362 + });
364 +```
366 +### 2. Structured Output Pattern
368 +```typescript
369 +// Convert Zod schema to JSON Schema for SDK
370 +import { zodToJsonSchema } from "zod-to-json-schema";
372 +async function executeStep(step: Step, context: any, client: SDKClient) {
373 + const jsonSchema = zodToJsonSchema(step.output);
375 + const result = await client.session.prompt({
376 + path: { id: sessionId },
377 + body: {
378 + parts: [{ type: "text", text: step.prompt }],
379 + format: {
380 + type: "json_schema",
381 + schema: jsonSchema,
382 + retryCount: 2,
383 + },
384 + },
385 + });
387 + // Already validated by SDK!
388 + return result.data.info.structured_output;
390 +```
392 +### 3. Session Management Pattern
394 +```typescript
395 +// Create dedicated session for each step
396 +const session = await client.session.create({
397 + body: {
398 + title: `Chef: ${step.name}`,
399 + agent: step.agent,
400 + },
401 +});
403 +try {
404 + await injectContext(session.id, context, client);
405 + const output = await executeStep(step, context, client);
406 + return output;
407 +} finally {
408 + // Optional: Clean up session
409 + await client.session.delete({ path: { id: session.id } });
411 +```
413 +---
415 +## Validated By
417 +- **@devil** - Challenged assumptions about LLM self-control, gate enforcement,
418 + schema injection
419 +- **@architect** - Identified missing specs (error taxonomy, state schema,
420 + concurrency, cancellation, observability)
421 +- **@simplify** - Challenged complexity (mostly rejected as our use cases
422 + require the complexity)
423 +- **@researcher** - Confirmed testability (Bun test patterns exist), storage
424 + options (bun:sqlite is standard)
425 +- **OpenCode SDK Docs** - Validated message injection and structured output
426 + capabilities
428 +---
430 +## References
432 +- OpenCode SDK Documentation - Structured output and message injection
433 +- Temporal.io workflow SDK - Orchestration patterns
434 +- Inngest step functions - Step execution model
435 +- Mastra workflow DSL - Fluent API design
436 +- Zod schema validation - Type-safe pipeline definitions
437 +- bun:sqlite documentation - State persistence
438 +- zod-to-json-schema - Schema conversion
440 +---
442 +_Last updated: 2026-03-31_

opencode/plugins/chef/PLUGIN_SDK.md

Added
new file mode 100644
1 +# OpenCode Plugin SDK - Research Findings
3 +> Compiled from official docs, source code analysis, ecosystem plugins, and GitHub issues.
5 +---
7 +## Overview
9 +Plugins are JavaScript/TypeScript modules that hook into OpenCode events, add custom tools, and modify behavior. They run within the OpenCode process and have access to a rich context API.
11 +---
13 +## Plugin Location
15 +- **Global**: `~/.config/opencode/plugins/` or `~/.config/opencode/plugin/`
16 +- **Project**: `.opencode/plugins/` or `.opencode/plugin/`
18 +Both locations work. Load order:
20 +1. Global config (`~/.config/opencode/opencode.json`)
21 +2. Project config (`opencode.json`)
22 +3. Global plugin directory
23 +4. Project plugin directory
25 +---
27 +## Basic Structure
29 +```typescript
30 +import type { Plugin } from "@opencode-ai/plugin";
32 +export const MyPlugin: Plugin = async (
33 + { client, project, directory, worktree, $ },
34 +) => {
35 + console.log("Plugin initialized!");
37 + return {
38 + // Hooks go here
39 + };
40 +};
41 +```
43 +### Context Parameters
45 +| Parameter | Type | Description |
46 +| ----------- | ---------- | ---------------------------------------- |
47 +| `client` | SDK Client | OpenCode SDK for AI/session interactions |
48 +| `project` | Project | Current project info `{ id, worktree }` |
49 +| `directory` | string | Current working directory |
50 +| `worktree` | string | Git worktree root |
51 +| `$` | Bun Shell | Bun's shell API for commands |
52 +| `serverUrl` | URL | Server URL (internal) |
54 +---
56 +## Available Hooks
58 +### Event Hook (General)
60 +```typescript
61 +event: (async ({ event }) => {
62 + console.log("Event:", event.type);
63 +});
64 +```
66 +**Session Events:**
68 +- `session.created` - New session started
69 +- `session.updated` - Session updated
70 +- `session.deleted` - Session deleted
71 +- `session.error` - Session error occurred
72 +- `session.idle` - Session became idle
73 +- `session.status` - Session status changed
74 +- `session.compacted` - Session was compacted
75 +- `session.diff` - Session diff occurred
77 +**Message Events:**
79 +- `message.updated` - Message updated
80 +- `message.removed` - Message removed
81 +- `message.part.updated` - Message part updated
82 +- `message.part.removed` - Message part removed
84 +**Tool Events:**
86 +- `tool.execute.before` - Before tool execution
87 +- `tool.execute.after` - After tool execution
89 +**File Events:**
91 +- `file.edited` - File edited
92 +- `file.watcher.updated` - File watcher updated
94 +**Permission Events:**
96 +- `permission.asked` - Permission requested
97 +- `permission.replied` - Permission answered
99 +**Other Events:**
101 +- `command.executed` - Command executed
102 +- `installation.updated` - Installation updated
103 +- `lsp.client.diagnostics` - LSP diagnostics
104 +- `lsp.updated` - LSP updated
105 +- `server.connected` - Server connected
106 +- `todo.updated` - Todo updated
107 +- `tui.prompt.append` - Prompt appended
108 +- `tui.command.execute` - Command executed
109 +- `tui.toast.show` - Toast shown
110 +- `shell.env` - Shell environment
112 +### Tool Execution Hooks
114 +```typescript
115 +"tool.execute.before": async (input, output) => {
116 + // input: { tool, args, sessionID, callID }
117 + // output: { args } - can modify args
118 + if (input.tool === "bash" && output.args.command.includes("rm -rf")) {
119 + throw new Error("Dangerous command blocked")
123 +"tool.execute.after": async (input, output) => {
124 + // input: { tool, args, sessionID, callID }
125 + // output: { title, output, metadata }
126 + console.log(`Tool ${input.tool} completed:`, output.output)
128 +```
130 +### Chat/Message Hooks
132 +```typescript
133 +"chat.message": async (input, output) => {
134 + // input: { message, parts }
135 + // output: { message } - can modify
138 +"chat.params": async (input, output) => {
139 + // Modify LLM params before sending
140 + output.temperature = 0.7
141 + output.topP = 0.9
143 +```
145 +### Experimental Hooks
147 +```typescript
148 +"experimental.chat.system.transform": async (input, output) => {
149 + // Inject into system prompt
150 + output.system.push(`<custom-context>...</custom-context>`)
153 +"experimental.session.compacting": async (input, output) => {
154 + // Customize compaction context
155 + output.context.push(`## State\nTask progress: 75%`)
156 + // Or replace entirely:
157 + // output.prompt = "Custom prompt..."
159 +```
161 +### Permission Hook
163 +```typescript
164 +"permission.ask": async (perm, output) => {
165 + // output: { status: 'allow' | 'deny' }
166 + if (perm.type === "read_file" && perm.path.includes(".env")) {
167 + output.status = "deny"
170 +```
172 +### Configuration Hook
174 +```typescript
175 +config: (async (config) => {
176 + // Modify config before it's applied
177 + config.model = "anthropic/claude-3-5-sonnet";
178 +});
179 +```
181 +---
183 +## Custom Tools
185 +```typescript
186 +import { type Plugin, tool } from "@opencode-ai/plugin";
188 +export const MyPlugin: Plugin = async (ctx) => {
189 + return {
190 + tool: {
191 + myTool: tool({
192 + description: "Does something useful",
193 + args: {
194 + input: tool.schema.string().describe("Input text"),
195 + count: tool.schema.number().optional().describe("Count"),
196 + },
197 + async execute(args, context) {
198 + // context: { sessionID, messageID, agent, directory, worktree, abort }
199 + return `Processed: ${args.input}`;
200 + },
201 + }),
202 + },
203 + };
205 +```
207 +### Tool Schema (Zod)
209 +`tool.schema` is Zod. All Zod types are available:
211 +- `tool.schema.string()`, `.number()`, `.boolean()`, `.array()`, `.object()`
212 +- `.describe()`, `.optional()`, `.default()`, `.min()`, `.max()`
214 +---
216 +## SDK Client Capabilities
218 +```typescript
219 +const { client } = await createOpencode();
220 +// or from plugin context
221 +await client.session.prompt({
222 + path: { id: sessionId },
223 + body: { parts: [{ type: "text", text: "Hello" }] },
224 +});
225 +```
227 +### Key SDK Methods
229 +| Method | Description |
230 +| --------------------------- | ------------------------- |
231 +| `client.session.create()` | Create new session |
232 +| `client.session.get()` | Get session by ID |
233 +| `client.session.list()` | List sessions |
234 +| `client.session.prompt()` | Send prompt to session |
235 +| `client.session.abort()` | Abort session |
236 +| `client.session.messages()` | Get session messages |
237 +| `client.app.agents()` | List available agents |
238 +| `client.app.log()` | Write log entry |
239 +| `client.event.subscribe()` | Subscribe to events (SSE) |
240 +| `client.file.read()` | Read file |
241 +| `client.find.text()` | Search text |
242 +| `client.tui.showToast()` | Show toast |
244 +### ✅ Message Injection (WORKS!)
246 +**Updated: This DOES work via `noReply: true`**
248 +You CAN inject AI-visible messages into sessions:
250 +```typescript
251 +// Inject context without triggering AI response
252 +await client.session.prompt({
253 + path: { id: sessionId },
254 + body: {
255 + noReply: true, // ← Injects message, no AI response
256 + parts: [{
257 + type: "text",
258 + text: "Context: Previous step completed with findings..."
259 + }],
260 + },
262 +```
264 +This is perfect for multi-agent orchestration - inject context from previous steps before prompting agent.
266 +### ✅ Structured Output (BUILT-IN!)
268 +The SDK supports native JSON schema validation with automatic retries:
270 +```typescript
271 +const result = await client.session.prompt({
272 + path: { id: sessionId },
273 + body: {
274 + parts: [{ type: "text", text: "Research the codebase and extract data" }],
275 + format: {
276 + type: "json_schema",
277 + schema: {
278 + type: "object",
279 + properties: {
280 + findings: { type: "string", description: "Research findings" },
281 + files: { type: "array", items: { type: "string" } },
282 + },
283 + required: ["findings", "files"],
284 + },
285 + retryCount: 2, // Auto-retry on validation failure
286 + },
287 + },
290 +// Already validated! No manual parsing needed
291 +const output = result.data.info.structured_output
292 +// output.findings: string
293 +// output.files: string[]
294 +```
296 +**Benefits:**
297 +- LLM is instructed to generate valid JSON matching schema
298 +- Automatic validation and retries
299 +- No manual parsing or Zod validation needed at runtime
300 +- Type-safe output
302 +**For Chef Plugin:** Convert Zod schemas to JSON Schema using `zodToJsonSchema` library, then pass to SDK.
304 +### Additional SDK Methods (Updated)
306 +**File Operations:**
307 +- `client.find.files({ query: { query, type, directory, limit } })` - Find files by pattern
308 +- `client.file.status({ query? })` - Get file status
310 +**TUI Control:**
311 +- `client.tui.appendPrompt({ body: { text } })` - Append to prompt
312 +- `client.tui.submitPrompt()` - Submit current prompt
313 +- `client.tui.clearPrompt()` - Clear prompt
314 +- `client.tui.executeCommand({ body })` - Execute command
316 +**Project/Config:**
317 +- `client.project.list()` - List all projects
318 +- `client.project.current()` - Get current project
319 +- `client.path.get()` - Get current path
320 +- `client.config.get()` - Get config info
321 +- `client.config.providers()` - List providers and models
323 +**Session Management:**
324 +- `client.session.children({ path })` - List child sessions
325 +- `client.session.update({ path, body })` - Update session properties
326 +- `client.session.init({ path, body })` - Initialize session with app analysis
327 +- `client.session.share({ path })` / `unshare({ path })` - Share sessions
328 +- `client.session.summarize({ path, body })` - Summarize session
329 +- `client.session.command({ path, body })` - Send command
330 +- `client.session.shell({ path, body })` - Run shell command
331 +- `client.session.revert({ path, body })` / `unrevert({ path })` - Revert messages
333 +**Auth & Global:**
334 +- `client.auth.set({ path, body })` - Set authentication credentials
335 +- `client.global.health()` - Health check
337 +---
339 +## Critical Limitations
341 +### 1. Event Handlers Are Fire-and-Forget
343 +The `event` hook does NOT wait for async operations:
345 +```typescript
346 +// From source: plugin/index.ts L138
347 +hook["event"]?.({ event: input }); // return value dropped
348 +```
350 +**Workaround**: Use `session.stopping` (being added per issue #16626) or external processes.
352 +### 2. ~~No Message Injection~~ ✅ WORKS NOW
354 +~~You cannot inject AI-visible messages from plugins. Issue #17412 tracks this.~~
356 +**UPDATED**: Message injection WORKS via `noReply: true` parameter in `session.prompt()`.
358 +### 3. No Session Continuation
360 +`session.idle` fires AFTER the agent loop breaks. Cannot keep agent running.
362 +### 4. Subagent Hooks Don't Work
364 +`tool.execute.before/after` don't intercept subagent (task tool) calls. Security issue #5894.
366 +### 5. ~~No Native Agent Spawning~~ ✅ WORKS NOW
368 +~~Plugins cannot spawn agents or sessions programmatically in a blocking way.~~
370 +**UPDATED**: Plugins CAN create sessions and prompt agents using the SDK client.
372 +---
374 +## Storage Patterns
376 +Plugins have no built-in state persistence. Options:
378 +### 1. File-Based
380 +```typescript
381 +import { $ } from "@opencode-ai/plugin";
382 +import { readFileSync, writeFileSync } from "fs";
384 +const stateFile = join(directory, ".opencode/chef/state.json");
386 +function loadState() {
387 + try {
388 + return JSON.parse(readFileSync(stateFile, "utf-8"));
389 + } catch {
390 + return { pipelines: [] };
394 +function saveState(state) {
395 + writeFileSync(stateFile, JSON.stringify(state, null, 2));
397 +```
399 +### 2. SQLite with bun:sqlite
401 +```typescript
402 +import { Database } from "bun:sqlite";
404 +const db = new Database(join(directory, ".opencode/chef/chef.db"));
405 +db.run("CREATE TABLE IF NOT EXISTS pipeline (...)");
406 +```
408 +**Note**: Need `package.json` in config dir for external deps.
410 +---
412 +## Package Dependencies
414 +Add `package.json` to config directory:
416 +```json
418 + "dependencies": {
419 + "bun:sqlite": "latest",
420 + "zod": "^3.0.0",
421 + "zod-to-json-schema": "^3.22.0"
424 +```
426 +OpenCode runs `bun install` at startup.
428 +---
430 +## Open Source Plugin Examples
432 +### Community Plugins (from ecosystem)
434 +| Plugin | Description |
435 +| ---------------------------- | ----------------------------------------------- |
436 +| `opencode-workspace` | Bundled orchestration harness (16 components) |
437 +| `opencode-background-agents` | Claude Code-style background agents |
438 +| `@openspoon/subtask2` | Orchestration system with granular flow control |
439 +| `opencode-rules` | Rule file injection into prompts |
440 +| `opencode-skillful` | Lazy-load prompts on demand |
441 +| `opencode-supermemory` | Persistent memory across sessions |
442 +| `micode` | Structured Brainstorm → Plan → Implement |
444 +### Key Pattern from `opencode-workspace`
446 +Uses a **bundle** approach with:
448 +- Multiple plugins (reactive features)
449 +- Multiple agents (planner, coder, reviewer)
450 +- Multiple skills (protocol enforcement)
451 +- MCP servers (external tools)
453 +NOT a centralized kernel - distributed coordination.
455 +---
457 +## Related GitHub Issues
459 +| Issue | Status | Description |
460 +| ------ | ------ | ------------------------------------------------------- |
461 +| #16626 | Open | `session.stopping` hook to allow re-entering agent loop |
462 +| #17412 | Closed | ~~Plugin hooks should inject AI-visible messages~~ (Resolved via `noReply`) |
463 +| #16879 | Closed | Await plugin event handlers on session.idle |
464 +| #12472 | Open | Native Claude Code hooks compatibility |
465 +| #5894 | Open | Bug: Plugin hooks don't intercept subagents |
466 +| #18007 | PR | Add `session.start` lifecycle hook |
468 +---
470 +## Security Considerations
472 +1. **Subagent bypass**: `tool.execute.before` doesn't fire for subagents
473 +2. **Permission system bypass**: Subagents can bypass permission checks
474 +3. **No isolation**: Plugin code runs in same process
476 +---
478 +## References
480 +- [Official Plugin Docs](https://opencode.ai/docs/plugins/)
481 +- [Custom Tools Docs](https://opencode.ai/docs/custom-tools/)
482 +- [SDK Docs](https://opencode.ai/docs/sdk/)
483 +- [Plugin Source](https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/index.ts)
484 +- [Plugin Package](https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/index.ts)
485 +- [Ecosystem](https://opencode.ai/docs/ecosystem)
486 +- [opencode-workspace](https://github.com/kdcokenny/opencode-workspace)
488 +---
490 +_Last updated: 2026-03-23_

opencode/plugins/chef/README.md

Added
new file mode 100644
1 +# Chef Orchestrator Plugin
3 +Declarative pipeline orchestration for OpenCode multi-agent workflows.
5 +## Overview
7 +Chef provides a TypeScript DSL for defining structured workflows that coordinate multiple agents. It leverages OpenCode's SDK capabilities for:
9 +- **Message Injection**: Pass context between agents via `noReply: true`
10 +- **Structured Output**: Automatic JSON schema validation with retries
11 +- **State Persistence**: SQLite-backed state management
12 +- **Fluent API**: Chaining syntax for pipeline definitions
13 +- **Retry Policies**: Configurable retry with exponential backoff
14 +- **Timeout Handling**: Per-step timeouts with automatic session cleanup
15 +- **Reusable Fragments**: Composable sub-pipelines via `fragment()` and `.use()`
16 +- **Pipeline Validation**: Startup checks for schemas, agents, and loop targets
17 +- **Error Taxonomy**: Classified errors for targeted retry and debugging
19 +## Installation
21 +The plugin is automatically loaded from `.opencode/plugins/chef/` directory.
23 +Dependencies are installed automatically via `bun install`.
25 +## Quick Start
27 +### 1. Create a Pipeline
29 +Create `.opencode/chef/pipelines/feature.ts`:
31 +```typescript
32 +import { pipeline } from "@opencode-ai/chef";
33 +import { z } from "zod";
35 +export default pipeline("feature")
36 + .step("research", {
37 + agent: "researcher",
38 + prompt: "Research the codebase",
39 + output: z.object({
40 + findings: z.string(),
41 + files: z.array(z.string()),
42 + }),
43 + })
44 + .step("plan", {
45 + agent: "planner",
46 + prompt: (ctx) => `Create plan based on: ${ctx.research.findings}`,
47 + output: z.object({
48 + tasks: z.array(z.string()),
49 + }),
50 + })
51 + .build();
52 +```
54 +### 2. Start a Pipeline
56 +In OpenCode:
58 +```
59 +Use the pipeline.start tool:
60 +- name: "feature"
61 +- input: { feature: "dark mode toggle" }
62 +```
64 +Or say: "Start the feature pipeline to add dark mode toggle"
66 +### 3. Check Status
68 +```
69 +Use pipeline.status tool
70 +```
72 +## Pipeline DSL
74 +### Steps
76 +Define agent tasks with structured outputs:
78 +```typescript
79 +.step("name", {
80 + agent: "agent-name",
81 + prompt: "Task description" | ((ctx) => string),
82 + output: z.object({ ... }),
83 +})
84 +```
86 +### Gates
88 +Add approval or validation checkpoints:
90 +```typescript
91 +.gate("approval", {
92 + agent: "reviewer", // optional
93 + expect: z.object({ approved: z.boolean() }),
94 +})
95 +```
97 +### Conditionals & Loops
99 +Branch based on context:
101 +```typescript
102 +.when((ctx) => !ctx.approval.approved)
103 +.loop("plan") // loop back to "plan" step
104 +```
106 +### Parallel Execution
108 +Run multiple agents concurrently:
110 +```typescript
111 +.parallel([
112 + step("review_security", { agent: "security", ... }),
113 + step("review_perf", { agent: "profiler", ... }),
115 +```
117 +## Retry Policies
119 +Steps support configurable retry behavior. When a step fails, Chef automatically retries with exponential backoff before marking the step as failed.
121 +### Configuration
123 +Add a `retry` option to any step:
125 +```typescript
126 +.step("implement", {
127 + agent: "programmer",
128 + prompt: "Implement the feature",
129 + output: z.object({ summary: z.string() }),
130 + retry: {
131 + maxAttempts: 3,
132 + backoffMs: 2000,
133 + retryOn: ["agent_error", "agent_timeout"],
134 + },
136 +```
138 +**Fields:**
140 +| Field | Type | Default | Description |
141 +|---|---|---|---|
142 +| `maxAttempts` | `number` | `1` | Maximum number of attempts (including the first run) |
143 +| `backoffMs` | `number` | `1000` | Base delay in milliseconds before the first retry |
144 +| `retryOn` | `string[] \| undefined` | `undefined` | Error types that trigger a retry |
146 +### Backoff Behavior
148 +Delays use exponential backoff: `backoffMs * 2^attempt`. For `backoffMs: 2000` with 3 attempts:
150 +- Attempt 1: immediate
151 +- Attempt 2: waits 2000ms
152 +- Attempt 3: waits 4000ms
154 +### Filtering Retries by Error Type
156 +The `retryOn` field controls which errors trigger a retry:
158 +- **`undefined`** (default): Retry on any error
159 +- **`["agent_error", "agent_timeout"]`**: Only retry on matching error types
160 +- **`["all"]`**: Explicitly retry on all errors
162 +See [Error Handling](#error-handling) for the full list of error types.
164 +### Retry Feedback
166 +On retry, Chef injects the previous error message into the agent's context so it can correct its behavior:
168 +```
169 +Previous attempt failed with: Step "implement" timed out after 30000ms.
170 +Please correct this and try again.
171 +```
173 +## Timeout Handling
175 +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`.
177 +### Usage
179 +```typescript
180 +.step("review_security", {
181 + agent: "security",
182 + prompt: "Review for security vulnerabilities",
183 + output: z.object({ passed: z.boolean(), findings: z.array(z.string()) }),
184 + timeout: 60000, // 60 seconds
186 +```
188 +When a timeout occurs:
190 +1. The timed-out session is automatically deleted (best-effort cleanup)
191 +2. The error is classified as `agent_timeout` (retryable if configured)
192 +3. If the step has a retry policy, it may be retried
194 +### Combining with Retry
196 +Timeout and retry work together naturally:
198 +```typescript
199 +.step("analyze", {
200 + agent: "analyst",
201 + prompt: "Analyze the dataset",
202 + output: z.object({ results: z.array(z.string()) }),
203 + timeout: 30000,
204 + retry: {
205 + maxAttempts: 3,
206 + backoffMs: 1000,
207 + retryOn: ["agent_timeout"],
208 + },
210 +```
212 +This retries up to 3 times but only when the agent times out.
214 +## Reusable Fragments
216 +Fragments let you define reusable sequences of steps that can be included in multiple pipelines. This avoids duplicating common step definitions.
218 +### Defining a Fragment
220 +Use the `fragment()` function with the `step()` helper:
222 +```typescript
223 +import { fragment, step } from "@opencode-ai/chef";
224 +import { z } from "zod";
226 +const reviewFragment = fragment("review", [
227 + step("review_security", {
228 + agent: "security",
229 + prompt: "Review for security vulnerabilities",
230 + output: z.object({
231 + passed: z.boolean(),
232 + findings: z.array(z.string()),
233 + }),
234 + timeout: 60000,
235 + }),
236 + step("review_quality", {
237 + agent: "reviewer",
238 + prompt: (ctx) => `Review code quality for:\n${ctx.implement.summary}`,
239 + output: z.object({
240 + passed: z.boolean(),
241 + feedback: z.array(z.string()),
242 + }),
243 + timeout: 60000,
244 + }),
245 +]);
246 +```
248 +### Including a Fragment
250 +Use the `.use()` method on a pipeline builder to include all steps from a fragment:
252 +```typescript
253 +export default pipeline("feature")
254 + .step("research", { ... })
255 + .step("implement", { ... })
256 + .use(reviewFragment) // Adds review_security and review_quality steps
257 + .build();
258 +```
260 +The `.use()` method adds each step from the fragment as an individual phase in the pipeline, preserving their order.
262 +## Pipeline Validation
264 +Chef validates pipeline definitions at startup when pipelines are loaded from disk. This catches configuration errors early, before any execution begins.
266 +### How It Works
268 +When the plugin loads pipeline files, it calls the builder's `validate()` method automatically. Validation warnings appear in the console:
270 +```
271 +Chef: Pipeline "feature" has validation errors:
272 + - Gate "approval" onFail target "unknown_step" not found in pipeline
273 +```
275 +### Manual Validation
277 +You can also call `validate()` explicitly before building:
279 +```typescript
280 +const builder = pipeline("feature")
281 + .step("research", { ... })
282 + .gate("approval", { ... });
284 +const result = builder.validate();
285 +if (!result.valid) {
286 + for (const err of result.errors) {
287 + console.error(`Validation error: ${err}`);
291 +const definition = builder.build();
292 +```
294 +### What Gets Validated
296 +| Check | Description |
297 +|---|---|
298 +| Output schema | Each step must have a valid Zod schema (`parse` is a function) |
299 +| Agent name | Each step must have a non-empty string agent |
300 +| Gate expect schema | Each gate must have a valid Zod schema for `expect` |
301 +| Gate `onFail` target | If set, must reference a step that exists earlier in the pipeline |
302 +| `when` loop target | If set, must reference a step that exists in the pipeline |
303 +| `when` condition | Must be a function |
304 +| Parallel step schemas | Each parallel sub-step must have valid output and agent |
306 +### Agent Name Checks
308 +In addition to structural validation, Chef checks that referenced agent names exist at startup. Unknown agents produce warnings:
310 +```
311 +Chef: Pipeline "feature" step "research" references unknown agent "unknown_agent"
312 +```
314 +## Error Handling
316 +Chef classifies errors into a taxonomy so that retry policies and debugging can target specific failure modes.
318 +### Error Types
320 +| Error Class | Type String | Cause |
321 +|---|---|---|
322 +| `AgentTimeoutError` | `agent_timeout` | Step exceeded its `timeout` deadline |
323 +| `AgentError` | `agent_error` | Agent returned an error during execution |
324 +| `GateFailureError` | `gate_failure` | Gate validation or agent evaluation failed |
325 +| `SchemaValidationError` | `schema_validation` | Agent output did not match the Zod schema |
326 +| `MaxIterationsError` | `max_iterations` | A loop exceeded the maximum iteration count (default: 10) |
328 +All errors extend `ChefError`, which carries a `type` string for programmatic handling.
330 +### Error Flow
332 +1. A step, gate, or parallel phase throws an error during execution
333 +2. The executor catches the error and records it in the phase state
334 +3. If the step has a retry policy and the error type matches `retryOn`, the step is retried
335 +4. If all retries are exhausted, the step is marked as `failed`
336 +5. The pipeline status is updated to `failed`
338 +### Loop Iteration Guard
340 +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.
342 +## Gate onFail
344 +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.
346 +### Usage
348 +```typescript
349 +.gate("approval", {
350 + agent: "devil",
351 + expect: z.object({
352 + approved: z.boolean(),
353 + feedback: z.string().optional(),
354 + }),
355 + onFail: "plan", // Loop back to "plan" step on failure
357 +```
359 +When the gate fails:
361 +1. The gate's phase state is marked as `failed`
362 +2. A warning is logged: `Chef: Gate "approval" failed, looping back to "plan"`
363 +3. Execution resumes at the named step ("plan")
364 +4. The loop iteration counter increments
366 +### Combining with `.when()` / `.loop()`
368 +The `onFail` option and `.when()` / `.loop()` can be used together or independently:
370 +```typescript
371 +// Gate onFail: automatic loop-back on gate failure
372 +.gate("approval", {
373 + agent: "devil",
374 + expect: z.object({ approved: z.boolean() }),
375 + onFail: "plan",
378 +// when/loop: conditional loop based on context
379 +.when((ctx) => !ctx.approval.approved)
380 +.loop("plan")
381 +```
383 +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.
385 +### Validation
387 +The `onFail` target is validated at startup. If the target step does not exist in the pipeline, a validation error is reported.
389 +## Tools
391 +### pipeline.start
393 +Start a new pipeline execution.
395 +**Arguments:**
396 +- `name` (string): Pipeline name
397 +- `input` (any, optional): Input data
399 +**Returns:**
400 +```json
402 + "pipeline_id": "uuid",
403 + "status": "running" | "completed" | "failed" | "needs_input",
404 + "context": { ... }
406 +```
408 +### pipeline.status
410 +Check pipeline status.
412 +**Arguments:**
413 +- `id` (string, optional): Pipeline ID (defaults to all running)
415 +### pipeline.continue
417 +Continue after `needs_input` status.
419 +**Arguments:**
420 +- `id` (string): Pipeline ID
421 +- `input` (any): Input data for next phase
423 +### pipeline.abort
425 +Cancel a running pipeline.
427 +**Arguments:**
428 +- `id` (string): Pipeline ID
430 +### pipeline.list
432 +List available pipelines.
434 +## Architecture
436 +```
437 +User → pipeline.start()
438 + ↓
439 +Chef Plugin (chef.ts)
440 + ↓
441 +Load & Validate Pipelines (builder.ts validate())
442 + ↓
443 +Executor (executor.ts)
444 + ↓
445 +SDK Client → session.create()
446 + ↓
447 +Context Injection → prompt({ noReply: true })
448 + ↓
449 +Agent Execution → prompt({ format: { type: "json_schema" } })
450 + ↓
451 +Retry/Timeout → exponential backoff + Promise.race
452 + ↓
453 +State Persistence → SQLite (store.ts)
454 +```
456 +## Example Pipeline
458 +See `pipelines/feature.ts` for a complete example with:
459 +- Research phase
460 +- Planning phase
461 +- Approval gate with `onFail` loop-back to "plan"
462 +- Conditional loop via `.when()` / `.loop()`
463 +- Implementation phase with retry policy (3 attempts, filtered to `agent_error` and `agent_timeout`)
464 +- Reusable review fragment via `fragment()` and `.use()`
465 +- Per-step timeouts on review steps
467 +## Status
469 +**Phase 1: Core Infrastructure** ✅
471 +- [x] SQLite state management
472 +- [x] Pipeline builder DSL
473 +- [x] Step execution with structured output
474 +- [x] Context injection
475 +- [x] Basic tools (start, status, continue, abort, list)
477 +**Phase 2: Execution Engine** ✅
479 +- [x] Enhanced error handling (error taxonomy)
480 +- [x] Gate evaluation
481 +- [x] Parallel execution
482 +- [x] Conditional loops
484 +**Phase 3: Advanced Features** ✅
486 +- [x] Pipeline validation on startup
487 +- [x] Reusable fragments
488 +- [x] Retry policies
489 +- [x] Timeout handling
491 +## Development
493 +```bash
494 +# Run tests (when available)
495 +bun test
497 +# Type checking
498 +bunx tsc --noEmit
499 +```
501 +## References
503 +- [PLAN.md](./PLAN.md) - Design documentation
504 +- [PLUGIN_SDK.md](./PLUGIN_SDK.md) - SDK capabilities research

opencode/plugins/chef/chef.ts

Added
new file mode 100644
1 +import { type Plugin, tool } from "@opencode-ai/plugin";
2 +import { join } from "path";
3 +import { glob } from "glob";
4 +import { Store } from "./store";
5 +import { Executor } from "./executor";
6 +import type {
7 + GateDefinition,
8 + PipelineDefinition,
9 + StepDefinition,
10 +} from "./pipeline/builder";
12 +export const ChefPlugin: Plugin = async ({
13 + client,
14 + project,
15 + directory,
16 + worktree,
17 +}) => {
18 + // Initialize store
19 + const store = new Store(directory);
21 + // Load pipeline definitions
22 + const pipelinesDir = join(directory, ".opencode/chef/pipelines");
23 + const pipelines = new Map<string, PipelineDefinition>();
25 + async function loadPipelines() {
26 + // Fetch available agents for validation
27 + let agentNames: Set<string> = new Set();
28 + try {
29 + const agents = await client.app.agents();
30 + agentNames = new Set(agents.map((a: any) => a.id ?? a.name));
31 + } catch {
32 + console.warn(
33 + "Chef: Could not fetch agent list, skipping agent validation",
34 + );
35 + }
37 + try {
38 + const files = await glob("*.ts", { cwd: pipelinesDir });
40 + for (const file of files) {
41 + try {
42 + const module = await import(join(pipelinesDir, file));
43 + const exported = module.default;
45 + if (!exported) continue;
47 + let definition: PipelineDefinition;
48 + let hasBuilder = false;
50 + if (typeof exported.build === "function") {
51 + definition = exported.build();
52 + hasBuilder = true;
53 + } else if (exported.name && exported.phases) {
54 + definition = exported;
55 + } else {
56 + continue;
57 + }
59 + // Run structural validation
60 + if (hasBuilder && typeof exported.validate === "function") {
61 + const result = exported.validate();
62 + if (!result.valid) {
63 + console.warn(
64 + `Chef: Pipeline "${definition.name}" has validation errors:`,
65 + );
66 + for (const err of result.errors) {
67 + console.warn(` - ${err}`);
68 + }
69 + }
70 + }
72 + // Check agent names exist
73 + for (const phase of definition.phases) {
74 + if (
75 + phase.type === "step" &&
76 + !agentNames.has((phase as StepDefinition).agent)
77 + ) {
78 + console.warn(
79 + `Chef: Pipeline "${definition.name}" step "${phase.name}" references unknown agent "${
80 + (phase as StepDefinition).agent
81 + }"`,
82 + );
83 + }
84 + if (
85 + phase.type === "gate" && (phase as GateDefinition).agent &&
86 + !agentNames.has((phase as GateDefinition).agent!)
87 + ) {
88 + console.warn(
89 + `Chef: Pipeline "${definition.name}" gate "${phase.name}" references unknown agent "${
90 + (phase as GateDefinition).agent
91 + }"`,
92 + );
93 + }
94 + if (phase.type === "parallel") {
95 + for (const s of (phase as any).steps) {
96 + if (!agentNames.has(s.agent)) {
97 + console.warn(
98 + `Chef: Pipeline "${definition.name}" parallel step "${s.name}" references unknown agent "${s.agent}"`,
99 + );
105 + pipelines.set(definition.name, definition);
106 + } catch (error) {
107 + console.error(`Chef: Failed to load pipeline ${file}:`, error);
110 + } catch (error) {
111 + // Pipelines directory doesn't exist yet
112 + console.log("Chef: No pipelines directory found");
116 + await loadPipelines();
118 + return {
119 + tool: {
120 + "pipeline.start": tool({
121 + description: "Start a new pipeline execution",
122 + args: {
123 + name: tool.schema.string().describe("Pipeline name"),
124 + input: tool.schema.any().optional().describe("Pipeline input data"),
125 + },
126 + async execute(args, context) {
127 + const definition = pipelines.get(args.name);
129 + if (!definition) {
130 + return `Pipeline "${args.name}" not found. Available pipelines: ${
131 + Array.from(pipelines.keys()).join(", ")
132 + }`;
135 + // Create pipeline instance
136 + const instance = store.createPipeline(args.name, args.input || {});
138 + // Execute pipeline
139 + const executor = new Executor(store, client, definition);
141 + try {
142 + const result = await executor.execute(
143 + instance.id,
144 + args.input || {},
145 + );
147 + return JSON.stringify(
149 + pipeline_id: instance.id,
150 + status: result.status,
151 + context: result.context,
152 + },
153 + null,
154 + 2,
155 + );
156 + } catch (error: any) {
157 + store.updatePipeline(instance.id, {
158 + status: "failed",
159 + });
161 + return `Pipeline execution failed: ${error.message}`;
163 + },
164 + }),
166 + "pipeline.status": tool({
167 + description: "Check status of pipeline(s)",
168 + args: {
169 + id: tool.schema.string().optional().describe(
170 + "Pipeline ID (optional, defaults to all running)",
171 + ),
172 + },
173 + async execute(args, context) {
174 + if (args.id) {
175 + const pipeline = store.getPipeline(args.id);
177 + if (!pipeline) {
178 + return `Pipeline ${args.id} not found`;
181 + return JSON.stringify(pipeline, null, 2);
184 + const running = store.listPipelines("running");
185 + return JSON.stringify(running, null, 2);
186 + },
187 + }),
189 + "pipeline.continue": tool({
190 + description: "Continue a pipeline after needs_input",
191 + args: {
192 + id: tool.schema.string().describe("Pipeline ID"),
193 + input: tool.schema.any().describe("Input data for next phase"),
194 + },
195 + async execute(args, context) {
196 + const instance = store.getPipeline(args.id);
198 + if (!instance) {
199 + return `Pipeline ${args.id} not found`;
202 + if (instance.status !== "needs_input") {
203 + return `Pipeline ${args.id} is not waiting for input (status: ${instance.status})`;
206 + const definition = pipelines.get(instance.definition);
207 + if (!definition) {
208 + return `Pipeline definition ${instance.definition} not found`;
211 + // Merge input into context
212 + const pipelineContext = JSON.parse(instance.context);
213 + Object.assign(pipelineContext, args.input);
214 + store.updatePipeline(args.id, {
215 + context: JSON.stringify(pipelineContext),
216 + status: "running",
217 + });
219 + // Continue execution
220 + const executor = new Executor(store, client, definition);
222 + try {
223 + const result = await executor.execute(args.id, pipelineContext);
225 + return JSON.stringify(
227 + pipeline_id: args.id,
228 + status: result.status,
229 + context: result.context,
230 + },
231 + null,
232 + 2,
233 + );
234 + } catch (error: any) {
235 + store.updatePipeline(args.id, {
236 + status: "failed",
237 + });
239 + return `Pipeline execution failed: ${error.message}`;
241 + },
242 + }),
244 + "pipeline.abort": tool({
245 + description: "Abort a running pipeline",
246 + args: {
247 + id: tool.schema.string().describe("Pipeline ID"),
248 + },
249 + async execute(args, context) {
250 + const instance = store.getPipeline(args.id);
252 + if (!instance) {
253 + return `Pipeline ${args.id} not found`;
256 + store.updatePipeline(args.id, {
257 + status: "aborted",
258 + });
260 + return `Pipeline ${args.id} aborted`;
261 + },
262 + }),
264 + "pipeline.list": tool({
265 + description: "List available pipelines",
266 + args: {},
267 + async execute(args, context) {
268 + const names = Array.from(pipelines.keys());
270 + return `Available pipelines:\n${
271 + names.map((n) => `- ${n}`).join("\n")
272 + }\n\nLoad custom pipelines by creating .opencode/chef/pipelines/*.ts files`;
273 + },
274 + }),
275 + },
276 + };
279 +export default ChefPlugin;

opencode/plugins/chef/executor.ts

Added
new file mode 100644
1 +import type { Client } from "@opencode-ai/sdk";
2 +import { zodToJsonSchema } from "zod-to-json-schema";
3 +import type {
4 + GateDefinition,
5 + ParallelDefinition,
6 + PhaseDefinition,
7 + PipelineDefinition,
8 + RetryPolicy,
9 + StepDefinition,
10 + WhenDefinition,
11 +} from "./pipeline/builder";
12 +import { Store } from "./store";
14 +// Error taxonomy
15 +export class ChefError extends Error {
16 + constructor(
17 + message: string,
18 + public readonly type: string,
19 + ) {
20 + super(message);
21 + this.name = "ChefError";
22 + }
25 +export class AgentTimeoutError extends ChefError {
26 + constructor(stepName: string, timeout: number) {
27 + super(`Step "${stepName}" timed out after ${timeout}ms`, "agent_timeout");
28 + this.name = "AgentTimeoutError";
29 + }
32 +export class AgentError extends ChefError {
33 + constructor(stepName: string, message: string) {
34 + super(`Agent error in "${stepName}": ${message}`, "agent_error");
35 + this.name = "AgentError";
36 + }
39 +export class GateFailureError extends ChefError {
40 + constructor(gateName: string, message: string) {
41 + super(`Gate "${gateName}" failed: ${message}`, "gate_failure");
42 + this.name = "GateFailureError";
43 + }
46 +export class MaxIterationsError extends ChefError {
47 + constructor(max: number) {
48 + super(`Max loop iterations (${max}) reached`, "max_iterations");
49 + this.name = "MaxIterationsError";
50 + }
53 +export class SchemaValidationError extends ChefError {
54 + constructor(stepName: string, message: string) {
55 + super(
56 + `Schema validation failed for "${stepName}": ${message}`,
57 + "schema_validation",
58 + );
59 + this.name = "SchemaValidationError";
60 + }
63 +const DEFAULT_MAX_LOOP_ITERATIONS = 10;
64 +const DEFAULT_RETRY: RetryPolicy = {
65 + maxAttempts: 1,
66 + backoffMs: 1000,
67 + retryOn: undefined,
68 +};
70 +export class Executor {
71 + private maxLoopIterations: number;
73 + constructor(
74 + private store: Store,
75 + private client: Client,
76 + private definition: PipelineDefinition,
77 + options?: { maxLoopIterations?: number },
78 + ) {
79 + this.maxLoopIterations = options?.maxLoopIterations ??
80 + DEFAULT_MAX_LOOP_ITERATIONS;
81 + }
83 + private async cleanupSession(sessionId: string): Promise<void> {
84 + await this.client.session.delete({ path: { id: sessionId } }).catch(
85 + (e) => {
86 + console.warn(
87 + `Chef: session cleanup failed for ${sessionId}:`,
88 + e?.message ?? e,
89 + );
90 + },
91 + );
92 + }
94 + async execute(pipelineId: string, input: any): Promise<any> {
95 + const instance = this.store.getPipeline(pipelineId);
96 + if (!instance) {
97 + throw new Error(`Pipeline ${pipelineId} not found`);
98 + }
100 + let context: any = JSON.parse(instance.context ?? "{}");
101 + const phases = this.definition.phases;
102 + let loopIterations = 0;
104 + for (let i = instance.current_phase; i < phases.length; i++) {
105 + // Check if pipeline was aborted
106 + const current = this.store.getPipeline(pipelineId);
107 + if (current && current.status === "aborted") {
108 + return { status: "aborted", context };
111 + const phase = phases[i];
113 + // Update current phase
114 + this.store.updatePipeline(pipelineId, {
115 + current_phase: i,
116 + status: "running",
117 + });
119 + try {
120 + const result = await this.executePhase(phase, context, pipelineId);
122 + if (result.status === "needs_input") {
123 + this.store.updatePipeline(pipelineId, {
124 + status: "needs_input",
125 + context: JSON.stringify(context),
126 + });
127 + return { status: "needs_input", context };
130 + if (result.status === "loop") {
131 + loopIterations++;
132 + if (loopIterations > this.maxLoopIterations) {
133 + this.store.updatePipeline(pipelineId, {
134 + status: "failed",
135 + context: JSON.stringify(context),
136 + });
137 + return {
138 + status: "failed",
139 + error: new MaxIterationsError(this.maxLoopIterations).message,
140 + };
142 + const targetIndex = phases.findIndex((p) => p.name === result.target);
143 + if (targetIndex >= 0) {
144 + i = targetIndex - 1; // -1 because loop will increment
145 + continue;
149 + if (result.status === "failed") {
150 + this.store.updatePipeline(pipelineId, {
151 + status: "failed",
152 + context: JSON.stringify(context),
153 + });
154 + return { status: "failed", error: result.error };
157 + // Merge output into context
158 + if (result.output) {
159 + context[phase.name] = result.output;
160 + this.store.updatePipeline(pipelineId, {
161 + context: JSON.stringify(context),
162 + });
164 + } catch (error: any) {
165 + this.store.updatePipeline(pipelineId, {
166 + status: "failed",
167 + });
168 + throw error;
172 + // Pipeline completed
173 + this.store.updatePipeline(pipelineId, {
174 + status: "completed",
175 + current_phase: phases.length,
176 + });
178 + return { status: "completed", context };
181 + private async executePhase(
182 + phase: PhaseDefinition,
183 + context: any,
184 + pipelineId: string,
185 + ): Promise<
186 + { status: string; output?: any; error?: string; target?: string }
187 + > {
188 + switch (phase.type) {
189 + case "step":
190 + return this.executeStep(phase, context, pipelineId);
192 + case "gate":
193 + return this.executeGate(phase, context, pipelineId);
195 + case "parallel":
196 + return this.executeParallel(phase, context, pipelineId);
198 + case "when":
199 + return this.executeWhen(phase, context);
201 + default:
202 + throw new Error(`Unknown phase type: ${(phase as any).type}`);
206 + private async executeStep(
207 + step: StepDefinition,
208 + context: any,
209 + pipelineId: string,
210 + parentPhaseId?: string,
211 + ): Promise<{ status: string; output?: any; error?: string }> {
212 + const phase = parentPhaseId
213 + ? (this.store.getPhase(parentPhaseId) ??
214 + this.store.createPhase(pipelineId, step.name))
215 + : this.store.createPhase(pipelineId, step.name);
216 + const retry: RetryPolicy = step.retry ?? DEFAULT_RETRY;
217 + let lastError: any;
219 + for (let attempt = 0; attempt < retry.maxAttempts; attempt++) {
220 + let sessionId: string | undefined;
222 + try {
223 + // Create fresh session for each attempt
224 + const session = await this.client.session.create({
225 + body: {
226 + title: `Chef: ${step.name}${
227 + attempt > 0 ? ` (retry ${attempt})` : ""
228 + }`,
229 + agent: step.agent,
230 + },
231 + });
232 + sessionId = session.id;
234 + // Inject context
235 + const contextParts: any[] = [
237 + type: "text",
238 + text: `Previous context:\n${JSON.stringify(context, null, 2)}`,
239 + },
240 + ];
242 + // On retry, inject previous error as feedback
243 + if (attempt > 0 && lastError) {
244 + contextParts.push({
245 + type: "text",
246 + text:
247 + `Previous attempt failed with: ${lastError.message}. Please correct this and try again.`,
248 + });
251 + await this.client.session.prompt({
252 + path: { id: session.id },
253 + body: {
254 + noReply: true,
255 + parts: contextParts,
256 + },
257 + });
259 + // Execute with structured output
260 + const prompt = typeof step.prompt === "function"
261 + ? step.prompt(context)
262 + : step.prompt;
264 + const jsonSchema = zodToJsonSchema(step.output);
266 + // Build prompt promise
267 + const promptPromise = this.client.session.prompt({
268 + path: { id: session.id },
269 + body: {
270 + parts: [{ type: "text", text: prompt }],
271 + format: {
272 + type: "json_schema",
273 + schema: jsonSchema,
274 + retryCount: 2,
275 + },
276 + },
277 + });
279 + // Apply timeout if configured
280 + let result: any;
281 + if (step.timeout) {
282 + result = await Promise.race([
283 + promptPromise,
284 + new Promise<never>((_, reject) =>
285 + setTimeout(
286 + () => reject(new AgentTimeoutError(step.name, step.timeout!)),
287 + step.timeout,
289 + ),
290 + ]);
291 + } else {
292 + result = await promptPromise;
295 + const output = result.data.info.structured_output;
297 + // Update phase state
298 + this.store.updatePhase(phase.id, {
299 + status: "completed",
300 + output: JSON.stringify(output),
301 + completed_at: Date.now(),
302 + attempts: attempt + 1,
303 + });
305 + return { status: "completed", output };
306 + } catch (error: any) {
307 + lastError = error;
309 + // Try to abort timed-out sessions
310 + if (sessionId && error instanceof AgentTimeoutError) {
311 + try {
312 + await this.client.session.delete({ path: { id: sessionId } });
313 + sessionId = undefined; // prevent double-delete in finally
314 + } catch {
315 + // best-effort abort
319 + this.store.updatePhase(phase.id, {
320 + attempts: attempt + 1,
321 + error: error.message,
322 + });
324 + // Check if error type is retryable
325 + const shouldRetry = retry.retryOn === undefined ||
326 + retry.retryOn.includes(error.type) ||
327 + retry.retryOn.includes("all");
329 + if (!shouldRetry || attempt >= retry.maxAttempts - 1) {
330 + break;
333 + // Exponential backoff before retry
334 + const delay = retry.backoffMs * Math.pow(2, attempt);
335 + console.warn(
336 + `Chef: Step "${step.name}" attempt ${
337 + attempt + 1
338 + } failed, retrying in ${delay}ms...`,
339 + );
340 + await new Promise((r) => setTimeout(r, delay));
341 + } finally {
342 + if (sessionId) {
343 + await this.cleanupSession(sessionId);
348 + // All attempts exhausted
349 + this.store.updatePhase(phase.id, {
350 + status: "failed",
351 + error: lastError?.message ?? "Unknown error",
352 + });
354 + return { status: "failed", error: lastError?.message ?? "Unknown error" };
357 + private async executeGate(
358 + gate: GateDefinition,
359 + context: any,
360 + pipelineId: string,
361 + ): Promise<
362 + { status: string; output?: any; error?: string; target?: string }
363 + > {
364 + const phase = this.store.createPhase(pipelineId, gate.name);
365 + let sessionId: string | undefined;
367 + try {
368 + // If gate has an agent, execute it
369 + if (gate.agent) {
370 + const session = await this.client.session.create({
371 + body: {
372 + title: `Chef Gate: ${gate.name}`,
373 + agent: gate.agent,
374 + },
375 + });
376 + sessionId = session.id;
378 + // Inject context
379 + await this.client.session.prompt({
380 + path: { id: session.id },
381 + body: {
382 + noReply: true,
383 + parts: [
385 + type: "text",
386 + text: `Context:\n${
387 + JSON.stringify(context, null, 2)
388 + }\n\nEvaluate this gate.`,
389 + },
390 + ],
391 + },
392 + });
394 + const jsonSchema = zodToJsonSchema(gate.expect);
396 + const result = await this.client.session.prompt({
397 + path: { id: session.id },
398 + body: {
399 + parts: [{ type: "text", text: "Evaluate gate conditions" }],
400 + format: {
401 + type: "json_schema",
402 + schema: jsonSchema,
403 + retryCount: 2,
404 + },
405 + },
406 + });
408 + const output = result.data.info.structured_output;
410 + // Validate against expectation
411 + const validated = gate.expect.parse(output);
413 + this.store.updatePhase(phase.id, {
414 + status: "completed",
415 + output: JSON.stringify(validated),
416 + completed_at: Date.now(),
417 + });
419 + return { status: "completed", output: validated };
420 + } else {
421 + // Direct validation without agent
422 + const validated = gate.expect.parse(context);
424 + this.store.updatePhase(phase.id, {
425 + status: "completed",
426 + output: JSON.stringify(validated),
427 + completed_at: Date.now(),
428 + });
430 + return { status: "completed", output: validated };
432 + } catch (error: any) {
433 + this.store.updatePhase(phase.id, {
434 + status: "failed",
435 + error: error.message,
436 + });
438 + // If gate has onFail, loop back to target phase
439 + if (gate.onFail) {
440 + console.warn(
441 + `Chef: Gate "${gate.name}" failed, looping back to "${gate.onFail}"`,
442 + );
443 + return { status: "loop", target: gate.onFail };
446 + return { status: "failed", error: error.message };
447 + } finally {
448 + if (sessionId) {
449 + await this.cleanupSession(sessionId);
454 + private async executeParallel(
455 + parallel: ParallelDefinition,
456 + context: any,
457 + pipelineId: string,
458 + ): Promise<{ status: string; output?: any; error?: string }> {
459 + const phase = this.store.createPhase(pipelineId, parallel.name);
461 + try {
462 + const results = await Promise.all(
463 + parallel.steps.map((step) =>
464 + this.executeStep(step, context, pipelineId, phase.id)
465 + ),
466 + );
468 + // Check if any failed
469 + const failed = results.find((r) => r.status === "failed");
470 + if (failed) {
471 + this.store.updatePhase(phase.id, {
472 + status: "failed",
473 + error: failed.error,
474 + });
475 + return failed;
478 + const outputs = results.reduce((acc, r, i) => {
479 + acc[parallel.steps[i].name] = r.output;
480 + return acc;
481 + }, {} as any);
483 + this.store.updatePhase(phase.id, {
484 + status: "completed",
485 + output: JSON.stringify(outputs),
486 + completed_at: Date.now(),
487 + });
489 + return { status: "completed", output: outputs };
490 + } catch (error: any) {
491 + this.store.updatePhase(phase.id, {
492 + status: "failed",
493 + error: error.message,
494 + });
496 + return { status: "failed", error: error.message };
500 + private executeWhen(
501 + when: WhenDefinition,
502 + context: any,
503 + ): { status: string; target?: string } {
504 + const conditionMet = when.condition(context);
506 + if (conditionMet && when.loopTarget) {
507 + return { status: "loop", target: when.loopTarget };
510 + return { status: "completed" };

opencode/plugins/chef/package.json

Added
new file mode 100644
1 +{
2 + "name": "@opencode-ai/chef",
3 + "version": "0.1.0",
4 + "description": "Orchestrator plugin for coordinating multiple agents in structured workflows",
5 + "type": "module",
6 + "dependencies": {
7 + "zod": "^3.22.0",
8 + "zod-to-json-schema": "^3.22.0",
9 + "glob": "^10.0.0"
10 + },
11 + "devDependencies": {
12 + "@types/bun": "latest"
13 + }

opencode/plugins/chef/pipeline/builder.ts

Added
new file mode 100644
1 +import { z } from "zod";
3 +export interface RetryPolicy {
4 + maxAttempts: number;
5 + backoffMs: number;
6 + retryOn: string[] | undefined;
7 +}
9 +export interface StepDefinition {
10 + name: string;
11 + type: "step";
12 + agent: string;
13 + prompt: string | ((ctx: any) => string);
14 + output: z.ZodType<any>;
15 + timeout?: number;
16 + retry?: RetryPolicy;
19 +export interface GateDefinition {
20 + name: string;
21 + type: "gate";
22 + agent?: string;
23 + expect: z.ZodType<any>;
24 + onFail?: string;
27 +export interface ParallelDefinition {
28 + name: string;
29 + type: "parallel";
30 + steps: StepDefinition[];
33 +export interface WhenDefinition {
34 + name: string;
35 + type: "when";
36 + condition: (ctx: any) => boolean;
37 + loopTarget?: string;
40 +export type PhaseDefinition =
41 + | StepDefinition
42 + | GateDefinition
43 + | ParallelDefinition
44 + | WhenDefinition;
46 +export interface PipelineDefinition {
47 + name: string;
48 + phases: PhaseDefinition[];
51 +export interface FragmentDefinition {
52 + name: string;
53 + steps: Omit<StepDefinition, "type">[];
56 +export class PipelineBuilder {
57 + private phases: PhaseDefinition[] = [];
59 + constructor(private name: string) {}
61 + step(name: string, config: {
62 + agent: string;
63 + prompt: string | ((ctx: any) => string);
64 + output: z.ZodType<any>;
65 + timeout?: number;
66 + retry?: RetryPolicy;
67 + }): this {
68 + this.phases.push({
69 + name,
70 + type: "step",
71 + ...config,
72 + });
73 + return this;
74 + }
76 + gate(name: string, config: {
77 + agent?: string;
78 + expect: z.ZodType<any>;
79 + onFail?: string;
80 + }): this {
81 + this.phases.push({
82 + name,
83 + type: "gate",
84 + ...config,
85 + });
86 + return this;
87 + }
89 + parallel(steps: Omit<StepDefinition, "type">[]): this {
90 + this.phases.push({
91 + name: `parallel_${this.phases.length}`,
92 + type: "parallel",
93 + steps: steps.map((s) => ({ ...s, type: "step" as const })),
94 + });
95 + return this;
96 + }
98 + when(condition: (ctx: any) => boolean): this {
99 + this.phases.push({
100 + name: `when_${this.phases.length}`,
101 + type: "when",
102 + condition,
103 + });
104 + return this;
107 + loop(targetStepName: string): this {
108 + const lastPhase = this.phases[this.phases.length - 1];
109 + if (lastPhase && lastPhase.type === "when") {
110 + lastPhase.loopTarget = targetStepName;
112 + return this;
115 + use(fragment: FragmentDefinition): this {
116 + for (const s of fragment.steps) {
117 + this.phases.push({
118 + ...s,
119 + type: "step" as const,
120 + });
122 + return this;
125 + validate(): { valid: boolean; errors: string[] } {
126 + const errors: string[] = [];
127 + const stepNames = new Set<string>();
129 + for (const phase of this.phases) {
130 + // Collect step names
131 + stepNames.add(phase.name);
132 + if (phase.type === "parallel") {
133 + for (const s of phase.steps) {
134 + stepNames.add(s.name);
138 + // Validate each phase
139 + if (phase.type === "step") {
140 + if (!phase.output || typeof phase.output.parse !== "function") {
141 + errors.push(
142 + `Step "${phase.name}" has invalid output schema (expected Zod type)`,
143 + );
145 + if (!phase.agent || typeof phase.agent !== "string") {
146 + errors.push(
147 + `Step "${phase.name}" has invalid agent (expected string)`,
148 + );
152 + if (phase.type === "gate") {
153 + if (!phase.expect || typeof phase.expect.parse !== "function") {
154 + errors.push(
155 + `Gate "${phase.name}" has invalid expect schema (expected Zod type)`,
156 + );
158 + if (phase.onFail && !stepNames.has(phase.onFail)) {
159 + errors.push(
160 + `Gate "${phase.name}" onFail target "${phase.onFail}" not found in pipeline`,
161 + );
165 + if (phase.type === "when") {
166 + if (phase.loopTarget && !stepNames.has(phase.loopTarget)) {
167 + errors.push(
168 + `Loop target "${phase.loopTarget}" not found in pipeline`,
169 + );
171 + if (typeof phase.condition !== "function") {
172 + errors.push(
173 + `When "${phase.name}" has invalid condition (expected function)`,
174 + );
178 + if (phase.type === "parallel") {
179 + for (const s of phase.steps) {
180 + if (!s.output || typeof s.output.parse !== "function") {
181 + errors.push(`Parallel step "${s.name}" has invalid output schema`);
183 + if (!s.agent || typeof s.agent !== "string") {
184 + errors.push(`Parallel step "${s.name}" has invalid agent`);
190 + return { valid: errors.length === 0, errors };
193 + build(): PipelineDefinition {
194 + return {
195 + name: this.name,
196 + phases: this.phases,
197 + };
201 +export function pipeline(name: string): PipelineBuilder {
202 + return new PipelineBuilder(name);
205 +export function step(
206 + name: string,
207 + config: Omit<StepDefinition, "name" | "type">,
208 +): Omit<StepDefinition, "type"> {
209 + return { name, ...config };
212 +export function fragment(
213 + name: string,
214 + steps: Omit<StepDefinition, "type">[],
215 +): FragmentDefinition {
216 + return { name, steps };

opencode/plugins/chef/pipelines/feature.ts

Added
new file mode 100644
1 +import { fragment, pipeline, step } from "../pipeline/builder";
2 +import { z } from "zod";
4 +// Reusable review fragment
5 +const reviewFragment = fragment("review", [
6 + step("review_security", {
7 + agent: "security",
8 + prompt: "Review the implementation for security vulnerabilities",
9 + output: z.object({
10 + passed: z.boolean(),
11 + findings: z.array(z.string()),
12 + }),
13 + timeout: 60000,
14 + }),
15 + step("review_quality", {
16 + agent: "reviewer",
17 + prompt: (ctx) => `Review code quality for:\n${ctx.implement.summary}`,
18 + output: z.object({
19 + passed: z.boolean(),
20 + feedback: z.array(z.string()),
21 + }),
22 + timeout: 60000,
23 + }),
24 +]);
26 +export default pipeline("feature")
27 + .step("research", {
28 + agent: "researcher",
29 + prompt: "Research the codebase and identify relevant files and patterns",
30 + output: z.object({
31 + findings: z.string().describe("Summary of research findings"),
32 + files: z.array(z.string()).describe("List of relevant files"),
33 + patterns: z.array(z.string()).describe("Identified patterns"),
34 + }),
35 + })
36 + .step("plan", {
37 + agent: "planner",
38 + prompt: (ctx) =>
39 + `Based on the research findings, create an implementation plan.\n\nResearch:\n${ctx.research.findings}\n\nFiles:\n${
40 + ctx.research.files.join("\n")
41 + }`,
42 + output: z.object({
43 + tasks: z.array(z.string()).describe("List of implementation tasks"),
44 + approach: z.string().describe("Overall approach"),
45 + risks: z.array(z.string()).describe("Potential risks"),
46 + }),
47 + })
48 + .gate("approval", {
49 + agent: "devil",
50 + expect: z.object({
51 + approved: z.boolean().describe("Whether the plan is approved"),
52 + feedback: z.string().optional().describe("Feedback if not approved"),
53 + }),
54 + onFail: "plan",
55 + })
56 + .when((ctx) => !ctx.approval.approved)
57 + .loop("plan")
58 + .step("implement", {
59 + agent: "programmer",
60 + prompt: (ctx) =>
61 + `Implement the approved plan.\n\nTasks:\n${
62 + ctx.plan.tasks.join("\n")
63 + }\n\nApproach: ${ctx.plan.approach}`,
64 + output: z.object({
65 + completed: z.array(z.string()).describe("Completed tasks"),
66 + modified_files: z.array(z.string()).describe("Modified files"),
67 + summary: z.string().describe("Implementation summary"),
68 + }),
69 + retry: {
70 + maxAttempts: 3,
71 + backoffMs: 2000,
72 + retryOn: ["agent_error", "agent_timeout"],
73 + },
74 + })
75 + .use(reviewFragment)
76 + .build();

opencode/plugins/chef/store.ts

Added
new file mode 100644
1 +import { Database } from "bun:sqlite";
2 +import { join } from "path";
3 +import { randomUUID } from "crypto";
5 +export type PipelineStatus =
6 + | "running"
7 + | "completed"
8 + | "failed"
9 + | "aborted"
10 + | "needs_input";
11 +export type PhaseStatus =
12 + | "pending"
13 + | "running"
14 + | "completed"
15 + | "failed"
16 + | "skipped";
17 +export type StepStatus = "pending" | "running" | "completed" | "failed";
19 +export interface PipelineInstance {
20 + id: string;
21 + definition: string;
22 + status: PipelineStatus;
23 + input: string;
24 + context: string;
25 + current_phase: number;
26 + created_at: number;
27 + updated_at: number;
30 +export interface PhaseState {
31 + id: string;
32 + pipeline_id: string;
33 + name: string;
34 + status: PhaseStatus;
35 + output: string;
36 + error: string | null;
37 + attempts: number;
38 + started_at: number | null;
39 + completed_at: number | null;
42 +export interface StepState {
43 + id: string;
44 + phase_id: string;
45 + name: string;
46 + agent: string;
47 + status: StepStatus;
48 + output: string;
49 + error: string | null;
50 + attempts: number;
53 +export class Store {
54 + private db: Database;
56 + constructor(directory: string) {
57 + const dbPath = join(directory, ".opencode/chef/chef.db");
58 + this.db = new Database(dbPath);
59 + this.db.run("PRAGMA journal_mode = WAL");
60 + this.initSchema();
61 + }
63 + private initSchema() {
64 + this.db.run(`
65 + CREATE TABLE IF NOT EXISTS pipeline_instance (
66 + id TEXT PRIMARY KEY,
67 + definition TEXT NOT NULL,
68 + status TEXT NOT NULL,
69 + input TEXT,
70 + context TEXT,
71 + current_phase INTEGER DEFAULT 0,
72 + created_at INTEGER,
73 + updated_at INTEGER
74 + )
75 + `);
77 + this.db.run(`
78 + CREATE TABLE IF NOT EXISTS phase_state (
79 + id TEXT PRIMARY KEY,
80 + pipeline_id TEXT NOT NULL,
81 + name TEXT NOT NULL,
82 + status TEXT NOT NULL,
83 + output TEXT,
84 + error TEXT,
85 + attempts INTEGER DEFAULT 0,
86 + started_at INTEGER,
87 + completed_at INTEGER,
88 + FOREIGN KEY (pipeline_id) REFERENCES pipeline_instance(id)
89 + )
90 + `);
92 + this.db.run(`
93 + CREATE TABLE IF NOT EXISTS step_state (
94 + id TEXT PRIMARY KEY,
95 + phase_id TEXT NOT NULL,
96 + name TEXT NOT NULL,
97 + agent TEXT NOT NULL,
98 + status TEXT NOT NULL,
99 + output TEXT,
100 + error TEXT,
101 + attempts INTEGER DEFAULT 0,
102 + FOREIGN KEY (phase_id) REFERENCES phase_state(id)
104 + `);
106 + // Add indexes for foreign key lookups
107 + this.db.run(
108 + "CREATE INDEX IF NOT EXISTS idx_phase_pipeline ON phase_state(pipeline_id)",
109 + );
110 + this.db.run(
111 + "CREATE INDEX IF NOT EXISTS idx_step_phase ON step_state(phase_id)",
112 + );
115 + // Pipeline operations
116 + createPipeline(definition: string, input: any): PipelineInstance {
117 + const id = randomUUID();
118 + const now = Date.now();
120 + this.db.run(
121 + `INSERT INTO pipeline_instance (id, definition, status, input, context, current_phase, created_at, updated_at)
122 + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
123 + [id, definition, "running", JSON.stringify(input), "{}", 0, now, now],
124 + );
126 + return this.getPipeline(id)!;
129 + getPipeline(id: string): PipelineInstance | null {
130 + const result = this.db.query<PipelineInstance, [string]>(
131 + "SELECT * FROM pipeline_instance WHERE id = ?",
132 + ).get(id);
134 + return result || null;
137 + private updateRecord(
138 + table: string,
139 + id: string,
140 + updates: Record<string, any>,
141 + withTimestamp = false,
142 + ): void {
143 + const filtered = Object.fromEntries(
144 + Object.entries(updates).filter(([k]) => k !== "id"),
145 + );
146 + if (Object.keys(filtered).length === 0) {
147 + if (withTimestamp) {
148 + this.db.run(
149 + `UPDATE ${table} SET updated_at = ? WHERE id = ?`,
150 + [Date.now(), id],
151 + );
153 + return;
155 + const fields = Object.keys(filtered).map((k) => `${k} = ?`).join(", ");
156 + const values = withTimestamp
157 + ? [...Object.values(filtered), Date.now(), id]
158 + : [...Object.values(filtered), id];
159 + const suffix = withTimestamp ? ", updated_at = ?" : "";
160 + this.db.run(
161 + `UPDATE ${table} SET ${fields}${suffix} WHERE id = ?`,
162 + values,
163 + );
166 + updatePipeline(id: string, updates: Partial<PipelineInstance>): void {
167 + this.updateRecord("pipeline_instance", id, updates, true);
170 + listPipelines(status?: PipelineStatus): PipelineInstance[] {
171 + if (status) {
172 + return this.db.query<PipelineInstance, [string]>(
173 + "SELECT * FROM pipeline_instance WHERE status = ? ORDER BY created_at DESC",
174 + ).all(status);
177 + return this.db.query<PipelineInstance, []>(
178 + "SELECT * FROM pipeline_instance ORDER BY created_at DESC",
179 + ).all([]);
182 + // Phase operations
183 + createPhase(pipelineId: string, name: string): PhaseState {
184 + const id = randomUUID();
186 + this.db.run(
187 + `INSERT INTO phase_state (id, pipeline_id, name, status, output, error, attempts, started_at, completed_at)
188 + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
189 + [id, pipelineId, name, "pending", "{}", null, 0, null, null],
190 + );
192 + return this.getPhase(id)!;
195 + getPhase(id: string): PhaseState | null {
196 + const result = this.db.query<PhaseState, [string]>(
197 + "SELECT * FROM phase_state WHERE id = ?",
198 + ).get(id);
200 + return result || null;
203 + updatePhase(id: string, updates: Partial<PhaseState>): void {
204 + this.updateRecord("phase_state", id, updates);
207 + getPhasesByPipeline(pipelineId: string): PhaseState[] {
208 + return this.db.query<PhaseState, [string]>(
209 + "SELECT * FROM phase_state WHERE pipeline_id = ? ORDER BY started_at ASC",
210 + ).all(pipelineId);
213 + // Step operations
214 + createStep(phaseId: string, name: string, agent: string): StepState {
215 + const id = randomUUID();
217 + this.db.run(
218 + `INSERT INTO step_state (id, phase_id, name, agent, status, output, error, attempts)
219 + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
220 + [id, phaseId, name, agent, "pending", "{}", null, 0],
221 + );
223 + return this.getStep(id)!;
226 + getStep(id: string): StepState | null {
227 + const result = this.db.query<StepState, [string]>(
228 + "SELECT * FROM step_state WHERE id = ?",
229 + ).get(id);
231 + return result || null;
234 + updateStep(id: string, updates: Partial<StepState>): void {
235 + this.updateRecord("step_state", id, updates);
238 + getStepsByPhase(phaseId: string): StepState[] {
239 + return this.db.query<StepState, [string]>(
240 + "SELECT * FROM step_state WHERE phase_id = ?",
241 + ).all(phaseId);
244 + close() {
245 + this.db.close();