Files
flynn/src/gateway/router.ts
T
William Valentin f30a8bc318 feat(gateway): add WebSocket gateway with JSON-RPC protocol and auth
Phase 2 of the Flynn roadmap. Adds a WebSocket gateway server that
starts alongside the Telegram bot, providing real-time API access to
the agent, sessions, and tools.

Protocol: JSON-RPC-like (request/response/event) over WebSocket.
8 methods: agent.send, agent.cancel, sessions.list, sessions.history,
sessions.create, tools.list, tools.invoke, system.health.

Auth: Bearer token + Tailscale identity header support.
Session bridge: per-connection agent instances with shared model router.

New files: src/gateway/ (protocol, router, server, auth, session-bridge,
handlers for agent/sessions/tools/system).
57 new tests (181 total), typecheck clean.
2026-02-05 19:11:25 -08:00

28 lines
1010 B
TypeScript

import type { GatewayRequest, OutboundMessage } from './protocol.js';
import { makeError, ErrorCode } from './protocol.js';
// A handler function receives a request and a send function for streaming events.
// It returns a final response/error, or void if it already sent a done event.
export type SendFn = (msg: OutboundMessage) => void;
export type HandlerFn = (request: GatewayRequest, send: SendFn) => Promise<OutboundMessage | void>;
export class Router {
private handlers: Map<string, HandlerFn> = new Map();
register(method: string, handler: HandlerFn): void {
this.handlers.set(method, handler);
}
async dispatch(request: GatewayRequest, send: SendFn): Promise<OutboundMessage | void> {
const handler = this.handlers.get(request.method);
if (!handler) {
return makeError(request.id, ErrorCode.MethodNotFound, `Unknown method: ${request.method}`);
}
return handler(request, send);
}
listMethods(): string[] {
return Array.from(this.handlers.keys());
}
}