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

# 27.2 Node Registration and Discovery

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

***

The previous section introduced node concepts and command classification. This section dives into the Gateway-side implementation: how nodes register with the Gateway, how commands are routed and invoked, how events flow between nodes and sessions, and how the subscription system implements real-time message delivery.

***

## 27.2.1 Node Registry (`src/gateway/node-registry.ts`)

### Bidirectional Index Structure

`NodeRegistry` is the core class in the Gateway that manages all online nodes. It uses two Maps to implement **bidirectional indexing**:

```typescript
// src/gateway/node-registry.ts

export class NodeRegistry {
  private nodesById   = new Map<string, NodeSession>();  // nodeId → NodeSession
  private nodesByConn = new Map<string, string>();        // connId → nodeId
  private pendingInvokes = new Map<string, PendingInvoke>(); // requestId → pending invocation
  // ...
}
```

* `nodesById`: Look up a node session by node ID—used when an Agent initiates a `node.invoke`.
* `nodesByConn`: Look up a node ID by WebSocket connection ID—used for reverse lookup when a connection closes.

> **Sidebar: Bidirectional Index**
>
> In database terminology, indexes accelerate queries. A unidirectional index supports lookup in only one direction, e.g., `Map<K, V>` can only look up values by key. A bidirectional index maintains mappings in both directions, making lookups in both directions O(1). The tradeoff is that writes must update both Maps simultaneously and maintain consistency. This is a classic **space-for-time** strategy.

### Registration and Deregistration

After a node connects to the Gateway via WebSocket, the `register` method extracts its information and stores it in the registry:

```typescript
// src/gateway/node-registry.ts

register(client: GatewayWsClient, opts: { remoteIp?: string }) {
  const connect = client.connect;
  const nodeId = connect.device?.id ?? connect.client.id;
  const caps = Array.isArray(connect.caps) ? connect.caps : [];
  const commands = Array.isArray(connect.commands) ? connect.commands : [];
  const permissions = typeof connect.permissions === "object"
    ? connect.permissions : undefined;
  const pathEnv = typeof connect.pathEnv === "string"
    ? connect.pathEnv : undefined;

  const session: NodeSession = {
    nodeId,
    connId: client.connId,
    client,
    displayName: connect.client.displayName,
    platform: connect.client.platform,
    // ... more fields
    caps,
    commands,
    permissions,
    pathEnv,
    connectedAtMs: Date.now(),
  };

  this.nodesById.set(nodeId, session);
  this.nodesByConn.set(client.connId, nodeId);
  return session;
}
```

The `nodeId` selection strategy is noteworthy: it prefers `device.id` (persistent device identifier), falling back to `client.id` if unavailable. This ensures that when the same device reconnects, its `nodeId` remains unchanged.

Deregistration requires additional handling of **pending invocations**:

```typescript
// src/gateway/node-registry.ts

unregister(connId: string): string | null {
  const nodeId = this.nodesByConn.get(connId);
  if (!nodeId) return null;

  this.nodesByConn.delete(connId);
  this.nodesById.delete(nodeId);

  // Clean up all pending invocations on this node
  for (const [id, pending] of this.pendingInvokes.entries()) {
    if (pending.nodeId !== nodeId) continue;
    clearTimeout(pending.timer);
    pending.reject(new Error(`node disconnected (${pending.command})`));
    this.pendingInvokes.delete(id);
  }
  return nodeId;
}
```

When a node disconnects, all Promises waiting for that node's results are `reject`ed, notifying callers that the node is offline. This prevents callers from waiting indefinitely for a result that will never arrive.

### Command Invocation (invoke)

The `invoke` method is the core of the Node System—it sends a command to the target node and returns a Promise waiting for the result:

```typescript
// src/gateway/node-registry.ts

async invoke(params: {
  nodeId: string;
  command: string;
  params?: unknown;
  timeoutMs?: number;
  idempotencyKey?: string;
}): Promise<NodeInvokeResult> {
  const node = this.nodesById.get(params.nodeId);
  if (!node) {
    return { ok: false, error: { code: "NOT_CONNECTED", message: "node not connected" } };
  }

  const requestId = randomUUID();
  const payload = {
    id: requestId,
    nodeId: params.nodeId,
    command: params.command,
    paramsJSON: params.params !== undefined ? JSON.stringify(params.params) : null,
    timeoutMs: params.timeoutMs,
    idempotencyKey: params.idempotencyKey,
  };

  // Send to node via WebSocket
  const ok = this.sendEventToSession(node, "node.invoke.request", payload);
  if (!ok) {
    return { ok: false, error: { code: "UNAVAILABLE", message: "failed to send" } };
  }

  // Wait for result (with timeout)
  const timeoutMs = typeof params.timeoutMs === "number" ? params.timeoutMs : 30_000;
  return await new Promise<NodeInvokeResult>((resolve, reject) => {
    const timer = setTimeout(() => {
      this.pendingInvokes.delete(requestId);
      resolve({ ok: false, error: { code: "TIMEOUT", message: "node invoke timed out" } });
    }, timeoutMs);
    this.pendingInvokes.set(requestId, {
      nodeId: params.nodeId,
      command: params.command,
      resolve, reject, timer,
    });
  });
}
```

