import { AUDIO_FORMAT, check, AgentsResponse, ConversationResponse, DeviceCredential, DeviceStatusResponse, ErrorResponse, RevokeResponse, SCHEMA_VERSION, TranscribeResponse, TurnResult, WakeResponse, type ErrorBody, } from '@hermeven/contracts'; import type { TSchema } from '@sinclair/typebox'; /** The bridge answered with a contract error. */ export class BridgeApiError extends Error { override name = 'BridgeApiError'; constructor( readonly status: number, readonly body: ErrorBody, ) { super(body.message); } } /** No usable answer: offline, timeout, CORS/whitelist block, or a non-contract response. */ export class BridgeNetworkError extends Error { override name = 'BridgeNetworkError'; } export interface BridgeClientOptions { baseUrl: string; token?: string; timeoutMs?: number; fetchImpl?: typeof fetch; } /** * Hosts on which plain HTTP is tolerated: this machine only, for the simulator and the * browser preview. Exact matches, so `127.0.0.1.example.com` or `localhost.example.com` * do not qualify, and neither does any LAN or public address. */ export function isLoopbackHost(hostname: string): boolean { return hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname); } /** * The device credential and the user's recordings travel to this URL, so it must be HTTPS. * The one exception is HTTP to loopback, which never leaves the machine. */ export function normalizeBridgeUrl(raw: string): string { let url: URL; try { url = new URL(raw.trim()); } catch { throw new Error('Enter the bridge address as a full URL, for example https://bridge.example'); } if (url.username || url.password) throw new Error('The bridge address must not contain a user name or password.'); if (url.protocol === 'https:') return url.origin + url.pathname.replace(/\/+$/, ''); if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.origin + url.pathname.replace(/\/+$/, ''); throw new Error('The bridge address must start with https://'); } export class BridgeClient { private readonly baseUrl: string; private readonly timeoutMs: number; private readonly fetchImpl: typeof fetch; token: string; constructor(options: BridgeClientOptions) { this.baseUrl = normalizeBridgeUrl(options.baseUrl); this.token = options.token ?? ''; this.timeoutMs = options.timeoutMs ?? 15_000; this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init)); } private async call( schema: T, method: string, path: string, init: { json?: unknown; binary?: Uint8Array; auth?: boolean } = {}, ): Promise { const headers: Record = { Accept: 'application/json' }; if (init.auth !== false) headers.Authorization = `Bearer ${this.token}`; let body: BodyInit | undefined; if (init.json !== undefined) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(init.json); } else if (init.binary) { headers['Content-Type'] = 'application/octet-stream'; body = init.binary as unknown as BodyInit; } let res: Response; let payload: unknown; try { res = await this.fetchImpl(`${this.baseUrl}${path}`, { method, headers, body, signal: AbortSignal.timeout(this.timeoutMs), credentials: 'omit', cache: 'no-store', }); payload = await res.json(); } catch (err) { throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error'); } if (!res.ok) { if (check(ErrorResponse, payload)) throw new BridgeApiError(res.status, payload.error as ErrorBody); // A proxy or captive portal answered instead of the bridge. throw new BridgeNetworkError(`unexpected HTTP ${res.status}`); } // A 200 that is not a valid contract response is not proof of anything. if (!check(schema, payload)) throw new BridgeNetworkError('response did not match the contract'); return payload; } claim(code: string, deviceName: string): Promise { return this.call(DeviceCredential, 'POST', '/v1/pairing/claim', { auth: false, json: { schema_version: SCHEMA_VERSION, code, device_name: deviceName }, }); } device(): Promise { return this.call(DeviceStatusResponse, 'GET', '/v1/device'); } renew(): Promise { return this.call(DeviceCredential, 'POST', '/v1/device/renew', { json: {} }); } revoke(): Promise { return this.call(RevokeResponse, 'DELETE', '/v1/device'); } /** The agents this device may talk to. A bridge from before agent selection answers `not_found`. */ agents(): Promise { return this.call(AgentsResponse, 'GET', '/v1/agents'); } /** `agentId` is sent only when given, so a bridge from before agent selection still accepts the request. */ createConversation(agentId?: string): Promise { return this.call(ConversationResponse, 'POST', '/v1/conversations', { json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId }, }); } submitText(args: { requestId: string; conversationId: string; locale: string; text: string }): Promise { return this.call(TurnResult, 'POST', '/v1/turns', { json: { schema_version: SCHEMA_VERSION, request_id: args.requestId, conversation_id: args.conversationId, locale: args.locale, input: { kind: 'text', text: args.text }, }, }) as Promise; } /** Raw PCM as the request body; metadata travels in the query string, never the audio in JSON. */ submitAudio(args: { requestId: string; conversationId: string; locale: string; pcm: Uint8Array }): Promise { const query = new URLSearchParams({ schema_version: String(SCHEMA_VERSION), request_id: args.requestId, conversation_id: args.conversationId, locale: args.locale, input_kind: 'audio', encoding: AUDIO_FORMAT.encoding, sample_rate: String(AUDIO_FORMAT.sampleRate), channels: String(AUDIO_FORMAT.channels), }); return this.call(TurnResult, 'POST', `/v1/turns?${query}`, { binary: args.pcm }) as Promise; } /** * One stretch of speech heard while listening: did it begin with an agent's name? Creates * nothing on the bridge. A bridge without wake names answers `not_found`. */ wake(args: { locale: string; pcm: Uint8Array }): Promise { const query = new URLSearchParams({ schema_version: String(SCHEMA_VERSION), locale: args.locale, encoding: AUDIO_FORMAT.encoding, sample_rate: String(AUDIO_FORMAT.sampleRate), channels: String(AUDIO_FORMAT.channels), }); return this.call(WakeResponse, 'POST', `/v1/wake?${query}`, { binary: args.pcm }); } /** * The words in a recording still being made, for showing while the user speaks. Creates * nothing on the bridge. A bridge without it answers `not_found`. */ transcribe(args: { locale: string; pcm: Uint8Array }): Promise { const query = new URLSearchParams({ schema_version: String(SCHEMA_VERSION), locale: args.locale, encoding: AUDIO_FORMAT.encoding, sample_rate: String(AUDIO_FORMAT.sampleRate), channels: String(AUDIO_FORMAT.channels), }); return this.call(TranscribeResponse, 'POST', `/v1/transcribe?${query}`, { binary: args.pcm }); } getTurn(requestId: string): Promise { return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise; } cancelTurn(requestId: string): Promise { return this.call(TurnResult, 'POST', `/v1/turns/${requestId}/cancel`, { json: {} }) as Promise; } }