InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

10-multi-agent

Shared from "Claude-Code" on Inkdown

Multi-Agent Architecture

Coordinator mode, agent swarms, and sub-agent spawning.


Overview

Claude Code supports multi-agent workflows at three levels:

  1. Sub-Agents — The AI spawns workers to handle tasks in parallel
  2. Coordinator Mode — The AI acts as an orchestrator managing multiple workers
  3. Agent Swarms — Teams of agents working together

Sub-Agents (AgentTool)

How It Works
Plain text
User: "Refactor the auth module and update the tests"
    │
    ▼
AI decides to parallelize
    │
    ├─ AgentTool("Refactor auth module in src/auth/")
    │   └─ Spawns sub-agent 1
    │
    └─ AgentTool("Update tests in tests/auth/")
        └─ Spawns sub-agent 2
    │
    ▼
AI continues with other work
    │
    ▼
Sub-agents work independently
    │
    ▼
Results delivered as <task-notification> blocks
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture
Agent Tool Restrictions

Sub-agents get a restricted tool set:

TypeScript
// Tools NOT available to sub-agents
const AGENT_DISALLOWED_TOOLS = [
  'Agent',           // Can't spawn more agents
  'TeamCreate',      // Can't create teams
  'TeamDelete',      // Can't delete teams
  'SendMessage',     // Can't message other agents
  'SyntheticOutput', // Internal tool
]

// Tools available to sub-agents
// Bash, Read, Edit, Write, Grep, Glob, etc.
Async vs Sync Agents
TypeBehavior
SyncBlocks until complete (default)
AsyncReturns immediately, result delivered later

Coordinator Mode

What Is It?

Coordinator mode transforms the AI into an orchestrator that delegates work across multiple worker agents.

Activation
TypeScript
// Check if coordinator mode is active
function isCoordinatorMode(): boolean {
  return feature('COORDINATOR_MODE') &&
         process.env.CLAUDE_CODE_COORDINATOR_MODE === 'true'
}
Coordinator System Prompt

The coordinator gets a detailed system prompt that teaches it:

  1. Role: Orchestrate, delegate, synthesize, communicate
  2. Available tools:
    • Spawn workers (AgentTool)
    • Send messages to workers (SendMessageTool)
    • Stop workers (TaskStopTool)
    • Subscribe to PR activity (SubscribePRTool)
  3. Phased workflow:
    • Research → Synthesis → Implementation → Verification
  4. How to write effective worker prompts:
    • Self-contained
    • Specific file paths/line numbers
    • Purpose statements
  5. When to continue vs. spawn fresh worker
Worker Capabilities
TypeScript
function getCoordinatorUserContext(mcpClients, scratchpadDir?) {
  return {
    allowedTools: [
      // All tools EXCEPT internal worker tools
      'Bash', 'Read', 'Edit', 'Write', 'Grep', 'Glob',
      'WebSearch', 'WebFetch', 'TodoWrite', 'AskUserQuestion',
      // ... etc
    ],
    mcpServers: mcpClients.map(c => c.serverName),
    scratchpadDir,  // For cross-worker file sharing
  }
}
Session Mode Matching

When resuming a session, the mode is matched:

TypeScript
function matchSessionMode(sessionMode: 'coordinator' | 'normal') {
  if (currentMode !== sessionMode) {
    // Flip environment variable to match
    process.env.CLAUDE_CODE_COORDINATOR_MODE = sessionMode === 'coordinator' ? 'true' : 'false'
    return `Switched to ${sessionMode} mode to match resumed session.`
  }
}
Coordinator in Simple Mode

When REPL mode + coordinator mode are both active:

TypeScript
if (isReplModeEnabled() && isCoordinatorMode()) {
  return [
    REPLTool,           // REPL wrapper
    TaskStopTool,       // Stop workers
    SendMessageTool,    // Message workers
  ]
}

Agent Swarms

What Are Swarms?

Teams of agents that work together on complex tasks. Enabled via:

TypeScript
function isAgentSwarmsEnabled(): boolean {
  return feature('TEAMMEM') && ...
}
Team Management Tools
ToolPurpose
TeamCreateCreate a team of agents
TeamDeleteDelete a team
SendMessageSend messages between agents
Team State in AppState
TypeScript
// In AppState
inbox: Message[]              // Inter-agent messages
teamContext: TeamContext | null
standaloneAgentContext: AgentContext | null
workerSandboxPermissions: Map<string, Permission>
Teammate Mode Snapshot

