> 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/ch27-node-system/27.3-node-host-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 27.3 Node Host Implementation

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

***

The previous two sections analyzed node concepts and Gateway-side management mechanisms. This section shifts to the node side—how Node Host runs: how it connects to the Gateway, how it handles command requests, how it safely executes system commands, and how it persists as a system service.

***

## 27.3.1 Node Host Runner (`src/node-host/runner.ts`)

### Startup Flow

`runNodeHost` is the entry point for Node Host. It completes a series of initialization work: configuration loading, identity resolution, WebSocket connection establishment, etc.:

```typescript
// src/node-host/runner.ts (simplified)

export async function runNodeHost(opts: NodeHostRunOptions): Promise<void> {
  // 1. Load or create configuration
  const config = await ensureNodeHostConfig();
  const nodeId = opts.nodeId?.trim() || config.nodeId;
  const displayName = opts.displayName?.trim()
    || config.displayName
    || await getMachineDisplayName();

  // 2. Save Gateway connection information
  const gateway: NodeHostGatewayConfig = {
    host: opts.gatewayHost,
    port: opts.gatewayPort,
    tls: opts.gatewayTls ?? loadConfig().gateway?.tls?.enabled ?? false,
    tlsFingerprint: opts.gatewayTlsFingerprint,
  };
  config.gateway = gateway;
  await saveNodeHostConfig(config);

  // 3. Resolve browser proxy configuration
  const browserProxy = resolveBrowserProxyConfig();
  const browserProxyEnabled = browserProxy.enabled && resolvedBrowser.enabled;

  // 4. Resolve authentication information
  const token = process.env.OPENCLAW_GATEWAY_TOKEN?.trim()
    || cfg.gateway?.auth?.token;
  const password = process.env.OPENCLAW_GATEWAY_PASSWORD?.trim()
    || cfg.gateway?.auth?.password;

  // 5. Ensure PATH environment variable is available
  const pathEnv = ensureNodePathEnv();

  // 6. Create Gateway client and connect
  const client = new GatewayClient({
    url: `${gateway.tls ? "wss" : "ws"}://${host}:${port}`,
    token, password,
    instanceId: nodeId,
    clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
    clientDisplayName: displayName,
    mode: GATEWAY_CLIENT_MODES.NODE,
    role: "node",
    caps: ["system", ...(browserProxyEnabled ? ["browser"] : [])],
    commands: [
      "system.run", "system.which",
      "system.execApprovals.get", "system.execApprovals.set",
      ...(browserProxyEnabled ? ["browser.proxy"] : []),
    ],
    pathEnv,
    deviceIdentity: loadOrCreateDeviceIdentity(),
    onEvent: (evt) => {
      if (evt.event !== "node.invoke.request") return;
      const payload = coerceNodeInvokePayload(evt.payload);
      if (!payload) return;
      void handleInvoke(payload, client, skillBins);
    },
    // ...
  });

  client.start();
  await new Promise(() => {}); // Never resolves—keeps process running
}
```

Several key design points in the startup flow:

| Step                          | Design Intent                                                      |
| ----------------------------- | ------------------------------------------------------------------ |
| `ensureNodeHostConfig`        | If config file doesn't exist, auto-generate nodeId (UUID) and save |
| `getMachineDisplayName`       | Get friendly name from OS (e.g., "MacBook Pro")                    |
| `ensureNodePathEnv`           | Ensure OpenClaw CLI is in PATH so other tools can invoke it        |
| `loadOrCreateDeviceIdentity`  | Generate persistent device identity for pairing and authentication |
| `await new Promise(() => {})` | Classic "never exit" pattern—keeps event loop running              |

### Declaring Capabilities and Commands

Note the distinction between `caps` and `commands`:

* **`caps` (capabilities)**: Coarse-grained capability categories, e.g., `"system"` means can execute system commands, `"browser"` means can proxy browser operations.
* **`commands` (commands)**: Fine-grained command list, e.g., `"system.run"` means supports executing Shell commands.

Node Host declares support for `system.*` commands by default. If browser proxy is configured, it additionally declares `browser.proxy`.

### Event Listening

Node Host listens for events pushed by the Gateway via the `onEvent` callback. When it receives a `node.invoke.request` event, it passes the event payload to `handleInvoke` for processing:

```typescript
onEvent: (evt) => {
  if (evt.event !== "node.invoke.request") return;
  const payload = coerceNodeInvokePayload(evt.payload);
  if (!payload) return;
  void handleInvoke(payload, client, skillBins);
},
```

`coerceNodeInvokePayload` performs defensive validation on event data—it won't crash even if it receives malformed data:

```typescript
function coerceNodeInvokePayload(payload: unknown): NodeInvokeRequestPayload | null {
  if (!payload || typeof payload !== "object") return null;
  const obj = payload as Record<string, unknown>;
  const id = typeof obj.id === "string" ? obj.id.trim() : "";
  const nodeId = typeof obj.nodeId === "string" ? obj.nodeId.trim() : "";
  const command = typeof obj.command === "string" ? obj.command.trim() : "";
  if (!id || !nodeId || !command) return null;
  // Support both paramsJSON string and params object formats
  const paramsJSON = typeof obj.paramsJSON === "string"
    ? obj.paramsJSON
    : obj.params !== undefined ? JSON.stringify(obj.params) : null;
  return { id, nodeId, command, paramsJSON, timeoutMs, idempotencyKey };
}
```

***

## 27.3.2 Command Handling Dispatch

`handleInvoke` is Node Host's command router, dispatching requests to different handling logic based on the `command` field:

```typescript
// src/node-host/runner.ts (simplified)

async function handleInvoke(
  frame: NodeInvokeRequestPayload,
  client: GatewayClient,
  skillBins: SkillBinsCache,
) {
  const command = String(frame.command ?? "");

  switch (command) {
    case "system.execApprovals.get":
      // → Return current execution approval configuration
    case "system.execApprovals.set":
      // → Update execution approval configuration (with optimistic locking)
    case "system.which":
      // → Find binary file path
    case "browser.proxy":
      // → Proxy browser operations
    case "system.run":
      // → Execute system command (most complex branch)
    default:
      // → Return "command not supported"
  }
}
```

### system.which — Binary File Discovery

The `system.which` command finds the absolute path of a specified binary file, similar to Unix's `which` command:

```typescript
async function handleSystemWhich(
  params: SystemWhichParams,
  env?: Record<string, string>,
) {
  const found: Record<string, string> = {};
  for (const bin of params.bins) {
    const path = resolveExecutable(bin.trim(), env);
    if (path) found[bin] = path;
  }
  return { bins: found };
}
```

`resolveExecutable` traverses each directory in PATH, and on Windows also tries adding `.EXE`, `.CMD` and other suffixes. This command is used by the Agent to **probe the target environment** before executing commands—for example, checking if `python3`, `node`, `git` are available.

### browser.proxy — Browser Operation Proxy

When Node Host is configured with browser proxy, the Gateway can remotely control the browser on the Node Host machine via the `browser.proxy` command. The implementation uses the browser control service introduced in Chapter 24:

```typescript
// src/node-host/runner.ts (simplified)

case "browser.proxy": {
  // Security check: is browser proxy enabled?
  if (!proxyConfig.enabled) throw new Error("node browser proxy disabled");

  // Security check: is the requested profile in the allowlist?
  if (!isProfileAllowed({ allowProfiles, profile: requestedProfile })) {
    throw new Error("browser profile not allowed");
  }

  // Ensure browser control service is started
  await ensureBrowserControlService();

  // Dispatch request to browser router
  const dispatcher = createBrowserRouteDispatcher(createBrowserControlContext());
  const response = await withTimeout(
    dispatcher.dispatch({ method, path, query, body }),
    params.timeoutMs,
  );

  // If response contains file paths, read and base64 encode them
  const paths = collectBrowserProxyPaths(response.body);
  const files = await Promise.all(paths.map(readBrowserProxyFile));

  await sendInvokeResult(client, frame, { ok: true, payloadJSON: JSON.stringify({ result, files }) });
}
```

Files (such as screenshots) are transmitted inline via base64 encoding, with individual files not exceeding 10MB (`BROWSER_PROXY_MAX_FILE_BYTES`).

***

## 27.3.3 system.run — Safe Command Execution

`system.run` is Node Host's most core and most dangerous capability—it allows an Agent to execute arbitrary Shell commands on a remote machine. Therefore, its security controls are the most complex part of the entire Node System.

### Security Layers

Command execution passes through four layers of security checks:

```
┌─────────────────────────────────────────────────────────┐
│  ① macOS App Execution Host (Exec Host)                 │
│  → Delegate to macOS native app execution via Unix Socket│
│  → If available, prioritize this path                    │
├─────────────────────────────────────────────────────────┤
│  ② Security Level                                       │
│  → "deny": Prohibit all execution                        │
│  → "allowlist": Only allow whitelisted commands          │
│  → "full": Allow all execution                           │
├─────────────────────────────────────────────────────────┤
│  ③ Approval Mechanism                                   │
│  → "off": No approval needed                             │
│  → "on-miss": Approval needed if whitelist doesn't match │
│  → "always": Approval needed every time                  │
├─────────────────────────────────────────────────────────┤
│  ④ Allowlist Evaluation                                 │
│  → Parse command argv → Match authorized executable paths│
│  → Support Skill Bins (dynamic whitelist)                │
└─────────────────────────────────────────────────────────┘
```

### macOS Execution Host Priority

On macOS, Node Host prioritizes executing commands via **Exec Host** (the execution sandbox of the macOS native app):

```typescript
// src/node-host/runner.ts (simplified)