This code demonstrates a classic **request-response matching** pattern:

1. Generate a unique `requestId` (UUID).
2. Send the request to the node, storing `{ resolve, reject, timer }` in `pendingInvokes`.
3. After the node completes execution, `handleInvokeResult` finds the corresponding `resolve` via `requestId` and completes the Promise.
4. On timeout, the `timer` automatically `resolve`s a timeout error (note: not `reject`—this is intentional design, making timeout a "normal" failure result).

> **Sidebar: Idempotency Key**
>
> The `idempotencyKey` parameter ensures **idempotency**—the same request executed multiple times produces the same effect. In distributed systems, unreliable networks may cause requests to be sent multiple times. The receiver checks the idempotency key to determine if it has already processed that request; if so, it returns the previous result directly. This is especially important in scenarios like financial transactions.

### Result Matching

When a node returns a result, the `handleInvokeResult` method matches it with the pending request:

```typescript
// src/gateway/node-registry.ts

handleInvokeResult(params: {
  id: string;       // requestId
  nodeId: string;
  ok: boolean;
  payload?: unknown;
  payloadJSON?: string | null;
  error?: { code?: string; message?: string } | null;
}): boolean {
  const pending = this.pendingInvokes.get(params.id);
  if (!pending) return false;              // May have timed out
  if (pending.nodeId !== params.nodeId) return false; // Security check

  clearTimeout(pending.timer);
  this.pendingInvokes.delete(params.id);
  pending.resolve({
    ok: params.ok,
    payload: params.payload,
    payloadJSON: params.payloadJSON ?? null,
    error: params.error ?? null,
  });
  return true;
}
```

If `pending` doesn't exist (a late result arriving after timeout), the method returns `false`, and the Gateway marks it as `ignored`—a manifestation of **eventual consistency**.

***

## 27.2.2 Node Event System (`src/gateway/server-node-events.ts`)

### Events vs. Command Invocation

The Node System has two communication modes:

| Mode                            | Direction                | Semantics            | Waits for Response |
| ------------------------------- | ------------------------ | -------------------- | ------------------ |
| **Command Invocation** (invoke) | Gateway → Node → Gateway | Request-response     | Yes (Promise)      |
| **Event** (event)               | Node → Gateway           | One-way notification | No                 |

Events are sent proactively by nodes to the Gateway to report state changes or transmit data. `handleNodeEvent` is the event dispatcher:

```typescript
// src/gateway/server-node-events.ts

export const handleNodeEvent = async (
  ctx: NodeEventContext,
  nodeId: string,
  evt: NodeEvent,
) => {
  switch (evt.event) {
    case "voice.transcript":   // Voice-to-text result
      // → Create session, trigger Agent processing
    case "agent.request":      // Agent deep link request
      // → Parse parameters, execute Agent command
    case "chat.subscribe":     // Subscribe to session messages
      // → Register node to subscription system
    case "chat.unsubscribe":   // Unsubscribe
      // → Remove from subscription system
    case "exec.started":       // Command execution started
    case "exec.finished":      // Command execution completed
    case "exec.denied":        // Command execution denied
      // → Inject system event, trigger heartbeat
  }
};
```

### Voice Transcript Event (voice.transcript)

When an iOS/Android node completes voice transcription, it sends the text to the Gateway:

```typescript
// src/gateway/server-node-events.ts (simplified)

case "voice.transcript": {
  const payload = JSON.parse(evt.payloadJSON);
  const text = payload.text?.trim();
  if (!text || text.length > 20_000) return;

  // Parse target session
  const sessionKey = payload.sessionKey || mainKey;
  const { storePath, entry, canonicalKey } = loadSessionEntry(sessionKey);
  const sessionId = entry?.sessionId ?? randomUUID();

  // Register chatRun so UI can refresh
  ctx.addChatRun(sessionId, {
    sessionKey,
    clientRunId: `voice-${randomUUID()}`,
  });

  // Trigger Agent processing
  void agentCommand({
    message: text,
    sessionId,
    sessionKey,
    thinking: "low",
    deliver: false,
    messageChannel: "node",
  }, defaultRuntime, ctx.deps);
  return;
}
```

