Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

multiagents

npm versionnpm downloads

Multi-agent orchestration platform for Claude Code, Codex CLI, and Gemini CLI. Enables AI agents to discover each other, communicate in real-time, coordinate file edits, and work as a team on shared codebases.

Built on MCP (Model Context Protocol).

What It Does

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Claude Code │ │ Codex CLI │ │ Gemini CLI │
│ (Engineer) │ │ (Reviewer) │ │ (Designer) │
└──────┬───────┘ └──────┬──────┘ └──────┬──────┘
│ MCP (stdio) │ CodexDriver │
└────────────┬───────┴────────────────────┘
│
┌───────▼────────┐
│ Broker Daemon │ SQLite + HTTP on localhost:7899
│ (singleton) │
└───────┬────────┘
│
┌───────▼────────┐
│ Orchestrator │ MCP server for Claude Desktop
│ (team manager) │ Spawns agents, forwards messages,
└────────────────┘ monitors progress, auto-restarts
  • Peer discovery: agents find each other via list_peers
  • Real-time messaging: instant for Claude (channel push), <3s for Codex (mid-turn steer), 1-3s for Gemini (piggyback)
  • Role assignment: assign_role, rename_peer at runtime
  • File coordination: exclusive locks + ownership zones prevent conflicts
  • Task lifecycle: idle → working → done_pending_review → addressing_feedback → approved → released
  • Review loops: signal_done → submit_feedback → fix → re-review → approve
  • Shared knowledge: persistent key-value store for architectural decisions, discovered patterns, and project context — prevents context drift across agents
  • Persistent sessions: survive agent restarts, full message history
  • TUI dashboard: real-time monitoring with 5 tabs (agents, messages, stats, plan, files)
  • Auto-restart: crashed agents respawn with handoff context
  • Graceful shutdown: broker and orchestrator kill all managed processes on exit

Quick Start

# Install globally
bun install -g multiagents
# Setup (detects CLIs, configures MCP servers, starts broker)
multiagents setup
# Restart your Claude Code / Codex / Gemini sessions to load MCP tools# Monitor
multiagents dashboard

From Claude Desktop (Orchestrator)

Ask Claude to create a team:

"Create a team of 3 agents: a Claude engineer, a Codex reviewer, and a Gemini designer. Build a calculator web app in TypeScript."

The orchestrator handles everything: spawning agents, assigning roles, creating slots, launching the dashboard, and forwarding messages between agents.

Agent Support

AgentDelivery MechanismLatencyConfig
Claude CodeChannel push notificationsInstant~/.claude/settings.json
Codex CLICodexDriver (codex app-server)<3s mid-turn, 3-9s between turns~/.codex/config.toml
Gemini CLIPiggyback on MCP tool responses1-3s~/.gemini/settings.json

Codex Integration (CodexDriver)

Codex CLI uses the app-server protocol — a JSON-RPC stdio interface with threads, turns, and rich notifications. The orchestrator uses a CodexDriver that:

  1. Spawns a persistent codex app-server process with JSON-RPC handshake
  2. Creates a thread (thread/start) and drives turns (turn/start) for task execution
  3. Injects messages mid-turn via turn/steer — no waiting for the current turn to finish
  4. Interrupts stuck turns via turn/interrupt when agents go idle for >60s
  5. Auto-approves all server-initiated requests (command execution, file changes, MCP elicitations)
  6. Tracks token usage from turn/completed notifications

The orchestrator drives Codex turns: the forwarding loop polls the broker every 3s. If Codex has an active turn, messages are steered in instantly. If idle, a new turn is started via driver.reply().

Task State Machine

Every agent slot has a task_state that governs the review/approval workflow:

 ┌──────────── (reviewer/QA roles) ────────────┐
