OpenClaw SDK
    Preparing search index...

    OpenClaw SDK

    OpenClaw SDK (TypeScript)

    OpenClaw SDK TypeScript License

    Feature-complete WebSocket SDK for TypeScript with automatic reconnection, event handling, and request/response correlation.

    TypeScript SDK for connecting to OpenClaw Gateway via WebSocket, providing a fully-featured WebSocket client with connection management, event handling, request/response patterns, and automatic reconnection.

    npm install openclaw-sdk
    
    import { createClient } from "openclaw-sdk";

    const client = createClient({
    url: "wss://gateway.openclaw.example.com",
    credentials: {
    deviceId: "your-device-id",
    apiKey: "your-api-key",
    },
    });

    await client.connect();
    console.log("Connected to OpenClaw Gateway");
    • WebSocket Transport: Cross-platform support (Node.js and Browser)
    • Automatic Reconnection: Configurable reconnection with Fibonacci backoff
    • Type-Safe: Full TypeScript support with comprehensive type exports
    • Error Handling: Rich error types with error codes and type guards
    • Event System: Subscribe to gateway events with wildcard support
    • Request Cancellation: AbortController support for long-running requests

    The ClientConfig interface provides all configuration options:

    interface ClientConfig {
    // Required
    url: string; // WebSocket URL
    credentials: CredentialsProvider | DeviceCredentials;

    // Optional
    autoReconnect?: boolean; // Auto-reconnect on disconnect (default: false)
    maxReconnectAttempts?: number; // Max reconnection attempts (default: 5)
    reconnectDelayMs?: number; // Initial reconnection delay (default: 1000)
    defaultRequestTimeout?: number; // Request timeout in ms (default: 30000)

    // TLS (Node.js only)
    tls?: TlsValidatorConfig; // TLS validation options
    }

    The SDK supports multiple authentication methods through CredentialsProvider:

    import { createClient, StaticCredentialsProvider } from "openclaw-sdk";

    const client = createClient({
    url: "wss://gateway.openclaw.example.com",
    credentials: {
    deviceId: "your-device-id",
    apiKey: "your-api-key",
    },
    });

    For dynamic token refresh or custom auth flows:

    import { type CredentialsProvider } from "openclaw-sdk";

    const customProvider: CredentialsProvider = {
    async getCredentials() {
    return {
    token: await getAuthToken(),
    success: true,
    };
    },

    async shouldRefresh() {
    return tokenWillExpireSoon();
    },

    async refresh() {
    return {
    token: await refreshAuthToken(),
    success: true,
    };
    },
    };

    const client = createClient({
    url: "wss://gateway.openclaw.example.com",
    credentials: customProvider,
    });

    When passing credentials directly via ClientConfig.auth, the credentials are stored in memory for the lifetime of the client instance. This applies to:

    • auth.token
    • auth.bootstrapToken
    • auth.deviceToken
    • auth.password

    For high-security environments, use the CredentialsProvider pattern instead:

    const client = createClient({
    url: "wss://gateway.openclaw.example.com",
    credentials: new CustomCredentialsProvider(),
    });

    This allows you to:

    • Retrieve credentials from secure storage (e.g., keychain, vault)
    • Implement dynamic token refresh without storing static credentials
    • Clear credentials from memory when not needed

    See Custom Credentials Provider for implementation details.

    Subscribe to gateway events using the client's event system:

    // Subscribe to specific event
    const unsubscribe = client.on("agent:status", (event) => {
    console.log("Agent status changed:", event.payload);
    });

    // Wildcard subscription
    const unsubscribeAll = client.on("agent:*", (event) => {
    console.log("Agent event:", event.type, event.payload);
    });

    // Unsubscribe when done
    unsubscribe();
    unsubscribeAll();

    The SDK uses the ws library for WebSocket connections in Node.js:

    npm install ws
    

    Native browser WebSocket API is used automatically—no additional dependencies needed.

    The SDK provides two approaches to reconnection:

    Use this when you need:

    • Simple automatic reconnection on disconnect
    • Configurable max attempts and delay
    • Standard Fibonacci backoff
    • Integration with connection lifecycle

    The ConnectionManager has built-in reconnection support:

    const client = createClient({
    url: "wss://gateway.openclaw.example.com",
    credentials: { ... },
    autoReconnect: true, // Enable auto-reconnect
    maxReconnectAttempts: 5, // Max retry attempts
    reconnectDelayMs: 1000, // Initial delay
    });

    // Reconnection happens automatically

    Use this when you need:

    • Custom reconnection logic separate from ConnectionManager
    • Reconnection state tracking for external management
    • Event-driven reconnection workflows
    • Advanced retry strategies beyond standard backoff
    import { createReconnectManager } from "openclaw-sdk";

    const reconnectMgr = createReconnectManager({
    maxAttempts: 10,
    initialDelayMs: 1000,
    maxDelayMs: 30000,
    });

    reconnectMgr.on("stateChange", (state) => {
    if (state.phase === "waiting") {
    console.log(`Reconnecting in ${state.delayMs}ms...`);
    }
    });

    // Manual control
    reconnectMgr.start();
    // ... custom logic ...
    reconnectMgr.stop();
    Need Recommended Approach
    Standard reconnection on disconnect ConnectionManager built-in
    Custom reconnection logic ReconnectManager stand-alone
    Integration with connection lifecycle ConnectionManager built-in
    Event-driven reconnection workflows ReconnectManager stand-alone
    import {
    createClient,
    OpenClawClient,
    type ClientConfig,
    } from "openclaw-sdk";

    All error classes and types are exported for proper error handling:

    import {
    // Error classes
    OpenClawError,
    AuthError,
    ConnectionError,
    ProtocolError,
    RequestError,
    TimeoutError,
    CancelledError,
    AbortError,
    GatewayError,
    ReconnectError,

    // Error code types
    type AuthErrorCode,
    type ConnectionErrorCode,
    type ProtocolErrorCode,
    type RequestErrorCode,
    type GatewayErrorCode,
    type ReconnectErrorCode,

    // Error type guards
    isOpenClawError,
    isAuthError,
    isConnectionError,
    isTimeoutError,
    isCancelledError,
    isAbortError,

    // Error factory
    createErrorFromResponse,
    } from "openclaw-sdk";

    Use type guards for safe error handling:

    try {
    await client.connect();
    } catch (error) {
    if (isAuthError(error)) {
    console.error("Authentication failed:", error.errorCode);
    } else if (isConnectionError(error)) {
    console.error("Connection failed:", error.errorCode);
    } else {
    console.error("Unknown error:", error);
    }
    }
    # Install dependencies
    npm install

    # Run tests
    npm test

    # Run linter
    npm run lint

    # Build
    npm run build

    # Type check
    npm run typecheck

    Apache 2.0