> 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/appendices/appendix-f-daemon-and-node-host-deep-dive.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# Appendix F: Daemon and Device Node Deep Dive

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

***

This appendix goes deep on two modules the main text only surveys: `src/daemon/` (cross-platform service installation, 4,377 lines) and `src/node-host/` (device node runtime, 2,966 lines).

Two reasons they get their own appendix: **cross-platform daemon installation is the densest block of platform-trap knowledge in the book** — nearly every comment is the fossil of an incident — and the node-host exec security design guards the sharpest attack surface in the system, so its defensive density deserves separate treatment.

Read alongside: Chapter 27 (node system), Chapter 37 (deployment), §45.2 (risk list).

## F.1 Two Long-Running Processes, One Installation Abstraction

OpenClaw has two processes installable as system services:

| Process       | Command                               | Role                                                                                                                |
| ------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Gateway**   | `openclaw gateway --port N`           | The hub. Runs the WS server, agents, channel connections                                                            |
| **Node Host** | `openclaw node run --host H --port N` | A device node. Connects **as a WS client** back to the Gateway, lending local shell/browser capability to the agent |

Note the direction: Gateway is the server, Node Host is the client. But both need "start at boot, restart on crash, log to disk," so both reuse the same `src/daemon` abstraction.

`src/daemon/service.ts:69-106` selects an implementation from a registry by `process.platform`:

| Platform | Mechanism             | Service label         |
| -------- | --------------------- | --------------------- |
| macOS    | launchd (LaunchAgent) | `ai.openclaw.gateway` |
| Linux    | systemd user unit     | `openclaw-gateway`    |
| Windows  | Scheduled Task        | `OpenClaw Gateway`    |

Unsupported platforms throw immediately — no silent degradation.

The three implementations are isomorphic behind a uniform interface: `install` / `uninstall` / `stop` / `restart` / `isLoaded` / `readCommand` / `readRuntime`.

**Multi-instance isolation**: the `OPENCLAW_PROFILE` environment variable drives a coordinated naming scheme — service label, systemd unit name, Windows task name, and state directory (`~/.openclaw-<profile>`) all pick up the profile suffix. This is the basis for the "profile-isolated rescue instance" mentioned in §45.2.

There's also a stretch of easily-missed code: **legacy brand service cleanup**. Services installed in the Clawdbot / Moltbot era are recognized and removed so upgrades don't leave orphaned processes. Code that takes care of legacy users is a maturity marker (§43.1).

## F.2 Per-Platform Quirk Patches

This is the most valuable part of the appendix. Behind a uniform interface, each platform implementation buries targeted patches for its own traps — **and every one carries an explanatory comment**.

### macOS: `launchd.ts` + `launchd-plist.ts`