│ ▼
idle ──► working ──► done_pending_review ──► addressing_feedback approved ──► released
│ │ ▲
│ └────────────────┘
└──────────► approved ─────────────────────┘
  • idle → working: Auto-transitions when agent calls set_summary or produces first output
  • working → done_pending_review: Agent calls signal_done
  • working → approved: Reviewer/QA agents auto-approve on signal_done (they don't need external review)
  • done_pending_review → addressing_feedback: Reviewer calls submit_feedback(actionable=true)
  • addressing_feedback → done_pending_review: Agent fixes issues and calls signal_done again
  • done_pending_review → approved: Reviewer calls approve
  • approved → released: Orchestrator calls release_agent

Agents cannot disconnect until explicitly released. This ensures the review loop completes.

MCP Tools (Available to All Agents)

ToolDescription
list_peersDiscover agents (filter by scope, type)
send_messageSend text message to a peer
check_messagesPoll for new messages
set_summaryUpdate your status (visible to peers and dashboard)
check_team_statusSee all agents: roles, states, summaries
get_plan / update_planTrack team progress against the plan
signal_doneSignal task completion (triggers review)
submit_feedbackSend review feedback (actionable or informational)
approveApprove a teammate's work
assign_role / rename_peerAssign roles and names
acquire_file / release_fileFile lock management
view_file_locksSee active locks and ownership zones
get_historyQuery session message history
store_knowledgeStore shared knowledge (decisions, patterns, conventions)
query_knowledgeQuery knowledge entries by key or category
remove_knowledgeRemove outdated knowledge entries

Orchestrator Tools (Claude Desktop)

ToolDescription
create_teamSpawn a team with roles, file ownership, and a plan
get_team_statusLive status of all agents with completion tracking
broadcast_to_teamMessage all agents at once
direct_agentMessage a specific agent by name/role
add_agent / remove_agentAdd or remove agents mid-session
control_sessionPause/resume all or individual agents
adjust_guardrailView or change session limits
release_agent / release_allRelease agents to disconnect
get_session_logFull message history
list_sessions / resume_sessionList and resume previous sessions
end_session / delete_sessionArchive or permanently delete
cleanup_dead_slotsRemove stale disconnected slots
get_guideBuilt-in documentation and tutorials

Sessions

Sessions persist across agent restarts:

multiagents session create "Auth Feature"# Create session
multiagents session list # List all sessions
multiagents session resume auth-feature # Resume (respawns agents)
multiagents session pause # Pause all agents
multiagents session delete auth-feature # Permanently delete

File Coordination

Ownership Zones (static, zero overhead):

create_team assigns: Engineer owns src/**, Reviewer owns tests/**

File Locks (dynamic, for shared files):

Engineer: acquire_file("package.json", "adding dependency")
→ Lock acquired, auto-expires in 5 minutes

Shared Knowledge Store

Agents share a persistent key-value store to prevent context drift — the #1 failure mode in multi-agent systems.

Engineer: store_knowledge("auth-pattern", "JWT with refresh rotation", category="decision")
Designer: query_knowledge() → sees the decision before designing auth UI
Reviewer: query_knowledge(category="decision") → reviews against team decisions

Categories: decision, convention, discovery, blocker, context

Knowledge persists across agent restarts and is scoped to the session. Agents are instructed to query knowledge on startup and store decisions as they work.

Guardrails

Session monitoring stats and enforced limits:

GuardrailDefaultScopeAction
Restart Limit5Per agentStop (prevents flapping)
Session DurationMonitorSessionObserve
Total MessagesMonitorSessionObserve
Active AgentsMonitorSessionObserve
Longest IdleMonitorPer agentObserve

Adjustable from the TUI dashboard (+/- keys) or via adjust_guardrail tool.

Web Dashboard

multiagents web [session-id]

Real-time web dashboard on localhost:7900 with live WebSocket updates. Auto-opens in browser when a team is created via the orchestrator. 6-tab interface:

  • Agents: agent cards with connection status, task state, role, summaries, token usage
  • Messages: live message feed with type badges and sender names
  • Plan: task progress with completion bar and assignee labels
  • Knowledge: shared knowledge entries with categories and provenance
  • Files: file locks and ownership zones
  • Stats: session metrics (connected agents, working, tokens) and guardrail bars

Dark theme, responsive layout, keyboard shortcuts (1-6 to switch tabs).

TUI Dashboard

multiagents dashboard [session-id]

5-tab terminal interface (same data, ANSI rendering):

  • [1] Agents: connection status, task state, summaries
  • [2] Messages: auto-scrolling message log with filtering
  • [3] Stats: guardrail monitoring and adjustment
  • [4] Plan: progress tracking with completion percentage
  • [5] Files: file locks and ownership zones

Keys: 1-5 switch tabs, j/k scroll, p pause all, r resume all, +/- adjust guardrails, q quit.

CLI Commands

multiagents setup Interactive setup wizard
multiagents web [session-id] Web dashboard (localhost:7900)
multiagents dashboard [session-id] TUI dashboard
multiagents session <sub> Session management (create/list/resume/pause/delete)
multiagents send <target> <msg> Send message to agent
multiagents peers List connected agents
multiagents status Broker health + peers
multiagents broker start|stop|status Manage broker daemon
multiagents install-mcp Configure MCP servers
multiagents help [command] Detailed help

Architecture

multiagents/
├── broker.ts SQLite broker daemon (sessions, slots, locks, messages, knowledge, guardrails)
├── server.ts MCP server entry point (dispatches to adapter by --agent-type)
├── cli.ts CLI entry point
├── shared/
│ ├── types.ts Type definitions (Peer, Slot, Session, Message, TaskState...)
│ ├── broker-client.ts HTTP client for broker API
│ ├── constants.ts Ports, intervals, thresholds
│ ├── summarize.ts Auto-summary generation
│ └── utils.ts Shared utilities
├── adapters/
│ ├── base-adapter.ts Abstract MCP adapter (tools, registration, polling)
│ ├── claude-adapter.ts Claude Code adapter (channel push delivery)
│ ├── codex-adapter.ts Codex adapter (piggyback + file inbox delivery)
│ ├── gemini-adapter.ts Gemini adapter (piggyback + file inbox delivery)
│ └── role-practices.ts Role-specific best practices injection
├── orchestrator/
│ ├── orchestrator-server.ts Orchestrator MCP server (team management)
│ ├── codex-driver.ts CodexDriver: persistent codex app-server via JSON-RPC (steer/interrupt)
│ ├── launcher.ts Agent spawning (CLI args, MCP configs, CodexDriver)
│ ├── monitor.ts Process monitoring (stdout parsing, token tracking)
│ ├── recovery.ts Crash recovery (flap detection, respawn with context)
│ ├── progress.ts Team status aggregation
│ ├── session-control.ts Pause/resume/broadcast
│ ├── guardrails.ts Guardrail enforcement
│ └── guide.ts Built-in documentation
└── cli/
├── commands.ts CLI command router
├── dashboard.ts TUI dashboard (ANSI, no dependencies)
├── session.ts Session management commands
├── setup.ts Interactive setup wizard
└── install-mcp.ts MCP server configuration

Process Lifecycle

Graceful Shutdown

  • Broker (SIGINT/SIGTERM): kills all registered peer processes, closes SQLite cleanly
  • Orchestrator (SIGINT/SIGTERM): kills all managed agent processes and CodexDriver instances
  • Adapters (SIGINT/SIGTERM): unregister from broker, release file locks

Orphan Prevention

  • Broker's cleanStalePeers runs every 30s: removes dead peer records, kills orphan processes without sessions
  • CodexDriver uses .multiagents/.driver-mode sentinel file to prevent internal MCP adapters from creating ghost slots
  • Session delete/end handlers kill both regular processes and CodexDriver instances
  • Flap detection stops auto-restart after 3 crashes in 5 minutes

Environment Variables

VariableDefaultPurpose
MULTIAGENTS_PORT7899Broker HTTP port
MULTIAGENTS_DB~/.multiagents/peers.dbSQLite database path
MULTIAGENTS_SESSION-Session ID (set by orchestrator)
MULTIAGENTS_SLOT-Slot ID (set by orchestrator)
MULTIAGENTS_ROLE-Agent role (set by orchestrator)
MULTIAGENTS_NAME-Agent display name (set by orchestrator)
MULTIAGENTS_DRIVER_MODE-Skip adapter registration (set by CodexDriver)

Requirements

  • Bun runtime (v1.1+)
  • At least one of: Claude Code, Codex CLI, or Gemini CLI

License

MIT

About

Multi-agent orchestration for Claude Code, Codex CLI & Gemini CLI — spawn AI agent teams that communicate, review code, and coordinate via MCP

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages