While a recording is being made the app sends the recording so far to a new bridge route, POST /v1/transcribe, about every half second of new audio and one request at a time, and draws the words under "... is listening…", newest words kept in view. No new service: it is the Whisper already in the bridge. A preview is only ever drawn. The question is transcribed again by its own turn, so a preview can never be what the agent receives. After sending, the last preview stays under "Transcribing…", then "Heard:" shows the transcript the bridge gave the agent, now for every spoken question (it was hands free only). The reducer tracks `spoken` explicitly and treats an accepted, not yet transcribed recording as transcribing. Bridge: /v1/transcribe needs a device credential, shares the audio checks with /v1/wake, runs one at a time per device within HERMEVEN_PREVIEWS_PER_MINUTE (60), creates nothing and logs no text. An older bridge answers 404 and the client stops asking. Simulator: a scenario that launches the app as shipped (menu, hands free) as Round 18 required. A diagnostics note marks when listening for a name starts and stops. Also records the 0.3.0 deployment, upload and Dan's device report (docs/evidence/device/2026-11-28.md), and decision 0005. Not reviewed, not deployed, not uploaded, not device-tested. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
218 lines
7.8 KiB
TypeScript
218 lines
7.8 KiB
TypeScript
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<T extends TSchema>(
|
|
schema: T,
|
|
method: string,
|
|
path: string,
|
|
init: { json?: unknown; binary?: Uint8Array; auth?: boolean } = {},
|
|
): Promise<T['static']> {
|
|
const headers: Record<string, string> = { 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<DeviceCredential> {
|
|
return this.call(DeviceCredential, 'POST', '/v1/pairing/claim', {
|
|
auth: false,
|
|
json: { schema_version: SCHEMA_VERSION, code, device_name: deviceName },
|
|
});
|
|
}
|
|
|
|
device(): Promise<DeviceStatusResponse> {
|
|
return this.call(DeviceStatusResponse, 'GET', '/v1/device');
|
|
}
|
|
|
|
renew(): Promise<DeviceCredential> {
|
|
return this.call(DeviceCredential, 'POST', '/v1/device/renew', { json: {} });
|
|
}
|
|
|
|
revoke(): Promise<RevokeResponse> {
|
|
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<AgentsResponse> {
|
|
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<ConversationResponse> {
|
|
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<TurnResult> {
|
|
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<TurnResult>;
|
|
}
|
|
|
|
/** 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<TurnResult> {
|
|
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<TurnResult>;
|
|
}
|
|
|
|
/**
|
|
* 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<WakeResponse> {
|
|
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<TranscribeResponse> {
|
|
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<TurnResult> {
|
|
return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise<TurnResult>;
|
|
}
|
|
|
|
cancelTurn(requestId: string): Promise<TurnResult> {
|
|
return this.call(TurnResult, 'POST', `/v1/turns/${requestId}/cancel`, { json: {} }) as Promise<TurnResult>;
|
|
}
|
|
}
|