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

# 23.3 Shell Tools and Shared Infrastructure

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

***

In the previous two sections, we analyzed the exec tool's command execution engine and the process tool's process management mechanism respectively. This section will focus on the **shared infrastructure** supporting their operation: Shell detection and configuration, Docker sandbox environment building, working directory resolution, binary output sanitization, and process tree management. These seemingly simple utility functions hide substantial cross-platform compatibility considerations.

***

## 23.3.1 Shell Detection and Configuration

### Platform-Aware Shell Selection

`getShellConfig()` is the entry point for the entire Bash tool chain—it determines which Shell executes commands:

```typescript
// src/agents/shell-utils.ts — getShellConfig
export function getShellConfig(): { shell: string; args: string[] } {
  if (process.platform === "win32") {
    return {
      shell: resolvePowerShellPath(),
      args: ["-NoProfile", "-NonInteractive", "-Command"],
    };
  }

  const envShell = process.env.SHELL?.trim();
  const shellName = envShell ? path.basename(envShell) : "";
  
  // Fish shell rejects bashism syntax, downgrade to bash
  if (shellName === "fish") {
    const bash = resolveShellFromPath("bash");
    if (bash) return { shell: bash, args: ["-c"] };
    const sh = resolveShellFromPath("sh");
    if (sh) return { shell: sh, args: ["-c"] };
  }
  
  const shell = envShell?.length > 0 ? envShell : "sh";
  return { shell, args: ["-c"] };
}
```

Three key design decisions:

**1. Windows Uses PowerShell Instead of cmd.exe**

```typescript
function resolvePowerShellPath(): string {
  const systemRoot = process.env.SystemRoot || process.env.WINDIR;
  if (systemRoot) {
    const candidate = path.join(
      systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"
    );
    if (fs.existsSync(candidate)) return candidate;
  }
  return "powershell.exe";
}
```

> **Sidebar**: Windows's `cmd.exe` has a serious flaw: many system tools (like `ipconfig`, `systeminfo`) output directly to the console via the Win32 API `WriteConsole()`, rather than through standard stdout pipes. When Node.js spawns cmd.exe in pipe mode, these tools' output "disappears". PowerShell correctly captures and redirects this output, so OpenClaw chooses PowerShell on Windows.

**2. Fish Shell Auto-Downgrade**

