> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch39-multi-agent-architecture/39.1-multi-agent-design.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 39.1 Multi-Agent Design

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~290k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The capabilities of modern AI assistants are expanding rapidly—from simple Q\&A to coding, browser automation, schedule management, and multimodal understanding. A single Agent struggles to perform optimally across all domains. OpenClaw's solution is **Multi-Agent Architecture**: allowing users to define multiple Agents on the same Gateway instance, each with independent identity, workspace, model configuration, and skill set.

> **Sidebar: Agent and Agency** In AI, an "Agent" refers to a software entity with autonomous decision-making capability. It can perceive its environment (receive messages, read files), make plans, invoke tools to execute actions, and adjust behavior based on feedback. Unlike traditional "chatbots," Agents emphasize **autonomy** and **tool-using capability**. In this chapter, "agent" and "Agent" are used interchangeably.

## 39.1.1 Agent Scope Resolution

The core question in a multi-agent system is: how to parse all Agents from configuration, determine the default Agent, and route sessions to the correct Agent. `agent-scope.ts` is the core implementation of this mechanism.

### Agent List Parsing

```typescript
// src/agents/agent-scope.ts (simplified)

function listAgents(cfg: OpenClawConfig): AgentEntry[] {
  const list = cfg.agents?.list;
  if (!Array.isArray(list)) return [];
  return list.filter(
    (entry): entry is AgentEntry =>
      Boolean(entry && typeof entry === "object")
  );
}

export function listAgentIds(cfg: OpenClawConfig): string[] {
  const agents = listAgents(cfg);
  if (agents.length === 0) return [DEFAULT_AGENT_ID];
  const seen = new Set<string>();
  const ids: string[] = [];
  for (const entry of agents) {
    const id = normalizeAgentId(entry?.id);
    if (seen.has(id)) continue;
    seen.add(id);
    ids.push(id);
  }
  return ids.length > 0 ? ids : [DEFAULT_AGENT_ID];
}
```

Key design decisions:

| Decision            | Implementation                    | Rationale                                                                   |
| ------------------- | --------------------------------- | --------------------------------------------------------------------------- |
| Empty list fallback | Return `[DEFAULT_AGENT_ID]`       | Zero-config operation; single-Agent scenarios need no configuration         |
| ID deduplication    | `Set` filters duplicates          | Prevent configuration errors from registering the same Agent multiple times |
| ID normalization    | `normalizeAgentId()` unifies case | `"Coder"` and `"coder"` are treated as the same Agent                       |

`DEFAULT_AGENT_ID` comes from `src/routing/session-key.ts` and is the system's built-in default identifier. When users configure no Agents, all sessions route to this default Agent.

### Default Agent Election

When multiple Agents are configured, the system must determine which is the "default" Agent—the one used when no Agent is explicitly specified:

```typescript
export function resolveDefaultAgentId(cfg: OpenClawConfig): string {
  const agents = listAgents(cfg);
  if (agents.length === 0) return DEFAULT_AGENT_ID;

  const defaults = agents.filter((agent) => agent?.default);
  if (defaults.length > 1 && !defaultAgentWarned) {
    defaultAgentWarned = true;
    console.warn(
      "Multiple agents marked default=true; using the first."
    );
  }
  const chosen = (defaults[0] ?? agents[0])?.id?.trim();
  return normalizeAgentId(chosen || DEFAULT_AGENT_ID);
}
```

The election logic follows a **priority chain**:

1. Agent marked with `default: true` (if multiple, take the first and warn)
2. First Agent in the configuration list
3. System built-in `DEFAULT_AGENT_ID`

`defaultAgentWarned` is a module-level boolean ensuring the warning outputs only once, avoiding log pollution.

### Session-Agent Binding

Each session binds to a specific Agent via **Session Key**. The Session Key format encodes Agent information:

```typescript
export function resolveSessionAgentIds(params: {
  sessionKey?: string;
  config?: OpenClawConfig;
}): { defaultAgentId: string; sessionAgentId: string } {
  const defaultAgentId = resolveDefaultAgentId(params.config ?? {});
  const normalizedSessionKey = params.sessionKey?.trim().toLowerCase();
  const parsed = normalizedSessionKey
    ? parseAgentSessionKey(normalizedSessionKey)
    : null;
  const sessionAgentId = parsed?.agentId
    ? normalizeAgentId(parsed.agentId)
    : defaultAgentId;
  return { defaultAgentId, sessionAgentId };
}
```

`parseAgentSessionKey()` extracts the Agent ID from the session key. For example, the key `agent:coder:subagent:abc123` parses out `agentId = "coder"`. If the session key doesn't contain an Agent prefix (like a plain `"main"` session), it falls back to the default Agent.

### ResolvedAgentConfig Type

Each Agent's complete configuration is resolved via `resolveAgentConfig()`. The return type `ResolvedAgentConfig` encompasses all configurable dimensions of an Agent:

