Skip to content

signalwire/signalwire-typescript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

427 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SignalWire SDK for TypeScript

Build AI voice agents, control live calls over WebSocket, and manage every SignalWire resource over REST -- all from one package.

Documentation · Report an Issue · npm

Discord MIT License GitHub Stars


export {}; // treat each example as a module (top-level await)
declare global {
  const callId: string;
  const signingKey: string;
  const signatureHeader: string;
  const fullUrl: string;
  const rawBodyString: string;
  const requestParams: Record<string, string>;
}

What's in this SDK

Capability What it does Quick link
AI Agents Build voice agents that handle calls autonomously -- the platform runs the AI pipeline, your code defines the persona, tools, and call flow Agent Guide
RELAY Client Control live calls and SMS/MMS in real time over WebSocket -- answer, play, record, collect DTMF, conference, transfer, and more RELAY docs
REST Client Manage SignalWire resources over HTTP -- phone numbers, SIP endpoints, Fabric AI agents, video rooms, messaging, and the full set of REST API namespaces REST docs
npm install @signalwire/sdk

AI Agents

Each agent is a self-contained microservice that generates SWML (SignalWire Markup Language) and handles SWAIG (SignalWire AI Gateway) tool calls. The SignalWire platform runs the entire AI pipeline (STT, LLM, TTS) -- your agent just defines the behavior.

import { AgentBase, FunctionResult } from '@signalwire/sdk';

const agent = new AgentBase({
  name: 'my-agent',
  route: '/agent',
});

agent.addLanguage({ name: 'English', code: 'en-US', voice: 'inworld.Mark' });
agent.promptAddSection('Role', { body: 'You are a helpful assistant.' });

agent.defineTool({
  name: 'get_time',
  description: 'Get the current time',
  parameters: {},
  handler: () => new FunctionResult(`The time is ${new Date().toLocaleTimeString()}`),
});

agent.run(); // Starts HTTP server on port 3000

Test locally without running a server:

npx tsx src/cli/swaig-test.ts examples/simple-agent.ts --list-tools
npx tsx src/cli/swaig-test.ts examples/simple-agent.ts --dump-swml
npx tsx src/cli/swaig-test.ts examples/simple-agent.ts --exec get_time

Agent Features

  • Prompt Object Model (POM) -- structured prompt composition via promptAddSection()
  • SWAIG tools -- define functions with defineTool() that the AI calls mid-conversation, with native access to the call's media stack
  • Skills system -- add capabilities with one-liners: await agent.addSkill(new DateTimeSkill())
  • Contexts and steps -- structured multi-step workflows with navigation control
  • DataMap tools -- tools that execute on SignalWire's servers, calling REST APIs without your own webhook
  • Dynamic configuration -- per-request agent customization for multi-tenant deployments
  • Call flow control -- pre-answer, post-answer, and post-AI verb insertion
  • Prefab agents -- ready-to-use archetypes (InfoGatherer, Survey, FAQ, Receptionist, Concierge)
  • Multi-agent hosting -- serve multiple agents on a single server with AgentServer
  • SIP routing -- route SIP calls to agents based on usernames
  • Session state -- persistent conversation state with global data and post-prompt summaries
  • Security -- auto-generated basic auth, function-specific HMAC tokens, SSL support
  • Serverless -- auto-detects Lambda, CGI, Google Cloud Functions, Azure Functions

Agent Examples

The examples/ directory contains 35+ working examples:

Example What it demonstrates
simple-agent.ts POM prompts, SWAIG tools, multilingual support, LLM tuning
contexts-steps.ts Multi-step workflow with context switching and step navigation
datamap-tools.ts Server-side API tools without webhooks
skills-demo.ts Loading built-in skills (datetime, math)
call-flow.ts Call flow verbs, debug events, FunctionResult actions
session-state.ts onSummary, global data, post-prompt summaries
multi-agent.ts Multiple agents on one server
serverless-lambda.ts AWS Lambda deployment
dynamic-config.ts Per-request dynamic configuration, multi-tenant routing

See examples/README.md for the full list organized by category.


RELAY Client

Real-time call control and messaging over WebSocket. The RELAY client connects to SignalWire via the Blade protocol and gives you imperative, async control over live phone calls and SMS/MMS.

import { RelayClient, Call } from '@signalwire/sdk';

const client = new RelayClient({
  contexts: ['default'],
});

client.onCall(async (call: Call) => {
  await call.answer();
  const action = await call.play([{ type: 'tts', text: 'Welcome to SignalWire!' }]);
  await action.wait();
  await call.hangup();
});

client.run();
  • 40+ calling methods (play, record, collect, detect, tap, stream, AI, conferencing, and more)
  • SMS/MMS messaging with delivery tracking
  • Action objects with wait(), stop(), pause(), resume()
  • Auto-reconnect with exponential backoff

See the RELAY documentation for the full guide, API reference, and examples.


REST Client

Typed HTTP client for managing SignalWire resources and controlling calls over HTTP. No WebSocket required -- just standard fetch requests.

import { RestClient } from '@signalwire/sdk';

const client = new RestClient({
  project: '...',
  token: '...',
  host: 'example.signalwire.com',
});