const useMacAppExec = process.platform === "darwin";
if (useMacAppExec) {
  const response = await runViaMacAppExecHost({ approvals, request: execRequest });
  if (response && response.ok) {
    // macOS App executed successfully
    await sendNodeEvent(client, "exec.finished", { ... });
    await sendInvokeResult(client, frame, { ok: true, payloadJSON: JSON.stringify(result) });
    return;
  }
  if (response && !response.ok) {
    // macOS App rejected execution
    await sendNodeEvent(client, "exec.denied", { reason: response.error.reason });
    await sendInvokeResult(client, frame, { ok: false, error: { message: response.error.message } });
    return;
  }
  // response === null: macOS App unreachable
  if (execHostEnforced || !execHostFallbackAllowed) {
    // Enforced mode: don't fall back, reject directly
    await sendInvokeResult(client, frame, { ok: false, error: { code: "UNAVAILABLE" } });
    return;
  }
  // Otherwise: fall back to direct execution
}
```

> **Sidebar: Exec Host and Unix Socket**
>
> Exec Host is a command execution service provided by the OpenClaw macOS native app. Node Host communicates with it via **Unix Domain Socket**. Unix Socket is an inter-process communication (IPC) mechanism that's much faster than TCP/IP (no network protocol stack overhead) and is naturally restricted to the local machine, offering higher security. The `OPENCLAW_NODE_EXEC_HOST=app` environment variable can enforce that all executions must go through Exec Host, preventing commands from bypassing the macOS app's approval UI.

### Allowlist Evaluation Flow

When the security level is `allowlist`, the command must pass allowlist evaluation:

```typescript
// src/node-host/runner.ts (simplified)

// Two evaluation paths:
if (rawCommand) {
  // Shell command string → evaluateShellAllowlist
  const result = evaluateShellAllowlist({
    command: rawCommand,
    allowlist: approvals.allowlist,
    safeBins,                    // Built-in safe binary list
    skillBins: await skillBins.current(), // Skill dynamic whitelist
    autoAllowSkills,
    platform: process.platform,
  });
} else {
  // argv array → analyzeArgvCommand + evaluateExecAllowlist
  const analysis = analyzeArgvCommand({ argv, cwd, env });
  const result = evaluateExecAllowlist({
    analysis,
    allowlist: approvals.allowlist,
    safeBins,
    skillBins,
    autoAllowSkills,
  });
}
```

**Skill Bins** is an interesting mechanism—the skill system can dynamically declare certain binary files as "safe", and these binaries are automatically added to the whitelist. `SkillBinsCache` caches this list with a 90-second TTL:

```typescript
class SkillBinsCache {
  private bins = new Set<string>();
  private lastRefresh = 0;
  private readonly ttlMs = 90_000;

  async current(force = false): Promise<Set<string>> {
    if (force || Date.now() - this.lastRefresh > this.ttlMs) {
      await this.refresh();
    }
    return this.bins;
  }

  private async refresh() {
    const bins = await this.fetch(); // Request skills.bins from Gateway
    this.bins = new Set(bins);
    this.lastRefresh = Date.now();
  }
}
```

### Command Execution

After passing all security checks, the command is actually executed via the `runCommand` function:

```typescript
// src/node-host/runner.ts (simplified)

