> 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.3-multi-agent-sandbox-tools.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 39.3 Multi-Agent Sandbox Tools

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

***

In a multi-agent architecture, different Agents' capabilities and permissions should be differentiated. An Agent responsible for code execution needs file read/write and shell tools, but shouldn't have permission to control browsers or send messages to channels. OpenClaw implements fine-grained tool-level isolation through **Sandbox Tool Policy**.

> **Sidebar: Principle of Least Privilege** The Principle of Least Privilege is one of the fundamental principles of computer security. It requires each module to possess only the minimum set of permissions necessary to complete its task. In the AI Agent context, this means sub-agents shouldn't gain tool access beyond what their task requires—an Agent that only needs to read files shouldn't have shell command execution capability.

## 39.3.1 Cross-Agent Tool Isolation

### Default Tool Policy

`sandbox/constants.ts` defines the allowlist and denylist of tools in the sandbox environment:

```typescript
// src/agents/sandbox/constants.ts

export const DEFAULT_TOOL_ALLOW = [
  "exec",              // Shell command execution
  "process",           // Process management
  "read",              // File reading
  "write",             // File writing
  "edit",              // File editing
  "apply_patch",       // Patch application
  "image",             // Image processing
  "sessions_list",     // List sessions
  "sessions_history",  // View session history
  "sessions_send",     // Send message to session
  "sessions_spawn",    // Spawn sub-agent
  "session_status",    // View session status
] as const;

export const DEFAULT_TOOL_DENY = [
  "browser",           // Browser automation
  "canvas",            // Canvas/A2UI
  "nodes",             // Device node control
  "cron",              // Scheduled tasks
  "gateway",           // Gateway management
  ...CHANNEL_IDS,      // All message channels (telegram, discord, slack...)
] as const;
```

The allowlist design embodies the security philosophy of "**execution capability open, communication capability closed**":

| Category           | Tools                           | Policy | Rationale                                                      |
| ------------------ | ------------------------------- | ------ | -------------------------------------------------------------- |
| Code execution     | exec, process                   | Allow  | Sandbox provides process-level isolation                       |
| File operations    | read, write, edit, apply\_patch | Allow  | Sandbox restricts filesystem scope                             |
| Multimodal         | image                           | Allow  | Image processing is common requirement                         |
| Session management | sessions\_\*                    | Allow  | Sub-agents need to collaborate with other agents               |
| Browser            | browser                         | Deny   | Browser has independent sandbox solution                       |
| UI rendering       | canvas                          | Deny   | Sub-agents shouldn't directly manipulate UI                    |
| Device control     | nodes                           | Deny   | Device operations require explicit authorization               |
| Scheduling         | cron                            | Deny   | Sub-agents are temporary, shouldn't create persistent tasks    |
| Message channels   | telegram, discord...            | Deny   | Prevent sub-agents from sending messages without authorization |

Note that `CHANNEL_IDS` is dynamically expanded from the channel registry, meaning every registered message channel is automatically added to the denylist—even future channels don't need manual updates.

### Tool Policy Resolution

`tool-policy.ts` implements three-level priority policy resolution:

```typescript
// src/agents/sandbox/tool-policy.ts

export function resolveSandboxToolPolicyForAgent(
  cfg?: OpenClawConfig,
  agentId?: string,
): SandboxToolPolicyResolved {
  const agentConfig = cfg && agentId
    ? resolveAgentConfig(cfg, agentId)
    : undefined;

  // Agent-level > global > default constants
  const agentAllow = agentConfig?.tools?.sandbox?.tools?.allow;
  const agentDeny  = agentConfig?.tools?.sandbox?.tools?.deny;
  const globalAllow = cfg?.tools?.sandbox?.tools?.allow;
  const globalDeny  = cfg?.tools?.sandbox?.tools?.deny;

  const deny = Array.isArray(agentDeny) ? agentDeny
    : Array.isArray(globalDeny) ? globalDeny
    : [...DEFAULT_TOOL_DENY];

  const allow = Array.isArray(agentAllow) ? agentAllow
    : Array.isArray(globalAllow) ? globalAllow
    : [...DEFAULT_TOOL_ALLOW];

  // Expand tool group aliases
  const expandedDeny = expandToolGroups(deny);
  let expandedAllow = expandToolGroups(allow);

  // Special handling for image tool: always allow unless explicitly denied
  if (
    !expandedDeny.includes("image") &&
    !expandedAllow.includes("image")
  ) {
    expandedAllow = [...expandedAllow, "image"];
  }

  return { allow: expandedAllow, deny: expandedDeny, sources: { ... } };
}
```

