First vertical slice: Even client, bridge, contract v1, tests, docs
Client (apps/even-client): pure interaction reducer with generation-based stale-result rejection, HUD renderer, measured pagination, Even Hub SDK 0.0.16 adapter, bridge HTTP client, phone pairing/status/diagnostics page. Bridge (services/bridge): device pairing and revocable expiring credentials, turn engine with idempotent submit, cancel, deadlines and restart recovery, Hermes Runs API adapter, OpenAI-compatible STT adapter, operator CLI. Contract (packages/contracts): versioned schemas, types and error codes. Tests: 122 unit/integration (fakes), 6 simulator scenarios (Even Hub simulator 0.9.5), 9 scenarios against a real Hermes v0.23.1 gateway with a stub model. No real STT, real model or physical device has been exercised; see docs/test-evidence.md and docs/device-test-plan.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
check,
|
||||
ConversationResponse,
|
||||
DeviceCredential,
|
||||
DeviceStatusResponse,
|
||||
ErrorResponse,
|
||||
RevokeResponse,
|
||||
SCHEMA_VERSION,
|
||||
TurnResult,
|
||||
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;
|
||||
}
|
||||
|
||||
export function normalizeBridgeUrl(raw: string): string {
|
||||
const url = new URL(raw.trim());
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bridge URL must start with https://');
|
||||
return url.origin + url.pathname.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
createConversation(): Promise<ConversationResponse> {
|
||||
return this.call(ConversationResponse, 'POST', '/v1/conversations', { json: { schema_version: SCHEMA_VERSION } });
|
||||
}
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
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>;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user