async function runCommand(
  argv: string[],
  cwd: string | undefined,
  env: Record<string, string> | undefined,
  timeoutMs: number | undefined,
): Promise<RunResult> {
  return await new Promise((resolve) => {
    let stdout = "", stderr = "";
    let outputLen = 0, truncated = false, timedOut = false;

    const child = spawn(argv[0], argv.slice(1), {
      cwd, env,
      stdio: ["ignore", "pipe", "pipe"],
      windowsHide: true,
    });

    // Output capture (with 200KB truncation protection)
    const onChunk = (chunk: Buffer, target: "stdout" | "stderr") => {
      if (outputLen >= OUTPUT_CAP) { truncated = true; return; }
      const remaining = OUTPUT_CAP - outputLen;
      const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
      // ...
    };

    // Timeout handling
    if (timeoutMs > 0) {
      setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, timeoutMs);
    }

    child.on("exit", (code) => resolve({ exitCode: code, timedOut, success: code === 0, ... }));
  });
}
```

Key security measures:

| Measure                               | Implementation                    | Purpose                                    |
| ------------------------------------- | --------------------------------- | ------------------------------------------ |
| **Output Truncation**                 | `OUTPUT_CAP = 200_000` characters | Prevent memory overflow                    |
| **Timeout Termination**               | `SIGKILL`                         | Prevent commands from running forever      |
| **Environment Variable Sanitization** | `sanitizeEnv()`                   | Block injection of dangerous variables     |
| **stdin Closure**                     | `stdio: ["ignore", ...]`          | Prevent interactive commands from blocking |
| **Windows Hiding**                    | `windowsHide: true`               | Prevent console window from popping up     |

### Environment Variable Security

The `sanitizeEnv` function filters out dangerous environment variables:

```typescript
// src/node-host/runner.ts

const blockedEnvKeys = new Set([
  "NODE_OPTIONS",    // Can inject arbitrary Node.js parameters
  "PYTHONHOME",      // Can hijack Python interpreter
  "PYTHONPATH",      // Can inject Python module paths
  "PERL5LIB",       // Can inject Perl library paths
  "PERL5OPT",       // Can inject Perl options
  "RUBYOPT",        // Can inject Ruby options
]);

const blockedEnvPrefixes = [
  "DYLD_",  // macOS dynamic linker control
  "LD_",    // Linux dynamic linker control
];
```

> **Sidebar: Environment Variable Injection Attack**
>
> Many programming language runtimes read environment variables to change behavior. For example, `LD_PRELOAD` allows Linux to load a custom shared library before any program, hijacking system calls. `NODE_OPTIONS` can inject `--require` parameters to Node.js to load malicious scripts. Blocking these variables from being overridden is a basic practice in application-layer security.

### Execution Event Reporting

Every time a command is executed (whether successful, failed, or denied), Node Host sends an event notification to the Gateway:

```typescript
async function sendNodeEvent(client: GatewayClient, event: string, payload: unknown) {
  try {
    await client.request("node.event", {
      event,
      payloadJSON: payload ? JSON.stringify(payload) : null,
    });
  } catch {
    // Event sending is best-effort, doesn't block main flow
  }
}
```

Event output is truncated to 20KB (`OUTPUT_EVENT_TAIL`), preventing large output from overwhelming the WebSocket channel.

***

## 27.3.4 Node Configuration (`src/node-host/config.ts`)

### Configuration Structure

Node Host's configuration is stored in the `node.json` file under the state directory:

```typescript
// src/node-host/config.ts

export type NodeHostConfig = {
  version: 1;                        // Config version number (for migrations)
  nodeId: string;                    // Unique node identifier
  token?: string;                    // Pairing token (optional)
  displayName?: string;              // Display name
  gateway?: NodeHostGatewayConfig;   // Gateway connection information
};

