> 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/ch23-bash-tools-and-process-management/23.1-bash-execution-engine.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 23.1 Bash Execution Engine

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

***

In the previous chapter, we comprehensively explored OpenClaw's tool system—how tools are registered, executed, and controlled. Starting from this chapter, we will dive into the implementation details of specific tools. The Bash execution engine is the **most complex and security-critical tool** in OpenClaw: it grants AI Agents the ability to execute arbitrary commands on the operating system, but simultaneously introduces enormous security risks. This section will progressively analyze the command execution core, PTY terminal emulation, PATH management, and security approval mechanisms.

***

## 23.1.1 Overall Architecture of the exec Tool

### Source File Distribution

The Bash tool implementation is distributed across multiple files:

| File                         | Responsibility                                                                   |
| ---------------------------- | -------------------------------------------------------------------------------- |
| `bash-tools.ts`              | Barrel file, re-exports exec and process tools                                   |
| `bash-tools.exec.ts`         | **exec tool core**—command execution engine (\~1630 lines)                       |
| `bash-tools.process.ts`      | process tool—background process management                                       |
| `bash-tools.shared.ts`       | Shared tool functions (environment variables, working directory, log truncation) |
| `bash-process-registry.ts`   | Process registry—manages all exec sessions in memory                             |
| `shell-utils.ts`             | Shell configuration detection, binary output sanitization, process tree killing  |
| `pty-dsr.ts`                 | PTY DSR (Device Status Report) request handling                                  |
| `pty-keys.ts`                | PTY key encoding (send-keys, paste operations)                                   |
| `exec-approvals.ts` (infra/) | Command approval system—allowlists, security policy evaluation                   |

### Three Execution Host Modes

The exec tool supports three execution hosts (Host), corresponding to different security levels:

```
┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│   sandbox    │  │   gateway    │  │     node     │
│  (Docker)    │  │  (host)      │  │  (remote)    │
├──────────────┤  ├──────────────┤  ├──────────────┤
│ Isolated     │  │ Direct       │  │ Via Gateway  │
│ container    │  │ execution on │  │ RPC forward  │
│ execution    │  │ server       │  │ to companion │
│ Highest      │  │ Requires     │  │ app execution│
│ security     │  │ approval or  │  │              │
│ Default mode │  │ allowlist    │  │              │
└──────────────┘  └──────────────┘  └──────────────┘
```

> **Sidebar**: In containerization technology, Docker is the most popular container engine. In "sandbox" mode, OpenClaw executes commands within a Docker container, where the container is isolated from the host's filesystem and network. Even if the AI executes malicious commands, the host system remains unaffected. This is the classic **Sandbox** security model.

### Tool Schema Definition

The exec tool defines parameter Schema through TypeBox, which LLMs can understand and populate:

```typescript
// src/agents/bash-tools.exec.ts — execSchema
const execSchema = Type.Object({
  command:   Type.String({ description: "Shell command to execute" }),
  workdir:   Type.Optional(Type.String()),    // working directory
  env:       Type.Optional(Type.Record(...)),  // environment variables
  yieldMs:   Type.Optional(Type.Number()),     // yield to background after N ms
  background:Type.Optional(Type.Boolean()),    // immediately background
  timeout:   Type.Optional(Type.Number()),     // timeout in seconds
  pty:       Type.Optional(Type.Boolean()),    // PTY mode
  elevated:  Type.Optional(Type.Boolean()),    // elevated execution
  host:      Type.Optional(Type.String()),     // sandbox|gateway|node
  security:  Type.Optional(Type.String()),     // deny|allowlist|full
  ask:       Type.Optional(Type.String()),     // off|on-miss|always
  node:      Type.Optional(Type.String()),     // node ID
});
```

Note the `yieldMs` and `background` parameters: this is a distinctive OpenClaw design. Command execution can first wait synchronously for a period of time (default 10 seconds), and if the command hasn't completed, it automatically transitions to background—more flexible than simple "synchronous blocking until completion" or "immediate backgrounding".

***

## 23.1.2 Command Execution Core Flow

### `createExecTool()` Factory Function

The exec tool is created by the factory function `createExecTool(defaults?)`. The factory receives default configuration parameters (`ExecToolDefaults`) and returns an `AgentTool` instance. Core configuration items include:

```typescript
// src/agents/bash-tools.exec.ts — ExecToolDefaults (simplified)
type ExecToolDefaults = {
  host?: ExecHost;              // default execution host
  security?: ExecSecurity;      // security policy
  ask?: ExecAsk;                // approval mode
  sandbox?: BashSandboxConfig;  // Docker sandbox config
  pathPrepend?: string[];       // PATH prefix
  safeBins?: string[];          // safe binary allowlist
  backgroundMs?: number;        // background yield time
  timeoutSec?: number;          // default timeout (seconds)
  elevated?: ExecElevatedDefaults; // elevation config
  sessionKey?: string;          // session identifier
  // ...
};
```

### execute Handler Chain

When an LLM calls the exec tool, the execute function sequentially performs the following steps:

```
┌─ 1. Parameter Validation & Normalization ─┐
│  Parse command, workdir, env, etc.        │
│  Handle background/yieldMs options        │
└──────────┬───────────┘
           ▼
┌─ 2. Host Mode Selection ────┐
│  sandbox → Docker container │
│  gateway → host direct      │
│  node    → RPC remote node  │
└──────────┬───────────┘
           ▼
┌─ 3. Security Check ────────┐
│  elevated (elevation) check │
│  env var security validation│
│  allowlist + safeBins eval  │
│  user approval needed?      │
└──────────┬───────────┘
           ▼
┌─ 4. Environment Building ──┐
│  sandbox: buildSandboxEnv()│
│  gateway: merge host env   │
│  PATH prefix injection     │
└──────────┬───────────┘
           ▼
┌─ 5. Process Creation ──────┐
│  runExecProcess() selects: │
│  ├─ sandbox → docker exec  │
│  ├─ PTY    → node-pty spawn│
│  └─ normal → child_process │
└──────────┬───────────┘
           ▼
┌─ 6. Output Collection ─────┐
│  stdout/stderr real-time   │
│  auto SIGKILL on timeout   │
│  auto background on yieldMs│
└──────────────────────┘
```

***

## 23.1.3 Three Process Creation Strategies

`runExecProcess()` selects different process creation strategies based on configuration:

### Strategy One: Docker Sandbox Execution

```typescript
// src/agents/bash-tools.exec.ts — runExecProcess sandbox branch (simplified)
if (opts.sandbox) {
  const { child } = await spawnWithFallback({
    argv: [
      "docker",
      ...buildDockerExecArgs({
        containerName: opts.sandbox.containerName,
        command: opts.command,
        workdir: opts.containerWorkdir ?? opts.sandbox.containerWorkdir,
        env: opts.env,
        tty: opts.usePty,
      }),
    ],
    options: {
      cwd: opts.workdir,
      detached: process.platform !== "win32",
      stdio: ["pipe", "pipe", "pipe"],
    },
    fallbacks: [{ label: "no-detach", options: { detached: false } }],
  });
  child = spawned;
}
```

Key points:

* `buildDockerExecArgs()` constructs `docker exec -i [-t] -w <dir> -e KEY=VAL ... <container> sh -lc '<command>'` command
* Uses `-l` (login shell) to ensure `.profile` and other initialization scripts are loaded, obtaining the complete PATH
* `spawnWithFallback()` provides a fallback mechanism—if `detached` mode spawn fails (certain Node.js versions/platform limitations), automatically falls back to non-detached mode

> **Sidebar**: `detached: true` is an option for Node.js `child_process.spawn()`, meaning the child process runs independently from the parent. On Unix systems, this creates a new process group (Process Group), so the child process won't be killed when the parent exits. OpenClaw needs this feature to support long-running background commands.

### Strategy Two: PTY Terminal Emulation Execution

```typescript
// src/agents/bash-tools.exec.ts — runExecProcess PTY branch (simplified)
} else if (opts.usePty) {
  const { shell, args: shellArgs } = getShellConfig();
  try {
    const ptyModule = await import("@lydell/node-pty");
    const spawnPty = ptyModule.spawn ?? ptyModule.default?.spawn;
    
    pty = spawnPty(shell, [...shellArgs, opts.command], {
      cwd: opts.workdir,
      env: opts.env,
      name: process.env.TERM ?? "xterm-256color",
      cols: 120,
      rows: 30,
    });
    
    // Construct stdin adapter—PTY uses pty.write() not child.stdin
    stdin = {
      write: (data, cb) => { pty?.write(data); cb?.(null); },
      end: () => {
        const eof = process.platform === "win32" ? "\x1a" : "\x04";
        pty?.write(eof);
      },
    };
  } catch (err) {
    // PTY creation failed → fallback to normal child_process spawn
    warnings.push(`PTY spawn failed; retrying without PTY.`);
    // Fall back to strategy three...
  }
}
```