```typescript
type ResolvedAgentConfig = {
  name?: string;           // Display name
  workspace?: string;      // Working directory path
  agentDir?: string;       // Agent state directory
  model?: AgentEntry["model"];     // Model configuration (string or {primary, fallbacks})
  skills?: AgentEntry["skills"];   // Skill filter list
  memorySearch?: ...;      // Memory search configuration
  humanDelay?: ...;        // Simulated human typing delay
  heartbeat?: ...;         // Heartbeat interval
  identity?: ...;          // Identity/personality definition
  groupChat?: ...;         // Group chat configuration
  subagents?: ...;         // Sub-agent strategy
  sandbox?: ...;           // Sandbox isolation configuration
  tools?: ...;             // Tool allowlist/denylist
};
```

Each field undergoes strict type guards, ensuring invalid configurations don't propagate downstream:

```typescript
model:
  typeof entry.model === "string" ||
  (entry.model && typeof entry.model === "object")
    ? entry.model
    : undefined,
```

This "take if valid, undefined if invalid" pattern permeates the entire configuration parsing layer.

### Model Resolution: Primary and Fallback Chain

Agent model configuration supports two formats:

```jsonc
// Simple format: specify model directly
{ "model": "claude-opus-4-6" }

// Advanced format: primary model + fallback chain
{
  "model": {
    "primary": "claude-opus-4-6",
    "fallbacks": ["claude-sonnet-4-20250514", "gpt-4o"]
  }
}
```

Corresponding parsing functions:

```typescript
// Primary model
export function resolveAgentModelPrimary(
  cfg: OpenClawConfig,
  agentId: string,
): string | undefined {
  const raw = resolveAgentConfig(cfg, agentId)?.model;
  if (typeof raw === "string") return raw.trim() || undefined;
  return raw?.primary?.trim() || undefined;
}

// Fallback chain (note: empty array [] is valid override, disabling global fallback)
export function resolveAgentModelFallbacksOverride(
  cfg: OpenClawConfig,
  agentId: string,
): string[] | undefined {
  const raw = resolveAgentConfig(cfg, agentId)?.model;
  if (!raw || typeof raw === "string") return undefined;
  if (!Object.hasOwn(raw, "fallbacks")) return undefined;
  return Array.isArray(raw.fallbacks) ? raw.fallbacks : undefined;
}
```

A subtle aspect of `resolveAgentModelFallbacksOverride` is its use of `Object.hasOwn` to distinguish between "fallbacks not set" and "fallbacks explicitly set to empty array". The latter means the user **intentionally disables** the global fallback model chain—an important semantic distinction.

## 39.1.2 Agent Path System

Each Agent needs two independent directories: **workspace** and **Agent state directory** (agent dir).

### Workspace Isolation

```typescript
// src/agents/agent-scope.ts
export function resolveAgentWorkspaceDir(
  cfg: OpenClawConfig,
  agentId: string,
) {
  const id = normalizeAgentId(agentId);
  // 1. Workspace configured in Agent itself
  const configured = resolveAgentConfig(cfg, id)?.workspace?.trim();
  if (configured) return resolveUserPath(configured);

  // 2. Default Agent uses global defaults.workspace or built-in path
  const defaultAgentId = resolveDefaultAgentId(cfg);
  if (id === defaultAgentId) {
    const fallback = cfg.agents?.defaults?.workspace?.trim();
    if (fallback) return resolveUserPath(fallback);
    return DEFAULT_AGENT_WORKSPACE_DIR;
  }

  // 3. Non-default Agent uses ~/.openclaw/workspace-{id}
  return path.join(os.homedir(), ".openclaw", `workspace-${id}`);
}
```

Path resolution follows a **three-level fallback** strategy:

```
Agent's own configuration
    ↓ (not set)
Default Agent? → global defaults.workspace → DEFAULT_AGENT_WORKSPACE_DIR
Non-default Agent? → ~/.openclaw/workspace-{id}
```

Non-default Agents' workspaces are automatically isolated by ID suffix. For example, the `coder` Agent's workspace is `~/.openclaw/workspace-coder`, and the `researcher` Agent's workspace is `~/.openclaw/workspace-researcher`. This ensures different Agents' file operations don't interfere.

### Agent State Directory

The Agent state directory stores Agent's persistent state data (such as memory files, SOUL configuration, etc.):

```typescript
// src/agents/agent-scope.ts
export function resolveAgentDir(
  cfg: OpenClawConfig,
  agentId: string,
) {
  const id = normalizeAgentId(agentId);
  const configured = resolveAgentConfig(cfg, id)?.agentDir?.trim();
  if (configured) return resolveUserPath(configured);
  const root = resolveStateDir(process.env, os.homedir);
  return path.join(root, "agents", id, "agent");
}
```

The default path is `~/.openclaw/agents/{id}/agent`. `resolveStateDir()` checks environment variables (like `OPENCLAW_STATE_DIR`) to determine the state root directory.

`agent-paths.ts` provides a simpler entry point specifically for resolving the current process's Agent directory:

```typescript
// src/agents/agent-paths.ts
export function resolveOpenClawAgentDir(): string {
  const override =
    process.env.OPENCLAW_AGENT_DIR?.trim() ||
    process.env.PI_CODING_AGENT_DIR?.trim();
  if (override) return resolveUserPath(override);
  return resolveUserPath(
    path.join(resolveStateDir(), "agents", DEFAULT_AGENT_ID, "agent")
  );
}

export function ensureOpenClawAgentEnv(): string {
  const dir = resolveOpenClawAgentDir();
  if (!process.env.OPENCLAW_AGENT_DIR) {
    process.env.OPENCLAW_AGENT_DIR = dir;
  }
  if (!process.env.PI_CODING_AGENT_DIR) {
    process.env.PI_CODING_AGENT_DIR = dir;
  }
  return dir;
}
```

`ensureOpenClawAgentEnv()` performs bidirectional writes (`OPENCLAW_AGENT_DIR` and `PI_CODING_AGENT_DIR`) for backward compatibility with older environment variable naming.

## 39.1.3 Agent Default Configuration

`defaults.ts` defines global default values for Agents:

```typescript
// src/agents/defaults.ts
export const DEFAULT_PROVIDER = "anthropic";
export const DEFAULT_MODEL = "claude-opus-4-6";
export const DEFAULT_CONTEXT_TOKENS = 200_000;
```

These constants serve as the **ultimate fallback** for all Agent configurations—used when users haven't specified a model provider, model name, or context window size.

| Constant                 | Value               | Meaning                           |
| ------------------------ | ------------------- | --------------------------------- |
| `DEFAULT_PROVIDER`       | `"anthropic"`       | Default LLM provider is Anthropic |
| `DEFAULT_MODEL`          | `"claude-opus-4-6"` | Default model is Claude Opus 4.6  |
| `DEFAULT_CONTEXT_TOKENS` | `200_000`           | Context window of 200K tokens     |

These defaults reflect OpenClaw's core positioning: Claude models from Anthropic as the primary force, while supporting other providers (OpenAI, Google Gemini, etc.) through configuration. `DEFAULT_CONTEXT_TOKENS = 200_000` is a conservative estimate—when model metadata is unavailable (e.g., self-hosted open-source models), the system uses this value to manage the context window.

## 39.1.4 Multi-Agent Configuration in Practice

A typical multi-agent configuration example:

```jsonc
// ~/.openclaw/openclaw.json
{
  "agents": {
    "list": [
      {
        "id": "main",
        "name": "Main Assistant",
        "default": true,
        "model": "claude-opus-4-6",
        "skills": ["coding-agent", "github", "weather"],
        "subagents": {
          "allowAgents": ["researcher", "coder"]
        }
      },
      {
        "id": "researcher",
        "name": "Researcher",
        "model": {
          "primary": "claude-sonnet-4-20250514",
          "fallbacks": []
        },
        "skills": ["web-search"],
        "workspace": "~/research-workspace"
      },
      {
        "id": "coder",
        "name": "Coding Assistant",
        "model": "claude-opus-4-6",
        "skills": ["coding-agent", "github"],
        "sandbox": {
          "mode": "auto",
          "scope": "session"
        }
      }
    ],
    "defaults": {
      "workspace": "~/openclaw-workspace"
    }
  }
}
```

In this configuration:

* **main** is the default Agent with permission to spawn sub-agents (can derive `researcher` and `coder`)
* **researcher** uses the more economical Sonnet model, explicitly disables fallback chain (`fallbacks: []`), and has its own workspace
* **coder** enables sandbox isolation (`sandbox.mode: "auto"`), creating independent containers per session

The directory layout for the three Agents is as follows:

```
~/.openclaw/
├── agents/
│   ├── main/agent/          ← main's state directory
│   ├── researcher/agent/    ← researcher's state directory
│   └── coder/agent/         ← coder's state directory
├── workspace/               ← main (default Agent) workspace
├── workspace-coder/         ← coder's workspace
└── ...

~/research-workspace/        ← researcher's custom workspace
```

***

## Section Summary

1. **Agent list parsing**: `listAgentIds()` extracts deduplicated Agent ID list from `agents.list` configuration, falling back to system default Agent when empty.
2. **Default Agent election**: Prioritizes Agent marked `default: true`, otherwise takes first in list, ultimately falls back to `DEFAULT_AGENT_ID`.
3. **Session routing**: Extracts target Agent ID from Session Key via `parseAgentSessionKey()`, implementing precise session-to-Agent binding.
4. **Agent configuration parsing**: `ResolvedAgentConfig` spans 11 dimensions (model, skills, workspace, sandbox, etc.), each field with strict type guards.
5. **Model fallback chain**: Supports both simple string and `{primary, fallbacks}` formats, with empty array `[]` for explicitly disabling global fallback.
6. **Path isolation**: Each Agent has independent workspace and state directory; default Agent uses global paths, non-default Agents isolated by ID suffix.
7. **Default constants**: `DEFAULT_PROVIDER="anthropic"`, `DEFAULT_MODEL="claude-opus-4-6"`, `DEFAULT_CONTEXT_TOKENS=200_000` as ultimate fallback configuration.