The priority chain for policy resolution:

```
Agent-level policy (agents.list[].tools.sandbox.tools)
    ↓ (not set)
Global policy (tools.sandbox.tools)
    ↓ (not set)
Default constants (DEFAULT_TOOL_ALLOW / DEFAULT_TOOL_DENY)
```

The returned `SandboxToolPolicyResolved` includes a `sources` field recording each policy's origin (`"agent"` / `"global"` / `"default"`), facilitating debugging and auditing.

The `image` tool receives special treatment: unless explicitly forbidden in the denylist, it's automatically added even if not listed in the allowlist. This is because multimodal interaction (like screenshot analysis, image generation) has become a foundational AI Agent capability.

### Tool Name Matching

Tool name matching supports exact matching and wildcard patterns:

```typescript
type CompiledPattern =
  | { kind: "all" }          // "*" — match all
  | { kind: "exact"; value: string }  // Exact match
  | { kind: "regex"; value: RegExp }; // Wildcard to regex

function compilePattern(pattern: string): CompiledPattern {
  const normalized = pattern.trim().toLowerCase();
  if (normalized === "*") return { kind: "all" };
  if (!normalized.includes("*")) {
    return { kind: "exact", value: normalized };
  }
  // "sessions_*" → /^sessions_.*$/
  const escaped = normalized
    .replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return {
    kind: "regex",
    value: new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`),
  };
}

export function isToolAllowed(
  policy: SandboxToolPolicy,
  name: string,
) {
  const normalized = name.trim().toLowerCase();
  // Denylist priority: hit deny then reject
  if (matchesAny(normalized, compilePatterns(policy.deny))) {
    return false;
  }
  // Empty allowlist allows all
  const allow = compilePatterns(policy.allow);
  if (allow.length === 0) return true;
  // Must hit allowlist
  return matchesAny(normalized, allow);
}
```

The matching algorithm follows **denylist priority** principle:

1. If tool name hits denylist → reject (regardless of allowlist)
2. Empty allowlist → allow all tools not rejected by denylist
3. Non-empty allowlist → must hit allowlist to allow

Wildcard `*` is converted to `.*` in regex. For example, `"sessions_*"` matches `sessions_list`, `sessions_spawn`, and all tools starting with `sessions_`.

## 39.3.2 Sandbox Agent Configuration

### Sandbox Mode and Scope

Each Agent's sandbox configuration is resolved via `resolveSandboxConfigForAgent()`:

```typescript
// src/agents/sandbox/config.ts

export function resolveSandboxConfigForAgent(
  cfg?: OpenClawConfig,
  agentId?: string,
): SandboxConfig {
  const globalSandbox = cfg?.agents?.defaults?.sandbox;
  const agentSandbox = agentConfig?.sandbox;

  return {
    mode: agentSandbox?.mode ?? globalSandbox?.mode ?? "off",
    scope: resolveSandboxScope({ ... }),
    workspaceAccess: ... ?? "none",
    workspaceRoot: ... ?? DEFAULT_SANDBOX_WORKSPACE_ROOT,
    docker: resolveSandboxDockerConfig({ ... }),
    browser: resolveSandboxBrowserConfig({ ... }),
    tools: { allow: ..., deny: ... },
    prune: resolveSandboxPruneConfig({ ... }),
  };
}
```

Key dimensions of sandbox configuration:

| Dimension         | Possible Values                         | Description                     |
| ----------------- | --------------------------------------- | ------------------------------- |
| `mode`            | `"off"` / `"auto"` / `"always"`         | Sandbox enablement mode         |
| `scope`           | `"agent"` / `"session"` / `"shared"`    | Container sharing granularity   |
| `workspaceAccess` | `"none"` / `"readonly"` / `"readwrite"` | Host workspace mount permission |

`scope` determines the Docker container's lifecycle:

* **`"agent"`**: Each Agent shares one container. Container is created on Agent's first use and reclaimed after idle.
* **`"session"`**: Each session creates independent container. Highest isolation, but highest resource consumption.
* **`"shared"`**: All Agents share one global container. Lowest resource consumption, but no isolation.

### Docker Container Configuration

`resolveSandboxDockerConfig()` resolves Docker container security parameters:

```typescript
export function resolveSandboxDockerConfig(params: {
  scope: SandboxScope;
  globalDocker?: Partial<SandboxDockerConfig>;
  agentDocker?: Partial<SandboxDockerConfig>;
}): SandboxDockerConfig {
  return {
    image: ... ?? DEFAULT_SANDBOX_IMAGE,
    // "openclaw-sandbox:bookworm-slim"
    containerPrefix: ... ?? DEFAULT_SANDBOX_CONTAINER_PREFIX,
    workdir: ... ?? DEFAULT_SANDBOX_WORKDIR,  // "/workspace"
    readOnlyRoot: ... ?? true,     // Read-only root filesystem
    tmpfs: ... ?? ["/tmp", "/var/tmp", "/run"],  // Writable temp directories
    network: ... ?? "none",        // Default no network
    capDrop: ... ?? ["ALL"],       // Drop all Linux capabilities
    env,                           // Environment variables (default LANG=C.UTF-8)
    // ... resource limits: pidsLimit, memory, cpus, etc.
  };
}
```

The default security configuration is extremely strict:

| Parameter      | Default                | Security Meaning                                                                   |
| -------------- | ---------------------- | ---------------------------------------------------------------------------------- |
| `readOnlyRoot` | `true`                 | Container root filesystem read-only, preventing malicious system file modification |
| `network`      | `"none"`               | No network access, preventing data leakage                                         |
| `capDrop`      | `["ALL"]`              | Drop all Linux kernel capabilities, running with minimal privilege                 |
| `tmpfs`        | `/tmp, /var/tmp, /run` | Only temp directories writable, auto-cleared on restart                            |

> **Sidebar: Linux Capabilities** Linux Capabilities split traditional root superuser privilege into multiple fine-grained permissions. For example, `CAP_NET_ADMIN` allows network configuration, `CAP_SYS_PTRACE` allows process debugging. `capDrop: ["ALL"]` means dropping all these capabilities—even if a container process runs as root, it has almost no privileged operation capability.

### Browser Sandbox

For Agents needing browser capability, OpenClaw provides an independent browser sandbox:

```typescript
export function resolveSandboxBrowserConfig(params) {
  return {
    enabled: ... ?? false,              // Default off
    image: ... ?? DEFAULT_SANDBOX_BROWSER_IMAGE,
    // "openclaw-sandbox-browser:bookworm-slim"
    cdpPort: ... ?? 9222,               // Chrome DevTools Protocol port
    vncPort: ... ?? 5900,               // VNC remote desktop port
    noVncPort: ... ?? 6080,             // noVNC web port
    headless: ... ?? false,             // Non-headless mode (observable via VNC)
    enableNoVnc: ... ?? true,           // Enable web VNC access
    allowHostControl: ... ?? false,     // Forbid host browser control
    autoStart: ... ?? true,             // Auto-start on tool call
    autoStartTimeoutMs: ... ?? 12_000,  // Auto-start timeout 12 seconds
  };
}
```

The browser sandbox uses a dedicated Docker image (`openclaw-sandbox-browser:bookworm-slim`), with built-in Chromium browser and VNC server. Agents control the container's browser remotely via CDP (Chrome DevTools Protocol), while administrators can observe Agent browser operations in real-time via noVNC's web interface.

### Container Lifecycle Management

Sandbox container cleanup is configured via `resolveSandboxPruneConfig()`:

```typescript
export function resolveSandboxPruneConfig(params) {
  return {
    idleHours: ... ?? DEFAULT_SANDBOX_IDLE_HOURS,    // 24 hours
    maxAgeDays: ... ?? DEFAULT_SANDBOX_MAX_AGE_DAYS,  // 7 days
  };
}
```

| Parameter    | Default | Meaning                                           |
| ------------ | ------- | ------------------------------------------------- |
| `idleHours`  | 24      | Container auto-stops after 24 hours idle          |
| `maxAgeDays` | 7       | Container forcibly removed after 7 days existence |

These two parameters together ensure sandbox containers don't indefinitely consume system resources.

### Sandbox State Directory

Sandbox runtime state is persisted in `~/.openclaw/sandbox/` directory:

```typescript
export const SANDBOX_STATE_DIR =
  path.join(resolvedSandboxStateDir, "sandbox");
export const SANDBOX_REGISTRY_PATH =
  path.join(SANDBOX_STATE_DIR, "containers.json");
export const SANDBOX_BROWSER_REGISTRY_PATH =
  path.join(SANDBOX_STATE_DIR, "browsers.json");
```

`containers.json` records all active sandbox container information (container ID, creation time, associated Agent, etc.), `browsers.json` records browser sandbox correspondences.

### Complete Configuration Example

The following shows a complete multi-agent sandbox configuration example:

```jsonc
{
  "agents": {
    "list": [
      {
        "id": "main",
        "default": true,
        // Main Agent doesn't use sandbox
      },
      {
        "id": "coder",
        "sandbox": {
          "mode": "auto",
          "scope": "session",
          "workspaceAccess": "readwrite",
          "docker": {
            "network": "bridge",  // Needs network (e.g., npm install)
            "memory": "2g",
            "cpus": 2
          }
        },
        "tools": {
          "sandbox": {
            "tools": {
              "allow": ["exec", "read", "write", "edit", "process"],
              "deny": ["sessions_spawn"]  // Forbid sub-agent nesting
            }
          }
        }
      },
      {
        "id": "browser-agent",
        "sandbox": {
          "mode": "always",
          "scope": "agent",
          "docker": {
            "network": "bridge"  // Browser needs network
          },
          "browser": {
            "enabled": true,
            "headless": true
          }
        },
        "tools": {
          "sandbox": {
            "tools": {
              "allow": ["browser", "read", "image"],
              "deny": ["exec", "process", "write"]  // Read-only + browser only
            }
          }
        }
      }
    ]
  }
}
```

In this configuration:

* **main** Agent runs directly on host with full permissions
* **coder** Agent runs in Docker sandbox, one container per session, with network access and 2GB memory limit, but cannot spawn sub-agents
* **browser-agent** runs in browser sandbox, can only use browser and file reading tools, cannot execute commands or write files

This configuration implements **defense in depth**—even if an AI Agent is tricked by malicious instructions, the damage it can cause is strictly limited within its sandbox boundary.

***

## Section Summary

1. **Default tool policy** follows "execution capability open, communication capability closed" principle: allow file and process operations, deny browser, channels, scheduled tasks, etc.
2. **Three-level priority** policy resolution: Agent-level > global > default constants, each level records source for auditing.
3. **Denylist priority** matching algorithm: deny takes precedence over allow, supports `*` wildcard matching.
4. **image tool special protection**: automatically added to allowlist unless explicitly denied, safeguarding multimodal foundational capability.
5. **Sandbox container security defaults** extremely strict: read-only root filesystem, no network, drop all Linux capabilities.
6. **Three container scopes**: `agent` (Agent-shared), `session` (session-isolated), `shared` (globally-shared), balancing isolation and resource consumption.
7. **Browser sandbox** uses dedicated image, controlled via CDP + observed via VNC, achieving secure browser operation isolation.
8. **Container lifecycle management**: 24-hour idle stop + 7-day forced removal, preventing resource leakage.

***

> ### 🔬 Going Deeper: 39.4 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**39.4 Source Deep Dive: Subagent Spawning and Cross-Agent Communication**](https://www.openclawbook.xyz/en/ch39-multi-agent-architecture/39.4-source-deep-dive-subagent-spawn-and-communication.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