| Patch                                                                | Reason                                                                                                                                                              |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ThrottleInterval=1`                                                 | launchd throttles *any* rapid restart — **including the one you deliberately issued from the CLI**. Set to 1 second, or a forced reinstall stalls for a full minute |
| `Umask=63`                                                           | That's `0o077` in decimal — **plists only accept decimal**. Effect: service artifacts readable only by the owner                                                    |
| Install sequence `bootout → unload → enable → bootstrap → kickstart` | The comment explains the key part: launchd persists "disabled" state **even after bootout and plist deletion**, so a separate `enable` step must clear it first     |
| Structured remediation guidance for SSH/headless                     | The `gui/$UID` domain is unavailable without a graphical session; give explicit "log into a desktop session and re-run" guidance instead of a raw error             |
| Uninstall renames the plist into `~/.Trash` rather than deleting     | Accidental uninstalls are recoverable                                                                                                                               |
| restart polls for the old PID to actually exit (10s / 200ms)         | launchd's stop is asynchronous; not waiting collides with port-in-use                                                                                               |

That `enable` comment is the one to remember: **"deleted the config file" does not mean "cleared the system state."** launchd stores the disabled flag elsewhere, so deleting only the plist yields a service that installs but won't start — an extremely hard failure to diagnose.

### Linux: the `systemd.ts` family

| Patch                                                                             | Reason                                                                                                                                                     |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| User unit written to `~/.config/systemd/user/`                                    | No root required                                                                                                                                           |
| `Restart=always`                                                                  | Auto-restart on crash                                                                                                                                      |
| `KillMode=control-group`                                                          | Comment: prevents orphaned ACP / runtime worker processes surviving a restart                                                                              |
| Environment variables validated for CR/LF before writing (`systemd-unit.ts:6-10`) | **Prevents unit-file injection** — a newline in an env var becomes a new unit directive                                                                    |
| **Dual-scope fallback** (`systemd.ts:387-417`)                                    | Under sudo, prefer `--machine user@ --user`; if direct `--user` fails with errors matching "failed to connect to bus" and similar, fall back automatically |
| `loginctl enable-linger` integration                                              | Keeps the service running after the user logs out                                                                                                          |
| Full `EnvironmentFile=` expansion when reading a unit                             | Supports the `-` prefix (optional file), the `%h` specifier, and relative paths; tags each env key with inline-vs-file provenance                          |

The unit-file injection guard deserves its own note: it's a real injection surface. If an environment variable's value contains `\nExecStart=/bin/evil`, writing it into the unit file creates a new directive. Validating newlines is the only reliable defense.

**This file is also where §45.2's verified defect lives** (`:484` / `:528` ignoring the unit-name override) — see F.4.

### Windows: `schtasks.ts`

| Patch                                                                              | Reason                                                                                                                |
| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Generate a `.cmd` wrapper first, then register an ONLOGON task                     | schtasks has limited command-line length and escaping capability                                                      |
| **Two different quoting strategies** for `/TR` and the `.cmd` contents             | The comment explains: `/TR` is parsed by schtasks, `.cmd` lines by cmd.exe — **different rules, not interchangeable** |
| Fall back to registering without `/RU user /NP /IT` when that combination fails    | Some account types don't support the set                                                                              |
| Running-state detection uses the numeric code `0x41301` rather than localized text | **Avoids output differences on localized Windows** — a Chinese system prints 正在运行, an English one prints "Running"    |

That last one is the general cross-platform lesson: **never parse output text that might be localized.**

### Rebuilding the service environment: `service-env.ts`

Neither launchd nor systemd **inherits the login shell environment**. Everything you configured in `.zshrc` — PATH, proxies, Node version managers — is absent inside the service.

So it gets rebuilt by hand:

| Variable              | Handling                                                                                                                                                 |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HOME` / `TMPDIR`     | Set explicitly                                                                                                                                           |
| Proxy variables       | Captured from the current environment and written in                                                                                                     |
| `NODE_EXTRA_CA_CERTS` | **macOS special case**, defaulting to `/etc/ssl/cert.pem` — under launchd, Node's fetch can't find the system CA store, which breaks every HTTPS request |
| `PATH`                | User directories first, and **aware of pnpm / fnm / nvm / volta version-manager paths**                                                                  |

Windows goes the other way: **deliberately does not freeze PATH into the `.cmd`**, letting it inherit the task's runtime PATH. The rationale is to avoid welding an install-time snapshot in place — if the user later installs a newer Node, the service shouldn't still point at the old one.

**One elegant decision** (`program-args.ts:24-37`): **deliberately preserve the symlink path rather than resolving realpath.**

pnpm's layout is `node_modules/openclaw -> .pnpm/openclaw@X.Y.Z/...`. That symlink automatically re-points as versions update. If you resolve realpath at install time and hard-code `.pnpm/openclaw@2026.3.9/...`, **the service points at a nonexistent directory after the next upgrade.**

Keep the symlink and upgrades take effect automatically. It's the kind of "looks non-canonical but is actually right" decision, and the comment explains why.

## F.3 The Node Service Is an Environment-Variable Decorator over the Gateway Service

`node-service.ts` is **66 lines** total.

It isn't a fourth platform implementation — it's a **decorator** over `resolveGatewayService()`, injecting six override environment variables and reusing all three platforms' installation code:

```
OPENCLAW_LAUNCHD_LABEL        → macOS service label
OPENCLAW_SYSTEMD_UNIT         → Linux unit name
OPENCLAW_WINDOWS_TASK_NAME    → Windows task name
(plus log prefix and others)
```

These variables are written into two places: the **install arguments** (for locating the service file) and the **service environment** (so the process can introspect what it is).