export type NodeHostGatewayConfig = {
  host?: string;           // Gateway address, default 127.0.0.1
  port?: number;           // Gateway port, default 18789
  tls?: boolean;           // Whether to use TLS
  tlsFingerprint?: string; // TLS certificate fingerprint (for self-signed certs)
};
```

### Secure Writing

Configuration files are written with `0o600` permissions, ensuring only the current user can read and write:

```typescript
export async function saveNodeHostConfig(config: NodeHostConfig): Promise<void> {
  const filePath = resolveNodeHostConfigPath();
  await fs.mkdir(path.dirname(filePath), { recursive: true });
  const payload = JSON.stringify(config, null, 2);
  await fs.writeFile(filePath, `${payload}\n`, { mode: 0o600 });
  try {
    await fs.chmod(filePath, 0o600); // Double safeguard
  } catch {
    // Windows doesn't support chmod
  }
}
```

### Automatic Initialization

`ensureNodeHostConfig` implements an atomic "read-normalize-save" operation:

```typescript
export async function ensureNodeHostConfig(): Promise<NodeHostConfig> {
  const existing = await loadNodeHostConfig();   // Read (may be null)
  const normalized = normalizeConfig(existing);  // Normalize (generate missing fields)
  await saveNodeHostConfig(normalized);          // Save
  return normalized;
}
```

`normalizeConfig` ensures required fields exist—if `nodeId` is empty, it auto-generates a UUID.

***

## 27.3.5 CLI and Daemon

### Two CLI Suites

OpenClaw provides two sets of node-related CLI commands:

| CLI Command Group | Purpose                | Entry File                      |
| ----------------- | ---------------------- | ------------------------------- |
| `openclaw node`   | Node Host management   | `src/cli/node-cli/register.ts`  |
| `openclaw nodes`  | Remote node management | `src/cli/nodes-cli/register.ts` |

`openclaw node` manages the Node Host process on the local machine:

```bash
openclaw node run                  # Run in foreground
openclaw node install              # Install as system service
openclaw node uninstall            # Uninstall system service
openclaw node status               # View service status
openclaw node stop                 # Stop service
openclaw node restart              # Restart service
```

`openclaw nodes` remotely manages nodes via Gateway RPC:

```bash
openclaw nodes list                # List all nodes
openclaw nodes describe <nodeId>   # View node details
openclaw nodes invoke <nodeId> ... # Send command to node
openclaw nodes pair ...            # Pairing management
openclaw nodes canvas ...          # Canvas operations
openclaw nodes camera ...          # Camera operations
openclaw nodes screen ...          # Screen recording operations
openclaw nodes location ...        # Location operations
openclaw nodes notify ...          # System notifications
```

### Daemon Installation

`openclaw node install` installs Node Host as a background service of the operating system. The installation plan selects the appropriate service manager based on the current OS:

| Operating System | Service Manager | Service File                                    |
| ---------------- | --------------- | ----------------------------------------------- |
| macOS            | launchd         | `~/Library/LaunchAgents/ai.openclaw.node.plist` |
| Linux            | systemd         | `~/.config/systemd/user/openclaw-node.service`  |
| Windows          | schtasks        | `OpenClaw-Node` scheduled task                  |

Installation supports multiple options:

```bash
openclaw node install \
  --host 192.168.1.100 \       # Remote Gateway address
  --port 18789 \               # Gateway port
  --tls \                      # Enable TLS
  --tls-fingerprint <sha256> \ # Self-signed certificate fingerprint
  --node-id <id> \             # Specify node ID
  --display-name "My Server" \ # Display name
  --runtime bun \              # Use Bun runtime (default Node.js)
  --force                      # Force reinstall
```

***

## Section Summary

1. **Node Host is a long-lived WebSocket client**—establishes a WebSocket connection via `GatewayClient`, declares its capabilities and supported commands, then continuously listens for `node.invoke.request` events.
2. **Command dispatch follows switch-case routing**—`handleInvoke` dispatches based on command name to handlers like `system.run`, `system.which`, `browser.proxy`, etc.
3. **system.run has four layers of security protection**—macOS Exec Host priority → security level check → approval mechanism → allowlist evaluation, ensuring remote command execution doesn't become a security vulnerability.
4. **Environment variables are strictly sanitized**—blocks injection of dangerous variables like `NODE_OPTIONS`, `LD_PRELOAD`, `DYLD_*`.
5. **Output has dual truncation**—execution output limited to 200KB, event reporting output limited to 20KB, preventing large output from overwhelming the communication link.
6. **Configuration file permissions are strict**—`0o600` ensures only the current user can read and write, preventing sensitive information like tokens from leaking.
7. **Cross-platform daemon support**—macOS uses launchd, Linux uses systemd, Windows uses schtasks, with a unified CLI interface masking platform differences.

***

> ### 🔬 Going Deeper: 27.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: [**27.4 Source Deep Dive: Reverse RPC and the Wake Mechanism**](https://www.openclawbook.xyz/en/ch27-node-system/27.4-source-deep-dive-reverse-rpc-and-wake.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.**