await client.fabric.aiAgents.create({ name: 'Support Bot', prompt: { text: 'You are helpful.' } });
await client.calling.play(callId, [{ type: 'tts', params: { text: 'Hello!' } }]);
await client.phoneNumbers.search({ areacode: '512' });
await client.datasphere.documents.search('billing policy');
  • Namespaced API surfaces: Fabric (16 resource types), Calling (37 commands), Video, Datasphere, Phone Numbers, SIP, Queues, Recordings, and more
  • Uses Node's built-in fetch -- no HTTP client dependency
  • Dict returns -- raw JSON, no wrapper objects

See the REST documentation for the full guide, API reference, and examples.


Webhook Verification

Verify that an inbound webhook (status callback, messaging callback, SWML/SWAIG request) genuinely came from SignalWire using your Signing Key. This is the spiritual successor to the Compatibility API's RestClient.validateRequest() / validateRequestWithBody() — and it ships built into @signalwire/sdk as a top-level export, so you do not need the separate @signalwire/compatibility-api package.

import { validateRequest } from '@signalwire/sdk';

// Parsed form params (classic cXML/Compat webhooks) — this one call replaces
// the two Python-SDK entry points (validateRequest for parsed params and
// validateRequestWithBody for raw bodies): TS unifies both behind validateRequest.
const ok = validateRequest(signingKey, signatureHeader, fullUrl, requestParams);

// Raw request body (JSON/SWML, or cXML form bodies that carry bodySHA256) —
// same unified function, passed the raw body string instead of parsed params.
const okBody = validateRequest(signingKey, signatureHeader, fullUrl, rawBodyString);

validateRequest folds both Compatibility API methods into one call: pass a parsed params object / Map / array of tuples for form-encoded webhooks, or the raw body string to additionally verify the bodySHA256 the platform includes for JSON/SWML payloads. It returns true on a match, false otherwise, and throws if the Signing Key is missing.

If you want the lower-level primitive (compute/compare a single signature over a raw body), validateWebhookSignature(signingKey, signature, url, rawBody) is also exported.


Installation

# Core SDK (agents, RELAY, REST)
npm install @signalwire/sdk

Requires Node.js >= 22.

Documentation

Full reference documentation is available at developer.signalwire.com/sdks/agents-sdk.

Guides are also available in the docs/ directory:

Getting Started

  • Agent Guide -- creating agents, prompt configuration, dynamic setup
  • Architecture -- SDK architecture and core concepts
  • SDK Features -- feature overview, SDK vs raw SWML comparison

Core Features

Skills and Extensions

Deployment

Reference

Environment Variables

Variable Used by Description
SIGNALWIRE_PROJECT_ID RELAY, REST Project identifier
SIGNALWIRE_API_TOKEN RELAY, REST API token
SIGNALWIRE_SPACE RELAY, REST Space hostname (e.g. example.signalwire.com)
SIGNALWIRE_REST_BASE_URL REST Override the REST base URL with a full http(s):// URL (local mock / private space / proxy). Precedence: host option > SIGNALWIRE_REST_BASE_URL > SIGNALWIRE_SPACE.
SIGNALWIRE_REST_CA_FILE REST Path to a PEM CA bundle to trust for HTTPS REST requests (private/self-signed certificates).
SIGNALWIRE_RELAY_HOST RELAY Override the RELAY WebSocket host (advanced/testing). Precedence: host option > SIGNALWIRE_RELAY_HOST > SIGNALWIRE_SPACE > built-in default.
SIGNALWIRE_RELAY_SCHEME RELAY Override the RELAY WebSocket scheme (ws/wss; default wss). Precedence: scheme option > SIGNALWIRE_RELAY_SCHEME > wss; any value other than ws/wss falls back to wss.
SWML_BASIC_AUTH_USER Agents Basic auth username (default: auto-generated)
SWML_BASIC_AUTH_PASSWORD Agents Basic auth password (default: auto-generated)
SWML_PROXY_URL_BASE Agents Base URL when behind a reverse proxy
SWML_SSL_ENABLED Agents Enable HTTPS (true, 1, yes)
SWML_SSL_CERT_PATH Agents Path to SSL certificate
SWML_SSL_KEY_PATH Agents Path to SSL private key
SIGNALWIRE_LOG_LEVEL All Logging level (debug, info, warn, error)
SIGNALWIRE_LOG_MODE All Set to off to suppress all logging

Testing

Lint, format, and test go through the canonical scripts under scripts/. They self-bootstrap their toolchain (installing dependencies on first run) and work from any directory:

# Run the test suite (optional filter passed through to vitest)
bash scripts/run-tests.sh
bash scripts/run-tests.sh AgentBase

# Format the tree (or --check to verify without writing)
bash scripts/run-format.sh
bash scripts/run-format.sh --check

# Lint (tsc + eslint; --fix to autofix)
bash scripts/run-lint.sh
# Build
npm run build

# Dev mode (watch + rebuild)
npm run dev

# Watch-mode tests
npm run test:watch

License

MIT -- see LICENSE for details.

About

SignalWire AI Agents Typescript SDK, Relay and REST

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages