> 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.4-source-deep-dive-reverse-rpc-and-wake.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 27.4 Source Deep Dive: Reverse RPC and the Wake Mechanism

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

***

The node system is essentially **reverse RPC over a WebSocket**: the Gateway is the WS server, but the call direction is Gateway → node.

This section covers the four wrapping layers on the Gateway side and the realist patches for mobile OS lifecycles. The node-side runtime and exec security live in **Appendix F.5**.

## 27.4.1 The Reverse RPC Skeleton

`NodeRegistry.invoke()` (`src/gateway/node-registry.ts:107-155`):

```
Gateway pushes a node.invoke.request event to the node (requestId + JSON-serialized params)
        ↓
hangs a promise in pendingInvokes
        ↓
waits for the node to call the node.invoke.result method with the outcome
        ↓
default 30-second timeout; all pending calls reject immediately on node disconnect
```

That last rule matters — **it doesn't wait for the timeout**. A disconnected node can't possibly produce a result, so making the caller wait a full 30 seconds accomplishes nothing.

> **A general principle: when you already know a pending operation cannot complete, fail immediately rather than waiting out the timeout.** A timeout is the backstop for "I don't know what happened," not the handling for "I know it failed."

## 27.4.2 Four Wrapping Layers Around the `node.invoke` Handler

`src/gateway/server-methods/nodes.ts:776-1003`.

### Layer one: command allowlist

`resolveNodeCommandAllowlist` plus the node's own declaration form a **double filter** (`:897-914`).

Recall §11.5.3's principle: **a node's self-declared commands are only claims**; the server-side allowlist is authoritative.

**One explicit prohibition** (`:802-813`):

```
system.execApprovals.* is forbidden over the invoke channel
It must go through the dedicated exec.approvals.node.* methods
```

**What does that defend against?** An agent using `node.invoke` to change the approval configuration — which is a **meta-permission** (a permission that changes permissions).

Without the prohibition, the attack chain is: the model gets induced into calling `node.invoke("system.execApprovals.set", {allowlist: ["*"]})`, and thereafter every command is auto-approved.

> **Any operation that can change permissions themselves must not share a channel with ordinary operations.** That's a hard rule in permission system design.

### Layer two: exec approval binding

`system.run` parameters must pass through `sanitizeNodeInvokeParamsForForwarding` (`src/gateway/node-invoke-sanitize.ts:5-23`), and approval tickets are validated and bound by the `ExecApprovalManager`.

**Clients cannot manufacture their own "already approved" marker.** Approval state is held server-side, and any "I've been approved" field carried in the parameters is stripped.

### Layer three: three-stage APNs wake

When the target node is offline (phone locked, app killed by the OS), a three-stage wake sequence runs (`:815-895`, with full stage logging):

```
① Send an APNs background wake → poll for reconnection for 3 seconds
        ↓ still nothing
② Force one more push → wait 12 seconds
        ↓ still failing
③ Send a visible "nudge" notification asking the user to open the app
```

The logic behind the three stages:

| Stage                | Intrusiveness           | Success rate                 |
| -------------------- | ----------------------- | ---------------------------- |
| Background wake      | Invisible to the user   | Medium (the OS may throttle) |
| Forced push          | Invisible to the user   | Higher                       |
| Visible notification | **Interrupts the user** | Depends on the user          |

**Only after the first two fail does it interrupt the user.** Another instance of §44.5's "conversation experience as a first-class object" — technically you could pop the notification immediately at step one, but that would be annoying.

### Layer four: the foreground queue

This is the layer with the strongest "realism" flavor.

On iOS, commands like `canvas.*` / `camera.*` / `screen.*` / `talk.*` **can only run in the foreground**. A node in the background receiving such a request reports `NODE_BACKGROUND_UNAVAILABLE`.

The handling (`:50-93`):

```
The request enters a per-node isolated pending queue
   TTL 10 minutes
   64-entry cap per node
        ↓
When the node returns to the foreground it consumes them via node.pending.pull / ack
```

> **This is a patch for mobile OS lifecycles, but it was built as a mechanism rather than a hack.**
>
> It has a TTL (no unbounded accumulation), a cap (no memory blowout), and a pull/ack protocol (no double consumption). Compare the common approach — error out and tell the user to retry — and this design lets "take a screenshot on my phone" eventually succeed even while the phone is locked.

## 27.4.3 The Node Side at a Glance

The headless node started by `openclaw node run` centers on `runNodeHost` (`src/node-host/runner.ts:144-231`):

```ts
// src/node-host/runner.ts:180-201 (excerpt)
const client = new GatewayClient({
  url, instanceId: nodeId,
  mode: GATEWAY_CLIENT_MODES.NODE, role: "node", scopes: [],
  caps: ["system", ...(browserProxyEnabled ? ["browser"] : [])],
  commands: [ ...NODE_SYSTEM_RUN_COMMANDS, ...NODE_EXEC_APPROVALS_COMMANDS,
              ...(browserProxyEnabled ? [NODE_BROWSER_PROXY_COMMAND] : []) ],
  deviceIdentity: loadOrCreateDeviceIdentity(),
  tlsFingerprint: gateway.tlsFingerprint,
});
```

Note `scopes: []` — **a node needs no operator scopes at all**. It only responds to invokes; it never calls control-plane methods.

It listens for exactly one event (`node.invoke.request`), dispatched at `src/node-host/invoke.ts:417-556`:

| Command                        | Notes                                                                                                                           |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `system.run`                   | Execute                                                                                                                         |
| `system.run.prepare`           | **Compute the approval plan without executing** — the two-phase split lets the approval UI bind to a validated concrete command |
| `system.which`                 | Check whether a command exists                                                                                                  |
| `system.execApprovals.get/set` | Carries a `baseHash` optimistic lock against concurrent overwrites                                                              |
| `browser.proxy`                | Forwards to the local browser control service (profile allowlist + 10 MB return cap)                                            |

**Execution security is "a pure-function decision core plus multi-point re-verification"** — full analysis in Appendix F.5.2. The essentials:

* `exec-policy.ts` is a **134-line pure function with no IO**;
* Three `security` settings × three `ask` settings;
* **`sh -c` / `cmd.exe /c` and other shell wrappers always count as a miss** in allowlist mode;
* After policy approval come shell-wrapper fail-closed a second time, TOCTOU re-verification of cwd and file operands, and comparison of actual argv against the allowlist-matched argv (`invoke-system-run.ts:312-402`);
* Output is hard-capped at 200 KB, with events carrying only the trailing 20 KB.

## 27.4.4 A Known Durability Gap

Listed in §45.2; stated explicitly here:

**`NodeRegistry`'s `pendingInvokes`, the iOS pending queue, and presence all live in memory and are lost when the Gateway restarts.**

Idempotency keys give clients room to retry, but **there is no persistent at-least-once delivery guarantee**.

The practical impact: the agent asks your phone to take a photo, the request sits in the pending queue (the phone is backgrounded), and the Gateway restarts — the request vanishes with nobody informed.

> This is the same trade-off as §13.6.7's "everything is in process memory": **zero dependencies and zero operations vs. loss on crash.** Reasonable for a single-machine personal assistant, but you should know where the edge is.

***

## Section Summary

1. **The reverse RPC skeleton**: the Gateway pushes `node.invoke.request` → hangs a pending promise → awaits `node.invoke.result`, with a 30-second timeout; **pending calls reject immediately on disconnect rather than waiting it out** — when you know it failed, don't make the caller wait.
2. **Layer one, the command allowlist**: self-declarations are only claims; **`system.execApprovals.*` is explicitly barred from the invoke channel** — any operation that can change permissions themselves must not share a channel with ordinary operations.
3. **Layer two, approval binding**: clients can't manufacture an "already approved" marker; approval state is held server-side.
4. **Layer three, three-stage APNs wake**: background wake (3s) → forced push (12s) → visible notification; **the user is only interrupted after the first two fail**.
5. **Layer four, the foreground queue**: iOS foreground-only commands enter a per-node isolated queue (10-minute TTL, 64-entry cap) consumed via `pull/ack` on return — **a mobile-lifecycle patch built as a mechanism, not a hack**.
6. **The node side declares `scopes: []`** — it only responds to invokes and never calls control-plane methods; `system.run.prepare`'s two-phase split binds approval to a validated concrete command; exec security is detailed in Appendix F.5.2.
7. **A known gap**: pendingInvokes / pending queue / presence all live in memory, **lost on Gateway restart**, with no persistent at-least-once delivery guarantee.
