npm package: @moderndegree/opencode-agent-teams
Description: Coordinator-mediated multi-agent orchestration plugin for OpenCode with structured memory, token budgets, and compression pipelines
Author: Brian Lewis
Latest version: 0.2.1
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# opencode-agent-teams

An [OpenCode](https://opencode.ai) plugin for coordinator-mediated multi-agent orchestration. Decomposes user requests into task graphs, dispatches work to specialized agents, and synthesizes results — without passing raw transcripts between agents.

**Targets:** ≥40% token reduction vs naive transcript passing, ≥95% validation pass rate.

## How it works

```
User Request → Coordinator (large) → TaskGraph → dispatch to subagents
  Subagents: Planner, Coder, Reviewer, Tester, Explorer (medium)
  Hidden agents: Summarizer, Validator (small)
  All communication via structured JSON through coordinator
```

The coordinator decomposes requests into a DAG of tasks, assigns them to specialized agents, monitors progress, and synthesizes the final result. Agents never share raw transcripts — only structured task descriptions and memory entries.

## Agents

| Agent | Tier | Default model | Role |
|---|---|---|---|
| coordinator | large | minimax-m2.5-free (Zen) | Decomposes, dispatches, synthesizes. Never writes code. |
| planner | medium | qwen3:14b (Ollama) | Read-only exploration → structured plan |
| coder | medium | qwen3:14b (Ollama) | Implements changes. Only touches owned files. |
| reviewer | medium | qwen3:14b (Ollama) | Read-only review → verdict |
| tester | medium | qwen3:14b (Ollama) | Writes and runs tests |
| explorer | small | qwen3:4b-thinking (Ollama) | Fast codebase search |
| summarizer | small | qwen3:4b-thinking (Ollama) | L1/L2/L3 compression (hidden) |
| validator | small | qwen3:4b-thinking (Ollama) | Correctness/quality checks (hidden) |

Models are driven by three env vars (`TEAM_MODEL_LARGE`, `TEAM_MODEL_MEDIUM`, `TEAM_MODEL_SMALL`). Change a single variable to reroute an entire tier. See [Model Configuration](#model-configuration).

## Setup

**Prerequisites:** [OpenCode](https://opencode.ai), Node.js 18+

```bash
npm install @moderndegree/opencode-agent-teams
```

Then add the plugin and agent configuration to your project's `opencode.json`. Models are driven by environment variables so you only need to change them in one place:

```json
{
  "plugin": ["@moderndegree/opencode-agent-teams/plugin"],
  "agent": {
    "coordinator": {
      "description": "Team coordinator - decomposes, dispatches, synthesizes. Never writes code.",
      "mode": "primary",
      "model": "${env:TEAM_MODEL_LARGE}"
    },
    "planner": { "mode": "subagent", "model": "${env:TEAM_MODEL_MEDIUM}" },
    "coder": { "mode": "subagent", "model": "${env:TEAM_MODEL_MEDIUM}" },
    "reviewer": { "mode": "subagent", "model": "${env:TEAM_MODEL_MEDIUM}" },
    "tester": { "mode": "subagent", "model": "${env:TEAM_MODEL_MEDIUM}" },
    "explorer": { "mode": "subagent", "model": "${env:TEAM_MODEL_SMALL}" }
  }
}
```

Define your tier models in `.env` (copy from `.env.example`):

```bash
TEAM_MODEL_LARGE=opencode/minimax-m2.5-free
TEAM_MODEL_MEDIUM=ollama/qwen3:14b
TEAM_MODEL_SMALL=ollama/qwen3:4b-thinking
```

The plugin also requires agent system prompt files in your project's `.opencode/agents/` directory. Copy them from the package after installing:

```bash
cp -r node_modules/@moderndegree/opencode-agent-teams/.opencode/agents .opencode/agents
```

## Model Configuration

Models are controlled by three environment variables referenced in `opencode.json`. Set them in `.env` (or your shell) to change all agents in a tier at once:

```bash
# .env
TEAM_MODEL_LARGE=opencode/minimax-m2.5-free   # coordinator
TEAM_MODEL_MEDIUM=ollama/qwen3:14b            # planner, coder, reviewer, tester
TEAM_MODEL_SMALL=ollama/qwen3:4b-thinking     # explorer, summarizer, validator
```

Individual agents can be overridden without touching the tier:

```bash
TEAM_MODEL_CODER=anthropic/claude-sonnet-4-20250514
```

Resolution order (highest → lowest priority):
1. `TEAM_MODEL_<ROLE>` — e.g. `TEAM_MODEL_COORDINATOR`
2. `TEAM_MODEL_<TIER>` — e.g. `TEAM_MODEL_LARGE`
3. Hardcoded defaults in `src/types/agents.ts`

### Alternative providers

**Ollama (local):**
```bash
ollama pull qwen3:14b
ollama pull qwen3:4b-thinking
```
Then set `TEAM_MODEL_MEDIUM=ollama/qwen3:14b` etc. New Ollama models should be declared in the `provider.ollama.models` block in `opencode.json` with context/output limits.

**OpenRouter (cloud):**
```bash
export OPENROUTER_API_KEY=sk-or-...
```
Then set `TEAM_MODEL_MEDIUM=openrouter/qwen/qwen-2.5-coder-32b-instruct`.

**OpenCode Zen (free cloud):**
```bash
TEAM_MODEL_LARGE=opencode/minimax-m2.5-free
```

**Tool calling note:** The coordinator makes continuous structured JSON tool calls (`team_task_create`, `team_message_send`, etc.). Test any new coordinator model thoroughly before relying on it — not all models handle multi-tool workflows reliably.

## Usage

Once installed, the plugin registers 7 `team_*` tools in OpenCode. The coordinator agent handles orchestration automatically when invoked.

| Tool | Description |
|---|---|
| `team_orchestrate` | Primary entry — request → team plan → DAG → execution start |
| `team_export_graph` | Export run graph as JSON, Mermaid, or ASCII |
| `team_explain_graph` | Natural language graph explanation + critical path |
| `team_query_memory` | Unified typed read/write for team memory |
| `team_stream_events` | Returns WebSocket URL + token for event stream |
| `team_open_inspector` | Returns CLI command + WS URL for inspector launch |
| `team_debug_run` | Pause/resume/step/cancel/retry_task controls |

## Development

```bash
npm run lint           # Lint and format check (Biome, read-only)
npm run typecheck      # Type-check only (tsc --noEmit)
npm test               # Run all tests
npm run test:unit      # Unit tests only
npx vitest run tests/unit/graph/task-graph.test.ts  # Single test file
npm run build          # Build to dist/
npm run validate       # Full validation: build + typecheck + lint + test:unit
```

## Architecture

### Key modules

- **Plugin entry** (`.opencode/plugins/opencode-agent-teams.ts`): Registers 7 custom `team_*` tools and event hooks. Integration surface.
- **Task Graph** (`src/graph/task-graph.ts`): DAG engine with Kahn's topological sort, optimistic concurrency, and token budget distribution (80/20 split by complexity weight).
- **KV Store** (`src/store/kv.ts`): In-memory hot tier with LRU eviction, namespace-scoped keys, TTL, SHA-256 dedup, and version history.
- **Message Bus** (`src/protocol/messages.ts`): Per-agent queues with dedup, TTL, and dead letter queue.
- **Compression** (`src/protocol/summarization.ts`): L1/L2/L3 levels (2:1, 5:1, 10:1 ratios) with trigger conditions.
- **Watchdog** (`src/watchdog/`): Token tracking per agent/task, 80%/95%/100% enforcement thresholds, diminishing-returns detection via Jaccard similarity.
- **Validation** (`src/validation/`): 4-stage pipeline (schema → static → test → semantic) with per-failure-type retry policies.
- **Failure taxonomy** (`src/failure/`): Structured failure classification (`FailureType`, `FailureSubtype`, `FailureSeverity`) and deterministic triage — maps failures to recovery strategies (`resume`, `fresh`, `escalate_model`, `decompose`, `abort`, `backoff`, `compress_context`) without LLM calls.
- **Events** (`src/events/`): Typed pub/sub event bus with per-run replay buffer (last 1000 events) and pattern matching (`exact`, `prefix.*`, `*`).
- **Team builder** (`src/team/`): Skill registry with built-in skills (`typescript-impl`, `debugging`, `refactoring`, `vitest-testing`, `code-review`, `documentation`, `research`, `analysis`) and budget-aware ephemeral team formation — groups tasks by skill, distributes token budget proportionally by complexity.
- **WebSocket server** (`src/server/`): Local WebSocket server that streams orchestrator events to external UIs (TUI inspector, dashboards). Supports event subscriptions, graph/memory/run queries, and token auth.
- **Monitoring** (`src/monitoring/`): Prometheus-compatible counters/gauges/histograms, threshold-based alerts.
- **Experiments** (`src/experiments/`): A/B framework with Welch's t-test for significance testing.

### Task state machine

```
pending → assigned → running → validating → completed
                                    ↓
                              failed (retryable) → pending
                              blocked (deps unmet) → pending (on unblock)
```

### Token budget inheritance

Parent reserves 20% for coordination; distributes 80% to children weighted by task type:

| Type | Weight |
|---|---|
| implement | 3 |
| debug | 2.5 |
| refactor | 2 |
| test / research | 1.5 |
| review / document | 1 |
| coordinate | 0.5 |

## WebSocket inspector

The built-in WebSocket server streams live orchestrator events to external UIs and answers graph/memory/run queries.

| Env var | Default | Description |
|---|---|---|
| `TEAM_WS_PORT` | `3847` | Port to bind (127.0.0.1 only) |
| `TEAM_WS_TOKEN` | _(unset — auth disabled)_ | Bearer token for client auth |

Connect with any WebSocket client. Send a `hello` message first, then `subscribe` to event patterns.

## Environment variables

| Env var | Default | Description |
|---|---|---|
| `TEAM_MODEL_LARGE` | `opencode/minimax-m2.5-free` | Model for coordinator (large tier) |
| `TEAM_MODEL_MEDIUM` | `ollama/qwen3:14b` | Model for planner, coder, reviewer, tester |
| `TEAM_MODEL_SMALL` | `ollama/qwen3:4b-thinking` | Model for explorer, summarizer, validator |
| `TEAM_MODEL_<ROLE>` | — | Per-role override; takes priority over tier (e.g. `TEAM_MODEL_CODER`) |
| `TEAM_WS_PORT` | `3847` | WebSocket inspector port |
| `TEAM_WS_TOKEN` | _(unset — auth disabled)_ | WebSocket bearer token |

## Conventions

- All imports use `.js` extensions (ESM)
- Error classes in `src/errors.ts`: `NotFoundError`, `ConflictError`, `CyclicDependencyError`, `InvalidTransitionError`, `TimeoutError`
- Zod schemas define all data contracts — agent outputs are validated against these
- IDs use prefixes: `task_`, `msg_`, `mem_`, `agent_`, `evt_`
- Plugin tools follow `team_*` naming convention