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

# 23.2 Process Management

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

***

In the previous section, we deeply analyzed how the exec tool creates and executes processes. When a command transitions to background due to `yieldMs` expiration or `background: true`, the Agent needs a mechanism to monitor, interact with, and terminate these processes. This is the responsibility of the **process tool** and **process registry**.

***

## 23.2.1 Process Registry

### Dual Map Architecture in Memory

The process registry is located in `bash-process-registry.ts`, using two `Map`s to manage process lifecycle:

```typescript
// src/agents/bash-process-registry.ts — core data structures
const runningSessions  = new Map<string, ProcessSession>();   // running
const finishedSessions = new Map<string, FinishedSession>();  // finished
```

`ProcessSession` is the complete state of a running process:

```typescript
interface ProcessSession {
  id: string;                  // session ID (short code, e.g., "a3f7bc")
  command: string;             // original command
  child?: ChildProcessWithoutNullStreams;  // Node.js child process handle
  stdin?: SessionStdin;        // stdin write adapter (supports PTY)
  pid?: number;                // operating system PID
  startedAt: number;           // startup timestamp
  cwd?: string;                // working directory
  
  // output management
  maxOutputChars: number;      // max output characters (default 200,000)
  totalOutputChars: number;    // total output characters produced
  pendingStdout: string[];     // pending stdout buffer
  pendingStderr: string[];     // pending stderr buffer
  aggregated: string;          // full output (capped with truncation)
  tail: string;                // last 2000 characters
  truncated: boolean;          // truncated due to limit exceeded?
  
  // status
  exited: boolean;
  exitCode?: number | null;
  exitSignal?: NodeJS.Signals | number | null;
  backgrounded: boolean;       // transitioned to background?
}
```

`FinishedSession` is a streamlined record after process completion:

```typescript
interface FinishedSession {
  id: string;
  command: string;
  startedAt: number;
  endedAt: number;
  status: ProcessStatus;       // "completed" | "failed" | "killed"
  exitCode?: number | null;
  exitSignal?: NodeJS.Signals | number | null;
  aggregated: string;          // preserve full output
  tail: string;                // last 2000 characters
  truncated: boolean;
  totalOutputChars: number;
}
```

### Output Buffering Strategy

When a process produces output, the `appendOutput()` function manages multi-level buffering:

```typescript
// src/agents/bash-process-registry.ts — appendOutput (simplified)
export function appendOutput(
  session: ProcessSession,
  stream: "stdout" | "stderr",
  chunk: string
) {
  const buffer = stream === "stdout" 
    ? session.pendingStdout 
    : session.pendingStderr;
    
  buffer.push(chunk);
  
  // 1. If pending buffer exceeds limit, truncate old data
  if (pendingChars > pendingCap) {
    session.truncated = true;
    capPendingBuffer(buffer, pendingChars, pendingCap);
  }
  
  // 2. aggregated also has a limit (default 200,000 characters)
  session.aggregated = trimWithCap(
    session.aggregated + chunk, 
    session.maxOutputChars
  );
  
  // 3. tail always preserves last 2000 characters
  session.tail = tail(session.aggregated, 2000);
}
```

This design solves practical problems:

* **pending buffer** is the data source for `poll` operations—Agent takes pending on each poll, then clears it
* **aggregated** is a rolling window of complete output—old content is discarded when limit exceeded
* **tail** for quick preview—displayed when listing processes

> **Sidebar**: The "rolling window" concept here is similar to Ring Buffer in logging systems. When new data is written and the buffer is full, the oldest data is discarded. The `trimWithCap()` function implementation is straightforward: `text.slice(text.length - max)`, keeping only the last `max` characters.

### Process Lifecycle Transitions

```
Creation              Backgrounding           Exit
addSession()  →  markBackgrounded()  →  markExited()
   │                   │                    │
   ▼                   ▼                    ▼
runningSessions    still in running     moveToFinished()
                   backgrounded=true    ├─ remove from runningSessions
                                        └─ add to finishedSessions
```

`moveToFinished()` has a critical check: **only backgrounded processes are saved to finishedSessions**. If a process completes synchronously (within yieldMs), its result is returned directly to the Agent without registering to the finished table.