This code demonstrates a complete **voice interaction loop**: user speaks on phone → phone completes speech recognition → recognition result sent to Gateway via WebSocket event → Gateway creates Agent session to process text → Agent reply pushed back to phone via subscription system.

### Agent Deep Link Request (agent.request)

`agent.request` is a more general-purpose event that allows nodes to trigger Agent execution via **deep link**:

```typescript
// src/gateway/server-node-events.ts (simplified)

case "agent.request": {
  const link = JSON.parse(evt.payloadJSON);
  const message = link.message?.trim();
  if (!message || message.length > 20_000) return;

  const channel = normalizeChannelId(link.channel) ?? undefined;
  const to = link.to?.trim() || undefined;
  const deliver = Boolean(link.deliver) && Boolean(channel);
  const sessionKey = link.sessionKey || `node-${nodeId}`;

  void agentCommand({
    message,
    sessionId,
    sessionKey,
    thinking: link.thinking,
    deliver,
    to,
    channel,
    timeout: link.timeoutSeconds?.toString(),
    messageChannel: "node",
  }, defaultRuntime, ctx.deps);
  return;
}
```

Unlike `voice.transcript`, `agent.request` supports more parameters: specifying target channel (`channel`), recipient (`to`), whether to deliver (`deliver`), etc. This allows nodes to trigger complex Agent workflows, such as "recognize image content and send via Telegram to a specific contact".

### Execution Events (exec.\*)

Node Host sends three types of events when executing system commands:

```typescript
// src/gateway/server-node-events.ts (simplified)

case "exec.started":
case "exec.finished":
case "exec.denied": {
  const sessionKey = payload.sessionKey || `node-${nodeId}`;
  const runId = payload.runId;
  const command = payload.command;

  let text = "";
  if (evt.event === "exec.started") {
    text = `Exec started (node=${nodeId}): ${command}`;
  } else if (evt.event === "exec.finished") {
    const exitLabel = payload.timedOut ? "timeout" : `code ${payload.exitCode}`;
    text = `Exec finished (node=${nodeId}, ${exitLabel})`;
    if (payload.output) text += `\n${payload.output}`;
  } else {
    text = `Exec denied (node=${nodeId}, ${payload.reason}): ${command}`;
  }

  enqueueSystemEvent(text, { sessionKey, contextKey: `exec:${runId}` });
  requestHeartbeatNow({ reason: "exec-event" });
  return;
}
```

These events are transformed into **system events** injected into the session context, allowing the Agent to perceive the progress and results of remote command execution. `requestHeartbeatNow` triggers a heartbeat to ensure the Agent processes these events promptly.

***

## 27.2.3 Node Subscriptions (`src/gateway/server-node-subscriptions.ts`)

### Why Subscriptions Are Needed

Consider this scenario: a user converses on an iPhone via the OpenClaw iOS App. The Agent's reply needs to be pushed to this iPhone in real-time. But how does the Gateway know "this reply should be pushed to which node"?

The answer is the **subscription mechanism**. A node tells the Gateway via a `chat.subscribe` event: "I'm interested in messages from sessionKey=xxx; please push related messages to me."

### Bidirectional Mapping Structure

`createNodeSubscriptionManager` uses two Maps to maintain a **many-to-many** subscription relationship between nodes and sessions:

```typescript
// src/gateway/server-node-subscriptions.ts

export function createNodeSubscriptionManager(): NodeSubscriptionManager {
  // nodeId → Set<sessionKey>  ——one node can subscribe to multiple sessions
  const nodeSubscriptions = new Map<string, Set<string>>();
  // sessionKey → Set<nodeId>  ——one session can be subscribed to by multiple nodes
  const sessionSubscribers = new Map<string, Set<string>>();
  // ...
}
```

> **Sidebar: Many-to-Many Relationship**
>
> In relational databases, many-to-many relationships are typically implemented via a junction table. Here, two Maps implement bidirectional indexing, which is essentially the same idea implemented in memory. `nodeSubscriptions` is like the "node → session" direction index, and `sessionSubscribers` is like the "session → node" direction index. Both Maps must be kept in sync during updates.