> **Sidebar**: PTY (Pseudo Terminal) is a mechanism provided by the operating system kernel that emulates a terminal device. Many command-line programs (such as `vim`, `htop`, `less`) detect whether they're running in a terminal—if not (e.g., stdout is a pipe), they change behavior (disable colors, don't show TUI, or even refuse to run). Through PTY, OpenClaw can make these programs believe they're running in a real terminal.

PTY mode has several special characteristics:

1. **Terminal size**: Set to 120 columns × 30 rows, a typical terminal size
2. **TERM environment variable**: Defaults to `xterm-256color`, supporting 256-color output
3. **stdin adaptation**: PTY doesn't use Node.js's `child.stdin`, but writes via `pty.write()`
4. **EOF signal**: Unix uses `\x04` (Ctrl-D), Windows uses `\x1a` (Ctrl-Z)
5. **Auto fallback**: If the `node-pty` module is unavailable (not installed or platform unsupported), automatically falls back to normal spawn

### Strategy Three: Normal Child Process Execution

```typescript
// src/agents/bash-tools.exec.ts — normal spawn branch
} else {
  const { shell, args: shellArgs } = getShellConfig();
  const { child } = await spawnWithFallback({
    argv: [shell, ...shellArgs, opts.command],
    options: {
      cwd: opts.workdir,
      env: opts.env,
      detached: process.platform !== "win32",
      stdio: ["pipe", "pipe", "pipe"],
    },
    fallbacks: [{ label: "no-detach", options: { detached: false } }],
  });
}
```

The simplest mode: obtain the system Shell (via `getShellConfig()`), then execute the command with the `-c` parameter.

***

## 23.1.4 PTY Data Stream Processing

In PTY mode, data stream processing differs significantly from normal child\_process.

### DSR Request Filtering

```typescript
// src/agents/bash-tools.exec.ts — PTY data processing (simplified)
if (pty) {
  const cursorResponse = buildCursorPositionResponse();
  pty.onData((data) => {
    const raw = data.toString();
    const { cleaned, requests } = stripDsrRequests(raw);
    if (requests > 0) {
      for (let i = 0; i < requests; i++) {
        pty.write(cursorResponse);  // reply to each DSR query
      }
    }
    handleStdout(cleaned);  // cleaned data enters output buffer
  });
}
```

> **Sidebar**: DSR (Device Status Report) is part of the terminal control sequence standard (ANSI/VT100). When a program sends `ESC[6n` to the terminal, it expects the terminal to reply with the current cursor position (format `ESC[row;colR`). Programs like `vim` and `zsh` send DSR at startup to get the cursor position. OpenClaw's PTY layer needs to "pretend" to be a terminal to reply to these queries, otherwise the program will hang waiting for a response.

The DSR handling implementation is very concise, just 16 lines:

