> 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/ch22-tool-system-overview/22.5-source-deep-dive-tool-assembly-and-sandbox.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 22.5 Source Deep Dive: The Tool Assembly Pipeline and the Sandbox

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~250,000 tokens, Output \~13,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§22.1–22.4 covered the tool system's structure, execution runtime, and permission model. This section reads two blocks of source: **how tools get assembled**, and **what the sandbox actually does**.

## 22.5.1 The Assembly Line: `createOpenClawCodingTools()`

`src/agents/pi-tools.ts:198`. It takes over 40 context parameters and returns the final tool array.

Five stages.

### Stage 1: Replace pi's base tools (`pi-tools.ts:364-406`)

Starting from pi's `codingTools`, three get touched:

| Tool             | Treatment                                                                                                      |
| ---------------- | -------------------------------------------------------------------------------------------------------------- |
| `read`           | Replaced with an OpenClaw version carrying **image sanitization** and a **context-window-aware output budget** |
| `bash`           | **Removed outright**, replaced by OpenClaw's own `exec` / `process`                                            |
| `write` / `edit` | Swapped for fs-bridge versions under sandbox; wrapped in a workspace-root guard otherwise                      |

`read`'s "context-window-aware output budget" is worth noting: the output cap for reading a file is **computed dynamically from the current model's window** rather than being a fixed constant. A small-window model reading a large file gets truncated harder — more sensible than a uniform limit.

### Stage 2: Add OpenClaw's own tool families

```
exec / process
apply_patch (OpenAI-family models only, and must be explicitly enabled, pi-tools.ts:350-357)
browser / canvas / message
sessions_* / cron / gateway
image / web_search / web_fetch
+ channel-specific action tools (Discord/Telegram/Slack/WhatsApp actions)
```

`apply_patch`'s conditions are deliberately narrow — OpenAI-family only, explicitly enabled. Models differ widely in how faithfully they follow patch formats, and handing it to a model that's bad at it just manufactures a stream of failed edits.

### Stage 3: Seven layers of policy filtering (`pi-tools.ts:568-588`)

This is the heart of the permission model. `applyToolPolicyPipeline` applies, in order:

```
1. profile policy
2. provider profile
3. global policy
4. agent policy
5. group policy
6. sandbox tool policy
7. subagent tool policy
```

**Seven allow/deny layers stacked — any one can remove a tool.**

Why seven? Because the same `browser` tool has completely different availability in these three situations:

| Situation            | `browser` tool                                                                    |
| -------------------- | --------------------------------------------------------------------------------- |
| Owner's main session | Available                                                                         |
| Group chat session   | Usually disabled (someone else's message shouldn't be able to drive your browser) |
| Sandboxed subagent   | Host browser disabled; only the in-container one                                  |

Beyond the seven layers there are scattered hard rules:

* **voice channels ban `tts`** (speech to speech to speech is a loop);
* **xAI bans the built-in `web_search`** (it collides with their native tool of the same name);
* **non-owner senders lose owner-only tools** — the comment stresses: **"unknown/undefined is always treated as unauthorized; opt-in, not opt-out."**

That last one is textbook secure-default construction. When sender identity can't be determined, the default is **no** permission, not yes.

### Stage 4: Schema normalization

`normalizeToolParameters` reconciles providers' disagreements about JSON Schema:

| Provider  | Requirement                                  |
| --------- | -------------------------------------------- |
| OpenAI    | Rejects top-level unions                     |
| Gemini    | Certain constraint keywords must be stripped |
| Anthropic | Those same keywords must be retained         |

One tool definition, three required shapes. That's the price of "one runtime serving every provider."

### Stage 5: Hooks and abort wrapping

Each tool gets one more wrapper:

* The `before_tool_call` plugin hook (including **loop detection** — preventing the model from calling the same tool repeatedly);
* An AbortSignal (so `/stop` can interrupt a running tool).

### The finish: one crucial decision

```
splitSdkTools() → every tool, adapted through toToolDefinitions, goes into pi's customTools
                  builtInTools is permanently an empty array
```

**pi's built-in tools are bypassed entirely.**

Why? Because pi's built-in tools don't pass through the seven policy layers above. Leaving them in place would open a back door around the permission system — and their behavior also varies across providers.

Routing everything through `customTools` **guarantees policy filtering applies uniformly for every provider.** (`docs/pi.md` calls this the Tool Split Strategy.)

## 22.5.2 `exec`: The Most Permission-Heavy Tool

`src/agents/bash-tools.exec.ts:151`. Three **orthogonal** dimensions.

### Dimension one: host (where it runs)

| Value     | Meaning                                |
| --------- | -------------------------------------- |
| `sandbox` | Inside a container                     |
| `gateway` | On the gateway host                    |
| `node`    | On a remote device node (Appendix F.5) |

**Want to change host from the request side? Rejected unless elevated** (`exec.ts:311-315`).

### Dimensions two and three: security and ask

