handleRequest

View as MarkdownOpen in Claude

Dispatch one inbound request from plain HTTP primitives and get back a [status, headers, body] triple to write to the response. Use it to serve the agent from a framework the SDK has no adapter for. It performs Basic Auth, runs any routing callback, applies onSwmlRequest modifications, and renders SWML with renderSwml(). For Hono-based hosts, mount asRouter() instead.

Parameters

method
stringRequired

HTTP method, such as "GET" or "POST".

url
stringRequired

The full request URL.

headers
Record<string, string>Required

Request headers as a plain object.

body
Record<string, unknown> | null

The already-parsed JSON body for POST requests. Omit for GET.

Returns

Promise<[number, Record<string, string>, string]> — The status code, response headers, and body string. A failed Basic Auth check returns 401 with a WWW-Authenticate header; a routing callback that redirects returns 307 with a Location header.

Example

import { createServer } from 'node:http';
import { AgentBase } from '@signalwire/sdk';
const agent = new AgentBase({ name: 'dispatch', route: '/' });
agent.setPromptText('You are a taxi dispatcher.');
createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const raw = Buffer.concat(chunks).toString();
const body = raw ? JSON.parse(raw) : null;
const url = `https://${req.headers.host}${req.url}`;
const [status, headers, text] = await agent.handleRequest(
req.method ?? 'GET',
url,
req.headers as Record<string, string>,
body,
);
res.writeHead(status, headers);
res.end(text);
}).listen(3000);