Skip to content

heypinchy/openclaw-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

34 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

openclaw-node

A Node.js client for OpenClaw β€” connect your app to AI agents in a few lines of code.

What is OpenClaw?

OpenClaw is an open-source AI agent platform. You run a Gateway (a local server) that manages AI agents β€” think of them as persistent AI assistants that can use tools, remember context, and connect to services like Slack, Telegram, or your own app.

This package lets you talk to those agents from Node.js.

Prerequisites

Before using this client, you need a running OpenClaw Gateway:

# Install OpenClaw
npm install -g openclaw

# Start the gateway
openclaw gateway start

The gateway runs on ws://localhost:18789 by default. If you've set an auth token (via OPENCLAW_GATEWAY_TOKEN), you'll need it for the client too.

β†’ Full OpenClaw setup guide

Installation

npm install openclaw-node

Node.js 22+ works out of the box (built-in WebSocket). For Node.js 20–21, also install ws:

npm install openclaw-node ws

Quick Start

import { OpenClawClient } from "openclaw-node";

const client = new OpenClawClient({
  url: "ws://localhost:18789",
  // Only needed if your gateway has a token set:
  // token: process.env.OPENCLAW_GATEWAY_TOKEN,
});

await client.connect();

// Send a message and stream the response
const stream = client.chat("What's the weather like in Vienna?");

for await (const chunk of stream) {
  if (chunk.type === "text") {
    process.stdout.write(chunk.text);
    // Prints token by token: "The current weather in Vienna is..."
  }
}
// Final chunk has type "done"

await client.disconnect();

Get a complete response (no streaming)

const response = await client.chatSync("Summarize my last 3 meetings");
console.log(response);
// "Here's a summary of your recent meetings: ..."

Core Concepts

Gateway β€” The local server that runs your agents. This client connects to it via WebSocket. Default address: ws://localhost:18789.

Agent β€” A configured AI assistant with its own personality, tools, and memory. The gateway can run multiple agents. Each has an agentId.

Session β€” A conversation thread with an agent. Sessions persist across connections, so you can pick up where you left off. Each session has a sessionKey.

Token β€” An optional auth string that protects your gateway from unauthorized access. Set it via OPENCLAW_GATEWAY_TOKEN on the gateway, then pass the same value to this client.

API Reference

Constructor

const client = new OpenClawClient({
  url: "ws://localhost:18789",  // Gateway address (required)
  token: "my-secret-token",     // Auth token (optional, must match gateway)
  autoReconnect: true,          // Reconnect on disconnect (default: true)
  maxReconnectAttempts: 10,     // Give up after N retries (default: 10)
});

Connecting

await client.connect();    // Connect and authenticate
await client.disconnect(); // Gracefully close

client.isConnected;        // true/false

The client handles all protocol details (challenge-response handshake, authentication, keepalive) automatically.

Chat β€” Streaming

const stream = client.chat("Your message here", {
  sessionKey: "optional-session-id",  // Continue a specific conversation
  agentId: "optional-agent-id",       // Talk to a specific agent
});

for await (const chunk of stream) {
  switch (chunk.type) {
    case "text":
      process.stdout.write(chunk.text);  // Partial response text
      break;
    case "tool_use":
      console.log(`\nπŸ”§ Using tool: ${chunk.text}`);
      break;
    case "tool_result":
      console.log(`βœ… Tool result: ${chunk.text}`);
      break;
    case "done":
      console.log("\n--- Response complete ---");
      break;
  }
}

Chat β€” Complete Response

const reply = await client.chatSync("What's on my calendar today?");
// Returns the full response as a string

Sessions

Sessions are conversation threads. They persist on the gateway, so you can resume them later.

// List all sessions
const sessions = await client.sessions.list({ limit: 10 });

// Get message history for a session
const history = await client.sessions.history("session-key-here", {
  limit: 20,
});

// Send a message into an existing session
await client.sessions.send("session-key-here", "Follow up on yesterday's task");

Events

// Connection lifecycle
client.on("connected", (info) => console.log("Connected to gateway"));
client.on("disconnected", ({ reason }) => console.log("Disconnected:", reason));
client.on("error", (err) => console.error("Error:", err));

// Gateway events (exec approvals, presence changes, etc.)
client.on("event", (event) => {
  console.log("Gateway event:", event.event, event.payload);
});

Low-Level Protocol Access

For advanced use cases, you can send raw protocol requests:

const response = await client.request("status", {});
console.log(response.payload);

Examples

Express API with AI backend

import express from "express";
import { OpenClawClient } from "openclaw-node";

const app = express();
const client = new OpenClawClient({ url: "ws://localhost:18789" });

await client.connect();

app.post("/api/ask", express.json(), async (req, res) => {
  const answer = await client.chatSync(req.body.question);
  res.json({ answer });
});

app.listen(3000);

CLI chatbot

import readline from "readline";
import { OpenClawClient } from "openclaw-node";

const client = new OpenClawClient({ url: "ws://localhost:18789" });
await client.connect();

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

rl.on("line", async (input) => {
  for await (const chunk of client.chat(input)) {
    if (chunk.type === "text") process.stdout.write(chunk.text);
  }
  console.log();
});

Compatibility

openclaw-node Gateway Protocol OpenClaw Gateway What's new
0.2.x v3 0.x (current) Tool event streaming
0.1.x v3 0.x Initial release

If the OpenClaw Gateway bumps its protocol version, you'll need a matching openclaw-node release. Check this table to find the right version.

Features

  • Streaming β€” AsyncIterator-based, get responses token by token
  • Tool events β€” See which tools agents use and what they return (tool_use / tool_result chunks)
  • Auto-reconnect β€” Exponential backoff, configurable retries
  • TypeScript-first β€” Full type definitions for all protocol messages
  • Zero config β€” Handles the full WebSocket protocol (handshake, auth, keepalive) for you
  • Lightweight β€” Zero required dependencies on Node.js 22+

Built for Pinchy

This client was extracted from Pinchy, an open-source web UI for OpenClaw with multi-user support, agent permissions, and a dashboard. It works great standalone β€” use it to build your own OpenClaw integrations.

Contributing

Contributions welcome! See CONTRIBUTING.md.

License

MIT

Links

  • OpenClaw β€” The AI agent platform
  • Pinchy β€” Open-source web UI for OpenClaw
  • OpenClaw Docs β€” Gateway setup and configuration

About

Node.js client for the OpenClaw Gateway WebSocket protocol

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors