New protocol version released: This page may contain outdated information.
The HAIP client is the main interface for interacting with HAIP servers. It manages connections, handles protocol state, and provides methods for sending messages and managing runs.
Creating a Client
Factory Function (Recommended)
import { createHAIPClient } from "haip-sdk";
const client = createHAIPClient({
url: "ws://localhost:8080",
token: "your-jwt-token",
transport: "websocket",
});
Direct Constructor
import { HAIPClientImpl } from "haip-sdk";
const client = new HAIPClientImpl({
url: "ws://localhost:8080",
token: "your-jwt-token",
transport: "websocket",
flowControl: {
initialCredits: 10,
initialCreditBytes: 1024 * 1024,
},
maxConcurrentRuns: 5,
maxReconnectAttempts: 5,
reconnectDelay: 1000,
heartbeatInterval: 30000,
});
Configuration Options
The server URL to connect to. Supports WebSocket, SSE, and HTTP streaming
endpoints.
JWT authentication token for server authentication.
transport
'websocket' | 'sse' | 'http-streaming'
default:"'websocket'"
The transport protocol to use for communication.
Flow control configuration for managing message back-pressure.
Maximum number of concurrent runs allowed.
Maximum number of reconnection attempts on connection loss.
Initial delay between reconnection attempts (uses exponential backoff).
Interval for heartbeat ping/pong messages in milliseconds.
Connection Management
connect()
Establishes a connection to the HAIP server.
Returns: Promise<void>
Events:
connect
- Emitted when connection is established
handshake
- Emitted when handshake is completed
error
- Emitted if connection fails
disconnect()
Gracefully disconnects from the server.
await client.disconnect();
Returns: Promise<void>
Events:
disconnect
- Emitted when disconnection is complete
isConnected()
Checks if the client is currently connected.
const connected = client.isConnected();
Returns: boolean
Run Management
startRun()
Starts a new HAIP run session.
const runId = await client.startRun(
threadId?: string,
metadata?: Record<string, any>
);
Optional thread identifier for grouping related runs.
Optional metadata to associate with the run.
Returns: Promise<string>
- The generated run ID
finishRun()
Completes a run with the specified status.
await client.finishRun(
runId: string,
status?: 'OK' | 'CANCELLED' | 'ERROR',
summary?: string
);
The ID of the run to finish.
status
'OK' | 'CANCELLED' | 'ERROR'
default:"'OK'"
The final status of the run.
Optional summary text describing the run outcome.
cancelRun()
Cancels an active run.
await client.cancelRun(runId: string);
The ID of the run to cancel.
Messaging
sendTextMessage()
Sends a text message on the specified channel.
const messageId = await client.sendTextMessage(
channel: HAIPChannel,
text: string,
author?: string,
runId?: string,
threadId?: string
);
The channel to send the message on (‘USER’, ‘AGENT’, ‘SYSTEM’).
The text content to send.
The author of the message.
Optional run ID to associate with the message.
Optional thread ID to associate with the message.
Returns: Promise<string>
- The generated message ID
sendMessage()
Sends a custom HAIP message.
await client.sendMessage(
message: HAIPMessage,
options?: HAIPMessageOptions
);
The HAIP message to send.
Optional message options for flow control.
sendBinary()
Sends binary data.
await client.sendBinary(data: ArrayBuffer);
Initiates a tool call.
const callId = await client.callTool(
channel: HAIPChannel,
tool: string,
params?: Record<string, any>,
runId?: string,
threadId?: string
);
The channel for the tool call.
The name of the tool to call.
Parameters to pass to the tool.
Optional run ID to associate with the tool call.
Optional thread ID to associate with the tool call.
Returns: Promise<string>
- The generated call ID
Updates the status of a tool call.
await client.updateTool(
channel: HAIPChannel,
callId: string,
status: 'QUEUED' | 'RUNNING' | 'CANCELLING',
progress?: number,
partial?: any,
runId?: string,
threadId?: string
);
Completes a tool call with results.
await client.completeTool(
channel: HAIPChannel,
callId: string,
status?: 'OK' | 'CANCELLED' | 'ERROR',
result?: any,
runId?: string,
threadId?: string
);
Cancels a tool call.
await client.cancelTool(
channel: HAIPChannel,
callId: string,
reason?: string,
runId?: string,
threadId?: string
);
Event Handling
The client extends EventEmitter and provides the following events:
Connection Events
client.on("connect", () => {
console.log("Connected to server");
});
client.on("disconnect", (reason: string) => {
console.log("Disconnected:", reason);
});
client.on("handshake", (payload: any) => {
console.log("Handshake completed:", payload);
});
Message Events
client.on("message", (message: HAIPMessage) => {
console.log("Received message:", message);
});
client.on("binary", (data: ArrayBuffer) => {
console.log("Received binary data:", data.byteLength, "bytes");
});
Error Events
client.on("error", (error: Error) => {
console.error("Client error:", error);
});
State Management
getConnectionState()
Gets the current connection state.
const state = client.getConnectionState();
Returns: HAIPConnectionState
interface HAIPConnectionState {
connected: boolean;
handshakeCompleted: boolean;
sessionId: string;
lastAck: string;
reconnectAttempts: number;
credits: Map<HAIPChannel, number>;
byteCredits: Map<HAIPChannel, number>;
}
Gets performance metrics.
const metrics = client.getPerformanceMetrics();
Returns: HAIPPerformanceMetrics
interface HAIPPerformanceMetrics {
messagesSent: number;
messagesReceived: number;
bytesSent: number;
bytesReceived: number;
connectionTime: number;
lastUpdated: number;
}
getActiveRuns()
Gets all active runs.
const runs = client.getActiveRuns();
Returns: HAIPRun[]
getRun()
Gets a specific run by ID.
const run = client.getRun(runId);
Returns: HAIPRun | undefined
Flow Control
sendFlowUpdate()
Sends a flow control update.
await client.sendFlowUpdate(
channel: string,
addMessages?: number,
addBytes?: number
);
The channel to update flow control for.
Number of message credits to add.
Number of byte credits to add.
Channel Control
pauseChannel()
Pauses message flow on a channel.
await client.pauseChannel(channel: string);
resumeChannel()
Resumes message flow on a channel.
await client.resumeChannel(channel: string);
Replay Support
requestReplay()
Requests message replay from a specific sequence number.
await client.requestReplay(
fromSeq: string,
toSeq?: string
);
Starting sequence number for replay.
Ending sequence number for replay (optional).
Audio Support
sendAudioChunk()
Sends an audio chunk.
await client.sendAudioChunk(
channel: HAIPChannel,
messageId: string,
mime: string,
data: ArrayBuffer,
durationMs?: number,
runId?: string,
threadId?: string
);
The channel for the audio data.
Unique identifier for the audio message.
MIME type of the audio data.
Duration of the audio chunk in milliseconds.
Optional run ID to associate with the audio.
Optional thread ID to associate with the audio.
Error Handling
The client provides comprehensive error handling:
client.on("error", (error: Error) => {
// Handle different error types
if (error.message.includes("AUTHENTICATION_FAILED")) {
console.log("Authentication failed - check your token");
} else if (error.message.includes("CONNECTION_FAILED")) {
console.log("Connection failed - will attempt to reconnect");
} else if (error.message.includes("FLOW_CONTROL")) {
console.log("Flow control error - message was dropped");
}
});
Next Steps