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,44 @@
|
||||
# Hermeven bridge configuration. Copy to `.env` (ignored by git) on the bridge host.
|
||||
# Nothing in this file belongs in the client app or in the repository.
|
||||
|
||||
# --- Hermes (required) -------------------------------------------------------
|
||||
# Base URL of the Hermes API server. For multi-profile routing use .../p/<profile>.
|
||||
HERMES_BASE_URL=http://127.0.0.1:8642
|
||||
# The API_SERVER_KEY of that Hermes profile. Stays on the bridge host only.
|
||||
HERMES_API_KEY=replace-with-your-hermes-api-server-key
|
||||
# A label for the profile this bridge serves. Devices are bound to it.
|
||||
HERMES_PROFILE_LABEL=default
|
||||
|
||||
# --- Bridge listener ---------------------------------------------------------
|
||||
# Loopback by default. A phone reaches it through a TLS-terminating reverse proxy or a
|
||||
# private network (for example Tailscale). Binding a non-loopback address needs the
|
||||
# explicit acknowledgement below; the bridge itself does not terminate TLS.
|
||||
HERMEVEN_HOST=127.0.0.1
|
||||
HERMEVEN_PORT=8787
|
||||
# HERMEVEN_ALLOW_NON_LOOPBACK=true
|
||||
# HERMEVEN_TRUST_PROXY=true
|
||||
HERMEVEN_DB_PATH=./data/hermeven.sqlite
|
||||
|
||||
# Exact origins of the page that calls the bridge (comma separated, no wildcards).
|
||||
# Read the real value from Diagnostics -> "Page origin" in the phone page.
|
||||
HERMEVEN_ALLOWED_ORIGINS=
|
||||
|
||||
# --- Speech-to-text (optional; typed questions work without it) --------------
|
||||
# "none" or "openai-compatible" (any server with POST {base}/audio/transcriptions).
|
||||
STT_PROVIDER=none
|
||||
# STT_BASE_URL=https://stt.example/v1
|
||||
# STT_API_KEY=replace-with-your-stt-key
|
||||
# STT_MODEL=whisper-1
|
||||
|
||||
# --- Budgets (defaults shown) ------------------------------------------------
|
||||
# HERMEVEN_CAPTURE_MAX_SECONDS=30
|
||||
# HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS=30
|
||||
# HERMEVEN_AGENT_DEADLINE_SECONDS=120
|
||||
# HERMEVEN_APPROVAL_WAIT_SECONDS=300
|
||||
# HERMEVEN_RESULT_RETENTION_SECONDS=900
|
||||
# HERMEVEN_TOKEN_TTL_SECONDS=604800
|
||||
# HERMEVEN_PAIRING_TTL_SECONDS=7776000
|
||||
|
||||
# Per-request instructions layered on the agent's own prompt (not stored in history).
|
||||
# Leave unset for the default "answer briefly in plain text" guidance; set empty to send none.
|
||||
# HERMEVEN_INSTRUCTIONS=
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.ehpk
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.sqlite
|
||||
*.sqlite-wal
|
||||
*.sqlite-shm
|
||||
data/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
# simulator screenshots are evidence only when deliberately copied into docs/
|
||||
tests/simulator/.artifacts/
|
||||
tests/real-hermes/.artifacts/
|
||||
dist-manifest/
|
||||
@@ -0,0 +1,101 @@
|
||||
# Hermeven
|
||||
|
||||
Hermeven makes Even Realities G2 glasses an interface to a Hermes Agent that you run yourself.
|
||||
Tap, ask a question out loud, read a short answer on the display, ask a follow-up.
|
||||
|
||||
Even supplies the microphone, gestures and display. Hermes stays in charge of the agent: its
|
||||
identity, memory, conversation, model, tools and approval rules. Hermeven is the glasses app and a
|
||||
small bridge between the two.
|
||||
|
||||
## Status: first software slice, not yet run on glasses
|
||||
|
||||
| Path | State |
|
||||
|---|---|
|
||||
| Client, bridge and contract | Implemented. |
|
||||
| Automated tests with fakes (122) | Passing. |
|
||||
| Client in Even's official simulator | Passing (6 scenarios). Simulator only. |
|
||||
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
|
||||
| Real speech-to-text | **Not run.** No provider was configured. |
|
||||
| Real model, real tools, approval flow | **Not run.** |
|
||||
| Physical G2, ring, locked-phone use, battery | **Not run.** See `docs/device-test-plan.md`. |
|
||||
|
||||
The product's first goal needs the microphone to work while the phone is locked in a pocket.
|
||||
Even's documentation says capture stops if the app's WebView is suspended. That is the first
|
||||
thing to test on a device and it is not known to work.
|
||||
|
||||
## How it fits together
|
||||
|
||||
```
|
||||
G2 <-Bluetooth-> Even phone app (WebView: apps/even-client)
|
||||
| HTTPS + device credential
|
||||
services/bridge --> speech-to-text endpoint you choose
|
||||
|
|
||||
your Hermes API server
|
||||
```
|
||||
|
||||
- `packages/contracts`: the versioned bridge contract (schemas, types, error codes).
|
||||
- `services/bridge`: pairing, the turn lifecycle, the Hermes and STT adapters, the operator CLI.
|
||||
- `apps/even-client`: the glasses app and its phone page.
|
||||
- `tests`: fakes, integration, simulator and real-Hermes suites.
|
||||
|
||||
## Quick start (no glasses needed)
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
cp .env.example .env # set HERMES_API_KEY; add HERMEVEN_ALLOWED_ORIGINS=http://localhost:5173
|
||||
npm run bridge # terminal 1
|
||||
npm run client:dev # terminal 2, then open http://localhost:5173
|
||||
npm run bridge:cli -- pair # terminal 3: prints a one-time pairing code
|
||||
```
|
||||
|
||||
Enter `http://127.0.0.1:8787` and the code in the page, then use "Typed question". Full
|
||||
instructions, including building for the glasses, are in `docs/setup.md`.
|
||||
|
||||
## Using it on the glasses
|
||||
|
||||
| You do | It does |
|
||||
|---|---|
|
||||
| Tap | Start recording. The display shows `● REC` and a timer the whole time. |
|
||||
| Tap again | Stop and send. Recording also stops by itself after 30 seconds. |
|
||||
| Swipe down / up | Next / previous page of the answer. |
|
||||
| Tap on an answer | Ask a follow-up in the same conversation. |
|
||||
| Double tap | Cancel what is in progress, or go back. At "Ready" it opens the system exit dialog. |
|
||||
| Tap, then long press | The system menu, with "New conversation" and "Cancel request". |
|
||||
|
||||
Cancelling stops the agent as soon as Hermes can; it does not undo anything the agent already did.
|
||||
If the agent needs an approval, the display says so and you approve it where you normally manage
|
||||
the agent. Hermeven never approves anything for you.
|
||||
|
||||
These gestures are a first binding and have only been exercised in the simulator.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm test # unit and integration, fakes only
|
||||
npm run test:simulator # opens Even's simulator window
|
||||
npm run test:real-hermes # real `hermes gateway` in a throwaway home, stub model
|
||||
```
|
||||
|
||||
What each suite does and does not show is in `docs/test-evidence.md`.
|
||||
|
||||
## Documentation
|
||||
|
||||
| Document | Contents |
|
||||
|---|---|
|
||||
| `docs/feasibility.md` | What Even and Hermes actually provide, with sources and a status for each claim. |
|
||||
| `docs/compatibility.md` | Versions used and tested. |
|
||||
| `docs/architecture.md` | Components, state machine, how ambiguous outcomes are classified. |
|
||||
| `docs/bridge-api.md` | The bridge contract. |
|
||||
| `docs/security.md` | Threat model, controls, known gaps. |
|
||||
| `docs/setup.md` | Running, building, operating. |
|
||||
| `docs/device-test-plan.md` | The physical-device checklist. Not yet run. |
|
||||
| `docs/test-evidence.md` | Commands run and their real results. |
|
||||
| `docs/decisions/` | Decision records. |
|
||||
| `docs/handoff/` | Review handoffs. |
|
||||
| `docs/build-in-public/` | Unpublished drafts. Nothing is published automatically. |
|
||||
|
||||
## Not in this slice
|
||||
|
||||
Wake words, always-on listening, camera features, text-to-speech, multiple agents, billing, store
|
||||
launch, and running alongside Even's native captions (the public SDK does not offer it).
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"package_id": "gg.xylo.hermeven",
|
||||
"edition": "202601",
|
||||
"name": "Hermeven",
|
||||
"version": "0.1.0",
|
||||
"min_sdk_version": "0.0.16",
|
||||
"entrypoint": "index.html",
|
||||
"permissions": [
|
||||
{
|
||||
"name": "network",
|
||||
"desc": "Sends your question to the Hermeven bridge you paired with and receives the answer.",
|
||||
"whitelist": ["__HERMEVEN_BRIDGE_ORIGIN__"]
|
||||
},
|
||||
{
|
||||
"name": "g2-microphone",
|
||||
"desc": "Records your question from the glasses microphone, only while you have tapped to ask."
|
||||
}
|
||||
],
|
||||
"supported_languages": ["en"]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
|
||||
/>
|
||||
<title>Hermeven</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<div id="preview" hidden></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@hermeven/even-client",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit -p . && vite build && node scripts/write-manifest.mjs",
|
||||
"pack": "npm run build && evenhub pack dist-manifest/app.json dist -o hermeven.ehpk --sdk-ver 0.0.16",
|
||||
"simulate": "node ../../node_modules/@evenrealities/evenhub-simulator/bin/index.js http://localhost:5173",
|
||||
"qr": "evenhub qr"
|
||||
},
|
||||
"dependencies": {
|
||||
"@evenrealities/even_hub_sdk": "0.0.16",
|
||||
"@evenrealities/pretext": "0.1.4",
|
||||
"@hermeven/contracts": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@evenrealities/evenhub-cli": "0.2.0",
|
||||
"@evenrealities/evenhub-simulator": "0.9.5",
|
||||
"vite": "^8.3.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Writes dist-manifest/app.json from app.template.json.
|
||||
//
|
||||
// Even Hub enforces a per-app network whitelist of exact origins, so the bridge
|
||||
// origin has to be in the packaged manifest. It is supplied at build time and is
|
||||
// never committed: no deployment hostname lives in this repository.
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const raw = process.env.HERMEVEN_BRIDGE_ORIGIN ?? '';
|
||||
if (!raw) {
|
||||
console.warn('[manifest] HERMEVEN_BRIDGE_ORIGIN is not set: skipping app.json. Set it before `npm run pack`.');
|
||||
process.exit(0);
|
||||
}
|
||||
let origin;
|
||||
try {
|
||||
origin = new URL(raw).origin;
|
||||
} catch {
|
||||
console.error('[manifest] HERMEVEN_BRIDGE_ORIGIN is not a URL.');
|
||||
process.exit(1);
|
||||
}
|
||||
if (origin !== raw) {
|
||||
console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!origin.startsWith('https://')) {
|
||||
console.warn('[manifest] The bridge origin is not https. Acceptable only for a local development build.');
|
||||
}
|
||||
const template = readFileSync(resolve(here, '../app.template.json'), 'utf8');
|
||||
const out = resolve(here, '../dist-manifest/app.json');
|
||||
mkdirSync(dirname(out), { recursive: true });
|
||||
writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin));
|
||||
console.log(`[manifest] wrote ${out}`);
|
||||
@@ -0,0 +1,663 @@
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS, type DeviceStatusResponse, type TurnResult } from '@hermeven/contracts';
|
||||
import { MENU_ITEM, type DeviceEvent } from '../device/events.ts';
|
||||
import type { DevicePort } from '../device/port.ts';
|
||||
import { BridgeApiError, BridgeClient, BridgeNetworkError } from '../net/bridgeClient.ts';
|
||||
import { BODY_BOX, HUD, renderHud } from './hud.ts';
|
||||
import { paginate, type MeasureLines } from './paginate.ts';
|
||||
import { toPlainText } from './plaintext.ts';
|
||||
import { initialState, reduce, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
|
||||
|
||||
const STORAGE_KEY = 'hermeven.v1';
|
||||
|
||||
interface Stored {
|
||||
bridgeUrl: string;
|
||||
token: string;
|
||||
deviceId: string;
|
||||
tokenExpiresAt: string;
|
||||
pairingExpiresAt: string;
|
||||
conversationId: string | null;
|
||||
/** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */
|
||||
activeRequestId: string | null;
|
||||
}
|
||||
|
||||
export interface DiagEntry {
|
||||
at: number;
|
||||
kind: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface Snapshot {
|
||||
state: AppState;
|
||||
paired: boolean;
|
||||
bridgeUrl: string;
|
||||
deviceId: string;
|
||||
tokenExpiresAt: string;
|
||||
pairingExpiresAt: string;
|
||||
status: DeviceStatusResponse | null;
|
||||
hudReady: boolean;
|
||||
/** Last settled turn, complete and untruncated, for the phone. */
|
||||
lastTurn: TurnResult | null;
|
||||
log: DiagEntry[];
|
||||
}
|
||||
|
||||
export interface ControllerOptions {
|
||||
device: DevicePort;
|
||||
measure: MeasureLines;
|
||||
locale: string;
|
||||
newId?: () => string;
|
||||
now?: () => number;
|
||||
makeClient?: (baseUrl: string, token: string) => BridgeClient;
|
||||
onChange?: (snapshot: Snapshot) => void;
|
||||
/** Receives each diagnostic entry (ids, codes, timings; never content). */
|
||||
onNote?: (entry: DiagEntry) => void;
|
||||
pollIntervalMs?: number;
|
||||
submitAttempts?: number;
|
||||
submitRetryMs?: number;
|
||||
/** No audio frames for this long while recording means the microphone is gone. */
|
||||
micStallMs?: number;
|
||||
}
|
||||
|
||||
interface Capture {
|
||||
generation: number;
|
||||
chunks: Uint8Array[];
|
||||
bytes: number;
|
||||
maxBytes: number;
|
||||
lastFrameAt: number;
|
||||
limitSent: boolean;
|
||||
}
|
||||
|
||||
type PendingInput = { requestId: string; kind: 'text'; text: string } | { requestId: string; kind: 'audio'; pcm: Uint8Array };
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
export class Controller {
|
||||
private state: AppState = initialState;
|
||||
private stored: Stored | null = null;
|
||||
private client: BridgeClient | null = null;
|
||||
private status: DeviceStatusResponse | null = null;
|
||||
private capture: Capture | null = null;
|
||||
private micOpen = false;
|
||||
private pending: PendingInput | null = null;
|
||||
private lastTurn: TurnResult | null = null;
|
||||
private hudReady = false;
|
||||
private stopped = false;
|
||||
private ticker: ReturnType<typeof setInterval> | null = null;
|
||||
private readonly log: DiagEntry[] = [];
|
||||
private readonly unsubscribers: Array<() => void> = [];
|
||||
|
||||
private readonly device: DevicePort;
|
||||
private readonly now: () => number;
|
||||
private readonly newId: () => string;
|
||||
private readonly pollIntervalMs: number;
|
||||
private readonly submitAttempts: number;
|
||||
private readonly submitRetryMs: number;
|
||||
private readonly micStallMs: number;
|
||||
|
||||
constructor(private readonly options: ControllerOptions) {
|
||||
this.device = options.device;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.newId = options.newId ?? (() => crypto.randomUUID());
|
||||
this.pollIntervalMs = options.pollIntervalMs ?? 700;
|
||||
this.submitAttempts = options.submitAttempts ?? 4;
|
||||
this.submitRetryMs = options.submitRetryMs ?? 1500;
|
||||
this.micStallMs = options.micStallMs ?? 3000;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ public
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.stored = await this.load();
|
||||
this.hudReady = await this.device.init(renderHud(this.state, this.now()));
|
||||
this.note('hud', this.hudReady ? 'HUD page created' : 'HUD page was refused by the host');
|
||||
this.unsubscribers.push(
|
||||
this.device.onEvent((event) => this.onDeviceEvent(event)),
|
||||
this.device.onConnection((connected) => {
|
||||
this.note('glasses', connected ? 'connected' : 'disconnected');
|
||||
this.dispatch({ type: 'glasses_status', connected });
|
||||
}),
|
||||
);
|
||||
|
||||
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
|
||||
if (this.stored) {
|
||||
this.client = this.makeClient(this.stored.bridgeUrl, this.stored.token);
|
||||
try {
|
||||
this.status = await this.client.device();
|
||||
captureMaxSeconds = this.status.limits.capture_max_seconds;
|
||||
await this.maybeRenew();
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError && (err.body.code === 'unauthorized' || err.body.code === 'credential_expired')) {
|
||||
this.note('auth', `stored credential rejected: ${err.body.code}`);
|
||||
await this.forget();
|
||||
} else {
|
||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.dispatch({
|
||||
type: 'init',
|
||||
paired: this.stored !== null,
|
||||
conversationId: this.stored?.conversationId ?? null,
|
||||
captureMaxSeconds,
|
||||
resumeRequestId: this.stored?.activeRequestId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true;
|
||||
for (const off of this.unsubscribers.splice(0)) off();
|
||||
this.stopTicker();
|
||||
await this.closeMic();
|
||||
}
|
||||
|
||||
snapshot(): Snapshot {
|
||||
return {
|
||||
state: this.state,
|
||||
paired: this.stored !== null,
|
||||
bridgeUrl: this.stored?.bridgeUrl ?? '',
|
||||
deviceId: this.stored?.deviceId ?? '',
|
||||
tokenExpiresAt: this.stored?.tokenExpiresAt ?? '',
|
||||
pairingExpiresAt: this.stored?.pairingExpiresAt ?? '',
|
||||
status: this.status,
|
||||
hudReady: this.hudReady,
|
||||
lastTurn: this.lastTurn,
|
||||
log: [...this.log],
|
||||
};
|
||||
}
|
||||
|
||||
/** Explicit pairing from the phone. Throws with a user-presentable message on failure. */
|
||||
async pair(bridgeUrl: string, code: string, deviceName: string): Promise<void> {
|
||||
const client = this.makeClient(bridgeUrl, '');
|
||||
const credential = await client.claim(code, deviceName);
|
||||
client.token = credential.token;
|
||||
this.client = client;
|
||||
this.stored = {
|
||||
bridgeUrl,
|
||||
token: credential.token,
|
||||
deviceId: credential.device_id,
|
||||
tokenExpiresAt: credential.token_expires_at,
|
||||
pairingExpiresAt: credential.pairing_expires_at,
|
||||
conversationId: null,
|
||||
activeRequestId: null,
|
||||
};
|
||||
await this.save();
|
||||
this.note('pairing', `paired as ${credential.device_id}`);
|
||||
let captureMaxSeconds: number = DEFAULT_LIMITS.captureMaxSeconds;
|
||||
try {
|
||||
this.status = await client.device();
|
||||
captureMaxSeconds = this.status.limits.capture_max_seconds;
|
||||
} catch (err) {
|
||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||
}
|
||||
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null });
|
||||
}
|
||||
|
||||
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
|
||||
async disconnect(): Promise<{ revoked: boolean }> {
|
||||
let revoked = false;
|
||||
try {
|
||||
await this.client?.revoke();
|
||||
revoked = true;
|
||||
} catch (err) {
|
||||
// Local state is cleared regardless; the phone tells the user to revoke on the bridge.
|
||||
this.note('pairing', `remote revoke failed: ${describe(err)}`);
|
||||
}
|
||||
await this.forget();
|
||||
this.dispatch({ type: 'unpaired' });
|
||||
return { revoked };
|
||||
}
|
||||
|
||||
async renew(): Promise<void> {
|
||||
if (!this.client || !this.stored) return;
|
||||
const credential = await this.client.renew();
|
||||
this.client.token = credential.token;
|
||||
this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at };
|
||||
await this.save();
|
||||
this.note('pairing', 'credential renewed');
|
||||
this.emit();
|
||||
}
|
||||
|
||||
async refreshStatus(): Promise<void> {
|
||||
if (!this.client) return;
|
||||
try {
|
||||
this.status = await this.client.device();
|
||||
} catch (err) {
|
||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
|
||||
askText(text: string): void {
|
||||
const trimmed = text.trim();
|
||||
if (trimmed) this.dispatch({ type: 'submit_text', freshId: this.newId(), text: trimmed });
|
||||
}
|
||||
|
||||
newConversation(): void {
|
||||
this.dispatch({ type: 'new_conversation' });
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.dispatch({ type: 'cancel' });
|
||||
}
|
||||
|
||||
dispatch(event: AppEvent): void {
|
||||
if (this.stopped) return;
|
||||
const before = this.state;
|
||||
const step = reduce(before, event);
|
||||
this.state = step.state;
|
||||
if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`);
|
||||
for (const effect of step.effects) void this.run(effect);
|
||||
this.render();
|
||||
this.emit();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- effects
|
||||
|
||||
private async run(effect: Effect): Promise<void> {
|
||||
try {
|
||||
switch (effect.type) {
|
||||
case 'start_capture':
|
||||
return await this.startCapture(effect.generation);
|
||||
case 'stop_capture_and_submit':
|
||||
return await this.stopCaptureAndSubmit(effect.generation, effect.requestId);
|
||||
case 'discard_capture':
|
||||
this.capture = null;
|
||||
this.pending = null;
|
||||
return await this.closeMic();
|
||||
case 'submit_text':
|
||||
this.pending = { requestId: effect.requestId, kind: 'text', text: effect.text };
|
||||
return await this.submit(effect.generation, effect.requestId);
|
||||
case 'resubmit':
|
||||
return await this.submit(effect.generation, effect.requestId);
|
||||
case 'poll':
|
||||
return await this.poll(effect.generation, effect.requestId);
|
||||
case 'cancel_turn':
|
||||
return await this.cancelTurn(effect.requestId);
|
||||
case 'create_conversation':
|
||||
return await this.createConversation(effect.generation);
|
||||
case 'exit_dialog':
|
||||
return await this.device.requestExit();
|
||||
}
|
||||
} catch (err) {
|
||||
this.note('internal', `effect ${effect.type} failed: ${describe(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async startCapture(generation: number): Promise<void> {
|
||||
const capture: Capture = {
|
||||
generation,
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
maxBytes: this.state.captureMaxSeconds * AUDIO_FORMAT.bytesPerSecond,
|
||||
lastFrameAt: this.now(),
|
||||
limitSent: false,
|
||||
};
|
||||
this.capture = capture;
|
||||
this.micOpen = true;
|
||||
const ok = await this.device.startMic();
|
||||
if (this.capture !== capture) {
|
||||
// Cancelled while the microphone was opening.
|
||||
if (!this.capture) await this.closeMic();
|
||||
return;
|
||||
}
|
||||
if (!ok) {
|
||||
this.capture = null;
|
||||
this.micOpen = false;
|
||||
this.dispatch({ type: 'capture_failed', generation, reason: 'mic_refused' });
|
||||
return;
|
||||
}
|
||||
capture.lastFrameAt = this.now();
|
||||
this.dispatch({ type: 'capture_started', generation, at: this.now() });
|
||||
this.startTicker();
|
||||
}
|
||||
|
||||
private onAudio(pcm: Uint8Array): void {
|
||||
const capture = this.capture;
|
||||
// Frames outside an active, current-generation capture are dropped on the floor.
|
||||
if (!capture || capture.generation !== this.state.generation || this.state.phase !== 'listening') return;
|
||||
capture.lastFrameAt = this.now();
|
||||
const room = capture.maxBytes - capture.bytes;
|
||||
if (room > 0) {
|
||||
const chunk = pcm.length > room ? pcm.slice(0, room) : pcm.slice();
|
||||
capture.chunks.push(chunk);
|
||||
capture.bytes += chunk.length;
|
||||
}
|
||||
if (capture.bytes >= capture.maxBytes && !capture.limitSent) {
|
||||
capture.limitSent = true;
|
||||
this.note('capture', 'capture limit reached');
|
||||
this.dispatch({ type: 'capture_limit', generation: capture.generation });
|
||||
}
|
||||
}
|
||||
|
||||
private async stopCaptureAndSubmit(generation: number, requestId: string): Promise<void> {
|
||||
const capture = this.capture;
|
||||
this.capture = null;
|
||||
this.stopTicker();
|
||||
await this.closeMic();
|
||||
if (!capture || capture.generation !== generation) return;
|
||||
const usable = capture.bytes - (capture.bytes % 2);
|
||||
if (usable === 0) {
|
||||
this.dispatch({ type: 'capture_failed', generation, reason: 'empty' });
|
||||
return;
|
||||
}
|
||||
const pcm = new Uint8Array(usable);
|
||||
let offset = 0;
|
||||
for (const chunk of capture.chunks) {
|
||||
const take = Math.min(chunk.length, usable - offset);
|
||||
pcm.set(chunk.subarray(0, take), offset);
|
||||
offset += take;
|
||||
}
|
||||
this.note('capture', `captured ${(usable / AUDIO_FORMAT.bytesPerSecond).toFixed(1)} s`);
|
||||
this.pending = { requestId, kind: 'audio', pcm };
|
||||
await this.submit(generation, requestId);
|
||||
}
|
||||
|
||||
private async closeMic(): Promise<void> {
|
||||
if (!this.micOpen) return;
|
||||
this.micOpen = false;
|
||||
this.stopTicker();
|
||||
await this.device.stopMic();
|
||||
}
|
||||
|
||||
private stale(generation: number): boolean {
|
||||
return this.stopped || generation !== this.state.generation;
|
||||
}
|
||||
|
||||
private async ensureConversation(): Promise<string> {
|
||||
if (this.state.conversationId) return this.state.conversationId;
|
||||
const created = await this.client!.createConversation();
|
||||
if (this.stored) {
|
||||
this.stored = { ...this.stored, conversationId: created.conversation_id };
|
||||
await this.save();
|
||||
}
|
||||
this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id });
|
||||
return created.conversation_id;
|
||||
}
|
||||
|
||||
private async submit(generation: number, requestId: string): Promise<void> {
|
||||
const pending = this.pending;
|
||||
if (!this.client || !pending || pending.requestId !== requestId) return;
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
if (this.stale(generation)) return;
|
||||
try {
|
||||
const conversationId = await this.ensureConversation();
|
||||
if (this.stale(generation)) return;
|
||||
const base = { requestId, conversationId, locale: this.options.locale };
|
||||
// The same request id on every attempt: the bridge deduplicates, so a retry after a
|
||||
// lost response cannot create a second turn.
|
||||
const result =
|
||||
pending.kind === 'text'
|
||||
? await this.client.submitText({ ...base, text: pending.text })
|
||||
: await this.client.submitAudio({ ...base, pcm: pending.pcm });
|
||||
if (this.pending === pending) this.pending = null;
|
||||
if (this.stale(generation)) {
|
||||
// Cancelled while the request was on the wire: the cancel may have beaten it there.
|
||||
void this.cancelTurn(requestId);
|
||||
return;
|
||||
}
|
||||
await this.setActiveRequest(requestId);
|
||||
this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`);
|
||||
this.onResult(generation, result);
|
||||
if (!result.terminal) await this.poll(generation, requestId);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError) {
|
||||
this.note('turn', `rejected: ${err.body.code}`);
|
||||
this.pending = null;
|
||||
if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
|
||||
await this.afterAuthFailure(err);
|
||||
return;
|
||||
}
|
||||
if (!(err instanceof BridgeNetworkError)) throw err;
|
||||
this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`);
|
||||
if (attempt >= this.submitAttempts) {
|
||||
if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' });
|
||||
return;
|
||||
}
|
||||
await sleep(this.submitRetryMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async poll(generation: number, requestId: string): Promise<void> {
|
||||
if (!this.client) return;
|
||||
let failures = 0;
|
||||
for (;;) {
|
||||
await sleep(failures ? Math.min(5000, this.pollIntervalMs * 2 ** Math.min(failures, 3)) : this.pollIntervalMs);
|
||||
if (this.stale(generation)) return;
|
||||
try {
|
||||
const result = await this.client.getTurn(requestId);
|
||||
if (this.stale(generation)) return;
|
||||
if (failures >= 3) this.dispatch({ type: 'network_restored', generation });
|
||||
failures = 0;
|
||||
this.onResult(generation, result);
|
||||
if (result.terminal) return;
|
||||
} catch (err) {
|
||||
if (this.stale(generation)) return;
|
||||
if (err instanceof BridgeApiError) {
|
||||
this.note('turn', `status rejected: ${err.body.code}`);
|
||||
await this.setActiveRequest(null);
|
||||
this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
|
||||
await this.afterAuthFailure(err);
|
||||
return;
|
||||
}
|
||||
if (!(err instanceof BridgeNetworkError)) throw err;
|
||||
failures += 1;
|
||||
if (failures === 3) {
|
||||
this.note('bridge', 'lost contact while waiting for the answer');
|
||||
this.dispatch({ type: 'network_lost', generation, stage: 'poll' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onResult(generation: number, result: TurnResult): void {
|
||||
let pages: string[] | null = null;
|
||||
if (result.terminal) {
|
||||
this.lastTurn = result;
|
||||
void this.setActiveRequest(null);
|
||||
this.note(
|
||||
'turn',
|
||||
`done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` +
|
||||
` stt=${result.timings.transcribe_ms ?? '-'}ms agent=${result.timings.agent_ms ?? '-'}ms`,
|
||||
);
|
||||
if (result.outcome === 'succeeded' || result.outcome === 'incomplete') {
|
||||
const plain = toPlainText(result.answer_text ?? '') || '(The agent returned no text.)';
|
||||
const started = this.now();
|
||||
pages = paginate(
|
||||
plain,
|
||||
{ width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes },
|
||||
this.options.measure,
|
||||
);
|
||||
this.note('hud', `answer laid out on ${pages.length} page(s) in ${this.now() - started} ms`);
|
||||
}
|
||||
}
|
||||
this.dispatch({ type: 'turn_update', generation, result, pages });
|
||||
}
|
||||
|
||||
private async cancelTurn(requestId: string): Promise<void> {
|
||||
await this.setActiveRequest(null);
|
||||
if (!this.client) return;
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
const result = await this.client.cancelTurn(requestId);
|
||||
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
|
||||
return;
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError) {
|
||||
// not_found: the request never reached the bridge, so there is nothing to cancel.
|
||||
this.note('turn', `cancel answered ${err.body.code}`);
|
||||
return;
|
||||
}
|
||||
await sleep(this.submitRetryMs);
|
||||
}
|
||||
}
|
||||
this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`);
|
||||
}
|
||||
|
||||
private async createConversation(generation: number): Promise<void> {
|
||||
if (!this.client) return;
|
||||
try {
|
||||
const created = await this.client.createConversation();
|
||||
if (this.stored) {
|
||||
this.stored = { ...this.stored, conversationId: created.conversation_id };
|
||||
await this.save();
|
||||
}
|
||||
this.note('conversation', `new conversation ${created.conversation_id}`);
|
||||
this.dispatch({ type: 'conversation_created', generation, conversationId: created.conversation_id });
|
||||
} catch (err) {
|
||||
const error: HudError =
|
||||
err instanceof BridgeApiError
|
||||
? this.hudError(err)
|
||||
: { code: 'network', hud: 'Could not reach the bridge.', retryable: true };
|
||||
this.note('conversation', `create failed: ${describe(err)}`);
|
||||
this.dispatch({ type: 'conversation_failed', generation, error });
|
||||
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ device
|
||||
|
||||
private onDeviceEvent(event: DeviceEvent): void {
|
||||
switch (event.type) {
|
||||
case 'audio':
|
||||
return this.onAudio(event.pcm);
|
||||
case 'tap':
|
||||
return this.dispatch({ type: 'activate', freshId: this.newId() });
|
||||
case 'double_tap':
|
||||
return this.dispatch({ type: 'back' });
|
||||
case 'swipe_down':
|
||||
return this.dispatch({ type: 'next_page' });
|
||||
case 'swipe_up':
|
||||
return this.dispatch({ type: 'prev_page' });
|
||||
case 'menu':
|
||||
if (event.itemId === MENU_ITEM.NEW_CONVERSATION) return this.dispatch({ type: 'new_conversation' });
|
||||
if (event.itemId === MENU_ITEM.CANCEL) return this.dispatch({ type: 'cancel' });
|
||||
return;
|
||||
case 'system_exit':
|
||||
case 'abnormal_exit':
|
||||
this.note('lifecycle', event.type);
|
||||
return this.dispatch({ type: 'app_exit' });
|
||||
case 'foreground_enter':
|
||||
case 'foreground_exit':
|
||||
// Also fired when the OS menu opens and closes; nothing is torn down here.
|
||||
this.note('lifecycle', event.type);
|
||||
return this.render();
|
||||
}
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
if (this.hudReady && !this.stopped) this.device.show(renderHud(this.state, this.now()));
|
||||
}
|
||||
|
||||
private startTicker(): void {
|
||||
this.stopTicker();
|
||||
this.ticker = setInterval(() => {
|
||||
const capture = this.capture;
|
||||
if (capture && this.state.phase === 'listening' && this.now() - capture.lastFrameAt > this.micStallMs) {
|
||||
// Permission loss or a suspended audio stream both look like silence on the wire.
|
||||
this.note('capture', 'no audio frames; stopping capture');
|
||||
this.dispatch({ type: 'capture_failed', generation: capture.generation, reason: 'mic_stalled' });
|
||||
return;
|
||||
}
|
||||
this.render();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
private stopTicker(): void {
|
||||
if (this.ticker) clearInterval(this.ticker);
|
||||
this.ticker = null;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- helpers
|
||||
|
||||
private makeClient(baseUrl: string, token: string): BridgeClient {
|
||||
return this.options.makeClient?.(baseUrl, token) ?? new BridgeClient({ baseUrl, token });
|
||||
}
|
||||
|
||||
private hudError(err: BridgeApiError): HudError {
|
||||
const code = err.body.code;
|
||||
if (code === 'unauthorized' || code === 'credential_expired') {
|
||||
return { code, hud: 'Not connected. Pair again on your phone.', retryable: false };
|
||||
}
|
||||
if (code === 'conversation_closed') return { code, hud: 'Conversation ended. Start a new one from the menu.', retryable: false };
|
||||
return { code, hud: err.body.message, retryable: err.body.retryable };
|
||||
}
|
||||
|
||||
private async afterAuthFailure(err: BridgeApiError): Promise<void> {
|
||||
if (err.body.code !== 'unauthorized') return;
|
||||
// Revoked or unknown credential: holding on to it helps nobody.
|
||||
await this.forget();
|
||||
this.dispatch({ type: 'unpaired' });
|
||||
}
|
||||
|
||||
private async maybeRenew(): Promise<void> {
|
||||
if (!this.stored) return;
|
||||
const remaining = Date.parse(this.stored.tokenExpiresAt) - this.now();
|
||||
if (Number.isFinite(remaining) && remaining < 2 * 86_400_000) {
|
||||
try {
|
||||
await this.renew();
|
||||
} catch (err) {
|
||||
this.note('pairing', `renewal failed: ${describe(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async setActiveRequest(requestId: string | null): Promise<void> {
|
||||
if (!this.stored || this.stored.activeRequestId === requestId) return;
|
||||
this.stored = { ...this.stored, activeRequestId: requestId };
|
||||
await this.save();
|
||||
}
|
||||
|
||||
private async load(): Promise<Stored | null> {
|
||||
try {
|
||||
const raw = await this.device.storageGet(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as Partial<Stored>;
|
||||
if (typeof parsed.bridgeUrl !== 'string' || typeof parsed.token !== 'string' || !parsed.token) return null;
|
||||
return {
|
||||
bridgeUrl: parsed.bridgeUrl,
|
||||
token: parsed.token,
|
||||
deviceId: String(parsed.deviceId ?? ''),
|
||||
tokenExpiresAt: String(parsed.tokenExpiresAt ?? ''),
|
||||
pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''),
|
||||
conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null,
|
||||
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async save(): Promise<void> {
|
||||
await this.device.storageSet(STORAGE_KEY, this.stored ? JSON.stringify(this.stored) : '');
|
||||
}
|
||||
|
||||
private async forget(): Promise<void> {
|
||||
this.stored = null;
|
||||
this.client = null;
|
||||
this.status = null;
|
||||
this.pending = null;
|
||||
this.lastTurn = null;
|
||||
await this.save();
|
||||
}
|
||||
|
||||
/** Diagnostics for the phone only: ids, codes and timings. Never transcript or answer text. */
|
||||
private note(kind: string, detail: string): void {
|
||||
const entry = { at: this.now(), kind, detail };
|
||||
this.log.push(entry);
|
||||
this.options.onNote?.(entry);
|
||||
if (this.log.length > 200) this.log.splice(0, this.log.length - 200);
|
||||
}
|
||||
|
||||
private emit(): void {
|
||||
if (this.stopped) return;
|
||||
this.options.onChange?.(this.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
function describe(err: unknown): string {
|
||||
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
|
||||
if (err instanceof Error) return `${err.name}: ${err.message}`;
|
||||
return 'unknown error';
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { AppState } from './reducer.ts';
|
||||
|
||||
/**
|
||||
* HUD geometry. Canvas size and line height are documented by Even
|
||||
* (576 x 288 px; 27 px fixed line height); see docs/feasibility.md, "HUD".
|
||||
* Two text containers: a body that takes the gestures, and a one-line status
|
||||
* bar pinned underneath so the recording indicator never scrolls away.
|
||||
*/
|
||||
export const HUD = {
|
||||
width: 576,
|
||||
height: 288,
|
||||
lineHeight: 27,
|
||||
padding: 4,
|
||||
bodyLines: 9,
|
||||
/** Kept well under the firmware's 999-byte create/rebuild limit. */
|
||||
pageMaxBytes: 900,
|
||||
} as const;
|
||||
|
||||
export const BODY_BOX = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: HUD.width,
|
||||
height: HUD.bodyLines * HUD.lineHeight + 2 * HUD.padding, // 251
|
||||
innerWidth: HUD.width - 2 * HUD.padding, // 568
|
||||
} as const;
|
||||
|
||||
export const STATUS_BOX = {
|
||||
x: 0,
|
||||
y: BODY_BOX.height,
|
||||
width: HUD.width,
|
||||
height: HUD.height - BODY_BOX.height, // 37: one 27 px line plus padding
|
||||
} as const;
|
||||
|
||||
export interface HudFrame {
|
||||
body: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
function clock(seconds: number): string {
|
||||
const s = Math.max(0, Math.floor(seconds));
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Pure: the complete HUD text for a state at a moment in time. */
|
||||
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
switch (state.phase) {
|
||||
case 'unpaired':
|
||||
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
||||
|
||||
case 'ready':
|
||||
return {
|
||||
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
|
||||
status: 'Tap: ask · Double-tap: exit',
|
||||
};
|
||||
|
||||
case 'listening': {
|
||||
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
||||
const cap = state.captureMaxSeconds;
|
||||
return {
|
||||
body: `Listening…\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap: send · 2×: cancel`,
|
||||
};
|
||||
}
|
||||
|
||||
case 'transcribing':
|
||||
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'thinking':
|
||||
return { body: 'Thinking…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'approval':
|
||||
return {
|
||||
body: 'Approval required.\n\nThe agent is waiting for you to approve an action. Approve or deny it where you normally manage the agent. It cannot be approved from the glasses.',
|
||||
status: 'Waiting · Double-tap: cancel',
|
||||
};
|
||||
|
||||
case 'answer': {
|
||||
const total = state.pages.length;
|
||||
const page = state.pages[state.pageIndex] ?? '';
|
||||
const position = total > 1 ? `${state.pageIndex + 1}/${total} · Swipe: page · ` : '';
|
||||
const partial = state.partial ? 'PARTIAL · ' : '';
|
||||
return { body: page, status: `${partial}${position}Tap: ask` };
|
||||
}
|
||||
|
||||
case 'cancelled':
|
||||
return {
|
||||
body: 'Cancelled.\n\nAnything the agent had already done is not undone.',
|
||||
status: 'Tap: ask · Double-tap: back',
|
||||
};
|
||||
|
||||
case 'disconnected':
|
||||
if (state.disconnectedFrom === 'glasses') {
|
||||
return { body: 'Glasses disconnected.', status: 'Reconnect to continue' };
|
||||
}
|
||||
return state.canResend
|
||||
? { body: 'No connection to the bridge.\n\nYour request has not been sent.', status: 'Tap: retry · Double-tap: discard' }
|
||||
: { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' };
|
||||
|
||||
case 'error':
|
||||
return {
|
||||
body: `${state.error?.hud ?? 'Something went wrong.'}\n\nDetails are on your phone.`,
|
||||
status: state.error?.retryable ? 'Tap: ask again · Double-tap: back' : 'Double-tap: back',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Split a complete answer into HUD pages without dropping any text.
|
||||
*
|
||||
* Page size comes from measurement, not character counts: `measure` reports
|
||||
* how many firmware lines a string wraps to at the container's inner width
|
||||
* (production uses @evenrealities/pretext, which mirrors the firmware's LVGL
|
||||
* line breaking). A second, independent budget keeps each page under the
|
||||
* firmware's text-container byte limit.
|
||||
*/
|
||||
export interface PageBox {
|
||||
/** Inner width in px: container width minus 2 x (padding + border). */
|
||||
width: number;
|
||||
/** Lines available for answer text on one page. */
|
||||
maxLines: number;
|
||||
/** UTF-8 byte budget for the answer text on one page. */
|
||||
maxBytes: number;
|
||||
}
|
||||
|
||||
export type MeasureLines = (text: string, width: number) => number;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
export function utf8Bytes(text: string): number {
|
||||
return encoder.encode(text).length;
|
||||
}
|
||||
|
||||
/** Grapheme-safe split so surrogate pairs, combining marks and ZWJ sequences stay intact. */
|
||||
function graphemes(text: string): string[] {
|
||||
if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {
|
||||
return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), (s) => s.segment);
|
||||
}
|
||||
return Array.from(text);
|
||||
}
|
||||
|
||||
export function paginate(source: string, box: PageBox, measure: MeasureLines): string[] {
|
||||
const text = source
|
||||
.replace(/\r\n?/g, '\n')
|
||||
.replace(/[ \t]+\n/g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
if (!text) return [''];
|
||||
|
||||
const fits = (candidate: string) =>
|
||||
utf8Bytes(candidate) <= box.maxBytes && measure(candidate, box.width) <= box.maxLines;
|
||||
|
||||
const pages: string[] = [];
|
||||
let page = '';
|
||||
const flush = () => {
|
||||
if (page) pages.push(page);
|
||||
page = '';
|
||||
};
|
||||
|
||||
// Alternating [word, separator, word, ...]; separators are kept verbatim inside a
|
||||
// page (so line breaks survive) and dropped only where a page break replaces them.
|
||||
const tokens = text.split(/(\s+)/);
|
||||
let separator = '';
|
||||
for (const token of tokens) {
|
||||
if (!token) continue;
|
||||
if (/^\s+$/.test(token)) {
|
||||
separator = token;
|
||||
continue;
|
||||
}
|
||||
const candidate = page ? page + separator + token : token;
|
||||
separator = '';
|
||||
if (fits(candidate)) {
|
||||
page = candidate;
|
||||
continue;
|
||||
}
|
||||
flush();
|
||||
if (fits(token)) {
|
||||
page = token;
|
||||
continue;
|
||||
}
|
||||
// One unbroken run longer than a whole page (long URL, unspaced CJK): split by grapheme.
|
||||
let chunk = '';
|
||||
for (const g of graphemes(token)) {
|
||||
if (fits(chunk + g)) {
|
||||
chunk += g;
|
||||
} else if (chunk) {
|
||||
pages.push(chunk);
|
||||
chunk = g;
|
||||
} else {
|
||||
// A single grapheme that cannot fit an empty page: emit it alone rather than lose it.
|
||||
pages.push(g);
|
||||
}
|
||||
}
|
||||
page = chunk;
|
||||
}
|
||||
flush();
|
||||
return pages.length ? pages : [''];
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Convert an agent answer to plain text for the HUD.
|
||||
*
|
||||
* The HUD renders one firmware font with no styling, so Markdown and HTML
|
||||
* markup would show up as literal noise. This only removes markup; it never
|
||||
* shortens or rewords the answer. Unicode is preserved as-is (NFC-normalised);
|
||||
* whether a glyph exists in the firmware font is a device property we cannot
|
||||
* check here (see docs/feasibility.md, "HUD").
|
||||
*/
|
||||
export function toPlainText(input: string): string {
|
||||
let text = input.replace(/\r\n?/g, '\n').normalize('NFC');
|
||||
|
||||
// Fenced code: keep the code, drop the fence lines.
|
||||
text = text.replace(/^[ \t]*(```|~~~)[^\n]*\n?/gm, '');
|
||||
|
||||
// HTML: turn structural breaks into newlines, drop remaining tags, decode common entities.
|
||||
text = text.replace(/<br\s*\/?>/gi, '\n').replace(/<\/(p|div|li|h[1-6])>/gi, '\n');
|
||||
text = text.replace(/<\/?[a-zA-Z][^<>\n]*>/g, '');
|
||||
text = text
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&');
|
||||
|
||||
// Images and links: keep the human-readable part, keep the URL only when it adds information.
|
||||
text = text.replace(/!\[([^\]]*)\]\([^)\s]+(?:\s+"[^"]*")?\)/g, '$1');
|
||||
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, label: string, url: string) =>
|
||||
label === url || /^#/.test(url) ? label : `${label} (${url})`,
|
||||
);
|
||||
|
||||
const lines = text.split('\n').map((line) => {
|
||||
let l = line;
|
||||
l = l.replace(/^\s{0,3}#{1,6}\s+/, ''); // headings
|
||||
l = l.replace(/^\s{0,3}>\s?/, ''); // block quotes
|
||||
l = l.replace(/^(\s*)[-*+]\s+(?=\S)/, '$1• '); // bullets
|
||||
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) return ''; // horizontal rules
|
||||
if (/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)) return null; // table separator rows
|
||||
if (/^\s*\|.*\|\s*$/.test(l)) {
|
||||
l = l
|
||||
.trim()
|
||||
.replace(/^\||\|$/g, '')
|
||||
.split('|')
|
||||
.map((cell) => cell.trim())
|
||||
.join(' · ');
|
||||
}
|
||||
return l;
|
||||
});
|
||||
text = lines.filter((l): l is string => l !== null).join('\n');
|
||||
|
||||
// Inline emphasis and code. Order matters: longest markers first.
|
||||
text = text.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '$2');
|
||||
text = text.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '$2');
|
||||
text = text.replace(/(?<![\w*])\*(?=\S)([^*\n]*?\S)\*(?![\w*])/g, '$1');
|
||||
text = text.replace(/(?<![\w_])_(?=\S)([^_\n]*?\S)_(?![\w_])/g, '$1');
|
||||
text = text.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '$1');
|
||||
text = text.replace(/`([^`\n]+)`/g, '$1');
|
||||
|
||||
// Whitespace: tabs to spaces, strip trailing space, at most one blank line in a row.
|
||||
text = text
|
||||
.replace(/\t/g, ' ')
|
||||
.replace(/[ \t]+$/gm, '')
|
||||
.replace(/\n{3,}/g, '\n\n');
|
||||
return text.trim();
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
import type { TurnResult } from '@hermeven/contracts';
|
||||
|
||||
/**
|
||||
* Pure interaction state machine. No I/O, no clocks, no randomness: everything
|
||||
* that varies arrives inside an event, and everything to be done leaves as an
|
||||
* effect. That is what makes cancellation and stale-result races testable.
|
||||
*
|
||||
* READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
||||
* with ERROR, DISCONNECTED and CANCELLED as explicit outcomes.
|
||||
*/
|
||||
export type Phase =
|
||||
| 'unpaired'
|
||||
| 'ready'
|
||||
| 'listening'
|
||||
| 'transcribing'
|
||||
| 'thinking'
|
||||
| 'approval'
|
||||
| 'answer'
|
||||
| 'error'
|
||||
| 'disconnected'
|
||||
| 'cancelled';
|
||||
|
||||
export interface HudError {
|
||||
/** Stable code for the phone diagnostics view. */
|
||||
code: string;
|
||||
/** One short line for the HUD. */
|
||||
hud: string;
|
||||
/** Whether asking again (as a deliberate new turn) is reasonable. */
|
||||
retryable: boolean;
|
||||
}
|
||||
|
||||
export interface AppState {
|
||||
phase: Phase;
|
||||
/**
|
||||
* Bumped whenever the user starts, cancels or abandons something. Every
|
||||
* asynchronous effect carries the generation it was issued under, and an
|
||||
* event from an older generation is dropped.
|
||||
*/
|
||||
generation: number;
|
||||
conversationId: string | null;
|
||||
requestId: string | null;
|
||||
captureStartedAt: number | null;
|
||||
captureMaxSeconds: number;
|
||||
pages: string[];
|
||||
pageIndex: number;
|
||||
/** The answer is a partial one (agent stopped short). Shown on the HUD. */
|
||||
partial: boolean;
|
||||
error: HudError | null;
|
||||
/** In DISCONNECTED: the request never reached the bridge, so resending it is safe. */
|
||||
canResend: boolean;
|
||||
/** Why we are disconnected: the bridge link, or the glasses themselves. */
|
||||
disconnectedFrom: 'bridge' | 'glasses' | null;
|
||||
notice: string | null;
|
||||
}
|
||||
|
||||
export const initialState: AppState = {
|
||||
phase: 'unpaired',
|
||||
generation: 0,
|
||||
conversationId: null,
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
captureMaxSeconds: 30,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
error: null,
|
||||
canResend: false,
|
||||
disconnectedFrom: null,
|
||||
notice: null,
|
||||
};
|
||||
|
||||
export type AppEvent =
|
||||
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null }
|
||||
| { type: 'unpaired' }
|
||||
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
||||
| { type: 'activate'; freshId: string }
|
||||
| { type: 'back' }
|
||||
| { type: 'next_page' }
|
||||
| { type: 'prev_page' }
|
||||
| { type: 'new_conversation' }
|
||||
| { type: 'cancel' }
|
||||
| { type: 'submit_text'; freshId: string; text: string }
|
||||
| { type: 'capture_started'; generation: number; at: number }
|
||||
| { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' }
|
||||
| { type: 'capture_limit'; generation: number }
|
||||
| { type: 'conversation_created'; generation: number; conversationId: string }
|
||||
| { type: 'conversation_failed'; generation: number; error: HudError }
|
||||
/** `pages` is the already-paginated plain-text answer when the result carries one. */
|
||||
| { type: 'turn_update'; generation: number; result: TurnResult; pages: string[] | null }
|
||||
| { type: 'turn_rejected'; generation: number; error: HudError }
|
||||
| { type: 'network_lost'; generation: number; stage: 'submit' | 'poll' }
|
||||
| { type: 'network_restored'; generation: number }
|
||||
| { type: 'glasses_status'; connected: boolean }
|
||||
| { type: 'app_exit' };
|
||||
|
||||
export type Effect =
|
||||
| { type: 'start_capture'; generation: number }
|
||||
| { type: 'stop_capture_and_submit'; generation: number; requestId: string }
|
||||
| { type: 'discard_capture' }
|
||||
| { type: 'submit_text'; generation: number; requestId: string; text: string }
|
||||
| { type: 'resubmit'; generation: number; requestId: string }
|
||||
| { type: 'poll'; generation: number; requestId: string }
|
||||
| { type: 'cancel_turn'; requestId: string }
|
||||
| { type: 'create_conversation'; generation: number }
|
||||
| { type: 'exit_dialog' };
|
||||
|
||||
export interface Step {
|
||||
state: AppState;
|
||||
effects: Effect[];
|
||||
}
|
||||
|
||||
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
||||
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
||||
|
||||
function clearTurn(state: AppState): AppState {
|
||||
return {
|
||||
...state,
|
||||
requestId: null,
|
||||
captureStartedAt: null,
|
||||
pages: [],
|
||||
pageIndex: 0,
|
||||
partial: false,
|
||||
error: null,
|
||||
canResend: false,
|
||||
disconnectedFrom: null,
|
||||
notice: null,
|
||||
};
|
||||
}
|
||||
|
||||
function same(state: AppState): Step {
|
||||
return { state, effects: [] };
|
||||
}
|
||||
|
||||
/** Abandon whatever is in progress. The generation bump is what silences late results. */
|
||||
function abandon(state: AppState): Step {
|
||||
const effects: Effect[] = [];
|
||||
if (state.phase === 'listening') effects.push({ type: 'discard_capture' });
|
||||
else if (state.requestId && (IN_FLIGHT.has(state.phase) || state.phase === 'disconnected')) {
|
||||
// Also drops any audio still held for a resend, and asks the bridge to stop the agent.
|
||||
effects.push({ type: 'discard_capture' }, { type: 'cancel_turn', requestId: state.requestId });
|
||||
}
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'cancelled', generation: state.generation + 1 },
|
||||
effects,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduce(state: AppState, event: AppEvent): Step {
|
||||
switch (event.type) {
|
||||
case 'init': {
|
||||
const base: AppState = {
|
||||
...initialState,
|
||||
generation: state.generation + 1,
|
||||
captureMaxSeconds: event.captureMaxSeconds,
|
||||
conversationId: event.conversationId,
|
||||
};
|
||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||
if (event.resumeRequestId) {
|
||||
// A turn was in flight when the page last died. Re-attach by polling: never resubmit,
|
||||
// and never reopen the microphone on our own.
|
||||
return {
|
||||
state: { ...base, phase: 'thinking', requestId: event.resumeRequestId },
|
||||
effects: [{ type: 'poll', generation: base.generation, requestId: event.resumeRequestId }],
|
||||
};
|
||||
}
|
||||
return same({ ...base, phase: 'ready' });
|
||||
}
|
||||
|
||||
case 'unpaired': {
|
||||
const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : [];
|
||||
return {
|
||||
state: { ...initialState, generation: state.generation + 1, captureMaxSeconds: state.captureMaxSeconds },
|
||||
effects,
|
||||
};
|
||||
}
|
||||
|
||||
case 'activate': {
|
||||
if (IDLE.has(state.phase)) {
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'listening', generation, requestId: event.freshId },
|
||||
effects: [{ type: 'start_capture', generation }],
|
||||
};
|
||||
}
|
||||
if (state.phase === 'listening' && state.requestId) {
|
||||
return {
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null },
|
||||
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
|
||||
};
|
||||
}
|
||||
if (state.phase === 'disconnected' && state.canResend && state.requestId) {
|
||||
// Same request id: the bridge deduplicates, so this cannot run the turn twice.
|
||||
return {
|
||||
state: { ...state, phase: 'transcribing', disconnectedFrom: null },
|
||||
effects: [{ type: 'resubmit', generation: state.generation, requestId: state.requestId }],
|
||||
};
|
||||
}
|
||||
return same(state);
|
||||
}
|
||||
|
||||
case 'capture_limit': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening' || !state.requestId) return same(state);
|
||||
return {
|
||||
state: { ...state, phase: 'transcribing', captureStartedAt: null },
|
||||
effects: [{ type: 'stop_capture_and_submit', generation: state.generation, requestId: state.requestId }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'submit_text': {
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'thinking', generation, requestId: event.freshId },
|
||||
effects: [{ type: 'submit_text', generation, requestId: event.freshId, text: event.text }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'back': {
|
||||
if (state.phase === 'ready' || state.phase === 'unpaired') return { state, effects: [{ type: 'exit_dialog' }] };
|
||||
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
||||
// answer / error / cancelled: step back to the root page.
|
||||
return same({ ...clearTurn(state), phase: 'ready' });
|
||||
}
|
||||
|
||||
case 'cancel': {
|
||||
if (state.phase === 'listening' || IN_FLIGHT.has(state.phase) || state.phase === 'disconnected') return abandon(state);
|
||||
return same(state);
|
||||
}
|
||||
|
||||
case 'next_page':
|
||||
case 'prev_page': {
|
||||
if (state.phase !== 'answer') return same(state);
|
||||
const delta = event.type === 'next_page' ? 1 : -1;
|
||||
const pageIndex = Math.min(state.pages.length - 1, Math.max(0, state.pageIndex + delta));
|
||||
return same(pageIndex === state.pageIndex ? state : { ...state, pageIndex });
|
||||
}
|
||||
|
||||
case 'new_conversation': {
|
||||
// Only from a resting state: a reset must never be mistaken for cancelling the backend.
|
||||
if (!IDLE.has(state.phase)) return same(state);
|
||||
const generation = state.generation + 1;
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'ready', generation, conversationId: null, notice: 'New conversation' },
|
||||
effects: [{ type: 'create_conversation', generation }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'conversation_created': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
return same({ ...state, conversationId: event.conversationId });
|
||||
}
|
||||
|
||||
case 'conversation_failed': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
return same({ ...clearTurn(state), phase: 'error', error: event.error });
|
||||
}
|
||||
|
||||
case 'capture_started': {
|
||||
if (event.generation !== state.generation || state.phase !== 'listening') return same(state);
|
||||
return same({ ...state, captureStartedAt: event.at });
|
||||
}
|
||||
|
||||
case 'capture_failed': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
if (state.phase !== 'listening' && state.phase !== 'transcribing') return same(state);
|
||||
const hud =
|
||||
event.reason === 'mic_refused'
|
||||
? 'Microphone unavailable.'
|
||||
: event.reason === 'mic_stalled'
|
||||
? 'Microphone stopped.'
|
||||
: 'Nothing was recorded.';
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'error', error: { code: event.reason, hud, retryable: true } },
|
||||
effects: [{ type: 'discard_capture' }],
|
||||
};
|
||||
}
|
||||
|
||||
case 'turn_update': {
|
||||
if (event.generation !== state.generation || event.result.request_id !== state.requestId) return same(state);
|
||||
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
|
||||
const result = event.result;
|
||||
if (!result.terminal) {
|
||||
const phase: Phase =
|
||||
result.state === 'transcribing' ? 'transcribing' : result.state === 'approval_required' ? 'approval' : 'thinking';
|
||||
return same({ ...state, phase, disconnectedFrom: null, canResend: false });
|
||||
}
|
||||
const settled = { ...clearTurn(state), requestId: state.requestId };
|
||||
switch (result.outcome) {
|
||||
case 'succeeded':
|
||||
case 'incomplete':
|
||||
return same({
|
||||
...settled,
|
||||
phase: 'answer',
|
||||
pages: event.pages ?? [''],
|
||||
pageIndex: 0,
|
||||
partial: result.outcome === 'incomplete',
|
||||
});
|
||||
case 'cancelled':
|
||||
return same({
|
||||
...settled,
|
||||
phase: result.error ? 'error' : 'cancelled',
|
||||
error: result.error ? { code: result.error.code, hud: result.error.message, retryable: result.error.retryable } : null,
|
||||
});
|
||||
default:
|
||||
return same({
|
||||
...settled,
|
||||
phase: 'error',
|
||||
error: {
|
||||
code: result.error?.code ?? 'internal',
|
||||
hud: result.error?.message ?? 'The request did not complete.',
|
||||
retryable: result.error?.retryable ?? false,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
case 'turn_rejected': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
return { state: { ...clearTurn(state), phase: 'error', error: event.error }, effects: [{ type: 'discard_capture' }] };
|
||||
}
|
||||
|
||||
case 'network_lost': {
|
||||
if (event.generation !== state.generation) return same(state);
|
||||
if (!IN_FLIGHT.has(state.phase) && state.phase !== 'disconnected') return same(state);
|
||||
return same({ ...state, phase: 'disconnected', disconnectedFrom: 'bridge', canResend: event.stage === 'submit' });
|
||||
}
|
||||
|
||||
case 'network_restored': {
|
||||
if (event.generation !== state.generation || state.phase !== 'disconnected' || state.disconnectedFrom !== 'bridge') {
|
||||
return same(state);
|
||||
}
|
||||
return same({ ...state, phase: 'thinking', disconnectedFrom: null, canResend: false });
|
||||
}
|
||||
|
||||
case 'glasses_status': {
|
||||
if (event.connected) {
|
||||
if (state.phase === 'disconnected' && state.disconnectedFrom === 'glasses') {
|
||||
// Back to rest. The microphone is never reopened without a fresh tap.
|
||||
return same({ ...clearTurn(state), phase: 'ready' });
|
||||
}
|
||||
return same(state);
|
||||
}
|
||||
if (state.phase === 'listening') {
|
||||
return {
|
||||
state: {
|
||||
...clearTurn(state),
|
||||
phase: 'disconnected',
|
||||
disconnectedFrom: 'glasses',
|
||||
generation: state.generation + 1,
|
||||
},
|
||||
effects: [{ type: 'discard_capture' }],
|
||||
};
|
||||
}
|
||||
if (IDLE.has(state.phase)) return same({ ...state, phase: 'disconnected', disconnectedFrom: 'glasses', canResend: false });
|
||||
// A turn already in flight keeps running on the bridge; its result is still wanted.
|
||||
return same(state);
|
||||
}
|
||||
|
||||
case 'app_exit': {
|
||||
if (state.phase !== 'listening') return same(state);
|
||||
return {
|
||||
state: { ...clearTurn(state), phase: 'ready', generation: state.generation + 1 },
|
||||
effects: [{ type: 'discard_capture' }],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import {
|
||||
AudioInputSource,
|
||||
CreateStartUpPageContainer,
|
||||
DeviceConnectType,
|
||||
StartUpPageCreateResult,
|
||||
TextContainerProperty,
|
||||
TextContainerUpgrade,
|
||||
type EvenAppBridge,
|
||||
} from '@evenrealities/even_hub_sdk';
|
||||
import { BODY_BOX, HUD, STATUS_BOX, type HudFrame } from '../core/hud.ts';
|
||||
import { MENU_ITEM, normalizeEvent, type DeviceEvent, type RawEvenHubEvent } from './events.ts';
|
||||
import type { DevicePort } from './port.ts';
|
||||
|
||||
const BODY = { id: 1, name: 'body' } as const;
|
||||
const STATUS = { id: 2, name: 'status' } as const;
|
||||
|
||||
/** A flaky BLE hop can hang a bridge call for a long time; never let one block the UI forever. */
|
||||
const CALL_TIMEOUT_MS = 8000;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS);
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
resolve(fallback);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapter over the public Even Hub SDK (0.0.16). Only documented SDK calls are
|
||||
* used: createStartUpPageContainer, textContainerUpgrade, audioControl,
|
||||
* shutDownPageContainer, set/getLocalStorage, onEvenHubEvent, onDeviceStatusChanged.
|
||||
*/
|
||||
export class EvenDevice implements DevicePort {
|
||||
private shown: HudFrame = { body: '', status: '' };
|
||||
private pending: HudFrame | null = null;
|
||||
private flushing = false;
|
||||
private ready = false;
|
||||
/** All host calls go through one queue: concurrent bridge calls are documented as unsafe. */
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(private readonly bridge: EvenAppBridge) {}
|
||||
|
||||
private enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> {
|
||||
const next = this.queue.then(() => withTimeout(call(), fallback));
|
||||
this.queue = next.catch(() => undefined);
|
||||
return next;
|
||||
}
|
||||
|
||||
async init(frame: HudFrame): Promise<boolean> {
|
||||
const page = new CreateStartUpPageContainer({
|
||||
containerTotalNum: 2,
|
||||
textObject: [
|
||||
new TextContainerProperty({
|
||||
xPosition: BODY_BOX.x,
|
||||
yPosition: BODY_BOX.y,
|
||||
width: BODY_BOX.width,
|
||||
height: BODY_BOX.height,
|
||||
borderWidth: 0,
|
||||
paddingLength: HUD.padding,
|
||||
containerID: BODY.id,
|
||||
containerName: BODY.name,
|
||||
content: frame.body || ' ',
|
||||
isEventCapture: 1,
|
||||
}),
|
||||
new TextContainerProperty({
|
||||
xPosition: STATUS_BOX.x,
|
||||
yPosition: STATUS_BOX.y,
|
||||
width: STATUS_BOX.width,
|
||||
height: STATUS_BOX.height,
|
||||
borderWidth: 0,
|
||||
paddingLength: HUD.padding,
|
||||
containerID: STATUS.id,
|
||||
containerName: STATUS.name,
|
||||
content: frame.status || ' ',
|
||||
isEventCapture: 0,
|
||||
}),
|
||||
],
|
||||
// Extra entries in the OS contextual menu (tap, then long press). The OS adds its
|
||||
// own "Close" entry, so no exit item is declared here.
|
||||
menuObject: {
|
||||
menuItems: [
|
||||
{ itemName: 'New conversation', itemID: MENU_ITEM.NEW_CONVERSATION },
|
||||
{ itemName: 'Cancel request', itemID: MENU_ITEM.CANCEL },
|
||||
],
|
||||
} as never,
|
||||
});
|
||||
const result = await this.enqueue(() => this.bridge.createStartUpPageContainer(page), StartUpPageCreateResult.invalid);
|
||||
this.ready = result === StartUpPageCreateResult.success;
|
||||
if (this.ready) this.shown = { body: frame.body || ' ', status: frame.status || ' ' };
|
||||
return this.ready;
|
||||
}
|
||||
|
||||
show(frame: HudFrame): void {
|
||||
this.pending = { body: frame.body || ' ', status: frame.status || ' ' };
|
||||
if (!this.flushing) void this.flush();
|
||||
}
|
||||
|
||||
private async flush(): Promise<void> {
|
||||
this.flushing = true;
|
||||
try {
|
||||
while (this.pending && this.ready) {
|
||||
const frame = this.pending;
|
||||
this.pending = null;
|
||||
// In-place text updates are flicker-free; a page rebuild is not needed for text changes.
|
||||
if (frame.body !== this.shown.body) {
|
||||
const ok = await this.enqueue(
|
||||
() =>
|
||||
this.bridge.textContainerUpgrade(
|
||||
new TextContainerUpgrade({ containerID: BODY.id, containerName: BODY.name, content: frame.body }),
|
||||
),
|
||||
false,
|
||||
);
|
||||
if (ok) this.shown.body = frame.body;
|
||||
}
|
||||
if (frame.status !== this.shown.status) {
|
||||
const ok = await this.enqueue(
|
||||
() =>
|
||||
this.bridge.textContainerUpgrade(
|
||||
new TextContainerUpgrade({ containerID: STATUS.id, containerName: STATUS.name, content: frame.status }),
|
||||
),
|
||||
false,
|
||||
);
|
||||
if (ok) this.shown.status = frame.status;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.flushing = false;
|
||||
}
|
||||
}
|
||||
|
||||
startMic(): Promise<boolean> {
|
||||
return this.enqueue(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false);
|
||||
}
|
||||
|
||||
async stopMic(): Promise<void> {
|
||||
await this.enqueue(() => this.bridge.audioControl(false), false);
|
||||
}
|
||||
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void {
|
||||
return this.bridge.onEvenHubEvent((event) => {
|
||||
for (const normalized of normalizeEvent(event as RawEvenHubEvent)) listener(normalized);
|
||||
});
|
||||
}
|
||||
|
||||
onConnection(listener: (connected: boolean) => void): () => void {
|
||||
return this.bridge.onDeviceStatusChanged((status) => {
|
||||
if (status.connectType === DeviceConnectType.Connected) listener(true);
|
||||
else if (
|
||||
status.connectType === DeviceConnectType.Disconnected ||
|
||||
status.connectType === DeviceConnectType.ConnectionFailed
|
||||
) {
|
||||
listener(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async requestExit(): Promise<void> {
|
||||
// Mode 1: the OS shows its own confirmation. Cleanup happens on SYSTEM_EXIT, not here,
|
||||
// because the user can still decline.
|
||||
await this.enqueue(() => this.bridge.shutDownPageContainer(1), false);
|
||||
}
|
||||
|
||||
storageGet(key: string): Promise<string> {
|
||||
return this.enqueue(() => this.bridge.getLocalStorage(key), '');
|
||||
}
|
||||
|
||||
async storageSet(key: string, value: string): Promise<void> {
|
||||
await this.enqueue(() => this.bridge.setLocalStorage(key, value), false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Normalise raw Even Hub events into Hermeven's device-neutral vocabulary.
|
||||
*
|
||||
* Kept free of SDK imports (numbers below are the SDK's `OsEventTypeList`
|
||||
* values, asserted against the real enum in the tests) so the mapping is a
|
||||
* pure function over plain objects.
|
||||
*/
|
||||
export const OS_EVENT = {
|
||||
CLICK: 0,
|
||||
SCROLL_TOP: 1,
|
||||
SCROLL_BOTTOM: 2,
|
||||
DOUBLE_CLICK: 3,
|
||||
FOREGROUND_ENTER: 4,
|
||||
FOREGROUND_EXIT: 5,
|
||||
ABNORMAL_EXIT: 6,
|
||||
SYSTEM_EXIT: 7,
|
||||
IMU_DATA_REPORT: 8,
|
||||
LONG_PRESS: 9,
|
||||
LONG_PRESS_RELEASE: 10,
|
||||
} as const;
|
||||
|
||||
export const MENU_ITEM = { NEW_CONVERSATION: 1, CANCEL: 2 } as const;
|
||||
|
||||
export type DeviceEvent =
|
||||
| { type: 'tap' }
|
||||
| { type: 'double_tap' }
|
||||
| { type: 'swipe_up' }
|
||||
| { type: 'swipe_down' }
|
||||
| { type: 'menu'; itemId: number }
|
||||
| { type: 'audio'; pcm: Uint8Array }
|
||||
| { type: 'foreground_enter' }
|
||||
| { type: 'foreground_exit' }
|
||||
| { type: 'system_exit' }
|
||||
| { type: 'abnormal_exit' };
|
||||
|
||||
interface Envelope {
|
||||
eventType?: number;
|
||||
}
|
||||
|
||||
export interface RawEvenHubEvent {
|
||||
listEvent?: Envelope;
|
||||
textEvent?: Envelope;
|
||||
sysEvent?: Envelope;
|
||||
audioEvent?: { audioPcm?: Uint8Array };
|
||||
menuItemClickEvent?: { itemID?: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* CLICK_EVENT is 0 and protobuf omits zero-valued fields, so a tap arrives as
|
||||
* an envelope with no `eventType` at all. The default must be applied per
|
||||
* envelope: an event with no gesture envelope (audio, menu) is not a tap.
|
||||
*/
|
||||
function typeOf(envelope: Envelope | undefined): number | null {
|
||||
if (!envelope) return null;
|
||||
return envelope.eventType ?? OS_EVENT.CLICK;
|
||||
}
|
||||
|
||||
export function normalizeEvent(event: RawEvenHubEvent): DeviceEvent[] {
|
||||
const out: DeviceEvent[] = [];
|
||||
|
||||
const pcm = event.audioEvent?.audioPcm;
|
||||
if (pcm && pcm.length > 0) out.push({ type: 'audio', pcm });
|
||||
|
||||
const itemId = event.menuItemClickEvent?.itemID;
|
||||
if (typeof itemId === 'number') out.push({ type: 'menu', itemId });
|
||||
|
||||
// Official sources disagree on whether gestures arrive on textEvent or sysEvent,
|
||||
// so both are read. One raw event carries one gesture; the first envelope wins.
|
||||
const gesture = typeOf(event.sysEvent) ?? typeOf(event.textEvent) ?? typeOf(event.listEvent);
|
||||
switch (gesture) {
|
||||
case OS_EVENT.DOUBLE_CLICK:
|
||||
out.push({ type: 'double_tap' });
|
||||
break;
|
||||
case OS_EVENT.SCROLL_TOP:
|
||||
out.push({ type: 'swipe_up' });
|
||||
break;
|
||||
case OS_EVENT.SCROLL_BOTTOM:
|
||||
out.push({ type: 'swipe_down' });
|
||||
break;
|
||||
case OS_EVENT.FOREGROUND_ENTER:
|
||||
out.push({ type: 'foreground_enter' });
|
||||
break;
|
||||
case OS_EVENT.FOREGROUND_EXIT:
|
||||
out.push({ type: 'foreground_exit' });
|
||||
break;
|
||||
case OS_EVENT.ABNORMAL_EXIT:
|
||||
out.push({ type: 'abnormal_exit' });
|
||||
break;
|
||||
case OS_EVENT.SYSTEM_EXIT:
|
||||
out.push({ type: 'system_exit' });
|
||||
break;
|
||||
case OS_EVENT.CLICK:
|
||||
out.push({ type: 'tap' });
|
||||
break;
|
||||
default:
|
||||
// IMU reports and long press are not part of the interaction contract.
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { HudFrame } from '../core/hud.ts';
|
||||
import type { DeviceEvent } from './events.ts';
|
||||
|
||||
/** Everything Hermeven needs from the glasses runtime. Implemented by the Even adapter and by test fakes. */
|
||||
export interface DevicePort {
|
||||
/** Create the HUD page. Resolves false when the host refused it. */
|
||||
init(frame: HudFrame): Promise<boolean>;
|
||||
/** Show a frame. Calls are serialised and coalesced; only the latest pending frame is sent. */
|
||||
show(frame: HudFrame): void;
|
||||
/** Open the glasses microphone. Resolves false when the host refused (for example no permission). */
|
||||
startMic(): Promise<boolean>;
|
||||
stopMic(): Promise<void>;
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void;
|
||||
onConnection(listener: (connected: boolean) => void): () => void;
|
||||
/** Ask the OS to show its own exit confirmation. */
|
||||
requestExit(): Promise<void>;
|
||||
storageGet(key: string): Promise<string>;
|
||||
storageSet(key: string, value: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { HudFrame } from '../core/hud.ts';
|
||||
import type { DeviceEvent } from './events.ts';
|
||||
import type { DevicePort } from './port.ts';
|
||||
|
||||
/**
|
||||
* Stand-in for the glasses when the page runs in a plain browser (no Even host).
|
||||
* Draws the two HUD text areas in the page and offers buttons for the gestures.
|
||||
* It has NO microphone: a tap that would start recording reports the mic as
|
||||
* unavailable. Nothing shown here is evidence about real hardware.
|
||||
*/
|
||||
export class BrowserPreviewDevice implements DevicePort {
|
||||
private readonly body = document.createElement('pre');
|
||||
private readonly status = document.createElement('pre');
|
||||
private readonly listeners = new Set<(event: DeviceEvent) => void>();
|
||||
|
||||
constructor(container: HTMLElement) {
|
||||
this.body.className = 'hud-body';
|
||||
this.status.className = 'hud-status';
|
||||
const label = document.createElement('p');
|
||||
label.className = 'hint';
|
||||
label.textContent = 'Browser preview of the HUD text. Not the glasses, not the simulator; fonts and wrapping differ.';
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'row';
|
||||
const gestures: Array<[string, DeviceEvent]> = [
|
||||
['Tap', { type: 'tap' }],
|
||||
['Double-tap', { type: 'double_tap' }],
|
||||
['Swipe up', { type: 'swipe_up' }],
|
||||
['Swipe down', { type: 'swipe_down' }],
|
||||
];
|
||||
for (const [text, event] of gestures) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'secondary';
|
||||
button.textContent = text;
|
||||
button.addEventListener('click', () => this.listeners.forEach((l) => l(event)));
|
||||
controls.append(button);
|
||||
}
|
||||
const screen = document.createElement('div');
|
||||
screen.className = 'hud';
|
||||
screen.append(this.body, this.status);
|
||||
container.append(label, screen, controls);
|
||||
}
|
||||
|
||||
async init(frame: HudFrame): Promise<boolean> {
|
||||
this.show(frame);
|
||||
return true;
|
||||
}
|
||||
|
||||
show(frame: HudFrame): void {
|
||||
this.body.textContent = frame.body;
|
||||
this.status.textContent = frame.status;
|
||||
}
|
||||
|
||||
async startMic(): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
|
||||
async stopMic(): Promise<void> {}
|
||||
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
onConnection(): () => void {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
async requestExit(): Promise<void> {}
|
||||
|
||||
async storageGet(key: string): Promise<string> {
|
||||
try {
|
||||
return localStorage.getItem(key) ?? '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async storageSet(key: string, value: string): Promise<void> {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, value);
|
||||
else localStorage.removeItem(key);
|
||||
} catch {
|
||||
/* preview only */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { waitForEvenAppBridge } from '@evenrealities/even_hub_sdk';
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { Controller } from './core/controller.ts';
|
||||
import { EvenDevice } from './device/evenAdapter.ts';
|
||||
import { BrowserPreviewDevice } from './device/previewDevice.ts';
|
||||
import type { DevicePort } from './device/port.ts';
|
||||
import { mountPhoneUi } from './ui/phone.ts';
|
||||
import './ui/phone.css';
|
||||
|
||||
/**
|
||||
* Entry point. Inside the Even app (or the Even Hub simulator) the SDK bridge
|
||||
* is present and the real adapter is used. In a plain browser there is no
|
||||
* bridge, so a clearly-labelled preview device is used instead: it has no
|
||||
* microphone and proves nothing about hardware.
|
||||
*/
|
||||
async function resolveDevice(): Promise<{ device: DevicePort; runtime: string }> {
|
||||
const hasHost = typeof (window as { flutter_inappwebview?: unknown }).flutter_inappwebview !== 'undefined';
|
||||
if (hasHost) {
|
||||
const bridge = await waitForEvenAppBridge();
|
||||
return { device: new EvenDevice(bridge), runtime: 'Even app host (SDK 0.0.16)' };
|
||||
}
|
||||
const preview = document.getElementById('preview')!;
|
||||
preview.hidden = false;
|
||||
return { device: new BrowserPreviewDevice(preview), runtime: 'Browser preview: no glasses, no microphone' };
|
||||
}
|
||||
|
||||
const { device, runtime } = await resolveDevice();
|
||||
const root = document.getElementById('app')!;
|
||||
|
||||
let update: (snapshot: ReturnType<Controller['snapshot']>) => void = () => undefined;
|
||||
const controller = new Controller({
|
||||
device,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: navigator.language || 'en-US',
|
||||
onChange: (snapshot) => update(snapshot),
|
||||
// Development builds mirror diagnostics to the console (visible in the simulator and the
|
||||
// Even dev console). Diagnostics never contain questions, answers or credentials.
|
||||
onNote: import.meta.env.DEV ? (entry) => console.info(`[hermeven] ${entry.kind}: ${entry.detail}`) : undefined,
|
||||
});
|
||||
update = mountPhoneUi(root, controller, {
|
||||
bridgeUrl: import.meta.env.VITE_HERMEVEN_BRIDGE_URL ?? '',
|
||||
runtime,
|
||||
});
|
||||
|
||||
// Never leave the microphone open behind a page that is going away.
|
||||
window.addEventListener('beforeunload', () => void controller.stop());
|
||||
|
||||
await controller.start();
|
||||
update(controller.snapshot());
|
||||
|
||||
// Development-only convenience for automated simulator runs, where nothing can type into the
|
||||
// phone page: `?bridge=<url>&pair=<code>` pairs on load. Compiled out of production builds.
|
||||
if (import.meta.env.DEV) {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const bridgeUrl = params.get('bridge');
|
||||
const code = params.get('pair');
|
||||
if (bridgeUrl && code && !controller.snapshot().paired) {
|
||||
try {
|
||||
await controller.pair(bridgeUrl, code, 'dev');
|
||||
} catch (err) {
|
||||
console.info(`[hermeven] dev-pair: failed ${err instanceof Error ? err.name : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f6f4;
|
||||
--surface: #ffffff;
|
||||
--text: #1c1c1a;
|
||||
--muted: #62625c;
|
||||
--line: #d9d9d3;
|
||||
--accent: #1f5fbf;
|
||||
--danger: #b3261e;
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #131312;
|
||||
--surface: #1e1e1c;
|
||||
--text: #ececE6;
|
||||
--muted: #a3a39b;
|
||||
--line: #3a3a36;
|
||||
--accent: #8ab4f8;
|
||||
--danger: #f2b8b5;
|
||||
}
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.45;
|
||||
overscroll-behavior: none;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
#app,
|
||||
#preview {
|
||||
max-width: 40rem;
|
||||
margin: 0 auto;
|
||||
padding: 0 16px 16px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 1.4rem;
|
||||
margin: 20px 0 8px;
|
||||
}
|
||||
h2 {
|
||||
font-size: 1.05rem;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
h3 {
|
||||
font-size: 0.85rem;
|
||||
margin: 12px 0 2px;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
section,
|
||||
details {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 14px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
color: var(--muted);
|
||||
margin: 10px 0;
|
||||
}
|
||||
input,
|
||||
textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
padding: 10px;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
min-height: 44px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--accent);
|
||||
color: var(--bg);
|
||||
}
|
||||
button.secondary {
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
}
|
||||
button.danger {
|
||||
background: transparent;
|
||||
border-color: var(--danger);
|
||||
color: var(--danger);
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.hint {
|
||||
font-size: 0.85rem;
|
||||
color: var(--muted);
|
||||
margin: 4px 0;
|
||||
}
|
||||
.message {
|
||||
min-height: 1.4em;
|
||||
margin: 4px 0;
|
||||
}
|
||||
.bad {
|
||||
color: var(--danger);
|
||||
}
|
||||
.phase {
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(7rem, auto) 1fr;
|
||||
gap: 4px 12px;
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.answer,
|
||||
.turn p {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
margin: 0;
|
||||
}
|
||||
.log {
|
||||
font-size: 0.72rem;
|
||||
overflow-x: auto;
|
||||
max-height: 16rem;
|
||||
margin: 10px 0 0;
|
||||
white-space: pre;
|
||||
}
|
||||
.hud {
|
||||
background: #000;
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.hud pre {
|
||||
margin: 0;
|
||||
color: #d8ffd8;
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.hud-body {
|
||||
min-height: 9em;
|
||||
}
|
||||
.hud-status {
|
||||
border-top: 1px solid #244;
|
||||
padding-top: 4px;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import type { Controller, Snapshot } from '../core/controller.ts';
|
||||
import { BridgeApiError, BridgeNetworkError, normalizeBridgeUrl } from '../net/bridgeClient.ts';
|
||||
|
||||
/**
|
||||
* Phone-side page: pairing, status, diagnostics, typed input and disconnect.
|
||||
* Built with DOM APIs and textContent only, so nothing from the bridge or the
|
||||
* agent is ever interpreted as HTML.
|
||||
*/
|
||||
function el<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
props: Partial<HTMLElementTagNameMap[K]> & { class?: string } = {},
|
||||
children: Array<Node | string> = [],
|
||||
): HTMLElementTagNameMap[K] {
|
||||
const node = document.createElement(tag);
|
||||
const { class: className, ...rest } = props;
|
||||
if (className) node.className = className;
|
||||
Object.assign(node, rest);
|
||||
for (const child of children) node.append(child);
|
||||
return node;
|
||||
}
|
||||
|
||||
function explain(err: unknown): string {
|
||||
if (err instanceof BridgeApiError) return `${err.body.message} (${err.body.code})`;
|
||||
if (err instanceof BridgeNetworkError) {
|
||||
return (
|
||||
'Could not reach the bridge. Check the address, that the bridge is running, that this app build ' +
|
||||
"lists the bridge in its network whitelist, and that the bridge allows this page's origin."
|
||||
);
|
||||
}
|
||||
return err instanceof Error ? err.message : 'Something went wrong.';
|
||||
}
|
||||
|
||||
const PHASE_LABEL: Record<string, string> = {
|
||||
unpaired: 'Not paired',
|
||||
ready: 'Ready',
|
||||
listening: 'Listening (microphone open)',
|
||||
transcribing: 'Transcribing',
|
||||
thinking: 'Thinking',
|
||||
approval: 'Approval required',
|
||||
answer: 'Answer shown',
|
||||
error: 'Error',
|
||||
disconnected: 'Disconnected',
|
||||
cancelled: 'Cancelled',
|
||||
};
|
||||
|
||||
export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults: { bridgeUrl: string; runtime: string }): (s: Snapshot) => void {
|
||||
root.replaceChildren();
|
||||
|
||||
const message = el('p', { class: 'message', role: 'status' } as never);
|
||||
const say = (text: string, bad = false) => {
|
||||
message.textContent = text;
|
||||
message.className = bad ? 'message bad' : 'message';
|
||||
};
|
||||
|
||||
async function guarded(button: HTMLButtonElement, action: () => Promise<string | void>): Promise<void> {
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await action();
|
||||
if (result) say(result);
|
||||
} catch (err) {
|
||||
say(explain(err), true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- pairing
|
||||
const urlInput = el('input', { type: 'url', value: defaults.bridgeUrl, placeholder: 'https://bridge.example', autocomplete: 'off' });
|
||||
const codeInput = el('input', { type: 'text', placeholder: 'ABCDE-FGHJK', autocomplete: 'off', autocapitalize: 'characters' } as never);
|
||||
const nameInput = el('input', { type: 'text', value: 'G2', maxLength: 60 });
|
||||
const pairButton = el('button', { type: 'button', textContent: 'Pair' });
|
||||
pairButton.addEventListener('click', () =>
|
||||
guarded(pairButton, async () => {
|
||||
const url = normalizeBridgeUrl(urlInput.value);
|
||||
await controller.pair(url, codeInput.value.trim(), nameInput.value.trim() || 'G2');
|
||||
codeInput.value = '';
|
||||
return 'Paired.';
|
||||
}),
|
||||
);
|
||||
const pairing = el('section', {}, [
|
||||
el('h2', { textContent: 'Pair with your bridge' }),
|
||||
el('p', { class: 'hint', textContent: 'On the bridge host run “npm run bridge:cli -- pair” and enter the code it prints. Codes work once and expire in a few minutes.' }),
|
||||
el('label', {}, ['Bridge address', urlInput]),
|
||||
el('label', {}, ['Pairing code', codeInput]),
|
||||
el('label', {}, ['Device name', nameInput]),
|
||||
pairButton,
|
||||
]);
|
||||
|
||||
// ---- status
|
||||
const statusList = el('dl');
|
||||
const refreshButton = el('button', { type: 'button', class: 'secondary', textContent: 'Refresh' });
|
||||
refreshButton.addEventListener('click', () => guarded(refreshButton, () => controller.refreshStatus()));
|
||||
const renewButton = el('button', { type: 'button', class: 'secondary', textContent: 'Renew credential' });
|
||||
renewButton.addEventListener('click', () => guarded(renewButton, async () => (await controller.renew(), 'Credential renewed.')));
|
||||
const disconnectButton = el('button', { type: 'button', class: 'danger', textContent: 'Disconnect' });
|
||||
disconnectButton.addEventListener('click', () =>
|
||||
guarded(disconnectButton, async () => {
|
||||
const { revoked } = await controller.disconnect();
|
||||
return revoked
|
||||
? 'Disconnected. The credential was revoked and removed from this phone.'
|
||||
: 'Removed from this phone, but the bridge could not be reached. Revoke this device on the bridge host to finish.';
|
||||
}),
|
||||
);
|
||||
const status = el('section', {}, [
|
||||
el('h2', { textContent: 'Connection' }),
|
||||
statusList,
|
||||
el('div', { class: 'row' }, [refreshButton, renewButton, disconnectButton]),
|
||||
]);
|
||||
|
||||
// ---- conversation and typed input
|
||||
const textInput = el('textarea', { rows: 3, placeholder: 'Type a question (for testing, or when speaking is not possible)' });
|
||||
const askButton = el('button', { type: 'button', textContent: 'Ask' });
|
||||
askButton.addEventListener('click', () => {
|
||||
controller.askText(textInput.value);
|
||||
textInput.value = '';
|
||||
});
|
||||
const cancelButton = el('button', { type: 'button', class: 'secondary', textContent: 'Cancel request' });
|
||||
cancelButton.addEventListener('click', () => controller.cancel());
|
||||
const newButton = el('button', { type: 'button', class: 'secondary', textContent: 'New conversation' });
|
||||
newButton.addEventListener('click', () => controller.newConversation());
|
||||
const phase = el('p', { class: 'phase' });
|
||||
const captureNote = el('p', { class: 'hint' });
|
||||
const turnView = el('div', { class: 'turn' });
|
||||
const conversation = el('section', {}, [
|
||||
el('h2', { textContent: 'Conversation' }),
|
||||
phase,
|
||||
captureNote,
|
||||
el('label', {}, ['Typed question', textInput]),
|
||||
el('div', { class: 'row' }, [askButton, cancelButton, newButton]),
|
||||
turnView,
|
||||
]);
|
||||
|
||||
// ---- diagnostics
|
||||
const diagList = el('dl');
|
||||
const logView = el('pre', { class: 'log' });
|
||||
const diagnostics = el('details', {}, [
|
||||
el('summary', { textContent: 'Diagnostics' }),
|
||||
el('p', { class: 'hint', textContent: 'Identifiers, states and timings only. Questions and answers are not written to this log.' }),
|
||||
diagList,
|
||||
logView,
|
||||
]);
|
||||
|
||||
root.append(el('h1', { textContent: 'Hermeven' }), message, pairing, status, conversation, diagnostics);
|
||||
|
||||
const rows = (list: HTMLElement, entries: Array<[string, string]>) => {
|
||||
list.replaceChildren(...entries.flatMap(([k, v]) => [el('dt', { textContent: k }), el('dd', { textContent: v })]));
|
||||
};
|
||||
const when = (iso: string) => (iso ? new Date(iso).toLocaleString() : 'unknown');
|
||||
|
||||
return (s: Snapshot) => {
|
||||
pairing.hidden = s.paired;
|
||||
status.hidden = !s.paired;
|
||||
conversation.hidden = !s.paired;
|
||||
|
||||
rows(statusList, [
|
||||
['Bridge', s.bridgeUrl],
|
||||
['Agent', s.status ? (s.status.agent_reachable ? 'reachable' : 'not reachable from the bridge') : 'not checked'],
|
||||
['Speech-to-text', s.status ? (s.status.stt_configured ? 'configured' : 'not configured (typed questions only)') : 'not checked'],
|
||||
['Credential valid until', when(s.tokenExpiresAt)],
|
||||
['Pairing valid until', when(s.pairingExpiresAt)],
|
||||
['Stored on this phone', 'In the Even app’s app storage, which is not an encrypted vault. The credential is revocable and expires.'],
|
||||
]);
|
||||
|
||||
phase.textContent = PHASE_LABEL[s.state.phase] ?? s.state.phase;
|
||||
captureNote.textContent =
|
||||
`Recording starts only when you tap the glasses, shows “● REC” for as long as the microphone is open, ` +
|
||||
`and stops by itself after ${s.state.captureMaxSeconds} seconds.`;
|
||||
const inFlight = ['listening', 'transcribing', 'thinking', 'approval', 'disconnected'].includes(s.state.phase);
|
||||
askButton.disabled = inFlight;
|
||||
newButton.disabled = inFlight;
|
||||
cancelButton.disabled = !inFlight;
|
||||
|
||||
const t = s.lastTurn;
|
||||
turnView.replaceChildren();
|
||||
if (s.state.error) {
|
||||
turnView.append(el('p', { class: 'bad', textContent: `${s.state.error.hud} [${s.state.error.code}]` }));
|
||||
}
|
||||
if (t) {
|
||||
if (t.input_text) turnView.append(el('h3', { textContent: 'Sent to the agent' }), el('p', { textContent: t.input_text }));
|
||||
if (t.answer_text !== null) {
|
||||
turnView.append(
|
||||
el('h3', { textContent: t.outcome === 'incomplete' ? 'Partial answer' : 'Answer' }),
|
||||
el('p', { class: 'answer', textContent: t.answer_text }),
|
||||
);
|
||||
}
|
||||
turnView.append(
|
||||
el('p', {
|
||||
class: 'hint',
|
||||
textContent:
|
||||
`Outcome: ${t.outcome ?? 'pending'}${t.error ? ` · ${t.error.code}` : ''}` +
|
||||
`${t.cancel_requested ? ' · cancel was requested' : ''}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
rows(diagList, [
|
||||
['Runtime', defaults.runtime],
|
||||
['Page origin', location.origin],
|
||||
['HUD page', s.hudReady ? 'created' : 'not created'],
|
||||
['Device id', s.deviceId || 'none'],
|
||||
['Conversation id', s.state.conversationId ?? 'none'],
|
||||
['Request id', s.state.requestId ?? 'none'],
|
||||
['Generation', String(s.state.generation)],
|
||||
['Audio format', s.status ? `${s.status.audio_format.encoding} ${s.status.audio_format.sample_rate} Hz × ${s.status.audio_format.channels}` : 'unknown'],
|
||||
[
|
||||
'Deadlines',
|
||||
s.status
|
||||
? `transcribe ${s.status.limits.transcribe_deadline_seconds} s · agent ${s.status.limits.agent_deadline_seconds} s · approval ${s.status.limits.approval_wait_seconds} s`
|
||||
: 'unknown',
|
||||
],
|
||||
]);
|
||||
logView.textContent = s.log
|
||||
.slice(-60)
|
||||
.map((e) => `${new Date(e.at).toISOString().slice(11, 23)} ${e.kind.padEnd(12)} ${e.detail}`)
|
||||
.join('\n');
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { evenHubEventFromJson, OsEventTypeList } from '@evenrealities/even_hub_sdk';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeEvent, OS_EVENT, type RawEvenHubEvent } from '../src/device/events.ts';
|
||||
|
||||
/**
|
||||
* These run the published SDK's own parser (`evenHubEventFromJson`) over host
|
||||
* payload shapes, then our normaliser. They verify our mapping against the SDK
|
||||
* as shipped, not against a pair of glasses.
|
||||
*/
|
||||
const parse = (payload: unknown) => normalizeEvent(evenHubEventFromJson(payload) as RawEvenHubEvent);
|
||||
|
||||
describe('event constants', () => {
|
||||
it('match the SDK enum', () => {
|
||||
expect(OS_EVENT).toEqual({
|
||||
CLICK: OsEventTypeList.CLICK_EVENT,
|
||||
SCROLL_TOP: OsEventTypeList.SCROLL_TOP_EVENT,
|
||||
SCROLL_BOTTOM: OsEventTypeList.SCROLL_BOTTOM_EVENT,
|
||||
DOUBLE_CLICK: OsEventTypeList.DOUBLE_CLICK_EVENT,
|
||||
FOREGROUND_ENTER: OsEventTypeList.FOREGROUND_ENTER_EVENT,
|
||||
FOREGROUND_EXIT: OsEventTypeList.FOREGROUND_EXIT_EVENT,
|
||||
ABNORMAL_EXIT: OsEventTypeList.ABNORMAL_EXIT_EVENT,
|
||||
SYSTEM_EXIT: OsEventTypeList.SYSTEM_EXIT_EVENT,
|
||||
IMU_DATA_REPORT: OsEventTypeList.IMU_DATA_REPORT,
|
||||
LONG_PRESS: OsEventTypeList.LONG_PRESS_EVENT,
|
||||
LONG_PRESS_RELEASE: OsEventTypeList.LONG_PRESS_RELEASE_EVENT,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('gestures through the SDK parser', () => {
|
||||
it('a tap arrives with no eventType (protobuf omits zero) on either envelope', () => {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventSource: 1 } })).toEqual([{ type: 'tap' }]);
|
||||
expect(parse({ type: 'textEvent', jsonData: { containerID: 1, containerName: 'body' } })).toEqual([{ type: 'tap' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 0 } })).toEqual([{ type: 'tap' }]);
|
||||
});
|
||||
|
||||
it('double tap, swipes and lifecycle map from sysEvent and textEvent', () => {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
|
||||
expect(parse({ type: 'textEvent', jsonData: { eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
|
||||
expect(parse({ type: 'textEvent', jsonData: { eventType: 1 } })).toEqual([{ type: 'swipe_up' }]);
|
||||
expect(parse({ type: 'textEvent', jsonData: { eventType: 2 } })).toEqual([{ type: 'swipe_down' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 'SCROLL_BOTTOM_EVENT' } })).toEqual([{ type: 'swipe_down' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 4 } })).toEqual([{ type: 'foreground_enter' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 5 } })).toEqual([{ type: 'foreground_exit' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 6 } })).toEqual([{ type: 'abnormal_exit' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 7 } })).toEqual([{ type: 'system_exit' }]);
|
||||
});
|
||||
|
||||
it('ring and left-temple sources produce the same semantic gestures', () => {
|
||||
for (const eventSource of [1, 2, 3]) {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventSource } })).toEqual([{ type: 'tap' }]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventSource, eventType: 3 } })).toEqual([{ type: 'double_tap' }]);
|
||||
}
|
||||
});
|
||||
|
||||
it('audio frames are never mistaken for taps', () => {
|
||||
const out = parse({ type: 'audioEvent', jsonData: { audioPcm: [1, 2, 3, 4] } });
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]!.type).toBe('audio');
|
||||
expect(Array.from((out[0] as { pcm: Uint8Array }).pcm)).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('menu selections carry their item id and are not taps', () => {
|
||||
expect(parse({ type: 'menuItemClickEvent', jsonData: { itemID: 2 } })).toEqual([{ type: 'menu', itemId: 2 }]);
|
||||
});
|
||||
|
||||
it('IMU reports and long presses are outside the interaction contract', () => {
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 8, imuData: { x: 1, y: 2, z: 3 } } })).toEqual([]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 9 } })).toEqual([]);
|
||||
expect(parse({ type: 'sysEvent', jsonData: { eventType: 10 } })).toEqual([]);
|
||||
});
|
||||
|
||||
it('an empty or unknown event produces nothing', () => {
|
||||
expect(normalizeEvent({})).toEqual([]);
|
||||
expect(parse({ type: 'somethingNew', jsonData: {} })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { BODY_BOX, HUD, STATUS_BOX, renderHud } from '../src/core/hud.ts';
|
||||
import { paginate, utf8Bytes, type MeasureLines } from '../src/core/paginate.ts';
|
||||
import { toPlainText } from '../src/core/plaintext.ts';
|
||||
import { initialState, type AppState, type Phase } from '../src/core/reducer.ts';
|
||||
|
||||
/**
|
||||
* Layout tests use Even's own measurement library (@evenrealities/pretext),
|
||||
* which mirrors the firmware's LVGL line breaking. That makes these
|
||||
* measured-against-the-vendor-model tests, not device tests.
|
||||
*/
|
||||
const measure: MeasureLines = (text, width) => measureTextWrap(text, width).lineCount;
|
||||
const box = { width: BODY_BOX.innerWidth, maxLines: HUD.bodyLines, maxBytes: HUD.pageMaxBytes };
|
||||
|
||||
const squash = (s: string) => s.replace(/\s+/g, '');
|
||||
|
||||
function expectValidPages(source: string, pages: string[]) {
|
||||
for (const page of pages) {
|
||||
expect(measure(page, box.width)).toBeLessThanOrEqual(box.maxLines);
|
||||
expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
|
||||
expect(page.length).toBeGreaterThan(0);
|
||||
}
|
||||
// Nothing dropped, nothing duplicated, order preserved (whitespace at page breaks aside).
|
||||
expect(squash(pages.join(' '))).toBe(squash(source));
|
||||
}
|
||||
|
||||
describe('geometry', () => {
|
||||
it('the two containers tile the 576x288 canvas exactly', () => {
|
||||
expect(BODY_BOX.height + STATUS_BOX.height).toBe(HUD.height);
|
||||
expect(STATUS_BOX.y).toBe(BODY_BOX.height);
|
||||
expect(BODY_BOX.height - 2 * HUD.padding).toBe(HUD.bodyLines * HUD.lineHeight);
|
||||
expect(STATUS_BOX.height - 2 * HUD.padding).toBeGreaterThanOrEqual(HUD.lineHeight);
|
||||
});
|
||||
});
|
||||
|
||||
describe('paginate', () => {
|
||||
it('keeps a short answer on one page', () => {
|
||||
expect(paginate('Paris.', box, measure)).toEqual(['Paris.']);
|
||||
expect(paginate(' ', box, measure)).toEqual(['']);
|
||||
});
|
||||
|
||||
it('splits a long answer into pages that each fit, losing nothing', () => {
|
||||
const sentence = 'The quick brown fox jumps over the lazy dog near the riverbank at dawn. ';
|
||||
const source = Array.from({ length: 80 }, (_, i) => `${i + 1}. ${sentence}`).join('').trim();
|
||||
const pages = paginate(source, box, measure);
|
||||
expect(pages.length).toBeGreaterThan(5);
|
||||
expectValidPages(source, pages);
|
||||
});
|
||||
|
||||
it('preserves line breaks inside a page', () => {
|
||||
const source = 'First line\nSecond line\n\nNew paragraph';
|
||||
expect(paginate(source, box, measure)).toEqual([source]);
|
||||
});
|
||||
|
||||
it('handles many short lines (lists) by line count, not characters', () => {
|
||||
const source = Array.from({ length: 40 }, (_, i) => `• item ${i + 1}`).join('\n');
|
||||
const pages = paginate(source, box, measure);
|
||||
expect(pages).toHaveLength(Math.ceil(40 / HUD.bodyLines));
|
||||
expectValidPages(source, pages);
|
||||
});
|
||||
|
||||
it('splits an unbroken run longer than a page without cutting a character in half', () => {
|
||||
const url = 'https://example.com/' + 'a'.repeat(1500);
|
||||
const pages = paginate(`See ${url} now`, box, measure);
|
||||
expectValidPages(`See ${url} now`, pages);
|
||||
});
|
||||
|
||||
it('keeps multi-byte text intact and within the byte budget', () => {
|
||||
const cjk = '東京は日本の首都であり、世界でも有数の大都市です。'.repeat(40);
|
||||
const accents = 'Voilà: café, naïve, façade, São Paulo, Zürich, Kraków, Ελληνικά, кириллица. '.repeat(30);
|
||||
for (const source of [cjk, accents]) {
|
||||
const pages = paginate(source, box, measure);
|
||||
expect(pages.length).toBeGreaterThan(1);
|
||||
expectValidPages(source, pages);
|
||||
// Every page is still well-formed UTF-16 (no lone surrogates).
|
||||
for (const page of pages) expect(page.isWellFormed()).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('never splits a surrogate pair or a ZWJ sequence', () => {
|
||||
const family = '👨👩👧👦';
|
||||
const source = family.repeat(300);
|
||||
const pages = paginate(source, box, measure);
|
||||
expectValidPages(source, pages);
|
||||
for (const page of pages) {
|
||||
expect(page.isWellFormed()).toBe(true);
|
||||
expect(page.length % family.length).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('respects a byte budget tighter than the line budget', () => {
|
||||
const source = 'é'.repeat(4000); // 2 bytes each
|
||||
const pages = paginate(source, { ...box, maxLines: 1000 }, measure);
|
||||
for (const page of pages) expect(utf8Bytes(page)).toBeLessThanOrEqual(box.maxBytes);
|
||||
expect(pages.join('')).toBe(source);
|
||||
});
|
||||
|
||||
it('a 20,000-character answer paginates quickly', () => {
|
||||
const source = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.repeat(360);
|
||||
const started = performance.now();
|
||||
const pages = paginate(source, box, measure);
|
||||
const elapsed = performance.now() - started;
|
||||
expectValidPages(source, pages);
|
||||
expect(elapsed).toBeLessThan(3000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('plain text', () => {
|
||||
it('removes Markdown markup but keeps every word', () => {
|
||||
const md = [
|
||||
'# Answer',
|
||||
'',
|
||||
'The **capital** of *France* is `Paris`. See [the docs](https://example.com/x) or [the anchor](#a).',
|
||||
'',
|
||||
'- one',
|
||||
'* two',
|
||||
'1. three',
|
||||
'',
|
||||
'> quoted',
|
||||
'',
|
||||
'```js',
|
||||
'const a = b * c * d;',
|
||||
'```',
|
||||
'',
|
||||
'| City | Country |',
|
||||
'|------|---------|',
|
||||
'| Paris | France |',
|
||||
'',
|
||||
'---',
|
||||
'<b>bold</b> & <br/>done',
|
||||
].join('\n');
|
||||
const out = toPlainText(md);
|
||||
expect(out).not.toMatch(/[`#>]|\*\*|\]\(|<b>|\|/);
|
||||
for (const word of ['Answer', 'capital', 'France', 'Paris', 'the docs (https://example.com/x)', 'or the anchor.', '• one', '• two', '1. three', 'quoted', 'const a = b * c * d;', 'City · Country', 'Paris · France', 'bold &\ndone']) {
|
||||
expect(out).toContain(word);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves ordinary punctuation, maths and identifiers alone', () => {
|
||||
for (const text of ['2 * 3 * 4 = 24', 'snake_case_name and another_one', 'a < b and b > c', 'Price: $5 * 2', 'Use the -v flag']) {
|
||||
expect(toPlainText(text)).toBe(text);
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves Unicode and normalises line endings', () => {
|
||||
expect(toPlainText('Zürich — 東京 – naïve\r\nline two\r\n\r\n\r\n\r\nline three')).toBe('Zürich — 東京 – naïve\nline two\n\nline three');
|
||||
// Decomposed input is composed, so the firmware sees one code point per accented letter.
|
||||
expect(toPlainText('é')).toBe('é');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HUD frames', () => {
|
||||
const phases: Phase[] = ['unpaired', 'ready', 'listening', 'transcribing', 'thinking', 'approval', 'answer', 'error', 'disconnected', 'cancelled'];
|
||||
const variants = (phase: Phase): AppState[] => {
|
||||
const base: AppState = { ...initialState, phase, captureStartedAt: 0, captureMaxSeconds: 120 };
|
||||
if (phase === 'answer') {
|
||||
return [
|
||||
{ ...base, pages: ['x'], pageIndex: 0 },
|
||||
{ ...base, pages: Array(99).fill('x'), pageIndex: 98, partial: true },
|
||||
];
|
||||
}
|
||||
if (phase === 'disconnected') {
|
||||
return [
|
||||
{ ...base, disconnectedFrom: 'glasses' },
|
||||
{ ...base, disconnectedFrom: 'bridge', canResend: true },
|
||||
{ ...base, disconnectedFrom: 'bridge', canResend: false },
|
||||
];
|
||||
}
|
||||
if (phase === 'error') {
|
||||
return [
|
||||
{ ...base, error: { code: 'outcome_unknown', hud: 'The outcome is unknown. Check the agent before asking again.', retryable: false } },
|
||||
{ ...base, error: { code: 'agent_timeout', hud: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.', retryable: true } },
|
||||
];
|
||||
}
|
||||
if (phase === 'ready') return [base, { ...base, notice: 'New conversation' }];
|
||||
return [base];
|
||||
};
|
||||
|
||||
it('every status line fits on one HUD line and every body fits without scrolling', () => {
|
||||
for (const phase of phases) {
|
||||
for (const state of variants(phase)) {
|
||||
const frame = renderHud(state, 119_000);
|
||||
expect(measure(frame.status, STATUS_BOX.width - 2 * HUD.padding), `status of ${phase}: ${frame.status}`).toBe(1);
|
||||
expect(measure(frame.body, BODY_BOX.innerWidth), `body of ${phase}`).toBeLessThanOrEqual(HUD.bodyLines);
|
||||
expect(utf8Bytes(frame.body)).toBeLessThanOrEqual(999);
|
||||
expect(frame.status.length).toBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('the recording indicator and elapsed time are visible for the whole capture', () => {
|
||||
const state: AppState = { ...initialState, phase: 'listening', captureStartedAt: 10_000, captureMaxSeconds: 30 };
|
||||
expect(renderHud(state, 10_000).status).toContain('● REC 0:00 / 0:30');
|
||||
expect(renderHud(state, 17_400).status).toContain('● REC 0:07 / 0:30');
|
||||
expect(renderHud(state, 17_400).body).toContain('30 seconds');
|
||||
for (const phase of phases.filter((p) => p !== 'listening')) {
|
||||
expect(renderHud({ ...initialState, phase }, 0).status).not.toContain('REC');
|
||||
}
|
||||
});
|
||||
|
||||
it('errors offer a recovery action and send detail to the phone', () => {
|
||||
const frame = renderHud({ ...initialState, phase: 'error', error: { code: 'stt_empty', hud: 'No speech was recognised.', retryable: true } }, 0);
|
||||
expect(frame.body).toContain('No speech was recognised.');
|
||||
expect(frame.body).toContain('phone');
|
||||
expect(frame.status).toContain('Tap');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,332 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
|
||||
|
||||
const ID1 = '11111111-1111-4111-8111-111111111111';
|
||||
const ID2 = '22222222-2222-4222-8222-222222222222';
|
||||
const CONV = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
|
||||
|
||||
function run(state: AppState, ...events: AppEvent[]): { state: AppState; effects: Effect[] } {
|
||||
let effects: Effect[] = [];
|
||||
for (const event of events) {
|
||||
const step = reduce(state, event);
|
||||
state = step.state;
|
||||
effects = step.effects;
|
||||
}
|
||||
return { state, effects };
|
||||
}
|
||||
|
||||
const ready = () =>
|
||||
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null }).state;
|
||||
|
||||
function result(requestId: string, over: Partial<TurnResult> = {}): TurnResult {
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: requestId,
|
||||
conversation_id: CONV,
|
||||
state: 'done',
|
||||
terminal: true,
|
||||
outcome: 'succeeded',
|
||||
cancel_requested: false,
|
||||
input_text: 'q',
|
||||
answer_text: 'a',
|
||||
error: null,
|
||||
replayed: false,
|
||||
created_at: '2026-01-01T00:00:00.000Z',
|
||||
updated_at: '2026-01-01T00:00:01.000Z',
|
||||
timings: { transcribe_ms: 1, agent_ms: 2 },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe('happy path', () => {
|
||||
it('READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER', () => {
|
||||
let s = ready();
|
||||
expect(s.phase).toBe('ready');
|
||||
|
||||
let step = reduce(s, { type: 'activate', freshId: ID1 });
|
||||
s = step.state;
|
||||
expect(s.phase).toBe('listening');
|
||||
expect(step.effects).toEqual([{ type: 'start_capture', generation: s.generation }]);
|
||||
|
||||
s = reduce(s, { type: 'capture_started', generation: s.generation, at: 1000 }).state;
|
||||
expect(s.captureStartedAt).toBe(1000);
|
||||
|
||||
step = reduce(s, { type: 'activate', freshId: ID2 });
|
||||
s = step.state;
|
||||
expect(s.phase).toBe('transcribing');
|
||||
// The request id chosen at activation is the one submitted: the stop tap's id is unused.
|
||||
expect(step.effects).toEqual([{ type: 'stop_capture_and_submit', generation: s.generation, requestId: ID1 }]);
|
||||
|
||||
s = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { state: 'thinking', terminal: false, outcome: null, answer_text: null }),
|
||||
pages: null,
|
||||
}).state;
|
||||
expect(s.phase).toBe('thinking');
|
||||
|
||||
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p1', 'p2', 'p3'] }).state;
|
||||
expect(s.phase).toBe('answer');
|
||||
expect(s.pages).toEqual(['p1', 'p2', 'p3']);
|
||||
expect(s.pageIndex).toBe(0);
|
||||
});
|
||||
|
||||
it('a tap on the answer starts a follow-up in the same conversation', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
|
||||
const step = reduce(s, { type: 'activate', freshId: ID2 });
|
||||
expect(step.state.phase).toBe('listening');
|
||||
expect(step.state.conversationId).toBe(CONV);
|
||||
expect(step.state.requestId).toBe(ID2);
|
||||
expect(step.state.pages).toEqual([]);
|
||||
});
|
||||
|
||||
it('the capture cap stops and submits exactly once', () => {
|
||||
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const step = reduce(s, { type: 'capture_limit', generation: s.generation });
|
||||
expect(step.state.phase).toBe('transcribing');
|
||||
expect(step.effects).toHaveLength(1);
|
||||
s = step.state;
|
||||
expect(reduce(s, { type: 'capture_limit', generation: s.generation }).effects).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('paging', () => {
|
||||
it('moves within bounds and only in ANSWER', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
expect(reduce(s, { type: 'next_page' }).state).toBe(s);
|
||||
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['a', 'b', 'c'] }).state;
|
||||
s = run(s, { type: 'next_page' }, { type: 'next_page' }, { type: 'next_page' }).state;
|
||||
expect(s.pageIndex).toBe(2);
|
||||
s = run(s, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }, { type: 'prev_page' }).state;
|
||||
expect(s.pageIndex).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancellation and stale results', () => {
|
||||
it('double-tap while listening discards the capture and never submits', () => {
|
||||
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const step = reduce(s, { type: 'back' });
|
||||
expect(step.state.phase).toBe('cancelled');
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
expect(step.state.generation).toBe(s.generation + 1);
|
||||
});
|
||||
|
||||
it('cancel while thinking asks the bridge to cancel, and a late answer cannot resurrect the UI', () => {
|
||||
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
const step = reduce(s, { type: 'back' });
|
||||
expect(step.state.phase).toBe('cancelled');
|
||||
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
|
||||
const late = reduce(step.state, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['LATE'] });
|
||||
expect(late.state).toBe(step.state);
|
||||
expect(late.state.pages).toEqual([]);
|
||||
});
|
||||
|
||||
it('a late result for an older request cannot replace a newer answer', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
|
||||
const gen1 = s.generation;
|
||||
s = reduce(s, { type: 'back' }).state; // cancelled
|
||||
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
|
||||
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID2), pages: ['NEW'] }).state;
|
||||
expect(s.pages).toEqual(['NEW']);
|
||||
// Old generation.
|
||||
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
|
||||
// Right generation, wrong request id.
|
||||
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
|
||||
});
|
||||
|
||||
it('a late result for a cancelled request is ignored while a newer request is still in flight', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'first' }).state;
|
||||
const gen1 = s.generation;
|
||||
s = reduce(s, { type: 'back' }).state;
|
||||
s = reduce(s, { type: 'submit_text', freshId: ID2, text: 'second' }).state;
|
||||
expect(s.phase).toBe('thinking');
|
||||
// The old turn finishes late, under its old generation.
|
||||
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
|
||||
// Even mislabelled with the current generation, the request id does not match.
|
||||
expect(reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['OLD'] }).state).toBe(s);
|
||||
// And an old-generation event cannot smuggle in the current request id either.
|
||||
expect(reduce(s, { type: 'turn_update', generation: gen1, result: result(ID2), pages: ['OLD'] }).state).toBe(s);
|
||||
});
|
||||
|
||||
it('stale capture and network events are ignored', () => {
|
||||
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const gen = s.generation;
|
||||
s = reduce(s, { type: 'back' }).state;
|
||||
for (const event of [
|
||||
{ type: 'capture_started', generation: gen, at: 5 },
|
||||
{ type: 'capture_failed', generation: gen, reason: 'mic_refused' },
|
||||
{ type: 'capture_limit', generation: gen },
|
||||
{ type: 'network_lost', generation: gen, stage: 'submit' },
|
||||
{ type: 'turn_rejected', generation: gen, error: { code: 'x', hud: 'x', retryable: false } },
|
||||
] as AppEvent[]) {
|
||||
expect(reduce(s, event).state).toBe(s);
|
||||
}
|
||||
});
|
||||
|
||||
it('a second cancel is a no-op', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }, { type: 'cancel' }).state;
|
||||
const again = reduce(s, { type: 'cancel' });
|
||||
expect(again.state).toBe(s);
|
||||
expect(again.effects).toEqual([]);
|
||||
s = again.state;
|
||||
expect(s.phase).toBe('cancelled');
|
||||
});
|
||||
|
||||
it('back from ANSWER, ERROR and CANCELLED returns to READY; back from READY asks the OS to exit', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
s = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
|
||||
s = reduce(s, { type: 'back' }).state;
|
||||
expect(s.phase).toBe('ready');
|
||||
expect(reduce(s, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
|
||||
expect(reduce(initialState, { type: 'back' }).effects).toEqual([{ type: 'exit_dialog' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('outcomes', () => {
|
||||
const thinking = () => run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
|
||||
it('incomplete answers are shown and flagged as partial', () => {
|
||||
const s = thinking();
|
||||
const next = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { outcome: 'incomplete', error: { code: 'agent_incomplete', message: 'partial', retryable: false } }),
|
||||
pages: ['half'],
|
||||
}).state;
|
||||
expect(next.phase).toBe('answer');
|
||||
expect(next.partial).toBe(true);
|
||||
});
|
||||
|
||||
it('failed and unknown become ERROR with the stable code; unknown is not retryable', () => {
|
||||
const s = thinking();
|
||||
const unknown = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { outcome: 'unknown', answer_text: null, error: { code: 'outcome_unknown', message: 'Unknown.', retryable: false } }),
|
||||
pages: null,
|
||||
}).state;
|
||||
expect(unknown.phase).toBe('error');
|
||||
expect(unknown.error).toEqual({ code: 'outcome_unknown', hud: 'Unknown.', retryable: false });
|
||||
});
|
||||
|
||||
it('approval-required is its own phase and can still be cancelled', () => {
|
||||
let s = thinking();
|
||||
s = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { state: 'approval_required', terminal: false, outcome: null, answer_text: null }),
|
||||
pages: null,
|
||||
}).state;
|
||||
expect(s.phase).toBe('approval');
|
||||
const step = reduce(s, { type: 'back' });
|
||||
expect(step.state.phase).toBe('cancelled');
|
||||
expect(step.effects).toContainEqual({ type: 'cancel_turn', requestId: ID1 });
|
||||
});
|
||||
|
||||
it('a stopped-by-deadline turn is an error, a user cancel confirmed by the bridge is CANCELLED', () => {
|
||||
const s = thinking();
|
||||
const timeout = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { outcome: 'cancelled', answer_text: null, error: { code: 'agent_timeout', message: 'Stopped.', retryable: false } }),
|
||||
pages: null,
|
||||
}).state;
|
||||
expect(timeout.phase).toBe('error');
|
||||
const plain = reduce(s, {
|
||||
type: 'turn_update',
|
||||
generation: s.generation,
|
||||
result: result(ID1, { outcome: 'cancelled', answer_text: null }),
|
||||
pages: null,
|
||||
}).state;
|
||||
expect(plain.phase).toBe('cancelled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('connection loss', () => {
|
||||
it('submit never delivered: DISCONNECTED with a safe resend of the same request id', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'submit' }).state;
|
||||
expect(s.phase).toBe('disconnected');
|
||||
expect(s.canResend).toBe(true);
|
||||
const step = reduce(s, { type: 'activate', freshId: ID2 });
|
||||
expect(step.effects).toEqual([{ type: 'resubmit', generation: s.generation, requestId: ID1 }]);
|
||||
expect(step.state.requestId).toBe(ID1);
|
||||
});
|
||||
|
||||
it('lost while waiting: no resend is offered, and the answer is still accepted when it arrives', () => {
|
||||
let s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
s = reduce(s, { type: 'network_lost', generation: s.generation, stage: 'poll' }).state;
|
||||
expect(s.canResend).toBe(false);
|
||||
expect(reduce(s, { type: 'activate', freshId: ID2 }).effects).toEqual([]);
|
||||
const restored = reduce(s, { type: 'network_restored', generation: s.generation }).state;
|
||||
expect(restored.phase).toBe('thinking');
|
||||
const answered = reduce(s, { type: 'turn_update', generation: s.generation, result: result(ID1), pages: ['p'] }).state;
|
||||
expect(answered.phase).toBe('answer');
|
||||
});
|
||||
|
||||
it('glasses disconnect while listening stops capture; reconnect never reopens the microphone', () => {
|
||||
let s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const step = reduce(s, { type: 'glasses_status', connected: false });
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
expect(step.state.phase).toBe('disconnected');
|
||||
s = step.state;
|
||||
const back = reduce(s, { type: 'glasses_status', connected: true });
|
||||
expect(back.state.phase).toBe('ready');
|
||||
expect(back.effects).toEqual([]);
|
||||
});
|
||||
|
||||
it('glasses disconnect during a running turn keeps the turn', () => {
|
||||
const s = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
expect(reduce(s, { type: 'glasses_status', connected: false }).state).toBe(s);
|
||||
});
|
||||
|
||||
it('app exit while listening stops capture', () => {
|
||||
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const step = reduce(s, { type: 'app_exit' });
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
expect(step.state.phase).toBe('ready');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pairing, restore and conversations', () => {
|
||||
it('unpaired ignores taps', () => {
|
||||
const step = reduce(initialState, { type: 'activate', freshId: ID1 });
|
||||
expect(step.state.phase).toBe('unpaired');
|
||||
expect(step.effects).toEqual([]);
|
||||
});
|
||||
|
||||
it('restoring an in-flight turn polls it and neither resubmits nor records', () => {
|
||||
const step = reduce(initialState, {
|
||||
type: 'init',
|
||||
paired: true,
|
||||
conversationId: CONV,
|
||||
captureMaxSeconds: 20,
|
||||
resumeRequestId: ID1,
|
||||
});
|
||||
expect(step.state.phase).toBe('thinking');
|
||||
expect(step.effects).toEqual([{ type: 'poll', generation: step.state.generation, requestId: ID1 }]);
|
||||
});
|
||||
|
||||
it('new conversation is refused mid-turn and resets cleanly at rest', () => {
|
||||
const busy = run(ready(), { type: 'submit_text', freshId: ID1, text: 'hi' }).state;
|
||||
expect(reduce(busy, { type: 'new_conversation' }).state).toBe(busy);
|
||||
|
||||
const s = ready();
|
||||
const step = reduce(s, { type: 'new_conversation' });
|
||||
expect(step.state.conversationId).toBeNull();
|
||||
expect(step.effects).toEqual([{ type: 'create_conversation', generation: step.state.generation }]);
|
||||
const stale = reduce(step.state, { type: 'conversation_created', generation: s.generation, conversationId: 'old' });
|
||||
expect(stale.state.conversationId).toBeNull();
|
||||
const fresh = reduce(step.state, { type: 'conversation_created', generation: step.state.generation, conversationId: 'new' });
|
||||
expect(fresh.state.conversationId).toBe('new');
|
||||
});
|
||||
|
||||
it('unpairing while listening closes the microphone', () => {
|
||||
const s = run(ready(), { type: 'activate', freshId: ID1 }).state;
|
||||
const step = reduce(s, { type: 'unpaired' });
|
||||
expect(step.state.phase).toBe('unpaired');
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["vite/client"] },
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
// `host: true` so a phone on the same network can load the dev server (QR sideload).
|
||||
// `esnext` because the entry point uses top-level await, as the official templates do.
|
||||
export default defineConfig({
|
||||
server: { host: true, port: 5173 },
|
||||
build: { target: 'esnext' },
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
# Architecture
|
||||
|
||||
```
|
||||
G2 mic / touch / HUD
|
||||
| Bluetooth (Even's protocol, not ours)
|
||||
Even phone app -- WebView running apps/even-client (public Even Hub SDK)
|
||||
| HTTPS, device credential, polling
|
||||
services/bridge (Fastify + SQLite)
|
||||
|-- STT adapter --> an OpenAI-compatible transcription endpoint you choose
|
||||
|-- Hermes adapter --> Hermes API server (Runs API) for one configured profile
|
||||
```
|
||||
|
||||
## Who owns what
|
||||
|
||||
| Concern | Owner |
|
||||
|---|---|
|
||||
| Agent identity, memory, transcript, model, tools, approval policy | Hermes |
|
||||
| Device authorisation, request deduplication, turn lifecycle, deadlines | Bridge |
|
||||
| Microphone, gestures, HUD, app lifecycle | Even runtime on the phone |
|
||||
| Starting, cancelling, resetting, approving | The user |
|
||||
|
||||
The bridge stores references and a short-lived result cache, not a transcript. Question and
|
||||
answer text is erased from the bridge 15 minutes after a turn ends (configurable).
|
||||
|
||||
## Packages
|
||||
|
||||
| Path | Role |
|
||||
|---|---|
|
||||
| `packages/contracts` | Contract v1: JSON Schemas (TypeBox), types, stable error codes. Imported by both sides. |
|
||||
| `services/bridge` | HTTP API, pairing and credentials, turn engine, Hermes and STT adapters, operator CLI. |
|
||||
| `apps/even-client` | Pure state reducer, HUD renderer, pagination, Even adapter, bridge client, phone page. |
|
||||
| `tests/fakes` | Labelled fakes: Hermes Runs API, STT endpoint, glasses, stub model. |
|
||||
| `tests/integration` | Bridge over HTTP, and client-to-bridge end to end, against the fakes. |
|
||||
| `tests/simulator` | The real client in the official simulator. |
|
||||
| `tests/real-hermes` | The bridge against a real Hermes gateway with a stub model. |
|
||||
|
||||
## Client
|
||||
|
||||
`core/reducer.ts` is a pure function `(state, event) -> (state, effects)`. It has no clock, no
|
||||
network and no randomness: request ids arrive inside events and work leaves as effects.
|
||||
|
||||
```
|
||||
READY -> LISTENING -> TRANSCRIBING -> THINKING -> ANSWER
|
||||
plus APPROVAL, ERROR, DISCONNECTED, CANCELLED, UNPAIRED
|
||||
```
|
||||
|
||||
Every user action that starts, cancels or abandons something increments a **generation**
|
||||
counter. Each asynchronous effect carries the generation it started under, and the reducer drops
|
||||
any event whose generation is not current or whose request id is not the current one. That is the
|
||||
single mechanism behind "a late result must not replace a newer answer or resurrect a cancelled
|
||||
screen".
|
||||
|
||||
`core/controller.ts` runs the effects: microphone capture, submit with retry, polling, cancel,
|
||||
conversation creation, persistence. `device/port.ts` is the seam to the glasses; the Even adapter
|
||||
and the test fake both implement it.
|
||||
|
||||
## Bridge turn lifecycle
|
||||
|
||||
```
|
||||
accepted -> transcribing -> thinking -> done
|
||||
|-> approval_required -> thinking
|
||||
|-> cancelling -> done
|
||||
```
|
||||
|
||||
`done` always carries an outcome: `succeeded`, `incomplete`, `failed`, `cancelled` or `unknown`.
|
||||
|
||||
Order of operations for one turn:
|
||||
|
||||
1. Validate, authenticate, check the conversation belongs to the device and is open, and that no
|
||||
other turn is running in it. Insert the turn row keyed by the client's request id. A repeat of
|
||||
the same request id returns the existing turn.
|
||||
2. Audio only: wrap the PCM as WAV in memory, transcribe, drop the audio.
|
||||
3. Persist the exact Hermes request body, then send it with `Idempotency-Key`.
|
||||
4. Persist the returned run id and erase the stored body.
|
||||
5. Poll the run until it is terminal, a deadline passes, or a cancel is requested.
|
||||
|
||||
Why the order matters: after step 3 a crash can always be recovered by re-sending the identical
|
||||
body under the same key (Hermes returns the original run), and before step 3 nothing has reached
|
||||
Hermes, so failing the turn is provably safe.
|
||||
|
||||
## How ambiguous situations are classified
|
||||
|
||||
| Situation | Outcome | Retryable |
|
||||
|---|---|---|
|
||||
| STT error, timeout or empty transcript | failed | yes: nothing reached Hermes |
|
||||
| Bridge restarted before step 3 | failed (`interrupted_before_agent`) | yes |
|
||||
| Connection to Hermes refused on every attempt | failed (`agent_unreachable`) | yes |
|
||||
| Hermes answered 4xx | failed (`agent_rejected`) | no |
|
||||
| Request sent, no usable reply, deadline passed | **unknown** | no |
|
||||
| Hermes reports `unknown` or no longer knows the run | **unknown** | no |
|
||||
| Deadline passed, stop requested, Hermes confirmed | cancelled (`agent_timeout`) | no |
|
||||
| Stop requested, not confirmed within the grace period | **unknown** | no |
|
||||
| Cancel requested but the run completed first | succeeded, `cancel_requested: true` | n/a |
|
||||
|
||||
"Retryable" means a deliberate new question by the user is safe. Nothing is ever replayed
|
||||
automatically under a new request id.
|
||||
|
||||
## Deliberate limits of this slice
|
||||
|
||||
- One process, one profile, one active conversation per device.
|
||||
- Polling only; no streaming.
|
||||
- A second question while one is running in the same conversation is refused
|
||||
(`conversation_busy`), not queued.
|
||||
- Capture ends by tap or cap. There is no end-of-speech detection.
|
||||
@@ -0,0 +1,126 @@
|
||||
# Bridge API, contract v1
|
||||
|
||||
These endpoints are Hermeven's own. They are not Hermes or Even APIs. Schemas live in
|
||||
`packages/contracts/src/schemas.ts` and are enforced on every request; the client validates
|
||||
every response against the same schemas.
|
||||
|
||||
All routes except `/healthz` and `/v1/pairing/claim` require `Authorization: Bearer <device token>`.
|
||||
Every error has the shape:
|
||||
|
||||
```json
|
||||
{ "schema_version": 1, "error": { "code": "conversation_busy", "message": "...", "retryable": true } }
|
||||
```
|
||||
|
||||
| Method and path | Purpose | Success |
|
||||
|---|---|---|
|
||||
| `GET /healthz` | Liveness only. Returns `{"status":"ok","schema_version":1}` and nothing else. | 200 |
|
||||
| `POST /v1/pairing/claim` | Exchange a single-use pairing code for a device credential. | 201 |
|
||||
| `GET /v1/device` | Pairing status, limits, whether the agent is reachable and STT is configured. | 200 |
|
||||
| `POST /v1/device/renew` | Rotate the device token. The old token stops working at once. | 200 |
|
||||
| `DELETE /v1/device` | Revoke this device and close its conversation. | 200 |
|
||||
| `POST /v1/conversations` | Start a new conversation; closes the device's previous one. | 201 |
|
||||
| `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate |
|
||||
| `GET /v1/turns/{request_id}` | Current state and result. | 200 |
|
||||
| `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 |
|
||||
|
||||
There is no SSE endpoint. Streaming through the Even WebView is undocumented and untested, so
|
||||
polling is the supported path.
|
||||
|
||||
## Creating a turn
|
||||
|
||||
Typed text (`Content-Type: application/json`):
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"request_id": "0b9f6c1e-3c1d-4b1e-9a51-2f6d0f4c8a11",
|
||||
"conversation_id": "5d0c2c35-6a8f-4f0e-8f55-0d1f7c0b2a90",
|
||||
"locale": "en-US",
|
||||
"input": { "kind": "text", "text": "What is on my calendar tomorrow?" }
|
||||
}
|
||||
```
|
||||
|
||||
Audio (`Content-Type: application/octet-stream`): the body is the raw PCM, and the metadata is in
|
||||
the query string. Audio is never placed in JSON.
|
||||
|
||||
```
|
||||
POST /v1/turns?schema_version=1&request_id=...&conversation_id=...&locale=en-US
|
||||
&input_kind=audio&encoding=pcm_s16le&sample_rate=16000&channels=1
|
||||
```
|
||||
|
||||
| Rule | Value |
|
||||
|---|---|
|
||||
| Accepted audio | `pcm_s16le`, 16000 Hz, 1 channel. Anything else: 415 `unsupported_media`. |
|
||||
| Maximum audio | capture cap + 1 second, 992,000 bytes at the default 30 s. Larger: 413. |
|
||||
| Maximum text | 4,000 characters |
|
||||
| Unknown fields | rejected (400). A client cannot name a Hermes session or profile. |
|
||||
| Rate | 20 new turns per minute per device by default. Duplicates do not count. |
|
||||
|
||||
`request_id` is generated by the client and is the idempotency identity. Submitting the same id
|
||||
with the same content returns the existing turn with `"replayed": true`. The same id with
|
||||
different content, or from another device, returns 409 `request_id_conflict`.
|
||||
|
||||
## Turn result
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"request_id": "...",
|
||||
"conversation_id": "...",
|
||||
"state": "done",
|
||||
"terminal": true,
|
||||
"outcome": "succeeded",
|
||||
"cancel_requested": false,
|
||||
"input_text": "what is on my calendar tomorrow",
|
||||
"answer_text": "...",
|
||||
"error": null,
|
||||
"replayed": false,
|
||||
"created_at": "2026-11-18T18:00:00.000Z",
|
||||
"updated_at": "2026-11-18T18:00:04.210Z",
|
||||
"timings": { "transcribe_ms": 640, "agent_ms": 3410 }
|
||||
}
|
||||
```
|
||||
|
||||
- `state`: `accepted`, `transcribing`, `thinking`, `approval_required`, `cancelling`, `done`.
|
||||
- `outcome` (when `terminal`): `succeeded`, `incomplete`, `failed`, `cancelled`, `unknown`.
|
||||
- `answer_text` is the agent's complete answer. The bridge never shortens it.
|
||||
- `input_text` and `answer_text` become `null` once the retention window passes.
|
||||
- An HTTP 200 only means the bridge answered. Read `terminal` and `outcome`.
|
||||
|
||||
## Error codes
|
||||
|
||||
Defined in `packages/contracts/src/errors.ts`. Codes are stable; a code is never repurposed.
|
||||
|
||||
| Code | Meaning | Retryable |
|
||||
|---|---|---|
|
||||
| `invalid_request`, `unsupported_schema_version`, `unsupported_media`, `payload_too_large` | The request was malformed. | no |
|
||||
| `unauthorized`, `credential_expired`, `forbidden` | Credential missing, revoked or expired. | no |
|
||||
| `pairing_invalid`, `pairing_locked` | Wrong code; too many wrong codes. | no |
|
||||
| `not_found` | Unknown, or belongs to another device. | no |
|
||||
| `request_id_conflict` | Request id reused for different content. | no |
|
||||
| `conversation_busy` | A turn is still running in this conversation. | yes |
|
||||
| `conversation_closed` | The conversation was replaced or the device was revoked. | no |
|
||||
| `rate_limited` | Too many requests. | yes |
|
||||
| `stt_unavailable`, `stt_failed`, `stt_timeout`, `stt_empty` | Transcription did not produce text. Nothing reached the agent. | yes |
|
||||
| `interrupted_before_agent` | The bridge restarted before sending. Nothing ran. | yes |
|
||||
| `agent_unreachable` | Hermes never received the request. Nothing ran. | yes |
|
||||
| `agent_rejected` | Hermes refused the request. Nothing ran. | no |
|
||||
| `agent_failed`, `agent_interrupted` | The agent ran and failed or was interrupted. Actions already taken are not undone. | no |
|
||||
| `agent_timeout`, `approval_timeout` | The bridge stopped the run after a deadline. | no |
|
||||
| `agent_incomplete` | The agent stopped short; the answer is partial. | no |
|
||||
| `outcome_unknown` | The bridge cannot tell whether the turn ran. Check the agent first. | no |
|
||||
|
||||
## Operating budgets
|
||||
|
||||
Defaults, all configurable. These are limits, not measured performance.
|
||||
|
||||
| Budget | Default |
|
||||
|---|---|
|
||||
| Capture | 30 s |
|
||||
| Transcription deadline | 30 s |
|
||||
| Agent deadline | 120 s, paused while an approval is pending |
|
||||
| Approval wait | 300 s |
|
||||
| Grace period to confirm a stop | 30 s |
|
||||
|
||||
No latency percentiles are published because none have been measured against a real STT
|
||||
provider, a real model or a real device.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Draft 01: A first slice, and what it does not prove yet
|
||||
|
||||
> Draft, written by Claude (an AI agent) on 2026-11-18. Not published anywhere. Not approved by
|
||||
> Dan. Not in Dan's voice. No part of this describes real glasses.
|
||||
|
||||
## What was attempted
|
||||
|
||||
A first end-to-end slice of Hermeven: tap the glasses, ask a question out loud, read a short
|
||||
answer on the display, ask a follow-up. The agent behind it is the user's own Hermes; a small
|
||||
bridge sits between the glasses app and Hermes.
|
||||
|
||||
## What actually ran
|
||||
|
||||
- The glasses app, inside Even's official simulator: it created its display page, opened the
|
||||
simulated microphone on a tap, sent the audio on a second tap, drew a multi-page answer, turned
|
||||
pages on a swipe, took a follow-up, and cancelled on a double tap.
|
||||
- The bridge, against a real Hermes gateway running a stand-in model: a typed question was
|
||||
answered, a follow-up carried the earlier turn, six identical submissions reached the model
|
||||
once, a cancel stopped the run, and a bridge restart mid-answer still delivered it once.
|
||||
- Automated tests of the awkward cases: lost replies, timeouts, duplicate taps, revoked
|
||||
credentials, late answers arriving after a cancel.
|
||||
|
||||
## What did not run
|
||||
|
||||
- Nothing ran on real glasses.
|
||||
- No real speech was transcribed. The recogniser in every test was a stand-in.
|
||||
- No real language model answered. No real tool was called.
|
||||
|
||||
## What was learned
|
||||
|
||||
- Even's public SDK hands apps raw audio, not text. Transcription has to happen elsewhere.
|
||||
- An Even Hub app may only call servers named in its package. So "bring your own agent" means
|
||||
a build per server for now.
|
||||
- Even's documentation says microphone capture stops when the phone app is suspended. The whole
|
||||
idea rests on asking with the phone locked in a pocket, and that is untested.
|
||||
- Two official sources disagreed with the published SDK about a background feature. The
|
||||
published package won.
|
||||
|
||||
## What failed along the way
|
||||
|
||||
- The first simulator run "recorded" 30 seconds in under two: the silent test audio device is not
|
||||
paced in real time. The test was wrong, not the app.
|
||||
- One test passed for the wrong reason and one failed for the wrong reason; deliberately breaking
|
||||
the code to see which tests noticed found two gaps, now covered.
|
||||
|
||||
## Next bounded step
|
||||
|
||||
Put it on the glasses and run the first checklist item that matters: phone locked, in a pocket,
|
||||
ask a question. Report what happens either way.
|
||||
|
||||
## Evidence
|
||||
|
||||
`docs/test-evidence.md`, `docs/evidence/simulator/` (simulator screenshots, labelled as such).
|
||||
@@ -0,0 +1,53 @@
|
||||
# Compatibility matrix
|
||||
|
||||
Recorded 2026-11-18. Versions are pinned in `package-lock.json`; the Even packages are pinned
|
||||
exactly in `apps/even-client/package.json`.
|
||||
|
||||
## Repository baseline
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Remote | `git@git.xylo.gg:Xylo-Digital/hermeven.git` |
|
||||
| State when work began | Empty repository: `git ls-remote` returned no refs, so there was no base branch, no base SHA and no repository instructions to follow. |
|
||||
| Working branch | `feat/vertical-slice-1` (local; nothing has been pushed) |
|
||||
|
||||
## Even
|
||||
|
||||
| Component | Version | How it was used |
|
||||
|---|---|---|
|
||||
| `@evenrealities/even_hub_sdk` | 0.0.16 | Client runtime. Declares minimum Even app 2.2.10. |
|
||||
| `@evenrealities/pretext` | 0.1.4 | Text measurement for pagination. |
|
||||
| `@evenrealities/evenhub-simulator` | 0.9.5 (linux-x64) | Simulator tests. |
|
||||
| `@evenrealities/evenhub-cli` | 0.2.0 | `evenhub pack` accepted the generated manifest and stamped `min_app_version 2.2.10`. |
|
||||
| Even phone app | not tested | Must be 2.2.10 or later per the SDK. |
|
||||
| G2 firmware, R1 ring | not tested | No device was available. |
|
||||
|
||||
## Hermes
|
||||
|
||||
| Component | Version | How it was used |
|
||||
|---|---|---|
|
||||
| hermes-agent | v0.23.1 (2026.9.24), commit `3b42157` | Docs and source read; a real gateway run in a throwaway `HERMES_HOME` with a stub model. |
|
||||
| API surface used | `GET /health`, `POST /v1/runs`, `GET /v1/runs/{id}`, `POST /v1/runs/{id}/stop` | See `docs/decisions/0002-hermes-runs-api.md`. |
|
||||
| Dan's target Hermes deployment | **not inspected** | No access. Version and configuration unverified. |
|
||||
|
||||
## Toolchain
|
||||
|
||||
| Component | Version |
|
||||
|---|---|
|
||||
| Node.js | 22.23.2 (requires 22.13 or later) |
|
||||
| TypeScript | 5.9.3 |
|
||||
| Vite / Vitest | 8.3.8 / 5.1.1 |
|
||||
| Fastify / @fastify/cors | 5.12.8 / 11.4.3 |
|
||||
| better-sqlite3 | 13.2.0 |
|
||||
| @sinclair/typebox | 0.34.52 |
|
||||
| pino | 10.4.0 |
|
||||
|
||||
## Known version hazards
|
||||
|
||||
- The official `everything-evenhub` skills describe SDK 0.0.12 and simulator 0.7.1 in places and
|
||||
are stale against 0.0.16. They name two functions (`setBackgroundState`,
|
||||
`onBackgroundRestore`) that SDK 0.0.16 does not export. See `docs/feasibility.md` item 8.
|
||||
- `evenhub pack` reads the SDK's minimum app version from npm `latest` unless `--sdk-ver` is
|
||||
given. The `pack` script passes `--sdk-ver 0.0.16` so builds are reproducible.
|
||||
- Hermes keeps a keyed run's idempotency record for 24 hours. The bridge finishes or abandons a
|
||||
turn within minutes, so the window is not a constraint today.
|
||||
@@ -0,0 +1,18 @@
|
||||
# 0001: TypeScript monorepo, SQLite, no new services
|
||||
|
||||
Status: accepted for the first slice. Date: 2026-11-18.
|
||||
|
||||
The repository was empty, so the layout proposed in the specification was adopted as written:
|
||||
`apps/even-client`, `services/bridge`, `packages/contracts`, `tests`, `docs`.
|
||||
|
||||
- One language end to end, so the client and the bridge compile against the same contract types
|
||||
and JSON Schemas (`@hermeven/contracts`, TypeBox).
|
||||
- npm workspaces, no build step for the bridge (run with `tsx`). A compiled build can come with
|
||||
packaging.
|
||||
- SQLite (better-sqlite3, WAL) for devices, conversation bindings and turn records. Single user,
|
||||
single process; no database service or queue.
|
||||
- The operator CLI writes to the SQLite file directly, so the bridge exposes no administrative
|
||||
endpoint at all.
|
||||
|
||||
Consequence: rate limits and in-flight turn workers are in-process. Running two bridge processes
|
||||
on one database is not supported.
|
||||
@@ -0,0 +1,51 @@
|
||||
# 0002: Use the Hermes Runs API, not `/v1/responses`
|
||||
|
||||
Status: accepted for the first slice; revisit if the target Hermes differs. Date: 2026-11-18.
|
||||
|
||||
## Context
|
||||
|
||||
The specification says to use the supported authenticated Hermes API, "normally
|
||||
`/v1/responses`", and to verify cancellation, idempotency and continuity before relying on it.
|
||||
Both were checked against hermes-agent v0.23.1 (docs and source), then against a running gateway.
|
||||
|
||||
| Need | `/v1/responses` | `/v1/runs` |
|
||||
|---|---|---|
|
||||
| Start a turn without holding a connection for its whole duration | No. Non-streaming blocks until the turn ends; streaming holds an SSE connection. | Yes. Returns 202 and a `run_id` at once. |
|
||||
| Read status later, including after a bridge restart | Only the finished response by id. | `GET /v1/runs/{id}`. |
|
||||
| Cancel | No endpoint. Only dropping a streaming connection interrupts the agent. | `POST /v1/runs/{id}/stop`; status settles as `cancelled`. |
|
||||
| Idempotent create | Yes, with replay rules that depend on the response store. | Yes: durable reservation, 24-hour retention, identical retry returns the same `run_id`. |
|
||||
| Approval-required visible | Not as a pollable state. | `waiting_for_approval`. |
|
||||
| "Outcome unknown" visible | 409 `unknown_execution` on retry. | `unknown` status. |
|
||||
| Continuity | `previous_response_id` or `conversation`. | `session_id` (loads that session's transcript). |
|
||||
|
||||
## Decision
|
||||
|
||||
One adapter (`services/bridge/src/hermes/runsAdapter.ts`) using `POST /v1/runs`,
|
||||
`GET /v1/runs/{id}` and `POST /v1/runs/{id}/stop`.
|
||||
|
||||
- Continuity: each Hermeven conversation owns one bridge-generated Hermes `session_id`
|
||||
(`hermeven-<uuid>`). It is never accepted from, or shown to, a client.
|
||||
- Idempotency: `Idempotency-Key: hermeven-turn-<request id>`. The exact request body is persisted
|
||||
before the first attempt so a retry is byte-identical, and erased once the run id is stored.
|
||||
- The bridge never calls the approval endpoint.
|
||||
|
||||
## Verified
|
||||
|
||||
Against a real gateway with a stub model: admission, identical replay
|
||||
(`Idempotency-Replayed: true`), 409 on a changed body, session continuity (the model received
|
||||
both user turns), stop settling as `cancelled`, and re-attachment after a bridge restart.
|
||||
|
||||
## Not verified
|
||||
|
||||
`waiting_for_approval`, `unknown`, `interrupted` and the stopped-short (`completed: false`) shape
|
||||
are implemented from the source and exercised only against the test fake, because the stub model
|
||||
calls no tools. They need a run against a real model with a tool that requires approval.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Polling adds up to one poll interval (500 ms by default) of latency to every answer.
|
||||
- No token streaming to the HUD. Acceptable: the HUD shows whole pages, and streaming through the
|
||||
Even WebView is undocumented.
|
||||
- If the target Hermes runs without the durable run ledger, the idempotency guarantee weakens.
|
||||
The bridge should check `/v1/capabilities` `runs_idempotency.durable` at startup; that check is
|
||||
not implemented yet.
|
||||
@@ -0,0 +1,22 @@
|
||||
# 0003: Gesture binding for the first slice
|
||||
|
||||
Status: provisional until device-tested. Date: 2026-11-18.
|
||||
|
||||
The product contract is the set of semantic actions (activate, stop/submit, cancel/back,
|
||||
next/previous page, new conversation). Gestures are a replaceable binding.
|
||||
|
||||
| Action | Binding | Why |
|
||||
|---|---|---|
|
||||
| activate, stop/submit | tap | The only gesture every source agrees reaches the app. Tap to start and tap to stop makes the end of capture explicit and deterministic. |
|
||||
| cancel / back | double tap | Even's submission rules require double tap on the root page to open the OS exit dialog. Treating double tap as "back one level" everywhere makes that the natural end of the same gesture. |
|
||||
| next / previous page | swipe down / swipe up | Matches Even's text-heavy template. |
|
||||
| new conversation, cancel request | OS contextual menu items | Keeps a destructive-feeling action off a single accidental gesture. |
|
||||
|
||||
Rejected for now:
|
||||
|
||||
- **Hold to talk** (long press, release to send). Attractive, but the OS claims tap-then-long-press
|
||||
for its menu, and the two official sources disagree about how long-press events are routed.
|
||||
- **End-of-speech detection.** Not attempted. Capture ends on tap, cancel, or the visible cap.
|
||||
|
||||
Open for device testing: whether Even treats a double tap that cancels a request (not on the root
|
||||
page) as acceptable under its exit rule, accidental double-tap rate, and ring behaviour.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Physical-device test plan
|
||||
|
||||
**Status: not started. No step below has been run.** Only Dan, or someone holding the G2, can run
|
||||
these and sign them off. A passing simulator or test suite does not count toward any item here.
|
||||
|
||||
Record results in a copy of this file under `docs/evidence/device/<date>.md`: for every step
|
||||
write pass, fail or not run, plus what you saw. Record failures as carefully as passes.
|
||||
|
||||
## Before you start: write these down
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Date and tester | |
|
||||
| Hermeven commit | |
|
||||
| G2 firmware version | |
|
||||
| R1 ring firmware (if used) | |
|
||||
| Even phone app version (needs 2.2.10+) | |
|
||||
| Phone model and OS version | |
|
||||
| Install method | QR sideload / private test / **beta channel** |
|
||||
| Bridge host, how the phone reaches it | |
|
||||
| Hermes version and profile (read-only or test profile) | |
|
||||
| STT provider and model | |
|
||||
|
||||
Lock-screen steps are only meaningful on a **beta-channel build**: Even's docs say sideloaded
|
||||
apps stop when the phone locks.
|
||||
|
||||
## A. Feasibility checks (do these first; each answers an open question)
|
||||
|
||||
| # | Step | What to record | Open question it answers |
|
||||
|---|---|---|---|
|
||||
| A1 | Open the phone page, Diagnostics. | The exact "Page origin" value. Put it in `HERMEVEN_ALLOWED_ORIGINS`. | WebView origin is undocumented. |
|
||||
| A2 | Pair with a code from `bridge:cli -- pair`. | Does pairing succeed? If not, the error text. | Whitelist and CORS on a real phone. |
|
||||
| A3 | Look at the HUD at rest. | Is "Hermeven / Ready." and the status line fully readable in your fitted position? Photo if possible. | Legibility, layout. |
|
||||
| A4 | Tap once on the right temple. | Does the HUD show `● REC` with a running timer? Was there a permission prompt? | Tap delivery; mic permission. |
|
||||
| A5 | Speak for about 5 seconds, tap again. | The timer value when you tapped, and "captured N s" in Diagnostics. Do they agree within a second? | Real frame pacing and size. |
|
||||
| A6 | Wait for the answer. | Was the transcript (phone page, "Sent to the agent") what you said? Time from tap to answer. | Real STT and Hermes path. |
|
||||
| A7 | Ask something with a long answer. Swipe down, then up. | Does each swipe turn exactly one page? Does any page scroll inside itself or cut a line? | Whether measurement matches firmware. |
|
||||
| A8 | Double tap on an answer, then double tap again at "Ready". | First returns to Ready; second shows the system exit dialog. | Double-tap delivery; exit rule. |
|
||||
| A9 | Tap, then long-press. | Does the OS menu show "New conversation" and "Cancel request"? Choose "New conversation". | Contextual menu, never exercised. |
|
||||
| A10 | Repeat A4 to A8 with the left temple, then the ring. | Any gesture that behaves differently. | Ring and left-temple parity. |
|
||||
| A11 | While recording, read the phone's developer console. | Is raw audio data being printed there? | Audio echo seen in the simulator. |
|
||||
| A12 | Start recording and say nothing for 35 seconds. | Does it stop by itself at 0:30 and submit? | Capture cap. |
|
||||
| A13 | **Lock the phone, put it in a pocket, tap, ask, tap.** | Does `● REC` appear? Does an answer arrive? If not, what does the HUD show? | **The first outcome.** |
|
||||
| A14 | With the phone locked for 5 minutes, tap. | Is the app still responsive? | Suspension. |
|
||||
| A15 | Try to start native captions while Hermeven is open, and Hermeven while captions run. | Exactly what happens and how you get back. | Coexistence with captions. |
|
||||
| A16 | Answer containing accents, a currency symbol, and non-Latin text. | Which characters appear, which are missing. | Glyph coverage. |
|
||||
|
||||
If A13 fails, stop and report it. It is a product-level blocker, not a bug to work around.
|
||||
|
||||
## B. Real integration (spec section 9)
|
||||
|
||||
| # | Step | Pass condition |
|
||||
|---|---|---|
|
||||
| B1 | One spoken question, real STT, real Hermes, answer on the HUD. | Answer is relevant to what was said. |
|
||||
| B2 | Say "My name is <name>." then ask "What is my name?" | Second answer uses the name. |
|
||||
| B3 | Choose "New conversation", ask "What is my name?" | The agent does not know. |
|
||||
| B4 | With a tool that leaves a countable trace (for example appending a line to a test file), ask once, and while it is thinking pull the phone's network for 5 seconds. | The trace shows exactly one execution. |
|
||||
| B5 | Ask for something that needs approval in the test profile. | HUD says approval required; nothing is approved from the glasses; approving on Hermes's own surface completes it. |
|
||||
| B6 | Start a long request, double tap. | HUD says Cancelled; the phone page shows the true outcome; no late answer appears. |
|
||||
|
||||
## C. Acceptance (do not call the MVP usable before these)
|
||||
|
||||
| # | Step | Record |
|
||||
|---|---|---|
|
||||
| C1 | 10 consecutive question and follow-up cycles, phone locked and pocketed. | Attempts, successes, and every failure with what the HUD showed. |
|
||||
| C2 | Turn Bluetooth off for 20 seconds while idle, and again while waiting for an answer. | What the HUD shows; whether the answer still arrives; that the microphone did not reopen. |
|
||||
| C3 | Walk out of range while recording, come back. | Recording stopped; nothing was sent; no automatic recording on return. |
|
||||
| C4 | Switch to another phone app for a minute and back, idle and mid-request. | State on return. |
|
||||
| C5 | Take a phone call mid-recording and mid-request. | State afterwards; no unintended recording. |
|
||||
| C6 | Restart the bridge mid-request. | The answer still arrives once; no duplicate tool run. |
|
||||
| C7 | Revoke the device on the bridge host, then tap and ask. | HUD says to pair again; nothing reaches the agent. |
|
||||
| C8 | Over the whole session: any unintended recording, any answer from the wrong conversation, any stale answer, any duplicate execution? | Each as yes or no with detail. |
|
||||
| C9 | Read a five-page answer in your normal fitted position. | Comfortable or not; what would change. |
|
||||
| C10 | Battery: glasses and phone percentage at start and after a stated duration and number of questions. | The four numbers and the duration. Do not extrapolate. |
|
||||
| C11 | Per question: seconds from second tap to answer, noted for at least 10 questions. | The raw list. The phone page shows the STT and agent split for each. |
|
||||
|
||||
## Reporting
|
||||
|
||||
Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to
|
||||
be written into the README as such.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
@@ -0,0 +1,282 @@
|
||||
# Feasibility report
|
||||
|
||||
Prepared 2026-11-18 for the first vertical slice. It answers the questions in section 2 of the
|
||||
kickoff specification.
|
||||
|
||||
## How to read this
|
||||
|
||||
Each finding carries one status:
|
||||
|
||||
| Status | Meaning |
|
||||
|---|---|
|
||||
| **documented** | Stated by an official Even or Hermes source, or by the published package's own types. Not exercised by us. |
|
||||
| **simulator-tested** | We ran it in the official Even Hub simulator 0.9.5 (see `docs/test-evidence.md`). |
|
||||
| **hermes-tested** | We ran it against a real `hermes gateway` v0.23.1 with a stub model. |
|
||||
| **device-tested** | Run on a physical G2. **Nothing in this report has this status.** |
|
||||
| **unsupported** | The public SDK does not offer it. |
|
||||
| **unknown** | Not documented and not something we could exercise. |
|
||||
|
||||
Simulator evidence is not device evidence. Even's own simulator README says the simulator
|
||||
"is a supplement to, not a replacement for, hardware testing".
|
||||
|
||||
## Sources
|
||||
|
||||
| Source | Version read |
|
||||
|---|---|
|
||||
| `@evenrealities/even_hub_sdk` (npm) | 0.0.16, README and `dist/index.d.ts` |
|
||||
| `@evenrealities/evenhub-simulator` (npm) | 0.9.5 |
|
||||
| `@evenrealities/evenhub-cli` (npm) | 0.2.0 |
|
||||
| `@evenrealities/pretext` (npm) | 0.1.4 |
|
||||
| `even-realities/everything-evenhub` (GitHub) | commit `cb8321f` (2026-10-21), all 13 skills |
|
||||
| `even-realities/evenhub-templates` (GitHub) | commit `8cb0135` (2026-08-07) |
|
||||
| hub.evenrealities.com/docs | all 48 sidebar pages, fetched 2026-11-18 |
|
||||
| hermes-agent (local install) | v0.23.1, commit `3b42157`, docs and `gateway/platforms/api_server*.py` |
|
||||
|
||||
Citations use `docs:<path>` for `https://hub.evenrealities.com/docs/<path>`, `skill:<name>` for
|
||||
`everything-evenhub/plugins/everything-evenhub/skills/<name>/SKILL.md`, `templates:<path>` for
|
||||
the templates repository, and `sdk:` for the published SDK package.
|
||||
|
||||
The official sources contradict each other in several places (they were written against
|
||||
different SDK versions). Where they do, both positions are given and the item is marked for
|
||||
device verification.
|
||||
|
||||
## Summary of what matters most
|
||||
|
||||
1. **The first outcome's hardest requirement, voice capture with the phone locked in a pocket,
|
||||
is not established.** The docs say microphone capture "Stops if the WebView is suspended".
|
||||
This needs a device test before anything else is built on it.
|
||||
2. **The public SDK provides raw PCM only.** There is no transcription API. STT has to be a
|
||||
server-side provider.
|
||||
3. **Every deployment needs its own app build.** Even Hub blocks network requests to any origin
|
||||
not listed in the packaged `app.json`. The bridge hostname therefore cannot be chosen at
|
||||
run time by the user of a store build. This affects distribution and is escalated below.
|
||||
4. **Hub apps are foreground-only on the glasses.** Running alongside native captions is not
|
||||
something the public SDK offers.
|
||||
5. Everything else the slice needs (text HUD, gestures, an OS menu, app storage, HTTPS fetch)
|
||||
is documented and works in the simulator.
|
||||
|
||||
## Findings
|
||||
|
||||
### 1. Microphone format and callbacks
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| Audio arrives through `bridge.onEvenHubEvent` as `event.audioEvent.audioPcm` (`Uint8Array`). | documented, simulator-tested | sdk: README "MIC Source" |
|
||||
| Format is 16 kHz, signed 16-bit little-endian, mono, on both glasses and phone sources. | documented, simulator-tested | docs:build/device-apis, "Format on both sources: PCM 16 kHz, signed 16-bit little-endian, mono." |
|
||||
| Frames are 100 ms (3,200 bytes). | documented for the simulator, simulator-tested; **unknown on device** | docs:test/simulator says payloads "match what the device emits". No page states the device frame size independently. |
|
||||
| `audioEvent` also carries `source`, `direction` and `speakerRole`. `speakerRole` is "the App audio algorithm result, not a firmware identity assertion". | documented | sdk: README |
|
||||
|
||||
What we did about it: the client accepts frames of any size and only requires the total to be
|
||||
whole 16-bit samples. The bridge accepts exactly one declared format (`pcm_s16le`, 16000 Hz,
|
||||
1 channel) and refuses anything else with `unsupported_media`.
|
||||
|
||||
Observed in the simulator, source not determined: every hub event, **including each raw PCM
|
||||
frame**, is echoed to the WebView console with an `[EvenAppBridge]` prefix. We could not tell
|
||||
whether the SDK or the simulator's host shim prints it (the SDK bundle is minified and contains
|
||||
no such literal string). Whether the phone's developer console receives audio the same way is
|
||||
**unknown** and is on the device checklist, because the docs call console output
|
||||
"reviewer-visible".
|
||||
|
||||
### 2. Start/stop lifecycle
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| `audioControl(true, AudioInputSource.Glasses)` starts, `audioControl(false)` stops. | documented, simulator-tested | sdk: README |
|
||||
| The glasses microphone requires `createStartUpPageContainer` to have succeeded first. | documented | docs:build/device-apis; skill:sdk-reference |
|
||||
| Permission `g2-microphone` must be declared; "Permission prompts fire on first invocation, not at launch." | documented | docs:test/private-testing |
|
||||
| `audioControl` returns `false` on failure. | documented | sdk: `audioControl(...): Promise<boolean>` |
|
||||
| Maximum capture duration imposed by the platform. | **unknown** | not documented |
|
||||
| The microphone may be left running if the app does not stop it on exit. | documented | skill:device-features |
|
||||
|
||||
What we did about it: the microphone opens only on a tap, closes on send, cancel, the capture
|
||||
cap (default 30 s), glasses disconnect, app exit and page unload. If no audio frame arrives for
|
||||
3 seconds while recording, the capture is ended with an error, which covers permission loss and
|
||||
a suspended stream. The microphone is never reopened without a new tap.
|
||||
|
||||
### 3. SDK-provided ASR versus raw audio
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| The public SDK has no speech-to-text API. | **unsupported** | No ASR in `sdk:` types, docs or skills. The official `asr` template says "The STT client itself is a blank stub... You pick your own provider". |
|
||||
|
||||
Decision: one server-side adapter for any service that implements the OpenAI
|
||||
`POST /audio/transcriptions` contract (hosted or self-hosted Whisper). It is exercised only
|
||||
against a test fake so far. **No real STT provider has been run**; none was available on the
|
||||
development machine and choosing a paid one is Dan's decision (see "Decisions needed").
|
||||
|
||||
### 4. Input events
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| G2 temples and the R1 ring give press, double press, swipe up, swipe down, long press and release. The ring has the "Same gesture set as Even G2, distinguishable by source". | documented | docs:build/device-apis |
|
||||
| Event type values 0 to 10 (`CLICK`, `SCROLL_TOP`, `SCROLL_BOTTOM`, `DOUBLE_CLICK`, lifecycle, `LONG_PRESS`, `LONG_PRESS_RELEASE`). | documented, verified against the SDK enum in tests | sdk: `OsEventTypeList` |
|
||||
| A tap arrives with **no `eventType`** because `CLICK_EVENT` is 0 and protobuf omits zero values. | documented, verified against the SDK parser in tests | templates:README.md |
|
||||
| Which envelope carries a tap on a text container: docs say `textEvent`, the skills and templates say `sysEvent`. | **conflicting**; simulator delivers gestures that our both-envelope reader handles | docs:build/device-apis vs skill:handle-input |
|
||||
| Tap, double tap, swipe up and swipe down reach the app. | simulator-tested | automation actions `click`, `double_click`, `up`, `down` |
|
||||
| Tap followed by long press is claimed by the OS and opens the contextual menu. App items are declared with `menuObject` (up to 10, names up to 32 UTF-8 bytes); a selection arrives as `menuItemClickEvent`. | documented; our menu declaration was accepted by the simulator; **selecting an item is not yet exercised** | docs:build/contextual-menu |
|
||||
| Double tap on the root page must call `shutDownPageContainer(1)`. Apps that do nothing or exit silently "are rejected". | documented | docs:ship/app-submission |
|
||||
| `FOREGROUND_ENTER`/`FOREGROUND_EXIT` also fire when the OS menu opens and closes. | documented | docs:build/contextual-menu |
|
||||
| Ring gestures behave the same as temple gestures in practice. | **unknown**; the simulator hard-codes the right-temple source | simulator README |
|
||||
|
||||
Mapping used by this slice (semantic action, then the gesture bound to it today):
|
||||
|
||||
| Semantic action | Gesture | Notes |
|
||||
|---|---|---|
|
||||
| activate | tap | at rest, on an answer (follow-up), or to resend an undelivered request |
|
||||
| stop and submit | tap | while recording |
|
||||
| cancel / back | double tap | cancels capture or request; at rest returns to the root page; on the root page asks the OS to exit |
|
||||
| next / previous page | swipe down / swipe up | on an answer |
|
||||
| new conversation | OS menu item | also available on the phone |
|
||||
| cancel request | OS menu item | duplicate path to double tap |
|
||||
|
||||
The product contract is the left-hand column. The gestures are one binding of it and are held
|
||||
in two small files (`device/events.ts`, the controller's event switch), so they can change
|
||||
after device testing without touching the state machine. A glasses-only path exists for every
|
||||
action except new conversation, which uses the OS menu (glasses) or the phone.
|
||||
|
||||
### 5. HUD layout and text constraints
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| Canvas is 576 x 288 px per eye, origin top-left, 4-bit greyscale shown as green. | documented, simulator-tested (screenshots are 576 x 288) | docs:build/display |
|
||||
| One firmware font, not monospaced, no size or weight control. "Characters outside the font set are silently dropped." | documented | docs:build/display |
|
||||
| Line height is a fixed 27 px. | documented | skill:font-measurement |
|
||||
| Text limits: 1,000 characters for create and rebuild, 2,000 for `textContainerUpgrade`; byte-denominated elsewhere (999 / 1,999). | documented, units conflict | docs:build/display; docs:reference/changelog (simulator "999-byte text container limit") |
|
||||
| If content overflows a capturing text container "the firmware scrolls it". | documented | docs:build/display |
|
||||
| Even publishes `@evenrealities/pretext` for "pixel-accurate" wrapping measurement, and the text-heavy template paginates with it. | documented | templates:text-heavy |
|
||||
| `textContainerUpgrade` updates in place without flicker; `rebuildPageContainer` "flashes the full page". | documented | templates:text-heavy |
|
||||
| No numeric rate limit for text updates; guidance is to serialise all bridge calls and debounce. | documented as guidance only | skill:glasses-ui |
|
||||
| Emoji do not render. Full glyph coverage is not officially tabulated. | documented / **unknown** | docs:reference/faq |
|
||||
|
||||
What we did about it: two text containers tile the canvas, a 9-line body (which takes the
|
||||
gestures) and a 1-line status bar that always shows the state and, while recording, a
|
||||
`● REC m:ss / m:ss` indicator. Answers are paginated with `pretext` to at most 9 measured lines
|
||||
**and** at most 900 UTF-8 bytes per page, so a page never overflows and the firmware never
|
||||
scrolls it. Nothing is truncated: every page is reachable by swiping, and the phone shows the
|
||||
complete original. Markdown and HTML markup are removed for the HUD; the wording is not changed.
|
||||
|
||||
Simulator-tested: page 2 of a long answer fills exactly 9 lines with the status bar beneath
|
||||
(`docs/evidence/simulator/05-answer-page-2.png`), and swiping down then up returns a
|
||||
pixel-identical page 1. **Unknown until a device test:** whether `pretext` agrees with the real
|
||||
firmware for the text Dan actually reads, legibility at his fitted position, and behaviour for
|
||||
characters missing from the firmware font.
|
||||
|
||||
### 6. Networking
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| The WebView can only reach origins listed in the `network` permission's `whitelist` in `app.json`. "Use the full origin... bare hostnames and wildcards aren't supported." | documented | docs:build/networking |
|
||||
| The whitelist "is not a CORS bypass"; the WebView enforces normal CORS. | documented | docs:build/networking |
|
||||
| The WebView's own origin is not specified. | **unknown** | docs say "the WebView origin if you can identify it" |
|
||||
| "HTTPS in production. Plain http:// is only useful for local dev against a LAN dev server." | documented | docs:build/networking |
|
||||
| `fetch` with a JSON body and with a binary body, with an `Authorization` header and a CORS preflight, works. | simulator-tested | this slice's simulator run |
|
||||
| WebSockets are allowed under the same whitelist; "Expect drops when the WebView backgrounds." | documented | docs:reference/faq |
|
||||
| SSE and streaming `fetch`. | **unknown** | not documented |
|
||||
| "WebView is suspended on background; in-flight requests stall." | documented | docs:reference/faq |
|
||||
| Whether the whitelist is enforced during QR sideloading. | **unknown** | not stated |
|
||||
|
||||
What we did about it: polling over plain `fetch` only, which is the fallback the specification
|
||||
allows. No SSE or WebSocket is used. Because the request is idempotent on the bridge and the
|
||||
client re-attaches by request id, a stalled or dropped request cannot run a turn twice.
|
||||
|
||||
Two consequences need Dan's attention:
|
||||
|
||||
- **The bridge origin is baked into each packaged build.** The repository contains no hostname:
|
||||
`app.json` is generated at build time from `HERMEVEN_BRIDGE_ORIGIN`. But a single store build
|
||||
cannot serve users with different bridges unless Even adds user-configurable origins or the
|
||||
product routes through one fixed relay origin. This is a distribution question, not an MVP
|
||||
blocker.
|
||||
- **The bridge's CORS allow-list needs the WebView's origin, which is not documented.** The
|
||||
phone page's diagnostics panel prints `location.origin` so it can be read on the device and
|
||||
put into `HERMEVEN_ALLOWED_ORIGINS`. Until that is done on a real phone, CORS configuration
|
||||
for a packaged build is unverified.
|
||||
|
||||
### 7. Storage
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| `bridge.setLocalStorage` / `getLocalStorage` store strings and survive app restarts. | documented, simulator-tested within one run | sdk: README; skill:device-features |
|
||||
| Browser `localStorage` reliability: the docs FAQ says it survives; the skill says it does "NOT reliably persist". | **conflicting** | docs:reference/faq vs skill:device-features |
|
||||
| Storage is sandboxed per `package_id`. | documented | docs |
|
||||
| Any secure or encrypted storage. | **unsupported / not offered** | nothing in the SDK or docs is described as secure |
|
||||
|
||||
What we did about it: the device credential is kept in the Even app storage and the phone page
|
||||
says plainly that this is not an encrypted vault. The credential is scoped to one device and
|
||||
one configured profile, expires after 7 days (renewable up to a 90-day pairing lifetime), is
|
||||
revocable from the phone or the bridge host, and is stored on the bridge only as a hash. It
|
||||
cannot reach the Hermes API directly and cannot choose a profile or session.
|
||||
|
||||
### 8. Lock screen, suspension and background restore
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| iOS: "The WebView keeps running." Android: "May be suspended under memory pressure... Treat Android suspend as 'the app starts cold.'" | documented | docs:build/background-lifecycle |
|
||||
| Microphone capture "Stops if the WebView is suspended... don't assume the stream is still live." | documented | docs:build/background-lifecycle |
|
||||
| QR-sideloaded apps do not survive the lock screen at all; private-testing builds "don't pass the 5-minute lock test"; beta builds do. | documented | docs:test/index |
|
||||
| Store review requires the app to stay alive with the phone locked for 5 minutes. | documented | docs:ship/app-submission |
|
||||
| The `background-state` skill describes a headless-WebView migration with `setBackgroundState` / `onBackgroundRestore` exported from the SDK. | **not present**: SDK 0.0.16 exports neither function and its bundle has no `__getStateSnapshot` string | skill:background-state vs sdk: `dist/index.d.ts` |
|
||||
| Whether a voice question can be captured and answered with the phone locked and pocketed. | **unknown** | no source addresses it; this is the first outcome |
|
||||
|
||||
Stated plainly, as the specification asks: **a state-persistence helper does not prove
|
||||
background microphone execution, and in SDK 0.0.16 even the helper is not there.** We did not
|
||||
invent it. Instead the app persists the one thing that matters, the id of a turn in flight, to
|
||||
app storage. A page that is killed and restarted re-attaches to that turn by polling and never
|
||||
resubmits it or reopens the microphone (covered by an automated test with fakes).
|
||||
|
||||
Whether capture works while locked can only be answered on the device, and it must be tested
|
||||
with a **beta-channel build**, since the docs say sideloaded builds die on lock.
|
||||
|
||||
### 9. Coexistence with native captions
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| "Plugins are foreground-only on the glasses." | documented | docs:reference/faq |
|
||||
| "After exit, glasses can launch other apps and first-party apps (Conversate, Navigate)". | documented | docs:ship/app-submission |
|
||||
| Any API to read native captions or run beside them. | **unsupported** | none in the SDK |
|
||||
| What happens to a Hub app when a native feature or notification interrupts it. | **unknown** | not documented |
|
||||
|
||||
Conclusion: assume the user must switch between Hermeven and native captions. This is reported
|
||||
as a limitation, not hidden. It is on the device checklist to record exactly what the switch
|
||||
looks like.
|
||||
|
||||
### 10. Hermes API (the other half of feasibility)
|
||||
|
||||
| Finding | Status | Source |
|
||||
|---|---|---|
|
||||
| Bearer auth with `API_SERVER_KEY`; the server refuses to start without one. | documented, hermes-tested (401 without it) | hermes docs; `_check_auth` |
|
||||
| `POST /v1/runs` returns 202 with a `run_id`; `GET /v1/runs/{id}` is pollable; `POST /v1/runs/{id}/stop` interrupts. | documented, hermes-tested | hermes docs "Runs API" |
|
||||
| `Idempotency-Key` on `/v1/runs`: an identical retry returns the original `run_id` with `Idempotency-Replayed: true`; a different body returns 409 `idempotency_key_conflict`; durable, retained 24 hours. | documented, hermes-tested | hermes docs; `/v1/capabilities` reported `{"supported":true,"durable":true,"retention_seconds":86400}` |
|
||||
| A `session_id` in the run body continues that API-created session: Hermes loads its transcript. | documented, hermes-tested (the model received both user turns) | `_handle_runs` |
|
||||
| `/v1/responses` has no cancel endpoint; a turn is interrupted only by dropping a streaming connection. | source-verified | `_write_sse_responses` |
|
||||
| Run statuses include `waiting_for_approval`, `unknown` (owner restarted mid-turn) and `interrupted` (gateway shutdown). | documented; **not hermes-tested** (the stub model calls no tools) | hermes docs |
|
||||
| A run that stops short (iteration budget) reports `failed` with `completed: false` and usable `output`. | source-verified; **not hermes-tested** | `terminal_run_status` |
|
||||
| `instructions` is layered on the agent's prompt per request, without changing stored history. | documented, hermes-tested | hermes docs "System Prompt Handling" |
|
||||
|
||||
Decision recorded in `docs/decisions/0002-hermes-runs-api.md`: the adapter uses the Runs API,
|
||||
not `/v1/responses`. The specification said "normally `/v1/responses`" and also asked us to
|
||||
verify cancellation and idempotency; Responses cannot cancel or be polled in flight, and Runs
|
||||
can. No `conversation_id` field is sent to Hermes.
|
||||
|
||||
**Not verified:** Dan's actual target deployment. The specification mentions a Hermes
|
||||
reachable from "Pepper's environment"; we had no access to it. All Hermes evidence here is from
|
||||
the hermes-agent v0.23.1 installed on the development machine, run in a throwaway home
|
||||
directory with a stub model. The target's version, profile routing (`/p/<profile>/`), tool
|
||||
permissions and approval policy are unverified.
|
||||
|
||||
## Decisions needed from Dan
|
||||
|
||||
1. **Device access.** Nothing here is device-tested. The checklist is `docs/device-test-plan.md`.
|
||||
Lock-screen capture comes first because it can invalidate the product's first outcome.
|
||||
2. **STT provider.** Hosted (per-minute cost, audio leaves your network) or self-hosted Whisper
|
||||
(free, needs a machine). The adapter is the same either way.
|
||||
3. **Target Hermes.** Which deployment and profile the bridge should point at, and a safe
|
||||
read-only test profile for the first real run.
|
||||
4. **Distribution model**, given the per-build network whitelist: one build per deployment, or a
|
||||
relay origin. Not needed for the single-user slice.
|
||||
|
||||
## What was escalated rather than worked around
|
||||
|
||||
- No background-microphone guarantee was assumed.
|
||||
- No SDK function was invented; the two background helpers named by an official skill but
|
||||
absent from the published SDK are not called.
|
||||
- No native Android/iOS app was started. Nothing measured so far requires one, but item 8 could.
|
||||
@@ -0,0 +1,77 @@
|
||||
# Security and threat model
|
||||
|
||||
Scope: the single-user slice. One owner, one bridge, one Hermes profile, one or a few paired
|
||||
devices. Not reviewed by anyone but its author yet; see `docs/handoff/`.
|
||||
|
||||
## What is being protected
|
||||
|
||||
| Asset | Why it matters |
|
||||
|---|---|
|
||||
| The Hermes API key | It gives full use of the agent, "including terminal commands" per Hermes's docs. |
|
||||
| The ability to make the agent act | A forged or replayed turn could run tools. |
|
||||
| Voice recordings, questions, answers | Private by nature. |
|
||||
| The STT provider key | Billing and access. |
|
||||
|
||||
## Trust boundaries
|
||||
|
||||
1. **Phone WebView to bridge.** Untrusted network. The client holds only a device credential.
|
||||
2. **Bridge to Hermes and to STT.** The bridge holds the real secrets. Both must be HTTPS unless
|
||||
on loopback; the bridge refuses to start otherwise.
|
||||
3. **Bridge host.** Whoever can run the CLI or read the SQLite file is the owner.
|
||||
|
||||
## Controls in this slice
|
||||
|
||||
| Threat | Control | Tested |
|
||||
|---|---|---|
|
||||
| Hermes key or STT key leaks through the client | Neither is in the client code, bundle or any API response. The production bundle was searched for them. | yes |
|
||||
| Stolen device credential | Scoped to one device and one profile; cannot name a Hermes session; expires in 7 days; pairing ends at 90 days; revocable from the phone or the bridge host; stored on the bridge as SHA-256 only. | yes |
|
||||
| Guessing a pairing code | 10 characters from a 31-symbol alphabet (about 49 bits); valid 5 minutes; single use; a new code voids the old one; 5 wrong guesses burn every outstanding code; 5 attempts per minute per client address. | yes |
|
||||
| Client picks someone else's agent session or profile | Requests with unknown fields are rejected. The Hermes session id is generated by the bridge and never leaves it. A device is valid only for the profile it was paired under. | yes |
|
||||
| One device reads or cancels another's turn | Every lookup is scoped to the authenticated device; a foreign id answers 404, not 403. | yes |
|
||||
| Duplicate or replayed submit runs a tool twice | Client request id is the bridge's idempotency key; the bridge forwards a derived key to Hermes. | yes, including against real Hermes |
|
||||
| Blind replay after a timeout | A sent-but-unanswered request ends as `unknown`, never as retryable. | yes |
|
||||
| Oversized or malformed input | 32 kB JSON limit; audio capped at capture length + 1 s; schema validation; only one audio format accepted. | yes |
|
||||
| Request flooding | Per-device turn limit, per-address pairing limit, general per-device limit. | yes |
|
||||
| Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes |
|
||||
| Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes |
|
||||
| Recordings retained | Audio exists only in memory for the length of one transcription call and is never written to disk by the bridge. | by construction; not independently audited |
|
||||
| Agent approves its own privileged action | The bridge never calls Hermes's approval endpoint. | yes |
|
||||
| Markup injection from an agent answer into the phone page | The page is built with `textContent` only. | by construction |
|
||||
| Administrative access over the network | There is none. Pairing codes and revocation are CLI-only. | by construction |
|
||||
| Accidental public exposure | Binds 127.0.0.1 by default; a non-loopback bind needs an explicit setting. | yes |
|
||||
|
||||
## Known gaps and accepted risks
|
||||
|
||||
Stated so they are not mistaken for protections.
|
||||
|
||||
1. **The device credential is not in secure storage.** Even's app storage is not described as
|
||||
encrypted, and the public SDK offers nothing better. The mitigation is that the credential is
|
||||
narrow, expiring and revocable, not that it is safe at rest. Anyone with the unlocked phone, or
|
||||
with developer access to the app's storage, can use it until it is revoked.
|
||||
2. **Renewal needs only the current token.** A thief who renews before the owner notices keeps
|
||||
access until revoked or until the 90-day pairing lifetime ends.
|
||||
3. **Audio leaves the device and, with a hosted STT provider, leaves your network.** A
|
||||
self-hosted Whisper endpoint avoids this. The provider's own retention is outside our control.
|
||||
4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone
|
||||
does the same is unknown and is on the device checklist. If it does, recordings would be
|
||||
visible to whoever can read that console.
|
||||
5. **TLS is not terminated by the bridge.** A reverse proxy or private network must provide it. A
|
||||
misconfigured proxy could expose plain HTTP.
|
||||
6. **Rate limits are in memory** and reset on restart. Behind a proxy, per-address limits are only
|
||||
meaningful with `HERMEVEN_TRUST_PROXY=true` and a proxy that sets the forwarded address.
|
||||
7. **The 15-minute result cache holds question and answer text in SQLite in clear text**, as does
|
||||
the pending request body for the moment between sending and recording the run id.
|
||||
8. **The SQLite file and `.env` are protected only by file permissions** on the bridge host.
|
||||
9. **No audit trail** of pairings and revocations beyond the log stream.
|
||||
10. **The network whitelist puts the bridge origin into the packaged app**, where anyone with the
|
||||
package can read it. The origin is not a secret and must not be treated as one.
|
||||
11. **The agent's tool permissions are whatever the Hermes profile allows.** Hermeven does not
|
||||
narrow them. Use a read-only or test profile until approval handling is proven on a device.
|
||||
12. **Dependencies were not audited** beyond `npm install` reporting no known vulnerabilities on
|
||||
2026-11-18.
|
||||
|
||||
## Operational rules
|
||||
|
||||
- Keep `.env` out of git (it is ignored) and out of screenshots.
|
||||
- Never put a real key in a tutorial, a build-in-public post or an issue.
|
||||
- Revoke a lost device from the bridge host: `npm run bridge:cli -- revoke <device-id>`.
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# Setup
|
||||
|
||||
Requirements: Node.js 22.13 or later, a Hermes install with the API server enabled, and (for
|
||||
voice) an OpenAI-compatible transcription endpoint.
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
cp .env.example .env # then edit: HERMES_API_KEY at minimum
|
||||
```
|
||||
|
||||
## 1. Hermes
|
||||
|
||||
Enable the API server for the profile you want to use (see Hermes's "API Server" docs):
|
||||
|
||||
```sh
|
||||
# in that profile's .env
|
||||
API_SERVER_ENABLED=true
|
||||
API_SERVER_KEY=<a long random value>
|
||||
```
|
||||
|
||||
Start the gateway, then put the same key in Hermeven's `.env` as `HERMES_API_KEY`. Use a
|
||||
read-only or test profile first.
|
||||
|
||||
## 2. Bridge
|
||||
|
||||
```sh
|
||||
npm run bridge # listens on 127.0.0.1:8787 by default
|
||||
curl http://127.0.0.1:8787/healthz
|
||||
```
|
||||
|
||||
The phone must reach the bridge over HTTPS. Two workable arrangements:
|
||||
|
||||
- a reverse proxy with a certificate in front of the loopback listener, or
|
||||
- a private network such as Tailscale with its HTTPS certificates.
|
||||
|
||||
Then set `HERMEVEN_ALLOWED_ORIGINS` to the origin of the page that calls the bridge. For a
|
||||
packaged app that value is not documented by Even: open the phone page, expand Diagnostics, read
|
||||
"Page origin", put that in `.env` and restart the bridge.
|
||||
|
||||
## 3. Try it without glasses
|
||||
|
||||
```sh
|
||||
npm run client:dev # http://localhost:5173
|
||||
```
|
||||
|
||||
Add `HERMEVEN_ALLOWED_ORIGINS=http://localhost:5173` to `.env`, restart the bridge, then:
|
||||
|
||||
```sh
|
||||
npm run bridge:cli -- pair # prints a one-time code
|
||||
```
|
||||
|
||||
Open the page, enter the bridge address and the code, and use "Typed question". This browser
|
||||
preview has no microphone and is not the glasses.
|
||||
|
||||
## 4. Simulator
|
||||
|
||||
```sh
|
||||
npm run client:dev
|
||||
npm run simulate -- http://localhost:5173
|
||||
```
|
||||
|
||||
`npm run simulate` calls the simulator package directly, because with npm 10.9 workspaces the
|
||||
`evenhub-simulator` command link was not created by `npm ci` on the development machine
|
||||
(`npm rebuild @evenrealities/evenhub-simulator` also restores it).
|
||||
|
||||
The simulator uses your computer's default audio input as the microphone. Add `--aid alsa:null`
|
||||
on Linux if you do not want it to open one.
|
||||
|
||||
## 5. On the glasses
|
||||
|
||||
The Even app only allows network requests to origins listed in the app's manifest, so the bridge
|
||||
origin is supplied when you build:
|
||||
|
||||
```sh
|
||||
export HERMEVEN_BRIDGE_ORIGIN=https://your-bridge.example
|
||||
npm run -w @hermeven/even-client pack # writes hermeven.ehpk
|
||||
```
|
||||
|
||||
For a first look, sideload the dev server instead: `npm run client:dev`, then
|
||||
`npx evenhub qr --url http://<your-lan-ip>:5173` and scan it from the Even app (developer mode).
|
||||
Even's docs say sideloaded apps stop when the phone locks, so lock-screen behaviour has to be
|
||||
tested with a beta-channel build (`evenhub create`, `evenhub promote --to beta`). Uploading
|
||||
anything to Even's portal is Dan's call.
|
||||
|
||||
Then follow `docs/device-test-plan.md`.
|
||||
|
||||
## Operating
|
||||
|
||||
```sh
|
||||
npm run bridge:cli -- devices # list
|
||||
npm run bridge:cli -- revoke <device-id> # revoke now
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm test # unit + integration, fakes only
|
||||
npm run test:simulator # needs a desktop session; opens the simulator window
|
||||
npm run test:real-hermes # needs the hermes CLI; uses a throwaway HERMES_HOME and a stub model
|
||||
```
|
||||
Generated
+2622
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "hermeven",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"description": "Even Realities G2 interface to a user-controlled Hermes Agent",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22.13.0"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*",
|
||||
"services/*",
|
||||
"apps/*"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p packages/contracts && tsc -p services/bridge && tsc -p apps/even-client && tsc -p tests",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run --project contracts --project bridge --project even-client",
|
||||
"test:integration": "vitest run --project integration",
|
||||
"test:simulator": "vitest run --config tests/simulator/vitest.config.ts",
|
||||
"test:real-hermes": "vitest run --config tests/real-hermes/vitest.config.ts",
|
||||
"bridge": "npm run -w @hermeven/bridge start --",
|
||||
"bridge:cli": "npm run -w @hermeven/bridge cli --",
|
||||
"client:dev": "npm run -w @hermeven/even-client dev --",
|
||||
"client:build": "npm run -w @hermeven/even-client build",
|
||||
"simulate": "node node_modules/@evenrealities/evenhub-simulator/bin/index.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.0",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^5.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@hermeven/contracts",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.34.52"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Stable, machine-readable error codes for the Hermeven bridge contract.
|
||||
*
|
||||
* Codes are part of the versioned contract: never repurpose one. `retryable`
|
||||
* means "a deliberate NEW turn by the user is safe", never "replay automatically".
|
||||
*/
|
||||
export const ERROR_CODES = {
|
||||
// transport / auth
|
||||
invalid_request: { http: 400, retryable: false },
|
||||
unsupported_schema_version: { http: 400, retryable: false },
|
||||
unauthorized: { http: 401, retryable: false },
|
||||
credential_expired: { http: 401, retryable: false },
|
||||
forbidden: { http: 403, retryable: false },
|
||||
not_found: { http: 404, retryable: false },
|
||||
request_id_conflict: { http: 409, retryable: false },
|
||||
conversation_busy: { http: 409, retryable: true },
|
||||
conversation_closed: { http: 409, retryable: false },
|
||||
payload_too_large: { http: 413, retryable: false },
|
||||
unsupported_media: { http: 415, retryable: false },
|
||||
rate_limited: { http: 429, retryable: true },
|
||||
pairing_invalid: { http: 401, retryable: false },
|
||||
pairing_locked: { http: 429, retryable: false },
|
||||
internal: { http: 500, retryable: false },
|
||||
// turn outcomes (carried in TurnResult.error, HTTP status of the GET is still 200)
|
||||
stt_unavailable: { http: 200, retryable: true },
|
||||
stt_failed: { http: 200, retryable: true },
|
||||
stt_timeout: { http: 200, retryable: true },
|
||||
stt_empty: { http: 200, retryable: true },
|
||||
/** Bridge restarted before anything was sent to Hermes: nothing ran. */
|
||||
interrupted_before_agent: { http: 200, retryable: true },
|
||||
/** Hermes definitely did not admit the turn (connection refused, 4xx, 429/503). */
|
||||
agent_unreachable: { http: 200, retryable: true },
|
||||
agent_rejected: { http: 200, retryable: false },
|
||||
/** Hermes ran the turn and reported failure. Tools may already have acted. */
|
||||
agent_failed: { http: 200, retryable: false },
|
||||
/** Hermes interrupted the turn (gateway shutdown). Tools may already have acted. */
|
||||
agent_interrupted: { http: 200, retryable: false },
|
||||
/** Deadline passed; a stop was requested and Hermes confirmed it. */
|
||||
agent_timeout: { http: 200, retryable: false },
|
||||
/** Hermes waited for a human approval that never arrived on a verified surface. */
|
||||
approval_timeout: { http: 200, retryable: false },
|
||||
/** Hermes stopped short (for example iteration budget); the text is partial. */
|
||||
agent_incomplete: { http: 200, retryable: false },
|
||||
/** Downstream status could not be reconciled. NOT permission to run again. */
|
||||
outcome_unknown: { http: 200, retryable: false },
|
||||
} as const;
|
||||
|
||||
export type ErrorCode = keyof typeof ERROR_CODES;
|
||||
|
||||
export const ERROR_CODE_LIST = Object.keys(ERROR_CODES) as ErrorCode[];
|
||||
|
||||
export function isRetryable(code: ErrorCode): boolean {
|
||||
return ERROR_CODES[code].retryable;
|
||||
}
|
||||
|
||||
export function httpStatusFor(code: ErrorCode): number {
|
||||
return ERROR_CODES[code].http;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './errors.ts';
|
||||
export * from './schemas.ts';
|
||||
@@ -0,0 +1,260 @@
|
||||
import { Type, type Static, type TSchema } from '@sinclair/typebox';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { ERROR_CODE_LIST, type ErrorCode } from './errors.ts';
|
||||
|
||||
/** Contract version. Bump on any breaking change; the bridge rejects unknown versions. */
|
||||
export const SCHEMA_VERSION = 1 as const;
|
||||
|
||||
/**
|
||||
* Audio the bridge accepts. Validated against what the Even Hub SDK actually
|
||||
* emits (see docs/feasibility.md, "Microphone"): raw PCM, signed 16-bit
|
||||
* little-endian, mono, 16 kHz. Nothing else is accepted until it is measured.
|
||||
*/
|
||||
export const AUDIO_FORMAT = {
|
||||
encoding: 'pcm_s16le',
|
||||
sampleRate: 16000,
|
||||
channels: 1,
|
||||
bytesPerSecond: 16000 * 2,
|
||||
} as const;
|
||||
|
||||
/** Defaults; the bridge can lower them via configuration and reports the effective values. */
|
||||
export const DEFAULT_LIMITS = {
|
||||
captureMaxSeconds: 30,
|
||||
transcribeDeadlineSeconds: 30,
|
||||
agentDeadlineSeconds: 120,
|
||||
approvalWaitSeconds: 300,
|
||||
textMaxChars: 4000,
|
||||
} as const;
|
||||
|
||||
const Uuid = Type.String({
|
||||
pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',
|
||||
description: 'Lower-case RFC 4122 UUID',
|
||||
});
|
||||
const Locale = Type.String({ pattern: '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$', maxLength: 20 });
|
||||
const IsoTime = Type.String({ minLength: 20, maxLength: 30 });
|
||||
const SchemaVersion = Type.Literal(SCHEMA_VERSION);
|
||||
|
||||
export const ErrorBody = Type.Object(
|
||||
{
|
||||
code: Type.Union(ERROR_CODE_LIST.map((c) => Type.Literal(c))),
|
||||
message: Type.String({ maxLength: 300 }),
|
||||
retryable: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ErrorBody = { code: ErrorCode; message: string; retryable: boolean };
|
||||
|
||||
export const ErrorResponse = Type.Object(
|
||||
{ schema_version: SchemaVersion, error: ErrorBody },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ErrorResponse = { schema_version: typeof SCHEMA_VERSION; error: ErrorBody };
|
||||
|
||||
// ---------------------------------------------------------------- health
|
||||
export const HealthResponse = Type.Object(
|
||||
{ status: Type.Literal('ok'), schema_version: SchemaVersion },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type HealthResponse = Static<typeof HealthResponse>;
|
||||
|
||||
// --------------------------------------------------------------- pairing
|
||||
export const PairingClaimRequest = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
code: Type.String({ minLength: 4, maxLength: 32 }),
|
||||
device_name: Type.String({ minLength: 1, maxLength: 60 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type PairingClaimRequest = Static<typeof PairingClaimRequest>;
|
||||
|
||||
export const DeviceCredential = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
device_id: Uuid,
|
||||
/** Opaque bearer credential. Shown once; the bridge stores only a hash. */
|
||||
token: Type.String({ minLength: 32, maxLength: 128 }),
|
||||
token_expires_at: IsoTime,
|
||||
/** Absolute lifetime of this pairing; after it the user must pair again. */
|
||||
pairing_expires_at: IsoTime,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type DeviceCredential = Static<typeof DeviceCredential>;
|
||||
|
||||
export const Limits = Type.Object(
|
||||
{
|
||||
capture_max_seconds: Type.Integer({ minimum: 1 }),
|
||||
transcribe_deadline_seconds: Type.Integer({ minimum: 1 }),
|
||||
agent_deadline_seconds: Type.Integer({ minimum: 1 }),
|
||||
approval_wait_seconds: Type.Integer({ minimum: 1 }),
|
||||
audio_max_bytes: Type.Integer({ minimum: 1 }),
|
||||
text_max_chars: Type.Integer({ minimum: 1 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type Limits = Static<typeof Limits>;
|
||||
|
||||
export const DeviceStatusResponse = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
device_id: Uuid,
|
||||
device_name: Type.String(),
|
||||
token_expires_at: IsoTime,
|
||||
pairing_expires_at: IsoTime,
|
||||
/** Whether the bridge could reach its configured agent just now. No detail by design. */
|
||||
agent_reachable: Type.Boolean(),
|
||||
stt_configured: Type.Boolean(),
|
||||
active_conversation_id: Type.Union([Uuid, Type.Null()]),
|
||||
limits: Limits,
|
||||
audio_format: Type.Object(
|
||||
{
|
||||
encoding: Type.Literal(AUDIO_FORMAT.encoding),
|
||||
sample_rate: Type.Literal(AUDIO_FORMAT.sampleRate),
|
||||
channels: Type.Literal(AUDIO_FORMAT.channels),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type DeviceStatusResponse = Static<typeof DeviceStatusResponse>;
|
||||
|
||||
export const RevokeResponse = Type.Object(
|
||||
{ schema_version: SchemaVersion, revoked: Type.Literal(true) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type RevokeResponse = Static<typeof RevokeResponse>;
|
||||
|
||||
// ---------------------------------------------------------- conversations
|
||||
export const ConversationCreateRequest = Type.Object(
|
||||
{ schema_version: SchemaVersion },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ConversationCreateRequest = Static<typeof ConversationCreateRequest>;
|
||||
|
||||
export const ConversationResponse = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** Hermeven conversation id. The Hermes session behind it is never exposed to clients. */
|
||||
conversation_id: Uuid,
|
||||
created_at: IsoTime,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ConversationResponse = Static<typeof ConversationResponse>;
|
||||
|
||||
// ------------------------------------------------------------------ turns
|
||||
/** JSON body of POST /v1/turns for typed text (development and accessibility input). */
|
||||
export const TextTurnRequest = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
request_id: Uuid,
|
||||
conversation_id: Uuid,
|
||||
locale: Locale,
|
||||
input: Type.Object(
|
||||
{ kind: Type.Literal('text'), text: Type.String({ minLength: 1, maxLength: DEFAULT_LIMITS.textMaxChars }) },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type TextTurnRequest = Static<typeof TextTurnRequest>;
|
||||
|
||||
/**
|
||||
* Query string of POST /v1/turns when the body is raw audio
|
||||
* (`Content-Type: application/octet-stream`). Audio is never JSON-encoded.
|
||||
*/
|
||||
export const AudioTurnQuery = Type.Object(
|
||||
{
|
||||
schema_version: Type.Literal(String(SCHEMA_VERSION)),
|
||||
request_id: Uuid,
|
||||
conversation_id: Uuid,
|
||||
locale: Locale,
|
||||
input_kind: Type.Literal('audio'),
|
||||
encoding: Type.Literal(AUDIO_FORMAT.encoding),
|
||||
sample_rate: Type.Literal(String(AUDIO_FORMAT.sampleRate)),
|
||||
channels: Type.Literal(String(AUDIO_FORMAT.channels)),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type AudioTurnQuery = Static<typeof AudioTurnQuery>;
|
||||
|
||||
export const TURN_STATES = [
|
||||
'accepted',
|
||||
'transcribing',
|
||||
'thinking',
|
||||
'approval_required',
|
||||
'cancelling',
|
||||
'done',
|
||||
] as const;
|
||||
export type TurnState = (typeof TURN_STATES)[number];
|
||||
|
||||
/**
|
||||
* Terminal outcome. Only meaningful when `terminal` is true.
|
||||
* - succeeded: Hermes reported the turn completed.
|
||||
* - incomplete: Hermes stopped short; `answer_text` is a usable partial answer.
|
||||
* - failed: definite failure (see error.code for whether anything may have run).
|
||||
* - cancelled: Hermes confirmed the stop, or the turn was cancelled before reaching it.
|
||||
* Cancellation is not rollback: tools may already have acted.
|
||||
* - unknown: downstream state could not be reconciled. Never replay automatically.
|
||||
*/
|
||||
export const TURN_OUTCOMES = ['succeeded', 'incomplete', 'failed', 'cancelled', 'unknown'] as const;
|
||||
export type TurnOutcome = (typeof TURN_OUTCOMES)[number];
|
||||
|
||||
export const TurnResult = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
request_id: Uuid,
|
||||
conversation_id: Uuid,
|
||||
state: Type.Union(TURN_STATES.map((s) => Type.Literal(s))),
|
||||
terminal: Type.Boolean(),
|
||||
outcome: Type.Union([...TURN_OUTCOMES.map((s) => Type.Literal(s)), Type.Null()]),
|
||||
/** True once a cancel was requested, whatever the eventual outcome. */
|
||||
cancel_requested: Type.Boolean(),
|
||||
/** What the bridge sent to the agent (typed text or transcript), while retained. */
|
||||
input_text: Type.Union([Type.String(), Type.Null()]),
|
||||
/** Complete agent answer, never truncated by the bridge, while retained. */
|
||||
answer_text: Type.Union([Type.String(), Type.Null()]),
|
||||
error: Type.Union([ErrorBody, Type.Null()]),
|
||||
/** True when this response is for a duplicate submit of an existing request_id. */
|
||||
replayed: Type.Boolean(),
|
||||
created_at: IsoTime,
|
||||
updated_at: IsoTime,
|
||||
timings: Type.Object(
|
||||
{
|
||||
transcribe_ms: Type.Union([Type.Integer(), Type.Null()]),
|
||||
agent_ms: Type.Union([Type.Integer(), Type.Null()]),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type TurnResult = Omit<Static<typeof TurnResult>, 'error' | 'state' | 'outcome'> & {
|
||||
state: TurnState;
|
||||
outcome: TurnOutcome | null;
|
||||
error: ErrorBody | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
export function check<T extends TSchema>(schema: T, value: unknown): value is Static<T> {
|
||||
return Value.Check(schema, value);
|
||||
}
|
||||
|
||||
/** First validation problem as a short path string, for diagnostics only. */
|
||||
export function firstError(schema: TSchema, value: unknown): string | null {
|
||||
const first = Value.Errors(schema, value).First();
|
||||
return first ? `${first.path || '/'}: ${first.message}` : null;
|
||||
}
|
||||
|
||||
export function parse<T extends TSchema>(schema: T, value: unknown, what: string): Static<T> {
|
||||
if (!Value.Check(schema, value)) {
|
||||
throw new ContractError(`${what} does not match contract v${SCHEMA_VERSION}: ${firstError(schema, value)}`);
|
||||
}
|
||||
return value as Static<T>;
|
||||
}
|
||||
|
||||
export class ContractError extends Error {
|
||||
override name = 'ContractError';
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
ContractError,
|
||||
ERROR_CODES,
|
||||
ERROR_CODE_LIST,
|
||||
ErrorResponse,
|
||||
firstError,
|
||||
parse,
|
||||
SCHEMA_VERSION,
|
||||
TextTurnRequest,
|
||||
TurnResult,
|
||||
} from '../src/index.ts';
|
||||
|
||||
const ID = '11111111-1111-4111-8111-111111111111';
|
||||
|
||||
describe('contract v1', () => {
|
||||
const text = {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: ID,
|
||||
conversation_id: ID,
|
||||
locale: 'en-US',
|
||||
input: { kind: 'text', text: 'hello' },
|
||||
};
|
||||
|
||||
it('accepts a well-formed text turn and rejects extra or malformed fields', () => {
|
||||
expect(check(TextTurnRequest, text)).toBe(true);
|
||||
expect(check(TextTurnRequest, { ...text, hermes_session_id: 'x' })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, profile: 'someone-else' })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, request_id: 'not-a-uuid' })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, request_id: 'ABCDEF12-1111-4111-8111-111111111111' })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, schema_version: 2 })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, locale: 'en_US; DROP' })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, input: { kind: 'text', text: '' } })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, input: { kind: 'text', text: 'x'.repeat(4001) } })).toBe(false);
|
||||
expect(check(TextTurnRequest, { ...text, input: { kind: 'audio', text: 'x' } })).toBe(false);
|
||||
});
|
||||
|
||||
it('audio metadata admits exactly one validated format', () => {
|
||||
const q = {
|
||||
schema_version: '1',
|
||||
request_id: ID,
|
||||
conversation_id: ID,
|
||||
locale: 'en-US',
|
||||
input_kind: 'audio',
|
||||
encoding: 'pcm_s16le',
|
||||
sample_rate: '16000',
|
||||
channels: '1',
|
||||
};
|
||||
expect(check(AudioTurnQuery, q)).toBe(true);
|
||||
for (const bad of [{ sample_rate: '8000' }, { channels: '2' }, { encoding: 'opus' }, { input_kind: 'text' }, { extra: '1' }]) {
|
||||
expect(check(AudioTurnQuery, { ...q, ...bad })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('a turn result keeps state, terminal flag and outcome distinct', () => {
|
||||
const result = {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: ID,
|
||||
conversation_id: ID,
|
||||
state: 'done',
|
||||
terminal: true,
|
||||
outcome: 'unknown',
|
||||
cancel_requested: false,
|
||||
input_text: null,
|
||||
answer_text: null,
|
||||
error: { code: 'outcome_unknown', message: 'Unknown.', retryable: false },
|
||||
replayed: false,
|
||||
created_at: '2026-01-01T00:00:00.000Z',
|
||||
updated_at: '2026-01-01T00:00:00.000Z',
|
||||
timings: { transcribe_ms: null, agent_ms: 12 },
|
||||
};
|
||||
expect(check(TurnResult, result)).toBe(true);
|
||||
expect(check(TurnResult, { ...result, outcome: 'approval_required' })).toBe(false);
|
||||
expect(check(TurnResult, { ...result, state: 'ANSWER' })).toBe(false);
|
||||
expect(check(TurnResult, { ...result, error: { code: 'made_up', message: '', retryable: false } })).toBe(false);
|
||||
expect(firstError(TurnResult, { ...result, state: 'ANSWER' })).toContain('/state');
|
||||
expect(() => parse(TurnResult, {}, 'turn')).toThrow(ContractError);
|
||||
});
|
||||
|
||||
it('error codes are stable, and nothing ambiguous is ever marked retryable', () => {
|
||||
expect(ERROR_CODE_LIST).toContain('outcome_unknown');
|
||||
for (const code of ['outcome_unknown', 'agent_failed', 'agent_interrupted', 'agent_timeout', 'approval_timeout', 'request_id_conflict'] as const) {
|
||||
expect(ERROR_CODES[code].retryable, code).toBe(false);
|
||||
}
|
||||
for (const code of ['stt_empty', 'stt_timeout', 'interrupted_before_agent', 'agent_unreachable'] as const) {
|
||||
expect(ERROR_CODES[code].retryable, code).toBe(true);
|
||||
}
|
||||
expect(check(ErrorResponse, { schema_version: 1, error: { code: 'rate_limited', message: 'x', retryable: true } })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@hermeven/bridge",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "tsx src/main.ts",
|
||||
"cli": "tsx src/cli.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.4.3",
|
||||
"@hermeven/contracts": "*",
|
||||
"@sinclair/typebox": "^0.34.52",
|
||||
"better-sqlite3": "^13.2.0",
|
||||
"fastify": "^5.12.8",
|
||||
"pino": "^10.4.0",
|
||||
"tsx": "^4.23.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^9.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { pino, type Logger } from 'pino';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { openDb, type Db } from './db.ts';
|
||||
import { Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { HermesRunsAdapter } from './hermes/runsAdapter.ts';
|
||||
import { buildServer } from './server.ts';
|
||||
import { NoSttAdapter, type SttAdapter } from './stt/adapter.ts';
|
||||
import { OpenAiCompatibleStt } from './stt/openaiCompatible.ts';
|
||||
import { TurnEngine, type EngineLog, type EngineTiming } from './turns.ts';
|
||||
|
||||
export interface Bridge {
|
||||
app: FastifyInstance;
|
||||
db: Db;
|
||||
devices: Devices;
|
||||
engine: TurnEngine;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Pino redaction: belt and braces, since we never pass these fields to the logger anyway. */
|
||||
export const LOG_REDACT = [
|
||||
'req.headers.authorization',
|
||||
'headers.authorization',
|
||||
'token',
|
||||
'code',
|
||||
'text',
|
||||
'input_text',
|
||||
'answer_text',
|
||||
'pending_body',
|
||||
'body',
|
||||
];
|
||||
|
||||
export function sttFromConfig(config: BridgeConfig): SttAdapter {
|
||||
if (config.stt.provider === 'openai-compatible') {
|
||||
return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model });
|
||||
}
|
||||
return new NoSttAdapter();
|
||||
}
|
||||
|
||||
export async function createBridge(
|
||||
config: BridgeConfig,
|
||||
overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean } = {},
|
||||
): Promise<Bridge> {
|
||||
const db = openDb(config.dbPath);
|
||||
const hermes =
|
||||
overrides.hermes ??
|
||||
new HermesRunsAdapter({
|
||||
baseUrl: config.hermes.baseUrl,
|
||||
apiKey: config.hermes.apiKey,
|
||||
requestTimeoutMs: config.hermes.requestTimeoutMs,
|
||||
});
|
||||
const stt = overrides.stt ?? sttFromConfig(config);
|
||||
const devices = new Devices(db, config);
|
||||
|
||||
const given = overrides.logger;
|
||||
const logger: Logger =
|
||||
given && typeof given === 'object'
|
||||
? typeof (given as Logger).child === 'function'
|
||||
? (given as Logger)
|
||||
: pino(given as object)
|
||||
: pino({ level: 'silent' });
|
||||
const engine = new TurnEngine({ db, config, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const app = await buildServer({ config, devices, hermes, stt, engine, logger });
|
||||
|
||||
engine.recover();
|
||||
engine.purgeExpired();
|
||||
const purge = setInterval(() => engine.purgeExpired(), 60_000);
|
||||
purge.unref();
|
||||
|
||||
return {
|
||||
app,
|
||||
db,
|
||||
devices,
|
||||
engine,
|
||||
async close() {
|
||||
clearInterval(purge);
|
||||
await app.close();
|
||||
await engine.shutdown();
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { openDb } from './db.ts';
|
||||
import { Devices } from './devices.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
|
||||
/**
|
||||
* Operator CLI. It talks to the SQLite file directly, so there is no admin
|
||||
* surface on the network: whoever can run this on the bridge host is the owner.
|
||||
*/
|
||||
function usage(): never {
|
||||
console.error(
|
||||
[
|
||||
'Usage: npm run bridge:cli -- <command>',
|
||||
'',
|
||||
' pair Print a single-use pairing code for one new device',
|
||||
' devices List paired devices',
|
||||
' revoke <device-id> Revoke a device credential immediately',
|
||||
].join('\n'),
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
loadEnvFile();
|
||||
const config = loadConfig();
|
||||
const db = openDb(config.dbPath);
|
||||
const devices = new Devices(db, config);
|
||||
const [command, arg] = process.argv.slice(2);
|
||||
|
||||
switch (command) {
|
||||
case 'pair': {
|
||||
const { code, expiresAt } = devices.createPairingCode();
|
||||
const minutes = Math.round((expiresAt - Date.now()) / 60_000);
|
||||
console.log(`Pairing code: ${code}`);
|
||||
console.log(`Valid for ${minutes} minute(s), one device, one use. Any earlier unused code is now void.`);
|
||||
break;
|
||||
}
|
||||
case 'devices': {
|
||||
const rows = devices.list();
|
||||
if (!rows.length) console.log('No devices paired.');
|
||||
for (const d of rows) {
|
||||
const status = d.revoked_at
|
||||
? 'revoked'
|
||||
: d.pairing_expires_at <= Date.now()
|
||||
? 'pairing expired'
|
||||
: d.token_expires_at <= Date.now()
|
||||
? 'token expired'
|
||||
: 'active';
|
||||
const seen = d.last_seen_at ? new Date(d.last_seen_at).toISOString() : 'never';
|
||||
console.log(`${d.id} ${status.padEnd(15)} last seen ${seen} ${d.name}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'revoke': {
|
||||
if (!arg) usage();
|
||||
console.log(devices.revoke(arg) ? `Revoked ${arg}.` : `No active device ${arg}.`);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
usage();
|
||||
}
|
||||
db.close();
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (err) {
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||
|
||||
export interface BridgeConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
dbPath: string;
|
||||
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
||||
allowedOrigins: string[];
|
||||
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
|
||||
allowNonLoopback: boolean;
|
||||
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
|
||||
trustProxy: boolean;
|
||||
hermes: {
|
||||
/** Base URL of the Hermes API server, e.g. http://127.0.0.1:8642 or .../p/<profile>. */
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
/** Label of the configured profile; devices are bound to it. Not sent to Hermes. */
|
||||
profileLabel: string;
|
||||
/** Per-request ephemeral instructions layered on the agent prompt. Empty disables. */
|
||||
instructions: string;
|
||||
pollIntervalMs: number;
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
stt: {
|
||||
provider: 'none' | 'openai-compatible';
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model: string;
|
||||
};
|
||||
limits: {
|
||||
captureMaxSeconds: number;
|
||||
transcribeDeadlineSeconds: number;
|
||||
agentDeadlineSeconds: number;
|
||||
approvalWaitSeconds: number;
|
||||
cancelGraceSeconds: number;
|
||||
textMaxChars: number;
|
||||
audioMaxBytes: number;
|
||||
turnsPerMinute: number;
|
||||
pairingAttemptsPerMinute: number;
|
||||
};
|
||||
credentials: {
|
||||
tokenTtlSeconds: number;
|
||||
pairingTtlSeconds: number;
|
||||
pairingCodeTtlSeconds: number;
|
||||
pairingCodeMaxFailures: number;
|
||||
};
|
||||
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
|
||||
resultRetentionSeconds: number;
|
||||
logLevel: string;
|
||||
}
|
||||
|
||||
const DEFAULT_INSTRUCTIONS =
|
||||
'The user reads this reply on a small monochrome heads-up display. ' +
|
||||
'Answer in plain text without Markdown, tables, code fences or links. ' +
|
||||
'Lead with the direct answer in one or two short sentences, then add detail only if it is needed.';
|
||||
|
||||
export class ConfigError extends Error {
|
||||
override name = 'ConfigError';
|
||||
}
|
||||
|
||||
function int(env: NodeJS.ProcessEnv, key: string, fallback: number, min = 1, max = Number.MAX_SAFE_INTEGER): number {
|
||||
const raw = env[key];
|
||||
if (raw === undefined || raw === '') return fallback;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < min || n > max) {
|
||||
throw new ConfigError(`${key} must be an integer between ${min} and ${max}`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function bool(env: NodeJS.ProcessEnv, key: string, fallback = false): boolean {
|
||||
const raw = env[key];
|
||||
if (raw === undefined || raw === '') return fallback;
|
||||
if (['1', 'true', 'yes'].includes(raw.toLowerCase())) return true;
|
||||
if (['0', 'false', 'no'].includes(raw.toLowerCase())) return false;
|
||||
throw new ConfigError(`${key} must be true or false`);
|
||||
}
|
||||
|
||||
export function isLoopback(host: string): boolean {
|
||||
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
||||
}
|
||||
|
||||
function httpUrl(key: string, raw: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
throw new ConfigError(`${key} is not a valid URL`);
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ConfigError(`${key} must be http(s)`);
|
||||
if (url.protocol === 'http:' && !isLoopback(url.hostname)) {
|
||||
throw new ConfigError(`${key} must use https outside loopback`);
|
||||
}
|
||||
return raw.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
const host = env.HERMEVEN_HOST || '127.0.0.1';
|
||||
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
|
||||
if (!isLoopback(host) && !allowNonLoopback) {
|
||||
throw new ConfigError(
|
||||
'HERMEVEN_HOST is not loopback. Put a TLS-terminating proxy or private network in front and set ' +
|
||||
'HERMEVEN_ALLOW_NON_LOOPBACK=true to confirm.',
|
||||
);
|
||||
}
|
||||
|
||||
const hermesKey = env.HERMES_API_KEY || '';
|
||||
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
|
||||
|
||||
const allowedOrigins = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const origin of allowedOrigins) {
|
||||
if (origin === '*' ) throw new ConfigError('HERMEVEN_ALLOWED_ORIGINS must list exact origins, not *');
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(origin);
|
||||
} catch {
|
||||
throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry is not an origin: ${origin}`);
|
||||
}
|
||||
if (parsed.origin !== origin) throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry must be scheme://host[:port]: ${origin}`);
|
||||
}
|
||||
|
||||
const sttProvider = (env.STT_PROVIDER || 'none') as BridgeConfig['stt']['provider'];
|
||||
if (sttProvider !== 'none' && sttProvider !== 'openai-compatible') {
|
||||
throw new ConfigError('STT_PROVIDER must be "none" or "openai-compatible"');
|
||||
}
|
||||
let sttBaseUrl = '';
|
||||
if (sttProvider === 'openai-compatible') {
|
||||
if (!env.STT_BASE_URL) throw new ConfigError('STT_BASE_URL is required for STT_PROVIDER=openai-compatible');
|
||||
if (!env.STT_MODEL) throw new ConfigError('STT_MODEL is required for STT_PROVIDER=openai-compatible');
|
||||
sttBaseUrl = httpUrl('STT_BASE_URL', env.STT_BASE_URL);
|
||||
}
|
||||
|
||||
const captureMaxSeconds = int(env, 'HERMEVEN_CAPTURE_MAX_SECONDS', DEFAULT_LIMITS.captureMaxSeconds, 1, 120);
|
||||
|
||||
return {
|
||||
host,
|
||||
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
|
||||
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
||||
allowedOrigins,
|
||||
allowNonLoopback,
|
||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||
hermes: {
|
||||
baseUrl: httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642'),
|
||||
apiKey: hermesKey,
|
||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 500, 20, 10_000),
|
||||
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||
},
|
||||
stt: {
|
||||
provider: sttProvider,
|
||||
baseUrl: sttBaseUrl,
|
||||
apiKey: env.STT_API_KEY || '',
|
||||
model: env.STT_MODEL || '',
|
||||
},
|
||||
limits: {
|
||||
captureMaxSeconds,
|
||||
transcribeDeadlineSeconds: int(env, 'HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS', DEFAULT_LIMITS.transcribeDeadlineSeconds, 1, 300),
|
||||
agentDeadlineSeconds: int(env, 'HERMEVEN_AGENT_DEADLINE_SECONDS', DEFAULT_LIMITS.agentDeadlineSeconds, 1, 3600),
|
||||
approvalWaitSeconds: int(env, 'HERMEVEN_APPROVAL_WAIT_SECONDS', DEFAULT_LIMITS.approvalWaitSeconds, 1, 3600),
|
||||
cancelGraceSeconds: int(env, 'HERMEVEN_CANCEL_GRACE_SECONDS', 30, 1, 600),
|
||||
textMaxChars: DEFAULT_LIMITS.textMaxChars,
|
||||
// One extra second of headroom over the capture cap for frame alignment.
|
||||
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
|
||||
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
|
||||
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
|
||||
},
|
||||
credentials: {
|
||||
tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60),
|
||||
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 86_400, 60),
|
||||
pairingCodeTtlSeconds: int(env, 'HERMEVEN_PAIRING_CODE_TTL_SECONDS', 300, 30, 3600),
|
||||
pairingCodeMaxFailures: int(env, 'HERMEVEN_PAIRING_CODE_MAX_FAILURES', 5, 1, 20),
|
||||
},
|
||||
resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
|
||||
logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
export type Db = Database.Database;
|
||||
|
||||
const MIGRATIONS: string[] = [
|
||||
`
|
||||
CREATE TABLE devices (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
token_expires_at INTEGER NOT NULL,
|
||||
pairing_expires_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER,
|
||||
last_seen_at INTEGER
|
||||
);
|
||||
CREATE TABLE pairing_codes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
used_at INTEGER,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE conversations (
|
||||
id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL REFERENCES devices(id),
|
||||
-- Opaque reference into Hermes. Generated by the bridge, never accepted from a client.
|
||||
hermes_session_id TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
closed_at INTEGER
|
||||
);
|
||||
CREATE INDEX conversations_device ON conversations(device_id, closed_at);
|
||||
CREATE TABLE turns (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL REFERENCES devices(id),
|
||||
conversation_id TEXT NOT NULL REFERENCES conversations(id),
|
||||
input_kind TEXT NOT NULL,
|
||||
-- SHA-256 of metadata + input bytes: detects a reused request_id with a different payload.
|
||||
input_fingerprint TEXT NOT NULL,
|
||||
locale TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
outcome TEXT,
|
||||
error_code TEXT,
|
||||
error_message TEXT,
|
||||
cancel_requested INTEGER NOT NULL DEFAULT 0,
|
||||
hermes_idempotency_key TEXT NOT NULL,
|
||||
hermes_run_id TEXT,
|
||||
-- Exact Hermes request body, held only between "about to submit" and "run id persisted"
|
||||
-- so a crash in that window can replay the same idempotent request. Cleared afterwards.
|
||||
pending_body TEXT,
|
||||
-- Result cache, cleared after the retention window. Hermes stays the transcript authority.
|
||||
input_text TEXT,
|
||||
answer_text TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
agent_started_at INTEGER,
|
||||
approval_started_at INTEGER,
|
||||
completed_at INTEGER,
|
||||
transcribe_ms INTEGER,
|
||||
agent_ms INTEGER
|
||||
);
|
||||
CREATE INDEX turns_conversation ON turns(conversation_id, state);
|
||||
CREATE INDEX turns_state ON turns(state);
|
||||
`,
|
||||
];
|
||||
|
||||
export function openDb(path: string): Db {
|
||||
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true });
|
||||
const db = new Database(path);
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
function migrate(db: Db): void {
|
||||
const current = db.pragma('user_version', { simple: true }) as number;
|
||||
for (let v = current; v < MIGRATIONS.length; v++) {
|
||||
const sql = MIGRATIONS[v]!;
|
||||
db.transaction(() => {
|
||||
db.exec(sql);
|
||||
db.pragma(`user_version = ${v + 1}`);
|
||||
})();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
|
||||
export interface DeviceRow {
|
||||
id: string;
|
||||
name: string;
|
||||
profile: string;
|
||||
token_hash: string;
|
||||
created_at: number;
|
||||
token_expires_at: number;
|
||||
pairing_expires_at: number;
|
||||
revoked_at: number | null;
|
||||
last_seen_at: number | null;
|
||||
}
|
||||
|
||||
export type AuthFailure = 'unauthorized' | 'credential_expired';
|
||||
export type PairingFailure = 'pairing_invalid' | 'pairing_locked';
|
||||
|
||||
// No 0/O, 1/I/L: read aloud or typed on a phone without ambiguity. 31 symbols.
|
||||
const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
|
||||
const CODE_LENGTH = 10; // ~49.5 bits; with 5 total failures before lockout, guessing is not viable.
|
||||
|
||||
export function sha256(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function normalizeCode(code: string): string {
|
||||
return code.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
}
|
||||
|
||||
function newToken(): string {
|
||||
return `hvn_${randomBytes(32).toString('base64url')}`;
|
||||
}
|
||||
|
||||
export class Devices {
|
||||
constructor(
|
||||
private readonly db: Db,
|
||||
private readonly config: BridgeConfig,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/** Operator action (CLI): mint a single-use, time-limited pairing code. Invalidates older unused codes. */
|
||||
createPairingCode(): { code: string; expiresAt: number } {
|
||||
const code = Array.from({ length: CODE_LENGTH }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join('');
|
||||
const now = this.now();
|
||||
const expiresAt = now + this.config.credentials.pairingCodeTtlSeconds * 1000;
|
||||
this.db.transaction(() => {
|
||||
this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE used_at IS NULL').run(now);
|
||||
this.db
|
||||
.prepare('INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES (?, ?, ?)')
|
||||
.run(sha256(code), now, expiresAt);
|
||||
})();
|
||||
return { code: `${code.slice(0, 5)}-${code.slice(5)}`, expiresAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange a pairing code for a device credential. A wrong guess counts against every
|
||||
* outstanding code, so the code is burned after a few failures regardless of who guessed.
|
||||
*/
|
||||
claimPairingCode(
|
||||
rawCode: string,
|
||||
deviceName: string,
|
||||
): { ok: true; device: DeviceRow; token: string } | { ok: false; reason: PairingFailure } {
|
||||
const now = this.now();
|
||||
const hash = sha256(normalizeCode(rawCode));
|
||||
return this.db.transaction(() => {
|
||||
const live = this.db
|
||||
.prepare('SELECT id, code_hash, failed_attempts FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?')
|
||||
.all(now) as Array<{ id: number; code_hash: string; failed_attempts: number }>;
|
||||
const match = live.find((row) => safeEqualHex(row.code_hash, hash));
|
||||
if (!match) {
|
||||
let locked = false;
|
||||
for (const row of live) {
|
||||
const failures = row.failed_attempts + 1;
|
||||
if (failures >= this.config.credentials.pairingCodeMaxFailures) {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ?, used_at = ? WHERE id = ?').run(failures, now, row.id);
|
||||
locked = true;
|
||||
} else {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ? WHERE id = ?').run(failures, row.id);
|
||||
}
|
||||
}
|
||||
return { ok: false as const, reason: locked ? ('pairing_locked' as const) : ('pairing_invalid' as const) };
|
||||
}
|
||||
this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE id = ?').run(now, match.id);
|
||||
const token = newToken();
|
||||
const device: DeviceRow = {
|
||||
id: randomUUID(),
|
||||
name: deviceName,
|
||||
profile: this.config.hermes.profileLabel,
|
||||
token_hash: sha256(token),
|
||||
created_at: now,
|
||||
token_expires_at: now + this.config.credentials.tokenTtlSeconds * 1000,
|
||||
pairing_expires_at: now + this.config.credentials.pairingTtlSeconds * 1000,
|
||||
revoked_at: null,
|
||||
last_seen_at: now,
|
||||
};
|
||||
device.token_expires_at = Math.min(device.token_expires_at, device.pairing_expires_at);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO devices (id, name, profile, token_hash, created_at, token_expires_at, pairing_expires_at, last_seen_at)
|
||||
VALUES (@id, @name, @profile, @token_hash, @created_at, @token_expires_at, @pairing_expires_at, @last_seen_at)`,
|
||||
)
|
||||
.run(device);
|
||||
return { ok: true as const, device, token };
|
||||
})();
|
||||
}
|
||||
|
||||
authenticate(token: string): { ok: true; device: DeviceRow } | { ok: false; reason: AuthFailure } {
|
||||
if (!token || token.length > 200) return { ok: false, reason: 'unauthorized' };
|
||||
const row = this.db.prepare('SELECT * FROM devices WHERE token_hash = ?').get(sha256(token)) as DeviceRow | undefined;
|
||||
if (!row || row.revoked_at !== null) return { ok: false, reason: 'unauthorized' };
|
||||
const now = this.now();
|
||||
if (row.token_expires_at <= now || row.pairing_expires_at <= now) return { ok: false, reason: 'credential_expired' };
|
||||
// A device is only valid for the profile this bridge is configured to serve.
|
||||
if (row.profile !== this.config.hermes.profileLabel) return { ok: false, reason: 'unauthorized' };
|
||||
this.db.prepare('UPDATE devices SET last_seen_at = ? WHERE id = ?').run(now, row.id);
|
||||
return { ok: true, device: row };
|
||||
}
|
||||
|
||||
/** Explicit renewal: rotates the token (the old one stops working immediately). */
|
||||
renew(deviceId: string): { device: DeviceRow; token: string } {
|
||||
const now = this.now();
|
||||
const token = newToken();
|
||||
const current = this.get(deviceId)!;
|
||||
const tokenExpiresAt = Math.min(now + this.config.credentials.tokenTtlSeconds * 1000, current.pairing_expires_at);
|
||||
this.db
|
||||
.prepare('UPDATE devices SET token_hash = ?, token_expires_at = ? WHERE id = ?')
|
||||
.run(sha256(token), tokenExpiresAt, deviceId);
|
||||
return { device: this.get(deviceId)!, token };
|
||||
}
|
||||
|
||||
revoke(deviceId: string): boolean {
|
||||
const now = this.now();
|
||||
return this.db.transaction(() => {
|
||||
const res = this.db.prepare('UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').run(now, deviceId);
|
||||
this.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
return res.changes > 0;
|
||||
})();
|
||||
}
|
||||
|
||||
get(deviceId: string): DeviceRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM devices WHERE id = ?').get(deviceId) as DeviceRow | undefined;
|
||||
}
|
||||
|
||||
list(): DeviceRow[] {
|
||||
return this.db.prepare('SELECT * FROM devices ORDER BY created_at').all() as DeviceRow[];
|
||||
}
|
||||
}
|
||||
|
||||
function safeEqualHex(a: string, b: string): boolean {
|
||||
const ab = Buffer.from(a, 'hex');
|
||||
const bb = Buffer.from(b, 'hex');
|
||||
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
/**
|
||||
* Load server secrets from an ignored `.env` (never committed, see .env.example).
|
||||
* Variables already present in the environment win.
|
||||
*/
|
||||
export function loadEnvFile(): void {
|
||||
const explicit = process.env.HERMEVEN_ENV_FILE;
|
||||
const candidates = explicit ? [explicit] : [resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')];
|
||||
for (const path of candidates) {
|
||||
if (existsSync(path)) {
|
||||
process.loadEnvFile(path);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* The one seam between Hermeven and Hermes. Everything the bridge knows about
|
||||
* Hermes goes through this interface so the real HTTP adapter and the test
|
||||
* fake are interchangeable.
|
||||
*/
|
||||
|
||||
export type RunState =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'waiting_for_approval'
|
||||
| 'stopping'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
| 'interrupted'
|
||||
/** Hermes itself does not know whether the turn executed (owner restart). */
|
||||
| 'unknown'
|
||||
/** Hermes has no record of the run under our credential. */
|
||||
| 'not_found';
|
||||
|
||||
export interface RunStatus {
|
||||
state: RunState;
|
||||
/** Final answer text; may also accompany a `failed` state when the turn stopped short. */
|
||||
output: string;
|
||||
/** False when Hermes says the turn did not finish (budget exhausted, partial). */
|
||||
finished: boolean;
|
||||
/** Redacted diagnostic from Hermes. Never shown on the HUD, never logged by default. */
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SubmitRequest {
|
||||
/** Forwarded as `Idempotency-Key`; an exact retry returns the original run. */
|
||||
idempotencyKey: string;
|
||||
/** Exact JSON body. Must be byte-identical on a retry or Hermes reports a conflict. */
|
||||
body: string;
|
||||
}
|
||||
|
||||
export type SubmitFailureKind =
|
||||
/** The request provably never reached Hermes (connection refused, DNS). Nothing ran. */
|
||||
| 'not_sent'
|
||||
/** Hermes answered and refused admission before running anything (4xx, 429, 503). */
|
||||
| 'rejected'
|
||||
| 'busy'
|
||||
/** Sent, but no usable answer came back. The turn may or may not have been admitted. */
|
||||
| 'ambiguous'
|
||||
/** The key is already bound to a different request. Never resend under a new key. */
|
||||
| 'conflict';
|
||||
|
||||
export class HermesSubmitError extends Error {
|
||||
override name = 'HermesSubmitError';
|
||||
constructor(
|
||||
readonly kind: SubmitFailureKind,
|
||||
message: string,
|
||||
readonly httpStatus?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Status could not be read at all (network). Distinct from a `not_found` answer. */
|
||||
export class HermesUnavailableError extends Error {
|
||||
override name = 'HermesUnavailableError';
|
||||
}
|
||||
|
||||
export interface HermesAdapter {
|
||||
submit(request: SubmitRequest): Promise<{ runId: string }>;
|
||||
status(runId: string): Promise<RunStatus>;
|
||||
/** Ask Hermes to interrupt. Resolves once the request was accepted, not once it stopped. */
|
||||
stop(runId: string): Promise<void>;
|
||||
/** Cheap liveness probe; true only when Hermes answered healthy. */
|
||||
reachable(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** Build the exact body for POST /v1/runs. Key order is fixed so retries are byte-identical. */
|
||||
export function buildRunBody(args: { input: string; sessionId: string; instructions: string }): string {
|
||||
const body: Record<string, string> = { input: args.input, session_id: args.sessionId };
|
||||
if (args.instructions) body.instructions = args.instructions;
|
||||
return JSON.stringify(body);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
HermesSubmitError,
|
||||
HermesUnavailableError,
|
||||
type HermesAdapter,
|
||||
type RunState,
|
||||
type RunStatus,
|
||||
type SubmitRequest,
|
||||
} from './adapter.ts';
|
||||
|
||||
/**
|
||||
* Hermes API server adapter using the Runs API (verified against hermes-agent
|
||||
* v0.23.1 source, see docs/compatibility.md):
|
||||
*
|
||||
* POST /v1/runs Idempotency-Key header, body {input, session_id, instructions}
|
||||
* -> 202 {run_id, status}; an exact retry replays the same run_id.
|
||||
* GET /v1/runs/{id} pollable status
|
||||
* POST /v1/runs/{id}/stop interrupt
|
||||
*
|
||||
* The Runs API is used instead of POST /v1/responses because Responses has no
|
||||
* cancel endpoint and no pollable in-flight status; see docs/decisions/0002.
|
||||
*/
|
||||
export class HermesRunsAdapter implements HermesAdapter {
|
||||
constructor(
|
||||
private readonly opts: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
requestTimeoutMs: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
},
|
||||
) {}
|
||||
|
||||
private get fetch(): typeof fetch {
|
||||
return this.opts.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
private headers(extra: Record<string, string> = {}): Record<string, string> {
|
||||
return { Authorization: `Bearer ${this.opts.apiKey}`, Accept: 'application/json', ...extra };
|
||||
}
|
||||
|
||||
async submit(request: SubmitRequest): Promise<{ runId: string }> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: this.headers({ 'Content-Type': 'application/json', 'Idempotency-Key': request.idempotencyKey }),
|
||||
body: request.body,
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesSubmitError(neverConnected(err) ? 'not_sent' : 'ambiguous', describe(err));
|
||||
}
|
||||
if (res.status === 202 || res.status === 200) {
|
||||
const json = (await safeJson(res)) as { run_id?: unknown } | null;
|
||||
if (json && typeof json.run_id === 'string' && json.run_id) return { runId: json.run_id };
|
||||
// Admitted but unreadable: the retry under the same key recovers the run id.
|
||||
throw new HermesSubmitError('ambiguous', 'Hermes accepted the run but returned no run_id', res.status);
|
||||
}
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
if (res.status === 409) throw new HermesSubmitError('conflict', 'Hermes refused the idempotency key', 409);
|
||||
if (res.status === 429 || res.status === 503) throw new HermesSubmitError('busy', `Hermes is busy (${res.status})`, res.status);
|
||||
if (res.status >= 400 && res.status < 500) {
|
||||
throw new HermesSubmitError('rejected', `Hermes rejected the request (${res.status})`, res.status);
|
||||
}
|
||||
// 5xx: the server may have admitted the run before failing to answer.
|
||||
throw new HermesSubmitError('ambiguous', `Hermes answered ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
async status(runId: string): Promise<RunStatus> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs/${encodeURIComponent(runId)}`, {
|
||||
headers: this.headers(),
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesUnavailableError(describe(err));
|
||||
}
|
||||
if (res.status === 404) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
return { state: 'not_found', output: '', finished: false, error: null };
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
throw new HermesUnavailableError(`Hermes status answered ${res.status}`);
|
||||
}
|
||||
const json = (await safeJson(res)) as Record<string, unknown> | null;
|
||||
if (!json || typeof json.status !== 'string') throw new HermesUnavailableError('Hermes status was not readable');
|
||||
return mapRunStatus(json);
|
||||
}
|
||||
|
||||
async stop(runId: string): Promise<void> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetch(`${this.opts.baseUrl}/v1/runs/${encodeURIComponent(runId)}/stop`, {
|
||||
method: 'POST',
|
||||
headers: this.headers({ 'Content-Type': 'application/json' }),
|
||||
body: '{}',
|
||||
signal: AbortSignal.timeout(this.opts.requestTimeoutMs),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new HermesUnavailableError(describe(err));
|
||||
}
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
// 409 covers "not active" and "unknown execution": the status poll decides the outcome.
|
||||
if (!res.ok && res.status !== 409 && res.status !== 404) {
|
||||
throw new HermesUnavailableError(`Hermes stop answered ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async reachable(): Promise<boolean> {
|
||||
try {
|
||||
const res = await this.fetch(`${this.opts.baseUrl}/health`, {
|
||||
signal: AbortSignal.timeout(Math.min(this.opts.requestTimeoutMs, 3000)),
|
||||
});
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const KNOWN_STATES: ReadonlySet<string> = new Set<RunState>([
|
||||
'queued',
|
||||
'running',
|
||||
'waiting_for_approval',
|
||||
'stopping',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
'interrupted',
|
||||
'unknown',
|
||||
]);
|
||||
|
||||
export function mapRunStatus(json: Record<string, unknown>): RunStatus {
|
||||
const raw = String(json.status);
|
||||
// An unrecognised status is treated as still in flight; the deadline bounds the wait.
|
||||
const state = (KNOWN_STATES.has(raw) ? raw : 'running') as RunState;
|
||||
return {
|
||||
state,
|
||||
output: typeof json.output === 'string' ? json.output : '',
|
||||
finished: json.completed !== false && json.partial !== true,
|
||||
error: typeof json.error === 'string' ? json.error : null,
|
||||
};
|
||||
}
|
||||
|
||||
async function safeJson(res: Response): Promise<unknown> {
|
||||
try {
|
||||
return await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function describe(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
const cause = (err as { cause?: { code?: string } }).cause;
|
||||
return cause?.code ? `${err.name}: ${cause.code}` : err.name;
|
||||
}
|
||||
return 'request failed';
|
||||
}
|
||||
|
||||
/** True only when the socket was never established, so no request bytes reached Hermes. */
|
||||
function neverConnected(err: unknown): boolean {
|
||||
const code = (err as { cause?: { code?: string } })?.cause?.code;
|
||||
return code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EHOSTUNREACH' || code === 'ENETUNREACH';
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { LOG_REDACT, createBridge } from './app.ts';
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { loadEnvFile } from './env.ts';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
loadEnvFile();
|
||||
const config = loadConfig();
|
||||
const bridge = await createBridge(config, {
|
||||
logger: { level: config.logLevel, redact: { paths: LOG_REDACT, censor: '[redacted]' } },
|
||||
});
|
||||
await bridge.app.listen({ host: config.host, port: config.port });
|
||||
|
||||
let closing = false;
|
||||
const stop = (signal: string) => {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
bridge.app.log.info({ signal }, 'bridge.stopping');
|
||||
bridge.close().then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1),
|
||||
);
|
||||
};
|
||||
process.on('SIGINT', () => stop('SIGINT'));
|
||||
process.on('SIGTERM', () => stop('SIGTERM'));
|
||||
}
|
||||
|
||||
main().catch((err: unknown) => {
|
||||
// Configuration problems are operator-facing; never print the environment.
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/** Fixed-window, in-memory limiter. Single-process by design (single-user MVP). */
|
||||
export class RateLimiter {
|
||||
private readonly windows = new Map<string, { start: number; count: number }>();
|
||||
|
||||
constructor(
|
||||
private readonly max: number,
|
||||
private readonly windowMs: number,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
/** Returns false when the caller is over budget. */
|
||||
take(key: string): boolean {
|
||||
const now = this.now();
|
||||
const current = this.windows.get(key);
|
||||
if (!current || now - current.start >= this.windowMs) {
|
||||
if (this.windows.size > 10_000) this.sweep(now);
|
||||
this.windows.set(key, { start: now, count: 1 });
|
||||
return true;
|
||||
}
|
||||
if (current.count >= this.max) return false;
|
||||
current.count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
private sweep(now: number): void {
|
||||
for (const [key, w] of this.windows) if (now - w.start >= this.windowMs) this.windows.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import cors from '@fastify/cors';
|
||||
import Fastify, { LogController, type FastifyBaseLogger, type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
ConversationCreateRequest,
|
||||
httpStatusFor,
|
||||
isRetryable,
|
||||
PairingClaimRequest,
|
||||
SCHEMA_VERSION,
|
||||
TextTurnRequest,
|
||||
type ConversationResponse,
|
||||
type DeviceCredential,
|
||||
type DeviceStatusResponse,
|
||||
type ErrorCode,
|
||||
type ErrorResponse,
|
||||
type Limits,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { DeviceRow, Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { RateLimiter } from './ratelimit.ts';
|
||||
import type { SttAdapter } from './stt/adapter.ts';
|
||||
import type { TurnEngine } from './turns.ts';
|
||||
|
||||
export interface ServerDeps {
|
||||
config: BridgeConfig;
|
||||
devices: Devices;
|
||||
engine: TurnEngine;
|
||||
hermes: HermesAdapter;
|
||||
stt: SttAdapter;
|
||||
/** Request bodies, queries and auth headers are never passed to it. */
|
||||
logger: FastifyBaseLogger;
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(
|
||||
readonly code: ErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function errorBody(code: ErrorCode, message: string): ErrorResponse {
|
||||
return { schema_version: SCHEMA_VERSION, error: { code, message, retryable: isRetryable(code) } };
|
||||
}
|
||||
|
||||
function iso(ms: number): string {
|
||||
return new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
export function effectiveLimits(config: BridgeConfig): Limits {
|
||||
return {
|
||||
capture_max_seconds: config.limits.captureMaxSeconds,
|
||||
transcribe_deadline_seconds: config.limits.transcribeDeadlineSeconds,
|
||||
agent_deadline_seconds: config.limits.agentDeadlineSeconds,
|
||||
approval_wait_seconds: config.limits.approvalWaitSeconds,
|
||||
audio_max_bytes: config.limits.audioMaxBytes,
|
||||
text_max_chars: config.limits.textMaxChars,
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const { config, devices, engine } = deps;
|
||||
const app = Fastify({
|
||||
loggerInstance: deps.logger,
|
||||
trustProxy: config.trustProxy,
|
||||
// JSON bodies are tiny; the audio parser below sets its own, larger limit.
|
||||
bodyLimit: 32 * 1024,
|
||||
// Per-request access logs are off: routes log ids and outcomes themselves, and a URL
|
||||
// can carry request metadata we do not want duplicated into logs.
|
||||
logController: new LogController({ disableRequestLogging: true }),
|
||||
// Fastify's default id is a counter; ours never contains client-supplied text.
|
||||
genReqId: () => crypto.randomUUID(),
|
||||
});
|
||||
|
||||
// Exact-origin CORS. CORS only tells browsers who may read answers; every route
|
||||
// except /healthz and the pairing claim still requires a device credential.
|
||||
await app.register(cors, {
|
||||
origin: config.allowedOrigins.length ? config.allowedOrigins : false,
|
||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||
credentials: false,
|
||||
maxAge: 600,
|
||||
});
|
||||
|
||||
app.addHook('onSend', async (_req, reply) => {
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.header('Cache-Control', 'no-store');
|
||||
reply.header('Referrer-Policy', 'no-referrer');
|
||||
});
|
||||
|
||||
// Raw audio: buffered in memory with a hard cap, never parsed as JSON, never written to disk.
|
||||
app.addContentTypeParser(
|
||||
'application/octet-stream',
|
||||
{ parseAs: 'buffer', bodyLimit: config.limits.audioMaxBytes },
|
||||
(_req, body, done) => done(null, body),
|
||||
);
|
||||
|
||||
app.setErrorHandler((err: Error & { statusCode?: number; code?: string }, req, reply) => {
|
||||
if (err instanceof ApiError) {
|
||||
return reply.code(httpStatusFor(err.code)).send(errorBody(err.code, err.message));
|
||||
}
|
||||
if (err.code === 'FST_ERR_CTP_BODY_TOO_LARGE' || err.statusCode === 413) {
|
||||
return reply.code(413).send(errorBody('payload_too_large', 'Request body is too large.'));
|
||||
}
|
||||
if (err.code === 'FST_ERR_CTP_INVALID_MEDIA_TYPE' || err.statusCode === 415) {
|
||||
return reply.code(415).send(errorBody('unsupported_media', 'Unsupported content type.'));
|
||||
}
|
||||
if (err.statusCode && err.statusCode >= 400 && err.statusCode < 500) {
|
||||
return reply.code(400).send(errorBody('invalid_request', 'Malformed request.'));
|
||||
}
|
||||
req.log.error({ err_name: err.name, err_code: err.code ?? null }, 'request.failed');
|
||||
return reply.code(500).send(errorBody('internal', 'Internal error.'));
|
||||
});
|
||||
app.setNotFoundHandler((_req, reply) => reply.code(404).send(errorBody('not_found', 'Not found.')));
|
||||
|
||||
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
|
||||
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
|
||||
const readLimiter = new RateLimiter(600, 60_000);
|
||||
|
||||
function authenticate(req: FastifyRequest): DeviceRow {
|
||||
const header = req.headers.authorization ?? '';
|
||||
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
|
||||
const result = devices.authenticate(token);
|
||||
if (!result.ok) {
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'credential_expired' ? 'Credential expired. Renew or pair again.' : 'Not authorized.',
|
||||
);
|
||||
}
|
||||
if (!readLimiter.take(result.device.id)) throw new ApiError('rate_limited', 'Too many requests.');
|
||||
return result.device;
|
||||
}
|
||||
|
||||
function requireVersion(value: unknown): void {
|
||||
if (value !== SCHEMA_VERSION && value !== String(SCHEMA_VERSION)) {
|
||||
throw new ApiError('unsupported_schema_version', `This bridge speaks contract version ${SCHEMA_VERSION}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function requireUuid(value: string): string {
|
||||
if (!UUID_RE.test(value)) throw new ApiError('not_found', 'Not found.');
|
||||
return value;
|
||||
}
|
||||
|
||||
function credential(device: DeviceRow, token: string): DeviceCredential {
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
device_id: device.id,
|
||||
token,
|
||||
token_expires_at: iso(device.token_expires_at),
|
||||
pairing_expires_at: iso(device.pairing_expires_at),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ health
|
||||
// Liveness only: no configuration, versions, counts or downstream state.
|
||||
app.get('/healthz', async () => ({ status: 'ok', schema_version: SCHEMA_VERSION }));
|
||||
|
||||
// ----------------------------------------------------------------- pairing
|
||||
app.post('/v1/pairing/claim', async (req, reply) => {
|
||||
if (!pairingLimiter.take(req.ip)) throw new ApiError('rate_limited', 'Too many pairing attempts. Wait a minute.');
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(PairingClaimRequest, body)) throw new ApiError('invalid_request', 'Malformed pairing request.');
|
||||
const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device');
|
||||
if (!result.ok) {
|
||||
req.log.warn({ reason: result.reason }, 'pairing.rejected');
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'pairing_locked'
|
||||
? 'Too many wrong codes. Generate a new pairing code on the bridge.'
|
||||
: 'Pairing code is not valid.',
|
||||
);
|
||||
}
|
||||
req.log.info({ device_id: result.device.id }, 'pairing.claimed');
|
||||
return reply.code(201).send(credential(result.device, result.token));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ device
|
||||
app.get('/v1/device', async (req): Promise<DeviceStatusResponse> => {
|
||||
const device = authenticate(req);
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
device_id: device.id,
|
||||
device_name: device.name,
|
||||
token_expires_at: iso(device.token_expires_at),
|
||||
pairing_expires_at: iso(device.pairing_expires_at),
|
||||
agent_reachable: await deps.hermes.reachable(),
|
||||
stt_configured: deps.stt.configured,
|
||||
active_conversation_id: engine.activeConversation(device.id)?.id ?? null,
|
||||
limits: effectiveLimits(config),
|
||||
audio_format: {
|
||||
encoding: AUDIO_FORMAT.encoding,
|
||||
sample_rate: AUDIO_FORMAT.sampleRate,
|
||||
channels: AUDIO_FORMAT.channels,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/v1/device/renew', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const renewed = devices.renew(device.id);
|
||||
req.log.info({ device_id: device.id }, 'device.renewed');
|
||||
return credential(renewed.device, renewed.token);
|
||||
});
|
||||
|
||||
app.delete('/v1/device', async (req) => {
|
||||
const device = authenticate(req);
|
||||
devices.revoke(device.id);
|
||||
req.log.info({ device_id: device.id }, 'device.revoked');
|
||||
return { schema_version: SCHEMA_VERSION, revoked: true };
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------- conversations
|
||||
app.post('/v1/conversations', async (req, reply): Promise<ConversationResponse> => {
|
||||
const device = authenticate(req);
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(ConversationCreateRequest, body)) throw new ApiError('invalid_request', 'Malformed conversation request.');
|
||||
const conversation = engine.createConversation(device.id);
|
||||
reply.code(201);
|
||||
return { schema_version: SCHEMA_VERSION, conversation_id: conversation.id, created_at: iso(conversation.created_at) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------- turns
|
||||
app.post('/v1/turns', async (req: FastifyRequest, reply: FastifyReply) => {
|
||||
const device = authenticate(req);
|
||||
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
|
||||
|
||||
let meta: { requestId: string; conversationId: string; locale: string };
|
||||
let input: { kind: 'text'; text: string } | { kind: 'audio'; pcm: Buffer };
|
||||
|
||||
if (contentType === 'application/json') {
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(TextTurnRequest, body)) throw new ApiError('invalid_request', 'Malformed turn request.');
|
||||
const text = body.input.text.trim();
|
||||
if (!text) throw new ApiError('invalid_request', 'Text is empty.');
|
||||
meta = { requestId: body.request_id, conversationId: body.conversation_id, locale: body.locale };
|
||||
input = { kind: 'text', text };
|
||||
} else if (contentType === 'application/octet-stream') {
|
||||
const query = req.query as Record<string, unknown>;
|
||||
requireVersion(query.schema_version);
|
||||
if (!check(AudioTurnQuery, query)) {
|
||||
// A declared format we have not validated against real SDK output is refused, not guessed.
|
||||
const formatDeclared = 'encoding' in query || 'sample_rate' in query || 'channels' in query;
|
||||
const formatOk =
|
||||
query.encoding === AUDIO_FORMAT.encoding &&
|
||||
query.sample_rate === String(AUDIO_FORMAT.sampleRate) &&
|
||||
query.channels === String(AUDIO_FORMAT.channels);
|
||||
if (formatDeclared && !formatOk) throw new ApiError('unsupported_media', 'Unsupported audio format.');
|
||||
throw new ApiError('invalid_request', 'Malformed turn metadata.');
|
||||
}
|
||||
const pcm = req.body as Buffer;
|
||||
if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.');
|
||||
if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.');
|
||||
meta = { requestId: query.request_id, conversationId: query.conversation_id, locale: query.locale };
|
||||
input = { kind: 'audio', pcm };
|
||||
} else {
|
||||
throw new ApiError('unsupported_media', 'Unsupported content type.');
|
||||
}
|
||||
|
||||
// A duplicate of an existing request never consumes rate budget or creates work.
|
||||
const existing = engine.get(device.id, meta.requestId);
|
||||
if (!existing && !turnLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
|
||||
|
||||
const result = engine.submit(device.id, meta, input);
|
||||
if (!result.ok) throw new ApiError(result.code, result.message);
|
||||
reply.code(result.replayed ? 200 : 202);
|
||||
return engine.toResult(result.turn, result.replayed);
|
||||
});
|
||||
|
||||
app.get('/v1/turns/:requestId', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const { requestId } = req.params as { requestId: string };
|
||||
// Another device's turn is "not found", never "forbidden": ids are not an oracle.
|
||||
const turn = engine.get(device.id, requireUuid(requestId));
|
||||
if (!turn) throw new ApiError('not_found', 'Not found.');
|
||||
return engine.toResult(turn);
|
||||
});
|
||||
|
||||
app.post('/v1/turns/:requestId/cancel', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const { requestId } = req.params as { requestId: string };
|
||||
const turn = engine.cancel(device.id, requireUuid(requestId));
|
||||
if (!turn) throw new ApiError('not_found', 'Not found.');
|
||||
return engine.toResult(turn);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { AUDIO_FORMAT } from '@hermeven/contracts';
|
||||
|
||||
export interface TranscribeRequest {
|
||||
/** Raw PCM, signed 16-bit little-endian, mono, 16 kHz. Held in memory only. */
|
||||
pcm: Buffer;
|
||||
locale: string;
|
||||
signal: AbortSignal;
|
||||
}
|
||||
|
||||
export type SttFailureKind = 'unavailable' | 'failed';
|
||||
|
||||
export class SttError extends Error {
|
||||
override name = 'SttError';
|
||||
constructor(
|
||||
readonly kind: SttFailureKind,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface SttAdapter {
|
||||
readonly configured: boolean;
|
||||
transcribe(request: TranscribeRequest): Promise<string>;
|
||||
}
|
||||
|
||||
/** Used when no provider is configured: audio turns fail cleanly, typed text still works. */
|
||||
export class NoSttAdapter implements SttAdapter {
|
||||
readonly configured = false;
|
||||
async transcribe(): Promise<string> {
|
||||
throw new SttError('unavailable', 'No speech-to-text provider is configured');
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrap raw PCM in a 44-byte RIFF/WAVE header, in memory. Nothing is written to disk. */
|
||||
export function pcmToWav(pcm: Buffer): Buffer {
|
||||
const header = Buffer.alloc(44);
|
||||
const { sampleRate, channels } = AUDIO_FORMAT;
|
||||
const bytesPerSample = 2;
|
||||
header.write('RIFF', 0, 'ascii');
|
||||
header.writeUInt32LE(36 + pcm.length, 4);
|
||||
header.write('WAVE', 8, 'ascii');
|
||||
header.write('fmt ', 12, 'ascii');
|
||||
header.writeUInt32LE(16, 16);
|
||||
header.writeUInt16LE(1, 20); // PCM
|
||||
header.writeUInt16LE(channels, 22);
|
||||
header.writeUInt32LE(sampleRate, 24);
|
||||
header.writeUInt32LE(sampleRate * channels * bytesPerSample, 28);
|
||||
header.writeUInt16LE(channels * bytesPerSample, 32);
|
||||
header.writeUInt16LE(16, 34);
|
||||
header.write('data', 36, 'ascii');
|
||||
header.writeUInt32LE(pcm.length, 40);
|
||||
return Buffer.concat([header, pcm]);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { pcmToWav, SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
|
||||
|
||||
/**
|
||||
* Speech-to-text through any server that implements the OpenAI
|
||||
* `POST {base}/audio/transcriptions` multipart contract (OpenAI, Groq, and
|
||||
* self-hosted Whisper servers such as speaches or whisper.cpp's server). The
|
||||
* operator chooses the endpoint, so audio can stay on hardware they control.
|
||||
*
|
||||
* NOT YET EXERCISED AGAINST A REAL PROVIDER: see docs/feasibility.md.
|
||||
*/
|
||||
export class OpenAiCompatibleStt implements SttAdapter {
|
||||
readonly configured = true;
|
||||
|
||||
constructor(
|
||||
private readonly opts: { baseUrl: string; apiKey: string; model: string; fetchImpl?: typeof fetch },
|
||||
) {}
|
||||
|
||||
async transcribe(request: TranscribeRequest): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.append('file', new Blob([new Uint8Array(pcmToWav(request.pcm))], { type: 'audio/wav' }), 'capture.wav');
|
||||
form.append('model', this.opts.model);
|
||||
form.append('response_format', 'json');
|
||||
const language = request.locale.split('-')[0]?.toLowerCase();
|
||||
if (language) form.append('language', language);
|
||||
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
if (this.opts.apiKey) headers.Authorization = `Bearer ${this.opts.apiKey}`;
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await (this.opts.fetchImpl ?? fetch)(`${this.opts.baseUrl}/audio/transcriptions`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form,
|
||||
signal: request.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
if (request.signal.aborted) throw err;
|
||||
throw new SttError('unavailable', 'Speech-to-text provider could not be reached');
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel().catch(() => undefined);
|
||||
throw new SttError(res.status >= 500 || res.status === 429 ? 'unavailable' : 'failed', `Speech-to-text provider answered ${res.status}`);
|
||||
}
|
||||
let json: unknown;
|
||||
try {
|
||||
json = await res.json();
|
||||
} catch {
|
||||
throw new SttError('failed', 'Speech-to-text provider returned an unreadable answer');
|
||||
}
|
||||
const text = (json as { text?: unknown })?.text;
|
||||
if (typeof text !== 'string') throw new SttError('failed', 'Speech-to-text provider returned no text');
|
||||
return text.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import {
|
||||
isRetryable,
|
||||
SCHEMA_VERSION,
|
||||
type ErrorCode,
|
||||
type TurnOutcome,
|
||||
type TurnResult,
|
||||
type TurnState,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
import {
|
||||
buildRunBody,
|
||||
HermesSubmitError,
|
||||
HermesUnavailableError,
|
||||
type HermesAdapter,
|
||||
type RunStatus,
|
||||
} from './hermes/adapter.ts';
|
||||
import { SttError, type SttAdapter } from './stt/adapter.ts';
|
||||
|
||||
export interface TurnRow {
|
||||
request_id: string;
|
||||
device_id: string;
|
||||
conversation_id: string;
|
||||
input_kind: 'text' | 'audio';
|
||||
input_fingerprint: string;
|
||||
locale: string;
|
||||
state: TurnState;
|
||||
outcome: TurnOutcome | null;
|
||||
error_code: ErrorCode | null;
|
||||
error_message: string | null;
|
||||
cancel_requested: 0 | 1;
|
||||
hermes_idempotency_key: string;
|
||||
hermes_run_id: string | null;
|
||||
pending_body: string | null;
|
||||
input_text: string | null;
|
||||
answer_text: string | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
agent_started_at: number | null;
|
||||
approval_started_at: number | null;
|
||||
completed_at: number | null;
|
||||
transcribe_ms: number | null;
|
||||
agent_ms: number | null;
|
||||
}
|
||||
|
||||
export interface ConversationRow {
|
||||
id: string;
|
||||
device_id: string;
|
||||
hermes_session_id: string;
|
||||
created_at: number;
|
||||
closed_at: number | null;
|
||||
}
|
||||
|
||||
export interface EngineTiming {
|
||||
transcribeDeadlineMs: number;
|
||||
agentDeadlineMs: number;
|
||||
approvalWaitMs: number;
|
||||
cancelGraceMs: number;
|
||||
pollIntervalMs: number;
|
||||
submitRetryMs: number;
|
||||
/** Attempts before giving up when Hermes provably never received the request. */
|
||||
notSentAttempts: number;
|
||||
}
|
||||
|
||||
export function timingFromConfig(config: BridgeConfig): EngineTiming {
|
||||
return {
|
||||
transcribeDeadlineMs: config.limits.transcribeDeadlineSeconds * 1000,
|
||||
agentDeadlineMs: config.limits.agentDeadlineSeconds * 1000,
|
||||
approvalWaitMs: config.limits.approvalWaitSeconds * 1000,
|
||||
cancelGraceMs: config.limits.cancelGraceSeconds * 1000,
|
||||
pollIntervalMs: config.hermes.pollIntervalMs,
|
||||
submitRetryMs: 500,
|
||||
notSentAttempts: 3,
|
||||
};
|
||||
}
|
||||
|
||||
/** Structured, content-free logging: ids, states, codes and timings only. */
|
||||
export interface EngineLog {
|
||||
info(fields: Record<string, unknown>, msg: string): void;
|
||||
warn(fields: Record<string, unknown>, msg: string): void;
|
||||
error(fields: Record<string, unknown>, msg: string): void;
|
||||
}
|
||||
|
||||
export type SubmitInput = { kind: 'text'; text: string } | { kind: 'audio'; pcm: Buffer };
|
||||
|
||||
export type SubmitResult =
|
||||
| { ok: true; turn: TurnRow; replayed: boolean }
|
||||
| { ok: false; code: ErrorCode; message: string };
|
||||
|
||||
interface ActiveTurn {
|
||||
sttAbort: AbortController | null;
|
||||
wake: (() => void) | null;
|
||||
}
|
||||
|
||||
const MESSAGES: Partial<Record<ErrorCode, string>> = {
|
||||
stt_unavailable: 'Speech-to-text is not available.',
|
||||
stt_failed: 'Speech could not be transcribed.',
|
||||
stt_timeout: 'Transcription took too long.',
|
||||
stt_empty: 'No speech was recognised.',
|
||||
interrupted_before_agent: 'The bridge restarted before the request reached the agent. Nothing ran.',
|
||||
agent_unreachable: 'The agent could not be reached. Nothing ran.',
|
||||
agent_rejected: 'The agent refused the request. Nothing ran.',
|
||||
agent_failed: 'The agent reported a failure. Actions it had already taken are not undone.',
|
||||
agent_interrupted: 'The agent was interrupted. Actions it had already taken are not undone.',
|
||||
agent_timeout: 'The agent ran out of time and was stopped. Actions it had already taken are not undone.',
|
||||
approval_timeout: 'The agent needed an approval that did not arrive, and was stopped.',
|
||||
agent_incomplete: 'The agent stopped before finishing. This answer is partial.',
|
||||
outcome_unknown: 'The outcome is unknown. Check the agent before asking again.',
|
||||
};
|
||||
|
||||
export class TurnEngine {
|
||||
private readonly active = new Map<string, ActiveTurn>();
|
||||
private readonly tasks = new Set<Promise<void>>();
|
||||
private stopping = false;
|
||||
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
db: Db;
|
||||
config: BridgeConfig;
|
||||
hermes: HermesAdapter;
|
||||
stt: SttAdapter;
|
||||
log: EngineLog;
|
||||
timing?: EngineTiming;
|
||||
now?: () => number;
|
||||
},
|
||||
) {
|
||||
this.timing = deps.timing ?? timingFromConfig(deps.config);
|
||||
this.now = deps.now ?? Date.now;
|
||||
}
|
||||
|
||||
private readonly timing: EngineTiming;
|
||||
private readonly now: () => number;
|
||||
|
||||
// ------------------------------------------------------------ conversations
|
||||
|
||||
/** Start a fresh conversation for the device. Any earlier one is closed, not deleted. */
|
||||
createConversation(deviceId: string): ConversationRow {
|
||||
const now = this.now();
|
||||
const row: ConversationRow = {
|
||||
id: randomUUID(),
|
||||
device_id: deviceId,
|
||||
hermes_session_id: `hermeven-${randomUUID()}`,
|
||||
created_at: now,
|
||||
closed_at: null,
|
||||
};
|
||||
this.deps.db.transaction(() => {
|
||||
this.deps.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
this.deps.db
|
||||
.prepare('INSERT INTO conversations (id, device_id, hermes_session_id, created_at) VALUES (@id, @device_id, @hermes_session_id, @created_at)')
|
||||
.run(row);
|
||||
})();
|
||||
this.deps.log.info({ device_id: deviceId, conversation_id: row.id }, 'conversation.created');
|
||||
return row;
|
||||
}
|
||||
|
||||
activeConversation(deviceId: string): ConversationRow | undefined {
|
||||
return this.deps.db
|
||||
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL ORDER BY created_at DESC LIMIT 1')
|
||||
.get(deviceId) as ConversationRow | undefined;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- turns
|
||||
|
||||
submit(
|
||||
deviceId: string,
|
||||
meta: { requestId: string; conversationId: string; locale: string },
|
||||
input: SubmitInput,
|
||||
): SubmitResult {
|
||||
const db = this.deps.db;
|
||||
const inputHash = createHash('sha256')
|
||||
.update(input.kind === 'text' ? input.text : input.pcm)
|
||||
.digest('hex');
|
||||
const fingerprint = createHash('sha256')
|
||||
.update([input.kind, meta.conversationId, meta.locale, inputHash].join('\n'))
|
||||
.digest('hex');
|
||||
|
||||
const decision = db.transaction((): SubmitResult => {
|
||||
const existing = db.prepare('SELECT * FROM turns WHERE request_id = ?').get(meta.requestId) as TurnRow | undefined;
|
||||
if (existing) {
|
||||
// Another device's request id is indistinguishable from a conflict on purpose.
|
||||
if (existing.device_id !== deviceId || existing.input_fingerprint !== fingerprint) {
|
||||
return { ok: false, code: 'request_id_conflict', message: 'This request id was already used for a different request.' };
|
||||
}
|
||||
return { ok: true, turn: existing, replayed: true };
|
||||
}
|
||||
const conversation = db.prepare('SELECT * FROM conversations WHERE id = ?').get(meta.conversationId) as ConversationRow | undefined;
|
||||
if (!conversation || conversation.device_id !== deviceId) {
|
||||
return { ok: false, code: 'not_found', message: 'Conversation not found.' };
|
||||
}
|
||||
if (conversation.closed_at !== null) {
|
||||
return { ok: false, code: 'conversation_closed', message: 'This conversation was closed. Start a new one.' };
|
||||
}
|
||||
const busy = db
|
||||
.prepare("SELECT 1 FROM turns WHERE conversation_id = ? AND state != 'done' LIMIT 1")
|
||||
.get(meta.conversationId);
|
||||
if (busy) {
|
||||
return { ok: false, code: 'conversation_busy', message: 'The previous request is still in progress.' };
|
||||
}
|
||||
const now = this.now();
|
||||
const row: TurnRow = {
|
||||
request_id: meta.requestId,
|
||||
device_id: deviceId,
|
||||
conversation_id: meta.conversationId,
|
||||
input_kind: input.kind,
|
||||
input_fingerprint: fingerprint,
|
||||
locale: meta.locale,
|
||||
state: 'accepted',
|
||||
outcome: null,
|
||||
error_code: null,
|
||||
error_message: null,
|
||||
cancel_requested: 0,
|
||||
// Derived from our own request id; opaque and unguessable enough (UUIDv4 inside).
|
||||
hermes_idempotency_key: `hermeven-turn-${meta.requestId}`,
|
||||
hermes_run_id: null,
|
||||
pending_body: null,
|
||||
input_text: input.kind === 'text' ? input.text : null,
|
||||
answer_text: null,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
agent_started_at: null,
|
||||
approval_started_at: null,
|
||||
completed_at: null,
|
||||
transcribe_ms: null,
|
||||
agent_ms: null,
|
||||
};
|
||||
db.prepare(
|
||||
`INSERT INTO turns (request_id, device_id, conversation_id, input_kind, input_fingerprint, locale, state,
|
||||
hermes_idempotency_key, input_text, created_at, updated_at)
|
||||
VALUES (@request_id, @device_id, @conversation_id, @input_kind, @input_fingerprint, @locale, @state,
|
||||
@hermes_idempotency_key, @input_text, @created_at, @updated_at)`,
|
||||
).run(row);
|
||||
return { ok: true, turn: row, replayed: false };
|
||||
})();
|
||||
|
||||
if (decision.ok && !decision.replayed) {
|
||||
this.deps.log.info({ request_id: meta.requestId, input_kind: input.kind, state: 'accepted' }, 'turn.accepted');
|
||||
this.launch(meta.requestId, input.kind === 'audio' ? input.pcm : null);
|
||||
}
|
||||
return decision;
|
||||
}
|
||||
|
||||
get(deviceId: string, requestId: string): TurnRow | undefined {
|
||||
const row = this.row(requestId);
|
||||
return row && row.device_id === deviceId ? row : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent. Records the request and nudges the worker; the terminal outcome is whatever
|
||||
* Hermes confirms. A cancel never claims that side effects were undone.
|
||||
*/
|
||||
cancel(deviceId: string, requestId: string): TurnRow | undefined {
|
||||
const row = this.get(deviceId, requestId);
|
||||
if (!row) return undefined;
|
||||
if (row.state === 'done' || row.cancel_requested) return row;
|
||||
this.update(requestId, { cancel_requested: 1 });
|
||||
this.deps.log.info({ request_id: requestId, state: row.state }, 'turn.cancel_requested');
|
||||
const active = this.active.get(requestId);
|
||||
active?.sttAbort?.abort();
|
||||
active?.wake?.();
|
||||
return this.row(requestId);
|
||||
}
|
||||
|
||||
/** Resume or settle every turn a previous process left in flight. Call once at startup. */
|
||||
recover(): void {
|
||||
const rows = this.deps.db.prepare("SELECT * FROM turns WHERE state != 'done'").all() as TurnRow[];
|
||||
for (const row of rows) {
|
||||
if (row.hermes_run_id || row.pending_body) {
|
||||
this.deps.log.warn({ request_id: row.request_id, state: row.state }, 'turn.recovering');
|
||||
this.launch(row.request_id, null, true);
|
||||
} else {
|
||||
// Audio lived only in memory and nothing had been sent to Hermes: provably nothing ran.
|
||||
this.finish(row.request_id, 'failed', { code: 'interrupted_before_agent' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop cached input/answer text past the retention window, and stale pairing codes. */
|
||||
purgeExpired(): number {
|
||||
const cutoff = this.now() - this.deps.config.resultRetentionSeconds * 1000;
|
||||
const res = this.deps.db
|
||||
.prepare(
|
||||
`UPDATE turns SET input_text = NULL, answer_text = NULL
|
||||
WHERE state = 'done' AND completed_at < ? AND (input_text IS NOT NULL OR answer_text IS NOT NULL)`,
|
||||
)
|
||||
.run(cutoff);
|
||||
this.deps.db.prepare('DELETE FROM pairing_codes WHERE expires_at < ?').run(this.now() - 86_400_000);
|
||||
return res.changes;
|
||||
}
|
||||
|
||||
/** Stop workers without settling their turns; the next start recovers them. */
|
||||
async shutdown(): Promise<void> {
|
||||
this.stopping = true;
|
||||
for (const active of this.active.values()) {
|
||||
active.sttAbort?.abort();
|
||||
active.wake?.();
|
||||
}
|
||||
await Promise.allSettled([...this.tasks]);
|
||||
}
|
||||
|
||||
toResult(row: TurnRow, replayed = false): TurnResult {
|
||||
const iso = (ms: number) => new Date(ms).toISOString();
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: row.request_id,
|
||||
conversation_id: row.conversation_id,
|
||||
state: row.state,
|
||||
terminal: row.state === 'done',
|
||||
outcome: row.outcome,
|
||||
cancel_requested: row.cancel_requested === 1,
|
||||
input_text: row.input_text,
|
||||
answer_text: row.answer_text,
|
||||
error: row.error_code
|
||||
? { code: row.error_code, message: row.error_message ?? '', retryable: isRetryable(row.error_code) }
|
||||
: null,
|
||||
replayed,
|
||||
created_at: iso(row.created_at),
|
||||
updated_at: iso(row.updated_at),
|
||||
timings: { transcribe_ms: row.transcribe_ms, agent_ms: row.agent_ms },
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- internals
|
||||
|
||||
private row(requestId: string): TurnRow | undefined {
|
||||
return this.deps.db.prepare('SELECT * FROM turns WHERE request_id = ?').get(requestId) as TurnRow | undefined;
|
||||
}
|
||||
|
||||
private update(requestId: string, fields: Partial<TurnRow>): void {
|
||||
const keys = Object.keys(fields);
|
||||
const sets = [...keys.map((k) => `${k} = @${k}`), 'updated_at = @updated_at'].join(', ');
|
||||
this.deps.db
|
||||
.prepare(`UPDATE turns SET ${sets} WHERE request_id = @request_id`)
|
||||
.run({ ...fields, updated_at: this.now(), request_id: requestId });
|
||||
}
|
||||
|
||||
private setState(requestId: string, state: TurnState, extra: Partial<TurnRow> = {}): void {
|
||||
const before = this.row(requestId);
|
||||
if (!before || before.state === 'done') return;
|
||||
if (before.state === state && Object.keys(extra).length === 0) return;
|
||||
this.update(requestId, { state, ...extra });
|
||||
if (before.state !== state) this.deps.log.info({ request_id: requestId, from: before.state, state }, 'turn.state');
|
||||
}
|
||||
|
||||
private finish(
|
||||
requestId: string,
|
||||
outcome: TurnOutcome,
|
||||
opts: { code?: ErrorCode; answer?: string | null } = {},
|
||||
): void {
|
||||
const before = this.row(requestId);
|
||||
if (!before || before.state === 'done') return;
|
||||
const now = this.now();
|
||||
this.update(requestId, {
|
||||
state: 'done',
|
||||
outcome,
|
||||
error_code: opts.code ?? null,
|
||||
error_message: opts.code ? (MESSAGES[opts.code] ?? 'The request did not complete.') : null,
|
||||
answer_text: opts.answer ?? null,
|
||||
pending_body: null,
|
||||
completed_at: now,
|
||||
agent_ms: before.agent_started_at ? now - before.agent_started_at : null,
|
||||
});
|
||||
this.deps.log.info(
|
||||
{
|
||||
request_id: requestId,
|
||||
outcome,
|
||||
error_code: opts.code ?? null,
|
||||
transcribe_ms: before.transcribe_ms,
|
||||
agent_ms: before.agent_started_at ? now - before.agent_started_at : null,
|
||||
total_ms: now - before.created_at,
|
||||
},
|
||||
'turn.done',
|
||||
);
|
||||
}
|
||||
|
||||
private launch(requestId: string, pcm: Buffer | null, recovered = false): void {
|
||||
const active: ActiveTurn = { sttAbort: null, wake: null };
|
||||
this.active.set(requestId, active);
|
||||
const task = this.drive(requestId, pcm, active, recovered)
|
||||
.catch((err: unknown) => {
|
||||
this.deps.log.error({ request_id: requestId, err_name: err instanceof Error ? err.name : 'unknown' }, 'turn.worker_crashed');
|
||||
const row = this.row(requestId);
|
||||
// Once anything may have reached Hermes, a crash leaves the outcome unknown.
|
||||
if (row && (row.hermes_run_id || row.pending_body)) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
else this.finish(requestId, 'failed', { code: 'interrupted_before_agent' });
|
||||
})
|
||||
.finally(() => {
|
||||
this.active.delete(requestId);
|
||||
this.tasks.delete(task);
|
||||
});
|
||||
this.tasks.add(task);
|
||||
}
|
||||
|
||||
private cancelRequested(requestId: string): boolean {
|
||||
return this.row(requestId)?.cancel_requested === 1;
|
||||
}
|
||||
|
||||
private sleep(active: ActiveTurn, ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(done, ms);
|
||||
function done() {
|
||||
clearTimeout(timer);
|
||||
active.wake = null;
|
||||
resolve();
|
||||
}
|
||||
active.wake = done;
|
||||
});
|
||||
}
|
||||
|
||||
private async drive(requestId: string, pcm: Buffer | null, active: ActiveTurn, recovered: boolean): Promise<void> {
|
||||
let row = this.row(requestId)!;
|
||||
|
||||
if (!recovered) {
|
||||
if (row.input_kind === 'audio') {
|
||||
const text = await this.transcribe(requestId, pcm!, active, row.locale);
|
||||
pcm = null; // the only reference to the recording; let it be collected
|
||||
if (text === null) return;
|
||||
}
|
||||
if (this.cancelRequested(requestId)) {
|
||||
// Nothing has been sent to Hermes: this cancel is clean and complete.
|
||||
this.finish(requestId, 'cancelled');
|
||||
return;
|
||||
}
|
||||
row = this.row(requestId)!;
|
||||
const conversation = this.deps.db
|
||||
.prepare('SELECT * FROM conversations WHERE id = ?')
|
||||
.get(row.conversation_id) as ConversationRow;
|
||||
// Persist the exact body BEFORE the first network attempt, so a crash can replay it
|
||||
// under the same idempotency key instead of guessing.
|
||||
this.setState(requestId, 'thinking', {
|
||||
pending_body: buildRunBody({
|
||||
input: row.input_text ?? '',
|
||||
sessionId: conversation.hermes_session_id,
|
||||
instructions: this.deps.config.hermes.instructions,
|
||||
}),
|
||||
agent_started_at: this.now(),
|
||||
});
|
||||
}
|
||||
|
||||
row = this.row(requestId)!;
|
||||
if (!row.hermes_run_id) {
|
||||
// A recovered turn may already have been sent by the previous process.
|
||||
const runId = await this.submitToHermes(requestId, active, recovered);
|
||||
if (runId === null) return;
|
||||
this.update(requestId, { hermes_run_id: runId, pending_body: null });
|
||||
}
|
||||
await this.poll(requestId, active);
|
||||
}
|
||||
|
||||
private async transcribe(requestId: string, pcm: Buffer, active: ActiveTurn, locale: string): Promise<string | null> {
|
||||
this.setState(requestId, 'transcribing');
|
||||
const started = this.now();
|
||||
const abort = new AbortController();
|
||||
active.sttAbort = abort;
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
abort.abort();
|
||||
}, this.timing.transcribeDeadlineMs);
|
||||
try {
|
||||
const text = await this.deps.stt.transcribe({ pcm, locale, signal: abort.signal });
|
||||
if (this.stopping) return null;
|
||||
if (!text) {
|
||||
this.finish(requestId, 'failed', { code: 'stt_empty' });
|
||||
return null;
|
||||
}
|
||||
this.update(requestId, { input_text: text, transcribe_ms: this.now() - started });
|
||||
return text;
|
||||
} catch (err) {
|
||||
if (this.stopping) return null; // left in flight; recover() settles it honestly
|
||||
if (timedOut) this.finish(requestId, 'failed', { code: 'stt_timeout' });
|
||||
else if (this.cancelRequested(requestId)) this.finish(requestId, 'cancelled');
|
||||
else if (err instanceof SttError && err.kind === 'unavailable') this.finish(requestId, 'failed', { code: 'stt_unavailable' });
|
||||
else this.finish(requestId, 'failed', { code: 'stt_failed' });
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
active.sttAbort = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the run id, or null when the turn was settled here. */
|
||||
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> {
|
||||
const row = this.row(requestId)!;
|
||||
const deadline = (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let ambiguous = maybeAlreadySent;
|
||||
let notSent = 0;
|
||||
|
||||
for (;;) {
|
||||
if (this.stopping) return null;
|
||||
try {
|
||||
const { runId } = await this.deps.hermes.submit({
|
||||
idempotencyKey: row.hermes_idempotency_key,
|
||||
body: row.pending_body!,
|
||||
});
|
||||
return runId;
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesSubmitError)) throw err;
|
||||
this.deps.log.warn({ request_id: requestId, kind: err.kind, http_status: err.httpStatus ?? null }, 'hermes.submit_failed');
|
||||
if (err.kind === 'conflict') {
|
||||
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
return null;
|
||||
}
|
||||
if (err.kind === 'rejected') {
|
||||
this.finish(requestId, 'failed', { code: 'agent_rejected' });
|
||||
return null;
|
||||
}
|
||||
if (err.kind === 'ambiguous') ambiguous = true;
|
||||
if (err.kind === 'not_sent' && !ambiguous && ++notSent >= this.timing.notSentAttempts) {
|
||||
this.finish(requestId, 'failed', { code: 'agent_unreachable' });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!ambiguous && this.cancelRequested(requestId)) {
|
||||
// Every attempt so far provably never reached Hermes.
|
||||
this.finish(requestId, 'cancelled');
|
||||
return null;
|
||||
}
|
||||
if (this.now() >= deadline) {
|
||||
// Timeout is "unknown until reconciled", never permission to run again.
|
||||
if (ambiguous) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
else this.finish(requestId, 'failed', { code: 'agent_unreachable' });
|
||||
return null;
|
||||
}
|
||||
await this.sleep(active, this.timing.submitRetryMs);
|
||||
}
|
||||
}
|
||||
|
||||
private async poll(requestId: string, active: ActiveTurn): Promise<void> {
|
||||
const start = this.row(requestId)!;
|
||||
const runId = start.hermes_run_id!;
|
||||
let deadlineAt = (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let approvalSince: number | null = null;
|
||||
let stopReason: 'user' | 'agent_timeout' | 'approval_timeout' | null = null;
|
||||
let stopAccepted = false;
|
||||
let graceUntil = 0;
|
||||
|
||||
for (;;) {
|
||||
if (this.stopping) return;
|
||||
const now = this.now();
|
||||
|
||||
if (!stopReason) {
|
||||
if (this.cancelRequested(requestId)) stopReason = 'user';
|
||||
else if (approvalSince !== null && now >= approvalSince + this.timing.approvalWaitMs) stopReason = 'approval_timeout';
|
||||
else if (approvalSince === null && now >= deadlineAt) stopReason = 'agent_timeout';
|
||||
if (stopReason) {
|
||||
graceUntil = now + this.timing.cancelGraceMs;
|
||||
this.setState(requestId, 'cancelling');
|
||||
}
|
||||
}
|
||||
if (stopReason && !stopAccepted) {
|
||||
try {
|
||||
await this.deps.hermes.stop(runId);
|
||||
stopAccepted = true;
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let status: RunStatus | null = null;
|
||||
try {
|
||||
status = await this.deps.hermes.status(runId);
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
}
|
||||
|
||||
if (status) {
|
||||
switch (status.state) {
|
||||
case 'completed':
|
||||
this.finish(requestId, 'succeeded', { answer: status.output });
|
||||
return;
|
||||
case 'failed':
|
||||
if (status.output && !status.finished) {
|
||||
this.finish(requestId, 'incomplete', { code: 'agent_incomplete', answer: status.output });
|
||||
} else {
|
||||
this.finish(requestId, 'failed', { code: 'agent_failed' });
|
||||
}
|
||||
return;
|
||||
case 'cancelled':
|
||||
this.finish(requestId, 'cancelled', stopReason && stopReason !== 'user' ? { code: stopReason } : {});
|
||||
return;
|
||||
case 'interrupted':
|
||||
this.finish(requestId, 'failed', { code: 'agent_interrupted' });
|
||||
return;
|
||||
case 'unknown':
|
||||
case 'not_found':
|
||||
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
return;
|
||||
case 'waiting_for_approval':
|
||||
if (approvalSince === null) approvalSince = now;
|
||||
if (!stopReason) this.setState(requestId, 'approval_required', { approval_started_at: now });
|
||||
break;
|
||||
default:
|
||||
if (approvalSince !== null) {
|
||||
// Approval was resolved on another surface; time spent waiting does not count.
|
||||
deadlineAt += now - approvalSince;
|
||||
approvalSince = null;
|
||||
}
|
||||
if (!stopReason) this.setState(requestId, 'thinking');
|
||||
}
|
||||
}
|
||||
|
||||
if (stopReason && this.now() >= graceUntil) {
|
||||
// We asked Hermes to stop and could not confirm what happened.
|
||||
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
return;
|
||||
}
|
||||
await this.sleep(active, this.timing.pollIntervalMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ConfigError, loadConfig } from '../src/config.ts';
|
||||
import { openDb } from '../src/db.ts';
|
||||
import { Devices } from '../src/devices.ts';
|
||||
import { buildRunBody } from '../src/hermes/adapter.ts';
|
||||
import { mapRunStatus } from '../src/hermes/runsAdapter.ts';
|
||||
import { RateLimiter } from '../src/ratelimit.ts';
|
||||
import { pcmToWav } from '../src/stt/adapter.ts';
|
||||
|
||||
const base = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:' };
|
||||
|
||||
describe('configuration', () => {
|
||||
it('binds loopback by default and refuses a public bind without an explicit acknowledgement', () => {
|
||||
expect(loadConfig(base).host).toBe('127.0.0.1');
|
||||
expect(() => loadConfig({ ...base, HERMEVEN_HOST: '0.0.0.0' })).toThrow(ConfigError);
|
||||
expect(loadConfig({ ...base, HERMEVEN_HOST: '0.0.0.0', HERMEVEN_ALLOW_NON_LOOPBACK: 'true' }).host).toBe('0.0.0.0');
|
||||
});
|
||||
|
||||
it('requires https for Hermes and STT outside loopback', () => {
|
||||
expect(() => loadConfig({ ...base, HERMES_BASE_URL: 'http://hermes.example:8642' })).toThrow(/https/);
|
||||
expect(loadConfig({ ...base, HERMES_BASE_URL: 'https://hermes.example/p/work/' }).hermes.baseUrl).toBe('https://hermes.example/p/work');
|
||||
expect(() =>
|
||||
loadConfig({ ...base, STT_PROVIDER: 'openai-compatible', STT_BASE_URL: 'http://stt.example/v1', STT_MODEL: 'm' }),
|
||||
).toThrow(/https/);
|
||||
});
|
||||
|
||||
it('requires a Hermes key and exact CORS origins', () => {
|
||||
expect(() => loadConfig({ HERMEVEN_DB_PATH: ':memory:' })).toThrow(/HERMES_API_KEY/);
|
||||
expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: '*' })).toThrow(ConfigError);
|
||||
expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example/path' })).toThrow(ConfigError);
|
||||
expect(loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example, http://localhost:5173' }).allowedOrigins).toEqual([
|
||||
'https://a.example',
|
||||
'http://localhost:5173',
|
||||
]);
|
||||
});
|
||||
|
||||
it('derives the audio byte cap from the capture cap and never puts secrets in error text', () => {
|
||||
const config = loadConfig({ ...base, HERMEVEN_CAPTURE_MAX_SECONDS: '10' });
|
||||
expect(config.limits.audioMaxBytes).toBe(11 * 32000);
|
||||
try {
|
||||
loadConfig({ ...base, HERMES_API_KEY: 'super-secret', HERMEVEN_PORT: 'abc' });
|
||||
throw new Error('should have thrown');
|
||||
} catch (err) {
|
||||
expect(String(err)).not.toContain('super-secret');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('device credentials', () => {
|
||||
const setup = (env: Record<string, string> = {}) => {
|
||||
let now = 1_000_000;
|
||||
const config = loadConfig({ ...base, ...env });
|
||||
const devices = new Devices(openDb(':memory:'), config, () => now);
|
||||
return { devices, config, advance: (ms: number) => (now += ms) };
|
||||
};
|
||||
|
||||
it('stores only a hash of the token and of the pairing code', () => {
|
||||
const { devices } = setup();
|
||||
const { code } = devices.createPairingCode();
|
||||
const claimed = devices.claimPairingCode(code, 'g2');
|
||||
if (!claimed.ok) throw new Error('claim failed');
|
||||
const row = devices.get(claimed.device.id)!;
|
||||
expect(row.token_hash).not.toContain(claimed.token);
|
||||
expect(row.token_hash).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(JSON.stringify(row)).not.toContain(claimed.token);
|
||||
});
|
||||
|
||||
it('pairing codes expire, are case/format tolerant, and a new code voids the old one', () => {
|
||||
const { devices, advance } = setup({ HERMEVEN_PAIRING_CODE_TTL_SECONDS: '60' });
|
||||
const first = devices.createPairingCode();
|
||||
const second = devices.createPairingCode();
|
||||
expect(devices.claimPairingCode(first.code, 'x').ok).toBe(false);
|
||||
expect(devices.claimPairingCode(second.code.toLowerCase().replace('-', ' '), 'x').ok).toBe(true);
|
||||
const third = devices.createPairingCode();
|
||||
advance(61_000);
|
||||
expect(devices.claimPairingCode(third.code, 'x')).toEqual({ ok: false, reason: 'pairing_invalid' });
|
||||
});
|
||||
|
||||
it('tokens expire, can be renewed while valid, and never outlive the pairing', () => {
|
||||
const { devices, advance } = setup({ HERMEVEN_TOKEN_TTL_SECONDS: '100', HERMEVEN_PAIRING_TTL_SECONDS: '250' });
|
||||
const claimed = devices.claimPairingCode(devices.createPairingCode().code, 'g2');
|
||||
if (!claimed.ok) throw new Error('claim failed');
|
||||
advance(90_000);
|
||||
expect(devices.authenticate(claimed.token).ok).toBe(true);
|
||||
const renewed = devices.renew(claimed.device.id);
|
||||
expect(devices.authenticate(claimed.token)).toEqual({ ok: false, reason: 'unauthorized' });
|
||||
advance(90_000);
|
||||
expect(devices.authenticate(renewed.token).ok).toBe(true);
|
||||
const again = devices.renew(claimed.device.id);
|
||||
// Renewal cannot push past the absolute pairing lifetime (t = 250 s).
|
||||
expect(again.device.token_expires_at).toBe(again.device.pairing_expires_at);
|
||||
advance(80_000);
|
||||
expect(devices.authenticate(again.token)).toEqual({ ok: false, reason: 'credential_expired' });
|
||||
});
|
||||
|
||||
it('a device paired for one profile is not valid for another', () => {
|
||||
const db = openDb(':memory:');
|
||||
const a = new Devices(db, loadConfig({ ...base, HERMES_PROFILE_LABEL: 'personal' }));
|
||||
const claimed = a.claimPairingCode(a.createPairingCode().code, 'g2');
|
||||
if (!claimed.ok) throw new Error('claim failed');
|
||||
const b = new Devices(db, loadConfig({ ...base, HERMES_PROFILE_LABEL: 'work' }));
|
||||
expect(b.authenticate(claimed.token)).toEqual({ ok: false, reason: 'unauthorized' });
|
||||
});
|
||||
|
||||
it('pairing codes have enough entropy and an unambiguous alphabet', () => {
|
||||
const { devices } = setup();
|
||||
const codes = new Set(Array.from({ length: 200 }, () => devices.createPairingCode().code));
|
||||
expect(codes.size).toBe(200);
|
||||
for (const code of codes) expect(code).toMatch(/^[A-HJ-KM-NP-Z2-9]{5}-[A-HJ-KM-NP-Z2-9]{5}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hermes adapter helpers', () => {
|
||||
it('builds a byte-stable request body', () => {
|
||||
const a = buildRunBody({ input: 'hi "there"', sessionId: 'hermeven-1', instructions: 'be brief' });
|
||||
expect(a).toBe('{"input":"hi \\"there\\"","session_id":"hermeven-1","instructions":"be brief"}');
|
||||
expect(buildRunBody({ input: 'hi', sessionId: 's', instructions: '' })).toBe('{"input":"hi","session_id":"s"}');
|
||||
});
|
||||
|
||||
it('maps run statuses, treating anything unrecognised as still running', () => {
|
||||
expect(mapRunStatus({ status: 'completed', output: 'x' })).toEqual({ state: 'completed', output: 'x', finished: true, error: null });
|
||||
expect(mapRunStatus({ status: 'failed', output: 'part', completed: false, partial: true }).finished).toBe(false);
|
||||
expect(mapRunStatus({ status: 'waiting_for_approval' }).state).toBe('waiting_for_approval');
|
||||
expect(mapRunStatus({ status: 'unknown' }).state).toBe('unknown');
|
||||
expect(mapRunStatus({ status: 'some_future_status' }).state).toBe('running');
|
||||
expect(mapRunStatus({ status: 'completed', output: { not: 'text' } }).output).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('small utilities', () => {
|
||||
it('rate limiter enforces a fixed window per key', () => {
|
||||
let now = 0;
|
||||
const limiter = new RateLimiter(2, 1000, () => now);
|
||||
expect([limiter.take('a'), limiter.take('a'), limiter.take('a'), limiter.take('b')]).toEqual([true, true, false, true]);
|
||||
now = 1000;
|
||||
expect(limiter.take('a')).toBe(true);
|
||||
});
|
||||
|
||||
it('wraps PCM in a correct WAV header', () => {
|
||||
const wav = pcmToWav(Buffer.alloc(3200, 1));
|
||||
expect(wav.length).toBe(3244);
|
||||
expect(wav.toString('ascii', 0, 4)).toBe('RIFF');
|
||||
expect(wav.readUInt32LE(4)).toBe(3236);
|
||||
expect(wav.readUInt16LE(20)).toBe(1);
|
||||
expect(wav.readUInt16LE(22)).toBe(1);
|
||||
expect(wav.readUInt32LE(24)).toBe(16000);
|
||||
expect(wav.readUInt32LE(28)).toBe(32000);
|
||||
expect(wav.readUInt16LE(34)).toBe(16);
|
||||
expect(wav.readUInt32LE(40)).toBe(3200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "types": ["node"] },
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { HudFrame } from '../../apps/even-client/src/core/hud.ts';
|
||||
import type { DeviceEvent } from '../../apps/even-client/src/device/events.ts';
|
||||
import type { DevicePort } from '../../apps/even-client/src/device/port.ts';
|
||||
|
||||
/**
|
||||
* TEST FAKE. Not glasses, not the simulator.
|
||||
*
|
||||
* Records what the app would draw, and lets a test play gestures and audio
|
||||
* frames. It proves the app's logic against the DevicePort contract only.
|
||||
*/
|
||||
export class FakeDevice implements DevicePort {
|
||||
frames: HudFrame[] = [];
|
||||
micOpen = false;
|
||||
micOpens = 0;
|
||||
micCloses = 0;
|
||||
micAllowed = true;
|
||||
exitRequests = 0;
|
||||
readonly storage = new Map<string, string>();
|
||||
private readonly listeners = new Set<(event: DeviceEvent) => void>();
|
||||
private readonly connectionListeners = new Set<(connected: boolean) => void>();
|
||||
|
||||
get frame(): HudFrame {
|
||||
return this.frames.at(-1) ?? { body: '', status: '' };
|
||||
}
|
||||
|
||||
async init(frame: HudFrame): Promise<boolean> {
|
||||
this.frames.push(frame);
|
||||
return true;
|
||||
}
|
||||
show(frame: HudFrame): void {
|
||||
this.frames.push(frame);
|
||||
}
|
||||
async startMic(): Promise<boolean> {
|
||||
if (!this.micAllowed) return false;
|
||||
this.micOpen = true;
|
||||
this.micOpens += 1;
|
||||
return true;
|
||||
}
|
||||
async stopMic(): Promise<void> {
|
||||
if (this.micOpen) this.micCloses += 1;
|
||||
this.micOpen = false;
|
||||
}
|
||||
onEvent(listener: (event: DeviceEvent) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
onConnection(listener: (connected: boolean) => void): () => void {
|
||||
this.connectionListeners.add(listener);
|
||||
return () => this.connectionListeners.delete(listener);
|
||||
}
|
||||
async requestExit(): Promise<void> {
|
||||
this.exitRequests += 1;
|
||||
}
|
||||
async storageGet(key: string): Promise<string> {
|
||||
return this.storage.get(key) ?? '';
|
||||
}
|
||||
async storageSet(key: string, value: string): Promise<void> {
|
||||
this.storage.set(key, value);
|
||||
}
|
||||
|
||||
// ---- test controls
|
||||
emit(event: DeviceEvent): void {
|
||||
for (const l of this.listeners) l(event);
|
||||
}
|
||||
tap = () => this.emit({ type: 'tap' });
|
||||
doubleTap = () => this.emit({ type: 'double_tap' });
|
||||
swipeDown = () => this.emit({ type: 'swipe_down' });
|
||||
swipeUp = () => this.emit({ type: 'swipe_up' });
|
||||
menu = (itemId: number) => this.emit({ type: 'menu', itemId });
|
||||
connection(connected: boolean): void {
|
||||
for (const l of this.connectionListeners) l(connected);
|
||||
}
|
||||
/** Deliver audio the way the SDK documents it: 100 ms frames of 3,200 bytes. Only while the mic is open. */
|
||||
speak(seconds: number): void {
|
||||
const frames = Math.round(seconds * 10);
|
||||
for (let i = 0; i < frames && this.micOpen; i++) {
|
||||
const pcm = new Uint8Array(3200);
|
||||
for (let s = 0; s < 1600; s++) {
|
||||
const v = Math.round(Math.sin((2 * Math.PI * 440 * (i * 1600 + s)) / 16000) * 8000);
|
||||
pcm[s * 2] = v & 0xff;
|
||||
pcm[s * 2 + 1] = (v >> 8) & 0xff;
|
||||
}
|
||||
this.emit({ type: 'audio', pcm });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
/**
|
||||
* TEST FAKE. Not Hermes.
|
||||
*
|
||||
* A deterministic stand-in for the Hermes API server's Runs API, written from
|
||||
* the hermes-agent v0.23.1 source (gateway/platforms/api_server_runs.py). It
|
||||
* exists so the bridge's real HTTP adapter can be exercised against scripted
|
||||
* outcomes and faults. A passing test against this file is evidence about
|
||||
* Hermeven's logic only, never about Hermes or about hardware.
|
||||
*/
|
||||
export interface FakeRun {
|
||||
runId: string;
|
||||
key: string;
|
||||
body: string;
|
||||
sessionId: string;
|
||||
input: string;
|
||||
status: string;
|
||||
output: string;
|
||||
extra: Record<string, unknown>;
|
||||
stopRequested: boolean;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
}
|
||||
|
||||
export type Script =
|
||||
| { kind: 'complete'; afterMs?: number; output?: string }
|
||||
| { kind: 'fail'; afterMs?: number; error?: string }
|
||||
| { kind: 'incomplete'; afterMs?: number; output: string }
|
||||
| { kind: 'approval' }
|
||||
| { kind: 'hang' }
|
||||
| { kind: 'unknown'; afterMs?: number }
|
||||
| { kind: 'interrupted'; afterMs?: number };
|
||||
|
||||
export class FakeHermes {
|
||||
readonly apiKey = 'fake-hermes-key';
|
||||
/** How many turns actually "executed". The duplicate-execution counter. */
|
||||
executions = 0;
|
||||
readonly runs = new Map<string, FakeRun>();
|
||||
private readonly byKey = new Map<string, FakeRun>();
|
||||
/** session id -> inputs seen, to prove follow-ups land in the same session. */
|
||||
readonly sessions = new Map<string, string[]>();
|
||||
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string }> = [];
|
||||
private script: Script[] = [];
|
||||
private defaultScript: Script = { kind: 'complete' };
|
||||
/** Faults applied to upcoming POST /v1/runs calls, in order. */
|
||||
private submitFaults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'> = [];
|
||||
/** When true, every request is refused at the socket level. */
|
||||
private server: Server | null = null;
|
||||
private stopIgnored = false;
|
||||
private statusDown = false;
|
||||
private seq = 0;
|
||||
url = '';
|
||||
|
||||
async start(port = 0): Promise<void> {
|
||||
this.server = createServer((req, res) => void this.handle(req, res));
|
||||
await new Promise<void>((resolve) => this.server!.listen(port, '127.0.0.1', resolve));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||
}
|
||||
|
||||
get port(): number {
|
||||
return Number(new URL(this.url).port);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
for (const run of this.runs.values()) if (run.timer) clearTimeout(run.timer);
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (server) {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
next(...scripts: Script[]): void {
|
||||
this.script.push(...scripts);
|
||||
}
|
||||
setDefault(script: Script): void {
|
||||
this.defaultScript = script;
|
||||
}
|
||||
failNextSubmit(...faults: Array<'drop_response' | 'http_503' | 'http_500' | 'http_400'>): void {
|
||||
this.submitFaults.push(...faults);
|
||||
}
|
||||
ignoreStop(value = true): void {
|
||||
this.stopIgnored = value;
|
||||
}
|
||||
setStatusDown(value: boolean): void {
|
||||
this.statusDown = value;
|
||||
}
|
||||
/** Resolve a pending approval the way another, verified surface would. */
|
||||
approve(runId: string, output = 'approved and done'): void {
|
||||
const run = this.runs.get(runId)!;
|
||||
run.status = 'running';
|
||||
this.finishLater(run, { kind: 'complete', afterMs: 30, output });
|
||||
}
|
||||
/** Forget every run, as if status retention had expired. */
|
||||
forgetRuns(): void {
|
||||
this.runs.clear();
|
||||
}
|
||||
lastRun(): FakeRun | undefined {
|
||||
return [...this.runs.values()].at(-1);
|
||||
}
|
||||
|
||||
private json(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const url = new URL(req.url ?? '/', 'http://x');
|
||||
const path = url.pathname;
|
||||
const key = req.headers['idempotency-key'];
|
||||
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined });
|
||||
|
||||
if (path === '/health') return this.json(res, 200, { status: 'ok' });
|
||||
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
|
||||
return this.json(res, 401, { error: { message: 'Invalid API key', code: 'invalid_api_key' } });
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
|
||||
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw);
|
||||
|
||||
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
|
||||
if (match) {
|
||||
const run = this.runs.get(decodeURIComponent(match[1]!));
|
||||
if (req.method === 'GET' && !match[2]) {
|
||||
if (this.statusDown) return this.json(res, 503, { error: { message: 'storage_unavailable' } });
|
||||
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
|
||||
return this.json(res, 200, {
|
||||
object: 'hermes.run',
|
||||
run_id: run.runId,
|
||||
status: run.status,
|
||||
session_id: run.sessionId,
|
||||
...(run.output ? { output: run.output } : {}),
|
||||
...run.extra,
|
||||
});
|
||||
}
|
||||
if (req.method === 'POST' && match[2]) {
|
||||
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
|
||||
if (['completed', 'failed', 'cancelled', 'interrupted'].includes(run.status)) {
|
||||
return this.json(res, 200, { run_id: run.runId, status: run.status });
|
||||
}
|
||||
if (!this.stopIgnored) {
|
||||
run.stopRequested = true;
|
||||
run.status = 'stopping';
|
||||
if (run.timer) clearTimeout(run.timer);
|
||||
run.timer = setTimeout(() => {
|
||||
run.status = 'cancelled';
|
||||
run.extra = { completed: false, partial: false, interrupted: true };
|
||||
}, 25);
|
||||
}
|
||||
return this.json(res, 200, { run_id: run.runId, status: 'stopping' });
|
||||
}
|
||||
}
|
||||
this.json(res, 404, { error: { message: 'not found' } });
|
||||
}
|
||||
|
||||
private submit(req: IncomingMessage, res: ServerResponse, raw: string): void {
|
||||
const key = String(req.headers['idempotency-key'] ?? '');
|
||||
const fault = this.submitFaults.shift();
|
||||
if (fault === 'http_503') return this.json(res, 503, { error: { message: 'runtime_draining' } }, { 'Retry-After': '1' });
|
||||
if (fault === 'http_400') return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
|
||||
let body: { input?: string; session_id?: string; instructions?: string };
|
||||
try {
|
||||
body = JSON.parse(raw);
|
||||
} catch {
|
||||
return this.json(res, 400, { error: { message: 'Invalid JSON' } });
|
||||
}
|
||||
if (!body.input) return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
|
||||
const existing = key ? this.byKey.get(key) : undefined;
|
||||
let run: FakeRun;
|
||||
let replayed = false;
|
||||
if (existing) {
|
||||
if (existing.body !== raw) {
|
||||
return this.json(res, 409, {
|
||||
error: { message: 'Idempotency-Key was already used with a different request payload', code: 'idempotency_key_conflict' },
|
||||
});
|
||||
}
|
||||
run = existing;
|
||||
replayed = true;
|
||||
} else {
|
||||
const sessionId = body.session_id || `run-session-${this.seq}`;
|
||||
run = {
|
||||
runId: `run_${String(++this.seq).padStart(6, '0')}`,
|
||||
key,
|
||||
body: raw,
|
||||
sessionId,
|
||||
input: body.input,
|
||||
status: 'running',
|
||||
output: '',
|
||||
extra: {},
|
||||
stopRequested: false,
|
||||
timer: null,
|
||||
};
|
||||
this.runs.set(run.runId, run);
|
||||
if (key) this.byKey.set(key, run);
|
||||
// The turn "executes" exactly once, at admission.
|
||||
this.executions += 1;
|
||||
const history = this.sessions.get(sessionId) ?? [];
|
||||
this.sessions.set(sessionId, history);
|
||||
const script = this.script.shift() ?? this.defaultScript;
|
||||
const defaultOutput = `FAKE-ANSWER turn=${history.length + 1} previous=${JSON.stringify(history.at(-1) ?? null)} input=${JSON.stringify(body.input)}`;
|
||||
history.push(body.input);
|
||||
this.finishLater(run, script, defaultOutput);
|
||||
}
|
||||
|
||||
// Admitted, but the answer never reaches the caller.
|
||||
if (fault === 'drop_response') return void res.destroy();
|
||||
if (fault === 'http_500') return this.json(res, 500, { error: { message: 'boom' } });
|
||||
this.json(res, 202, { run_id: run.runId, status: replayed ? run.status : 'started', replayed }, replayed ? { 'Idempotency-Replayed': 'true' } : {});
|
||||
}
|
||||
|
||||
private finishLater(run: FakeRun, script: Script, defaultOutput = ''): void {
|
||||
const settle = (fn: () => void, afterMs = 30) => {
|
||||
run.timer = setTimeout(() => {
|
||||
if (!run.stopRequested) fn();
|
||||
}, afterMs);
|
||||
};
|
||||
switch (script.kind) {
|
||||
case 'complete':
|
||||
return settle(() => {
|
||||
run.status = 'completed';
|
||||
run.output = script.output ?? defaultOutput;
|
||||
run.extra = { completed: true, partial: false, interrupted: false };
|
||||
}, script.afterMs);
|
||||
case 'fail':
|
||||
return settle(() => {
|
||||
run.status = 'failed';
|
||||
run.extra = { completed: false, partial: false, interrupted: false, error: script.error ?? 'agent run failed' };
|
||||
}, script.afterMs);
|
||||
case 'incomplete':
|
||||
return settle(() => {
|
||||
run.status = 'failed';
|
||||
run.output = script.output;
|
||||
run.extra = { completed: false, partial: true, interrupted: false, turn_exit_reason: 'max_iterations' };
|
||||
}, script.afterMs);
|
||||
case 'approval':
|
||||
run.status = 'waiting_for_approval';
|
||||
return;
|
||||
case 'unknown':
|
||||
return settle(() => {
|
||||
run.status = 'unknown';
|
||||
}, script.afterMs);
|
||||
case 'interrupted':
|
||||
return settle(() => {
|
||||
run.status = 'interrupted';
|
||||
run.extra = { error: 'Gateway shutdown interrupted the run.' };
|
||||
}, script.afterMs);
|
||||
case 'hang':
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
/**
|
||||
* TEST FAKE. Not a speech recogniser.
|
||||
*
|
||||
* Accepts the OpenAI-style `POST /audio/transcriptions` multipart upload,
|
||||
* checks that what arrived really is a 16 kHz mono 16-bit WAV, and returns a
|
||||
* scripted transcript. It proves the bridge's upload format and failure
|
||||
* handling, and nothing about real transcription quality or latency.
|
||||
*/
|
||||
export class FakeStt {
|
||||
readonly apiKey = 'fake-stt-key';
|
||||
calls = 0;
|
||||
lastWav: { sampleRate: number; channels: number; bitsPerSample: number; dataBytes: number } | null = null;
|
||||
lastFields: Record<string, string> = {};
|
||||
private replies: Array<{ text?: string; status?: number; delayMs?: number }> = [];
|
||||
private server: Server | null = null;
|
||||
url = '';
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.server = createServer(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const body = Buffer.concat(chunks);
|
||||
if (req.method !== 'POST' || !req.url?.endsWith('/audio/transcriptions')) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
|
||||
res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"error":"unauthorized"}');
|
||||
return;
|
||||
}
|
||||
this.calls += 1;
|
||||
const riff = body.indexOf('RIFF');
|
||||
if (riff >= 0 && body.toString('ascii', riff + 8, riff + 12) === 'WAVE') {
|
||||
this.lastWav = {
|
||||
channels: body.readUInt16LE(riff + 22),
|
||||
sampleRate: body.readUInt32LE(riff + 24),
|
||||
bitsPerSample: body.readUInt16LE(riff + 34),
|
||||
dataBytes: body.readUInt32LE(riff + 40),
|
||||
};
|
||||
} else {
|
||||
this.lastWav = null;
|
||||
}
|
||||
const text = body.toString('latin1');
|
||||
this.lastFields = {};
|
||||
for (const m of text.matchAll(/name="(model|language|response_format)"\r\n\r\n([^\r]*)\r\n/g)) {
|
||||
this.lastFields[m[1]!] = m[2]!;
|
||||
}
|
||||
const reply = this.replies.shift() ?? { text: 'what is the capital of france' };
|
||||
if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs));
|
||||
if (res.destroyed) return;
|
||||
if (reply.status && reply.status !== 200) {
|
||||
res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end('{"error":"scripted failure"}');
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ text: reply.text ?? '' }));
|
||||
});
|
||||
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||
}
|
||||
|
||||
next(...replies: Array<{ text?: string; status?: number; delayMs?: number }>): void {
|
||||
this.replies.push(...replies);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (server) {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Deterministic synthetic PCM (a sine tone). Stands in for speech in tests; it is not speech. */
|
||||
export function syntheticPcm(seconds: number, sampleRate = 16000): Buffer {
|
||||
const samples = Math.floor(seconds * sampleRate);
|
||||
const buf = Buffer.alloc(samples * 2);
|
||||
for (let i = 0; i < samples; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 8000), i * 2);
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
/**
|
||||
* TEST STUB. Not a language model.
|
||||
*
|
||||
* A minimal OpenAI-compatible chat endpoint so a REAL Hermes gateway can run
|
||||
* whole agent turns without any provider account or cost. Its "answer" is a
|
||||
* deterministic description of the conversation it was handed, which is how
|
||||
* the real-Hermes test proves that Hermes itself carried the earlier turns.
|
||||
*/
|
||||
export class StubLlm {
|
||||
/** Agent turns served. */
|
||||
calls = 0;
|
||||
auxiliaryCalls = 0;
|
||||
delayMs = 0;
|
||||
/** User messages seen in the most recent request, oldest first. */
|
||||
lastUserMessages: string[] = [];
|
||||
lastSystem = '';
|
||||
private server: Server | null = null;
|
||||
url = '';
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.server = createServer(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const path = (req.url ?? '').split('?')[0]!;
|
||||
if (req.method === 'GET' && path.endsWith('/models')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ object: 'list', data: [{ id: 'stub-model', object: 'model', owned_by: 'hermeven-test' }] }));
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'POST' || !path.endsWith('/chat/completions')) {
|
||||
res.writeHead(404, { 'Content-Type': 'application/json' }).end('{"error":{"message":"not found"}}');
|
||||
return;
|
||||
}
|
||||
let body: { messages?: Array<{ role: string; content: unknown }>; stream?: boolean; model?: string };
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
} catch {
|
||||
res.writeHead(400).end('{}');
|
||||
return;
|
||||
}
|
||||
const text = (c: unknown): string =>
|
||||
typeof c === 'string' ? c : Array.isArray(c) ? c.map((p) => (p && typeof p === 'object' && 'text' in p ? String((p as { text: unknown }).text) : '')).join('') : '';
|
||||
const messages = body.messages ?? [];
|
||||
const users = messages.filter((m) => m.role === 'user').map((m) => text(m.content));
|
||||
// Hermes also calls the model for housekeeping (naming the chat, compressing history).
|
||||
// Those are not agent turns and must not be counted as executions.
|
||||
const system = text(messages.find((m) => m.role === 'system')?.content).slice(0, 600);
|
||||
const isTurn = users.length > 0 && !/you name chat sessions|generate a (short )?title|summari[sz]e/i.test(system);
|
||||
if (!isTurn) this.auxiliaryCalls += 1;
|
||||
if (isTurn) {
|
||||
this.calls += 1;
|
||||
this.lastUserMessages = users;
|
||||
this.lastSystem = messages.filter((m) => m.role === 'system').map((m) => text(m.content)).join('\n');
|
||||
}
|
||||
const answer = `STUB-ANSWER users=${users.length} first=${JSON.stringify(users[0] ?? null)} last=${JSON.stringify(users.at(-1) ?? null)}`;
|
||||
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
|
||||
if (res.destroyed) return;
|
||||
const id = `chatcmpl-stub-${this.calls}`;
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
const usage = { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 };
|
||||
if (body.stream) {
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
|
||||
const chunk = (delta: object, finish: string | null, extra: object = {}) =>
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model: body.model ?? 'stub-model', choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
|
||||
chunk({ role: 'assistant', content: '' }, null);
|
||||
chunk({ content: answer }, null);
|
||||
chunk({}, 'stop', { usage });
|
||||
res.end('data: [DONE]\n\n');
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
id,
|
||||
object: 'chat.completion',
|
||||
created,
|
||||
model: body.model ?? 'stub-model',
|
||||
choices: [{ index: 0, message: { role: 'assistant', content: answer }, finish_reason: 'stop' }],
|
||||
usage,
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => this.server!.listen(0, '127.0.0.1', resolve));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
const server = this.server;
|
||||
this.server = null;
|
||||
if (server) {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { check, DeviceStatusResponse, SCHEMA_VERSION, TurnResult } from '@hermeven/contracts';
|
||||
import { syntheticPcm } from '../fakes/fakeStt.ts';
|
||||
import { createHarness, type Harness } from './harness.ts';
|
||||
|
||||
/**
|
||||
* Bridge behaviour over real HTTP, with the real Hermes Runs adapter and the real
|
||||
* STT adapter talking to TEST FAKES. Evidence about Hermeven's own logic only.
|
||||
*/
|
||||
let h: Harness;
|
||||
afterEach(async () => {
|
||||
await h?.close();
|
||||
});
|
||||
|
||||
describe('health, auth and binding', () => {
|
||||
beforeEach(async () => {
|
||||
h = await createHarness();
|
||||
});
|
||||
|
||||
it('healthz is minimal and unauthenticated', async () => {
|
||||
const res = await h.api('GET', '/healthz');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ status: 'ok', schema_version: SCHEMA_VERSION });
|
||||
});
|
||||
|
||||
it('rejects missing, malformed and unknown credentials', async () => {
|
||||
expect((await h.api('GET', '/v1/device')).status).toBe(401);
|
||||
expect((await h.api('GET', '/v1/device', { token: 'hvn_nope' })).status).toBe(401);
|
||||
expect((await h.api('GET', '/v1/device', { headers: { Authorization: 'Basic abc' } })).status).toBe(401);
|
||||
const turn = await h.textTurn('hvn_nope', randomUUID(), 'hi');
|
||||
expect(turn.status).toBe(401);
|
||||
expect(turn.body.error.code).toBe('unauthorized');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('device status matches the contract and exposes no secrets', async () => {
|
||||
const cred = await h.pair();
|
||||
const res = await h.api('GET', '/v1/device', { token: cred.token });
|
||||
expect(res.status).toBe(200);
|
||||
expect(check(DeviceStatusResponse, res.body)).toBe(true);
|
||||
expect(res.body.agent_reachable).toBe(true);
|
||||
expect(res.body.stt_configured).toBe(true);
|
||||
const text = JSON.stringify(res.body);
|
||||
expect(text).not.toContain(h.hermes.apiKey);
|
||||
expect(text).not.toContain(h.stt.apiKey);
|
||||
expect(text).not.toContain(h.hermes.url);
|
||||
});
|
||||
|
||||
it('a device cannot use, read or cancel another device’s conversation or turn', async () => {
|
||||
const a = await h.pair('a');
|
||||
const b = await h.pair('b');
|
||||
const convA = await h.conversation(a.token);
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
const turnA = await h.textTurn(a.token, convA, 'private question');
|
||||
expect(turnA.status).toBe(202);
|
||||
const id = turnA.body.request_id;
|
||||
|
||||
expect((await h.textTurn(b.token, convA, 'intrude')).body.error.code).toBe('not_found');
|
||||
expect((await h.api('GET', `/v1/turns/${id}`, { token: b.token })).status).toBe(404);
|
||||
expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: b.token, json: {} })).status).toBe(404);
|
||||
// Reusing A's request id from B is a conflict and never reveals A's turn.
|
||||
const reuse = await h.textTurn(b.token, await h.conversation(b.token), 'private question', id);
|
||||
expect(reuse.status).toBe(409);
|
||||
expect(reuse.body.error.code).toBe('request_id_conflict');
|
||||
expect(JSON.stringify(reuse.body)).not.toContain('private');
|
||||
await h.api('POST', `/v1/turns/${id}/cancel`, { token: a.token, json: {} });
|
||||
await h.waitTerminal(a.token, id);
|
||||
});
|
||||
|
||||
it('never forwards a client-chosen Hermes session: unknown fields are rejected', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const res = await h.api('POST', '/v1/turns', {
|
||||
token: cred.token,
|
||||
json: {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: randomUUID(),
|
||||
conversation_id: conv,
|
||||
locale: 'en-US',
|
||||
input: { kind: 'text', text: 'hi' },
|
||||
session_id: 'someone-elses-session',
|
||||
},
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('revocation takes effect immediately and closes the conversation', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
expect((await h.api('DELETE', '/v1/device', { token: cred.token })).body).toEqual({ schema_version: 1, revoked: true });
|
||||
expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401);
|
||||
expect((await h.textTurn(cred.token, conv, 'hi')).status).toBe(401);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('renewal rotates the token; the old one stops working', async () => {
|
||||
const cred = await h.pair();
|
||||
const renewed = await h.api('POST', '/v1/device/renew', { token: cred.token, json: {} });
|
||||
expect(renewed.status).toBe(200);
|
||||
expect(renewed.body.token).not.toBe(cred.token);
|
||||
expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401);
|
||||
expect((await h.api('GET', '/v1/device', { token: renewed.body.token })).status).toBe(200);
|
||||
});
|
||||
|
||||
it('CORS allows only the configured origin and is not a substitute for auth', async () => {
|
||||
const ok = await h.api('OPTIONS', '/v1/turns', {
|
||||
headers: { Origin: 'https://app.example', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'authorization,content-type' },
|
||||
});
|
||||
expect(ok.headers.get('access-control-allow-origin')).toBe('https://app.example');
|
||||
const bad = await h.api('OPTIONS', '/v1/turns', {
|
||||
headers: { Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST' },
|
||||
});
|
||||
expect(bad.headers.get('access-control-allow-origin')).toBeNull();
|
||||
const authed = await h.api('GET', '/v1/device', { headers: { Origin: 'https://app.example' } });
|
||||
expect(authed.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pairing', () => {
|
||||
it('codes are single-use', async () => {
|
||||
h = await createHarness();
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
const claim = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code, device_name: 'x' } });
|
||||
expect((await claim()).status).toBe(201);
|
||||
const second = await claim();
|
||||
expect(second.status).toBe(401);
|
||||
expect(second.body.error.code).toBe('pairing_invalid');
|
||||
});
|
||||
|
||||
it('wrong guesses burn the outstanding code', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '50', HERMEVEN_PAIRING_CODE_MAX_FAILURES: '3' } });
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } });
|
||||
expect((await guess('AAAAA-AAAAA')).body.error.code).toBe('pairing_invalid');
|
||||
expect((await guess('AAAAA-AAAAB')).body.error.code).toBe('pairing_invalid');
|
||||
expect((await guess('AAAAA-AAAAC')).body.error.code).toBe('pairing_locked');
|
||||
// The real code no longer works.
|
||||
expect((await guess(code)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('claim attempts are rate limited per client', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '2' } });
|
||||
const guess = () => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: 'AAAAA-AAAAA', device_name: 'x' } });
|
||||
await guess();
|
||||
await guess();
|
||||
const third = await guess();
|
||||
expect(third.status).toBe(429);
|
||||
expect(third.body.error.code).toBe('rate_limited');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validation and limits', () => {
|
||||
beforeEach(async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', HERMEVEN_TURNS_PER_MINUTE: '3' } });
|
||||
});
|
||||
|
||||
it('rejects unknown schema versions', async () => {
|
||||
const cred = await h.pair();
|
||||
const res = await h.api('POST', '/v1/turns', {
|
||||
token: cred.token,
|
||||
json: { schema_version: 2, request_id: randomUUID(), conversation_id: randomUUID(), locale: 'en-US', input: { kind: 'text', text: 'hi' } },
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('unsupported_schema_version');
|
||||
});
|
||||
|
||||
it('rejects oversized audio, odd byte counts, wrong formats and wrong content types', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
// Cap is 2 s (+1 s headroom) = 96,000 bytes.
|
||||
const big = await h.audioTurn(cred.token, conv, syntheticPcm(4));
|
||||
expect(big.status).toBe(413);
|
||||
expect(big.body.error.code).toBe('payload_too_large');
|
||||
|
||||
const odd = await h.audioTurn(cred.token, conv, Buffer.alloc(1001));
|
||||
expect(odd.status).toBe(400);
|
||||
|
||||
const rate = await h.audioTurn(cred.token, conv, syntheticPcm(0.5), randomUUID(), { sample_rate: '44100' });
|
||||
expect(rate.status).toBe(415);
|
||||
expect(rate.body.error.code).toBe('unsupported_media');
|
||||
|
||||
const type = await h.api('POST', '/v1/turns', { token: cred.token, body: Buffer.from('x'), headers: { 'Content-Type': 'text/plain' } });
|
||||
expect(type.status).toBe(415);
|
||||
|
||||
const bigJson = await h.textTurn(cred.token, conv, 'x'.repeat(5000));
|
||||
expect(bigJson.status).toBe(400);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
expect(h.stt.calls).toBe(0);
|
||||
});
|
||||
|
||||
it('rate limits new turns per device but never a duplicate of an existing one', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const ids: string[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const res = await h.textTurn(cred.token, conv, `q${i}`);
|
||||
expect(res.status).toBe(202);
|
||||
ids.push(res.body.request_id);
|
||||
await h.waitTerminal(cred.token, res.body.request_id);
|
||||
}
|
||||
const over = await h.textTurn(cred.token, conv, 'q4');
|
||||
expect(over.status).toBe(429);
|
||||
const dup = await h.textTurn(cred.token, conv, 'q0', ids[0]);
|
||||
expect(dup.status).toBe(200);
|
||||
expect(dup.body.replayed).toBe(true);
|
||||
expect(h.hermes.executions).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('turn lifecycle', () => {
|
||||
beforeEach(async () => {
|
||||
h = await createHarness();
|
||||
});
|
||||
|
||||
it('typed text -> agent -> complete answer, result matches the contract', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const long = 'Paris. '.repeat(900); // ~6 kB: must come back untruncated
|
||||
h.hermes.next({ kind: 'complete', output: long });
|
||||
const res = await h.textTurn(cred.token, conv, 'What is the capital of France?');
|
||||
expect(res.status).toBe(202);
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(check(TurnResult, done)).toBe(true);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe(long);
|
||||
expect(done.error).toBeNull();
|
||||
expect(done.timings.agent_ms).toBeGreaterThanOrEqual(0);
|
||||
// Hermes received our own opaque session id and the forwarded idempotency key.
|
||||
const run = h.hermes.lastRun()!;
|
||||
expect(run.sessionId).toMatch(/^hermeven-[0-9a-f-]{36}$/);
|
||||
expect(run.key).toBe(`hermeven-turn-${res.body.request_id}`);
|
||||
});
|
||||
|
||||
it('audio -> STT -> agent: uploads a valid 16 kHz mono WAV and sends the transcript', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.stt.next({ text: 'how tall is mount everest' });
|
||||
const res = await h.audioTurn(cred.token, conv, syntheticPcm(1.5));
|
||||
expect(res.status).toBe(202);
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.input_text).toBe('how tall is mount everest');
|
||||
expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 48000 });
|
||||
expect(h.stt.lastFields).toMatchObject({ model: 'fake-whisper', language: 'en' });
|
||||
expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest');
|
||||
expect(done.timings.transcribe_ms).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('a follow-up lands in the same Hermes session; a new conversation gets a fresh one', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const first = await h.textTurn(cred.token, conv, 'My name is Ada.');
|
||||
await h.waitTerminal(cred.token, first.body.request_id);
|
||||
const second = await h.textTurn(cred.token, conv, 'What is my name?');
|
||||
const answer = await h.waitTerminal(cred.token, second.body.request_id);
|
||||
// The fake echoes the previous input of the same session.
|
||||
expect(answer.answer_text).toContain('turn=2');
|
||||
expect(answer.answer_text).toContain('previous="My name is Ada."');
|
||||
|
||||
const conv2 = await h.conversation(cred.token);
|
||||
expect(conv2).not.toBe(conv);
|
||||
const third = await h.textTurn(cred.token, conv2, 'What is my name?');
|
||||
const fresh = await h.waitTerminal(cred.token, third.body.request_id);
|
||||
expect(fresh.answer_text).toContain('turn=1');
|
||||
expect(fresh.answer_text).toContain('previous=null');
|
||||
// The old conversation is closed, not silently reused.
|
||||
const stale = await h.textTurn(cred.token, conv, 'still there?');
|
||||
expect(stale.status).toBe(409);
|
||||
expect(stale.body.error.code).toBe('conversation_closed');
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
});
|
||||
|
||||
it('turns in one conversation are serialised', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 200 });
|
||||
const first = await h.textTurn(cred.token, conv, 'one');
|
||||
const second = await h.textTurn(cred.token, conv, 'two');
|
||||
expect(second.status).toBe(409);
|
||||
expect(second.body.error.code).toBe('conversation_busy');
|
||||
await h.waitTerminal(cred.token, first.body.request_id);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('distinguishes failed, incomplete, interrupted and unknown agent outcomes', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const run = async (text: string) => {
|
||||
const res = await h.textTurn(cred.token, conv, text);
|
||||
return h.waitTerminal(cred.token, res.body.request_id);
|
||||
};
|
||||
|
||||
h.hermes.next({ kind: 'fail', error: 'provider said sk-secret-123' });
|
||||
const failed = await run('a');
|
||||
expect(failed.outcome).toBe('failed');
|
||||
expect(failed.error).toMatchObject({ code: 'agent_failed', retryable: false });
|
||||
// Hermes' diagnostic text is never relayed to the client.
|
||||
expect(JSON.stringify(failed)).not.toContain('sk-secret-123');
|
||||
|
||||
h.hermes.next({ kind: 'incomplete', output: 'So far I found two of three.' });
|
||||
const incomplete = await run('b');
|
||||
expect(incomplete.outcome).toBe('incomplete');
|
||||
expect(incomplete.answer_text).toBe('So far I found two of three.');
|
||||
expect(incomplete.error?.code).toBe('agent_incomplete');
|
||||
|
||||
h.hermes.next({ kind: 'interrupted' });
|
||||
const interrupted = await run('c');
|
||||
expect(interrupted.outcome).toBe('failed');
|
||||
expect(interrupted.error?.code).toBe('agent_interrupted');
|
||||
|
||||
h.hermes.next({ kind: 'unknown' });
|
||||
const unknown = await run('d');
|
||||
expect(unknown.outcome).toBe('unknown');
|
||||
expect(unknown.error).toMatchObject({ code: 'outcome_unknown', retryable: false });
|
||||
});
|
||||
|
||||
it('approval-required is surfaced, never auto-approved, and resolves when approved elsewhere', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'approval' });
|
||||
const res = await h.textTurn(cred.token, conv, 'delete the file');
|
||||
const waiting = await h.waitState(cred.token, res.body.request_id, 'approval_required');
|
||||
expect(waiting.terminal).toBe(false);
|
||||
expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false);
|
||||
h.hermes.approve(h.hermes.lastRun()!.runId, 'file deleted');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe('file deleted');
|
||||
});
|
||||
|
||||
it('an approval that never arrives ends as stopped, with a distinct code', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'approval' });
|
||||
const res = await h.textTurn(cred.token, conv, 'delete the file');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('cancelled');
|
||||
expect(done.error?.code).toBe('approval_timeout');
|
||||
expect(h.hermes.requests.some((r) => r.path.endsWith('/approval'))).toBe(false);
|
||||
});
|
||||
|
||||
it('agent deadline: stop is requested and confirmed; unconfirmed stop is unknown, not replayed', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
const a = await h.textTurn(cred.token, conv, 'slow');
|
||||
const timedOut = await h.waitTerminal(cred.token, a.body.request_id);
|
||||
expect(timedOut.outcome).toBe('cancelled');
|
||||
expect(timedOut.error?.code).toBe('agent_timeout');
|
||||
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
h.hermes.ignoreStop();
|
||||
const b = await h.textTurn(cred.token, conv, 'slow and stubborn');
|
||||
const unknown = await h.waitTerminal(cred.token, b.body.request_id);
|
||||
expect(unknown.outcome).toBe('unknown');
|
||||
expect(unknown.error?.code).toBe('outcome_unknown');
|
||||
expect(h.hermes.executions).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('STT failures', () => {
|
||||
beforeEach(async () => {
|
||||
h = await createHarness();
|
||||
});
|
||||
|
||||
it('provider error, empty transcript and timeout each fail cleanly without reaching the agent', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const run = async () => {
|
||||
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
|
||||
return h.waitTerminal(cred.token, res.body.request_id);
|
||||
};
|
||||
h.stt.next({ status: 500 });
|
||||
expect((await run()).error).toMatchObject({ code: 'stt_unavailable', retryable: true });
|
||||
h.stt.next({ status: 400 });
|
||||
expect((await run()).error?.code).toBe('stt_failed');
|
||||
h.stt.next({ text: ' ' });
|
||||
expect((await run()).error?.code).toBe('stt_empty');
|
||||
h.stt.next({ delayMs: 1500, text: 'too late' });
|
||||
expect((await run()).error?.code).toBe('stt_timeout');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('with no STT configured, audio fails cleanly and typed text still works', async () => {
|
||||
await h.close();
|
||||
h = await createHarness({ stt: false });
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
|
||||
expect((await h.waitTerminal(cred.token, audio.body.request_id)).error?.code).toBe('stt_unavailable');
|
||||
const text = await h.textTurn(cred.token, conv, 'hello');
|
||||
expect((await h.waitTerminal(cred.token, text.body.request_id)).outcome).toBe('succeeded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('duplicates, retries, cancellation and recovery', () => {
|
||||
beforeEach(async () => {
|
||||
h = await createHarness();
|
||||
});
|
||||
|
||||
it('duplicate submits of one request id execute once', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const id = randomUUID();
|
||||
const results = await Promise.all(Array.from({ length: 8 }, () => h.textTurn(cred.token, conv, 'run the tool', id)));
|
||||
expect(results.filter((r) => r.status === 202)).toHaveLength(1);
|
||||
expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(7);
|
||||
await h.waitTerminal(cred.token, id);
|
||||
const late = await h.textTurn(cred.token, conv, 'run the tool', id);
|
||||
expect(late.status).toBe(200);
|
||||
expect(late.body.outcome).toBe('succeeded');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
// Same id, different payload: refused.
|
||||
const conflict = await h.textTurn(cred.token, conv, 'run a different tool', id);
|
||||
expect(conflict.status).toBe(409);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('a lost Hermes response is retried under the same idempotency key: one execution', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.failNextSubmit('drop_response', 'http_500');
|
||||
const res = await h.textTurn(cred.token, conv, 'charge the card');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
expect(posts).toHaveLength(3);
|
||||
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
|
||||
});
|
||||
|
||||
it('if no answer to the submit ever arrives, the deadline ends as unknown, never as "safe to retry"', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.failNextSubmit(...Array(500).fill('drop_response'));
|
||||
const res = await h.textTurn(cred.token, conv, 'send the email');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('unknown');
|
||||
expect(done.error).toMatchObject({ code: 'outcome_unknown', retryable: false });
|
||||
// Hermes did run it (once); the bridge could not know, and said so.
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
const posts = h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
expect(posts.length).toBeGreaterThan(1);
|
||||
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
|
||||
});
|
||||
|
||||
it('busy Hermes (503) is retried; a 4xx rejection is final and nothing ran', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.failNextSubmit('http_503', 'http_503');
|
||||
const ok = await h.textTurn(cred.token, conv, 'hello');
|
||||
expect((await h.waitTerminal(cred.token, ok.body.request_id)).outcome).toBe('succeeded');
|
||||
h.hermes.failNextSubmit('http_400');
|
||||
const bad = await h.textTurn(cred.token, conv, 'hello again');
|
||||
const rejected = await h.waitTerminal(cred.token, bad.body.request_id);
|
||||
expect(rejected.error?.code).toBe('agent_rejected');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('Hermes down before anything was sent: fails as retryable, provably nothing ran', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
await h.hermes.stop();
|
||||
const res = await h.textTurn(cred.token, conv, 'anyone there');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('failed');
|
||||
expect(done.error).toMatchObject({ code: 'agent_unreachable', retryable: true });
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('cancel during transcription is clean and never reaches the agent', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.stt.next({ delayMs: 300, text: 'never used' });
|
||||
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
|
||||
await h.waitState(cred.token, res.body.request_id, 'transcribing');
|
||||
const cancel = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
|
||||
expect(cancel.status).toBe(200);
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('cancelled');
|
||||
expect(done.error).toBeNull();
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('cancel while the agent runs asks Hermes to stop; repeated cancels are idempotent', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
const res = await h.textTurn(cred.token, conv, 'long job');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
const cancels = await Promise.all(
|
||||
Array.from({ length: 5 }, () => h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} })),
|
||||
);
|
||||
expect(cancels.every((c) => c.status === 200 && c.body.cancel_requested)).toBe(true);
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('cancelled');
|
||||
expect(done.cancel_requested).toBe(true);
|
||||
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1);
|
||||
// Cancelling a finished turn changes nothing.
|
||||
const after = await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
|
||||
expect(after.body.outcome).toBe('cancelled');
|
||||
// The conversation is usable again.
|
||||
const next = await h.textTurn(cred.token, conv, 'next');
|
||||
expect((await h.waitTerminal(cred.token, next.body.request_id)).outcome).toBe('succeeded');
|
||||
});
|
||||
|
||||
it('a cancel that loses the race reports what really happened', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 60, output: 'already done' });
|
||||
h.hermes.ignoreStop();
|
||||
const res = await h.textTurn(cred.token, conv, 'quick job');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.cancel_requested).toBe(true);
|
||||
expect(done.answer_text).toBe('already done');
|
||||
});
|
||||
|
||||
it('bridge restart mid-run re-attaches to the same run: one execution, answer delivered', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'survived the restart' });
|
||||
const res = await h.textTurn(cred.token, conv, 'long job');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe('survived the restart');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('bridge crash between sending and recording the run id replays the same key, not a new run', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'only once' });
|
||||
// Hermes admits the run but the bridge never learns the run id, then the bridge dies.
|
||||
h.hermes.failNextSubmit('drop_response', 'drop_response', 'drop_response', 'drop_response');
|
||||
const res = await h.textTurn(cred.token, conv, 'transfer money');
|
||||
await new Promise((r) => setTimeout(r, 80));
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
await h.restartBridge();
|
||||
h.hermes.failNextSubmit(); // no more faults
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe('only once');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('bridge restart during transcription fails the turn as provably-not-run', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.stt.next({ delayMs: 350, text: 'lost' });
|
||||
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
|
||||
await h.waitState(cred.token, res.body.request_id, 'transcribing');
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('failed');
|
||||
expect(done.error).toMatchObject({ code: 'interrupted_before_agent', retryable: true });
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('if Hermes no longer knows the run, the outcome is unknown and nothing is resent', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
const res = await h.textTurn(cred.token, conv, 'job');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
h.hermes.forgetRuns();
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('unknown');
|
||||
expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('status outage during a run is ridden out without resubmitting', async () => {
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250, output: 'fine' });
|
||||
const res = await h.textTurn(cred.token, conv, 'job');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
h.hermes.setStatusDown(true);
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
h.hermes.setStatusDown(false);
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('logging and retention', () => {
|
||||
it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => {
|
||||
h = await createHarness();
|
||||
const cred = await h.pair('pocket-g2');
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.stt.next({ text: 'SECRET-TRANSCRIPT-zebra' });
|
||||
h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-giraffe' });
|
||||
const audio = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
|
||||
await h.waitTerminal(cred.token, audio.body.request_id);
|
||||
h.hermes.next({ kind: 'fail', error: 'SECRET-DIAGNOSTIC-okapi' });
|
||||
const text = await h.textTurn(cred.token, conv, 'SECRET-QUESTION-lemur');
|
||||
await h.waitTerminal(cred.token, text.body.request_id);
|
||||
await h.api('GET', '/v1/device', { token: 'hvn_SECRET-BAD-TOKEN' });
|
||||
|
||||
const all = h.logs.join('');
|
||||
expect(all).toContain(audio.body.request_id);
|
||||
expect(all).toContain('turn.done');
|
||||
expect(all).toContain('transcribe_ms');
|
||||
for (const secret of ['zebra', 'giraffe', 'okapi', 'lemur', 'SECRET-BAD-TOKEN', cred.token, h.hermes.apiKey, h.stt.apiKey]) {
|
||||
expect(all).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it('cached question and answer text is dropped after the retention window', async () => {
|
||||
h = await createHarness({ env: { HERMEVEN_RESULT_RETENTION_SECONDS: '10' } });
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
const res = await h.textTurn(cred.token, conv, 'remember me?');
|
||||
const done = await h.waitTerminal(cred.token, res.body.request_id);
|
||||
expect(done.answer_text).toBeTruthy();
|
||||
// Age the row past retention, then run the same purge the bridge runs every minute.
|
||||
h.bridge.db.prepare('UPDATE turns SET completed_at = completed_at - 11000').run();
|
||||
expect(h.bridge.engine.purgeExpired()).toBe(1);
|
||||
const after = await h.api('GET', `/v1/turns/${res.body.request_id}`, { token: cred.token });
|
||||
expect(after.body.outcome).toBe('succeeded');
|
||||
expect(after.body.answer_text).toBeNull();
|
||||
expect(after.body.input_text).toBeNull();
|
||||
const row = h.bridge.db.prepare('SELECT pending_body, input_text, answer_text FROM turns').get();
|
||||
expect(row).toEqual({ pending_body: null, input_text: null, answer_text: null });
|
||||
});
|
||||
|
||||
it('the exact Hermes body is held only until the run id is recorded', async () => {
|
||||
h = await createHarness();
|
||||
const cred = await h.pair();
|
||||
const conv = await h.conversation(cred.token);
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
const res = await h.textTurn(cred.token, conv, 'hold on');
|
||||
await h.waitState(cred.token, res.body.request_id, 'thinking');
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
const row = h.bridge.db.prepare('SELECT pending_body, hermes_run_id FROM turns').get() as any;
|
||||
expect(row.hermes_run_id).toBeTruthy();
|
||||
expect(row.pending_body).toBeNull();
|
||||
await h.api('POST', `/v1/turns/${res.body.request_id}/cancel`, { token: cred.token, json: {} });
|
||||
await h.waitTerminal(cred.token, res.body.request_id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
|
||||
import { MENU_ITEM } from '../../apps/even-client/src/device/events.ts';
|
||||
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
|
||||
import { FakeDevice } from '../fakes/fakeDevice.ts';
|
||||
import { createHarness, type Harness } from './harness.ts';
|
||||
|
||||
/**
|
||||
* The whole software path in one process: the client's controller, reducer,
|
||||
* pagination and HTTP client -> the real bridge over HTTP -> TEST FAKES for
|
||||
* the glasses, the speech recogniser and Hermes. No hardware, no simulator,
|
||||
* no real model. See docs/device-test-plan.md for what this does not cover.
|
||||
*/
|
||||
let h: Harness;
|
||||
let device: FakeDevice;
|
||||
let controller: Controller;
|
||||
let snapshot: Snapshot;
|
||||
let network: { down: boolean };
|
||||
|
||||
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase} hud=${JSON.stringify(device.frame)}`);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
const phase = () => snapshot.state.phase;
|
||||
|
||||
function makeController(dev: FakeDevice): Controller {
|
||||
return new Controller({
|
||||
device: dev,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: 'en-US',
|
||||
pollIntervalMs: 20,
|
||||
submitAttempts: 3,
|
||||
submitRetryMs: 30,
|
||||
micStallMs: 300,
|
||||
makeClient: (baseUrl, token) =>
|
||||
new BridgeClient({
|
||||
baseUrl,
|
||||
token,
|
||||
timeoutMs: 500,
|
||||
fetchImpl: (input, init) => (network.down ? Promise.reject(new TypeError('offline')) : fetch(input, init)),
|
||||
}),
|
||||
onChange: (s) => {
|
||||
snapshot = s;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function pairedController(): Promise<void> {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
expect(phase()).toBe('unpaired');
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
await controller.pair(h.url, code, 'fake-g2');
|
||||
expect(phase()).toBe('ready');
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
network = { down: false };
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
await h?.close();
|
||||
});
|
||||
|
||||
describe('voice question, answer and follow-up', () => {
|
||||
it('tap -> record -> tap -> transcribe -> think -> paged answer -> follow-up with context', async () => {
|
||||
await pairedController();
|
||||
expect(device.frame.status).toContain('Tap: ask');
|
||||
expect(device.micOpens).toBe(0);
|
||||
|
||||
const answer = Array.from({ length: 60 }, (_, i) => `Sentence number ${i + 1} of a long answer about Mount Everest.`).join(' ');
|
||||
h.stt.next({ text: 'how tall is mount everest' });
|
||||
h.hermes.next({ kind: 'complete', output: `**Mount Everest** is 8,849 m tall.\n\n${answer}` });
|
||||
|
||||
device.tap();
|
||||
await until('listening with mic open', () => phase() === 'listening' && device.micOpen);
|
||||
await until('REC indicator', () => device.frame.status.includes('● REC'));
|
||||
device.speak(1.2);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
|
||||
expect(device.micOpen).toBe(false);
|
||||
expect(device.micCloses).toBe(1);
|
||||
// 1.2 s of 16 kHz 16-bit mono reached the recogniser as a WAV.
|
||||
expect(h.stt.lastWav).toEqual({ sampleRate: 16000, channels: 1, bitsPerSample: 16, dataBytes: 38400 });
|
||||
expect(h.hermes.lastRun()!.input).toBe('how tall is mount everest');
|
||||
|
||||
// Paged, plain text, complete.
|
||||
const pages = snapshot.state.pages;
|
||||
expect(pages.length).toBeGreaterThan(2);
|
||||
expect(pages[0]).toMatch(/^Mount Everest is 8,849 m tall\./);
|
||||
expect(pages.join(' ')).toContain('Sentence number 60 of a long answer');
|
||||
expect(device.frame.body).toBe(pages[0]);
|
||||
expect(device.frame.status).toContain(`1/${pages.length}`);
|
||||
device.swipeDown();
|
||||
expect(device.frame.body).toBe(pages[1]);
|
||||
device.swipeUp();
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe(pages[0]);
|
||||
for (let i = 0; i < pages.length + 3; i++) device.swipeDown();
|
||||
expect(device.frame.body).toBe(pages.at(-1));
|
||||
// The phone keeps the complete original, Markdown and all.
|
||||
expect(snapshot.lastTurn!.answer_text).toContain('**Mount Everest**');
|
||||
|
||||
// Follow-up in the same conversation.
|
||||
h.stt.next({ text: 'and in feet' });
|
||||
device.tap();
|
||||
await until('listening again', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.6);
|
||||
device.tap();
|
||||
await until('second answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('previous="how tall is mount everest"');
|
||||
expect(h.hermes.sessions.size).toBe(1);
|
||||
expect(h.hermes.executions).toBe(2);
|
||||
});
|
||||
|
||||
it('recording stops by itself at the cap and submits what was captured', async () => {
|
||||
await pairedController();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(5); // cap is 2 s
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.micOpen).toBe(false);
|
||||
expect(h.stt.lastWav!.dataBytes).toBe(2 * 32000);
|
||||
});
|
||||
|
||||
it('explicit new conversation from the glasses menu starts a fresh agent session', async () => {
|
||||
await pairedController();
|
||||
controller.askText('remember the word pineapple');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
device.menu(MENU_ITEM.NEW_CONVERSATION);
|
||||
await until('new conversation ready', () => phase() === 'ready' && snapshot.state.conversationId !== null);
|
||||
expect(device.frame.body).toContain('New conversation');
|
||||
controller.askText('what word?');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toContain('turn=1');
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancel and stale results', () => {
|
||||
it('double-tap while recording discards the audio: nothing is uploaded', async () => {
|
||||
await pairedController();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.5);
|
||||
device.doubleTap();
|
||||
await until('cancelled', () => phase() === 'cancelled' && !device.micOpen);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(h.stt.calls).toBe(0);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
// Audio arriving after the stop is ignored.
|
||||
device.micOpen = true;
|
||||
device.speak(0.3);
|
||||
device.micOpen = false;
|
||||
expect(phase()).toBe('cancelled');
|
||||
});
|
||||
|
||||
it('cancel while thinking stops the agent, and its late answer never reaches the HUD', async () => {
|
||||
await pairedController();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250, output: 'LATE ANSWER' });
|
||||
h.hermes.ignoreStop(); // the agent finishes anyway
|
||||
controller.askText('slow question');
|
||||
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
|
||||
device.doubleTap();
|
||||
expect(phase()).toBe('cancelled');
|
||||
expect(device.frame.body).toContain('not undone');
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
expect(phase()).toBe('cancelled');
|
||||
expect(device.frames.some((f) => f.body.includes('LATE ANSWER'))).toBe(false);
|
||||
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop')).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// A newer question is answered normally and the old one cannot overwrite it.
|
||||
h.hermes.ignoreStop(false);
|
||||
h.hermes.next({ kind: 'complete', output: 'NEW ANSWER' });
|
||||
controller.askText('new question');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toBe('NEW ANSWER');
|
||||
});
|
||||
|
||||
it('cancel from the glasses menu works while thinking', async () => {
|
||||
await pairedController();
|
||||
h.hermes.next({ kind: 'hang' });
|
||||
controller.askText('q');
|
||||
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
|
||||
device.menu(MENU_ITEM.CANCEL);
|
||||
expect(phase()).toBe('cancelled');
|
||||
await until('bridge saw the cancel', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
|
||||
});
|
||||
});
|
||||
|
||||
describe('connection loss', () => {
|
||||
it('bridge unreachable at submit: nothing is sent; tap resends the same request exactly once', async () => {
|
||||
await pairedController();
|
||||
network.down = true;
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.5);
|
||||
device.tap();
|
||||
await until('disconnected', () => phase() === 'disconnected');
|
||||
expect(device.frame.body).toContain('has not been sent');
|
||||
expect(device.micOpen).toBe(false);
|
||||
const requestId = snapshot.state.requestId;
|
||||
|
||||
network.down = false;
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.lastTurn!.request_id).toBe(requestId);
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
expect(h.stt.calls).toBe(1);
|
||||
// The microphone was not reopened by the retry.
|
||||
expect(device.micOpens).toBe(1);
|
||||
});
|
||||
|
||||
it('connection lost while waiting: keeps the turn, shows it, and delivers the answer on return', async () => {
|
||||
await pairedController();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 500, output: 'worth the wait' });
|
||||
controller.askText('q');
|
||||
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
|
||||
network.down = true;
|
||||
await until('disconnected', () => phase() === 'disconnected');
|
||||
expect(device.frame.body).toContain('Still waiting');
|
||||
device.tap(); // must not resubmit
|
||||
network.down = false;
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toBe('worth the wait');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
});
|
||||
|
||||
it('glasses disconnect while recording stops capture; reconnecting does not reopen the microphone', async () => {
|
||||
await pairedController();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.connection(false);
|
||||
await until('mic closed', () => !device.micOpen);
|
||||
expect(phase()).toBe('disconnected');
|
||||
device.connection(true);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(phase()).toBe('ready');
|
||||
expect(device.micOpen).toBe(false);
|
||||
expect(device.micOpens).toBe(1);
|
||||
expect(h.stt.calls).toBe(0);
|
||||
});
|
||||
|
||||
it('a microphone that stops delivering audio ends the capture with an error', async () => {
|
||||
await pairedController();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
await until('stall detected', () => phase() === 'error', 3000);
|
||||
expect(snapshot.state.error!.code).toBe('mic_stalled');
|
||||
expect(device.micOpen).toBe(false);
|
||||
});
|
||||
|
||||
it('a refused microphone is reported and nothing is recorded', async () => {
|
||||
await pairedController();
|
||||
device.micAllowed = false;
|
||||
device.tap();
|
||||
await until('error', () => phase() === 'error');
|
||||
expect(snapshot.state.error!.code).toBe('mic_refused');
|
||||
expect(device.frame.body).toContain('Microphone unavailable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('restart, revocation and disconnect', () => {
|
||||
it('a page restart mid-turn re-attaches to the turn without resubmitting or recording', async () => {
|
||||
await pairedController();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'found after restart' });
|
||||
controller.askText('q');
|
||||
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
|
||||
await until('active request persisted', () => (device.storage.get('hermeven.v1') ?? '').includes('"activeRequestId":"'));
|
||||
await controller.stop();
|
||||
|
||||
// New page, same app storage.
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.body).toBe('found after restart');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
expect(device.micOpens).toBe(0);
|
||||
});
|
||||
|
||||
it('a credential revoked on the bridge sends the app back to unpaired and wipes local state', async () => {
|
||||
await pairedController();
|
||||
const [paired] = h.bridge.devices.list();
|
||||
h.bridge.devices.revoke(paired!.id);
|
||||
controller.askText('q');
|
||||
await until('unpaired', () => phase() === 'unpaired');
|
||||
expect(device.storage.get('hermeven.v1')).toBe('');
|
||||
expect(snapshot.paired).toBe(false);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('disconnect revokes on the bridge and clears the phone', async () => {
|
||||
await pairedController();
|
||||
const stored = JSON.parse(device.storage.get('hermeven.v1')!);
|
||||
expect((await controller.disconnect()).revoked).toBe(true);
|
||||
expect(phase()).toBe('unpaired');
|
||||
expect(device.storage.get('hermeven.v1')).toBe('');
|
||||
expect((await h.api('GET', '/v1/device', { token: stored.token })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('double-tap on the root page asks the OS for its exit dialog', async () => {
|
||||
await pairedController();
|
||||
device.doubleTap();
|
||||
await until('exit requested', () => device.exitRequests === 1);
|
||||
expect(phase()).toBe('ready');
|
||||
});
|
||||
|
||||
it('pairing with a wrong code fails without storing anything', async () => {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await expect(controller.pair(h.url, 'WRONG-CODE1', 'x')).rejects.toMatchObject({ body: { code: 'pairing_invalid' } });
|
||||
expect(phase()).toBe('unpaired');
|
||||
expect(device.storage.get('hermeven.v1') ?? '').toBe('');
|
||||
});
|
||||
|
||||
it('diagnostics never contain the question, the answer or the credential', async () => {
|
||||
await pairedController();
|
||||
h.stt.next({ text: 'SECRET-QUESTION-walrus' });
|
||||
h.hermes.next({ kind: 'complete', output: 'SECRET-ANSWER-narwhal' });
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.speak(0.4);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
const log = snapshot.log.map((e) => `${e.kind} ${e.detail}`).join('\n');
|
||||
const token = JSON.parse(device.storage.get('hermeven.v1')!).token;
|
||||
expect(log).toContain('done');
|
||||
for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Writable } from 'node:stream';
|
||||
import { pino } from 'pino';
|
||||
import { SCHEMA_VERSION, type DeviceCredential, type TurnResult } from '@hermeven/contracts';
|
||||
import { LOG_REDACT, createBridge, type Bridge } from '../../services/bridge/src/app.ts';
|
||||
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
|
||||
import type { EngineTiming } from '../../services/bridge/src/turns.ts';
|
||||
import { FakeHermes } from '../fakes/fakeHermes.ts';
|
||||
import { FakeStt } from '../fakes/fakeStt.ts';
|
||||
|
||||
export const FAST: EngineTiming = {
|
||||
transcribeDeadlineMs: 400,
|
||||
agentDeadlineMs: 900,
|
||||
approvalWaitMs: 500,
|
||||
cancelGraceMs: 400,
|
||||
pollIntervalMs: 20,
|
||||
submitRetryMs: 30,
|
||||
notSentAttempts: 3,
|
||||
};
|
||||
|
||||
export interface Harness {
|
||||
hermes: FakeHermes;
|
||||
stt: FakeStt;
|
||||
bridge: Bridge;
|
||||
config: BridgeConfig;
|
||||
url: string;
|
||||
/** Every log line the bridge wrote, for redaction assertions. */
|
||||
logs: string[];
|
||||
dir: string;
|
||||
pair(name?: string): Promise<DeviceCredential>;
|
||||
api(method: string, path: string, opts?: { token?: string; json?: unknown; body?: Buffer; headers?: Record<string, string> }): Promise<{ status: number; body: any; headers: Headers }>;
|
||||
conversation(token: string): Promise<string>;
|
||||
textTurn(token: string, conversationId: string, text: string, requestId?: string): Promise<{ status: number; body: any }>;
|
||||
audioTurn(token: string, conversationId: string, pcm: Buffer, requestId?: string, query?: Record<string, string>): Promise<{ status: number; body: any }>;
|
||||
waitTerminal(token: string, requestId: string, timeoutMs?: number): Promise<TurnResult>;
|
||||
waitState(token: string, requestId: string, state: string, timeoutMs?: number): Promise<TurnResult>;
|
||||
/** Stop the bridge process-equivalent and start a new one on the same database. */
|
||||
restartBridge(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export async function createHarness(
|
||||
opts: { env?: Record<string, string>; timing?: Partial<EngineTiming>; stt?: boolean } = {},
|
||||
): Promise<Harness> {
|
||||
const hermes = new FakeHermes();
|
||||
const stt = new FakeStt();
|
||||
await hermes.start();
|
||||
await stt.start();
|
||||
const dir = mkdtempSync(join(tmpdir(), 'hermeven-test-'));
|
||||
const logs: string[] = [];
|
||||
const sink = new Writable({
|
||||
write(chunk, _enc, cb) {
|
||||
logs.push(String(chunk));
|
||||
cb();
|
||||
},
|
||||
});
|
||||
|
||||
const env: Record<string, string> = {
|
||||
HERMEVEN_HOST: '127.0.0.1',
|
||||
HERMEVEN_PORT: '0',
|
||||
HERMEVEN_DB_PATH: join(dir, 'bridge.sqlite'),
|
||||
HERMES_BASE_URL: hermes.url,
|
||||
HERMES_API_KEY: hermes.apiKey,
|
||||
HERMEVEN_ALLOWED_ORIGINS: 'https://app.example',
|
||||
HERMES_REQUEST_TIMEOUT_MS: '300',
|
||||
...(opts.stt === false
|
||||
? {}
|
||||
: { STT_PROVIDER: 'openai-compatible', STT_BASE_URL: stt.url, STT_API_KEY: stt.apiKey, STT_MODEL: 'fake-whisper' }),
|
||||
...opts.env,
|
||||
};
|
||||
const config = loadConfig(env);
|
||||
const timing = { ...FAST, ...opts.timing };
|
||||
|
||||
const h = {} as Harness;
|
||||
const boot = async () => {
|
||||
h.bridge = await createBridge(config, {
|
||||
timing,
|
||||
logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink),
|
||||
});
|
||||
await h.bridge.app.listen({ host: '127.0.0.1', port: 0 });
|
||||
h.url = `http://127.0.0.1:${(h.bridge.app.server.address() as AddressInfo).port}`;
|
||||
};
|
||||
|
||||
Object.assign(h, { hermes, stt, config, logs, dir });
|
||||
await boot();
|
||||
|
||||
h.api = async (method, path, o = {}) => {
|
||||
const headers: Record<string, string> = { ...(o.headers ?? {}) };
|
||||
if (o.token) headers.Authorization = `Bearer ${o.token}`;
|
||||
let body: BodyInit | undefined;
|
||||
if (o.json !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
body = JSON.stringify(o.json);
|
||||
} else if (o.body) {
|
||||
headers['Content-Type'] ??= 'application/octet-stream';
|
||||
body = new Uint8Array(o.body);
|
||||
}
|
||||
const res = await fetch(`${h.url}${path}`, { method, headers, body });
|
||||
const text = await res.text();
|
||||
let parsed: unknown = text;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
/* keep raw text */
|
||||
}
|
||||
return { status: res.status, body: parsed, headers: res.headers };
|
||||
};
|
||||
|
||||
h.pair = async (name = 'test-g2') => {
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
const res = await h.api('POST', '/v1/pairing/claim', { json: { schema_version: SCHEMA_VERSION, code, device_name: name } });
|
||||
if (res.status !== 201) throw new Error(`pairing failed: ${res.status} ${JSON.stringify(res.body)}`);
|
||||
return res.body as DeviceCredential;
|
||||
};
|
||||
|
||||
h.conversation = async (token) => {
|
||||
const res = await h.api('POST', '/v1/conversations', { token, json: { schema_version: SCHEMA_VERSION } });
|
||||
if (res.status !== 201) throw new Error(`conversation failed: ${res.status} ${JSON.stringify(res.body)}`);
|
||||
return res.body.conversation_id as string;
|
||||
};
|
||||
|
||||
h.textTurn = (token, conversationId, text, requestId = randomUUID()) =>
|
||||
h.api('POST', '/v1/turns', {
|
||||
token,
|
||||
json: {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: requestId,
|
||||
conversation_id: conversationId,
|
||||
locale: 'en-US',
|
||||
input: { kind: 'text', text },
|
||||
},
|
||||
});
|
||||
|
||||
h.audioTurn = (token, conversationId, pcm, requestId = randomUUID(), query = {}) => {
|
||||
const q = new URLSearchParams({
|
||||
schema_version: String(SCHEMA_VERSION),
|
||||
request_id: requestId,
|
||||
conversation_id: conversationId,
|
||||
locale: 'en-US',
|
||||
input_kind: 'audio',
|
||||
encoding: 'pcm_s16le',
|
||||
sample_rate: '16000',
|
||||
channels: '1',
|
||||
...query,
|
||||
});
|
||||
return h.api('POST', `/v1/turns?${q}`, { token, body: pcm });
|
||||
};
|
||||
|
||||
const waitFor = async (token: string, requestId: string, done: (t: TurnResult) => boolean, timeoutMs: number) => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last: TurnResult | undefined;
|
||||
while (Date.now() < deadline) {
|
||||
const res = await h.api('GET', `/v1/turns/${requestId}`, { token });
|
||||
if (res.status === 200) {
|
||||
last = res.body as TurnResult;
|
||||
if (done(last)) return last;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
}
|
||||
throw new Error(`timed out waiting for turn ${requestId}; last=${JSON.stringify(last)}`);
|
||||
};
|
||||
h.waitTerminal = (token, requestId, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.terminal, timeoutMs);
|
||||
h.waitState = (token, requestId, state, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.state === state, timeoutMs);
|
||||
|
||||
h.restartBridge = async () => {
|
||||
await h.bridge.close();
|
||||
await boot();
|
||||
};
|
||||
|
||||
h.close = async () => {
|
||||
await h.bridge.close().catch(() => undefined);
|
||||
await hermes.stop();
|
||||
await stt.stop();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
};
|
||||
return h;
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||
import { createBridge, type Bridge } from '../../services/bridge/src/app.ts';
|
||||
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
|
||||
import { StubLlm } from '../fakes/stubLlm.ts';
|
||||
|
||||
/**
|
||||
* REAL HERMES, STUB MODEL.
|
||||
*
|
||||
* The bridge (real code, real HTTP adapter) talks to a real `hermes gateway`
|
||||
* process: the installed hermes-agent, started in a throwaway HERMES_HOME so
|
||||
* the operator's own profile, sessions and credentials are never read or
|
||||
* written. The only fake is the language model behind Hermes (tests/fakes/
|
||||
* stubLlm.ts), which costs nothing and answers deterministically.
|
||||
*
|
||||
* So this verifies Hermeven against Hermes's actual API server behaviour
|
||||
* (admission, idempotency, session continuity, stop). It does not verify a
|
||||
* real model, real tools, a deployed Hermes, or any hardware.
|
||||
*/
|
||||
const API_KEY = `test-${randomUUID()}`;
|
||||
let home: string;
|
||||
let gateway: ChildProcess;
|
||||
let gatewayLog = '';
|
||||
let hermesUrl: string;
|
||||
let llm: StubLlm;
|
||||
let bridge: Bridge;
|
||||
let config: BridgeConfig;
|
||||
let token: string;
|
||||
let hermesVersion = '';
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
const srv = createServer();
|
||||
srv.listen(0, '127.0.0.1', () => {
|
||||
const { port } = srv.address() as { port: number };
|
||||
srv.close(() => resolve(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function startBridge(): Promise<void> {
|
||||
bridge = await createBridge(config);
|
||||
}
|
||||
|
||||
async function api(method: string, path: string, json?: unknown, auth = token) {
|
||||
const res = await bridge.app.inject({
|
||||
method: method as 'GET',
|
||||
url: path,
|
||||
headers: { authorization: `Bearer ${auth}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) },
|
||||
payload: json !== undefined ? JSON.stringify(json) : undefined,
|
||||
});
|
||||
return { status: res.statusCode, body: res.json() };
|
||||
}
|
||||
|
||||
async function ask(conversationId: string, text: string, requestId = randomUUID()) {
|
||||
return api('POST', '/v1/turns', {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
request_id: requestId,
|
||||
conversation_id: conversationId,
|
||||
locale: 'en-US',
|
||||
input: { kind: 'text', text },
|
||||
});
|
||||
}
|
||||
|
||||
async function settle(requestId: string, timeoutMs = 60_000): Promise<TurnResult> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const res = await api('GET', `/v1/turns/${requestId}`);
|
||||
if (res.body.terminal) return res.body as TurnResult;
|
||||
if (Date.now() > deadline) throw new Error(`turn did not settle: ${JSON.stringify(res.body)}\n${gatewayLog.slice(-1500)}`);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
}
|
||||
|
||||
async function newConversation(): Promise<string> {
|
||||
return (await api('POST', '/v1/conversations', { schema_version: SCHEMA_VERSION })).body.conversation_id;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
hermesVersion = execFileSync('hermes', ['--version'], { encoding: 'utf8' }).split('\n')[0]!.trim();
|
||||
llm = new StubLlm();
|
||||
await llm.start();
|
||||
|
||||
home = mkdtempSync(join(tmpdir(), 'hermeven-hermes-home-'));
|
||||
writeFileSync(
|
||||
join(home, 'config.yaml'),
|
||||
['model:', ' default: "stub-model"', ' provider: "custom"', ` base_url: "${llm.url}"`, ' api_key: "stub-key-not-a-secret"', ''].join('\n'),
|
||||
);
|
||||
const port = await freePort();
|
||||
hermesUrl = `http://127.0.0.1:${port}`;
|
||||
gateway = spawn('hermes', ['gateway', 'run'], {
|
||||
cwd: home,
|
||||
env: {
|
||||
...process.env,
|
||||
HERMES_HOME: home,
|
||||
API_SERVER_ENABLED: 'true',
|
||||
API_SERVER_KEY: API_KEY,
|
||||
API_SERVER_PORT: String(port),
|
||||
API_SERVER_HOST: '127.0.0.1',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
gateway.stdout!.on('data', (d) => (gatewayLog += String(d)));
|
||||
gateway.stderr!.on('data', (d) => (gatewayLog += String(d)));
|
||||
|
||||
const deadline = Date.now() + 200_000;
|
||||
for (;;) {
|
||||
try {
|
||||
if ((await fetch(`${hermesUrl}/health`)).ok) break;
|
||||
} catch {
|
||||
/* starting */
|
||||
}
|
||||
if (gateway.exitCode !== null) throw new Error(`hermes gateway exited early:\n${gatewayLog.slice(-3000)}`);
|
||||
if (Date.now() > deadline) throw new Error(`hermes gateway did not become healthy:\n${gatewayLog.slice(-3000)}`);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
|
||||
config = loadConfig({
|
||||
HERMEVEN_DB_PATH: join(home, 'hermeven-bridge.sqlite'),
|
||||
HERMES_BASE_URL: hermesUrl,
|
||||
HERMES_API_KEY: API_KEY,
|
||||
HERMES_POLL_INTERVAL_MS: '100',
|
||||
HERMEVEN_AGENT_DEADLINE_SECONDS: '60',
|
||||
HERMEVEN_CANCEL_GRACE_SECONDS: '30',
|
||||
});
|
||||
await startBridge();
|
||||
const { code } = bridge.devices.createPairingCode();
|
||||
const claim = await bridge.app.inject({
|
||||
method: 'POST',
|
||||
url: '/v1/pairing/claim',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
payload: JSON.stringify({ schema_version: SCHEMA_VERSION, code, device_name: 'real-hermes-test' }),
|
||||
});
|
||||
token = claim.json().token;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bridge?.close().catch(() => undefined);
|
||||
try {
|
||||
execFileSync('hermes', ['gateway', 'stop'], { env: { ...process.env, HERMES_HOME: home }, cwd: home, timeout: 60_000, stdio: 'ignore' });
|
||||
} catch {
|
||||
gateway?.kill('SIGTERM');
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
if (gateway && gateway.exitCode === null) gateway.kill('SIGKILL');
|
||||
await llm?.stop();
|
||||
if (home) rmSync(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('bridge against a real Hermes gateway (stub model)', () => {
|
||||
it('records which Hermes was tested', async () => {
|
||||
const health = await (await fetch(`${hermesUrl}/health`)).json();
|
||||
console.info(`[real-hermes] CLI: ${hermesVersion}; /health: ${JSON.stringify(health)}`);
|
||||
expect(health.status).toBe('ok');
|
||||
const caps = await (await fetch(`${hermesUrl}/v1/capabilities`, { headers: { Authorization: `Bearer ${API_KEY}` } })).json();
|
||||
expect(caps.features.run_submission).toBe(true);
|
||||
expect(caps.features.run_status).toBe(true);
|
||||
expect(caps.features.run_stop).toBe(true);
|
||||
expect(caps.features.runs_idempotency).toMatchObject({ supported: true, durable: true });
|
||||
console.info(`[real-hermes] runs_idempotency: ${JSON.stringify(caps.features.runs_idempotency)}`);
|
||||
});
|
||||
|
||||
it('device status reports the agent as reachable', async () => {
|
||||
expect((await api('GET', '/v1/device')).body.agent_reachable).toBe(true);
|
||||
});
|
||||
|
||||
it('a typed question is answered through Hermes, with Hermeven instructions layered on', async () => {
|
||||
const conv = await newConversation();
|
||||
const res = await ask(conv, 'My favourite colour is teal.');
|
||||
expect(res.status).toBe(202);
|
||||
const done = await settle(res.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('STUB-ANSWER users=1');
|
||||
expect(done.answer_text).toContain('My favourite colour is teal.');
|
||||
// The per-request instructions reached the model's system prompt, alongside Hermes' own.
|
||||
expect(llm.lastSystem).toContain('heads-up display');
|
||||
console.info(`[real-hermes] first turn agent_ms=${done.timings.agent_ms}`);
|
||||
});
|
||||
|
||||
it('a follow-up carries the earlier turn through Hermes’ own session store; a new conversation does not', async () => {
|
||||
const conv = await newConversation();
|
||||
await settle((await ask(conv, 'Remember the word pineapple.')).body.request_id);
|
||||
const followUp = await settle((await ask(conv, 'What word did I ask you to remember?')).body.request_id);
|
||||
expect(followUp.outcome).toBe('succeeded');
|
||||
// The model was handed both user turns by Hermes; the bridge sent only the new one.
|
||||
expect(llm.lastUserMessages).toEqual(['Remember the word pineapple.', 'What word did I ask you to remember?']);
|
||||
expect(followUp.answer_text).toContain('users=2');
|
||||
|
||||
const fresh = await newConversation();
|
||||
const first = await settle((await ask(fresh, 'What word did I ask you to remember?')).body.request_id);
|
||||
expect(first.answer_text).toContain('users=1');
|
||||
expect(llm.lastUserMessages).toEqual(['What word did I ask you to remember?']);
|
||||
});
|
||||
|
||||
it('duplicate submits reach the model exactly once (backend invocation counter)', async () => {
|
||||
const conv = await newConversation();
|
||||
const before = llm.calls;
|
||||
const id = randomUUID();
|
||||
const results = await Promise.all(Array.from({ length: 6 }, () => ask(conv, 'Count me once.', id)));
|
||||
expect(results.filter((r) => r.status === 202)).toHaveLength(1);
|
||||
expect(results.filter((r) => r.status === 200 && r.body.replayed)).toHaveLength(5);
|
||||
await settle(id);
|
||||
await ask(conv, 'Count me once.', id);
|
||||
expect(llm.calls - before).toBe(1);
|
||||
});
|
||||
|
||||
it('Hermes replays an identical keyed submit and refuses a changed one (the adapter’s premise)', async () => {
|
||||
const key = `hermeven-test-${randomUUID()}`;
|
||||
const body = JSON.stringify({ input: 'idempotency probe', session_id: `hermeven-${randomUUID()}` });
|
||||
const post = (payload: string) =>
|
||||
fetch(`${hermesUrl}/v1/runs`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body: payload,
|
||||
});
|
||||
const before = llm.calls;
|
||||
const first = await post(body);
|
||||
expect(first.status).toBe(202);
|
||||
const runId = (await first.json()).run_id;
|
||||
const again = await post(body);
|
||||
expect(again.status).toBe(202);
|
||||
expect(again.headers.get('idempotency-replayed')).toBe('true');
|
||||
expect((await again.json()).run_id).toBe(runId);
|
||||
const changed = await post(JSON.stringify({ input: 'something else', session_id: 'x' }));
|
||||
expect(changed.status).toBe(409);
|
||||
expect((await changed.json()).error.code).toBe('idempotency_key_conflict');
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
expect(llm.calls - before).toBe(1);
|
||||
});
|
||||
|
||||
it('cancel during a slow turn: Hermes confirms the stop and no answer is delivered', async () => {
|
||||
const conv = await newConversation();
|
||||
llm.delayMs = 15_000;
|
||||
try {
|
||||
const res = await ask(conv, 'This will take a while.');
|
||||
const id = res.body.request_id;
|
||||
const deadline = Date.now() + 20_000;
|
||||
while ((await api('GET', `/v1/turns/${id}`)).body.state !== 'thinking') {
|
||||
if (Date.now() > deadline) throw new Error('never reached thinking');
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const started = Date.now();
|
||||
const cancel = await api('POST', `/v1/turns/${id}/cancel`, {});
|
||||
expect(cancel.body.cancel_requested).toBe(true);
|
||||
const done = await settle(id, 45_000);
|
||||
console.info(`[real-hermes] cancel settled as ${done.outcome} in ${Date.now() - started} ms`);
|
||||
expect(done.outcome).toBe('cancelled');
|
||||
expect(done.answer_text).toBeNull();
|
||||
} finally {
|
||||
llm.delayMs = 0;
|
||||
}
|
||||
});
|
||||
|
||||
it('a bridge restart mid-turn re-attaches to the same Hermes run', async () => {
|
||||
const conv = await newConversation();
|
||||
llm.delayMs = 4000;
|
||||
try {
|
||||
const before = llm.calls;
|
||||
const res = await ask(conv, 'Survive a restart.');
|
||||
const id = res.body.request_id;
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
await bridge.close();
|
||||
await startBridge();
|
||||
const done = await settle(id, 60_000);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('Survive a restart.');
|
||||
expect(llm.calls - before).toBe(1);
|
||||
} finally {
|
||||
llm.delayMs = 0;
|
||||
}
|
||||
});
|
||||
|
||||
it('a wrong Hermes key is a definite rejection: nothing runs', async () => {
|
||||
await bridge.close();
|
||||
const good = config;
|
||||
config = { ...good, hermes: { ...good.hermes, apiKey: 'wrong-key' } };
|
||||
await startBridge();
|
||||
try {
|
||||
const conv = await newConversation();
|
||||
const before = llm.calls;
|
||||
const done = await settle((await ask(conv, 'Should not run.')).body.request_id);
|
||||
expect(done.outcome).toBe('failed');
|
||||
expect(done.error?.code).toBe('agent_rejected');
|
||||
expect(llm.calls).toBe(before);
|
||||
} finally {
|
||||
await bridge.close();
|
||||
config = good;
|
||||
await startBridge();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
// Opt-in: needs the `hermes` CLI installed. Runs a REAL Hermes gateway in a throwaway
|
||||
// HERMES_HOME against a stub model, so no account, key or spend is involved.
|
||||
export default defineConfig({
|
||||
test: {
|
||||
name: 'real-hermes',
|
||||
root: new URL('../..', import.meta.url).pathname,
|
||||
include: ['tests/real-hermes/**/*.test.ts'],
|
||||
testTimeout: 90_000,
|
||||
hookTimeout: 240_000,
|
||||
fileParallelism: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { createServer as createNetServer } from 'node:net';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { createServer, type ViteDevServer } from 'vite';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createHarness, type Harness } from '../integration/harness.ts';
|
||||
|
||||
/**
|
||||
* SIMULATOR TEST: the real client, loaded in the official Even Hub simulator
|
||||
* (@evenrealities/evenhub-simulator), driven through its automation API,
|
||||
* talking over HTTP to the real bridge. Hermes and the speech recogniser are
|
||||
* TEST FAKES, and the simulator's audio input is ALSA's null device (silence),
|
||||
* so no real microphone is opened and no real speech is transcribed.
|
||||
*
|
||||
* This is simulator evidence. It is not device evidence: Even documents that
|
||||
* the simulator differs from hardware in font rendering, events and lifecycle.
|
||||
*/
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const artifacts = resolve(here, '.artifacts');
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
let h: Harness;
|
||||
let vite: ViteDevServer;
|
||||
let sim: ChildProcess;
|
||||
let simOutput = '';
|
||||
let automation = '';
|
||||
let lastConsoleId = 0;
|
||||
const consoleLines: string[] = [];
|
||||
let audioEchoLines = 0;
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolvePort) => {
|
||||
const srv = createNetServer();
|
||||
srv.listen(0, '127.0.0.1', () => {
|
||||
const { port } = srv.address() as { port: number };
|
||||
srv.close(() => resolvePort(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function pumpConsole(): Promise<void> {
|
||||
const res = await fetch(`${automation}/api/console?since_id=${lastConsoleId}`);
|
||||
const body = (await res.json()) as { entries: Array<{ id: number; level: string; message: string }> };
|
||||
for (const entry of body.entries) {
|
||||
lastConsoleId = Math.max(lastConsoleId, entry.id);
|
||||
// In the simulator every hub event, including each raw PCM frame, is echoed to the webview
|
||||
// console with an "[EvenAppBridge]" prefix. Those lines are counted, not kept.
|
||||
if (entry.message.includes('audioPcm')) {
|
||||
audioEchoLines += 1;
|
||||
continue;
|
||||
}
|
||||
consoleLines.push(`${entry.level}: ${entry.message}`.slice(0, 600));
|
||||
}
|
||||
}
|
||||
|
||||
async function waitConsole(needle: string, timeoutMs = 20_000, from = 0): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
await pumpConsole();
|
||||
if (consoleLines.slice(from).some((l) => l.includes(needle))) return;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`simulator console never showed "${needle}".\nConsole:\n${consoleLines.join('\n')}\nSimulator output:\n${simOutput.slice(-2000)}`);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
}
|
||||
}
|
||||
|
||||
async function input(action: string): Promise<void> {
|
||||
const res = await fetch(`${automation}/api/input`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action }),
|
||||
});
|
||||
expect(res.status, `input ${action}`).toBe(200);
|
||||
}
|
||||
|
||||
/** Minimal RGBA8 PNG decoder (non-interlaced), enough to count lit pixels. */
|
||||
function decodePng(png: Buffer): { width: number; height: number; lit: number; rows: Buffer[] } {
|
||||
let offset = 8;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let colorType = 0;
|
||||
const idat: Buffer[] = [];
|
||||
while (offset < png.length) {
|
||||
const length = png.readUInt32BE(offset);
|
||||
const type = png.toString('ascii', offset + 4, offset + 8);
|
||||
const data = png.subarray(offset + 8, offset + 8 + length);
|
||||
if (type === 'IHDR') {
|
||||
width = data.readUInt32BE(0);
|
||||
height = data.readUInt32BE(4);
|
||||
colorType = data[9]!;
|
||||
} else if (type === 'IDAT') idat.push(data);
|
||||
offset += 12 + length;
|
||||
}
|
||||
expect(colorType, 'glasses screenshot should be RGBA').toBe(6);
|
||||
const raw = inflateSync(Buffer.concat(idat));
|
||||
const bpp = 4;
|
||||
const stride = width * bpp;
|
||||
const rows: Buffer[] = [];
|
||||
let prev = Buffer.alloc(stride);
|
||||
let lit = 0;
|
||||
for (let y = 0; y < height; y++) {
|
||||
const filter = raw[y * (stride + 1)]!;
|
||||
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
|
||||
for (let x = 0; x < stride; x++) {
|
||||
const a = x >= bpp ? line[x - bpp]! : 0;
|
||||
const b = prev[x]!;
|
||||
const c = x >= bpp ? prev[x - bpp]! : 0;
|
||||
let add = 0;
|
||||
if (filter === 1) add = a;
|
||||
else if (filter === 2) add = b;
|
||||
else if (filter === 3) add = (a + b) >> 1;
|
||||
else if (filter === 4) {
|
||||
const p = a + b - c;
|
||||
const pa = Math.abs(p - a);
|
||||
const pb = Math.abs(p - b);
|
||||
const pc = Math.abs(p - c);
|
||||
add = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
||||
}
|
||||
line[x] = (line[x]! + add) & 0xff;
|
||||
}
|
||||
for (let x = 0; x < width; x++) if (line[x * 4 + 3]! > 0) lit += 1;
|
||||
rows.push(line);
|
||||
prev = line;
|
||||
}
|
||||
return { width, height, lit, rows };
|
||||
}
|
||||
|
||||
async function screenshot(name: string) {
|
||||
const res = await fetch(`${automation}/api/screenshot/glasses`);
|
||||
expect(res.status).toBe(200);
|
||||
const png = Buffer.from(await res.arrayBuffer());
|
||||
writeFileSync(resolve(artifacts, `${name}.png`), png);
|
||||
return { png, ...decodePng(png) };
|
||||
}
|
||||
|
||||
/** Lit pixels inside a horizontal band of the canvas. */
|
||||
function litInBand(shot: { rows: Buffer[]; width: number }, fromY: number, toY: number): number {
|
||||
let lit = 0;
|
||||
for (let y = fromY; y < toY; y++) for (let x = 0; x < shot.width; x++) if (shot.rows[y]![x * 4 + 3]! > 0) lit += 1;
|
||||
return lit;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
mkdirSync(artifacts, { recursive: true });
|
||||
const vitePort = await freePort();
|
||||
vite = await createServer({
|
||||
root: resolve(here, '../../apps/even-client'),
|
||||
configFile: resolve(here, '../../apps/even-client/vite.config.ts'),
|
||||
server: { host: '127.0.0.1', port: vitePort, strictPort: true },
|
||||
logLevel: 'error',
|
||||
});
|
||||
await vite.listen();
|
||||
const pageOrigin = `http://127.0.0.1:${vitePort}`;
|
||||
|
||||
h = await createHarness({
|
||||
env: { HERMEVEN_ALLOWED_ORIGINS: pageOrigin, HERMEVEN_CAPTURE_MAX_SECONDS: '120' },
|
||||
timing: { agentDeadlineMs: 20_000, transcribeDeadlineMs: 10_000 },
|
||||
});
|
||||
const { code } = h.bridge.devices.createPairingCode();
|
||||
|
||||
const automationPort = await freePort();
|
||||
automation = `http://127.0.0.1:${automationPort}`;
|
||||
const bin = require.resolve('@evenrealities/sim-linux-x64/bin/evenhub-simulator');
|
||||
const url = `${pageOrigin}/?bridge=${encodeURIComponent(h.url)}&pair=${encodeURIComponent(code)}`;
|
||||
// alsa:null yields silence: the simulator never opens a real microphone in this test.
|
||||
sim = spawn(bin, [url, '--automation-port', String(automationPort), '--no-glow', '--aid', 'alsa:null'], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
cwd: artifacts,
|
||||
});
|
||||
sim.stdout!.on('data', (d) => (simOutput += String(d)));
|
||||
sim.stderr!.on('data', (d) => (simOutput += String(d)));
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
for (;;) {
|
||||
try {
|
||||
if ((await fetch(`${automation}/api/ping`)).ok) break;
|
||||
} catch {
|
||||
/* not up yet */
|
||||
}
|
||||
if (Date.now() > deadline) throw new Error(`simulator automation API did not start.\n${simOutput.slice(-2000)}`);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
sim?.kill('SIGTERM');
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
if (sim && sim.exitCode === null) sim.kill('SIGKILL');
|
||||
await vite?.close();
|
||||
await h?.close();
|
||||
writeFileSync(
|
||||
resolve(artifacts, 'console.log'),
|
||||
`${consoleLines.join('\n')}\n(audio frame echo lines omitted: ${audioEchoLines})\n`,
|
||||
);
|
||||
});
|
||||
|
||||
describe('Even Hub simulator 0.9.5', () => {
|
||||
it('boots through the real SDK bridge, creates the HUD page and pairs', async () => {
|
||||
await waitConsole('hud: HUD page created', 30_000);
|
||||
await waitConsole('state: unpaired -> ready');
|
||||
expect(consoleLines.some((l) => l.includes('HUD page was refused'))).toBe(false);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const shot = await screenshot('01-ready');
|
||||
expect([shot.width, shot.height]).toEqual([576, 288]);
|
||||
// Body text at the top and the status bar in the bottom band are both drawn.
|
||||
expect(litInBand(shot, 0, 120)).toBeGreaterThan(200);
|
||||
expect(litInBand(shot, 251, 288)).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it('tap opens the microphone, audio frames arrive as 16 kHz PCM, tap submits, the answer is drawn', async () => {
|
||||
const answer = Array.from({ length: 40 }, (_, i) => `Simulator sentence ${i + 1} of the answer.`).join(' ');
|
||||
h.stt.next({ text: 'simulated question' });
|
||||
h.hermes.next({ kind: 'complete', afterMs: 600, output: answer });
|
||||
|
||||
const mark = consoleLines.length;
|
||||
await input('click');
|
||||
await waitConsole('state: ready -> listening', 10_000, mark);
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
const recording = await screenshot('02-listening');
|
||||
expect(litInBand(recording, 251, 288)).toBeGreaterThan(100);
|
||||
|
||||
// Second tap = stop and send. With the unpaced null audio device the capture cap can be
|
||||
// reached first, in which case this tap is a harmless no-op; both are valid ways to end a
|
||||
// capture and the assertions below hold for either.
|
||||
await input('click');
|
||||
await waitConsole('state: listening -> transcribing', 10_000, mark);
|
||||
await waitConsole('-> answer', 20_000, mark);
|
||||
await pumpConsole();
|
||||
// No stall: the simulator really delivered audio frames while the mic was open.
|
||||
expect(consoleLines.slice(mark).some((l) => l.includes('no audio frames'))).toBe(false);
|
||||
const captured = consoleLines.slice(mark).find((l) => l.includes('capture: captured'));
|
||||
expect(captured, 'capture summary').toBeTruthy();
|
||||
const seconds = Number(/captured ([\d.]+) s/.exec(captured!)![1]);
|
||||
// The null audio device is not paced in real time, so the amount captured in a fixed wall
|
||||
// time says nothing about a real microphone. What matters: frames arrived, the explicit tap
|
||||
// (not the cap) ended the capture, and exactly those bytes reached the recogniser as WAV.
|
||||
const endedByCap = consoleLines.slice(mark).some((l) => l.includes('capture limit reached'));
|
||||
console.info(`[simulator] capture ended by ${endedByCap ? 'the 120 s cap' : 'the second tap'} with ${seconds} s of null-device audio`);
|
||||
expect(seconds).toBeGreaterThan(0);
|
||||
expect(seconds).toBeLessThanOrEqual(120);
|
||||
if (endedByCap) expect(seconds).toBe(120);
|
||||
expect(audioEchoLines).toBeGreaterThan(0);
|
||||
expect(h.stt.lastWav).toMatchObject({ sampleRate: 16000, channels: 1, bitsPerSample: 16 });
|
||||
expect(h.stt.lastWav!.dataBytes % 3200).toBe(0);
|
||||
expect(h.stt.lastWav!.dataBytes / 32000).toBeCloseTo(seconds, 1);
|
||||
expect(h.hermes.lastRun()!.input).toBe('simulated question');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const page1 = await screenshot('03-answer-page-1');
|
||||
expect(litInBand(page1, 0, 251)).toBeGreaterThan(2000);
|
||||
expect(consoleLines.slice(mark).some((l) => /answer laid out on [2-9] page/.test(l))).toBe(true);
|
||||
});
|
||||
|
||||
it('swipe down turns the page, swipe up returns, and the page fits without firmware scrolling', async () => {
|
||||
const page1 = await screenshot('04-before-swipe');
|
||||
await input('down');
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const page2 = await screenshot('05-answer-page-2');
|
||||
expect(page2.png.equals(page1.png)).toBe(false);
|
||||
await input('up');
|
||||
await new Promise((r) => setTimeout(r, 900));
|
||||
const back = await screenshot('06-answer-page-1-again');
|
||||
expect(back.png.equals(page1.png)).toBe(true);
|
||||
});
|
||||
|
||||
it('a follow-up tap continues the same conversation', async () => {
|
||||
h.stt.next({ text: 'simulated follow-up' });
|
||||
const mark = consoleLines.length;
|
||||
await input('click');
|
||||
await waitConsole('state: answer -> listening', 10_000, mark);
|
||||
// Give the microphone a moment to deliver frames (an instant second tap records nothing,
|
||||
// which the app correctly reports as "Nothing was recorded"). If the unpaced null device
|
||||
// has already hit the cap, the capture is over and a tap now would start a new question.
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
await pumpConsole();
|
||||
if (!consoleLines.slice(mark).some((l) => l.includes('capture limit reached'))) await input('click');
|
||||
await waitConsole('-> answer', 20_000, mark);
|
||||
expect(h.hermes.sessions.size).toBe(1);
|
||||
expect(h.hermes.executions).toBe(2);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
await screenshot('07-follow-up-answer');
|
||||
});
|
||||
|
||||
it('double-tap while recording cancels and uploads nothing; double-tap on an answer goes back', async () => {
|
||||
const sttCalls = h.stt.calls;
|
||||
let mark = consoleLines.length;
|
||||
await input('click');
|
||||
// Sent back to back, so the cancel lands before the unpaced null device can fill the cap.
|
||||
await input('double_click');
|
||||
await waitConsole('state: listening -> cancelled', 10_000, mark);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
await screenshot('08-cancelled');
|
||||
expect(h.stt.calls).toBe(sttCalls);
|
||||
|
||||
mark = consoleLines.length;
|
||||
await input('double_click');
|
||||
await waitConsole('state: cancelled -> ready', 10_000, mark);
|
||||
expect(h.hermes.executions).toBe(2);
|
||||
});
|
||||
|
||||
it('no uncaught errors or failed fetches were reported by the webview', async () => {
|
||||
await pumpConsole();
|
||||
const problems = consoleLines.filter((l) => /\[uncaught\]|\[unhandledrejection\]|\[fetch\]/.test(l));
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
// Separate from the default suite: needs a desktop session and the official
|
||||
// Even Hub simulator binary. Run with `npm run test:simulator`.
|
||||
export default defineConfig({
|
||||
test: {
|
||||
name: 'simulator',
|
||||
root: new URL('../..', import.meta.url).pathname,
|
||||
include: ['tests/simulator/**/*.test.ts'],
|
||||
testTimeout: 120_000,
|
||||
hookTimeout: 120_000,
|
||||
fileParallelism: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": { "lib": ["ES2024", "DOM", "DOM.Iterable"], "types": ["node"] },
|
||||
"include": ["."]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2024"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
projects: [
|
||||
{ test: { name: 'contracts', include: ['packages/contracts/test/**/*.test.ts'] } },
|
||||
{ test: { name: 'bridge', include: ['services/bridge/test/**/*.test.ts'] } },
|
||||
{ test: { name: 'even-client', include: ['apps/even-client/test/**/*.test.ts'] } },
|
||||
{ test: { name: 'integration', include: ['tests/integration/**/*.test.ts'], testTimeout: 20_000 } },
|
||||
],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user