### Subscribe and Unsubscribe

```typescript
// src/gateway/server-node-subscriptions.ts

const subscribe = (nodeId: string, sessionKey: string) => {
  // Update nodeSubscriptions: nodeId → sessionKeys
  let nodeSet = nodeSubscriptions.get(nodeId);
  if (!nodeSet) {
    nodeSet = new Set<string>();
    nodeSubscriptions.set(nodeId, nodeSet);
  }
  if (nodeSet.has(sessionKey)) return; // Idempotent—duplicate subscriptions have no side effects
  nodeSet.add(sessionKey);

  // Update sessionSubscribers: sessionKey → nodeIds
  let sessionSet = sessionSubscribers.get(sessionKey);
  if (!sessionSet) {
    sessionSet = new Set<string>();
    sessionSubscribers.set(sessionKey, sessionSet);
  }
  sessionSet.add(nodeId);
};
```

On unsubscribe, both Maps are cleaned up synchronously, and entries are deleted when Sets become empty to prevent memory leaks:

```typescript
const unsubscribe = (nodeId: string, sessionKey: string) => {
  const nodeSet = nodeSubscriptions.get(nodeId);
  nodeSet?.delete(sessionKey);
  if (nodeSet?.size === 0) nodeSubscriptions.delete(nodeId);

  const sessionSet = sessionSubscribers.get(sessionKey);
  sessionSet?.delete(nodeId);
  if (sessionSet?.size === 0) sessionSubscribers.delete(sessionKey);
};
```

When a node disconnects, `unsubscribeAll` removes all its subscriptions at once:

```typescript
const unsubscribeAll = (nodeId: string) => {
  const nodeSet = nodeSubscriptions.get(nodeId);
  if (!nodeSet) return;
  for (const sessionKey of nodeSet) {
    const sessionSet = sessionSubscribers.get(sessionKey);
    sessionSet?.delete(nodeId);
    if (sessionSet?.size === 0) sessionSubscribers.delete(sessionKey);
  }
  nodeSubscriptions.delete(nodeId);
};
```

### Message Distribution

The subscription manager provides three distribution methods:

```typescript
// 1. Send to all nodes subscribed to a specific session
sendToSession(sessionKey, event, payload, sendEvent) {
  const subs = sessionSubscribers.get(sessionKey);
  if (!subs) return;
  const payloadJSON = JSON.stringify(payload);
  for (const nodeId of subs) {
    sendEvent({ nodeId, event, payloadJSON });
  }
}

// 2. Send to all nodes with any subscription (regardless of which session)
sendToAllSubscribed(event, payload, sendEvent) {
  const payloadJSON = JSON.stringify(payload);
  for (const nodeId of nodeSubscriptions.keys()) {
    sendEvent({ nodeId, event, payloadJSON });
  }
}

// 3. Send to all online nodes (regardless of subscription status)
sendToAllConnected(event, payload, listConnected, sendEvent) {
  const payloadJSON = JSON.stringify(payload);
  for (const node of listConnected()) {
    sendEvent({ nodeId: node.nodeId, event, payloadJSON });
  }
}
```

The `sendEvent` parameter is an injected callback function; the actual implementation sends messages via `NodeRegistry.sendEvent` to the WebSocket. This **dependency injection** design makes the subscription manager completely independent of WebSocket implementation details, facilitating isolated testing.

***

## 27.2.4 Gateway Method Handling (`src/gateway/server-methods/nodes.ts`)

### Method Overview

Node-related Gateway RPC methods are defined in `server-methods/nodes.ts`:

| Method               | Description                      |
| -------------------- | -------------------------------- |
| `node.pair.request`  | Node initiates pairing request   |
| `node.pair.list`     | List pairing requests            |
| `node.pair.approve`  | Approve pairing                  |
| `node.pair.reject`   | Reject pairing                   |
| `node.pair.verify`   | Verify node token                |
| `node.rename`        | Rename node                      |
| `node.list`          | List all nodes (paired + online) |
| `node.describe`      | View single node details         |
| `node.invoke`        | Send command to node             |
| `node.invoke.result` | Node returns command result      |
| `node.event`         | Node reports event               |

### Complete Flow of node.invoke

`node.invoke` is the most critical method—Agents use it to send commands to nodes:

```typescript
// src/gateway/server-methods/nodes.ts (simplified)

"node.invoke": async ({ params, respond, context }) => {
  const { nodeId, command } = params;

  // 1. Find node
  const nodeSession = context.nodeRegistry.get(nodeId);
  if (!nodeSession) {
    respond(false, undefined, { code: "NOT_CONNECTED" });
    return;
  }

  // 2. Permission check
  const cfg = loadConfig();
  const allowlist = resolveNodeCommandAllowlist(cfg, nodeSession);
  const allowed = isNodeCommandAllowed({
    command,
    declaredCommands: nodeSession.commands,
    allowlist,
  });
  if (!allowed.ok) {
    respond(false, undefined, { reason: allowed.reason });
    return;
  }

  // 3. Invoke node (via NodeRegistry.invoke)
  const res = await context.nodeRegistry.invoke({
    nodeId,
    command,
    params: params.params,
    timeoutMs: params.timeoutMs,
    idempotencyKey: params.idempotencyKey,
  });

  // 4. Return result
  if (!res.ok) {
    respond(false, undefined, { message: res.error?.message });
    return;
  }
  respond(true, { ok: true, nodeId, command, payload: res.payload }, undefined);
};
```

### Security Validation of node.invoke.result

When a node returns a result, the Gateway checks the caller's identity:

```typescript
"node.invoke.result": async ({ params, respond, context, client }) => {
  // Verify: the node returning the result must be the node that was invoked
  const callerNodeId = client?.connect?.device?.id ?? client?.connect?.client?.id;
  if (callerNodeId && callerNodeId !== params.nodeId) {
    respond(false, undefined, { message: "nodeId mismatch" });
    return;
  }

  const ok = context.nodeRegistry.handleInvokeResult({
    id: params.id,
    nodeId: params.nodeId,
    ok: params.ok,
    payload: params.payload,
    payloadJSON: params.payloadJSON,
    error: params.error,
  });

  // Late results are silently ignored
  if (!ok) {
    context.logGateway.debug(`late invoke result ignored: id=${params.id}`);
    respond(true, { ok: true, ignored: true }, undefined);
    return;
  }
  respond(true, { ok: true }, undefined);
};
```

Late results (arriving after invoke has timed out) don't produce errors—the Gateway returns `{ ok: true, ignored: true }`. This avoids spurious error logs caused by network delays.

### Merged View of node.list

`node.list` returns not only currently online nodes but also paired but offline nodes, providing a **merged view**:

```typescript
"node.list": async ({ params, respond, context }) => {
  // Get list of paired nodes
  const list = await listDevicePairing();
  const pairedById = new Map(/* paired nodes → basic info */);

  // Get list of currently online nodes
  const connected = context.nodeRegistry.listConnected();
  const connectedById = new Map(connected.map(n => [n.nodeId, n]));

  // Merge: take union
  const nodeIds = new Set([...pairedById.keys(), ...connectedById.keys()]);
  const nodes = [...nodeIds].map(nodeId => {
    const paired = pairedById.get(nodeId);
    const live = connectedById.get(nodeId);
    return {
      nodeId,
      displayName: live?.displayName ?? paired?.displayName,
      // ... online info takes priority, offline info as fallback
      paired: Boolean(paired),
      connected: Boolean(live),
    };
  });

  // Sort: online first, then by name
  nodes.sort((a, b) => {
    if (a.connected !== b.connected) return a.connected ? -1 : 1;
    return (a.displayName ?? a.nodeId).localeCompare(b.displayName ?? b.nodeId);
  });

  respond(true, { ts: Date.now(), nodes }, undefined);
};
```

***

## Section Summary

1. **NodeRegistry uses bidirectional indexing**—`nodesById` and `nodesByConn` Maps support bidirectional lookup by node ID and connection ID, with consistency maintained during writes.
2. **invoke implements request-response matching**—each request is identified by UUID, with `{ resolve, reject, timer }` stored in `pendingInvokes`; when the node returns a result, the Promise is completed via ID matching. Timeout is treated as normal failure rather than exception.
3. **Event system handles five types of node events**—`voice.transcript` (voice transcription), `agent.request` (Agent deep link), `chat.subscribe/unsubscribe` (subscription management), `exec.*` (execution status).
4. **Subscription manager maintains many-to-many relationships**—two Maps bidirectionally index node-session subscriptions, providing three distribution methods: `sendToSession`, `sendToAllSubscribed`, `sendToAllConnected`.
5. **Gateway methods implement complete node lifecycle**—from pairing to discovery (list/describe) to invocation to events, each method includes parameter validation and security checks.
6. **Late results are handled gracefully**—invoke results arriving after timeout don't produce errors; instead, they're silently ignored and logged as debug messages.
