Node / TypeScript SDK
@kolwire/sdk — zero runtime dependencies (global fetch / WebSocket / WebCrypto), ESM + CommonJS, full types for every resource and event. Node 18+; Node 22+ for the realtime client without extra packages (otherwise install ws).
npm i @kolwire/sdk| Import | Contents | Runs in |
|---|---|---|
@kolwire/sdk | Kolwire client, models, events, commands, webhooks, realtime, errors | Node, Bun, Deno, Edge |
@kolwire/sdk/realtime | StreamClient only | Browsers too |
@kolwire/sdk/webhooks | Signature verification only | Anywhere with WebCrypto |
@kolwire/sdk/node | createMediaStreamServer | Node |
Client
import { Kolwire } from "@kolwire/sdk";
const vi = new Kolwire({
apiKey: process.env.KOLWIRE_API_KEY, // default: env KOLWIRE_API_KEY
baseURL: "https://api.kolwire.com/v1", // default: env KOLWIRE_BASE_URL
streamURL: "wss://stream.kolwire.com/v1/stream", // default: env KOLWIRE_STREAM_URL or derived
maxRetries: 2,
timeout: 60_000, // ms per attempt
fetch: customFetch, // optional
webhookSecret: process.env.KOLWIRE_WEBHOOK_SECRET, // default for vi.webhooks
});Resources: vi.numbers, vi.calls, vi.callFlows, vi.contacts, vi.messages, vi.conversations, vi.whatsapp.templates, vi.agents, vi.playbooks, vi.knowledgeBases, vi.teamAgents, vi.queues, vi.campaigns, vi.dispositions, vi.webhookEndpoints, vi.apiKeys, vi.streamTokens, vi.search, vi.billing, vi.usage, vi.wallboard. Every method: resources & methods.
const call = await vi.calls.create({ from: "+15550001111", to: "+15550002222", agent_id: "agt_123" });
await vi.calls.actions(call.id, { commands: [{ command: "say", text: "One moment." }] });
const transcript = await vi.calls.transcript(call.id);
const insights = await vi.calls.insights(call.id);Not in the SDK yet? vi.request("GET", "/new-endpoint", { query }) and vi.paginate("/new-list").
Per-request options
The last argument of every method:
await vi.messages.create(params, {
idempotencyKey: "order-1042-shipped", // default: auto-generated for POST/PATCH, reused across retries
timeout: 10_000,
maxRetries: 0,
signal: abortController.signal,
headers: { "x-trace-id": traceId },
});Pagination
list methods return a PagePromise:
const page = await vi.calls.list({ limit: 50 }); // Page: data, has_more, next_cursor
if (page.hasNextPage()) await page.getNextPage();
for await (const call of vi.calls.list({ status: "completed" })) { /* every item, lazily */ }
const firstHundred = await vi.contacts.list().toArray(100);Errors
| Class | When |
|---|---|
APIError | Base for any non-2xx: status, code, message, details, requestId, headers |
BadRequestError (400), AuthenticationError (401), InsufficientFundsError (402), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), UnprocessableEntityError (422), RateLimitError (429), InternalServerError (5xx) | Specific statuses |
APIConnectionError, APITimeoutError | Network failure / timeout (after retries) |
WebhookVerificationError | Bad or stale webhook signature |
All extend KolwireError.
Webhooks
const event = await vi.webhooks.constructEvent(rawBody, req.headers); // verifies + parses, throws WebhookVerificationError
const ok = await vi.webhooks.isValid(rawBody, req.headers);
const event2 = await vi.webhooks.unwrap(request); // fetch-style Request
import { constructEvent, verifySignature, isValidSignature, signPayload } from "@kolwire/sdk/webhooks";
await verifySignature(rawBody, header, [newSecret, oldSecret], { toleranceSec: 300 });Verification is async (WebCrypto), so it works on Edge runtimes. See webhook security.
Events
import type { KolwireEvent, EventOf } from "@kolwire/sdk";
import { PUBLIC_EVENT_TYPES, isEvent } from "@kolwire/sdk";
function onEvent(e: KolwireEvent) {
if (isEvent(e, "call.transcript.final")) console.log(e.data.speaker, e.data.text);
}
type Ended = EventOf<"call.ended">;Commands
import { VoiceResponse, Flow, say, play } from "@kolwire/sdk";
const response = new VoiceResponse()
.say("Hi!")
.gather({ input: ["dtmf", "speech"], max_digits: 1, prompt: say("Press 1 for sales") })
.connectAgent("agt_123");
res.json(response); // { commands: [...] }
const flow = new Flow()
.gather({ max_digits: 1, prompt: play("https://cdn.example.com/menu.mp3") }, {
"1": (b) => b.enqueue("sales"),
default: (b) => b.hangup(),
})
.build(); // { version: 1, start: [...] }Builder methods: say, play, pause, answer, hangup, reject, gather, dial, transfer, conference, enqueue, record, stream, connectAgent, assist, transcribe, sendDtmf, redirect, sms, detectMachine, and add(command) for anything else. See commands & flows.
Realtime
// Server: tokens minted and refreshed for you
const stream = await vi.realtime({ callId: "call_123", events: ["call.transcript.*"] });
stream.on("call.transcript.final", (e) => console.log(e.data.text));
for await (const e of stream.events("call.assist.suggestion")) console.log(e.data.title);
// Browser
import { StreamClient } from "@kolwire/sdk/realtime";
const s = new StreamClient({ url: "wss://stream.kolwire.com/v1/stream", token: getToken });
await s.connect();StreamClient options: url, token (string or async function), WebSocket (constructor, e.g. from ws), reconnect (true), minReconnectDelayMs / maxReconnectDelayMs, lastEventId, subscribe ({ events?, call_id? } or false), pingIntervalMs. Lifecycle events: open, close, error, reconnecting. See realtime protocol.
Media streams
import { createMediaStreamServer } from "@kolwire/sdk/node";
const server = await createMediaStreamServer({
port: 8080,
path: "/media",
token: process.env.MEDIA_TOKEN,
onSession(s) {
s.on("start", (info) => console.log(info.call_id, info.codec, info.sample_rate));
s.on("audio", (f) => f.pcm /* Int16Array */);
s.on("dtmf", (d) => console.log(d));
s.sendAudio(pcmInt16, { sampleRate: 24000 });
s.mark("greeting");
s.clear();
s.on("stop", () => {});
},
});
await server.close();Also attachable to an existing HTTP server (server option) and an authenticate(req) hook. MediaStreamSession can wrap any WebSocket (e.g. from ws). Audio helpers: mulawEncode, mulawDecode, resample, pcm16ToBytes, bytesToPcm16. See BYO voice agent.
Environment variables
| Variable | Used for |
|---|---|
KOLWIRE_API_KEY | Default API key |
KOLWIRE_BASE_URL | Default base URL |
KOLWIRE_STREAM_URL | Default realtime URL |
KOLWIRE_WEBHOOK_SECRET | Default webhook secret |