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");
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.tokenauth.bootstrapTokenauth.deviceTokenauth.passwordFor high-security environments, use the CredentialsProvider pattern instead:
const client = createClient({
url: "wss://gateway.openclaw.example.com",
credentials: new CustomCredentialsProvider(),
});
This allows you to:
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:
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:
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