### Auto-Cleanup (Sweeper)

```typescript
// src/agents/bash-process-registry.ts — periodic cleanup
const DEFAULT_JOB_TTL_MS = 30 * 60 * 1000;  // 30 minutes
const MIN_JOB_TTL_MS     = 60 * 1000;        // minimum 1 minute
const MAX_JOB_TTL_MS     = 3 * 60 * 60 * 1000; // maximum 3 hours

function pruneFinishedSessions() {
  const cutoff = Date.now() - jobTtlMs;
  for (const [id, session] of finishedSessions.entries()) {
    if (session.endedAt < cutoff) {
      finishedSessions.delete(id);
    }
  }
}

function startSweeper() {
  sweeper = setInterval(pruneFinishedSessions, 
    Math.max(30_000, jobTtlMs / 6));
  sweeper.unref?.();  // don't prevent Node.js process exit
}
```

The sweeper interval is TTL/6 (minimum 30 seconds). Using `unref()` ensures the timer won't prevent normal Node.js process exit.

***

## 23.2.2 process Tool

### Tool Definition

```typescript
// src/agents/bash-tools.process.ts — Schema
const processSchema = Type.Object({
  action:    Type.String(),                      // action type
  sessionId: Type.Optional(Type.String()),       // target session ID
  data:      Type.Optional(Type.String()),       // write data
  keys:      Type.Optional(Type.Array(Type.String())),  // send-keys keys
  hex:       Type.Optional(Type.Array(Type.String())),  // send-keys hex bytes
  literal:   Type.Optional(Type.String()),       // send-keys literal string
  text:      Type.Optional(Type.String()),       // paste text
  bracketed: Type.Optional(Type.Boolean()),      // use bracketed paste?
  eof:       Type.Optional(Type.Boolean()),      // close stdin after write?
  offset:    Type.Optional(Type.Number()),       // log offset
  limit:     Type.Optional(Type.Number()),       // log line limit
});
```

### Ten Actions

The process tool supports ten actions, covering complete process management needs:

| Action      | Purpose                                           | Needs sessionId |
| ----------- | ------------------------------------------------- | :-------------: |
| `list`      | List all background sessions (running + finished) |        ✗        |
| `poll`      | Get incremental output (consume pending buffer)   |        ✓        |
| `log`       | Read complete log (supports pagination)           |        ✓        |
| `write`     | Write data to stdin                               |        ✓        |
| `send-keys` | Send terminal key sequence                        |        ✓        |
| `submit`    | Send Enter key (`\r`)                             |        ✓        |
| `paste`     | Paste text (supports bracketed paste)             |        ✓        |
| `kill`      | Terminate process                                 |        ✓        |
| `clear`     | Clear finished session records                    |        ✓        |
| `remove`    | Force remove session (kill if running)            |        ✓        |

### `list` — Session List

```typescript
// src/agents/bash-tools.process.ts — list action (simplified)
case "list": {
  const running = listRunningSessions()
    .filter(s => isInScope(s))
    .map(s => ({
      sessionId: s.id,
      status: "running",
      pid: s.pid,
      runtimeMs: Date.now() - s.startedAt,
      command: s.command,
      name: deriveSessionName(s.command),
      tail: s.tail,
    }));
  const finished = listFinishedSessions()
    .filter(s => isInScope(s))
    .map(s => ({
      sessionId: s.id,
      status: s.status,
      runtimeMs: s.endedAt - s.startedAt,
      name: deriveSessionName(s.command),
      exitCode: s.exitCode,
    }));
  // sort by startup time descending
  const lines = [...running, ...finished]
    .toSorted((a, b) => b.startedAt - a.startedAt)
    .map(s => `${s.sessionId} ${pad(s.status, 9)} ${formatDuration(s.runtimeMs)} :: ${label}`);
  return { content: [{ type: "text", text: lines.join("\n") }] };
}
```

`deriveSessionName()` extracts a short name from the command—takes the first token as the "verb" and the first non-option argument as the "target":