```typescript
// src/agents/pty-dsr.ts — complete implementation
const ESC = String.fromCharCode(0x1b);
const DSR_PATTERN = new RegExp(`${ESC}\\[\\??6n`, "g");

export function stripDsrRequests(input: string) {
  let requests = 0;
  const cleaned = input.replace(DSR_PATTERN, () => {
    requests += 1;
    return "";
  });
  return { cleaned, requests };
}

export function buildCursorPositionResponse(row = 1, col = 1): string {
  return `\x1b[${row};${col}R`;
}
```

### Output Format Comparison

| Feature                  | Normal Mode               | PTY Mode                 |
| ------------------------ | ------------------------- | ------------------------ |
| stdout/stderr separation | ✓ Independent streams     | ✗ Mixed together         |
| ANSI color codes         | Usually none              | Included                 |
| DSR queries              | None                      | Need filtering and reply |
| TUI program support      | Not supported             | Supported                |
| Data events              | `child.stdout.on('data')` | `pty.onData()`           |

***

## 23.1.5 Environment Variable Security Mechanism

### Host Mode Environment Variable Blacklist

When the execution host is `gateway` (host machine) or `node` (remote node), OpenClaw strictly checks the environment variables requested by the Agent:

```typescript
// src/agents/bash-tools.exec.ts — dangerous environment variable blacklist
const DANGEROUS_HOST_ENV_VARS = new Set([
  "LD_PRELOAD",             // shared library injection
  "LD_LIBRARY_PATH",        // custom library search path
  "LD_AUDIT",               // audit shared library
  "DYLD_INSERT_LIBRARIES",  // macOS library injection
  "DYLD_LIBRARY_PATH",      // macOS library search path
  "NODE_OPTIONS",           // Node.js startup option injection
  "NODE_PATH",              // Node.js module search path
  "PYTHONPATH",             // Python module search path
  "PYTHONHOME",             // Python installation path
  "RUBYLIB",                // Ruby library path
  "PERL5LIB",               // Perl library path
  "BASH_ENV",               // script auto-executed at bash startup
  "ENV",                    // script executed at sh startup
  "GCONV_PATH",             // glibc character conversion path
  "IFS",                    // Shell internal field separator
  "SSLKEYLOGFILE",          // TLS key leakage
]);

const DANGEROUS_HOST_ENV_PREFIXES = ["DYLD_", "LD_"];
```

> **Sidebar**: `LD_PRELOAD` attack is a classic code injection technique on Linux systems. The `LD_PRELOAD` environment variable specifies a shared library (.so file) that will be loaded before all other libraries. Attackers can use a custom library to override standard library functions (like `read()`, `write()`), thereby intercepting or tampering with program behavior. Similarly, macOS's `DYLD_INSERT_LIBRARIES` has the same danger.

The validation function rejects any attempt to set these variables:

```typescript
function validateHostEnv(env: Record<string, string>): void {
  for (const key of Object.keys(env)) {
    const upperKey = key.toUpperCase();
    // prefix matching (e.g., LD_xxx, DYLD_xxx)
    if (DANGEROUS_HOST_ENV_PREFIXES.some(p => upperKey.startsWith(p))) {
      throw new Error(`Security Violation: '${key}' is forbidden.`);
    }
    // exact matching
    if (DANGEROUS_HOST_ENV_VARS.has(upperKey)) {
      throw new Error(`Security Violation: '${key}' is forbidden.`);
    }
    // PATH also not allowed to customize
    if (upperKey === "PATH") {
      throw new Error(`Security Violation: Custom 'PATH' is forbidden.`);
    }
  }
}
```

Note: sandbox (Docker) mode skips this check—because environment variables inside the container won't affect the host.

### PATH Management Strategy

PATH handling differs across modes:

```
sandbox mode:
  buildSandboxEnv() → use sandbox config's DEFAULT_PATH
  
gateway mode:
  1. Get base PATH from host process process.env
  2. If user didn't specify PATH → call getShellPathFromLoginShell()
     get complete PATH from login shell (includes nvm, rbenv, etc.)
  3. Use applyPathPrepend() to inject configured prefix paths

node mode:
  Remote node manages PATH itself
```

### Safe Bins (Safe Binary Allowlist)

```typescript
// src/infra/exec-approvals.ts — default safe binary list
export const DEFAULT_SAFE_BINS = [
  "jq", "grep", "cut", "sort", "uniq", "head", "tail", "tr", "wc"
];
```

In `allowlist` security mode, if the command is one of these "safe" tools (and doesn't include file path parameters), it can be executed directly without approval. The `isSafeBinUsage()` function performs fine-grained checks:

* The executable name must be in the `safeBins` set
* The executable must resolve to a concrete path (prevent PATH injection)
* Parameters must not include file paths (prevent reading/writing sensitive files)

***

## 23.1.6 Command Approval System

### Approval File Structure

Command approval configuration is stored in `~/.openclaw/exec-approvals.json`:

```json
{
  "version": 1,
  "socket": {
    "path": "~/.openclaw/exec-approvals.sock",
    "token": "base64url-random-token"
  },
  "defaults": {
    "security": "allowlist",
    "ask": "on-miss"
  },
  "agents": {
    "pi": {
      "security": "allowlist",
      "ask": "on-miss",
      "allowlist": [
        { "id": "uuid", "pattern": "/usr/bin/git", "lastUsedAt": 1700000000 },
        { "id": "uuid", "pattern": "/usr/local/bin/npm" }
      ]
    }
  }
}
```

### Three-Layer Security Policy

| Policy    | security    | ask       | Behavior                                         |
| --------- | ----------- | --------- | ------------------------------------------------ |
| Strictest | `deny`      | —         | Reject all execution                             |
| Allowlist | `allowlist` | `on-miss` | Execute if matches allowlist, otherwise ask user |
| Open      | `full`      | `off`     | Direct execution (sandbox only)                  |

The `minSecurity()` function ensures security level can only **decrease** (take minimum):

```typescript
// src/infra/exec-approvals.ts
export function minSecurity(a: ExecSecurity, b: ExecSecurity): ExecSecurity {
  const order = { deny: 0, allowlist: 1, full: 2 };
  return order[a] <= order[b] ? a : b;
}
```

### Shell Command Analysis Engine

When evaluating the allowlist, OpenClaw needs to **parse Shell commands** to extract executable file paths. This is a mini Shell parser:

```typescript
// src/infra/exec-approvals.ts — command analysis flow (simplified)
export function evaluateShellAllowlist(params) {
  // 1. Split chained commands (&&, ||, ;)
  const chainParts = splitCommandChain(params.command);
  
  // 2. For each chain part, split pipelines (|)
  for (const part of chainParts) {
    const pipelineSplit = splitShellPipeline(part);
    
    // 3. For each pipeline segment, tokenize and parse executable
    for (const segment of pipelineSplit.segments) {
      const argv = tokenizeShellSegment(segment);
      const resolution = resolveCommandResolution(argv);
      // resolution.resolvedPath → e.g., "/usr/bin/git"
    }
  }
  
  // 4. Each segment must match allowlist or safeBins
  return { allowlistSatisfied, allowlistMatches };
}
```

The command parser supports:

* Chaining operators: `&&`, `||`, `;`
* Pipelines: `|`
* Single and double quotes
* Escape character `\`
* Forbidden dangerous tokens: `>`, `<`, `` ` ``, `$()`, `\n`

### Approval Flow

When a command is not on the allowlist and `ask` is not `off`, user approval is triggered:

```
Agent initiates exec → command not on allowlist
    │
    ▼
Create approval request → send to user via Gateway
    │
    ▼
Wait for user decision (max 120 seconds)
    │
    ├─ "allow-once"  → execute this time
    ├─ "allow-always" → execute this time + add to allowlist
    └─ "deny"        → reject execution
    
If timeout:
    └─ decide based on askFallback
       ├─ "full"      → allow execution
       ├─ "allowlist"  → allow only if allowlist matches
       └─ "deny"      → reject
```

Approval requests are passed through Unix Domain Socket, ensuring only local processes can participate in approval.

***

## 23.1.7 Backgrounding and Output Collection

### yieldMs Mechanism

One of the most clever designs of the exec tool is `yieldMs`—during command execution, first wait synchronously for a period of time, and if the command hasn't completed, automatically transition to background:

```typescript
// src/agents/bash-tools.exec.ts — yield mechanism (simplified)
if (allowBackground && yieldWindow !== null) {
  if (yieldWindow === 0) {
    // background: true → immediate backgrounding
    markBackgrounded(run.session);
    return { status: "running", sessionId: run.session.id };
  } else {
    // transition to background after yieldMs expires
    yieldTimer = setTimeout(() => {
      markBackgrounded(run.session);
      resolve({ status: "running", sessionId: ... });
    }, yieldWindow);
  }
}

// if command completes within yieldMs
run.promise.then((outcome) => {
  if (yielded) return;  // already backgrounded, don't process
  clearTimeout(yieldTimer);
  resolve({ status: outcome.status, aggregated: outcome.aggregated });
});
```

Benefits of this design:

* Fast commands (like `ls`, `cat`) return results directly, no extra poll calls needed
* Long-running commands (like `npm install`, `make`) don't block the Agent's conversation loop
* Agent can continue processing other tasks while waiting, then check results with the `process` tool

### Timeout Handling

```typescript
if (opts.timeoutSec > 0) {
  timeoutTimer = setTimeout(() => {
    timedOut = true;
    killSession(session);        // first SIGKILL the process
    timeoutFinalizeTimer = setTimeout(() => {
      finalizeTimeout();         // force settlement after 1 second
    }, 1000);
  }, opts.timeoutSec * 1000);
}
```

Timeout handling is two-step:

1. Immediately kill the process (via `killProcessTree()` to kill the entire process tree)
2. Wait 1 second for kernel cleanup, then mark the session as `failed` and collect available output

***

## Summary of This Section

1. **exec tool is OpenClaw's most complex tool**, \~1630 lines of code, involving process management, security approval, PTY terminals, and multiple subsystems
2. **Three execution hosts**: sandbox (Docker isolation), gateway (host direct execution), node (remote node RPC)
3. **Three process creation strategies**: Docker exec, PTY spawn (node-pty), normal child\_process spawn, each with fallback strategies
4. **PTY mode needs to handle DSR requests**—pretend to be a terminal replying to cursor position queries, otherwise TUI programs hang
5. **Multi-layer security protection**: environment variable blacklist, PATH modification prohibition, allowlist + safe bins, user approval flow
6. **Shell command parser** supports chaining, pipelines, quotes, can precisely extract executable paths for each pipeline segment
7. **yieldMs design** lets fast commands return directly, long-running commands auto-background, balancing responsiveness and non-blocking