| Dimension  | Values                        | Merge rule                                                 |
| ---------- | ----------------------------- | ---------------------------------------------------------- |
| `security` | `deny` / `allowlist` / `full` | Take the **minimum** of config and request (`minSecurity`) |
| `ask`      | Approval policy               | Take the **maximum** of config and request (`maxAsk`)      |

**The two directions are deliberately opposite.** The net effect: a requester can only tighten permissions, never loosen them.

Defaults: sandbox `deny`, host `allowlist`.

**`elevated` is the only exception path**: it must clear both `tools.elevated.enabled` and `allowFrom.<provider>`, only then reaches full level bypassing approval, and **forces host=gateway**.

### Approval is a two-phase protocol

```ts
// src/agents/bash-tools.exec-approval-request.ts:88-93
export async function registerExecApprovalRequest(...) {
  // Two-phase registration is critical: the ID must be registered server-side
  // before exec returns `approval-pending`, otherwise `/approve` can race and orphan.
  const registrationResult = await callGatewayTool(
    "exec.approval.request", ...
```

The flow:

```
① Register the approval ID (the gateway broadcasts it to the owner)
       ↓
   The human replies /approve <id> in chat
       ↓
② exec.approval.waitDecision awaits the decision
```

**Why must it be two phases?** The comment says it: the ID must be registered server-side **before** exec returns `approval-pending`, or a fast user typing `/approve` hits an ID that doesn't exist yet — the approval is orphaned.

If the registration response already contains a decision (an auto-allow rule matched), the wait phase is skipped.

During approval the exec tool returns a pending result, and after the decision `bash-tools.exec-approval-followup.ts` **delivers the execution result afterwards**.

> **The core tension**: an LLM's tool call is **synchronous** (it calls and waits for a result), while human approval is **asynchronous** (they may check their phone ten minutes later). The two-phase protocol plus deferred delivery decouples them.

### Two more clever bits

**Backgrounding.** If a command hasn't finished within the `yieldMs` window, it returns "still running" and hands management to the `process` tool (list / poll / log / write / kill).

The process registry is isolated by sessionKey (the scopeKey at `pi-tools.ts:317-320`) — **preventing one session from seeing or killing another's processes**.

**Preflight static checks** (`exec.ts:80-149`). Before running `python x.py`, it scans the target file for patterns like `$SHELL_VAR`.

That check intercepts a real incident: **the model wrote shell syntax into a Python script and then burned a day of tokens on it in cron**. The script failed every run, cron didn't know, and the model retried every time.

> Checks that look strange usually correspond to a real billing incident.

## 22.5.3 The `tools/` Directory: A "Channel as Tool" Family

`src/agents/tools/` (\~15,000 lines) divides into five families. Understanding the split clarifies OpenClaw's "message gateway + agent" product shape:

| Family          | Main files                                                                                                                      | Notes                                                                                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Messaging**   | `message-tool.ts` (792 lines) + per-channel action tools                                                                        | Unified cross-channel send entry point supporting sendMessage / threadReply / react; channel capabilities (polls? pinning?) are declared by `channel-tools.ts` in the system prompt |
| **Sessions**    | `sessions-spawn-tool.ts` / `sessions-send-tool.ts` / `sessions-list-tool.ts` / `sessions-history-tool.ts` / `subagents-tool.ts` | Spawn subagents, cross-session messaging (with an A2A variant), listing and termination; visibility constrained by `sessions-access.ts`                                             |
| **Peripherals** | `browser-tool.ts` (659 lines) / `canvas-tool.ts` / `image-tool.ts` / `pdf-tool.ts` / `tts-tool.ts`                              | browser splits schema and actions; goes through the bridge under sandbox                                                                                                            |
| **Web**         | `web-search.ts` / `web-fetch.ts`                                                                                                | With `web-guarded-fetch.ts` for SSRF protection and `web-fetch-visibility.ts` for visibility filtering                                                                              |
| **System**      | `cron-tool.ts` / `gateway-tool.ts` / `nodes-tool.ts` / `memory-tool.ts` / `session-status-tool.ts`                              | `gateway-tool` is the bridge letting the agent call internal Gateway RPCs — **exec approval goes through it**                                                                       |

This inventory explains two things simultaneously:

1. **Why tool schemas are the top context-budget expense** (the system prompt bill in §15.5.4) — many tools, each carrying a full JSON Schema;
2. **Why the policy pipeline needs seven layers** — availability varies enormously by scenario.

## 22.5.4 The Sandbox: More Than `docker exec`

`src/agents/sandbox/`, in four parts.

### Layered images

| Dockerfile                   | Contents                                                        |
| ---------------------------- | --------------------------------------------------------------- |
| `Dockerfile.sandbox`         | debian bookworm-slim + bash / git / python3 / ripgrep (minimal) |
| `Dockerfile.sandbox-common`  | Adds node / go / rust / bun / brew                              |
| `Dockerfile.sandbox-browser` | Adds a browser                                                  |

The container runs `sleep infinity` as a **non-root `sandbox` user** — it persists rather than starting fresh per execution.

### Hardening parameters (`sandbox/docker.ts:348-423`)

```ts
// src/agents/sandbox/docker.ts:360-402 (excerpt)
args.push("--read-only");
// ...
args.push("--network", params.cfg.network);
// ...
args.push("--cap-drop", cap);
args.push("--security-opt", "no-new-privileges");
if (params.cfg.seccompProfile) {
  args.push("--security-opt", `seccomp=${params.cfg.seccompProfile}`);
}
// ...
args.push("--pids-limit", String(params.cfg.pidsLimit));
args.push("--memory", memory);
```

Item by item:

| Parameter                                | Defends against                          |
| ---------------------------------------- | ---------------------------------------- |
| `--read-only` + tmpfs                    | Writing to the container root filesystem |
| `--network` (can be disabled by default) | Data exfiltration                        |
| `--cap-drop`                             | Linux capability escalation              |
| `--security-opt no-new-privileges`       | setuid escalation                        |
| seccomp / apparmor profile (optional)    | The syscall surface                      |
| `--pids-limit` / `--memory` / `--cpus`   | Fork bombs and resource exhaustion       |

**Container reuse**: containers carry `openclaw.sessionKey` / `openclaw.configHash` labels; a config change triggers a rebuild, and the registry (`registry.ts`) reuses hot containers within `HOT_CONTAINER_WINDOW_MS = 5min`.

Using a configHash as a label is a good pattern — **config changed means rebuild, config unchanged means reuse**, with no manual container lifecycle management.

### Scope

`agents.defaults.sandbox.mode` has three settings:

| Value      | Meaning                                                  |
| ---------- | -------------------------------------------------------- |
| `off`      | Everything runs on the host (**default**)                |
| `non-main` | Main session on the host, everything else in a container |
| `all`      | Everything in a container                                |

The typical shape is `non-main`: **the main session works on the host (your own instructions), while subagents and group sessions go into containers** (paths potentially influenced by others).

`workspaceAccess` controls workspace visibility: `rw` mounts the real workspace directly, `ro` / `none` use a copy.

> Note the default is `off`. That matches §44.4's trust model — SECURITY.md states plainly that host-first exec is expected behavior under the one-user trusted-operator model, and the sandbox is optional hardening for non-main sessions, not a boundary promise.

### fs-bridge: file access under sandbox

Under sandbox, `read` / `write` / `edit` **don't touch the host filesystem directly** — they execute inside the container through `fs-bridge.ts`.

* Mutations are implemented with **injected Python source** (`fs-bridge-mutation-python-source.ts`) — because python3 is guaranteed present in the container, requiring no extra tooling;
* Path safety is enforced by `fs-bridge-path-safety.ts` and `assertSandboxPath`.

**browser bridge**: the in-container browser tool is forwarded over a bridgeUrl, and `novnc-auth.ts` provides an authenticated visual debugging entry point (you can watch the container's Chrome live in your browser).

### Two supporting defenses

* `sandbox-tool-policy.ts` additionally filters tools in sandbox sessions (removing host browser control, for instance) — layer six of §22.5.1's seven;
* `validate-sandbox-security.ts` validates configuration combinations **before the container is created** (dangerous pairings of mounts and network mode, say).

The second one's value: **it keeps "misconfigured but running anyway" silent degradation outside the door.** A sandbox configured but rendered ineffective by a parameter combination is more dangerous than no sandbox at all — because you believe you're protected.

***

## Section Summary

1. **Five assembly stages**: replace pi's base tools (**`bash` removed outright**, `read` replaced with a window-aware version) → add OpenClaw's families → **seven layers of policy filtering** → three-way schema normalization → hook and abort wrapping.
2. The finishing decision: **every tool goes through `customTools`, `builtInTools` stays permanently empty** — bypassing pi's built-ins entirely so policy filtering applies uniformly across providers.
3. **`exec` has three orthogonal dimensions**: host (changing it requires elevation), security (**take the minimum**), ask (**take the maximum**) — the two directions are deliberately opposite, so requesters can only tighten. Textbook secure default: **"unknown/undefined is always treated as unauthorized; opt-in, not opt-out."**
4. **The two-phase approval protocol decouples "synchronous LLM call" from "asynchronous human approval"**; the ID must be registered before returning pending, or `/approve` hits a nonexistent ID.
5. **`exec`'s preflight static check** (scanning Python scripts for `$SHELL_VAR`) intercepts the real incident of "model writes a broken script, cron retries it for a day."
6. **The sandbox is full hardening, not `docker exec`**: read-only root + no network + cap-drop + no-new-privileges + resource caps + configHash-labeled auto-rebuild; file access goes through fs-bridge with independent path-safety enforcement.
7. **The default is `mode: off`** — consistent with the trust model, the sandbox is optional hardening rather than a boundary promise; `validate-sandbox-security.ts` blocks dangerous configuration combinations before container creation, **preventing "believing you're protected when you aren't."**