Fish shell syntax differs drastically from POSIX shell/bash (e.g., doesn't support `$()` command substitution, `&&`, etc.), and most tool-generated commands assume bash syntax. OpenClaw detects Fish and tries to find `bash` → `sh` as replacements.

**3. Shell Path Resolution**

```typescript
function resolveShellFromPath(name: string): string | undefined {
  const entries = (process.env.PATH ?? "").split(path.delimiter);
  for (const entry of entries) {
    const candidate = path.join(entry, name);
    try {
      fs.accessSync(candidate, fs.constants.X_OK);
      return candidate;
    } catch { /* ignore */ }
  }
  return undefined;
}
```

Manually traverse PATH, using `accessSync(X_OK)` to check if the file is executable. This is more reliable than depending on the `which` command—`which` itself needs a Shell to execute, creating circular dependency.

***

## 23.3.2 Docker Sandbox Environment Building

### buildDockerExecArgs — Build Docker exec Parameters

```typescript
// src/agents/bash-tools.shared.ts — buildDockerExecArgs
export function buildDockerExecArgs(params) {
  const args = ["exec", "-i"];           // -i: keep stdin open
  if (params.tty) args.push("-t");       // -t: allocate TTY
  if (params.workdir) args.push("-w", params.workdir);  // working directory
  
  // inject environment variables
  for (const [key, value] of Object.entries(params.env)) {
    args.push("-e", `${key}=${value}`);
  }
  
  // special PATH handling
  if (hasCustomPath) {
    args.push("-e", `OPENCLAW_PREPEND_PATH=${params.env.PATH}`);
  }
  
  // use login shell and prepend PATH after profile loading
  const pathExport = hasCustomPath
    ? 'export PATH="${OPENCLAW_PREPEND_PATH}:$PATH"; unset OPENCLAW_PREPEND_PATH; '
    : "";
  args.push(params.containerName, "sh", "-lc", `${pathExport}${params.command}`);
  return args;
}
```

There's a clever PATH handling trick here:

```
Problem: When using login shell (-l) in Docker container, /etc/profile resets PATH
         causing custom PATH set via -e PATH=xxx to be overwritten
         
Solution:
  1. Store custom PATH in temporary variable OPENCLAW_PREPEND_PATH
  2. Add before command: export PATH="${OPENCLAW_PREPEND_PATH}:$PATH"
  3. This way custom PATH is injected after profile loading, won't be overwritten
  4. Finally unset OPENCLAW_PREPEND_PATH to avoid variable leakage
```

### buildSandboxEnv — Build Sandbox Environment Variables

```typescript
// src/agents/bash-tools.shared.ts — sandbox environment variables
export function buildSandboxEnv(params) {
  const env: Record<string, string> = {
    PATH: params.defaultPath,        // system default PATH
    HOME: params.containerWorkdir,   // HOME set to working directory
  };
  // merge sandbox config env first, then user-specified env
  for (const [key, value] of Object.entries(params.sandboxEnv ?? {})) {
    env[key] = value;
  }
  for (const [key, value] of Object.entries(params.paramsEnv ?? {})) {
    env[key] = value;
  }
  return env;
}
```

Note the merge order: user-specified environment variables (`paramsEnv`) have highest priority and can override sandbox defaults. In sandbox mode, there's no environment variable security check—because the container provides sufficient isolation.

***

## 23.3.3 Working Directory Resolution

### Host Machine Mode

```typescript
// src/agents/bash-tools.shared.ts — resolveWorkdir
export function resolveWorkdir(workdir: string, warnings: string[]) {
  const current = safeCwd();
  const fallback = current ?? homedir();
  try {
    const stats = statSync(workdir);
    if (stats.isDirectory()) return workdir;
  } catch { /* ignore */ }
  
  warnings.push(`Warning: workdir "${workdir}" is unavailable; using "${fallback}".`);
  return fallback;
}

function safeCwd() {
  try {
    const cwd = process.cwd();
    return existsSync(cwd) ? cwd : null;
  } catch { return null; }
}
```

`safeCwd()` handles an edge case: if the current working directory is deleted (e.g., by another process), `process.cwd()` throws an exception. This is not rare in long-running servers.

### Sandbox Mode

```typescript
// src/agents/bash-tools.shared.ts — resolveSandboxWorkdir
export async function resolveSandboxWorkdir(params) {
  try {
    // verify path is within sandbox allowed range
    const resolved = await assertSandboxPath({
      filePath: params.workdir,
      cwd: process.cwd(),
      root: params.sandbox.workspaceDir,
    });
    // convert to container path
    const relative = resolved.relative
      ? resolved.relative.split(path.sep).join(path.posix.sep)
      : "";
    const containerWorkdir = relative
      ? path.posix.join(params.sandbox.containerWorkdir, relative)
      : params.sandbox.containerWorkdir;
    return { hostWorkdir: resolved.resolved, containerWorkdir };
  } catch {
    return {
      hostWorkdir: params.sandbox.workspaceDir,
      containerWorkdir: params.sandbox.containerWorkdir,
    };
  }
}
```

Sandbox mode requires **path mapping**: host machine path → container path. For example:

```
Host path:        /home/user/projects/myapp
Sandbox workspace: /home/user/projects
Container workdir: /workspace

Mapping result:
  hostWorkdir:      /home/user/projects/myapp
  containerWorkdir: /workspace/myapp
```

Note the conversion from `path.sep` to `path.posix.sep`—if the host is Windows (backslash separator), the container path still needs forward slashes.

***

## 23.3.4 Binary Output Sanitization

```typescript
// src/agents/shell-utils.ts — sanitizeBinaryOutput
export function sanitizeBinaryOutput(text: string): string {
  // 1. remove Unicode format characters and surrogate pairs
  const scrubbed = text.replace(/[\p{Format}\p{Surrogate}]/gu, "");
  
  // 2. filter character by character
  const chunks: string[] = [];
  for (const char of scrubbed) {
    const code = char.codePointAt(0);
    // preserve Tab(\x09), newline(\x0a), carriage return(\x0d)
    if (code === 0x09 || code === 0x0a || code === 0x0d) {
      chunks.push(char);
      continue;
    }
    // filter ASCII control characters (0x00-0x1f)
    if (code < 0x20) continue;
    chunks.push(char);
  }
  return chunks.join("");
}
```

When command output contains binary data (like `cat` on an image file) or garbled terminal control sequences, `sanitizeBinaryOutput` ensures the text passed to the Agent is a valid displayable string. It preserves tabs, newlines, carriage returns and other necessary whitespace, but filters out all other control characters.

> **Sidebar**: Unicode's `\p{Format}` category includes zero-width joiners (ZWJ), directional control characters (LTR/RTL marks), and other invisible characters; `\p{Surrogate}` are surrogate pairs in UTF-16 encoding, representing incomplete surrogates in JavaScript strings (usually encoding errors). If these characters are passed to LLM APIs, they may cause JSON serialization errors or produce unexpected behavior.

***

## 23.3.5 Process Tree Management

```typescript
// src/agents/shell-utils.ts — killProcessTree
export function killProcessTree(pid: number): void {
  if (process.platform === "win32") {
    spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
      stdio: "ignore",
      detached: true,
    });
    return;
  }

  try {
    process.kill(-pid, "SIGKILL");  // negative PID = kill entire process group
  } catch {
    try {
      process.kill(pid, "SIGKILL"); // fallback: kill main process only
    } catch { /* process already dead */ }
  }
}
```

> **Sidebar**: On Unix systems, child processes created with `detached: true` become the group leader of a new process group (Process Group). `process.kill(-pid, signal)` with negative PID sends the signal to the entire process group, killing the process and all its children. For example, running `npm run build` spawns npm, which spawns node, which may spawn webpack, which spawns multiple workers—killing just npm isn't enough; you need to kill the entire process tree. On Windows, `taskkill /T` (/T = tree) achieves the same effect.

`killSession()` is a wrapper around `killProcessTree()`:

```typescript
// src/agents/bash-tools.shared.ts
export function killSession(session) {
  const pid = session.pid ?? session.child?.pid;
  if (pid) killProcessTree(pid);
}
```

***

## 23.3.6 Shared Utility Functions

The Bash tool chain also includes a set of practical shared functions:

### String Truncation

```typescript
// middle truncation — preserve start and end, replace middle with ...
export function truncateMiddle(str: string, max: number) {
  if (str.length <= max) return str;
  const half = Math.floor((max - 3) / 2);
  return `${sliceUtf16Safe(str, 0, half)}...${sliceUtf16Safe(str, -half)}`;
}
// truncateMiddle("very-long-command-name", 15) → "very-l...d-name"
```

Note using `sliceUtf16Safe()` instead of plain `String.slice()`—ensures we don't truncate in the middle of UTF-16 surrogate pairs, producing invalid Unicode characters.

### Log Pagination

```typescript
// src/agents/bash-tools.shared.ts — log slicing
export function sliceLogLines(text: string, offset?: number, limit?: number) {
  const lines = text.replace(/\r\n/g, "\n").split("\n");
  // remove trailing empty line
  if (lines[lines.length - 1] === "") lines.pop();
  
  let start = offset ?? 0;
  // if only limit specified without offset, get last N lines (like tail -n)
  if (limit !== undefined && offset === undefined) {
    start = Math.max(lines.length - limit, 0);
  }
  
  return {
    slice: lines.slice(start, end).join("\n"),
    totalLines: lines.length,
    totalChars: text.length,
  };
}
```

One clever aspect of this function: when only `limit` is passed, the default behavior is like `tail -n`—return the last N lines. This matches the Agent's typical use case: "show me the last few lines of output".

### Command Name Extraction

```typescript
export function deriveSessionName(command: string): string | undefined {
  const tokens = tokenizeCommand(command);
  const verb = tokens[0];
  let target = tokens.slice(1).find(t => !t.startsWith("-"));
  return target ? `${verb} ${truncateMiddle(stripQuotes(target), 48)}` : verb;
}
```

### Duration Formatting

```typescript
export function formatDuration(ms: number) {
  if (ms < 1000) return `${ms}ms`;
  const seconds = Math.floor(ms / 1000);
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const rem = seconds % 60;
  return `${minutes}m${rem.toString().padStart(2, "0")}s`;
}
// 500 → "500ms"
// 3000 → "3s"
// 125000 → "2m05s"
```

***

## 23.3.7 Barrel File and Module Exports

Finally, `bash-tools.ts` as a barrel file aggregates all exports:

```typescript
// src/agents/bash-tools.ts — complete file
export type { BashSandboxConfig, ExecElevatedDefaults, 
              ExecToolDefaults, ExecToolDetails } from "./bash-tools.exec.js";
export { createExecTool, execTool } from "./bash-tools.exec.js";
export type { ProcessToolDefaults } from "./bash-tools.process.js";
export { createProcessTool, processTool } from "./bash-tools.process.js";
```

> **Sidebar**: Barrel File is a common module organization pattern in TypeScript/JavaScript projects. It contains no business logic itself, only re-exports symbols from submodules, allowing consumers to import needed content from a single entry point: `import { execTool, processTool } from "./bash-tools.js"`, without needing to know about internal file splitting.

External code only needs `import { execTool, processTool } from "./bash-tools.js"` to get pre-configured tool instances, or use `createExecTool(customDefaults)` to create custom instances.

***

## Summary of This Section

1. **Shell detection is platform-aware**: Windows uses PowerShell (avoiding WriteConsole capture issues); Fish downgrades to bash (avoiding bashism incompatibility); defaults to `$SHELL` environment variable
2. **Docker PATH injection uses temporary variable trick**—store in `OPENCLAW_PREPEND_PATH`, export after login shell profile loads, avoiding being overwritten by `/etc/profile`
3. **Working directory resolution handles multiple edge cases**: directory doesn't exist, current directory deleted, sandbox path mapping (host → container), Windows/Unix path separator conversion
4. **Binary output sanitization** removes Unicode format characters, surrogate pairs, and ASCII control characters, ensuring LLM receives valid text
5. **Process tree killing** uses Unix process groups (negative PID) and Windows taskkill /T to ensure complete child process chain termination
6. **Shared utility functions** handle UTF-16 safe truncation, tail-like log pagination, command name extraction, and duration formatting
7. **Barrel file pattern** provides a clean unified import entry point for external consumers
