Package Exports
- opencode-swarm-plugin
Readme
opencode-swarm-plugin
Type-safe multi-agent coordination for OpenCode with beads integration and Agent Mail.
Overview
This plugin provides structured, validated tools for multi-agent workflows in OpenCode:
- Type-safe beads operations - Zod-validated wrappers around the
bdCLI with proper error handling - Agent Mail integration - File reservations, async messaging, and thread coordination between agents
- Structured outputs - Reliable JSON responses with schema validation and retry support
- Swarm primitives - Task decomposition, status tracking, and parallel agent coordination
Installation
bun add opencode-swarm-pluginCopy the plugin to your OpenCode plugins directory:
cp node_modules/opencode-swarm-plugin/dist/plugin.js ~/.config/opencode/plugin/swarm.jsPlugins are automatically loaded from ~/.config/opencode/plugin/ - no config file changes needed.
Note: The package has two entry points:
dist/index.js- Full library exports (schemas, errors, utilities)dist/plugin.js- Plugin entry point that only exports thepluginfunction for OpenCode
Prerequisites
| Requirement | Purpose |
|---|---|
| OpenCode 1.0+ | Plugin host |
| Agent Mail MCP | Multi-agent coordination (localhost:8765) |
Beads CLI (bd) |
Git-backed issue tracking |
Verify Agent Mail is running
curl http://127.0.0.1:8765/health/livenessVerify beads is installed
bd --versionTools Reference
Beads Tools
| Tool | Description |
|---|---|
beads_create |
Create a new bead with type-safe validation |
beads_create_epic |
Create epic with subtasks in one atomic operation |
beads_query |
Query beads with filters (replaces bd list, bd ready, bd wip) |
beads_update |
Update bead status/description/priority |
beads_close |
Close a bead with reason |
beads_start |
Mark bead as in-progress (shortcut) |
beads_ready |
Get next ready bead (unblocked, highest priority) |
beads_sync |
Sync beads to git and push (MANDATORY at session end) |
beads_link_thread |
Link bead to Agent Mail thread |
Agent Mail Tools
| Tool | Description |
|---|---|
agentmail_init |
Initialize session (ensure project + register agent) |
agentmail_send |
Send message to other agents |
agentmail_inbox |
Fetch inbox (CONTEXT-SAFE: bodies excluded, limit 5) |
agentmail_read_message |
Fetch ONE message body by ID |
agentmail_summarize_thread |
Summarize thread (PREFERRED over fetching all) |
agentmail_reserve |
Reserve file paths for exclusive editing |
agentmail_release |
Release file reservations |
agentmail_ack |
Acknowledge a message |
agentmail_search |
Search messages (FTS5 syntax) |
agentmail_health |
Check if Agent Mail server is running |
Schemas (for structured outputs)
The plugin exports Zod schemas for validated agent responses:
| Schema | Purpose |
|---|---|
TaskDecompositionSchema |
Decompose task into parallelizable subtasks |
EvaluationSchema |
Agent self-evaluation of completed work |
SwarmStatusSchema |
Swarm progress tracking |
SwarmSpawnResultSchema |
Result of spawning agent swarm |
BeadSchema |
Validated bead data |
EpicCreateResultSchema |
Atomic epic creation result |
Usage Examples
Basic Bead Creation
// Create a bug report with priority
await tools["beads_create"]({
title: "Fix login redirect loop",
type: "bug",
priority: 1,
description: "Users stuck in redirect after OAuth callback",
});Atomic Epic with Subtasks
// Create epic and all subtasks atomically (with rollback hints on failure)
const result = await tools["beads_create_epic"]({
epic_title: "Implement user dashboard",
epic_description: "New dashboard with metrics and activity feed",
subtasks: [
{
title: "Create dashboard layout",
priority: 2,
files: ["src/components/Dashboard.tsx"],
},
{
title: "Add metrics API endpoint",
priority: 2,
files: ["src/api/metrics.ts"],
},
{
title: "Build activity feed component",
priority: 3,
files: ["src/components/ActivityFeed.tsx"],
},
],
});Agent Mail Coordination
// 1. Initialize session
await tools["agentmail_init"]({
project_path: "/Users/you/project",
task_description: "Working on auth refactor",
});
// Returns: { agent: { name: "BlueLake", ... } }
// 2. Reserve files before editing
await tools["agentmail_reserve"]({
paths: ["src/auth/**", "src/middleware/auth.ts"],
reason: "bd-abc123: Auth refactor",
ttl_seconds: 3600,
});
// 3. Check inbox (bodies excluded by default)
const messages = await tools["agentmail_inbox"]({ limit: 5 });
// 4. Send status update to other agents
await tools["agentmail_send"]({
to: ["RedStone", "GreenCastle"],
subject: "Auth refactor complete",
body: "Finished updating the auth middleware. Ready for review.",
thread_id: "bd-abc123",
});
// 5. Release reservations when done
await tools["agentmail_release"]({});Swarm Workflow
// 1. Create epic for the work
const epic = await tools["beads_create_epic"]({
epic_title: "Add export feature",
subtasks: [
{ title: "Export to CSV", files: ["src/export/csv.ts"] },
{ title: "Export to JSON", files: ["src/export/json.ts"] },
{ title: "Export to PDF", files: ["src/export/pdf.ts"] },
],
});
// 2. Each parallel agent reserves its files
// Agent 1 (BlueLake):
await tools["agentmail_reserve"]({
paths: ["src/export/csv.ts"],
reason: `${epic.subtasks[0].id}: Export to CSV`,
});
// 3. Agents communicate via thread
await tools["agentmail_send"]({
to: ["Coordinator"],
subject: "CSV export complete",
body: "Implemented CSV export with streaming support.",
thread_id: epic.epic.id,
});
// 4. Coordinator uses summarize_thread (not fetch all)
const summary = await tools["agentmail_summarize_thread"]({
thread_id: epic.epic.id,
include_examples: true,
});Context Preservation
CRITICAL: This plugin enforces context-safe defaults to prevent session exhaustion.
Why These Constraints Exist
| Constraint | Default | Reason |
|---|---|---|
| Inbox limit | 5 messages | Fetching 20+ messages with bodies exhausts context |
| Bodies excluded | include_bodies: false |
Message bodies can be huge; fetch individually |
| Summarize over fetch | summarize_thread preferred |
Get key points, not raw message dump |
The Pattern
// WRONG: This can dump thousands of tokens into context
const messages = await tools["agentmail_inbox"]({
limit: 20,
include_bodies: true, // Plugin prevents this
});
// RIGHT: Headers only, then fetch specific messages
const headers = await tools["agentmail_inbox"]({ limit: 5 });
const importantMessage = await tools["agentmail_read_message"]({
message_id: headers[0].id,
});
// BEST: Summarize threads instead of fetching all messages
const summary = await tools["agentmail_summarize_thread"]({
thread_id: "bd-abc123",
});Hard Caps
The plugin enforces these limits regardless of input:
agentmail_inbox- Max 5 messages, bodies always excluded- Thread summaries use LLM mode for concise output
- File reservations auto-track for cleanup
Integration with /swarm Command
This plugin provides the primitives used by OpenCode's /swarm command:
/swarm "Add user authentication with OAuth providers"The /swarm command uses this plugin to:
- Decompose - Break task into subtasks using
TaskDecompositionSchema - Create beads - Use
beads_create_epicfor atomic issue creation - Initialize agents - Each agent calls
agentmail_init - Reserve files - Prevent conflicts with
agentmail_reserve - Coordinate - Agents communicate via
agentmail_send - Track status - Use
SwarmStatusSchemafor progress - Evaluate - Validate work with
EvaluationSchema - Cleanup - Release reservations and sync beads
Error Handling
The plugin provides typed errors for robust error handling:
import {
BeadError,
BeadValidationError,
AgentMailError,
AgentMailNotInitializedError,
FileReservationConflictError,
} from "opencode-swarm-plugin";
try {
await tools["agentmail_reserve"]({ paths: ["src/index.ts"] });
} catch (error) {
if (error instanceof FileReservationConflictError) {
console.log("Conflicts:", error.conflicts);
// [{ path: "src/index.ts", holders: ["RedStone"] }]
}
}Development
# Install dependencies
bun install
# Type check
bun run typecheck
# Run tests
bun test
# Build for distribution
bun run build
# Clean build artifacts
bun run cleanLicense
MIT