Address Cody review round 2: all ten findings (CODY-001 to CODY-010)

CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
         in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
         a microphone start that completes after its timeout is followed by
         a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
         definitive answer; lost replies are treated as ambiguous and
         reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
         transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
         verified ahead of time; verified on every load; never downloaded
         at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
         restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
         stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
         failures are indistinguishable.

Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); test:real-hermes 9
passed; test:simulator 6 passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-18 19:49:14 -08:00
co-authored by Claude Fable 5.2
parent 3d5691dfa3
commit e1c02d5266
43 changed files with 2104 additions and 227 deletions
+7 -4
View File
@@ -25,13 +25,16 @@ HERMEVEN_ALLOWED_ORIGINS=
# --- Speech-to-text ----------------------------------------------------------- # --- Speech-to-text -----------------------------------------------------------
# "builtin" (default): Whisper runs inside the bridge on the CPU. No account, and recordings # "builtin" (default): Whisper runs inside the bridge on the CPU. No account, and recordings
# never leave the bridge host. Model files (about 80 MB) are downloaded on first start. # never leave the bridge host. The model is pinned (commit id + SHA-256 per file) and is
# never downloaded by the running bridge: fetch it once with
# npm run bridge:cli -- fetch-model
# "openai-compatible": any server with POST {base}/audio/transcriptions. # "openai-compatible": any server with POST {base}/audio/transcriptions.
# "none": typed questions only. # "none": typed questions only.
STT_PROVIDER=builtin STT_PROVIDER=builtin
# STT_MODEL=onnx-community/whisper-base # or whisper-tiny (faster), whisper-base.en (English only) # STT_MODEL=whisper-base # bundled pinned models: whisper-base, whisper-tiny (faster, less accurate)
# STT_DTYPE=q8 # STT_MODEL_DIR=./data/models # where the verified files live; can be read-only at run time
# STT_CACHE_DIR=./data/models # STT_MODEL_MANIFEST= # path to your own manifest for any other model (must pin a
# # 40-character commit id and a SHA-256 for every file)
# #
# For STT_PROVIDER=openai-compatible: # For STT_PROVIDER=openai-compatible:
# STT_BASE_URL=https://stt.example/v1 # STT_BASE_URL=https://stt.example/v1
+3 -2
View File
@@ -12,10 +12,10 @@ small bridge between the two.
| Path | State | | Path | State |
|---|---| |---|---|
| Client, bridge and contract | Implemented. | | Client, bridge and contract | Implemented. |
| Automated tests with fakes (130) | Passing. | | Automated tests with fakes (182) | Passing. |
| Client in Even's official simulator | Passing (6 scenarios). Simulator only. | | Client in Even's official simulator | Passing (6 scenarios). Simulator only. |
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
| Built-in speech-to-text (Whisper, in the bridge) | Passing (4 scenarios) on a real speech recording. Not yet on audio from the glasses. | | Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. |
| Running on a droplet | **Not run.** See `docs/deploy-droplet.md`. | | Running on a droplet | **Not run.** See `docs/deploy-droplet.md`. |
| Real model, real tools, approval flow | **Not run.** | | Real model, real tools, approval flow | **Not run.** |
| Physical G2, ring, locked-phone use, battery | **Not run.** See `docs/device-test-plan.md`. | | Physical G2, ring, locked-phone use, battery | **Not run.** See `docs/device-test-plan.md`. |
@@ -44,6 +44,7 @@ G2 <-Bluetooth-> Even phone app (WebView: apps/even-client)
```sh ```sh
npm ci npm ci
cp .env.example .env # set HERMES_API_KEY; add HERMEVEN_ALLOWED_ORIGINS=http://localhost:5173 cp .env.example .env # set HERMES_API_KEY; add HERMEVEN_ALLOWED_ORIGINS=http://localhost:5173
npm run bridge:cli -- fetch-model # one-time: download and verify the pinned speech model
npm run bridge # terminal 1 npm run bridge # terminal 1
npm run client:dev # terminal 2, then open http://localhost:5173 npm run client:dev # terminal 2, then open http://localhost:5173
npm run bridge:cli -- pair # terminal 3: prints a one-time pairing code npm run bridge:cli -- pair # terminal 3: prints a one-time pairing code
+12 -3
View File
@@ -24,11 +24,20 @@ if (origin !== raw) {
console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`); console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`);
process.exit(1); process.exit(1);
} }
if (!origin.startsWith('https://')) { // Same rule as the app enforces at run time (src/net/bridgeClient.ts): HTTPS, or HTTP to
console.warn('[manifest] The bridge origin is not https. Acceptable only for a local development build.'); // loopback for the simulator. A packaged app must never be allowed to send the device
// credential and recordings over plain HTTP to a LAN or public host.
const { protocol, hostname } = new URL(origin);
const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
if (protocol !== 'https:' && !(protocol === 'http:' && loopback)) {
console.error('[manifest] HERMEVEN_BRIDGE_ORIGIN must be https:// (plain http is accepted only for loopback).');
process.exit(1);
}
if (protocol === 'http:') {
console.warn('[manifest] Loopback HTTP origin: this build is for the simulator only and cannot work on a phone.');
} }
const template = readFileSync(resolve(here, '../app.template.json'), 'utf8'); const template = readFileSync(resolve(here, '../app.template.json'), 'utf8');
const out = resolve(here, '../dist-manifest/app.json'); const out = process.env.HERMEVEN_MANIFEST_OUT ?? resolve(here, '../dist-manifest/app.json');
mkdirSync(dirname(out), { recursive: true }); mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin)); writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin));
console.log(`[manifest] wrote ${out}`); console.log(`[manifest] wrote ${out}`);
+131 -38
View File
@@ -16,8 +16,14 @@ interface Stored {
tokenExpiresAt: string; tokenExpiresAt: string;
pairingExpiresAt: string; pairingExpiresAt: string;
conversationId: string | null; conversationId: string | null;
/** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */ /**
* The request id of a turn that may exist on the bridge. Written BEFORE the first submit and
* cleared only on a definitive answer: a terminal result, a definite rejection, or the bridge
* confirming it has no such turn. After a restart it is re-attached by polling.
*/
activeRequestId: string | null; activeRequestId: string | null;
/** The user abandoned that turn but the bridge has not yet acknowledged the cancel. */
activeCancelled: boolean;
} }
export interface DiagEntry { export interface DiagEntry {
@@ -81,6 +87,8 @@ export class Controller {
private pending: PendingInput | null = null; private pending: PendingInput | null = null;
private lastTurn: TurnResult | null = null; private lastTurn: TurnResult | null = null;
private hudReady = false; private hudReady = false;
private creating: { epoch: number; promise: Promise<string> } | null = null;
private createChain: Promise<void> = Promise.resolve();
private stopped = false; private stopped = false;
private ticker: ReturnType<typeof setInterval> | null = null; private ticker: ReturnType<typeof setInterval> | null = null;
private readonly log: DiagEntry[] = []; private readonly log: DiagEntry[] = [];
@@ -134,13 +142,16 @@ export class Controller {
} }
} }
} }
// A turn the user had abandoned is not shown again; its cancel is simply delivered now.
const abandoned = this.stored?.activeCancelled ? this.stored.activeRequestId : null;
this.dispatch({ this.dispatch({
type: 'init', type: 'init',
paired: this.stored !== null, paired: this.stored !== null,
conversationId: this.stored?.conversationId ?? null, conversationId: this.stored?.conversationId ?? null,
captureMaxSeconds, captureMaxSeconds,
resumeRequestId: this.stored?.activeRequestId ?? null, resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null),
}); });
if (abandoned) void this.cancelTurn(abandoned);
} }
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */ /** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
@@ -180,6 +191,7 @@ export class Controller {
pairingExpiresAt: credential.pairing_expires_at, pairingExpiresAt: credential.pairing_expires_at,
conversationId: null, conversationId: null,
activeRequestId: null, activeRequestId: null,
activeCancelled: false,
}; };
await this.save(); await this.save();
this.note('pairing', `paired as ${credential.device_id}`); this.note('pairing', `paired as ${credential.device_id}`);
@@ -210,7 +222,13 @@ export class Controller {
async renew(): Promise<void> { async renew(): Promise<void> {
if (!this.client || !this.stored) return; if (!this.client || !this.stored) return;
const credential = await this.client.renew(); let credential;
try {
credential = await this.client.renew();
} catch (err) {
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
throw err;
}
this.client.token = credential.token; this.client.token = credential.token;
this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at }; this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at };
await this.save(); await this.save();
@@ -224,6 +242,7 @@ export class Controller {
this.status = await this.client.device(); this.status = await this.client.device();
} catch (err) { } catch (err) {
this.note('bridge', `status check failed: ${describe(err)}`); this.note('bridge', `status check failed: ${describe(err)}`);
if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
} }
this.emit(); this.emit();
} }
@@ -275,7 +294,7 @@ export class Controller {
case 'cancel_turn': case 'cancel_turn':
return await this.cancelTurn(effect.requestId); return await this.cancelTurn(effect.requestId);
case 'create_conversation': case 'create_conversation':
return await this.createConversation(effect.generation); return await this.createConversation(effect.epoch);
case 'exit_dialog': case 'exit_dialog':
return await this.device.requestExit(); return await this.device.requestExit();
} }
@@ -296,9 +315,15 @@ export class Controller {
this.capture = capture; this.capture = capture;
this.micOpen = true; this.micOpen = true;
const ok = await this.device.startMic(); const ok = await this.device.startMic();
if (this.capture !== capture) { if (this.capture !== capture || this.stale(generation)) {
// Cancelled while the microphone was opening. // Cancelled while the microphone was opening. Stop unconditionally unless a newer
if (!this.capture) await this.closeMic(); // capture now owns the microphone: a stop that turns out to be redundant is harmless.
if (!this.capture || this.capture === capture) {
this.capture = null;
this.micOpen = false;
this.stopTicker();
await this.device.stopMic();
}
return; return;
} }
if (!ok) { if (!ok) {
@@ -364,24 +389,64 @@ export class Controller {
return this.stopped || generation !== this.state.generation; return this.stopped || generation !== this.state.generation;
} }
private async ensureConversation(): Promise<string> { /**
if (this.state.conversationId) return this.state.conversationId; * The current conversation id, creating one if there is none. At most one create is in
const created = await this.client!.createConversation(); * flight per conversation epoch, and creates are sent strictly one after another, so the
if (this.stored) { * bridge and the app can never disagree about which conversation is the live one: the last
this.stored = { ...this.stored, conversationId: created.conversation_id }; * create the app sent is the last one the bridge processed.
await this.save(); */
} private ensureConversation(): Promise<string> {
this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id }); if (this.state.conversationId) return Promise.resolve(this.state.conversationId);
return created.conversation_id; const epoch = this.state.conversationEpoch;
if (this.creating && this.creating.epoch === epoch) return this.creating.promise;
const client = this.client;
const promise = this.createChain.then(async () => {
if (!client || this.stopped || epoch !== this.state.conversationEpoch) throw new StaleConversationError();
const created = await client.createConversation();
// Checked BEFORE anything is stored: a result for a conversation the user has since
// replaced (or for a pairing that has ended) is dropped, not persisted.
if (this.stopped || epoch !== this.state.conversationEpoch || this.client !== client) throw new StaleConversationError();
if (this.stored) {
this.stored = { ...this.stored, conversationId: created.conversation_id };
await this.save();
}
this.note('conversation', `conversation ${created.conversation_id}`);
this.dispatch({ type: 'conversation_created', epoch, conversationId: created.conversation_id });
return created.conversation_id;
});
this.createChain = promise.then(
() => undefined,
() => undefined,
);
const entry = { epoch, promise };
this.creating = entry;
void this.createChain.then(() => {
if (this.creating === entry) this.creating = null;
});
return promise;
} }
private async submit(generation: number, requestId: string): Promise<void> { private async submit(generation: number, requestId: string): Promise<void> {
const pending = this.pending; const pending = this.pending;
if (!this.client || !pending || pending.requestId !== requestId) return; if (!this.client || !pending || pending.requestId !== requestId) return;
// Remember the request id before anything is sent. From here until the bridge gives a
// definite answer, this request may or may not exist there; if the page dies in between,
// the next start re-attaches to it by id instead of forgetting a turn that is running.
await this.setActiveRequest(requestId);
for (let attempt = 1; ; attempt++) { for (let attempt = 1; ; attempt++) {
if (this.stale(generation)) return; if (this.stale(generation)) return;
try { try {
const conversationId = await this.ensureConversation(); let conversationId: string;
try {
conversationId = await this.ensureConversation();
} catch (err) {
if (!(err instanceof StaleConversationError)) throw err;
// The conversation was replaced while it was being created; use the new one.
if (this.stale(generation)) return;
attempt -= 1;
continue;
}
if (this.stale(generation)) return; if (this.stale(generation)) return;
const base = { requestId, conversationId, locale: this.options.locale }; const base = { requestId, conversationId, locale: this.options.locale };
// The same request id on every attempt: the bridge deduplicates, so a retry after a // The same request id on every attempt: the bridge deduplicates, so a retry after a
@@ -396,15 +461,16 @@ export class Controller {
void this.cancelTurn(requestId); void this.cancelTurn(requestId);
return; return;
} }
await this.setActiveRequest(requestId);
this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`); this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`);
this.onResult(generation, result); this.onResult(generation, result);
if (!result.terminal) await this.poll(generation, requestId); if (!result.terminal) await this.poll(generation, requestId);
return; return;
} catch (err) { } catch (err) {
if (err instanceof BridgeApiError) { if (err instanceof BridgeApiError) {
// A contract error is a definite "this turn was not created".
this.note('turn', `rejected: ${err.body.code}`); this.note('turn', `rejected: ${err.body.code}`);
this.pending = null; this.pending = null;
await this.setActiveRequest(null);
if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) }); if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) });
await this.afterAuthFailure(err); await this.afterAuthFailure(err);
return; return;
@@ -412,6 +478,8 @@ export class Controller {
if (!(err instanceof BridgeNetworkError)) throw err; if (!(err instanceof BridgeNetworkError)) throw err;
this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`); this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`);
if (attempt >= this.submitAttempts) { if (attempt >= this.submitAttempts) {
// Ambiguous: a request may have been admitted even though no reply came back. The
// request id stays stored; a retry or a restart reconciles under the same id.
if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' }); if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' });
return; return;
} }
@@ -439,8 +507,13 @@ export class Controller {
if (this.stale(generation)) return; if (this.stale(generation)) return;
if (err instanceof BridgeApiError) { if (err instanceof BridgeApiError) {
this.note('turn', `status rejected: ${err.body.code}`); this.note('turn', `status rejected: ${err.body.code}`);
// not_found is the bridge confirming the turn does not exist: it was never admitted.
await this.setActiveRequest(null); await this.setActiveRequest(null);
this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) }); const error: HudError =
err.body.code === 'not_found'
? { code: 'not_delivered', hud: 'Your last request did not reach the bridge. Please ask again.', retryable: true }
: this.hudError(err);
this.dispatch({ type: 'turn_rejected', generation, error });
await this.afterAuthFailure(err); await this.afterAuthFailure(err);
return; return;
} }
@@ -458,7 +531,7 @@ export class Controller {
let pages: string[] | null = null; let pages: string[] | null = null;
if (result.terminal) { if (result.terminal) {
this.lastTurn = result; this.lastTurn = result;
void this.setActiveRequest(null); void this.clearActiveRequest(result.request_id);
this.note( this.note(
'turn', 'turn',
`done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` + `done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` +
@@ -479,42 +552,48 @@ export class Controller {
} }
private async cancelTurn(requestId: string): Promise<void> { private async cancelTurn(requestId: string): Promise<void> {
await this.setActiveRequest(null); // Keep the id, marked as abandoned, until the bridge acknowledges the cancel. If the cancel
if (!this.client) return; // cannot be delivered now it is retried on the next start, so an abandoned turn is not
// left running unnoticed and is never shown to the user again.
if (this.stored && this.stored.activeRequestId === requestId && !this.stored.activeCancelled) {
this.stored = { ...this.stored, activeCancelled: true };
await this.save();
}
const client = this.client;
if (!client) return;
for (let attempt = 1; attempt <= 3; attempt++) { for (let attempt = 1; attempt <= 3; attempt++) {
try { try {
const result = await this.client.cancelTurn(requestId); const result = await client.cancelTurn(requestId);
this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`); this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`);
await this.clearActiveRequest(requestId);
return; return;
} catch (err) { } catch (err) {
if (err instanceof BridgeApiError) { if (err instanceof BridgeApiError) {
// not_found: the request never reached the bridge, so there is nothing to cancel. // not_found: the request never reached the bridge, so there is nothing to cancel.
this.note('turn', `cancel answered ${err.body.code}`); this.note('turn', `cancel answered ${err.body.code}`);
await this.clearActiveRequest(requestId);
await this.afterAuthFailure(err);
return; return;
} }
if (this.stopped) return;
await sleep(this.submitRetryMs); await sleep(this.submitRetryMs);
} }
} }
this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`); this.note('turn', `cancel for ${requestId} could not be delivered yet; it will be retried`);
} }
private async createConversation(generation: number): Promise<void> { private async createConversation(epoch: number): Promise<void> {
if (!this.client) return; if (!this.client || epoch !== this.state.conversationEpoch) return;
try { try {
const created = await this.client.createConversation(); await this.ensureConversation();
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) { } catch (err) {
if (err instanceof StaleConversationError) return;
const error: HudError = const error: HudError =
err instanceof BridgeApiError err instanceof BridgeApiError
? this.hudError(err) ? this.hudError(err)
: { code: 'network', hud: 'Could not reach the bridge.', retryable: true }; : { code: 'network', hud: 'Could not reach the bridge.', retryable: true };
this.note('conversation', `create failed: ${describe(err)}`); this.note('conversation', `create failed: ${describe(err)}`);
this.dispatch({ type: 'conversation_failed', generation, error }); this.dispatch({ type: 'conversation_failed', epoch, error });
if (err instanceof BridgeApiError) await this.afterAuthFailure(err); if (err instanceof BridgeApiError) await this.afterAuthFailure(err);
} }
} }
@@ -588,8 +667,11 @@ export class Controller {
} }
private async afterAuthFailure(err: BridgeApiError): Promise<void> { private async afterAuthFailure(err: BridgeApiError): Promise<void> {
if (err.body.code !== 'unauthorized') return; if (err.body.code !== 'unauthorized' && err.body.code !== 'credential_expired') return;
// Revoked or unknown credential: holding on to it helps nobody. if (!this.stored) return;
// Revoked, unknown or expired: the stored credential can no longer do anything (an expired
// token cannot even renew itself), so it is forgotten and the pairing screen comes back.
this.note('auth', `credential no longer accepted: ${err.body.code}`);
await this.forget(); await this.forget();
this.dispatch({ type: 'unpaired' }); this.dispatch({ type: 'unpaired' });
} }
@@ -607,11 +689,16 @@ export class Controller {
} }
private async setActiveRequest(requestId: string | null): Promise<void> { private async setActiveRequest(requestId: string | null): Promise<void> {
if (!this.stored || this.stored.activeRequestId === requestId) return; if (!this.stored || (this.stored.activeRequestId === requestId && !this.stored.activeCancelled)) return;
this.stored = { ...this.stored, activeRequestId: requestId }; this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false };
await this.save(); await this.save();
} }
/** Clear the stored request id only if it is still this one (a newer turn may own the slot). */
private async clearActiveRequest(requestId: string): Promise<void> {
if (this.stored?.activeRequestId === requestId) await this.setActiveRequest(null);
}
private async load(): Promise<Stored | null> { private async load(): Promise<Stored | null> {
try { try {
const raw = await this.device.storageGet(STORAGE_KEY); const raw = await this.device.storageGet(STORAGE_KEY);
@@ -626,6 +713,7 @@ export class Controller {
pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''), pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''),
conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null, conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null,
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null, activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
activeCancelled: parsed.activeCancelled === true,
}; };
} catch { } catch {
return null; return null;
@@ -670,6 +758,11 @@ export function pollDelay(elapsedMs: number): number {
return 1000; return 1000;
} }
/** The conversation this create was for has been replaced; its result must not be used. */
class StaleConversationError extends Error {
override name = 'StaleConversationError';
}
function describe(err: unknown): string { function describe(err: unknown): string {
if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`; if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`;
if (err instanceof Error) return `${err.name}: ${err.message}`; if (err instanceof Error) return `${err.name}: ${err.message}`;
+3 -1
View File
@@ -93,7 +93,9 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
return { body: 'Glasses disconnected.', status: 'Reconnect to continue' }; return { body: 'Glasses disconnected.', status: 'Reconnect to continue' };
} }
return state.canResend return state.canResend
? { body: 'No connection to the bridge.\n\nYour request has not been sent.', status: 'Tap: retry · Double-tap: discard' } ? // Deliberately not "has not been sent": a request can be admitted even when no reply
// comes back, so the honest statement is that it is unconfirmed.
{ body: 'No connection to the bridge.\n\nYour request is not confirmed yet.', status: 'Tap: retry · Double-tap: discard' }
: { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' }; : { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' };
case 'error': case 'error':
+38 -11
View File
@@ -38,6 +38,10 @@ export interface AppState {
*/ */
generation: number; generation: number;
conversationId: string | null; conversationId: string | null;
/** Bumped whenever the conversation is reset; a create result from an older epoch is dropped. */
conversationEpoch: number;
/** A new conversation has been requested and not yet confirmed. */
creatingConversation: boolean;
requestId: string | null; requestId: string | null;
captureStartedAt: number | null; captureStartedAt: number | null;
captureMaxSeconds: number; captureMaxSeconds: number;
@@ -57,6 +61,8 @@ export const initialState: AppState = {
phase: 'unpaired', phase: 'unpaired',
generation: 0, generation: 0,
conversationId: null, conversationId: null,
conversationEpoch: 0,
creatingConversation: false,
requestId: null, requestId: null,
captureStartedAt: null, captureStartedAt: null,
captureMaxSeconds: 30, captureMaxSeconds: 30,
@@ -83,8 +89,8 @@ export type AppEvent =
| { type: 'capture_started'; generation: number; at: number } | { type: 'capture_started'; generation: number; at: number }
| { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' } | { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' }
| { type: 'capture_limit'; generation: number } | { type: 'capture_limit'; generation: number }
| { type: 'conversation_created'; generation: number; conversationId: string } | { type: 'conversation_created'; epoch: number; conversationId: string }
| { type: 'conversation_failed'; generation: number; error: HudError } | { type: 'conversation_failed'; epoch: number; error: HudError }
/** `pages` is the already-paginated plain-text answer when the result carries one. */ /** `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_update'; generation: number; result: TurnResult; pages: string[] | null }
| { type: 'turn_rejected'; generation: number; error: HudError } | { type: 'turn_rejected'; generation: number; error: HudError }
@@ -101,7 +107,7 @@ export type Effect =
| { type: 'resubmit'; generation: number; requestId: string } | { type: 'resubmit'; generation: number; requestId: string }
| { type: 'poll'; generation: number; requestId: string } | { type: 'poll'; generation: number; requestId: string }
| { type: 'cancel_turn'; requestId: string } | { type: 'cancel_turn'; requestId: string }
| { type: 'create_conversation'; generation: number } | { type: 'create_conversation'; epoch: number }
| { type: 'exit_dialog' }; | { type: 'exit_dialog' };
export interface Step { export interface Step {
@@ -153,6 +159,7 @@ export function reduce(state: AppState, event: AppEvent): Step {
generation: state.generation + 1, generation: state.generation + 1,
captureMaxSeconds: event.captureMaxSeconds, captureMaxSeconds: event.captureMaxSeconds,
conversationId: event.conversationId, conversationId: event.conversationId,
conversationEpoch: state.conversationEpoch + 1,
}; };
if (!event.paired) return same({ ...base, phase: 'unpaired' }); if (!event.paired) return same({ ...base, phase: 'unpaired' });
if (event.resumeRequestId) { if (event.resumeRequestId) {
@@ -169,7 +176,12 @@ export function reduce(state: AppState, event: AppEvent): Step {
case 'unpaired': { case 'unpaired': {
const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : []; const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : [];
return { return {
state: { ...initialState, generation: state.generation + 1, captureMaxSeconds: state.captureMaxSeconds }, state: {
...initialState,
generation: state.generation + 1,
conversationEpoch: state.conversationEpoch + 1,
captureMaxSeconds: state.captureMaxSeconds,
},
effects, effects,
}; };
} }
@@ -238,21 +250,36 @@ export function reduce(state: AppState, event: AppEvent): Step {
case 'new_conversation': { case 'new_conversation': {
// Only from a resting state: a reset must never be mistaken for cancelling the backend. // Only from a resting state: a reset must never be mistaken for cancelling the backend.
if (!IDLE.has(state.phase)) return same(state); if (!IDLE.has(state.phase)) return same(state);
const generation = state.generation + 1; // One is already on its way: a second press must not start a second create.
if (state.creatingConversation) return same(state);
const conversationEpoch = state.conversationEpoch + 1;
return { return {
state: { ...clearTurn(state), phase: 'ready', generation, conversationId: null, notice: 'New conversation' }, state: {
effects: [{ type: 'create_conversation', generation }], ...clearTurn(state),
phase: 'ready',
generation: state.generation + 1,
conversationId: null,
conversationEpoch,
creatingConversation: true,
notice: 'New conversation',
},
effects: [{ type: 'create_conversation', epoch: conversationEpoch }],
}; };
} }
case 'conversation_created': { case 'conversation_created': {
if (event.generation !== state.generation) return same(state); // Keyed to the conversation epoch, not the turn generation: the user may already have
return same({ ...state, conversationId: event.conversationId }); // started a question (which bumps the generation) while the conversation was being made.
if (event.epoch !== state.conversationEpoch) return same(state);
return same({ ...state, conversationId: event.conversationId, creatingConversation: false });
} }
case 'conversation_failed': { case 'conversation_failed': {
if (event.generation !== state.generation) return same(state); if (event.epoch !== state.conversationEpoch) return same(state);
return same({ ...clearTurn(state), phase: 'error', error: event.error }); // If a question is in flight, its own submit reports the failure; only a resting screen
// is replaced by the error.
if (!IDLE.has(state.phase)) return same({ ...state, creatingConversation: false });
return same({ ...clearTurn(state), creatingConversation: false, phase: 'error', error: event.error });
} }
case 'capture_started': { case 'capture_started': {
+48 -24
View File
@@ -14,23 +14,14 @@ import type { DevicePort } from './port.ts';
const BODY = { id: 1, name: 'body' } as const; const BODY = { id: 1, name: 'body' } as const;
const STATUS = { id: 2, name: 'status' } 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. */ /** A flaky BLE hop can hang a host call for a long time; never let one block the UI forever. */
const CALL_TIMEOUT_MS = 8000; export const CALL_TIMEOUT_MS = 8000;
function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> { interface Bounded<T> {
return new Promise((resolve) => { /** The caller's answer: the real result, or the fallback if the host took too long. */
const timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS); value: T;
promise.then( /** True when `value` is the fallback because the host had not answered in time. */
(value) => { timedOut: boolean;
clearTimeout(timer);
resolve(value);
},
() => {
clearTimeout(timer);
resolve(fallback);
},
);
});
} }
/** /**
@@ -43,15 +34,37 @@ export class EvenDevice implements DevicePort {
private pending: HudFrame | null = null; private pending: HudFrame | null = null;
private flushing = false; private flushing = false;
private ready = false; private ready = false;
/** All host calls go through one queue: concurrent bridge calls are documented as unsafe. */ /**
* All host calls go through one queue: concurrent bridge calls are documented as unsafe.
* The queue advances only when the host call has ACTUALLY settled. A caller that gives up
* waiting gets a fallback answer, but the next host call still waits its turn, so two calls
* are never in flight together and a late completion is always followed, in order, by
* whatever was queued behind it.
*/
private queue: Promise<unknown> = Promise.resolve(); private queue: Promise<unknown> = Promise.resolve();
constructor(private readonly bridge: EvenAppBridge) {} constructor(
private readonly bridge: EvenAppBridge,
private readonly callTimeoutMs: number = CALL_TIMEOUT_MS,
) {}
private enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> { private enqueueBounded<T>(call: () => Promise<T>, fallback: T): Promise<Bounded<T>> {
const next = this.queue.then(() => withTimeout(call(), fallback)); // What the host really does, serialised behind every earlier call.
this.queue = next.catch(() => undefined); const settled: Promise<T> = this.queue.then(call).catch(() => fallback);
return next; this.queue = settled;
// What the caller sees: the same result, or the fallback after the timeout. The timer
// starts when the call is requested, so time spent queued behind a stuck call counts.
return new Promise((resolve) => {
const timer = setTimeout(() => resolve({ value: fallback, timedOut: true }), this.callTimeoutMs);
void settled.then((value) => {
clearTimeout(timer);
resolve({ value, timedOut: false });
});
});
}
private async enqueue<T>(call: () => Promise<T>, fallback: T): Promise<T> {
return (await this.enqueueBounded(call, fallback)).value;
} }
async init(frame: HudFrame): Promise<boolean> { async init(frame: HudFrame): Promise<boolean> {
@@ -136,10 +149,21 @@ export class EvenDevice implements DevicePort {
} }
} }
startMic(): Promise<boolean> { async startMic(): Promise<boolean> {
return this.enqueue(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false); const started = await this.enqueueBounded(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false);
if (started.timedOut) {
// The caller is being told "the microphone did not open" and will not stop it. But the
// host may still open it later. Queue a stop now: it runs strictly after the pending
// start settles, so whatever the start ends up doing, the microphone finishes closed.
void this.enqueueBounded(() => this.bridge.audioControl(false), false);
}
return started.value;
} }
/**
* Always sends the stop, even if a start is still pending or was never confirmed: closing a
* closed microphone is harmless, leaving one open is not. Queued behind any pending start.
*/
async stopMic(): Promise<void> { async stopMic(): Promise<void> {
await this.enqueue(() => this.bridge.audioControl(false), false); await this.enqueue(() => this.bridge.audioControl(false), false);
} }
+23 -3
View File
@@ -35,10 +35,30 @@ export interface BridgeClientOptions {
fetchImpl?: typeof fetch; fetchImpl?: typeof fetch;
} }
/**
* Hosts on which plain HTTP is tolerated: this machine only, for the simulator and the
* browser preview. Exact matches, so `127.0.0.1.example.com` or `localhost.example.com`
* do not qualify, and neither does any LAN or public address.
*/
export function isLoopbackHost(hostname: string): boolean {
return hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
}
/**
* The device credential and the user's recordings travel to this URL, so it must be HTTPS.
* The one exception is HTTP to loopback, which never leaves the machine.
*/
export function normalizeBridgeUrl(raw: string): string { export function normalizeBridgeUrl(raw: string): string {
const url = new URL(raw.trim()); let url: URL;
if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bridge URL must start with https://'); try {
return url.origin + url.pathname.replace(/\/+$/, ''); url = new URL(raw.trim());
} catch {
throw new Error('Enter the bridge address as a full URL, for example https://bridge.example');
}
if (url.username || url.password) throw new Error('The bridge address must not contain a user name or password.');
if (url.protocol === 'https:') return url.origin + url.pathname.replace(/\/+$/, '');
if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.origin + url.pathname.replace(/\/+$/, '');
throw new Error('The bridge address must start with https://');
} }
export class BridgeClient { export class BridgeClient {
+29 -3
View File
@@ -329,11 +329,37 @@ describe('pairing, restore and conversations', () => {
const s = ready(); const s = ready();
const step = reduce(s, { type: 'new_conversation' }); const step = reduce(s, { type: 'new_conversation' });
expect(step.state.conversationId).toBeNull(); expect(step.state.conversationId).toBeNull();
expect(step.effects).toEqual([{ type: 'create_conversation', generation: step.state.generation }]); expect(step.state.creatingConversation).toBe(true);
const stale = reduce(step.state, { type: 'conversation_created', generation: s.generation, conversationId: 'old' }); expect(step.effects).toEqual([{ type: 'create_conversation', epoch: step.state.conversationEpoch }]);
const stale = reduce(step.state, { type: 'conversation_created', epoch: s.conversationEpoch, conversationId: 'old' });
expect(stale.state.conversationId).toBeNull(); expect(stale.state.conversationId).toBeNull();
const fresh = reduce(step.state, { type: 'conversation_created', generation: step.state.generation, conversationId: 'new' }); const fresh = reduce(step.state, { type: 'conversation_created', epoch: step.state.conversationEpoch, conversationId: 'new' });
expect(fresh.state.conversationId).toBe('new'); expect(fresh.state.conversationId).toBe('new');
expect(fresh.state.creatingConversation).toBe(false);
});
it('a second "new conversation" while one is being created starts nothing (CODY-009)', () => {
const first = reduce(ready(), { type: 'new_conversation' });
const second = reduce(first.state, { type: 'new_conversation' });
expect(second.state).toBe(first.state);
expect(second.effects).toEqual([]);
});
it('the conversation result is accepted even after a question has started, because it is keyed to the conversation, not the turn (CODY-009)', () => {
const created = reduce(ready(), { type: 'new_conversation' });
const asking = reduce(created.state, { type: 'submit_text', freshId: ID1, text: 'hi' });
expect(asking.state.generation).toBeGreaterThan(created.state.generation);
const done = reduce(asking.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'new' });
expect(done.state.conversationId).toBe('new');
expect(done.state.phase).toBe('thinking');
});
it('a conversation result from before a re-pair or a later reset is dropped', () => {
const created = reduce(ready(), { type: 'new_conversation' });
const repaired = reduce(created.state, { type: 'init', paired: true, conversationId: null, captureMaxSeconds: 30, resumeRequestId: null });
expect(reduce(repaired.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'x' }).state).toBe(repaired.state);
const failedLate = reduce(repaired.state, { type: 'conversation_failed', epoch: created.state.conversationEpoch, error: { code: 'x', hud: 'x', retryable: false } });
expect(failedLate.state).toBe(repaired.state);
}); });
it('unpairing while listening closes the microphone', () => { it('unpairing while listening closes the microphone', () => {
+5 -3
View File
@@ -11,7 +11,9 @@ HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite
# Read the real value from the phone page: Diagnostics -> "Page origin". # Read the real value from the phone page: Diagnostics -> "Page origin".
HERMEVEN_ALLOWED_ORIGINS= HERMEVEN_ALLOWED_ORIGINS=
# Built-in speech-to-text (the default). Model files are downloaded once into this directory. # Built-in speech-to-text (the default). The model is pinned and verified; the running service
# never downloads it and only reads this directory. Populate it at deploy time with
# npm run bridge:cli -- fetch-model
STT_PROVIDER=builtin STT_PROVIDER=builtin
STT_MODEL=onnx-community/whisper-base STT_MODEL=whisper-base
STT_CACHE_DIR=/var/lib/hermeven/models STT_MODEL_DIR=/opt/hermeven/models
+5
View File
@@ -20,11 +20,16 @@ RestartSec=3
TimeoutStopSec=20 TimeoutStopSec=20
# Hardening # Hardening
# Everything the service creates is owner-only (database, WAL, SHM).
UMask=0077
StateDirectory=hermeven
StateDirectoryMode=0700
NoNewPrivileges=true NoNewPrivileges=true
PrivateTmp=true PrivateTmp=true
ProtectSystem=strict ProtectSystem=strict
ProtectHome=true ProtectHome=true
ReadWritePaths=/var/lib/hermeven ReadWritePaths=/var/lib/hermeven
# The verified speech model is read-only to the service: it lives under /opt (see ProtectSystem).
ProtectKernelTunables=true ProtectKernelTunables=true
ProtectControlGroups=true ProtectControlGroups=true
RestrictSUIDSGID=true RestrictSUIDSGID=true
+1 -1
View File
@@ -95,7 +95,7 @@ Defined in `packages/contracts/src/errors.ts`. Codes are stable; a code is never
|---|---|---| |---|---|---|
| `invalid_request`, `unsupported_schema_version`, `unsupported_media`, `payload_too_large` | The request was malformed. | no | | `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 | | `unauthorized`, `credential_expired`, `forbidden` | Credential missing, revoked or expired. | no |
| `pairing_invalid`, `pairing_locked` | Wrong code; too many wrong codes. | no | | `pairing_invalid` | The pairing code was wrong, expired or already used. The answer is identical in all three cases. (`pairing_locked` is reserved and no longer returned.) | no |
| `not_found` | Unknown, or belongs to another device. | no | | `not_found` | Unknown, or belongs to another device. | no |
| `request_id_conflict` | Request id reused for different content. | no | | `request_id_conflict` | Request id reused for different content. | no |
| `conversation_busy` | A turn is still running in this conversation. | yes | | `conversation_busy` | A turn is still running in this conversation. | yes |
+1 -1
View File
@@ -40,7 +40,7 @@ exactly in `apps/even-client/package.json`.
| Fastify / @fastify/cors | 5.12.8 / 11.4.3 | | Fastify / @fastify/cors | 5.12.8 / 11.4.3 |
| better-sqlite3 | 13.2.0 | | better-sqlite3 | 13.2.0 |
| @huggingface/transformers (ONNX Runtime 1.30.0) | 4.3.2 | | @huggingface/transformers (ONNX Runtime 1.30.0) | 4.3.2 |
| Speech model | `onnx-community/whisper-base`, `q8` | | Speech model | `onnx-community/whisper-base` at commit `27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c`, `q8`; alternative `onnx-community/whisper-tiny` at `ff4177021cc41f7db950912b73ea4fdf7d01d8e7`. Per-file SHA-256 in `services/bridge/models/`. |
| @sinclair/typebox | 0.34.52 | | @sinclair/typebox | 0.34.52 |
| pino | 10.4.0 | | pino | 10.4.0 |
+16 -4
View File
@@ -29,7 +29,7 @@ weights:
| Memory after transcribing | about 0.8 GB | | Memory after transcribing | about 0.8 GB |
| 11 s of speech, process pinned to one core | about 1.7 s | | 11 s of speech, process pinned to one core | about 1.7 s |
| Same, `whisper-tiny` | about 1.2 s, about 0.6 GB | | Same, `whisper-tiny` | about 1.2 s, about 0.6 GB |
| Model download on first start | about 80 MB (`base`), cached afterwards | | Model download at deploy time (`fetch-model`) | 79 MB (`whisper-base`), 4 s on the desktop's connection |
| Longest pause of the bridge's event loop while transcribing | 3 ms (the model runs in a worker thread) | | Longest pause of the bridge's event loop while transcribing | 3 ms (the model runs in a worker thread) |
Pinning to one core made no difference to speed, so extra cores will not help; a single droplet Pinning to one core made no difference to speed, so extra cores will not help; a single droplet
@@ -41,8 +41,8 @@ Suggested starting point, to be confirmed by measuring on the droplet: **2 GB RA
for the bridge alone. 1 GB is likely too tight alongside the OS. If Hermes shares the droplet, for the bridge alone. 1 GB is likely too tight alongside the OS. If Hermes shares the droplet,
add whatever Hermes needs; that was not measured. add whatever Hermes needs; that was not measured.
If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisper-tiny` If transcription is too slow on the droplet, set `STT_MODEL=whisper-tiny` (faster, less
(faster, less accurate) or, for English only, `onnx-community/whisper-base.en`. accurate) and run `fetch-model` again.
## Steps ## Steps
@@ -59,11 +59,22 @@ If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisp
needed: the bridge runs through `tsx`.) needed: the bridge runs through `tsx`.)
5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it 5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it
in, `chmod 600`, `chown hermeven`. in, `chmod 600`, `chown hermeven`.
5a. **Speech model.** As root (not the service user), fetch and verify the pinned model into a
directory the service can read but not write:
```sh
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- fetch-model
HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- verify-model
```
Every file is checked against the SHA-256 committed in `services/bridge/models/`. The running
service never downloads anything: it re-verifies these files each time it loads the model and
refuses to load if one is missing or different. This is the only step that needs outbound
access to huggingface.co.
6. **Hermes.** Enable its API server with a key, bound to `127.0.0.1`. Use a read-only or test 6. **Hermes.** Enable its API server with a key, bound to `127.0.0.1`. Use a read-only or test
profile first. profile first.
7. **Service.** Copy `deploy/hermeven-bridge.service` to `/etc/systemd/system/`, then 7. **Service.** Copy `deploy/hermeven-bridge.service` to `/etc/systemd/system/`, then
`systemctl daemon-reload && systemctl enable --now hermeven-bridge`. Watch `systemctl daemon-reload && systemctl enable --now hermeven-bridge`. Watch
`journalctl -u hermeven-bridge -f` for `stt.ready` (the first start downloads the model). `journalctl -u hermeven-bridge -f` for `stt.ready`. `stt.load_failed` with `reason: missing`
or `mismatch` means step 5a was skipped or the files changed.
8. **TLS.** Put `deploy/Caddyfile.example` at `/etc/caddy/Caddyfile` with your hostname, reload 8. **TLS.** Put `deploy/Caddyfile.example` at `/etc/caddy/Caddyfile` with your hostname, reload
Caddy, then check `curl https://bridge.example.com/healthz`. Caddy, then check `curl https://bridge.example.com/healthz`.
9. **App build.** On your own machine: 9. **App build.** On your own machine:
@@ -80,6 +91,7 @@ If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisp
- Time from `stt.loading` to `stt.ready`, and memory of the service after a few questions. - Time from `stt.loading` to `stt.ready`, and memory of the service after a few questions.
- `transcribe_ms` for a few real questions (the phone page shows it per question). - `transcribe_ms` for a few real questions (the phone page shows it per question).
- That `curl http://<droplet-ip>:8787/healthz` from outside **fails** (bridge not exposed). - That `curl http://<droplet-ip>:8787/healthz` from outside **fails** (bridge not exposed).
- `stat -c '%a' /var/lib/hermeven /var/lib/hermeven/hermeven.sqlite*` shows `700` and `600`.
- That the unit's hardening options do not stop the model loading. `ProtectSystem=strict` and - That the unit's hardening options do not stop the model loading. `ProtectSystem=strict` and
`MemoryMax` in particular are untested with ONNX Runtime. `MemoryMax` in particular are untested with ONNX Runtime.
+2 -1
View File
@@ -101,7 +101,8 @@ a suspended stream. The microphone is never reopened without a new tap.
Decision (updated after Dan asked for speech-to-text to be built in and to run on a droplet): Decision (updated after Dan asked for speech-to-text to be built in and to run on a droplet):
the bridge runs OpenAI's Whisper model itself, on the CPU, through ONNX Runtime the bridge runs OpenAI's Whisper model itself, on the CPU, through ONNX Runtime
(`@huggingface/transformers` 4.3.2, model `onnx-community/whisper-base`, 8-bit weights). No (`@huggingface/transformers` 4.3.2, model `onnx-community/whisper-base` pinned to a commit and
verified by SHA-256, 8-bit weights; fetched ahead of time, never downloaded by the running bridge). No
provider account, and recordings never leave the bridge host. An adapter for any external provider account, and recordings never leave the bridge host. An adapter for any external
OpenAI-compatible transcription endpoint remains as an alternative. OpenAI-compatible transcription endpoint remains as an alternative.
+74
View File
@@ -0,0 +1,74 @@
# Handoff for Cody, Round 3
From: Claude (implementation). Date: 2026-11-18.
**Not reviewed.** Cody's Round 2 verdict (NEEDS CHANGES) applies to `3d5691d` only. Nothing below
is a claim that any finding is closed; that is Cody's call on the new SHA.
| Item | Value |
|---|---|
| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` |
| Branch | `cody/slice-1-review` |
| Reviewed in Round 2 | `3d5691dfa3e3015f7d0e4f760de60c588ffea0dc` |
| `main` | `0c9dcd864f16782097471e5bbf57cbd701c26616` (unchanged; nothing merged) |
| New head for Round 3 | the tip of `cody/slice-1-review` after this push; the exact SHA is in the push report, since a file cannot contain its own commit id |
## What was done for each finding
| Finding | Change | Where |
|---|---|---|
| CODY-001 | Bridge URL must be HTTPS; HTTP only for `localhost`, `127.x.x.x`, `[::1]` (exact match). Same rule in the manifest generator, which exits 1. URLs with embedded credentials are refused. | `net/bridgeClient.ts`, `scripts/write-manifest.mjs` |
| CODY-002 | The host-call queue advances only when the SDK call has actually settled; the caller's timeout is a separate, bounded answer. A start that times out queues a stop behind it. The controller stops unconditionally when a capture was abandoned while opening. | `device/evenAdapter.ts`, `core/controller.ts` |
| CODY-003 | The request id is stored before the first submit and cleared only on a terminal result, a definite rejection, or the bridge confirming it has no such turn. An undelivered cancel is remembered and retried at next start. The HUD says "not confirmed yet" instead of "has not been sent". | `core/controller.ts`, `core/hud.ts` |
| CODY-004 | `Devices.revoke` flags every non-terminal turn of the device in the same transaction that revokes it. `TurnEngine.revokeDevice` (HTTP path) applies the flags at once; a one-second sweep applies flags written by the CLI process. Workers abort transcription and ask Hermes to stop. | `devices.ts`, `turns.ts`, `server.ts`, `app.ts` |
| CODY-005 | Manifests pin a 40-character commit id and a SHA-256 and size per file (`services/bridge/models/`). `fetch-model` downloads and verifies; the worker verifies on every load, disables remote models, and loads only from the store. No unpinned configuration exists. | `stt/modelStore.mjs`, `stt/whisperWorker.mjs`, `config.ts`, `cli.ts`, `deploy/*` |
| CODY-006 | Database file is created 0600 before SQLite opens it, in a 0700 directory; WAL and SHM inherit. Unit sets `UMask=0077` and a 0700 state directory. | `db.ts`, `deploy/hermeven-bridge.service`, `docs/deploy-droplet.md` |
| CODY-007 | `credential_expired` is handled like `unauthorized` on every runtime path (submit, poll, cancel, status refresh, renew, conversation create). | `core/controller.ts` |
| CODY-008 | `approval_started_at` is written once, when the approval is first seen (it was previously rewritten on every poll). The agent deadline is stored in a new column and updated in the same write that ends an approval wait. Both are restored after a restart. Schema migration v2. | `turns.ts`, `db.ts` |
| CODY-009 | One in-flight create per conversation epoch, shared by the menu action and the lazy first-turn path; creates are sent strictly in sequence; a result for a replaced conversation is dropped before persistence. A second "new conversation" while one is pending does nothing. | `core/controller.ts`, `core/reducer.ts` |
| CODY-010 | Wrong guesses no longer count against the outstanding code. Brute force is bounded by 49 bits of entropy, a 5-minute lifetime and the per-address limit. Wrong, expired and used codes return the same response. `pairing_locked` is reserved and no longer returned. | `devices.ts`, `server.ts` |
The tests for each are listed in `docs/test-evidence.md` under "Round 3".
## Check results
| Check | Result |
|---|---|
| `npm run typecheck` | exit 0 |
| `npm test` | 182 passed, 0 failed |
| `npm run client:build` | built |
| `npm run test:real-stt` | 11 passed, 0 failed |
| `npm run test:real-hermes` | 9 passed, 0 failed |
| `npm run test:simulator` | 6 passed, 0 failed |
| `git diff --check` | clean |
No check was omitted.
## Decisions made while fixing, for Cody to judge
- **CODY-010 uses entropy and a per-address limit, with no global cap.** A global cap would let a
flood block the owner's own pairing, which is the same denial of service by another route. The
arithmetic is in `docs/security.md`.
- **CODY-009 keys the result check to a conversation epoch, not the turn generation.** A question
asked while the conversation is being created bumps the turn generation; a strict generation
check would throw away the conversation that question is waiting for.
- **CODY-005 removes the automatic first-start download entirely**, including for development.
- **CODY-004 through the CLI is honoured within the sweep interval (1 s)**, not instantly, because
the CLI is a separate process with no channel to the running bridge other than the database.
- **CODY-003: after a restart, a voice question that never reached the bridge cannot be resent**,
because the recording lived only in memory. The user is told to ask again, and only after the
bridge has confirmed it has no record of the request.
## Things the author is unsure about
- `whisperWorker.mjs` and `modelStore.mjs` are plain JavaScript, typed only through a hand-written
declaration file.
- Between verifying the model files and loading them there is a short window; a read-only model
directory closes it, and that is a deployment setting, not something the code enforces.
- The CODY-006 test observes permissions at each `chmod` call, not continuously.
- A device revoked through the CLI while its turn is still being submitted to Hermes relies on the
poll loop noticing the flag after admission.
## Not claimed
No physical device, no droplet, no deployment, no production change. Nothing merged to `main`.
+13 -5
View File
@@ -24,8 +24,9 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`.
| Threat | Control | Tested | | 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 | | 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 | | 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. Revoking also cancels every turn the device has in flight and asks Hermes to stop it, from the HTTP route and from the CLI alike. | 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 | | Credential or recordings sent in clear text | The app refuses any bridge address that is not HTTPS, except HTTP to loopback; the manifest generator refuses to package one. | yes |
| Guessing a pairing code | 10 characters from a 31-symbol alphabet (8.2 x 10^14 values, about 49 bits); valid 5 minutes; single use; a new code voids the old one; 5 attempts per minute per client address. At that rate one address gets 25 guesses per code: a 3 in 10^14 chance. Even a million guesses in the 5 minutes would be about 1 in 10^9. Wrong guesses do not consume the code, so nobody can void the owner's code by guessing; every failure returns the same answer. | 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 | | 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 | | 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 | | 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 |
@@ -34,6 +35,8 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`.
| Request flooding | Per-device turn limit, per-address pairing limit, general per-device limit. | 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 | | 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 | | 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 |
| Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all |
| State files readable by other users | The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that), in a 0700 directory; the systemd unit sets `UMask=0077`. | yes, under umask 0022 |
| 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 | | 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 | | 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 | | Markup injection from an agent answer into the phone page | The page is built with `textContent` only. | by construction |
@@ -48,14 +51,19 @@ Stated so they are not mistaken for protections.
encrypted, and the public SDK offers nothing better. The mitigation is that the credential is 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 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. with developer access to the app's storage, can use it until it is revoked.
1a. **Pairing brute force is bounded by entropy and a per-address limit, not by a lockout.** A
distributed attacker is limited only by how fast the bridge answers. That is still far short
of a useful chance (see the table), but it is a deliberate trade against letting anyone
cancel the owner's code.
2. **Renewal needs only the current token.** A thief who renews before the owner notices keeps 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. access until revoked or until the 90-day pairing lifetime ends.
3. **Audio leaves the phone for the bridge host.** With the default built-in speech model it 3. **Audio leaves the phone for the bridge host.** With the default built-in speech model it
goes no further. With `STT_PROVIDER=openai-compatible` it is sent to that provider, whose goes no further. With `STT_PROVIDER=openai-compatible` it is sent to that provider, whose
retention is outside our control. retention is outside our control.
3a. **The built-in model's files are downloaded from the Hugging Face hub on first start** and 3a. **The pinned hashes are only as trustworthy as the moment they were recorded.** They were
are not pinned to a revision or checked against a known hash. A compromised hub account or taken from the hub on 2026-11-18. They prove the files have not changed since; they do not
path could serve different weights. Pinning a revision is a follow-up. prove the files were benign then. The verified-then-loaded sequence also has a small window
between check and use, which a read-only model directory closes.
3b. **The speech model runs in a worker thread of the bridge process**, not a separate 3b. **The speech model runs in a worker thread of the bridge process**, not a separate
sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the
native runtime could still take the bridge down; systemd restarts it and in-flight turns are native runtime could still take the bridge down; systemd restarts it and in-flight turns are
+6 -2
View File
@@ -1,14 +1,18 @@
# Setup # Setup
Requirements: Node.js 22.13 or later and a Hermes install with the API server enabled. Speech Requirements: Node.js 22.13 or later and a Hermes install with the API server enabled. Speech
recognition is built into the bridge (Whisper on the CPU, about 0.8 GB of memory); the first recognition is built into the bridge (Whisper on the CPU, about 0.8 GB of memory). The model is
start downloads about 80 MB of model files into `data/models`. pinned and verified, and the bridge never downloads it by itself: fetch it once (79 MB).
```sh ```sh
npm ci npm ci
cp .env.example .env # then edit: HERMES_API_KEY at minimum cp .env.example .env # then edit: HERMES_API_KEY at minimum
npm run bridge:cli -- fetch-model # downloads and verifies the pinned speech model
``` ```
The bridge address entered in the app must be `https://`. Plain `http://` is accepted only for
this machine (`localhost`, `127.x.x.x`), which is what the simulator and browser preview use.
## 1. Hermes ## 1. Hermes
Enable the API server for the profile you want to use (see Hermes's "API Server" docs): Enable the API server for the profile you want to use (see Hermes's "API Server" docs):
+59
View File
@@ -253,3 +253,62 @@ unauthenticated `/v1/device` answered 401, `bridge:cli -- pair` printed a code,
- Selecting a contextual-menu item. - Selecting a contextual-menu item.
The checklist for the hardware items is `docs/device-test-plan.md`. The checklist for the hardware items is `docs/device-test-plan.md`.
## Round 3: after Cody's review (2026-11-18)
Cody reviewed `3d5691d` and returned NEEDS CHANGES with ten findings. This section records what
was run after the fixes. Everything above this heading describes the code before them; where a
number differs, this section is the current one.
```
$ npm run typecheck exit 0
$ npm test Test Files 10 passed (10) Tests 182 passed (182) (4 consecutive runs)
$ npm run client:build built; the development pairing hook is absent from the bundle
$ npm run test:real-stt Tests 11 passed (11)
$ npm run test:real-hermes Tests 9 passed (9)
$ npm run test:simulator Tests 6 passed (6) (3 consecutive runs)
$ git diff --check clean
```
No check was omitted. The offline speech test needs unprivileged network namespaces
(`unshare -rn`); they were available here and the test ran. Where they are not, that test prints
"OFFLINE CHECK NOT RUN" rather than passing silently.
### Regression tests added, by finding
| Finding | Test (file) | What it proves |
|---|---|---|
| CODY-001 | `tests/integration/clientSecurity.test.ts` | 15 public, private-LAN and look-alike HTTP addresses rejected; HTTPS accepted; HTTP accepted only for `localhost`, `127.x.x.x`, `[::1]`; the HTTP client refuses a remote HTTP base URL; manifest generation exits 1 and writes nothing for remote HTTP |
| CODY-002 | same file, fake timers and a host whose calls settle on command | Start times out, host opens the microphone late: a stop follows and the microphone ends closed; at most one host call in flight throughout; stop requested during a pending start waits its turn; calls queued behind a stuck call are sent one at a time |
| CODY-003 | `tests/integration/client-bridge.test.ts` | Every reply dropped after the bridge admitted the turn, then a client restart: one Hermes execution for that request, re-attached under the same request id, the HUD never said "not sent"; a request that truly never arrived is reported only after the bridge confirms it has no record; an undeliverable cancel is retried on the next start |
| CODY-004 | `tests/integration/bridge.test.ts` | Revoking over HTTP during a hanging run: one stop request reaches Hermes, the turn settles as cancelled, every later request is 401; the same through the CLI path (database only); revocation during transcription aborts it within 250 ms, in-process and via the sweep; another device's turn is untouched |
| CODY-005 | `services/bridge/test/modelStore.test.ts`, `tests/real-stt/realStt.test.ts` | Branch, tag and short revisions refused; unknown model without a manifest refused; a hub serving different bytes fails the fetch and leaves nothing behind; a changed or missing file refuses to load, with no network request; real pinned artifacts fetched from the real hub and verified; one flipped byte in the real model refuses to load; transcription from a read-only store; transcription inside a network namespace with no interfaces |
| CODY-006 | `services/bridge/test/units.test.ts` | In a child process under umask 0022: directory 0700, database, WAL and SHM 0600, and none of the three was group- or world-accessible at any point observed during creation |
| CODY-007 | `tests/integration/client-bridge.test.ts` | Credential expires during a live session: asking, waiting for an answer, status refresh, renew and new conversation each clear the stored pairing and return to the pairing screen; pairing again works |
| CODY-008 | `tests/integration/bridge.test.ts` | Restart before the original agent deadline: approval timeout still fires 700 ms after the approval was first seen, not after the restart; restart after the original agent deadline: still classified `approval_timeout`; approved after a restart: the paused deadline is stored and survives a second restart; a run that never finishes afterwards ends as `agent_timeout` |
| CODY-009 | `tests/integration/client-bridge.test.ts`, `apps/even-client/test/reducer.test.ts` | "New conversation" twice plus an immediate question with the reply delayed: one create, one stored id equal to the bridge's active conversation, the question succeeds; cancel-and-ask-again during a pending lazy create: one create; a reset during a pending create with the first reply arriving late: its result is dropped before persistence, the second create is not sent until the first settles, app and bridge agree |
| CODY-010 | `tests/integration/bridge.test.ts` | 40 wrong guesses, then the real code still pairs; every failure (wrong, expired, used) is byte-identical; a client is cut off after its 5 attempts per minute |
### Did the new tests have teeth?
Each fix was removed or broken in turn, 20 ways, and the default suite re-run. 16 were caught
at once. Two more exposed missing coverage (the CLI-path sweep during transcription; a database
file created loose and tightened a moment later); tests were added and both are now caught.
The remaining two are redundant safeguards whose removal changes nothing observable: the
directory `chmod` after `mkdir` with mode 0700 (a umask can only remove permissions), and the
final permission pass after a file that was already created owner-only.
### Real deployment sequence, run by hand on the development desktop
`verify-model` on an empty store exited 1 ("missing"). The bridge started without the model,
answered `/healthz`, and logged `stt.load_failed` with `reason: missing` and the command to run.
`fetch-model` downloaded 7 files (79 MB) from huggingface.co at the pinned commit in 4 s and
verified them. `verify-model` then exited 0, and the bridge logged `stt.ready` in 1.1 s. The
state directory was 700 and the database, WAL and SHM files 600.
This was not a droplet. `deploy/` and `docs/deploy-droplet.md` remain unrun.
### Still not tested
Unchanged from the list above: no physical G2, no audio from the glasses, no real model or tools
behind Hermes, no approval prompt from a real Hermes, no droplet, no HTTPS termination.
+1
View File
@@ -19,6 +19,7 @@ export const ERROR_CODES = {
unsupported_media: { http: 415, retryable: false }, unsupported_media: { http: 415, retryable: false },
rate_limited: { http: 429, retryable: true }, rate_limited: { http: 429, retryable: true },
pairing_invalid: { http: 401, retryable: false }, pairing_invalid: { http: 401, retryable: false },
/** Reserved. No longer returned: every pairing failure is `pairing_invalid` (see docs/security.md). */
pairing_locked: { http: 429, retryable: false }, pairing_locked: { http: 429, retryable: false },
internal: { http: 500, retryable: false }, internal: { http: 500, retryable: false },
// turn outcomes (carried in TurnResult.error, HTTP status of the GET is still 200) // turn outcomes (carried in TurnResult.error, HTTP status of the GET is still 200)
+43
View File
@@ -0,0 +1,43 @@
{
"name": "whisper-base",
"model": "onnx-community/whisper-base",
"revision": "27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c",
"dtype": "q8",
"files": [
{
"path": "config.json",
"sha256": "f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b",
"bytes": 2243
},
{
"path": "generation_config.json",
"sha256": "61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0",
"bytes": 3832
},
{
"path": "preprocessor_config.json",
"sha256": "a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d",
"bytes": 339
},
{
"path": "tokenizer.json",
"sha256": "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",
"bytes": 2480466
},
{
"path": "tokenizer_config.json",
"sha256": "2e036e4dbacfdeb7242c7d4ec4149f4a16e86026048f94d1637e3a8ee9c6a573",
"bytes": 282682
},
{
"path": "onnx/encoder_model_quantized.onnx",
"sha256": "5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46",
"bytes": 23201314
},
{
"path": "onnx/decoder_model_merged_quantized.onnx",
"sha256": "fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",
"bytes": 53693315
}
]
}
+43
View File
@@ -0,0 +1,43 @@
{
"name": "whisper-tiny",
"model": "onnx-community/whisper-tiny",
"revision": "ff4177021cc41f7db950912b73ea4fdf7d01d8e7",
"dtype": "q8",
"files": [
{
"path": "config.json",
"sha256": "46aeea0a406afbeb563fc8e59ca10609203df4299af6a83f73752fef369efd2d",
"bytes": 2243
},
{
"path": "generation_config.json",
"sha256": "f5c67e5a4f7102f8cb4d058bc95da276bbc19eeec997267c3bb0f25ef68facd1",
"bytes": 3772
},
{
"path": "preprocessor_config.json",
"sha256": "a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d",
"bytes": 339
},
{
"path": "tokenizer.json",
"sha256": "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566",
"bytes": 2480466
},
{
"path": "tokenizer_config.json",
"sha256": "2a4c4281cf9f51ac6ccc406fdc711a087afe6530f671fa7b80953edc498275ce",
"bytes": 282683
},
{
"path": "onnx/encoder_model_quantized.onnx",
"sha256": "2af4a414ca47aa30f61246017e5fe82b0a8d229281d1255ba666a2a7f6b84d19",
"bytes": 10124990
},
{
"path": "onnx/decoder_model_merged_quantized.onnx",
"sha256": "25e807a962b6349356d0ea5d0dfe530b7e5bf0e2a484aeca0359d03143faddd3",
"bytes": 30719241
}
]
}
+7 -3
View File
@@ -38,14 +38,14 @@ export function sttFromConfig(config: BridgeConfig): SttAdapter {
return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model }); return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model });
} }
if (config.stt.provider === 'builtin') { if (config.stt.provider === 'builtin') {
return new BuiltinWhisperStt({ model: config.stt.model, dtype: config.stt.dtype, cacheDir: config.stt.cacheDir }); return new BuiltinWhisperStt({ manifest: config.stt.manifest!, modelDir: config.stt.modelDir });
} }
return new NoSttAdapter(); return new NoSttAdapter();
} }
export async function createBridge( export async function createBridge(
config: BridgeConfig, config: BridgeConfig,
overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean } = {}, overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean; cancelSweepMs?: number } = {},
): Promise<Bridge> { ): Promise<Bridge> {
const db = openDb(config.dbPath); const db = openDb(config.dbPath);
const hermes = const hermes =
@@ -65,13 +65,16 @@ export async function createBridge(
? (given as Logger) ? (given as Logger)
: pino(given as object) : pino(given as object)
: pino({ level: 'silent' }); : pino({ level: 'silent' });
const engine = new TurnEngine({ db, config, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing }); const engine = new TurnEngine({ db, config, devices, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
const app = await buildServer({ config, devices, hermes, stt, engine, logger }); const app = await buildServer({ config, devices, hermes, stt, engine, logger });
engine.recover(); engine.recover();
engine.purgeExpired(); engine.purgeExpired();
const purge = setInterval(() => engine.purgeExpired(), 60_000); const purge = setInterval(() => engine.purgeExpired(), 60_000);
purge.unref(); purge.unref();
// Picks up revocations made by the operator CLI, which writes to the database directly.
const cancelSweep = setInterval(() => engine.applyCancelFlags(), overrides.cancelSweepMs ?? 1000);
cancelSweep.unref();
return { return {
app, app,
@@ -81,6 +84,7 @@ export async function createBridge(
engine, engine,
async close() { async close() {
clearInterval(purge); clearInterval(purge);
clearInterval(cancelSweep);
await app.close(); await app.close();
await engine.shutdown(); await engine.shutdown();
await stt.close?.(); await stt.close?.();
+34 -7
View File
@@ -2,6 +2,7 @@ import { ConfigError, loadConfig } from './config.ts';
import { openDb } from './db.ts'; import { openDb } from './db.ts';
import { Devices } from './devices.ts'; import { Devices } from './devices.ts';
import { loadEnvFile } from './env.ts'; import { loadEnvFile } from './env.ts';
import { fetchModel, verifyModel } from './stt/modelStore.mjs';
/** /**
* Operator CLI. It talks to the SQLite file directly, so there is no admin * Operator CLI. It talks to the SQLite file directly, so there is no admin
@@ -15,17 +16,45 @@ function usage(): never {
' pair Print a single-use pairing code for one new device', ' pair Print a single-use pairing code for one new device',
' devices List paired devices', ' devices List paired devices',
' revoke <device-id> Revoke a device credential immediately', ' revoke <device-id> Revoke a device credential immediately',
' fetch-model Download the pinned speech model and verify every file',
' verify-model Check the speech model on disk against its pinned hashes',
].join('\n'), ].join('\n'),
); );
process.exit(2); process.exit(2);
} }
function main(): void { async function main(): Promise<void> {
loadEnvFile(); loadEnvFile();
const config = loadConfig(); const config = loadConfig();
const [command, arg] = process.argv.slice(2);
// Model commands run at deploy time, possibly as a different user from the service, and
// must not create or touch the database.
if (command === 'fetch-model' || command === 'verify-model') {
const manifest = config.stt.manifest;
if (!manifest) {
console.log('STT_PROVIDER is not "builtin": there is no speech model to manage.');
return;
}
console.log(`${manifest.model} at ${manifest.revision} (${manifest.dtype}) in ${config.stt.modelDir}`);
if (command === 'fetch-model') {
const result = await fetchModel(config.stt.modelDir, manifest, {
onFile: (path, bytes) => console.log(` fetched ${path} (${bytes} bytes)`),
});
console.log(`Verified ${result.verified} file(s); downloaded ${result.downloaded}.`);
return;
}
const check = await verifyModel(config.stt.modelDir, manifest);
if (!check.ok) {
console.error(`Verification FAILED: ${check.reason} ${check.path}`);
process.exit(1);
}
console.log(`Verified ${manifest.files.length} file(s).`);
return;
}
const db = openDb(config.dbPath); const db = openDb(config.dbPath);
const devices = new Devices(db, config); const devices = new Devices(db, config);
const [command, arg] = process.argv.slice(2);
switch (command) { switch (command) {
case 'pair': { case 'pair': {
@@ -62,9 +91,7 @@ function main(): void {
db.close(); db.close();
} }
try { main().catch((err: unknown) => {
main(); console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err instanceof Error ? err.message : err);
} catch (err) {
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
process.exit(1); process.exit(1);
} });
+41 -16
View File
@@ -1,4 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts'; import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
export interface BridgeConfig { export interface BridgeConfig {
host: string; host: string;
@@ -25,11 +28,11 @@ export interface BridgeConfig {
provider: 'none' | 'builtin' | 'openai-compatible'; provider: 'none' | 'builtin' | 'openai-compatible';
baseUrl: string; baseUrl: string;
apiKey: string; apiKey: string;
/** Hub model id for `builtin`; provider model name for `openai-compatible`. */ /** Bundled manifest name for `builtin`; provider model name for `openai-compatible`. */
model: string; model: string;
/** `builtin` only: weight precision and where model files are cached. */ /** `builtin` only: the pinned artifacts to load, and the directory they are read from. */
dtype: string; manifest: ModelManifest | null;
cacheDir: string; modelDir: string;
}; };
limits: { limits: {
captureMaxSeconds: number; captureMaxSeconds: number;
@@ -46,7 +49,6 @@ export interface BridgeConfig {
tokenTtlSeconds: number; tokenTtlSeconds: number;
pairingTtlSeconds: number; pairingTtlSeconds: number;
pairingCodeTtlSeconds: number; pairingCodeTtlSeconds: number;
pairingCodeMaxFailures: number;
}; };
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */ /** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
resultRetentionSeconds: number; resultRetentionSeconds: number;
@@ -98,6 +100,34 @@ function httpUrl(key: string, raw: string): string {
return raw.replace(/\/+$/, ''); return raw.replace(/\/+$/, '');
} }
/** Manifests shipped with the bridge: `services/bridge/models/<name>.json`. */
export function bundledManifestPath(name: string): string {
return fileURLToPath(new URL(`../models/${name}.json`, import.meta.url));
}
function loadModelManifest(name: string, customPath: string | undefined): ModelManifest {
let path: string;
if (customPath) {
path = customPath;
} else {
if (!/^[a-z0-9][a-z0-9.-]*$/.test(name)) {
throw new ConfigError('STT_MODEL must be the name of a bundled pinned model (whisper-base, whisper-tiny)');
}
path = bundledManifestPath(name);
if (!existsSync(path)) {
throw new ConfigError(
`STT_MODEL "${name}" has no bundled pinned manifest. Use whisper-base or whisper-tiny, or point ` +
'STT_MODEL_MANIFEST at a manifest that pins a commit id and a SHA-256 for every file.',
);
}
}
try {
return validateManifest(JSON.parse(readFileSync(path, 'utf8')));
} catch (err) {
throw new ConfigError(`Speech model manifest could not be used: ${err instanceof Error ? err.message : 'unreadable'}`);
}
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig { export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
const host = env.HERMEVEN_HOST || '127.0.0.1'; const host = env.HERMEVEN_HOST || '127.0.0.1';
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK'); const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
@@ -132,14 +162,10 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
if (sttProvider !== 'none' && sttProvider !== 'builtin' && sttProvider !== 'openai-compatible') { if (sttProvider !== 'none' && sttProvider !== 'builtin' && sttProvider !== 'openai-compatible') {
throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"'); throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"');
} }
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'onnx-community/whisper-base' : ''); const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'whisper-base' : '');
if (sttProvider === 'builtin' && !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(sttModel)) { // The built-in model is always pinned: a commit id plus a SHA-256 for every file. There is
throw new ConfigError('STT_MODEL must be a Hugging Face model id such as onnx-community/whisper-base'); // no unpinned mode. A model that is not bundled needs its own manifest file.
} const sttManifest = sttProvider === 'builtin' ? loadModelManifest(sttModel, env.STT_MODEL_MANIFEST) : null;
const sttDtype = env.STT_DTYPE || 'q8';
if (!['q8', 'q4', 'fp32', 'fp16', 'int8', 'uint8'].includes(sttDtype)) {
throw new ConfigError('STT_DTYPE must be one of q8, q4, fp32, fp16, int8, uint8');
}
let sttBaseUrl = ''; let sttBaseUrl = '';
if (sttProvider === 'openai-compatible') { 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_BASE_URL) throw new ConfigError('STT_BASE_URL is required for STT_PROVIDER=openai-compatible');
@@ -169,8 +195,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
baseUrl: sttBaseUrl, baseUrl: sttBaseUrl,
apiKey: env.STT_API_KEY || '', apiKey: env.STT_API_KEY || '',
model: sttModel, model: sttModel,
dtype: sttDtype, manifest: sttManifest,
cacheDir: env.STT_CACHE_DIR || './data/models', modelDir: env.STT_MODEL_DIR || './data/models',
}, },
limits: { limits: {
captureMaxSeconds, captureMaxSeconds,
@@ -188,7 +214,6 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60), tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60),
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 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), 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), resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
logLevel: env.HERMEVEN_LOG_LEVEL || 'info', logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
+34 -2
View File
@@ -1,5 +1,5 @@
import Database from 'better-sqlite3'; import Database from 'better-sqlite3';
import { mkdirSync } from 'node:fs'; import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs';
import { dirname } from 'node:path'; import { dirname } from 'node:path';
export type Db = Database.Database; export type Db = Database.Database;
@@ -66,15 +66,47 @@ const MIGRATIONS: string[] = [
CREATE INDEX turns_conversation ON turns(conversation_id, state); CREATE INDEX turns_conversation ON turns(conversation_id, state);
CREATE INDEX turns_state ON turns(state); CREATE INDEX turns_state ON turns(state);
`, `,
// v2: the agent deadline is stored, so a restart resumes the same deadline (including time
// already paused for an approval) instead of recomputing it.
`
ALTER TABLE turns ADD COLUMN agent_deadline_at INTEGER;
`,
]; ];
/** The database holds credential hashes and, briefly, question and answer text. */
const DIR_MODE = 0o700;
const FILE_MODE = 0o600;
function sidecars(path: string): string[] {
return [path, `${path}-wal`, `${path}-shm`];
}
/** Force owner-only permissions on the database and its WAL/SHM files, whatever the umask. */
export function secureDbFiles(path: string): void {
if (path === ':memory:') return;
for (const file of sidecars(path)) if (existsSync(file)) chmodSync(file, FILE_MODE);
}
export function openDb(path: string): Db { export function openDb(path: string): Db {
if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true }); if (path !== ':memory:') {
const dir = dirname(path);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: DIR_MODE });
// mkdir's mode is masked by the umask; state the result explicitly.
chmodSync(dir, DIR_MODE);
}
// Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and
// SHM files the same permissions as the database file, so they are never world-readable,
// not even for a moment.
if (!existsSync(path)) closeSync(openSync(path, 'a', FILE_MODE));
chmodSync(path, FILE_MODE);
}
const db = new Database(path); const db = new Database(path);
db.pragma('journal_mode = WAL'); db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON'); db.pragma('foreign_keys = ON');
db.pragma('busy_timeout = 5000'); db.pragma('busy_timeout = 5000');
migrate(db); migrate(db);
secureDbFiles(path);
return db; return db;
} }
+21 -19
View File
@@ -15,11 +15,15 @@ export interface DeviceRow {
} }
export type AuthFailure = 'unauthorized' | 'credential_expired'; export type AuthFailure = 'unauthorized' | 'credential_expired';
export type PairingFailure = 'pairing_invalid' | 'pairing_locked'; export type PairingFailure = 'pairing_invalid';
// No 0/O, 1/I/L: read aloud or typed on a phone without ambiguity. 31 symbols. // No 0/O, 1/I/L: read aloud or typed on a phone without ambiguity. 31 symbols.
const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
const CODE_LENGTH = 10; // ~49.5 bits; with 5 total failures before lockout, guessing is not viable. // ~49.5 bits. Brute force is bounded by this entropy, the code's few-minute lifetime and the
// per-client attempt limit in the HTTP layer; see docs/security.md for the arithmetic. Wrong
// guesses are deliberately NOT counted against the outstanding code: if they were, anyone
// who can reach the endpoint could void the owner's real code with a handful of junk guesses.
const CODE_LENGTH = 10;
export function sha256(value: string): string { export function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex'); return createHash('sha256').update(value).digest('hex');
@@ -55,8 +59,8 @@ export class Devices {
} }
/** /**
* Exchange a pairing code for a device credential. A wrong guess counts against every * Exchange a pairing code for a device credential. A wrong, expired or already-used code
* outstanding code, so the code is burned after a few failures regardless of who guessed. * all fail the same way and change nothing: only the correct code consumes the code.
*/ */
claimPairingCode( claimPairingCode(
rawCode: string, rawCode: string,
@@ -66,22 +70,10 @@ export class Devices {
const hash = sha256(normalizeCode(rawCode)); const hash = sha256(normalizeCode(rawCode));
return this.db.transaction(() => { return this.db.transaction(() => {
const live = this.db const live = this.db
.prepare('SELECT id, code_hash, failed_attempts FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?') .prepare('SELECT id, code_hash FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?')
.all(now) as Array<{ id: number; code_hash: string; failed_attempts: number }>; .all(now) as Array<{ id: number; code_hash: string }>;
const match = live.find((row) => safeEqualHex(row.code_hash, hash)); const match = live.find((row) => safeEqualHex(row.code_hash, hash));
if (!match) { if (!match) return { ok: false as const, reason: 'pairing_invalid' as const };
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); this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE id = ?').run(now, match.id);
const token = newToken(); const token = newToken();
const device: DeviceRow = { const device: DeviceRow = {
@@ -130,11 +122,21 @@ export class Devices {
return { device: this.get(deviceId)!, token }; return { device: this.get(deviceId)!, token };
} }
/**
* Revoke a device. One transaction ends its access, closes its conversation and flags every
* turn it still has in flight for cancellation, so nothing the device started keeps running
* on its behalf. The flag is in the database, so it also reaches a bridge process that did
* not perform the revocation (the operator CLI is a separate process): the turn engine acts
* on it by aborting transcription and asking Hermes to stop.
*/
revoke(deviceId: string): boolean { revoke(deviceId: string): boolean {
const now = this.now(); const now = this.now();
return this.db.transaction(() => { return this.db.transaction(() => {
const res = this.db.prepare('UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').run(now, deviceId); 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); this.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
this.db
.prepare("UPDATE turns SET cancel_requested = 1, updated_at = ? WHERE device_id = ? AND state != 'done' AND cancel_requested = 0")
.run(now, deviceId);
return res.changes > 0; return res.changes > 0;
})(); })();
} }
+18 -7
View File
@@ -11,14 +11,25 @@ async function main(): Promise<void> {
}); });
await bridge.app.listen({ host: config.host, port: config.port }); await bridge.app.listen({ host: config.host, port: config.port });
// Load the built-in speech model in the background so the first spoken question is not // Verify and load the built-in speech model in the background so the first spoken question
// slowed by it. On a first start this downloads the model files. // is not slowed by it. Nothing is downloaded here: the files must already be in the model
if (bridge.stt instanceof BuiltinWhisperStt) { // store (`bridge:cli fetch-model`) and must match their pinned hashes.
const stt = bridge.stt;
if (stt instanceof BuiltinWhisperStt) {
const started = Date.now(); const started = Date.now();
bridge.app.log.info({ model: config.stt.model, dtype: config.stt.dtype }, 'stt.loading'); const pin = { model: config.stt.manifest!.model, revision: config.stt.manifest!.revision };
bridge.stt.warm().then( bridge.app.log.info(pin, 'stt.loading');
() => bridge.app.log.info({ load_ms: Date.now() - started }, 'stt.ready'), stt.warm().then(
() => bridge.app.log.error({ model: config.stt.model }, 'stt.load_failed'), () => bridge.app.log.info({ ...pin, load_ms: Date.now() - started }, 'stt.ready'),
() =>
bridge.app.log.error(
{
...pin,
reason: stt.lastLoadFailure,
hint: stt.lastLoadFailure === 'missing' ? 'run: npm run bridge:cli -- fetch-model' : undefined,
},
'stt.load_failed',
),
); );
} }
+3 -7
View File
@@ -171,12 +171,8 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device'); const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device');
if (!result.ok) { if (!result.ok) {
req.log.warn({ reason: result.reason }, 'pairing.rejected'); req.log.warn({ reason: result.reason }, 'pairing.rejected');
throw new ApiError( // One answer for wrong, expired and used codes: the response reveals nothing about which.
result.reason, throw new ApiError('pairing_invalid', 'Pairing code is not valid.');
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'); req.log.info({ device_id: result.device.id }, 'pairing.claimed');
return reply.code(201).send(credential(result.device, result.token)); return reply.code(201).send(credential(result.device, result.token));
@@ -212,7 +208,7 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
app.delete('/v1/device', async (req) => { app.delete('/v1/device', async (req) => {
const device = authenticate(req); const device = authenticate(req);
devices.revoke(device.id); engine.revokeDevice(device.id);
req.log.info({ device_id: device.id }, 'device.revoked'); req.log.info({ device_id: device.id }, 'device.revoked');
return { schema_version: SCHEMA_VERSION, revoked: true }; return { schema_version: SCHEMA_VERSION, revoked: true };
}); });
+15 -10
View File
@@ -1,6 +1,7 @@
import { Worker } from 'node:worker_threads'; import { Worker } from 'node:worker_threads';
import { AUDIO_FORMAT } from '@hermeven/contracts'; import { AUDIO_FORMAT } from '@hermeven/contracts';
import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts'; import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts';
import type { ModelManifest } from './modelStore.mjs';
/** /**
* Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU * Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU
@@ -10,15 +11,15 @@ import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts'
* The model lives in a worker thread (whisperWorker.mjs), so loading it and * The model lives in a worker thread (whisperWorker.mjs), so loading it and
* transcribing never block the bridge's HTTP server or its Hermes polling. * transcribing never block the bridge's HTTP server or its Hermes polling.
* *
* The model files are downloaded from the Hugging Face hub the first time the * The bridge never downloads anything at run time. Model files are fetched ahead of
* bridge starts and are then read from `cacheDir`. * time (`bridge:cli fetch-model`) at a pinned commit, and every file is checked against
* its pinned SHA-256 each time the model is loaded.
*/ */
export interface BuiltinWhisperOptions { export interface BuiltinWhisperOptions {
/** Hub id, for example `onnx-community/whisper-base` (multilingual) or `...-base.en`. */ /** What exactly to load: hub id, immutable revision, precision, and each file's hash. */
model: string; manifest: ModelManifest;
/** Weight precision. `q8` is the small, CPU-friendly default. */ /** Model store directory. Read-only at run time. */
dtype: string; modelDir: string;
cacheDir: string;
/** Test seam: replaces the worker thread with an in-process recogniser. */ /** Test seam: replaces the worker thread with an in-process recogniser. */
load?: () => Promise<Recognizer>; load?: () => Promise<Recognizer>;
} }
@@ -58,6 +59,8 @@ export class BuiltinWhisperStt implements SttAdapter {
private recognizer: Promise<Recognizer> | null = null; private recognizer: Promise<Recognizer> | null = null;
private worker: Worker | null = null; private worker: Worker | null = null;
private closed = false; private closed = false;
/** Why the last load failed: `missing`, `mismatch` (files differ from the pin) or `load`. */
lastLoadFailure: 'missing' | 'mismatch' | 'load' | null = null;
/** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */ /** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */
private queue: Promise<unknown> = Promise.resolve(); private queue: Promise<unknown> = Promise.resolve();
@@ -102,9 +105,10 @@ export class BuiltinWhisperStt implements SttAdapter {
}; };
worker.on('error', () => fail('worker error')); worker.on('error', () => fail('worker error'));
worker.on('exit', () => fail('worker exited')); worker.on('exit', () => fail('worker exited'));
worker.on('message', (message: { type: string; id?: number; text?: string }) => { worker.on('message', (message: { type: string; id?: number; text?: string; reason?: 'missing' | 'mismatch' | 'load' }) => {
if (message.type === 'loaded') { if (message.type === 'loaded') {
loaded = true; loaded = true;
this.lastLoadFailure = null;
resolve( resolve(
(audio, options) => (audio, options) =>
new Promise((res, rej) => { new Promise((res, rej) => {
@@ -115,6 +119,7 @@ export class BuiltinWhisperStt implements SttAdapter {
}), }),
); );
} else if (message.type === 'load_failed') { } else if (message.type === 'load_failed') {
this.lastLoadFailure = message.reason ?? 'load';
void worker.terminate(); void worker.terminate();
} else if (message.id !== undefined) { } else if (message.id !== undefined) {
const pending = waiting.get(message.id); const pending = waiting.get(message.id);
@@ -123,7 +128,7 @@ export class BuiltinWhisperStt implements SttAdapter {
else pending?.reject(new Error('recognition failed')); else pending?.reject(new Error('recognition failed'));
} }
}); });
worker.postMessage({ type: 'load', model: this.opts.model, dtype: this.opts.dtype, cacheDir: this.opts.cacheDir }); worker.postMessage({ type: 'load', dir: this.opts.modelDir, manifest: this.opts.manifest });
}); });
} }
@@ -150,7 +155,7 @@ export class BuiltinWhisperStt implements SttAdapter {
} }
// English-only models take no language argument; multilingual ones are told the // English-only models take no language argument; multilingual ones are told the
// language from the device locale rather than left to guess it from a short clip. // language from the device locale rather than left to guess it from a short clip.
const options: Record<string, unknown> = this.opts.model.endsWith('.en') const options: Record<string, unknown> = this.opts.manifest.model.endsWith('.en')
? {} ? {}
: { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' }; : { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' };
try { try {
+24
View File
@@ -0,0 +1,24 @@
export interface ModelFile {
path: string;
sha256: string;
bytes: number;
}
export interface ModelManifest {
name: string;
/** Hugging Face hub id, `<owner>/<name>`. */
model: string;
/** Full 40-character commit id. Branches and tags are refused. */
revision: string;
dtype: string;
files: ModelFile[];
}
export type VerifyResult = { ok: true } | { ok: false; reason: 'missing' | 'mismatch'; path: string };
export function validateManifest(value: unknown): ModelManifest;
export function modelPath(dir: string, manifest: ModelManifest): string;
export function verifyModel(dir: string, manifest: ModelManifest): Promise<VerifyResult>;
export function fetchModel(
dir: string,
manifest: ModelManifest,
options?: { baseUrl?: string; fetchImpl?: typeof fetch; onFile?: (path: string, bytes: number) => void },
): Promise<{ downloaded: number; verified: number }>;
+123
View File
@@ -0,0 +1,123 @@
// Pinned speech-model artifacts: manifest validation, download and verification.
//
// Plain JavaScript because the worker thread imports it directly; types are in
// modelStore.d.mts. This is the only code that decides whether model files are trusted.
import { createHash } from 'node:crypto';
import { createReadStream, createWriteStream } from 'node:fs';
import { mkdir, rename, rm, stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { pipeline as pump } from 'node:stream/promises';
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/;
const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
const DTYPES = new Set(['q8', 'q4', 'fp32', 'fp16', 'int8', 'uint8']);
/** Throws with a plain reason unless the manifest pins everything it names. */
export function validateManifest(value) {
const fail = (why) => {
throw new Error(`Invalid model manifest: ${why}`);
};
if (!value || typeof value !== 'object') fail('not an object');
const { name, model, revision, dtype, files } = value;
if (typeof name !== 'string' || !SEGMENT.test(name)) fail('name');
if (typeof model !== 'string' || !MODEL_ID.test(model)) fail('model must be <owner>/<name>');
// A branch or tag can move. Only a full commit id is immutable.
if (typeof revision !== 'string' || !/^[0-9a-f]{40}$/.test(revision)) fail('revision must be a full 40-character commit id');
if (typeof dtype !== 'string' || !DTYPES.has(dtype)) fail('dtype');
if (!Array.isArray(files) || files.length === 0) fail('files');
const seen = new Set();
for (const file of files) {
if (!file || typeof file !== 'object') fail('file entry');
if (typeof file.path !== 'string' || !file.path.split('/').every((s) => SEGMENT.test(s))) fail(`unsafe path`);
if (seen.has(file.path)) fail('duplicate path');
seen.add(file.path);
if (typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256)) fail(`sha256 for ${file.path}`);
if (!Number.isInteger(file.bytes) || file.bytes <= 0) fail(`bytes for ${file.path}`);
}
return { name, model, revision, dtype, files: files.map((f) => ({ path: f.path, sha256: f.sha256, bytes: f.bytes })) };
}
/** Directory that holds one model's files inside the model store. */
export function modelPath(dir, manifest) {
return join(dir, manifest.model);
}
async function sha256File(path) {
const hash = createHash('sha256');
await pump(createReadStream(path), hash);
return hash.digest('hex');
}
/**
* Check every file the manifest names: present, exact size, exact SHA-256.
* Resolves `{ ok: true }` or `{ ok: false, reason: 'missing' | 'mismatch', path }`.
*/
export async function verifyModel(dir, manifest) {
const root = modelPath(dir, manifest);
for (const file of manifest.files) {
const path = join(root, file.path);
let info;
try {
info = await stat(path);
} catch {
return { ok: false, reason: 'missing', path: file.path };
}
if (!info.isFile()) return { ok: false, reason: 'missing', path: file.path };
if (info.size !== file.bytes) return { ok: false, reason: 'mismatch', path: file.path };
if ((await sha256File(path)) !== file.sha256) return { ok: false, reason: 'mismatch', path: file.path };
}
return { ok: true };
}
/**
* Download the pinned revision's files into the store, verifying each before it is put in
* place. A file that does not match its pinned hash is deleted and the fetch fails.
* Files already present and correct are left alone, so the command is safe to repeat.
*/
export async function fetchModel(dir, manifest, options = {}) {
const baseUrl = (options.baseUrl ?? 'https://huggingface.co').replace(/\/+$/, '');
const fetchImpl = options.fetchImpl ?? fetch;
const root = modelPath(dir, manifest);
let downloaded = 0;
for (const file of manifest.files) {
const dest = join(root, file.path);
const single = { ...manifest, files: [file] };
if ((await verifyModel(dir, single)).ok) continue;
await mkdir(dirname(dest), { recursive: true });
const partial = `${dest}.partial`;
await rm(partial, { force: true });
// The commit id in the URL pins what the hub serves; the hash check does not rely on that.
const url = `${baseUrl}/${manifest.model}/resolve/${manifest.revision}/${file.path}`;
const res = await fetchImpl(url, { redirect: 'follow' });
if (!res.ok || !res.body) throw new Error(`Download failed for ${file.path}: HTTP ${res.status}`);
const hash = createHash('sha256');
let bytes = 0;
try {
await pump(
Readable.fromWeb(res.body),
async function* (source) {
for await (const chunk of source) {
bytes += chunk.length;
if (bytes > file.bytes) throw new Error(`Download for ${file.path} is larger than pinned`);
hash.update(chunk);
yield chunk;
}
},
createWriteStream(partial, { mode: 0o644 }),
);
if (bytes !== file.bytes || hash.digest('hex') !== file.sha256) {
throw new Error(`Downloaded ${file.path} does not match its pinned SHA-256`);
}
} catch (err) {
await rm(partial, { force: true });
throw err;
}
await rename(partial, dest);
downloaded += 1;
options.onFile?.(file.path, file.bytes);
}
const check = await verifyModel(dir, manifest);
if (!check.ok) throw new Error(`Model store failed verification after fetch: ${check.reason} ${check.path}`);
return { downloaded, verified: manifest.files.length };
}
+22 -8
View File
@@ -2,27 +2,41 @@
// directly by `new Worker(...)`, so it must run without any TypeScript loader. // directly by `new Worker(...)`, so it must run without any TypeScript loader.
// //
// Protocol (all messages are plain objects): // Protocol (all messages are plain objects):
// in : { type: 'load', model, dtype, cacheDir } // in : { type: 'load', dir, manifest }
// out: { type: 'loaded' } | { type: 'load_failed' } // out: { type: 'loaded' } | { type: 'load_failed', reason: 'missing' | 'mismatch' | 'load' }
// in : { type: 'run', id, samples: Float32Array, options } // in : { type: 'run', id, samples: Float32Array, options }
// out: { type: 'result', id, text } | { type: 'failed', id } // out: { type: 'result', id, text } | { type: 'failed', id }
// Error details are deliberately not sent back: they could contain file paths, and nothing // Only fixed reason codes are sent back: error text could contain file paths, and nothing
// derived from audio content should travel as an error string. // derived from audio content should travel as an error string.
import { parentPort } from 'node:worker_threads'; import { parentPort } from 'node:worker_threads';
import { verifyModel } from './modelStore.mjs';
let recognizer = null; let recognizer = null;
parentPort.on('message', async (message) => { parentPort.on('message', async (message) => {
if (message.type === 'load') { if (message.type === 'load') {
try { try {
const { pipeline } = await import('@huggingface/transformers'); // 1. The files on disk must be exactly the pinned ones.
recognizer = await pipeline('automatic-speech-recognition', message.model, { const check = await verifyModel(message.dir, message.manifest);
dtype: message.dtype, if (!check.ok) {
cache_dir: message.cacheDir, parentPort.postMessage({ type: 'load_failed', reason: check.reason });
return;
}
// 2. Load from that directory only. The network is never consulted at run time: remote
// models are disabled, so a missing file is an error rather than a download.
const { env, pipeline } = await import('@huggingface/transformers');
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = message.dir;
env.useFSCache = false;
env.useBrowserCache = false;
recognizer = await pipeline('automatic-speech-recognition', message.manifest.model, {
dtype: message.manifest.dtype,
local_files_only: true,
}); });
parentPort.postMessage({ type: 'loaded' }); parentPort.postMessage({ type: 'loaded' });
} catch { } catch {
parentPort.postMessage({ type: 'load_failed' }); parentPort.postMessage({ type: 'load_failed', reason: 'load' });
} }
return; return;
} }
+54 -6
View File
@@ -9,6 +9,7 @@ import {
} from '@hermeven/contracts'; } from '@hermeven/contracts';
import type { BridgeConfig } from './config.ts'; import type { BridgeConfig } from './config.ts';
import type { Db } from './db.ts'; import type { Db } from './db.ts';
import type { Devices } from './devices.ts';
import { import {
buildRunBody, buildRunBody,
HermesSubmitError, HermesSubmitError,
@@ -39,6 +40,8 @@ export interface TurnRow {
updated_at: number; updated_at: number;
agent_started_at: number | null; agent_started_at: number | null;
approval_started_at: number | null; approval_started_at: number | null;
/** Absolute time the agent must finish by; pushed back by time spent awaiting approval. */
agent_deadline_at: number | null;
completed_at: number | null; completed_at: number | null;
transcribe_ms: number | null; transcribe_ms: number | null;
agent_ms: number | null; agent_ms: number | null;
@@ -118,6 +121,7 @@ export class TurnEngine {
private readonly deps: { private readonly deps: {
db: Db; db: Db;
config: BridgeConfig; config: BridgeConfig;
devices: Devices;
hermes: HermesAdapter; hermes: HermesAdapter;
stt: SttAdapter; stt: SttAdapter;
log: EngineLog; log: EngineLog;
@@ -220,6 +224,7 @@ export class TurnEngine {
updated_at: now, updated_at: now,
agent_started_at: null, agent_started_at: null,
approval_started_at: null, approval_started_at: null,
agent_deadline_at: null,
completed_at: null, completed_at: null,
transcribe_ms: null, transcribe_ms: null,
agent_ms: null, agent_ms: null,
@@ -261,6 +266,38 @@ export class TurnEngine {
return this.row(requestId); return this.row(requestId);
} }
/**
* Revoke a device and stop everything it has in flight. Access ends and the turns are
* flagged in one transaction (Devices.revoke); this then acts on the flags at once.
*/
revokeDevice(deviceId: string): boolean {
const revoked = this.deps.devices.revoke(deviceId);
this.deps.log.info({ device_id: deviceId, revoked }, 'device.revoke_applied');
this.applyCancelFlags();
return revoked;
}
/**
* Act on cancel flags set directly in the database: abort transcription and wake the worker
* so it asks Hermes to stop. Runs right after an in-process revocation, and on a short
* timer so a revocation made by the operator CLI (another process) is honoured promptly.
*/
applyCancelFlags(): number {
if (this.active.size === 0) return 0;
const flagged = this.deps.db
.prepare("SELECT request_id FROM turns WHERE state != 'done' AND cancel_requested = 1")
.all() as Array<{ request_id: string }>;
let nudged = 0;
for (const { request_id } of flagged) {
const active = this.active.get(request_id);
if (!active) continue;
active.sttAbort?.abort();
active.wake?.();
nudged += 1;
}
return nudged;
}
/** Resume or settle every turn a previous process left in flight. Call once at startup. */ /** Resume or settle every turn a previous process left in flight. Call once at startup. */
recover(): void { recover(): void {
const rows = this.deps.db.prepare("SELECT * FROM turns WHERE state != 'done'").all() as TurnRow[]; const rows = this.deps.db.prepare("SELECT * FROM turns WHERE state != 'done'").all() as TurnRow[];
@@ -427,13 +464,15 @@ export class TurnEngine {
.get(row.conversation_id) as ConversationRow; .get(row.conversation_id) as ConversationRow;
// Persist the exact body BEFORE the first network attempt, so a crash can replay it // Persist the exact body BEFORE the first network attempt, so a crash can replay it
// under the same idempotency key instead of guessing. // under the same idempotency key instead of guessing.
const agentStartedAt = this.now();
this.setState(requestId, 'thinking', { this.setState(requestId, 'thinking', {
pending_body: buildRunBody({ pending_body: buildRunBody({
input: row.input_text ?? '', input: row.input_text ?? '',
sessionId: conversation.hermes_session_id, sessionId: conversation.hermes_session_id,
instructions: this.deps.config.hermes.instructions, instructions: this.deps.config.hermes.instructions,
}), }),
agent_started_at: this.now(), agent_started_at: agentStartedAt,
agent_deadline_at: agentStartedAt + this.timing.agentDeadlineMs,
}); });
} }
@@ -482,7 +521,7 @@ export class TurnEngine {
/** Returns the run id, or null when the turn was settled here. */ /** Returns the run id, or null when the turn was settled here. */
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> { private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> {
const row = this.row(requestId)!; const row = this.row(requestId)!;
const deadline = (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; const deadline = row.agent_deadline_at ?? (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
let ambiguous = maybeAlreadySent; let ambiguous = maybeAlreadySent;
let notSent = 0; let notSent = 0;
@@ -529,8 +568,11 @@ export class TurnEngine {
private async poll(requestId: string, active: ActiveTurn): Promise<void> { private async poll(requestId: string, active: ActiveTurn): Promise<void> {
const start = this.row(requestId)!; const start = this.row(requestId)!;
const runId = start.hermes_run_id!; const runId = start.hermes_run_id!;
let deadlineAt = (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; // Both clocks come from the database, so a bridge restart resumes them where they were:
let approvalSince: number | null = null; // the approval wait is measured from when the approval was first seen, and the agent
// deadline keeps whatever pause earlier approvals earned it.
let deadlineAt = start.agent_deadline_at ?? (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
let approvalSince: number | null = start.approval_started_at;
let stopReason: 'user' | 'agent_timeout' | 'approval_timeout' | null = null; let stopReason: 'user' | 'agent_timeout' | 'approval_timeout' | null = null;
let stopAccepted = false; let stopAccepted = false;
let graceUntil = 0; let graceUntil = 0;
@@ -587,14 +629,20 @@ export class TurnEngine {
this.finish(requestId, 'unknown', { code: 'outcome_unknown' }); this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
return; return;
case 'waiting_for_approval': case 'waiting_for_approval':
if (approvalSince === null) approvalSince = now; if (approvalSince === null) {
if (!stopReason) this.setState(requestId, 'approval_required', { approval_started_at: now }); // Recorded once, when the approval is first seen, and never moved afterwards.
approvalSince = now;
this.update(requestId, { approval_started_at: now });
}
if (!stopReason) this.setState(requestId, 'approval_required');
break; break;
default: default:
if (approvalSince !== null) { if (approvalSince !== null) {
// Approval was resolved on another surface; time spent waiting does not count. // Approval was resolved on another surface; time spent waiting does not count.
// Persisted in one write, so a restart cannot apply the pause twice or not at all.
deadlineAt += now - approvalSince; deadlineAt += now - approvalSince;
approvalSince = null; approvalSince = null;
this.update(requestId, { agent_deadline_at: deadlineAt, approval_started_at: null });
} }
if (!stopReason) this.setState(requestId, 'thinking'); if (!stopReason) this.setState(requestId, 'thinking');
} }
+5 -6
View File
@@ -9,14 +9,14 @@ function tone(seconds: number, amplitude = 8000): Buffer {
return buf; return buf;
} }
const never = new AbortController().signal; const never = new AbortController().signal;
const manifestFor = (model: string) => ({ name: 'test', model, revision: 'a'.repeat(40), dtype: 'q8', files: [] });
function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') { function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') {
let loads = 0; let loads = 0;
const calls: Array<{ samples: number; options: Record<string, unknown> }> = []; const calls: Array<{ samples: number; options: Record<string, unknown> }> = [];
const stt = new BuiltinWhisperStt({ const stt = new BuiltinWhisperStt({
model, manifest: manifestFor(model),
dtype: 'q8', modelDir: '/nonexistent',
cacheDir: '/nonexistent',
load: async () => { load: async () => {
loads += 1; loads += 1;
return async (audio, options) => { return async (audio, options) => {
@@ -99,9 +99,8 @@ describe('built-in Whisper adapter', () => {
it('a model that fails to load is "unavailable" and is retried next time', async () => { it('a model that fails to load is "unavailable" and is retried next time', async () => {
let attempts = 0; let attempts = 0;
const stt = new BuiltinWhisperStt({ const stt = new BuiltinWhisperStt({
model: 'onnx-community/whisper-base', manifest: manifestFor('onnx-community/whisper-base'),
dtype: 'q8', modelDir: '/nonexistent',
cacheDir: '/nonexistent',
load: async () => { load: async () => {
attempts += 1; attempts += 1;
if (attempts === 1) throw new Error('no network'); if (attempts === 1) throw new Error('no network');
+196
View File
@@ -0,0 +1,196 @@
import { createHash } from 'node:crypto';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { bundledManifestPath, ConfigError, loadConfig } from '../src/config.ts';
import { BuiltinWhisperStt } from '../src/stt/builtinWhisper.ts';
import { fetchModel, validateManifest, verifyModel, type ModelManifest } from '../src/stt/modelStore.mjs';
/**
* Pinning and verification of speech-model artifacts. A local stand-in for the model hub is
* used, so these run without network. The real pinned artifacts are fetched and verified by
* `npm run test:real-stt`.
*/
const sha = (data: string | Buffer) => createHash('sha256').update(data).digest('hex');
const CONTENT: Record<string, Buffer> = {
'config.json': Buffer.from('{"a":1}'),
'onnx/model.onnx': Buffer.from('not really weights, but bytes all the same'),
};
const REVISION = '0123456789abcdef0123456789abcdef01234567';
const manifest: ModelManifest = {
name: 'test-model',
model: 'test-org/test-model',
revision: REVISION,
dtype: 'q8',
files: Object.entries(CONTENT).map(([path, data]) => ({ path, sha256: sha(data), bytes: data.length })),
};
let dir: string;
let hub: Server;
let hubUrl: string;
let requests: string[];
let served: Record<string, Buffer>;
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'hermeven-models-'));
requests = [];
served = { ...CONTENT };
hub = createServer((req, res) => {
requests.push(req.url ?? '');
const prefix = `/${manifest.model}/resolve/${REVISION}/`;
const file = req.url?.startsWith(prefix) ? served[req.url.slice(prefix.length)] : undefined;
if (!file) return void res.writeHead(404).end();
res.writeHead(200, { 'Content-Length': file.length }).end(file);
});
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', r));
hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
});
afterEach(async () => {
hub.closeAllConnections();
await new Promise<void>((r) => hub.close(() => r()));
chmodRecursive(dir, 0o700, 0o600);
rmSync(dir, { recursive: true, force: true });
});
function chmodRecursive(path: string, dirMode: number, fileMode: number): void {
if (!existsSync(path)) return;
chmodSync(path, dirMode);
for (const entry of readdirSync(path, { withFileTypes: true })) {
const child = join(path, entry.name);
if (entry.isDirectory()) chmodRecursive(child, dirMode, fileMode);
else chmodSync(child, fileMode);
}
}
describe('manifest validation: nothing unpinned is accepted', () => {
const base = { ...manifest };
it('accepts a fully pinned manifest', () => {
expect(validateManifest(base)).toEqual(manifest);
});
it('refuses a branch, tag or short id as the revision', () => {
for (const revision of ['main', 'v1.0', REVISION.slice(0, 12), REVISION.toUpperCase(), '', undefined]) {
expect(() => validateManifest({ ...base, revision })).toThrow(/revision/);
}
});
it('refuses a file without a full SHA-256 or size', () => {
expect(() => validateManifest({ ...base, files: [{ path: 'a', bytes: 1 }] })).toThrow(/sha256/);
expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: 'abc', bytes: 1 }] })).toThrow(/sha256/);
expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: sha('x') }] })).toThrow(/bytes/);
expect(() => validateManifest({ ...base, files: [] })).toThrow(/files/);
});
it('refuses paths that could leave the model store', () => {
for (const path of ['../evil', '/etc/passwd', 'a/../../b', 'a//b', '.hidden/x', 'a\\b']) {
expect(() => validateManifest({ ...base, files: [{ path, sha256: sha('x'), bytes: 1 }] })).toThrow(/unsafe path/);
}
expect(() => validateManifest({ ...base, model: '../x/y' })).toThrow(/model/);
});
it('the bundled manifests are valid and pin a commit', () => {
for (const name of ['whisper-base', 'whisper-tiny']) {
const bundled = validateManifest(JSON.parse(readFileSync(bundledManifestPath(name), 'utf8')));
expect(bundled.revision).toMatch(/^[0-9a-f]{40}$/);
expect(bundled.files.length).toBeGreaterThanOrEqual(7);
}
});
});
describe('configuration: an unpinned built-in model cannot be configured', () => {
const env = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:' };
it('defaults to the bundled pinned whisper-base', () => {
const config = loadConfig(env);
expect(config.stt.provider).toBe('builtin');
expect(config.stt.manifest).toMatchObject({ model: 'onnx-community/whisper-base', dtype: 'q8' });
expect(config.stt.manifest!.revision).toMatch(/^[0-9a-f]{40}$/);
});
it('refuses a hub id or any model without a bundled manifest', () => {
for (const model of ['onnx-community/whisper-base', 'whisper-large', 'main', '../../etc/passwd']) {
expect(() => loadConfig({ ...env, STT_MODEL: model })).toThrow(ConfigError);
}
});
it('accepts a custom manifest only if it is fully pinned', () => {
const good = join(dir, 'good.json');
writeFileSync(good, JSON.stringify(manifest));
expect(loadConfig({ ...env, STT_MODEL_MANIFEST: good }).stt.manifest).toEqual(manifest);
const moving = join(dir, 'moving.json');
writeFileSync(moving, JSON.stringify({ ...manifest, revision: 'main' }));
expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: moving })).toThrow(/revision/);
expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: join(dir, 'absent.json') })).toThrow(ConfigError);
});
});
describe('fetch and verify', () => {
it('downloads the pinned revision, verifies it, and is a no-op the second time', async () => {
expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'missing', path: 'config.json' });
expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 2, verified: 2 });
expect(requests).toEqual([
`/test-org/test-model/resolve/${REVISION}/config.json`,
`/test-org/test-model/resolve/${REVISION}/onnx/model.onnx`,
]);
expect(await verifyModel(dir, manifest)).toEqual({ ok: true });
requests.length = 0;
expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 0, verified: 2 });
expect(requests).toEqual([]);
});
it('a hub that serves different bytes fails the fetch and leaves nothing in place', async () => {
served['onnx/model.onnx'] = Buffer.from('not really weights, but bytes all the SAME'); // same length
await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/does not match its pinned SHA-256/);
const onnxDir = join(dir, manifest.model, 'onnx');
expect(existsSync(join(onnxDir, 'model.onnx'))).toBe(false);
expect(readdirSync(onnxDir)).toEqual([]);
expect((await verifyModel(dir, manifest)).ok).toBe(false);
served['onnx/model.onnx'] = Buffer.concat([CONTENT['onnx/model.onnx']!, Buffer.from('extra')]);
await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/larger than pinned/);
delete served['config.json'];
rmSync(join(dir, manifest.model), { recursive: true });
await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/HTTP 404/);
});
it('detects a file changed on disk, by content and by size', async () => {
await fetchModel(dir, manifest, { baseUrl: hubUrl });
const target = join(dir, manifest.model, 'config.json');
writeFileSync(target, '{"a":2}'); // same size, different content
expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' });
writeFileSync(target, '{"a":1} ');
expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' });
// Fetching again repairs it from the pinned revision.
expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 1, verified: 2 });
});
it('verification works on a read-only store', async () => {
await fetchModel(dir, manifest, { baseUrl: hubUrl });
chmodRecursive(dir, 0o500, 0o400);
expect(await verifyModel(dir, manifest)).toEqual({ ok: true });
});
});
describe('the adapter refuses to load unverified artifacts, and never downloads', () => {
const pcm = () => {
const buf = Buffer.alloc(32000);
for (let i = 0; i < 16000; i++) buf.writeInt16LE(Math.round(Math.sin(i / 5) * 8000), i * 2);
return buf;
};
const signal = new AbortController().signal;
it('missing files: unavailable, reason "missing", and no network request', async () => {
const stt = new BuiltinWhisperStt({ manifest, modelDir: dir });
await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
expect(stt.lastLoadFailure).toBe('missing');
expect(requests).toEqual([]);
await stt.close();
});
it('tampered files: unavailable, reason "mismatch"', async () => {
await fetchModel(dir, manifest, { baseUrl: hubUrl });
writeFileSync(join(dir, manifest.model, 'onnx/model.onnx'), Buffer.from('not really weights, but bytes all the SAME'));
requests.length = 0;
const stt = new BuiltinWhisperStt({ manifest, modelDir: dir });
await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
expect(stt.lastLoadFailure).toBe('mismatch');
expect(requests).toEqual([]);
await stt.close();
});
});
+63
View File
@@ -1,3 +1,8 @@
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { ConfigError, loadConfig } from '../src/config.ts'; import { ConfigError, loadConfig } from '../src/config.ts';
import { openDb } from '../src/db.ts'; import { openDb } from '../src/db.ts';
@@ -46,6 +51,64 @@ describe('configuration', () => {
}); });
}); });
describe('state files are owner-only whatever the umask (CODY-006)', () => {
const mode = (path: string) => statSync(path).mode & 0o777;
it('under umask 0022 the directory is 0700 and the database, WAL and SHM are 0600', () => {
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
const dbPath = join(root, 'state', 'hermeven.sqlite');
// A separate process, so the permissive umask is real and does not leak into this one.
const script = `
process.umask(0o022);
const { openDb } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))});
const fs = await import('node:fs');
const { syncBuiltinESMExports } = await import('node:module');
// Record the loosest mode each state file ever has, from the instant SQLite or the
// bridge touches permissions, so a file that is briefly world-readable is caught too.
const loosest = {};
const seen = (p) => { try { const mode = fs.statSync(p).mode & 0o777; loosest[p] = Math.max(loosest[p] ?? 0, mode & 0o077); } catch {} };
const realChmod = fs.chmodSync;
fs.default.chmodSync = (p, mode) => { seen(${JSON.stringify(dbPath)}); seen(${JSON.stringify(dbPath + '-wal')}); seen(${JSON.stringify(dbPath + '-shm')}); return realChmod(p, mode); };
syncBuiltinESMExports();
const db = openDb(${JSON.stringify(dbPath)});
db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run();
const { statSync } = fs;
const m = (p) => (statSync(p).mode & 0o777).toString(8);
const everLoose = Object.values(loosest).some((bits) => bits !== 0);
// Read while the database is open, so the WAL and SHM files exist.
console.log(JSON.stringify({ everLoose, umask: process.umask().toString(8), dir: m(${JSON.stringify(join(root, 'state'))}), db: m(${JSON.stringify(dbPath)}), wal: m(${JSON.stringify(dbPath + '-wal')}), shm: m(${JSON.stringify(dbPath + '-shm')}) }));
db.close();
`;
try {
const out = execFileSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], {
encoding: 'utf8',
cwd: fileURLToPath(new URL('..', import.meta.url)),
});
expect(JSON.parse(out.trim().split('\n').at(-1)!)).toEqual({ everLoose: false, umask: '22', dir: '700', db: '600', wal: '600', shm: '600' });
expect(mode(dbPath)).toBe(0o600);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it('an existing database with loose permissions is tightened when opened', async () => {
const { chmodSync } = await import('node:fs');
const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-'));
const dbPath = join(root, 'hermeven.sqlite');
try {
openDb(dbPath).close();
chmodSync(dbPath, 0o644);
const db = openDb(dbPath);
db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run();
expect(mode(dbPath)).toBe(0o600);
expect(mode(`${dbPath}-wal`)).toBe(0o600);
db.close();
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
describe('device credentials', () => { describe('device credentials', () => {
const setup = (env: Record<string, string> = {}) => { const setup = (env: Record<string, string> = {}) => {
let now = 1_000_000; let now = 1_000_000;
+242 -7
View File
@@ -129,15 +129,45 @@ describe('pairing', () => {
expect(second.body.error.code).toBe('pairing_invalid'); expect(second.body.error.code).toBe('pairing_invalid');
}); });
it('wrong guesses burn the outstanding code', async () => { it('unrelated wrong guesses cannot invalidate the owner\'s real code (CODY-010)', async () => {
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '50', HERMEVEN_PAIRING_CODE_MAX_FAILURES: '3' } }); h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } });
const { code } = h.bridge.devices.createPairingCode(); 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' } }); 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'); const responses = [];
expect((await guess('AAAAA-AAAAB')).body.error.code).toBe('pairing_invalid'); for (let i = 0; i < 40; i++) responses.push(await guess(`AAAAA-AAA${String(i).padStart(2, '0')}`.replace(/[01]/g, 'B')));
expect((await guess('AAAAA-AAAAC')).body.error.code).toBe('pairing_locked'); // Every failure looks the same: same status, same code, same message, nothing about lockout.
// The real code no longer works. expect(new Set(responses.map((r) => `${r.status} ${JSON.stringify(r.body)}`)).size).toBe(1);
expect((await guess(code)).status).toBe(401); expect(responses[0]!.status).toBe(401);
expect(responses[0]!.body.error).toEqual({ code: 'pairing_invalid', message: 'Pairing code is not valid.', retryable: false });
// The real code still works after forty wrong guesses.
expect((await guess(code)).status).toBe(201);
// And then it is spent, with the same indistinguishable failure.
const spent = await guess(code);
expect(`${spent.status} ${JSON.stringify(spent.body)}`).toBe(`${responses[0]!.status} ${JSON.stringify(responses[0]!.body)}`);
});
it('an expired code fails exactly like a wrong one', async () => {
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } });
const { code } = h.bridge.devices.createPairingCode();
h.bridge.db.prepare('UPDATE pairing_codes SET expires_at = 1').run();
const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } });
const expired = await guess(code);
const wrong = await guess('ZZZZZ-ZZZZZ');
expect(expired.status).toBe(401);
expect(expired.body).toEqual(wrong.body);
});
it('brute force stays bounded: a client gets its per-minute attempts and no more, and still cannot burn the code', async () => {
h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '5' } });
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' } });
const statuses = [];
for (let i = 0; i < 30; i++) statuses.push((await guess('ZZZZZ-ZZZZZ')).status);
expect(statuses.filter((s) => s === 401)).toHaveLength(5);
expect(statuses.filter((s) => s === 429)).toHaveLength(25);
// The limiter is per client address. The owner pairing from another address is unaffected,
// which is exercised here at the layer below HTTP because the test has one address.
expect(h.bridge.devices.claimPairingCode(code, 'owner').ok).toBe(true);
}); });
it('claim attempts are rate limited per client', async () => { it('claim attempts are rate limited per client', async () => {
@@ -590,6 +620,211 @@ describe('duplicates, retries, cancellation and recovery', () => {
}); });
}); });
describe('device revocation stops what the device started (CODY-004)', () => {
beforeEach(async () => {
h = await createHarness({ timing: { agentDeadlineMs: 30_000, cancelGraceMs: 2000 } });
});
it('revoking over HTTP during a hanging run asks Hermes to stop and settles the turn', 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');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'thinking');
expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false);
expect((await h.api('DELETE', '/v1/device', { token: cred.token })).status).toBe(200);
// The device can no longer ask, so the outcome is read from the bridge's own records.
const row = () => h.bridge.db.prepare('SELECT state, outcome, cancel_requested FROM turns WHERE request_id = ?').get(id) as any;
const deadline = Date.now() + 3000;
while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
expect(row()).toEqual({ state: 'done', outcome: 'cancelled', cancel_requested: 1 });
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1);
expect(h.hermes.lastRun()!.status).toBe('cancelled');
// Still unauthorized afterwards, for reads, new turns and cancels alike.
expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).status).toBe(401);
expect((await h.textTurn(cred.token, conv, 'again')).status).toBe(401);
expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: cred.token, json: {} })).status).toBe(401);
expect((await h.api('POST', '/v1/conversations', { token: cred.token, json: { schema_version: 1 } })).status).toBe(401);
expect(h.hermes.executions).toBe(1);
});
it('revoking from the operator CLI path (database only, no engine call) also stops the run', 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');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'thinking');
// Exactly what `bridge:cli revoke` does: a second Devices instance on the same database
// file, as another process would have. The running engine is never called.
const { Devices } = await import('../../services/bridge/src/devices.ts');
const { openDb } = await import('../../services/bridge/src/db.ts');
const otherProcessDb = openDb(h.config.dbPath);
const [device] = h.bridge.devices.list();
expect(new Devices(otherProcessDb, h.config).revoke(device!.id)).toBe(true);
otherProcessDb.close();
const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any;
const deadline = Date.now() + 3000;
while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
expect(row()).toEqual({ state: 'done', outcome: 'cancelled' });
expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1);
expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401);
});
it('revoking during transcription aborts it and nothing reaches the agent', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.stt.next({ delayMs: 350, text: 'never used' });
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
const id = res.body.request_id;
await h.waitState(cred.token, id, 'transcribing');
const started = Date.now();
await h.api('DELETE', '/v1/device', { token: cred.token });
const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any;
while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5));
expect(row()).toEqual({ state: 'done', outcome: 'cancelled' });
// Settled by the abort, not by waiting for the recogniser to finish.
expect(Date.now() - started).toBeLessThan(250);
await new Promise((r) => setTimeout(r, 400));
expect(h.hermes.executions).toBe(0);
});
it('a CLI-path revocation during transcription is picked up by the sweep and aborts the recogniser', async () => {
const cred = await h.pair();
const conv = await h.conversation(cred.token);
h.stt.next({ delayMs: 380, text: 'never used' });
const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5));
const id = res.body.request_id;
await h.waitState(cred.token, id, 'transcribing');
const { Devices } = await import('../../services/bridge/src/devices.ts');
const { openDb } = await import('../../services/bridge/src/db.ts');
const otherProcessDb = openDb(h.config.dbPath);
const started = Date.now();
new Devices(otherProcessDb, h.config).revoke(h.bridge.devices.list()[0]!.id);
otherProcessDb.close();
const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any;
while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5));
expect(row()).toEqual({ state: 'done', outcome: 'cancelled' });
// Nobody in this process was told; only the periodic sweep can have aborted it this early.
expect(Date.now() - started).toBeLessThan(250);
await new Promise((r) => setTimeout(r, 400));
expect(h.hermes.executions).toBe(0);
});
it('revoking one device leaves another device\'s running turn alone', async () => {
const a = await h.pair('a');
const b = await h.pair('b');
const convB = await h.conversation(b.token);
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'b is fine' });
const res = await h.textTurn(b.token, convB, 'b question');
await h.waitState(b.token, res.body.request_id, 'thinking');
await h.api('DELETE', '/v1/device', { token: a.token });
const done = await h.waitTerminal(b.token, res.body.request_id);
expect(done.outcome).toBe('succeeded');
expect(done.cancel_requested).toBe(false);
expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false);
});
});
describe('approval wait and agent deadline survive a bridge restart (CODY-008)', () => {
it('restart BEFORE the original agent deadline: the approval timeout still fires at its original time', async () => {
h = await createHarness({ timing: { agentDeadlineMs: 5000, approvalWaitMs: 700, cancelGraceMs: 1000 } });
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, 'needs approval');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'approval_required');
const before = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at FROM turns').get() as any;
expect(before.approval_started_at).toBeGreaterThan(0);
await new Promise((r) => setTimeout(r, 400));
// Polling must not have moved the recorded start of the wait.
expect((h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at).toBe(before.approval_started_at);
await h.restartBridge();
const restartedAt = Date.now();
const done = await h.waitTerminal(cred.token, id);
// 700 ms from first sight of the approval, not 700 ms from the restart.
expect(Date.now() - before.approval_started_at).toBeGreaterThanOrEqual(690);
expect(Date.now() - restartedAt).toBeLessThan(550);
expect(done.outcome).toBe('cancelled');
expect(done.error?.code).toBe('approval_timeout');
});
it('restart AFTER the original agent deadline, still awaiting approval: classified as approval timeout, not agent timeout', async () => {
h = await createHarness({ timing: { agentDeadlineMs: 300, approvalWaitMs: 1200, cancelGraceMs: 1000 } });
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, 'needs approval');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'approval_required');
const startedAt = (h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at;
await new Promise((r) => setTimeout(r, 500)); // the 300 ms agent deadline is now in the past
await h.restartBridge();
// Not stopped on restart just because the unpaused agent deadline has passed.
await new Promise((r) => setTimeout(r, 200));
expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('approval_required');
const done = await h.waitTerminal(cred.token, id);
expect(done.error?.code).toBe('approval_timeout');
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1190);
expect(Date.now() - startedAt).toBeLessThan(1900);
});
it('restart while waiting, then approved elsewhere: the run keeps the time it had left and completes', async () => {
h = await createHarness({ timing: { agentDeadlineMs: 600, approvalWaitMs: 5000, cancelGraceMs: 1000 } });
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, 'needs approval');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'approval_required');
await new Promise((r) => setTimeout(r, 400));
await h.restartBridge();
await new Promise((r) => setTimeout(r, 500)); // 900 ms since start: past the unpaused 600 ms deadline
const run = h.hermes.lastRun()!;
run.status = 'running'; // approved on another surface; the agent carries on for a while
await h.waitState(cred.token, id, 'thinking');
const row = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at, agent_started_at FROM turns').get() as any;
expect(row.approval_started_at).toBeNull();
// The deadline was pushed back by the time spent waiting (about 900 ms), and stored.
expect(row.agent_deadline_at - row.agent_started_at).toBeGreaterThan(600 + 800);
// A second restart must not lose or double the pause.
await h.restartBridge();
await new Promise((r) => setTimeout(r, 150));
expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('thinking');
h.hermes.approve(run.runId, 'approved and finished');
const done = await h.waitTerminal(cred.token, id);
expect(done.outcome).toBe('succeeded');
expect(done.answer_text).toBe('approved and finished');
expect(h.hermes.executions).toBe(1);
});
it('after approval and restart, the paused agent deadline still ends a run that never finishes, as an agent timeout', async () => {
h = await createHarness({ timing: { agentDeadlineMs: 500, approvalWaitMs: 5000, cancelGraceMs: 1000 } });
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, 'needs approval');
const id = res.body.request_id;
await h.waitState(cred.token, id, 'approval_required');
await new Promise((r) => setTimeout(r, 300));
h.hermes.lastRun()!.status = 'running';
await h.waitState(cred.token, id, 'thinking');
await h.restartBridge();
const done = await h.waitTerminal(cred.token, id);
expect(done.outcome).toBe('cancelled');
expect(done.error?.code).toBe('agent_timeout');
});
});
describe('logging and retention', () => { describe('logging and retention', () => {
it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => { it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => {
h = await createHarness(); h = await createHarness();
+273 -5
View File
@@ -16,7 +16,14 @@ let h: Harness;
let device: FakeDevice; let device: FakeDevice;
let controller: Controller; let controller: Controller;
let snapshot: Snapshot; let snapshot: Snapshot;
let network: { down: boolean }; let network: {
down: boolean;
/** Runs the real request, then loses the reply: the bridge acts, the client hears nothing. */
dropReplies: boolean;
/** Optional per-request hook: return a promise to delay or reorder a reply. */
hook: ((url: string, init: RequestInit | undefined, send: () => Promise<Response>) => Promise<Response> | null) | null;
sent: Array<{ method: string; path: string }>;
};
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> { async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
const deadline = Date.now() + timeoutMs; const deadline = Date.now() + timeoutMs;
@@ -41,7 +48,20 @@ function makeController(dev: FakeDevice): Controller {
baseUrl, baseUrl,
token, token,
timeoutMs: 500, timeoutMs: 500,
fetchImpl: (input, init) => (network.down ? Promise.reject(new TypeError('offline')) : fetch(input, init)), fetchImpl: async (input, init) => {
if (network.down) throw new TypeError('offline');
const url = String(input);
network.sent.push({ method: init?.method ?? 'GET', path: new URL(url).pathname });
const send = () => fetch(input, init);
const hooked = network.hook?.(url, init, send);
if (hooked) return hooked;
const res = await send();
if (network.dropReplies) {
await res.arrayBuffer();
throw new TypeError('reply lost');
}
return res;
},
}), }),
onChange: (s) => { onChange: (s) => {
snapshot = s; snapshot = s;
@@ -60,7 +80,7 @@ async function pairedController(): Promise<void> {
} }
beforeEach(async () => { beforeEach(async () => {
network = { down: false }; network = { down: false, dropReplies: false, hook: null, sent: [] };
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } }); h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
}); });
afterEach(async () => { afterEach(async () => {
@@ -197,7 +217,7 @@ describe('cancel and stale results', () => {
}); });
describe('connection loss', () => { describe('connection loss', () => {
it('bridge unreachable at submit: nothing is sent; tap resends the same request exactly once', async () => { it('bridge unreachable at submit: tap resends the same request exactly once', async () => {
await pairedController(); await pairedController();
network.down = true; network.down = true;
device.tap(); device.tap();
@@ -205,7 +225,8 @@ describe('connection loss', () => {
device.speak(0.5); device.speak(0.5);
device.tap(); device.tap();
await until('disconnected', () => phase() === 'disconnected'); await until('disconnected', () => phase() === 'disconnected');
expect(device.frame.body).toContain('has not been sent'); expect(device.frame.body).toContain('not confirmed yet');
expect(device.frame.body).not.toContain('not been sent');
expect(device.micOpen).toBe(false); expect(device.micOpen).toBe(false);
const requestId = snapshot.state.requestId; const requestId = snapshot.state.requestId;
@@ -340,3 +361,250 @@ describe('restart, revocation and disconnect', () => {
for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret); for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret);
}); });
}); });
describe('CODY-003: a submit whose reply is lost is ambiguous, never "not sent"', () => {
it('replies dropped after the bridge admitted the turn, then a client restart: one execution, same request id, re-attached', async () => {
await pairedController();
// An ordinary first question, so a conversation exists before the connection turns bad.
controller.askText('hello');
await until('first answer', () => phase() === 'answer');
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'the one and only answer' });
h.stt.next({ text: 'transfer ten pounds' });
device.tap();
await until('listening', () => phase() === 'listening' && device.micOpen);
device.speak(0.5);
// From now on every request reaches the bridge and is acted on, but no reply comes back.
network.dropReplies = true;
device.tap();
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
// The bridge really did admit it, and Hermes really is running it.
await until('admitted by the bridge', () => h.hermes.executions === 2);
// The HUD does not claim the request was not sent.
for (const frame of device.frames) expect(frame.body).not.toMatch(/not been sent|was not sent|has not been sent/i);
expect(device.frame.body).toContain('not confirmed yet');
// The id was stored before the first attempt, so a restart can find the turn.
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
// The page dies and comes back. The recording is gone; only storage survives.
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.dropReplies = false;
controller = makeController(device);
await controller.start();
await until('answer after restart', () => phase() === 'answer');
expect(device.frame.body).toBe('the one and only answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
// Two questions were asked in this test; the lost-reply one ran exactly once.
expect(h.hermes.executions).toBe(2);
expect(h.hermes.lastRun()!.input).toBe('transfer ten pounds');
expect(h.stt.calls).toBe(1);
expect(device.micOpens).toBe(0);
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull();
});
it('same loss without a restart: tapping retry re-attaches under the same id and still executes once', async () => {
await pairedController();
controller.askText('hello');
await until('first answer', () => phase() === 'answer');
h.hermes.next({ kind: 'complete', afterMs: 200, output: 'answered once' });
network.dropReplies = true;
controller.askText('do the thing');
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
network.dropReplies = false;
device.tap();
await until('answer', () => phase() === 'answer');
expect(snapshot.lastTurn!.request_id).toBe(requestId);
expect(device.frame.body).toBe('answered once');
expect(h.hermes.executions).toBe(2);
expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(2);
});
it('a request that truly never arrived is reported as such only after the bridge confirms it has no record', async () => {
await pairedController();
network.down = true;
controller.askText('lost in the tunnel');
await until('disconnected', () => phase() === 'disconnected');
const requestId = snapshot.state.requestId!;
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.down = false;
controller = makeController(device);
await controller.start();
await until('confirmed absent', () => phase() === 'error');
expect(snapshot.state.error).toMatchObject({ code: 'not_delivered', retryable: true });
expect(device.frame.body).toContain('did not reach the bridge');
expect(h.hermes.executions).toBe(0);
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull();
});
it('a cancel that cannot be delivered is remembered and delivered on the next start, without showing the abandoned turn', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('abandon me');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
const requestId = snapshot.state.requestId!;
network.down = true;
device.doubleTap();
expect(phase()).toBe('cancelled');
await until('cancel recorded as pending', () => JSON.parse(device.storage.get('hermeven.v1')!).activeCancelled === true);
await new Promise((r) => setTimeout(r, 200));
expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId);
expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false);
await controller.stop();
const reborn = new FakeDevice();
for (const [k, v] of device.storage) reborn.storage.set(k, v);
device = reborn;
network.down = false;
controller = makeController(device);
await controller.start();
expect(phase()).toBe('ready');
await until('stop reached Hermes', () => h.hermes.requests.some((r) => r.path.endsWith('/stop')));
await until('slot cleared', () => JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId === null);
expect(device.frames.every((f) => !f.body.includes('Thinking'))).toBe(true);
});
});
describe('CODY-007: an expired credential is treated like a revoked one', () => {
const expireNow = () => h.bridge.db.prepare('UPDATE devices SET token_expires_at = ?').run(Date.now() - 1000);
it('expiry during a live session: asking clears the local pairing and brings pairing back', async () => {
await pairedController();
expect(snapshot.paired).toBe(true);
expireNow();
controller.askText('still there?');
await until('unpaired', () => phase() === 'unpaired');
expect(snapshot.paired).toBe(false);
expect(device.storage.get('hermeven.v1')).toBe('');
expect(device.frame.body).toContain('Open Hermeven on your phone to pair');
expect(h.hermes.executions).toBe(0);
// Pairing works again straight away.
const { code } = h.bridge.devices.createPairingCode();
await controller.pair(h.url, code, 'again');
expect(phase()).toBe('ready');
controller.askText('hello again');
await until('answer', () => phase() === 'answer');
});
it('expiry while waiting for an answer', async () => {
await pairedController();
h.hermes.next({ kind: 'hang' });
controller.askText('long one');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
expireNow();
await until('unpaired', () => phase() === 'unpaired');
expect(device.storage.get('hermeven.v1')).toBe('');
});
it('expiry noticed by the status refresh, by renew, and by new conversation', async () => {
for (const action of ['refresh', 'renew', 'conversation'] as const) {
await controller?.stop();
await pairedController();
expireNow();
if (action === 'refresh') await controller.refreshStatus();
else if (action === 'renew') await expect(controller.renew()).rejects.toMatchObject({ body: { code: 'credential_expired' } });
else controller.newConversation();
await until(`unpaired after ${action}`, () => phase() === 'unpaired');
expect(snapshot.paired, action).toBe(false);
expect(device.storage.get('hermeven.v1'), action).toBe('');
}
});
});
describe('CODY-009: exactly one conversation is created, whatever the timing', () => {
const creates = () => network.sent.filter((r) => r.method === 'POST' && r.path === '/v1/conversations').length;
const serverActive = async () => {
const token = JSON.parse(device.storage.get('hermeven.v1')!).token;
return (await h.api('GET', '/v1/device', { token })).body.active_conversation_id as string;
};
/** Hold every reply to a conversation create until released. */
function holdCreates() {
const held: Array<() => void> = [];
network.hook = (url, init, send) => {
if (init?.method !== 'POST' || !url.endsWith('/v1/conversations')) return null;
return send().then((res) => new Promise<Response>((resolve) => held.push(() => resolve(res))));
};
return {
count: () => held.length,
release: (index: number) => held[index]!(),
};
}
it('"new conversation" pressed twice and a question asked at once, with the create reply delayed: one create, one stored id, the question succeeds', async () => {
await pairedController();
const gate = holdCreates();
device.menu(MENU_ITEM.NEW_CONVERSATION);
device.menu(MENU_ITEM.NEW_CONVERSATION);
controller.askText('first question in the new conversation');
await until('create reached the bridge', () => gate.count() === 1);
await new Promise((r) => setTimeout(r, 150));
expect(creates()).toBe(1);
expect(h.hermes.executions).toBe(0); // the turn is waiting for its conversation, not racing it
gate.release(0);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(1);
const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId;
expect(stored).toBe(snapshot.state.conversationId);
expect(stored).toBe(await serverActive());
expect(snapshot.lastTurn!.conversation_id).toBe(stored);
expect(snapshot.lastTurn!.outcome).toBe('succeeded');
expect(h.hermes.sessions.size).toBe(1);
});
it('first question right after pairing, cancelled and asked again while the lazy create is still pending: still one create', async () => {
await pairedController();
const gate = holdCreates();
controller.askText('one');
await until('create reached the bridge', () => gate.count() === 1);
device.doubleTap(); // abandon the first question; the create it started is still in flight
controller.askText('two');
await new Promise((r) => setTimeout(r, 150));
expect(creates()).toBe(1);
gate.release(0);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(1);
expect(h.hermes.lastRun()!.input).toBe('two');
expect(h.hermes.executions).toBe(1);
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBe(await serverActive());
});
it('a reset during a pending create: replies arrive out of order, yet app and bridge agree on the live conversation and the next question succeeds', async () => {
await pairedController();
const gate = holdCreates();
controller.askText('one'); // lazy create A
await until('create A at the bridge', () => gate.count() === 1);
device.doubleTap();
device.menu(MENU_ITEM.NEW_CONVERSATION); // reset: create B is wanted while A is unanswered
await new Promise((r) => setTimeout(r, 150));
// B is not sent until A has settled, so the bridge can never process them in the wrong order.
expect(creates()).toBe(1);
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull();
gate.release(0); // A's reply arrives late, for a conversation the user has already replaced
await until('create B at the bridge', () => gate.count() === 2);
// A's result was dropped before persistence.
expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull();
expect(snapshot.state.conversationId).toBeNull();
controller.askText('first question after the reset'); // immediate first turn, B still pending
gate.release(1);
await until('answer', () => phase() === 'answer');
expect(creates()).toBe(2); // one per conversation the user asked for, never more
const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId;
expect(stored).toBe(await serverActive());
expect(snapshot.lastTurn!.conversation_id).toBe(stored);
expect(snapshot.lastTurn!.outcome).toBe('succeeded');
expect(h.hermes.executions).toBe(1);
});
});
+230
View File
@@ -0,0 +1,230 @@
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CALL_TIMEOUT_MS, EvenDevice } from '../../apps/even-client/src/device/evenAdapter.ts';
import { BridgeClient, isLoopbackHost, normalizeBridgeUrl } from '../../apps/even-client/src/net/bridgeClient.ts';
describe('CODY-001: the bridge address must be HTTPS, or HTTP to loopback only', () => {
const REMOTE_HTTP = [
'http://bridge.example.com',
'http://bridge.example.com:8787/x',
'http://203.0.113.7:8787', // public
'http://192.168.1.20:8787', // private LAN
'http://10.0.0.5',
'http://172.16.4.4:80',
'http://100.114.1.2:8787', // carrier-grade / tailnet range
'http://169.254.1.1',
'http://[fe80::1]:8787',
'http://[2001:db8::1]',
'http://0.0.0.0:8787',
'http://localhost.example.com', // loopback look-alikes
'http://127.0.0.1.example.com',
'http://127.evil.example',
'http://my-laptop.local:8787',
];
it('rejects every public and private-LAN HTTP address', () => {
for (const url of REMOTE_HTTP) expect(() => normalizeBridgeUrl(url), url).toThrow(/https/);
});
it('rejects other schemes, credentials in the URL, and non-URLs', () => {
for (const url of ['ftp://bridge.example', 'ws://bridge.example', 'javascript:alert(1)', 'file:///etc/passwd', 'bridge.example', '']) {
expect(() => normalizeBridgeUrl(url), url).toThrow();
}
expect(() => normalizeBridgeUrl('https://user:pass@bridge.example')).toThrow(/user name or password/);
});
it('accepts HTTPS anywhere and HTTP only on loopback', () => {
expect(normalizeBridgeUrl(' https://bridge.example.com/ ')).toBe('https://bridge.example.com');
expect(normalizeBridgeUrl('https://192.168.1.20:8443/p/x/')).toBe('https://192.168.1.20:8443/p/x');
expect(normalizeBridgeUrl('http://127.0.0.1:8787')).toBe('http://127.0.0.1:8787');
expect(normalizeBridgeUrl('http://localhost:8787/')).toBe('http://localhost:8787');
expect(normalizeBridgeUrl('http://[::1]:8787')).toBe('http://[::1]:8787');
expect(normalizeBridgeUrl('http://127.8.9.10')).toBe('http://127.8.9.10');
expect(isLoopbackHost('LOCALHOST')).toBe(false); // URL parsing lower-cases; raw input is not trusted
});
it('the HTTP client itself refuses a remote HTTP base URL, so no code path can bypass the check', () => {
expect(() => new BridgeClient({ baseUrl: 'http://192.168.1.20:8787' })).toThrow(/https/);
expect(() => new BridgeClient({ baseUrl: 'https://bridge.example.com' })).not.toThrow();
});
describe('manifest generation', () => {
const script = fileURLToPath(new URL('../../apps/even-client/scripts/write-manifest.mjs', import.meta.url));
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'hermeven-manifest-'));
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
const run = (origin: string) =>
spawnSync(process.execPath, [script], {
env: { ...process.env, HERMEVEN_BRIDGE_ORIGIN: origin, HERMEVEN_MANIFEST_OUT: join(dir, 'app.json') },
encoding: 'utf8',
});
it('exits nonzero and writes nothing for remote HTTP origins', () => {
for (const origin of ['http://bridge.example.com', 'http://192.168.1.20:8787', 'http://10.0.0.5', 'http://localhost.example.com']) {
const res = run(origin);
expect(res.status, origin).toBe(1);
expect(res.stderr).toContain('https://');
expect(existsSync(join(dir, 'app.json')), origin).toBe(false);
}
});
it('writes the whitelist for HTTPS, and for loopback HTTP with a warning', () => {
const https = run('https://bridge.example.com');
expect(https.status).toBe(0);
const manifest = JSON.parse(readFileSync(join(dir, 'app.json'), 'utf8'));
expect(manifest.permissions[0]).toMatchObject({ name: 'network', whitelist: ['https://bridge.example.com'] });
const loopback = run('http://127.0.0.1:8787');
expect(loopback.status).toBe(0);
expect(loopback.stderr).toContain('simulator only');
});
it('still refuses origins with a path', () => {
expect(run('https://bridge.example.com/api').status).toBe(1);
});
});
});
describe('CODY-002: host calls stay serialised and a late microphone start ends closed', () => {
type Call = { name: string; args: unknown[]; resolve: (value: unknown) => void; settled: boolean };
/** A stand-in for the Even host whose calls settle only when the test says so. */
function fakeHost() {
const calls: Call[] = [];
let inFlight = 0;
let maxInFlight = 0;
let micOpen = false;
const call = (name: string, args: unknown[], onSettle?: (value: unknown) => void) =>
new Promise((resolve) => {
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
const entry: Call = {
name,
args,
settled: false,
resolve: (value) => {
entry.settled = true;
inFlight -= 1;
onSettle?.(value);
resolve(value);
},
};
calls.push(entry);
});
const bridge = {
createStartUpPageContainer: (...a: unknown[]) => call('create', a),
textContainerUpgrade: (...a: unknown[]) => call('text', a),
audioControl: (open: boolean, ...rest: unknown[]) =>
call(open ? 'mic_on' : 'mic_off', [open, ...rest], (ok) => {
if (ok) micOpen = open;
}),
shutDownPageContainer: (...a: unknown[]) => call('exit', a),
getLocalStorage: (...a: unknown[]) => call('get', a),
setLocalStorage: (...a: unknown[]) => call('set', a),
};
return { bridge, calls, micOpen: () => micOpen, maxInFlight: () => maxInFlight, pending: () => calls.filter((c) => !c.settled) };
}
const tick = async () => {
for (let i = 0; i < 10; i++) await Promise.resolve();
};
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it('timeout, then the host opens the microphone late: the microphone ends closed and calls never overlap', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const starting = device.startMic();
await tick();
expect(host.pending().map((c) => c.name)).toEqual(['mic_on']);
// The host does not answer within the caller's timeout.
await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1);
expect(await starting).toBe(false); // the app is told the microphone did not open
// Nothing else has been sent to the host while the start is still pending.
expect(host.calls.map((c) => c.name)).toEqual(['mic_on']);
expect(host.maxInFlight()).toBe(1);
// Now the late completion arrives: the host really did open the microphone.
host.pending()[0]!.resolve(true);
await tick();
expect(host.micOpen()).toBe(true);
// The compensating stop goes out next, strictly after the start settled.
expect(host.calls.map((c) => c.name)).toEqual(['mic_on', 'mic_off']);
host.pending()[0]!.resolve(true);
await tick();
expect(host.micOpen()).toBe(false);
expect(host.maxInFlight()).toBe(1);
expect(host.pending()).toEqual([]);
});
it('a stop requested while the start is still pending waits its turn and still leaves the microphone closed', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const starting = device.startMic();
await tick();
const stopping = device.stopMic(); // user cancelled while the microphone was opening
device.show({ body: 'x', status: 'y' });
await tick();
expect(host.calls.map((c) => c.name)).toEqual(['mic_on']); // stop is queued, not sent alongside
host.pending()[0]!.resolve(true);
await tick();
expect(await starting).toBe(true);
expect(host.calls.map((c) => c.name)).toEqual(['mic_on', 'mic_off']);
host.pending()[0]!.resolve(true);
await stopping;
expect(host.micOpen()).toBe(false);
expect(host.maxInFlight()).toBe(1);
});
it('a start that times out and then fails late leaves nothing open and the queue usable', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const starting = device.startMic();
await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1);
expect(await starting).toBe(false);
host.pending()[0]!.resolve(false); // the host refused after all
await tick();
host.pending()[0]!.resolve(true); // the compensating stop
await tick();
expect(host.micOpen()).toBe(false);
// A later start works normally.
const again = device.startMic();
await tick();
host.pending()[0]!.resolve(true);
expect(await again).toBe(true);
expect(host.micOpen()).toBe(true);
expect(host.maxInFlight()).toBe(1);
});
it('many calls behind a stuck one each time out for their caller but are sent one at a time, in order', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const a = device.storageGet('a');
const b = device.storageSet('b', '1');
const c = device.requestExit();
await tick();
expect(host.calls.map((x) => x.name)).toEqual(['get']);
await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1);
expect(await a).toBe(''); // bounded for the caller
await b;
await c;
expect(host.calls.map((x) => x.name)).toEqual(['get']); // still only the stuck call at the host
host.pending()[0]!.resolve('late');
await tick();
expect(host.calls.map((x) => x.name)).toEqual(['get', 'set']);
host.pending()[0]!.resolve(true);
await tick();
expect(host.calls.map((x) => x.name)).toEqual(['get', 'set', 'exit']);
expect(host.maxInFlight()).toBe(1);
});
});
+2
View File
@@ -79,6 +79,8 @@ export async function createHarness(
const boot = async () => { const boot = async () => {
h.bridge = await createBridge(config, { h.bridge = await createBridge(config, {
timing, timing,
// Fast sweep so a database-only revocation (the operator CLI path) is seen quickly.
cancelSweepMs: 25,
logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink), logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink),
}); });
await h.bridge.app.listen({ host: '127.0.0.1', port: 0 }); await h.bridge.app.listen({ host: '127.0.0.1', port: 0 });
+24
View File
@@ -0,0 +1,24 @@
// Run inside a network namespace with no interfaces (`unshare -rn`). Proves the built-in
// speech model verifies and transcribes with no network at all. Prints one JSON line.
import { readFileSync } from 'node:fs';
import { loadConfig } from '../../services/bridge/src/config.ts';
import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts';
const [modelDir, wavPath] = process.argv.slice(2);
let networkReachable = true;
try {
await fetch('https://huggingface.co/', { signal: AbortSignal.timeout(3000) });
} catch {
networkReachable = false;
}
const config = loadConfig({ HERMES_API_KEY: 'unused', HERMEVEN_DB_PATH: ':memory:', STT_MODEL_DIR: modelDir });
const stt = new BuiltinWhisperStt({ manifest: config.stt.manifest!, modelDir: config.stt.modelDir });
let text = '';
let error: string | null = null;
try {
text = await stt.transcribe({ pcm: readFileSync(wavPath!).subarray(44), locale: 'en-US', signal: new AbortController().signal });
} catch (err) {
error = `${(err as Error).name}:${stt.lastLoadFailure}`;
}
await stt.close();
console.log(JSON.stringify({ networkReachable, text, error, revision: config.stt.manifest!.revision }));
+110 -18
View File
@@ -1,8 +1,11 @@
import { readFileSync } from 'node:fs'; import { spawnSync } from 'node:child_process';
import { dirname, resolve } from 'node:path'; import { chmodSync, cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts'; import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts';
import { fetchModel, modelPath, verifyModel, type ModelManifest } from '../../services/bridge/src/stt/modelStore.mjs';
import { createHarness, type Harness } from '../integration/harness.ts'; import { createHarness, type Harness } from '../integration/harness.ts';
/** /**
@@ -15,30 +18,59 @@ import { createHarness, type Harness } from '../integration/harness.ts';
*/ */
const here = dirname(fileURLToPath(import.meta.url)); const here = dirname(fileURLToPath(import.meta.url));
const speech = readFileSync(resolve(here, 'fixtures/jfk.wav')).subarray(44); // strip the WAV header: raw PCM const speech = readFileSync(resolve(here, 'fixtures/jfk.wav')).subarray(44); // strip the WAV header: raw PCM
const store = resolve(here, '.cache');
let h: Harness; let h: Harness;
let token: string; let token: string;
let conversation: string; let conversation: string;
let manifest: ModelManifest;
const scratch: string[] = [];
function chmodTree(path: string, dirMode: number, fileMode: number): void {
chmodSync(path, dirMode);
for (const entry of readdirSync(path, { withFileTypes: true })) {
const child = join(path, entry.name);
if (entry.isDirectory()) chmodTree(child, dirMode, fileMode);
else chmodSync(child, fileMode);
}
}
/** A private copy of the verified model store, so a test can damage or lock it. */
function copyStore(): string {
const dir = mkdtempSync(join(tmpdir(), 'hermeven-model-copy-'));
scratch.push(dir);
cpSync(store, dir, { recursive: true });
return dir;
}
beforeAll(async () => { beforeAll(async () => {
h = await createHarness({ h = await createHarness({
stt: false, stt: false,
env: { env: {
STT_PROVIDER: 'builtin', STT_PROVIDER: 'builtin',
STT_CACHE_DIR: resolve(here, '.cache'), STT_MODEL_DIR: store,
HERMEVEN_CAPTURE_MAX_SECONDS: '30', HERMEVEN_CAPTURE_MAX_SECONDS: '30',
}, },
timing: { transcribeDeadlineMs: 120_000, agentDeadlineMs: 30_000 }, timing: { transcribeDeadlineMs: 120_000, agentDeadlineMs: 30_000 },
}); });
expect(h.bridge.stt).toBeInstanceOf(BuiltinWhisperStt); expect(h.bridge.stt).toBeInstanceOf(BuiltinWhisperStt);
manifest = h.config.stt.manifest!;
// The deployment step: fetch the pinned revision from the real hub and verify every file
// against the SHA-256 values committed in services/bridge/models/. Files already present and
// correct are not downloaded again.
const fetched = await fetchModel(store, manifest);
console.info(`[real-stt] pinned ${manifest.model}@${manifest.revision}: ${fetched.verified} files verified, ${fetched.downloaded} downloaded`);
const started = Date.now(); const started = Date.now();
await (h.bridge.stt as BuiltinWhisperStt).warm(); await (h.bridge.stt as BuiltinWhisperStt).warm();
console.info(`[real-stt] model ${h.config.stt.model} (${h.config.stt.dtype}) loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`); console.info(`[real-stt] model verified and loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`);
token = (await h.pair()).token; token = (await h.pair()).token;
conversation = await h.conversation(token); conversation = await h.conversation(token);
}); });
afterAll(async () => { afterAll(async () => {
await h?.close(); await h?.close();
for (const dir of scratch) {
if (existsSync(dir)) chmodTree(dir, 0o700, 0o600);
rmSync(dir, { recursive: true, force: true });
}
}); });
describe('built-in Whisper speech-to-text', () => { describe('built-in Whisper speech-to-text', () => {
@@ -105,21 +137,8 @@ describe('built-in Whisper speech-to-text', () => {
expect(doneB.input_text).toContain('fellow Americans'); expect(doneB.input_text).toContain('fellow Americans');
}); });
it('a model that cannot be loaded makes speech "unavailable" without taking the bridge down', async () => {
const broken = new BuiltinWhisperStt({ model: 'hermeven-test/does-not-exist', dtype: 'q8', cacheDir: resolve(here, '.cache') });
try {
const err = await broken
.transcribe({ pcm: Buffer.from(speech.subarray(0, 32000)), locale: 'en-US', signal: new AbortController().signal })
.catch((e) => e);
expect(err).toMatchObject({ name: 'SttError', kind: 'unavailable' });
} finally {
await broken.close();
}
expect((await h.api('GET', '/healthz')).status).toBe(200);
});
it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => { it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => {
const stt = new BuiltinWhisperStt({ model: h.config.stt.model, dtype: h.config.stt.dtype, cacheDir: resolve(here, '.cache') }); const stt = new BuiltinWhisperStt({ manifest, modelDir: store });
const signal = new AbortController().signal; const signal = new AbortController().signal;
expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans'); expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans');
await stt.close(); await stt.close();
@@ -134,4 +153,77 @@ describe('built-in Whisper speech-to-text', () => {
expect(done.outcome).toBe('succeeded'); expect(done.outcome).toBe('succeeded');
expect((done.input_text ?? '').toLowerCase()).toContain('fellow americans'); expect((done.input_text ?? '').toLowerCase()).toContain('fellow americans');
}); });
describe('deployment checks (CODY-005): pinned, verified, offline, read-only', () => {
const signal = new AbortController().signal;
it('the real artifacts on disk match the committed pins', async () => {
expect(await verifyModel(store, manifest)).toEqual({ ok: true });
expect(manifest.revision).toMatch(/^[0-9a-f]{40}$/);
});
it('one changed byte in the real model: load is refused as a mismatch, speech is unavailable, the bridge keeps running', async () => {
const dir = copyStore();
const target = join(modelPath(dir, manifest), 'onnx/encoder_model_quantized.onnx');
const bytes = readFileSync(target);
const middle = bytes.length >> 1;
bytes[middle] = bytes[middle]! ^ 0x01;
writeFileSync(target, bytes);
expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'onnx/encoder_model_quantized.onnx' });
const stt = new BuiltinWhisperStt({ manifest, modelDir: dir });
try {
await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
expect(stt.lastLoadFailure).toBe('mismatch');
} finally {
await stt.close();
}
expect((await h.api('GET', '/healthz')).status).toBe(200);
});
it('a missing file is refused as missing, with no attempt to download it', async () => {
const dir = copyStore();
rmSync(join(modelPath(dir, manifest), 'tokenizer.json'));
const stt = new BuiltinWhisperStt({ manifest, modelDir: dir });
try {
await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' });
expect(stt.lastLoadFailure).toBe('missing');
} finally {
await stt.close();
}
expect(existsSync(join(modelPath(dir, manifest), 'tokenizer.json'))).toBe(false);
});
it('transcribes from a read-only model store and writes nothing into it', async () => {
const dir = copyStore();
chmodTree(dir, 0o500, 0o400);
const before = readdirSync(modelPath(dir, manifest), { recursive: true }).sort();
const stt = new BuiltinWhisperStt({ manifest, modelDir: dir });
try {
expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans');
} finally {
await stt.close();
}
expect(readdirSync(modelPath(dir, manifest), { recursive: true }).sort()).toEqual(before);
});
it('verifies and transcribes with no network at all (network namespace with no interfaces)', () => {
const probe = spawnSync(
'unshare',
['-rn', process.execPath, '--import', 'tsx', resolve(here, 'offlineProbe.mts'), store, resolve(here, 'fixtures/jfk.wav')],
{ encoding: 'utf8', cwd: resolve(here, '../../services/bridge'), timeout: 120_000 },
);
if (probe.error || (probe.status !== 0 && /unshare|Operation not permitted/i.test(probe.stderr))) {
// Reported, not hidden: on this machine the offline proof could not be run.
console.info(`[real-stt] OFFLINE CHECK NOT RUN: unprivileged network namespaces are unavailable (${(probe.stderr || String(probe.error)).trim().slice(0, 120)})`);
return;
}
expect(probe.status, probe.stderr.slice(-500)).toBe(0);
const out = JSON.parse(probe.stdout.trim().split('\n').at(-1)!);
console.info(`[real-stt] offline run: networkReachable=${out.networkReachable} transcript=${JSON.stringify(out.text)}`);
expect(out.networkReachable).toBe(false);
expect(out.error).toBeNull();
expect(out.revision).toBe(manifest.revision);
expect(out.text).toContain('ask not what your country can do for you');
});
});
}); });