Extreme DRY. **The cost is that every override must be honored by every code path in all three platform implementations** — which is exactly the cause of the defect below.

### Another highlight: the service file is both write target and source of truth

All three platforms implement `readCommand`:

| Platform | Reverse parsing                  |
| -------- | -------------------------------- |
| macOS    | Regex-parse the plist            |
| Linux    | Line-parse the unit file         |
| Windows  | Reverse-parse the `.cmd` wrapper |

So `service-audit.ts` can **diagnose by reading the service file directly**, with no additional state record:

* a token inlined into the unit file (a security problem)
* the runtime pointing at a stale node path (the classic post-upgrade failure)

This is pattern #9 from §45.1: *the service file as the source of configuration truth*. It eliminates the entire class of bug where "recorded state" disagrees with "actual state."

## F.4 Verified Defect: systemd install/uninstall Ignores the Unit-Name Override

**This book has independently verified this issue at the source level.**

**What's correct**: `resolveSystemdServiceName(env)` (`systemd.ts:40-46`) correctly handles the `OPENCLAW_SYSTEMD_UNIT` override, and `resolveSystemdUnitPath` uses it — so **the unit file is written to the right place** (`openclaw-node.service`).

**What's wrong**: `installSystemdService` at enable/restart time (`:484-485`) and `uninstallSystemdService` at disable time (`:528-529`) both call `resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE)` directly, **bypassing the override**:

```ts
// systemd.ts:484 (one copy each in install and uninstall)
const serviceName = resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE);
const unitName = `${serviceName}.service`;
// ...
const enable  = await execSystemctlUser(env, ["enable",  unitName]);
const restart = await execSystemctlUser(env, ["restart", unitName]);
```

**Consequences**:

| Command                   | Expected                                 | Actual                                                                                                                          |
| ------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `openclaw node install`   | Write and enable `openclaw-node.service` | Unit file written correctly, but enable/restart target `openclaw-gateway.service` — **the node service is never enabled**       |
| `openclaw node uninstall` | Disable and remove the node service      | Runs `disable --now openclaw-gateway.service` — **uninstalling the node stops the gateway** — then removes the node's unit file |

**Confirmed as oversight, not intent**: three other sites in the same file — `:549` (service action), `:593` (isEnabled), `:617` (readRuntime) — **all use `resolveSystemdServiceName(env)` correctly**. macOS (`launchd.ts:405` uses `resolveLaunchAgentLabel` throughout) and Windows (`schtasks.ts:242` uses `resolveTaskName`) are unaffected.

**Why tests missed it**: the existing test (`systemd.test.ts:384-404`) covers the override only for unit **path** resolution, not for the **unitName** inside install/uninstall.

**Fix direction**: switch both sites to `resolveSystemdServiceName(env)` and add a regression test asserting the enable/restart/disable target names under an override.

## F.5 node-host: Device Node Runtime and Security Model

### F.5.1 Connection and capability declaration (`runner.ts:144-231`)

Node identity lives in `~/.openclaw/node.json`:

```
version / nodeId / token / displayName / gateway
```

Written **atomically at 0o600**; `nodeId` is generated with `crypto.randomUUID()` when missing.

Startup flow:

```
1. Read config
2. Build ws(s)://host:port (default 127.0.0.1:18789)
3. Connect with role: "node", declaring:
     caps:     ["system", ...browser]
     commands: system.run / system.run.prepare / system.which
               system.execApprovals.get / .set
               (optional) browser.proxy
4. Listen for exactly one event: node.invoke.request → dispatch
5. await new Promise(() => {})   ← never exits
```

That last line is worth explaining: the process deliberately parks, and **reconnection is handled entirely by GatewayClient**. The node doesn't manage connection lifecycle, which keeps reconnect logic in one implementation.

Two implementation details:

* **Local mode clones the config and strips `gateway.remote.token/password`.** The comment states the reason: inheriting remote credentials suppresses device-token fallback and produces local token mismatches. (This corroborates the documentation-level credential precedence rules in Appendix G.)
* **The executable manifest for skills is fetched via reverse RPC `skills.bins`**, cached with a 90-second TTL.