Captures the current state of teammates:

TypeScript
// Called at startup (if swarms enabled)
captureTeammateModeSnapshot()

// Includes:
// - Active teammates
// - Their capabilities
// - Current tasks
Team Memory Sync

Syncs team state across processes:

TypeScript
// Start watcher
startTeamMemoryWatcher()

// Syncs to shared storage

Task Types

LocalShellTask

Runs in a subprocess with shell access:

TypeScript
// Spawn
const handle = LocalShellTask.spawn({
  taskDescription: "Run the tests",
  tools: [BashTool, ...],
  context: toolUseContext
})

// Handle
handle.id        // Task UUID
handle.status    // 'running' | 'completed' | 'failed'
handle.result    // Output
handle.kill()    // Stop
LocalAgentTask

Runs in-process (lighter weight):

TypeScript
// Spawn
const handle = LocalAgentTask.spawn({
  taskDescription: "Analyze this code",
  tools: [ReadTool, GrepTool, ...],
  context: toolUseContext
})
RemoteAgentTask

Runs on a remote machine:

TypeScript
// Spawn
const handle = RemoteAgentTask.spawn({
  taskDescription: "Deploy to staging",
  remoteHost: "staging.example.com",
  tools: [BashTool, ...],
  context: toolUseContext
})
DreamTask

Background processing (auto-dream feature):

TypeScript
// Spawn
const handle = DreamTask.spawn({
  taskDescription: "Review the PR",
  context: toolUseContext
})
// Runs in background, results delivered later
LocalWorkflowTask

Workflow script execution (feature-gated):

TypeScript
// Only available with WORKFLOW_SCRIPTS feature
const handle = LocalWorkflowTask.spawn({
  workflowPath: ".claude/workflows/deploy.js",
  context: toolUseContext
})
MonitorMcpTask

MCP monitoring (feature-gated):

TypeScript
// Only available with MONITOR_TOOL feature
const handle = MonitorMcpTask.spawn({
  mcpServer: "my-server",
  context: toolUseContext
})

Task Management in UI

Task List

Tasks are displayed in the expanded view:

Plain text
┌──────────────────────────────────────┐
│  Tasks                               │
│                                      │
│  ● Refactor auth    running  45s     │
│  ● Update tests     running  30s     │
│  ✓ Deploy to staging completed       │
│                                      │
│  [View All]                          │
└──────────────────────────────────────┘
Task Tools
ToolDescription
/tasksView task list
TaskOutputToolStream task output
TaskStopToolStop a task
TaskCreateToolCreate a task
TaskGetToolGet task details
TaskUpdateToolUpdate task
TaskListToolList tasks

Inter-Agent Communication

SendMessageTool

Agents can message each other:

TypeScript
// Send a message
SendMessageTool.execute({
  recipient: "agent-uuid",
  message: "I've finished the refactor"
})

// Received as <task-notification>
<task-notification id="agent-uuid">
I've finished the refactor. Here's what I changed:
...
</task-notification>
Inbox

Messages are stored in the AppState inbox:

TypeScript
// In AppState
inbox: Message[]

// Processed by the query loop

Permission Isolation

Each agent has its own permission context:

TypeScript
// Worker sandbox permissions
workerSandboxPermissions: Map<string, Permission>

// Each worker's permissions are isolated

Agent Color Management

Each agent gets a unique color in the UI:

TypeScript
// In AppState
agentColorMap: Map<string, AgentColorName>
agentColorIndex: number

// Assignment
assignAgentColor(agentId) → color

Key Files Reference

FilePurpose
src/coordinator/coordinatorMode.tsCoordinator mode logic and system prompt
src/tools/AgentTool/Sub-agent spawning tool
src/tools/TeamCreateTool/Team creation
src/tools/TeamDeleteTool/Team deletion
src/tools/SendMessageTool/Inter-agent messaging
src/tools/TaskCreateTool/Task creation
src/tools/TaskStopTool/Task termination
src/tools/TaskOutputTool/Task output streaming
src/tasks/LocalShellTask/Local shell task
src/tasks/LocalAgentTask/Local agent task
src/tasks/RemoteAgentTask/Remote agent task
src/tasks/DreamTask/Dream task
src/tasks/LocalWorkflowTask/Workflow task
src/tasks/MonitorMcpTask/MCP monitor task
src/utils/swarm/Swarm utilities
src/utils/agentSwarmsEnabled.tsSwarm feature gate
src/services/teamMemorySync/Team memory sync