opencode-swarm-plugin 0.6.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,689 +3,332 @@
3
3
  [![npm version](https://img.shields.io/npm/v/opencode-swarm-plugin.svg)](https://www.npmjs.com/package/opencode-swarm-plugin)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- Multi-agent swarm coordination for [OpenCode](https://opencode.ai) with learning capabilities, beads integration, and Agent Mail.
7
-
8
- ## Overview
9
-
10
- This plugin provides intelligent, self-improving tools for multi-agent workflows in OpenCode:
11
-
12
- - **Type-safe beads operations** - Zod-validated wrappers around the `bd` CLI with proper error handling
13
- - **Agent Mail integration** - File reservations, async messaging, and thread coordination between agents
14
- - **Structured outputs** - Reliable JSON responses with schema validation and retry support
15
- - **Swarm primitives** - Task decomposition, status tracking, and parallel agent coordination
16
- - **Learning from outcomes** - Confidence decay, implicit feedback scoring, and pattern maturity tracking
17
- - **Anti-pattern detection** - Automatically learns what decomposition strategies fail and avoids them
18
- - **Pre-completion validation** - UBS bug scanning before marking tasks complete
19
- - **History-informed decomposition** - Queries CASS for similar past tasks to inform strategy
20
- - **Graceful degradation** - Works with whatever tools are available, degrades features when tools missing
21
- - **Swarm discipline** - Enforces beads tracking, aggressive planning, and agent communication
6
+ ```
7
+ ███████╗██╗ ██╗ █████╗ ██████╗ ███╗ ███╗
8
+ ██╔════╝██║ ██║██╔══██╗██╔══██╗████╗ ████║
9
+ ███████╗██║ █╗ ██║███████║██████╔╝██╔████╔██║
10
+ ╚════██║██║███╗██║██╔══██║██╔══██╗██║╚██╔╝██║
11
+ ███████║╚███╔███╔╝██║ ██║██║ ██║██║ ╚═╝ ██║
12
+ ╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝
22
13
 
23
- ## Quick Start
14
+ \ ` - ' /
15
+ - .(o o). -
16
+ ( >.< ) Multi-agent coordination for OpenCode
17
+ /| |\ Break complex tasks into parallel subtasks,
18
+ (_| |_) spawn agents, coordinate via messaging.
19
+ bzzzz... The plugin learns from outcomes.
20
+ ```
24
21
 
25
- ### 1. Install Dependencies
22
+ ## Install
26
23
 
27
24
  ```bash
28
- # OpenCode (plugin host)
29
- brew install sst/tap/opencode
30
-
31
- # Beads CLI (issue tracking)
32
- npm install -g @joelhooks/beads
33
- ```
34
-
35
- ### 2. Install Plugin
25
+ npm install -g opencode-swarm-plugin
26
+ swarm setup
27
+ ```
28
+
29
+ The setup wizard handles everything:
30
+
31
+ ```
32
+ ┌ opencode-swarm-plugin v0.10.0
33
+
34
+ ◇ Checking dependencies...
35
+
36
+ ◆ OpenCode
37
+ ◆ Beads
38
+ ◆ Go
39
+ ▲ Agent Mail (optional)
40
+ ▲ Redis (optional)
41
+
42
+ ◆ Install optional dependencies?
43
+ │ ◻ Agent Mail - Multi-agent coordination
44
+ │ ◻ Redis - Rate limiting
45
+
46
+ ◇ Setting up OpenCode integration...
47
+
48
+ ◆ Plugin: ~/.config/opencode/plugins/swarm.ts
49
+ ◆ Command: ~/.config/opencode/commands/swarm.md
50
+ ◆ Agent: ~/.config/opencode/agents/swarm-planner.md
51
+
52
+ └ Setup complete!
53
+ ```
54
+
55
+ Then in your project:
36
56
 
37
57
  ```bash
38
- npm install opencode-swarm-plugin
58
+ cd your-project
59
+ swarm init
39
60
  ```
40
61
 
41
- ### 3. Create Plugin Wrapper
62
+ ## CLI
42
63
 
43
- Create a file at `~/.config/opencode/plugins/swarm.ts`:
44
-
45
- ```ts
46
- import { SwarmPlugin } from "opencode-swarm-plugin";
47
- export default SwarmPlugin;
64
+ ```
65
+ swarm setup Interactive installer - checks and installs all dependencies
66
+ swarm doctor Health check - shows status of all dependencies
67
+ swarm init Initialize beads in current project
68
+ swarm config Show paths to generated config files
69
+ swarm version Show version and banner
70
+ swarm help Show help
48
71
  ```
49
72
 
50
- That's it! OpenCode will load the plugin automatically.
51
-
52
- ### 4. Copy Examples (Recommended)
53
-
54
- ```bash
55
- # Create directories
56
- mkdir -p ~/.config/opencode/commands ~/.config/opencode/agents
73
+ ## Usage
57
74
 
58
- # Copy /swarm command
59
- cp node_modules/opencode-swarm-plugin/examples/commands/swarm.md ~/.config/opencode/commands/
75
+ In OpenCode:
60
76
 
61
- # Copy @swarm-planner agent
62
- cp node_modules/opencode-swarm-plugin/examples/agents/swarm-planner.md ~/.config/opencode/agents/
77
+ ```
78
+ /swarm "Add user authentication with OAuth"
63
79
  ```
64
80
 
65
- ### 5. Initialize Beads in Your Project
81
+ Or invoke the planner directly:
66
82
 
67
- ```bash
68
- cd your-project
69
- bd init
83
+ ```
84
+ @swarm-planner "Refactor all components to use hooks"
70
85
  ```
71
86
 
72
- ### Alternative: Direct Copy (No Wrapper)
87
+ ## Customization
73
88
 
74
- If you prefer not to use the wrapper pattern:
89
+ Run `swarm config` to see your config file paths:
75
90
 
76
- ```bash
77
- mkdir -p ~/.config/opencode/plugins
78
- cp node_modules/opencode-swarm-plugin/dist/plugin.js ~/.config/opencode/plugins/swarm.js
79
91
  ```
92
+ 🔌 Plugin loader
93
+ ~/.config/opencode/plugins/swarm.ts
80
94
 
81
- ## Dependencies
95
+ 📜 /swarm command prompt
96
+ ~/.config/opencode/commands/swarm.md
82
97
 
83
- ### Required
98
+ 🤖 @swarm-planner agent
99
+ ~/.config/opencode/agents/swarm-planner.md
100
+ ```
84
101
 
85
- | Dependency | Purpose | Install |
86
- | ----------------------------------------------- | ------------------------- | --------------------------------- |
87
- | [OpenCode](https://opencode.ai) | Plugin host | `brew install sst/tap/opencode` |
88
- | [Beads CLI](https://github.com/joelhooks/beads) | Git-backed issue tracking | `npm install -g @joelhooks/beads` |
102
+ ### /swarm Command
89
103
 
90
- ### Optional (Graceful Degradation)
104
+ The `/swarm` command is defined in `~/.config/opencode/commands/swarm.md`:
91
105
 
92
- The plugin works without these, but with reduced functionality:
106
+ ```markdown
107
+ ---
108
+ description: Decompose task into parallel subtasks and coordinate agents
109
+ ---
93
110
 
94
- | Dependency | Purpose | Without It |
95
- | ----------------------------------------------------- | ------------------------ | ---------------------------------------- |
96
- | [Agent Mail](https://github.com/joelhooks/agent-mail) | Multi-agent coordination | No file reservations, no agent messaging |
97
- | [Redis](https://redis.io) | Rate limiting | Falls back to SQLite |
98
- | [CASS](https://github.com/Dicklesworthstone/cass) | Historical context | No "similar past tasks" in decomposition |
99
- | [UBS](https://github.com/joelhooks/ubs) | Bug scanning | No pre-completion validation |
111
+ You are a swarm coordinator. Take a complex task, break it into beads,
112
+ and unleash parallel agents.
100
113
 
101
- ### Verify Installation
114
+ ## Usage
102
115
 
103
- ```bash
104
- # Check OpenCode
105
- opencode --version
116
+ /swarm <task description or bead-id>
106
117
 
107
- # Check Beads
108
- bd --version
118
+ ## Workflow
109
119
 
110
- # Check Agent Mail (if using multi-agent)
111
- curl http://127.0.0.1:8765/health/liveness
120
+ 1. **Initialize**: `agentmail_init` with project_path and task_description
121
+ 2. **Decompose**: Use `swarm_select_strategy` then `swarm_plan_prompt`
122
+ 3. **Create beads**: `beads_create_epic` with subtasks and file assignments
123
+ 4. **Reserve files**: `agentmail_reserve` for each subtask's files
124
+ 5. **Spawn agents**: Use Task tool with `swarm_spawn_subtask` prompts
125
+ 6. **Monitor**: Check `agentmail_inbox` for progress
126
+ 7. **Complete**: `swarm_complete` when done, then `beads_sync` to push
112
127
 
113
- # Check Redis (optional)
114
- redis-cli ping
115
- ```
116
-
117
- ## Installation Details
128
+ ## Strategy Selection
118
129
 
119
- ### From npm
130
+ | Strategy | Best For | Keywords |
131
+ | ------------- | ----------------------- | ------------------------------------- |
132
+ | file-based | Refactoring, migrations | refactor, migrate, rename, update all |
133
+ | feature-based | New features | add, implement, build, create |
134
+ | risk-based | Bug fixes, security | fix, bug, security, critical, urgent |
120
135
 
121
- ```bash
122
- npm install opencode-swarm-plugin
123
- # or
124
- bun add opencode-swarm-plugin
125
- # or
126
- pnpm add opencode-swarm-plugin
136
+ Begin decomposition now.
127
137
  ```
128
138
 
129
- ### Plugin Setup (Wrapper Pattern)
139
+ ### @swarm-planner Agent
130
140
 
131
- Create `~/.config/opencode/plugins/swarm.ts`:
141
+ The `@swarm-planner` agent is defined in `~/.config/opencode/agents/swarm-planner.md`:
132
142
 
133
- ```ts
134
- import { SwarmPlugin } from "opencode-swarm-plugin";
135
- export default SwarmPlugin;
136
- ```
143
+ ````markdown
144
+ ---
145
+ name: swarm-planner
146
+ description: Strategic task decomposition for swarm coordination
147
+ model: claude-sonnet-4-5
148
+ ---
137
149
 
138
- OpenCode runs on Bun and loads TypeScript directly - no build step needed.
150
+ You are a swarm planner. Decompose tasks into optimal parallel subtasks.
139
151
 
140
- ### Plugin Setup (Direct Copy)
152
+ ## Workflow
141
153
 
142
- Alternatively, copy the pre-built bundle:
154
+ 1. Call `swarm_select_strategy` to analyze the task
155
+ 2. Call `swarm_plan_prompt` to get strategy-specific guidance
156
+ 3. Create a BeadTree following the guidelines
157
+ 4. Return ONLY valid JSON - no markdown, no explanation
143
158
 
144
- ```bash
145
- mkdir -p ~/.config/opencode/plugins
146
- cp node_modules/opencode-swarm-plugin/dist/plugin.js ~/.config/opencode/plugins/swarm.js
159
+ ## Output Format
160
+
161
+ ```json
162
+ {
163
+ "epic": { "title": "...", "description": "..." },
164
+ "subtasks": [
165
+ {
166
+ "title": "...",
167
+ "description": "...",
168
+ "files": ["src/..."],
169
+ "dependencies": [],
170
+ "estimated_complexity": 2
171
+ }
172
+ ]
173
+ }
147
174
  ```
175
+ ````
148
176
 
149
- ### Example Files
177
+ ## Rules
150
178
 
151
- Copy the `/swarm` command and `@swarm-planner` agent:
179
+ - 2-7 subtasks (too few = not parallel, too many = overhead)
180
+ - No file overlap between subtasks
181
+ - Include tests with the code they test
182
+ - Order by dependency (if B needs A, A comes first)
152
183
 
153
- ```bash
154
- # Command
155
- mkdir -p ~/.config/opencode/commands
156
- cp node_modules/opencode-swarm-plugin/examples/commands/swarm.md ~/.config/opencode/commands/
184
+ ````
157
185
 
158
- # Agent
159
- mkdir -p ~/.config/opencode/agents
160
- cp node_modules/opencode-swarm-plugin/examples/agents/swarm-planner.md ~/.config/opencode/agents/
161
- ```
186
+ Edit these files to customize behavior. Run `swarm setup` to regenerate defaults.
162
187
 
163
- > **Note:** The package has two entry points:
164
- >
165
- > - `dist/index.js` - Full library exports (schemas, errors, utilities, learning modules)
166
- > - `dist/plugin.js` - Plugin entry point that only exports the `plugin` function for OpenCode
188
+ ## Dependencies
167
189
 
168
- ## Tools Reference
190
+ | Dependency | Purpose | Required |
191
+ |------------|---------|----------|
192
+ | [OpenCode](https://opencode.ai) | Plugin host | Yes |
193
+ | [Beads](https://github.com/steveyegge/beads) | Git-backed issue tracking | Yes |
194
+ | [Go](https://go.dev) | Required for Agent Mail | No |
195
+ | [Agent Mail](https://github.com/joelhooks/agent-mail) | Multi-agent coordination, file reservations | No |
196
+ | [CASS](https://github.com/Dicklesworthstone/cass) | Historical context from past sessions | No |
197
+ | [UBS](https://github.com/joelhooks/ubs) | Pre-completion bug scanning | No |
198
+ | [semantic-memory](https://github.com/joelhooks/semantic-memory) | Learning persistence | No |
199
+ | [Redis](https://redis.io) | Rate limiting (SQLite fallback available) | No |
169
200
 
170
- ### Beads Tools
171
-
172
- | Tool | Description |
173
- | ------------------- | ------------------------------------------------------------------- |
174
- | `beads_create` | Create a new bead with type-safe validation |
175
- | `beads_create_epic` | Create epic with subtasks in one atomic operation |
176
- | `beads_query` | Query beads with filters (replaces `bd list`, `bd ready`, `bd wip`) |
177
- | `beads_update` | Update bead status/description/priority |
178
- | `beads_close` | Close a bead with reason |
179
- | `beads_start` | Mark bead as in-progress (shortcut) |
180
- | `beads_ready` | Get next ready bead (unblocked, highest priority) |
181
- | `beads_sync` | Sync beads to git and push (MANDATORY at session end) |
182
- | `beads_link_thread` | Link bead to Agent Mail thread |
183
-
184
- ### Agent Mail Tools
185
-
186
- | Tool | Description |
187
- | ---------------------------- | ---------------------------------------------------- |
188
- | `agentmail_init` | Initialize session (ensure project + register agent) |
189
- | `agentmail_send` | Send message to other agents |
190
- | `agentmail_inbox` | Fetch inbox (CONTEXT-SAFE: bodies excluded, limit 5) |
191
- | `agentmail_read_message` | Fetch ONE message body by ID |
192
- | `agentmail_summarize_thread` | Summarize thread (PREFERRED over fetching all) |
193
- | `agentmail_reserve` | Reserve file paths for exclusive editing |
194
- | `agentmail_release` | Release file reservations |
195
- | `agentmail_ack` | Acknowledge a message |
196
- | `agentmail_search` | Search messages (FTS5 syntax) |
197
- | `agentmail_health` | Check if Agent Mail server is running |
201
+ All dependencies are checked and can be installed via `swarm setup`.
198
202
 
199
- ## Rate Limiting
203
+ ## Tools Reference
200
204
 
201
- Client-side, per-agent rate limits prevent abuse and ensure fair resource usage across agents. Uses Redis as primary store (`localhost:6379`) with automatic SQLite fallback (`~/.config/opencode/rate-limits.db`).
202
-
203
- ### Default Limits
204
-
205
- | Endpoint | Per Minute | Per Hour |
206
- | ------------------ | ---------- | -------- |
207
- | `send` | 20 | 200 |
208
- | `reserve` | 10 | 100 |
209
- | `release` | 10 | 100 |
210
- | `ack` | 20 | 200 |
211
- | `inbox` | 60 | 600 |
212
- | `read_message` | 60 | 600 |
213
- | `summarize_thread` | 30 | 300 |
214
- | `search` | 30 | 300 |
215
-
216
- ### Configuration
217
-
218
- | Environment Variable | Description |
219
- | ----------------------------------------- | --------------------------------------------------------------------------- |
220
- | `OPENCODE_RATE_LIMIT_REDIS_URL` | Redis connection URL (default: `redis://localhost:6379`) |
221
- | `OPENCODE_RATE_LIMIT_SQLITE_PATH` | SQLite database path (default: `~/.config/opencode/rate-limits.db`) |
222
- | `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN` | Per-minute limit for endpoint (e.g., `OPENCODE_RATE_LIMIT_SEND_PER_MIN=30`) |
223
- | `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_HOUR` | Per-hour limit for endpoint (e.g., `OPENCODE_RATE_LIMIT_SEND_PER_HOUR=300`) |
224
-
225
- ### Troubleshooting
226
-
227
- - **Rate limit exceeded errors** - Adjust limits via environment variables for your workload
228
- - **Redis unavailable** - Automatic SQLite fallback with warning logged; no action needed
229
- - **SQLite cleanup** - Expired entries cleaned automatically on init
230
-
231
- ### Swarm Tools
232
-
233
- | Tool | Description |
234
- | ------------------------------ | ------------------------------------------------------------------------ |
235
- | `swarm_init` | Check tool availability, report degraded features |
236
- | `swarm_select_strategy` | Analyze task and recommend decomposition strategy |
237
- | `swarm_plan_prompt` | Generate strategy-specific planning prompt with CASS integration |
238
- | `swarm_decompose` | Generate decomposition prompt, optionally queries CASS for similar tasks |
239
- | `swarm_validate_decomposition` | Validate decomposition response, detect instruction conflicts |
240
- | `swarm_status` | Get swarm status by epic ID |
241
- | `swarm_progress` | Report progress on a subtask |
242
- | `swarm_complete` | Mark subtask complete with UBS bug scan, release reservations |
243
- | `swarm_record_outcome` | Record outcome for implicit feedback (duration, errors, retries) |
244
- | `swarm_subtask_prompt` | Generate prompt for spawned subtask agent (V1 - includes coordination) |
245
- | `swarm_spawn_subtask` | Generate V2 prompt with Agent Mail/beads instructions for subagents |
246
- | `swarm_complete_subtask` | Handle subtask completion: close bead, create issue beads |
247
- | `swarm_evaluation_prompt` | Generate self-evaluation prompt |
248
-
249
- ### Structured Output Tools
250
-
251
- | Tool | Description |
252
- | -------------------------------- | -------------------------------------------------------- |
253
- | `structured_extract_json` | Extract JSON from markdown/text with multiple strategies |
254
- | `structured_validate` | Validate response against named schema |
255
- | `structured_parse_evaluation` | Parse and validate evaluation response |
256
- | `structured_parse_decomposition` | Parse and validate task decomposition |
257
- | `structured_parse_bead_tree` | Parse and validate bead tree for epic creation |
205
+ ### Swarm
206
+
207
+ | Tool | Description |
208
+ |------|-------------|
209
+ | `swarm_init` | Initialize swarm session |
210
+ | `swarm_select_strategy` | Analyze task, recommend decomposition strategy (file/feature/risk-based) |
211
+ | `swarm_plan_prompt` | Generate strategy-specific planning prompt with CASS history |
212
+ | `swarm_decompose` | Generate decomposition prompt |
213
+ | `swarm_validate_decomposition` | Validate response, detect file conflicts |
214
+ | `swarm_spawn_subtask` | Generate worker agent prompt with Agent Mail/beads instructions |
215
+ | `swarm_status` | Get swarm progress by epic ID |
216
+ | `swarm_progress` | Report subtask progress to coordinator |
217
+ | `swarm_complete` | Complete subtask - runs UBS scan, releases reservations |
218
+ | `swarm_record_outcome` | Record outcome for learning (duration, errors, retries) |
219
+
220
+ ### Beads
221
+
222
+ | Tool | Description |
223
+ |------|-------------|
224
+ | `beads_create` | Create bead with type-safe validation |
225
+ | `beads_create_epic` | Create epic + subtasks atomically |
226
+ | `beads_query` | Query beads with filters (status, type, ready) |
227
+ | `beads_update` | Update status/description/priority |
228
+ | `beads_close` | Close bead with reason |
229
+ | `beads_start` | Mark bead as in-progress |
230
+ | `beads_ready` | Get next unblocked bead |
231
+ | `beads_sync` | Sync to git and push |
232
+ | `beads_link_thread` | Link bead to Agent Mail thread |
233
+
234
+ ### Agent Mail
235
+
236
+ | Tool | Description |
237
+ |------|-------------|
238
+ | `agentmail_init` | Initialize session, register agent |
239
+ | `agentmail_send` | Send message to agents |
240
+ | `agentmail_inbox` | Fetch inbox (max 5, no bodies - context safe) |
241
+ | `agentmail_read_message` | Fetch single message body by ID |
242
+ | `agentmail_summarize_thread` | Summarize thread (preferred over fetching all) |
243
+ | `agentmail_reserve` | Reserve file paths for exclusive editing |
244
+ | `agentmail_release` | Release file reservations |
245
+ | `agentmail_ack` | Acknowledge message |
246
+ | `agentmail_search` | Search messages by keyword |
247
+ | `agentmail_health` | Check if Agent Mail server is running |
248
+
249
+ ### Structured Output
250
+
251
+ | Tool | Description |
252
+ |------|-------------|
253
+ | `structured_extract_json` | Extract JSON from markdown/text (multiple strategies) |
254
+ | `structured_validate` | Validate response against schema |
255
+ | `structured_parse_evaluation` | Parse self-evaluation response |
256
+ | `structured_parse_decomposition` | Parse task decomposition response |
257
+ | `structured_parse_bead_tree` | Parse bead tree for epic creation |
258
258
 
259
259
  ## Decomposition Strategies
260
260
 
261
- The plugin supports three decomposition strategies, auto-selected based on task keywords:
262
-
263
- ### File-Based Strategy
264
-
265
- Best for: Refactoring, migrations, pattern changes across codebase
266
-
267
- **Keywords**: refactor, migrate, rename, update all, convert, upgrade
261
+ ### File-Based
268
262
 
269
- **Guidelines**:
263
+ Best for: refactoring, migrations, pattern changes
270
264
 
271
265
  - Group files by directory or type
272
266
  - Handle shared types/utilities first
273
267
  - Minimize cross-directory dependencies
274
268
 
275
- ### Feature-Based Strategy
269
+ **Keywords**: refactor, migrate, rename, update all, replace
276
270
 
277
- Best for: New features, adding functionality
271
+ ### Feature-Based
278
272
 
279
- **Keywords**: add, implement, build, create, feature, new
280
-
281
- **Guidelines**:
273
+ Best for: new features, adding functionality
282
274
 
283
275
  - Each subtask is a complete vertical slice
284
276
  - Start with data layer, then logic, then UI
285
277
  - Keep related components together
286
278
 
287
- ### Risk-Based Strategy
288
-
289
- Best for: Bug fixes, security issues, critical changes
279
+ **Keywords**: add, implement, build, create, feature
290
280
 
291
- **Keywords**: fix, bug, security, critical, urgent, hotfix
281
+ ### Risk-Based
292
282
 
293
- **Guidelines**:
283
+ Best for: bug fixes, security issues
294
284
 
295
285
  - Write tests FIRST
296
286
  - Isolate risky changes
297
287
  - Audit similar code for same issue
298
288
 
299
- ### Strategy Selection
300
-
301
- Use `swarm_select_strategy` to see the recommended strategy:
302
-
303
- ```typescript
304
- swarm_select_strategy({ task: "Add user authentication" });
305
- // Returns: { strategy: "feature-based", confidence: 0.85, reasoning: "..." }
306
- ```
307
-
308
- Or let `swarm_plan_prompt` auto-select:
309
-
310
- ```typescript
311
- swarm_plan_prompt({ task: "Refactor all components to use hooks" });
312
- // Auto-selects file-based strategy
313
- ```
314
-
315
- ## Example Planner Agent
316
-
317
- The plugin includes an example planner agent at `examples/agents/swarm-planner.md`.
318
-
319
- Copy to your OpenCode agents directory:
320
-
321
- ```bash
322
- cp examples/agents/swarm-planner.md ~/.config/opencode/agents/
323
- ```
324
-
325
- Then invoke with:
326
-
327
- ```
328
- @swarm-planner "Add user authentication with OAuth"
329
- ```
330
-
331
- The planner uses `swarm_select_strategy` and `swarm_plan_prompt` internally to create optimal decompositions.
332
-
333
- ### Schemas (for structured outputs)
334
-
335
- The plugin exports Zod schemas for validated agent responses:
336
-
337
- | Schema | Purpose |
338
- | ---------------------------- | -------------------------------------------- |
339
- | `TaskDecompositionSchema` | Decompose task into parallelizable subtasks |
340
- | `EvaluationSchema` | Agent self-evaluation of completed work |
341
- | `WeightedEvaluationSchema` | Evaluation with confidence-weighted criteria |
342
- | `SwarmStatusSchema` | Swarm progress tracking |
343
- | `SwarmSpawnResultSchema` | Result of spawning agent swarm |
344
- | `BeadSchema` | Validated bead data |
345
- | `EpicCreateResultSchema` | Atomic epic creation result |
346
- | `FeedbackEventSchema` | Feedback event for learning |
347
- | `OutcomeSignalsSchema` | Implicit feedback from task outcomes |
348
- | `DecompositionPatternSchema` | Tracked decomposition pattern |
349
- | `PatternMaturitySchema` | Pattern maturity state tracking |
350
-
351
- ## Usage Examples
352
-
353
- ### Basic Bead Creation
354
-
355
- ```typescript
356
- // Create a bug report with priority
357
- await tools["beads_create"]({
358
- title: "Fix login redirect loop",
359
- type: "bug",
360
- priority: 1,
361
- description: "Users stuck in redirect after OAuth callback",
362
- });
363
- ```
364
-
365
- ### Atomic Epic with Subtasks
366
-
367
- ```typescript
368
- // Create epic and all subtasks atomically (with rollback hints on failure)
369
- const result = await tools["beads_create_epic"]({
370
- epic_title: "Implement user dashboard",
371
- epic_description: "New dashboard with metrics and activity feed",
372
- subtasks: [
373
- {
374
- title: "Create dashboard layout",
375
- priority: 2,
376
- files: ["src/components/Dashboard.tsx"],
377
- },
378
- {
379
- title: "Add metrics API endpoint",
380
- priority: 2,
381
- files: ["src/api/metrics.ts"],
382
- },
383
- {
384
- title: "Build activity feed component",
385
- priority: 3,
386
- files: ["src/components/ActivityFeed.tsx"],
387
- },
388
- ],
389
- });
390
- ```
391
-
392
- ### Agent Mail Coordination
393
-
394
- ```typescript
395
- // 1. Initialize session
396
- await tools["agentmail_init"]({
397
- project_path: "/Users/you/project",
398
- task_description: "Working on auth refactor",
399
- });
400
- // Returns: { agent: { name: "BlueLake", ... } }
401
-
402
- // 2. Reserve files before editing
403
- await tools["agentmail_reserve"]({
404
- paths: ["src/auth/**", "src/middleware/auth.ts"],
405
- reason: "bd-abc123: Auth refactor",
406
- ttl_seconds: 3600,
407
- });
408
-
409
- // 3. Check inbox (bodies excluded by default)
410
- const messages = await tools["agentmail_inbox"]({ limit: 5 });
411
-
412
- // 4. Send status update to other agents
413
- await tools["agentmail_send"]({
414
- to: ["RedStone", "GreenCastle"],
415
- subject: "Auth refactor complete",
416
- body: "Finished updating the auth middleware. Ready for review.",
417
- thread_id: "bd-abc123",
418
- });
419
-
420
- // 5. Release reservations when done
421
- await tools["agentmail_release"]({});
422
- ```
423
-
424
- ### Swarm Workflow
425
-
426
- ```typescript
427
- // 1. Create epic for the work
428
- const epic = await tools["beads_create_epic"]({
429
- epic_title: "Add export feature",
430
- subtasks: [
431
- { title: "Export to CSV", files: ["src/export/csv.ts"] },
432
- { title: "Export to JSON", files: ["src/export/json.ts"] },
433
- { title: "Export to PDF", files: ["src/export/pdf.ts"] },
434
- ],
435
- });
436
-
437
- // 2. Each parallel agent reserves its files
438
- // Agent 1 (BlueLake):
439
- await tools["agentmail_reserve"]({
440
- paths: ["src/export/csv.ts"],
441
- reason: `${epic.subtasks[0].id}: Export to CSV`,
442
- });
443
-
444
- // 3. Agents communicate via thread
445
- await tools["agentmail_send"]({
446
- to: ["Coordinator"],
447
- subject: "CSV export complete",
448
- body: "Implemented CSV export with streaming support.",
449
- thread_id: epic.epic.id,
450
- });
451
-
452
- // 4. Coordinator uses summarize_thread (not fetch all)
453
- const summary = await tools["agentmail_summarize_thread"]({
454
- thread_id: epic.epic.id,
455
- include_examples: true,
456
- });
457
- ```
458
-
459
- ## Learning Capabilities
460
-
461
- The plugin learns from swarm outcomes to improve future decompositions.
462
-
463
- ### Confidence Decay
464
-
465
- Evaluation criteria weights decay over time unless revalidated. If a criterion (e.g., `type_safe`) has been historically unreliable, its weight decreases.
466
-
467
- ```typescript
468
- import {
469
- calculateDecayedValue,
470
- calculateCriterionWeight,
471
- } from "opencode-swarm-plugin";
472
-
473
- // Value decays by 50% every 90 days (configurable half-life)
474
- const weight = calculateDecayedValue(timestamp, now, halfLifeDays);
475
-
476
- // Calculate criterion weight from feedback history
477
- const criterionWeight = calculateCriterionWeight(feedbackEvents);
478
- // { criterion: "type_safe", weight: 0.85, helpful_count: 10, harmful_count: 2 }
479
- ```
480
-
481
- ### Implicit Feedback Scoring
482
-
483
- The `swarm_record_outcome` tool tracks task outcomes and infers feedback:
484
-
485
- - **Fast completion + success** → helpful signal
486
- - **Slow completion + errors + retries** → harmful signal
487
-
488
- ```typescript
489
- // Record outcome after completing a subtask
490
- await tools["swarm_record_outcome"]({
491
- bead_id: "bd-abc123.1",
492
- duration_ms: 60000,
493
- error_count: 0,
494
- retry_count: 0,
495
- success: true,
496
- files_touched: ["src/auth.ts"],
497
- });
498
- // Returns feedback events for each criterion
499
- ```
500
-
501
- ### Anti-Pattern Learning
502
-
503
- Failed decomposition patterns are automatically inverted to anti-patterns:
289
+ **Keywords**: fix, bug, security, critical, urgent
504
290
 
505
- ```typescript
506
- import {
507
- recordPatternObservation,
508
- formatAntiPatternsForPrompt,
509
- } from "opencode-swarm-plugin";
291
+ ## Learning
510
292
 
511
- // Record pattern failure
512
- const result = recordPatternObservation(pattern, false, beadId);
513
- if (result.inversion) {
514
- // Pattern was inverted: "Split by file type" → "AVOID: Split by file type. Failed 4/5 times (80% failure rate)"
515
- }
516
-
517
- // Include anti-patterns in decomposition prompts
518
- const antiPatternContext = formatAntiPatternsForPrompt(patterns);
519
- ```
520
-
521
- ### Pattern Maturity
522
-
523
- Patterns progress through maturity states: `candidate` → `established` → `proven` (or `deprecated`).
524
-
525
- ```typescript
526
- import {
527
- calculateMaturityState,
528
- getMaturityMultiplier,
529
- } from "opencode-swarm-plugin";
530
-
531
- // Calculate state from feedback
532
- const state = calculateMaturityState(feedbackEvents);
533
- // "candidate" | "established" | "proven" | "deprecated"
534
-
535
- // Get weight multiplier for pattern ranking
536
- const multiplier = getMaturityMultiplier("proven"); // 1.5
537
- ```
293
+ The plugin learns from outcomes:
538
294
 
539
- ### UBS Pre-Completion Scan
540
-
541
- The `swarm_complete` tool runs UBS (Ultimate Bug Scanner) on modified files before marking complete:
542
-
543
- ```typescript
544
- await tools["swarm_complete"]({
545
- project_key: "/path/to/project",
546
- agent_name: "BlueLake",
547
- bead_id: "bd-abc123.1",
548
- summary: "Implemented auth flow",
549
- files_touched: ["src/auth.ts", "src/middleware.ts"],
550
- // skip_ubs_scan: true // Optional: bypass scan
551
- });
552
- // Blocks completion if critical bugs found
553
- ```
554
-
555
- ### CASS History Context
556
-
557
- The `swarm_decompose` tool queries CASS (Cross-Agent Session Search) for similar past tasks:
558
-
559
- ```typescript
560
- await tools["swarm_decompose"]({
561
- task: "Add user authentication with OAuth",
562
- max_subtasks: 5,
563
- query_cass: true, // Default: true
564
- cass_limit: 3, // Max results to include
565
- });
566
- // Includes successful patterns from past decompositions in context
567
- ```
295
+ | Mechanism | How It Works |
296
+ |-----------|--------------|
297
+ | Confidence decay | Criteria weights fade unless revalidated (90-day half-life) |
298
+ | Implicit feedback | Fast + success = helpful signal, slow + errors = harmful |
299
+ | Pattern maturity | candidate → established → proven (or deprecated) |
300
+ | Anti-patterns | Patterns with >60% failure rate auto-invert |
568
301
 
569
302
  ## Context Preservation
570
303
 
571
- **CRITICAL**: This plugin enforces context-safe defaults to prevent session exhaustion.
572
-
573
- ### Why These Constraints Exist
304
+ Hard limits to prevent context exhaustion:
574
305
 
575
- | Constraint | Default | Reason |
576
- | -------------------- | ---------------------------- | -------------------------------------------------- |
577
- | Inbox limit | 5 messages | Fetching 20+ messages with bodies exhausts context |
578
- | Bodies excluded | `include_bodies: false` | Message bodies can be huge; fetch individually |
579
- | Summarize over fetch | `summarize_thread` preferred | Get key points, not raw message dump |
306
+ | Constraint | Default | Reason |
307
+ |------------|---------|--------|
308
+ | Inbox limit | 5 messages | Prevents token burn |
309
+ | Bodies excluded | Always | Fetch individually when needed |
310
+ | Summarize preferred | Yes | Key points, not raw dump |
580
311
 
581
- ### The Pattern
582
-
583
- ```typescript
584
- // WRONG: This can dump thousands of tokens into context
585
- const messages = await tools["agentmail_inbox"]({
586
- limit: 20,
587
- include_bodies: true, // Plugin prevents this
588
- });
589
-
590
- // RIGHT: Headers only, then fetch specific messages
591
- const headers = await tools["agentmail_inbox"]({ limit: 5 });
592
- const importantMessage = await tools["agentmail_read_message"]({
593
- message_id: headers[0].id,
594
- });
595
-
596
- // BEST: Summarize threads instead of fetching all messages
597
- const summary = await tools["agentmail_summarize_thread"]({
598
- thread_id: "bd-abc123",
599
- });
600
- ```
601
-
602
- ### Hard Caps
603
-
604
- The plugin enforces these limits regardless of input:
605
-
606
- - `agentmail_inbox` - Max 5 messages, bodies always excluded
607
- - Thread summaries use LLM mode for concise output
608
- - File reservations auto-track for cleanup
609
-
610
- ## Custom Commands
611
-
612
- This plugin provides tools that work with OpenCode's [custom commands](https://opencode.ai/docs/commands). Create a `/swarm` command to orchestrate multi-agent work.
613
-
614
- ### Setup /swarm Command
615
-
616
- Copy the example command to your OpenCode config:
617
-
618
- ```bash
619
- cp examples/commands/swarm.md ~/.config/opencode/command/
620
- ```
621
-
622
- ### Usage
623
-
624
- ```
625
- /swarm "Add user authentication with OAuth providers"
626
- ```
627
-
628
- ### How It Works
629
-
630
- 1. **Decompose** - `swarm_decompose` breaks task into subtasks with file assignments
631
- 2. **Create beads** - `beads_create_epic` creates epic + subtasks atomically
632
- 3. **Spawn agents** - `swarm_spawn_subtask` generates prompts WITH Agent Mail/beads instructions
633
- 4. **Parallel work** - Subagents use Agent Mail to communicate, beads to track progress
634
- 5. **Coordination** - Agents report progress, ask questions, announce blockers via Agent Mail
635
- 6. **Completion** - Agents use `swarm_complete` when done
636
- 7. **Cleanup** - `beads_sync` pushes to git
637
-
638
- ### Subagent Capabilities
639
-
640
- Spawned subagents have **full access** to all plugin tools:
641
-
642
- - **Agent Mail** - `agentmail_send`, `agentmail_inbox`, `agentmail_reserve`, etc.
643
- - **Beads** - `beads_update`, `beads_create`, `swarm_complete`
644
- - All standard OpenCode tools
645
-
646
- The prompts tell agents to actively communicate and coordinate.
647
-
648
- ## Error Handling
312
+ ## Rate Limiting
649
313
 
650
- The plugin provides typed errors for robust error handling:
314
+ Client-side limits (Redis primary, SQLite fallback):
651
315
 
652
- ```typescript
653
- import {
654
- BeadError,
655
- BeadValidationError,
656
- AgentMailError,
657
- AgentMailNotInitializedError,
658
- FileReservationConflictError,
659
- } from "opencode-swarm-plugin";
316
+ | Endpoint | Per Minute | Per Hour |
317
+ |----------|------------|----------|
318
+ | send | 20 | 200 |
319
+ | reserve | 10 | 100 |
320
+ | inbox | 60 | 600 |
660
321
 
661
- try {
662
- await tools["agentmail_reserve"]({ paths: ["src/index.ts"] });
663
- } catch (error) {
664
- if (error instanceof FileReservationConflictError) {
665
- console.log("Conflicts:", error.conflicts);
666
- // [{ path: "src/index.ts", holders: ["RedStone"] }]
667
- }
668
- }
669
- ```
322
+ Configure via `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN` env vars.
670
323
 
671
324
  ## Development
672
325
 
673
326
  ```bash
674
- # Install dependencies
675
327
  bun install
676
-
677
- # Type check
678
328
  bun run typecheck
679
-
680
- # Run tests
681
329
  bun test
682
-
683
- # Build for distribution
684
330
  bun run build
685
-
686
- # Clean build artifacts
687
- bun run clean
688
- ```
331
+ ````
689
332
 
690
333
  ## License
691
334