On the Gateway side (`node-registry.ts`), caps/commands are stored in the `NodeSession`; `invoke()` generates a requestId, registers a pending promise, defaults to a 30-second timeout, and **rejects immediately when the node disconnects** (rather than waiting out the timeout).

### F.5.2 exec security: deny by default + multi-point re-verification

This is the sharpest attack surface in the system — a device node lending shell capability to a remote Gateway. Defensive density matches.

**Policy core: `exec-policy.ts`, 134 lines of pure function**

No IO, returns a discriminated union, backed by 143 lines of tests. Two dimensions, three settings each:

| `security`  | Meaning                                |
| ----------- | -------------------------------------- |
| `deny`      | Reject everything                      |
| `allowlist` | **Default.** Only allowlisted commands |
| `full`      | Allow everything                       |

| `ask`     | Meaning                                  |
| --------- | ---------------------------------------- |
| `off`     | Never prompt                             |
| `on-miss` | **Default.** Prompt when not allowlisted |
| `always`  | Prompt every time                        |

**Key rule**: in allowlist mode, shell wrappers like `sh -c` / `bash -c` / `zsh -c` / `cmd.exe /c` are **always treated as a miss** and forcibly downgraded.

The reasoning is direct: otherwise an attacker only needs `sh` on the allowlist to smuggle in anything via `sh -c "arbitrary command"`. **An allowlist validates a command name, and shell wrappers make the command name meaningless.**

**Four more gates on the execution path (`invoke-system-run.ts`)**

After policy approval, execution adds four layers of defense in depth against TOCTOU and runtime drift:

| # | Gate                                                                                      | Protects against                                                                            |
| - | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| 1 | Shell-wrapper fail-closed, again                                                          | Original comment: `Fail closed if policy/runtime drift re-allows unapproved shell wrappers` |
| 2 | Snapshot cwd and script operands at approval; re-verify before execution; reject on drift | State changing between approval and execution                                               |
| 3 | execution-plan-miss: reject if actual argv ≠ allowlist-matched argv                       | Argument substitution                                                                       |
| 4 | Two-layer env sanitization (including `blockPathOverrides: true`)                         | Hijacking command resolution via PATH override                                              |

**Supporting mechanisms are equally restrained**:

* `system.run.prepare` and `system.run` are **split into two RPCs** — so the approval UI binds to an already-validated command rather than raw user input;
* `execApprovals.set` requires a **`baseHash` optimistic lock**, preventing concurrent clients from clobbering approval config;
* `allow-always` writes to the allowlist **only when static analysis passes**;
* Output governance: 200 KB cap (truncating as it streams), events carry only the trailing 20 KB;
* Windows probes the code page via `chcp` and decodes as 936/950/932 etc. to avoid mojibake.

**`browser.proxy` has its own separate boundary**: a `nodeHost.browserProxy.enabled` master switch plus an `allowProfiles` allowlist, a 10 MB per-file cap, and a 20-second timeout whose error carries the result of a 0.75-second status probe.

## F.6 Appendix Summary

These two modules are the engineering foundation of OpenClaw's "runs on your devices" vision, and they display three characteristics:

1. **Extremely high knowledge density in cross-platform service management.** launchd's persisted disabled state, systemd's dual-scope bus fallback, schtasks' localized-text trap — most of these platform quirks have no official documentation, and every comment is an incident record. **This code can serve directly as a reference implementation for cross-platform daemon installation.**
2. **The node exec security design clearly exceeds the daemon's engineering complexity.** A pure-function policy core + four runtime re-verifications + two-phase approval RPC + optimistic locking — a defensive density matched to the judgment that this is the system's sharpest attack surface, and consistent with `SECURITY.md`'s position that trust boundaries must be executable (§44.4).
3. **F.4's verified defect illustrates the hidden cost of extreme DRY.** "66 lines of decorator reusing three platform implementations" is elegant, but the override contract has **no type-system enforcement** — it depends on every call site voluntarily honoring it. One omission produces a "uninstalling the node stops the gateway" class of behavioral error, and the existing tests happened not to cover it.

The third point is worth keeping as a review heuristic: **when you see "parameterize with environment variables or string keys to reuse a large block of code," check the contract at every call site.** The type system can't help at reuse points of this shape.
