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

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

url
string
required
The server URL to connect to. Supports WebSocket, SSE, and HTTP streaming endpoints.
token
string
required
JWT authentication token for server authentication.
transport
'websocket' | 'sse' | 'http-streaming'
default:"'websocket'"
The transport protocol to use for communication.
flowControl
HAIPFlowControlConfig
Flow control configuration for managing message back-pressure.
maxConcurrentRuns
number
default:"5"
Maximum number of concurrent runs allowed.
maxReconnectAttempts
number
default:"5"
Maximum number of reconnection attempts on connection loss.
reconnectDelay
number
default:"1000"
Initial delay between reconnection attempts (uses exponential backoff).
heartbeatInterval
number
default:"30000"
Interval for heartbeat ping/pong messages in milliseconds.

Connection Management

connect()

Establishes a connection to the HAIP server.
await client.connect();
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>
);
threadId
string
Optional thread identifier for grouping related runs.
metadata
Record<string, any>
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
);
runId
string
required
The ID of the run to finish.
status
'OK' | 'CANCELLED' | 'ERROR'
default:"'OK'"
The final status of the run.
summary
string
Optional summary text describing the run outcome.

cancelRun()

Cancels an active run.
await client.cancelRun(runId: string);
runId
string
required
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
);
channel
HAIPChannel
required
The channel to send the message on (‘USER’, ‘AGENT’, ‘SYSTEM’).
text
string
required
The text content to send.
author
string
The author of the message.
runId
string
Optional run ID to associate with the message.
threadId
string
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
);
message
HAIPMessage
required
The HAIP message to send.
options
HAIPMessageOptions
Optional message options for flow control.

sendBinary()

Sends binary data.
await client.sendBinary(data: ArrayBuffer);
data
ArrayBuffer
required
The binary data to send.

Tool Integration

callTool()

Initiates a tool call.
const callId = await client.callTool(
  channel: HAIPChannel,
  tool: string,
  params?: Record<string, any>,
  runId?: string,
  threadId?: string
);
channel
HAIPChannel
required
The channel for the tool call.
tool
string
required
The name of the tool to call.
params
Record<string, any>
Parameters to pass to the tool.
runId
string
Optional run ID to associate with the tool call.
threadId
string
Optional thread ID to associate with the tool call.
Returns: Promise<string> - The generated call ID

updateTool()

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
);

completeTool()

Completes a tool call with results.
await client.completeTool(
  channel: HAIPChannel,
  callId: string,
  status?: 'OK' | 'CANCELLED' | 'ERROR',
  result?: any,
  runId?: string,
  threadId?: string
);

cancelTool()

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>;
}

getPerformanceMetrics()

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
);
channel
string
required
The channel to update flow control for.
addMessages
number
Number of message credits to add.
addBytes
number
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
);
fromSeq
string
required
Starting sequence number for replay.
toSeq
string
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
);
channel
HAIPChannel
required
The channel for the audio data.
messageId
string
required
Unique identifier for the audio message.
mime
string
required
MIME type of the audio data.
data
ArrayBuffer
required
The audio data to send.
durationMs
number
Duration of the audio chunk in milliseconds.
runId
string
Optional run ID to associate with the audio.
threadId
string
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