```typescript
// src/agents/bash-tools.shared.ts — name extraction
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(target, 48)}` : verb;
}
// "npm install express" → "npm express"
// "git log --oneline" → "git log"
```

### `poll` — Incremental Output

The core difference between `poll` and `log`:

```
poll:
  1. Get pendingStdout + pendingStderr
  2. Clear pending buffers (drainSession)
  3. Return new output since last poll
  
log:
  1. Read aggregated (full output)
  2. Support offset/limit pagination
  3. Don't modify any state
```

poll is **consumptive**—pending is cleared after each call; log is **read-only**—can be viewed repeatedly.

### Difference Between `write` and `send-keys`

Both write data to process stdin, but serve different purposes:

```typescript
// write — write raw data directly
case "write": {
  const stdin = scopedSession.stdin ?? scopedSession.child?.stdin;
  await new Promise((resolve, reject) => {
    stdin.write(params.data ?? "", (err) => err ? reject(err) : resolve());
  });
  if (params.eof) stdin.end();  // optionally close stdin
}

// send-keys — encode terminal key sequence
case "send-keys": {
  const { data, warnings } = encodeKeySequence({
    keys: params.keys,       // ["C-c", "Enter", "M-x"]
    hex: params.hex,         // ["0x1b", "0x5b"]
    literal: params.literal, // "hello"
  });
  await stdin.write(data);
}
```

`write` is suitable for pipe-style input (passing data to scripts); `send-keys` is suitable for interacting with TUI programs (like pressing `Esc`, `Ctrl-C` in vim).

***

## 23.2.3 PTY Key Encoding

### encodeKeySequence

The PTY key encoding engine is located in `pty-keys.ts`, supporting multiple input formats:

```typescript
// src/agents/pty-keys.ts — encodeKeySequence (simplified)
export function encodeKeySequence(request: KeyEncodingRequest) {
  let data = "";
  
  // 1. literal — append literal text directly
  if (request.literal) data += request.literal;
  
  // 2. hex — hexadecimal byte sequence
  for (const raw of request.hex ?? []) {
    const byte = parseHexByte(raw);  // "0x1b" → 27
    data += String.fromCharCode(byte);
  }
  
  // 3. keys — key token encoding
  for (const token of request.keys ?? []) {
    data += encodeKeyToken(token, warnings);
  }
  
  return { data, warnings };
}
```

### Key Token Syntax

Key tokens use modifier syntax similar to tmux/Emacs:

| Token                            | Meaning       | Encoded Result       |
| -------------------------------- | ------------- | -------------------- |
| `Enter`                          | Enter key     | `\r`                 |
| `Tab`                            | Tab character | `\t`                 |
| `Escape` / `Esc`                 | ESC key       | `\x1b`               |
| `BSpace`                         | Backspace     | `\x7f`               |
| `Up` / `Down` / `Left` / `Right` | Arrow keys    | `\x1b[A` \~ `\x1b[D` |
| `F1` \~ `F12`                    | Function keys | VT100 sequence       |
| `C-c`                            | Ctrl-C        | `\x03`               |
| `M-x`                            | Alt-X         | `\x1b` + `x`         |
| `S-Tab`                          | Shift-Tab     | `\x1b[Z`             |
| `C-M-a`                          | Ctrl-Alt-A    | `\x1b` + `\x01`      |

> **Sidebar**: In VT100/xterm terminal standards, special keys are encoded through **escape sequences**. They start with the ESC character (`\x1b`), followed by CSI (Control Sequence Introducer, i.e., `[`), then parameters and terminator. For example, the Up arrow key is encoded as `\x1b[A`, and the Delete key as `\x1b[3~`. These sequences are standard terminal emulator protocols.

Modifier prefix handling:

```typescript
// src/agents/pty-keys.ts — modifier parsing
function parseModifiers(token: string) {
  const mods = { ctrl: false, alt: false, shift: false };
  let rest = token;
  while (rest.length > 2 && rest[1] === "-") {
    const mod = rest[0].toLowerCase();
    if (mod === "c") mods.ctrl = true;   // C- = Ctrl
    else if (mod === "m") mods.alt = true;   // M- = Alt/Meta
    else if (mod === "s") mods.shift = true; // S- = Shift
    else break;
    rest = rest.slice(2);
  }
  return { mods, base: rest };
}
```

### Ctrl Character Encoding

Ctrl combination key encoding follows ASCII control character rules:

```typescript
function toCtrlChar(char: string): string | null {
  if (char === "?") return "\x7f";  // Ctrl-? = DEL
  const code = char.toUpperCase().charCodeAt(0);
  if (code >= 64 && code <= 95) {
    return String.fromCharCode(code & 0x1f);  // bit mask
  }
  return null;
}
// 'C' (67) & 0x1f = 3 → Ctrl-C = \x03
// 'A' (65) & 0x1f = 1 → Ctrl-A = \x01
```

> **Sidebar**: In the ASCII table, uppercase letters A-Z are encoded as 65-90. Performing `& 0x1f` (bitwise AND with 31) on these encodings yields 1-26, corresponding to ASCII control characters SOH through SUB. This is why Ctrl-C is `\x03` (3 = 67 & 31)—this rule comes from 1960s terminal hardware design and continues to be used today.

### xterm Modifier Encoding

For combinations with modifiers like Shift-Up, use xterm extended syntax:

```typescript
function xtermModifier(mods: Modifiers): number {
  let mod = 1;
  if (mods.shift) mod += 1;   // 2
  if (mods.alt)   mod += 2;   // 3
  if (mods.ctrl)  mod += 4;   // 5
  return mod;
}

// S-Up → \x1b[1;2A  (1 is default param, 2 = shift)
// C-Right → \x1b[1;5C  (5 = ctrl)
// C-S-Left → \x1b[1;6D  (6 = ctrl+shift)
```

### Bracketed Paste

```typescript
// src/agents/pty-keys.ts
export const BRACKETED_PASTE_START = `\x1b[200~`;
export const BRACKETED_PASTE_END   = `\x1b[201~`;

export function encodePaste(text: string, bracketed = true): string {
  if (!bracketed) return text;
  return `${BRACKETED_PASTE_START}${text}${BRACKETED_PASTE_END}`;
}
```

> **Sidebar**: Bracketed Paste is a security feature of modern terminal emulators. When users paste text, the terminal inserts special sequences `\x1b[200~` and `\x1b[201~` before and after the text. Shells (like zsh, bash 5.1+) detecting these sequences know the content is pasted rather than manually typed, so they won't execute immediately—preventing "paste attacks" (malicious websites putting `rm -rf /` in the clipboard). OpenClaw's `paste` action uses bracketed mode by default to simulate correct paste behavior.

***

## 23.2.4 Scope Isolation

The process tool supports **scopeKey** to implement process isolation:

```typescript
// src/agents/bash-tools.process.ts — scope filtering
const scopeKey = defaults?.scopeKey;
const isInScope = (session) => 
  !scopeKey || session?.scopeKey === scopeKey;
```

When multiple Agent instances run in parallel, each Agent can only see and operate on processes under its own scopeKey. This prevents Agent A from accidentally killing Agent B's background tasks.

***

## Summary of This Section

1. **Process registry uses dual Map architecture**: `runningSessions` (running) and `finishedSessions` (finished), transitioning between them via `markExited()`
2. **Three-level output buffering**: pending (incremental consumption), aggregated (rolling window, default 200K character limit), tail (last 2000 characters preview)
3. **process tool supports ten actions**: list, poll, log, write, send-keys, submit, paste, kill, clear, remove
4. **PTY key encoding supports complete terminal key syntax**: modifier prefixes (C-/M-/S-), named keys (Enter/Tab/F1-F12), hex bytes, xterm modifier extensions
5. **Ctrl character encoding uses ASCII bit mask rule** (`& 0x1f`), a design legacy from terminal hardware era
6. **Bracketed Paste** prevents paste attacks—adds special escape sequences around pasted text
7. **Auto-cleanup (sweeper)** scans finished sessions every TTL/6, default 30 minutes to evict
8. **scopeKey isolation** ensures multiple Agents running in parallel don't interfere
