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:
@@ -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 });
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
export async function createBridge(
|
||||
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> {
|
||||
const db = openDb(config.dbPath);
|
||||
const hermes =
|
||||
@@ -65,13 +65,16 @@ export async function createBridge(
|
||||
? (given as Logger)
|
||||
: pino(given as object)
|
||||
: pino({ level: 'silent' });
|
||||
const engine = new TurnEngine({ db, config, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const 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 });
|
||||
|
||||
engine.recover();
|
||||
engine.purgeExpired();
|
||||
const purge = setInterval(() => engine.purgeExpired(), 60_000);
|
||||
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 {
|
||||
app,
|
||||
@@ -81,6 +84,7 @@ export async function createBridge(
|
||||
engine,
|
||||
async close() {
|
||||
clearInterval(purge);
|
||||
clearInterval(cancelSweep);
|
||||
await app.close();
|
||||
await engine.shutdown();
|
||||
await stt.close?.();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ConfigError, loadConfig } from './config.ts';
|
||||
import { openDb } from './db.ts';
|
||||
import { Devices } from './devices.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
|
||||
@@ -15,17 +16,45 @@ function usage(): never {
|
||||
' pair Print a single-use pairing code for one new device',
|
||||
' devices List paired devices',
|
||||
' 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'),
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
async function main(): Promise<void> {
|
||||
loadEnvFile();
|
||||
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 devices = new Devices(db, config);
|
||||
const [command, arg] = process.argv.slice(2);
|
||||
|
||||
switch (command) {
|
||||
case 'pair': {
|
||||
@@ -62,9 +91,7 @@ function main(): void {
|
||||
db.close();
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (err) {
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err);
|
||||
main().catch((err: unknown) => {
|
||||
console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
|
||||
|
||||
export interface BridgeConfig {
|
||||
host: string;
|
||||
@@ -25,11 +28,11 @@ export interface BridgeConfig {
|
||||
provider: 'none' | 'builtin' | 'openai-compatible';
|
||||
baseUrl: 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;
|
||||
/** `builtin` only: weight precision and where model files are cached. */
|
||||
dtype: string;
|
||||
cacheDir: string;
|
||||
/** `builtin` only: the pinned artifacts to load, and the directory they are read from. */
|
||||
manifest: ModelManifest | null;
|
||||
modelDir: string;
|
||||
};
|
||||
limits: {
|
||||
captureMaxSeconds: number;
|
||||
@@ -46,7 +49,6 @@ export interface BridgeConfig {
|
||||
tokenTtlSeconds: number;
|
||||
pairingTtlSeconds: number;
|
||||
pairingCodeTtlSeconds: number;
|
||||
pairingCodeMaxFailures: number;
|
||||
};
|
||||
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
|
||||
resultRetentionSeconds: number;
|
||||
@@ -98,6 +100,34 @@ function httpUrl(key: string, raw: string): string {
|
||||
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 {
|
||||
const host = env.HERMEVEN_HOST || '127.0.0.1';
|
||||
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') {
|
||||
throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"');
|
||||
}
|
||||
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'onnx-community/whisper-base' : '');
|
||||
if (sttProvider === 'builtin' && !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(sttModel)) {
|
||||
throw new ConfigError('STT_MODEL must be a Hugging Face model id such as onnx-community/whisper-base');
|
||||
}
|
||||
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');
|
||||
}
|
||||
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'whisper-base' : '');
|
||||
// The built-in model is always pinned: a commit id plus a SHA-256 for every file. There is
|
||||
// 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;
|
||||
let sttBaseUrl = '';
|
||||
if (sttProvider === '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,
|
||||
apiKey: env.STT_API_KEY || '',
|
||||
model: sttModel,
|
||||
dtype: sttDtype,
|
||||
cacheDir: env.STT_CACHE_DIR || './data/models',
|
||||
manifest: sttManifest,
|
||||
modelDir: env.STT_MODEL_DIR || './data/models',
|
||||
},
|
||||
limits: {
|
||||
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),
|
||||
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 86_400, 60),
|
||||
pairingCodeTtlSeconds: int(env, 'HERMEVEN_PAIRING_CODE_TTL_SECONDS', 300, 30, 3600),
|
||||
pairingCodeMaxFailures: int(env, 'HERMEVEN_PAIRING_CODE_MAX_FAILURES', 5, 1, 20),
|
||||
},
|
||||
resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
|
||||
logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
export type Db = Database.Database;
|
||||
@@ -66,15 +66,47 @@ const MIGRATIONS: string[] = [
|
||||
CREATE INDEX turns_conversation ON turns(conversation_id, 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 {
|
||||
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);
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
migrate(db);
|
||||
secureDbFiles(path);
|
||||
return db;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,15 @@ export interface DeviceRow {
|
||||
}
|
||||
|
||||
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.
|
||||
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 {
|
||||
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
|
||||
* outstanding code, so the code is burned after a few failures regardless of who guessed.
|
||||
* Exchange a pairing code for a device credential. A wrong, expired or already-used code
|
||||
* all fail the same way and change nothing: only the correct code consumes the code.
|
||||
*/
|
||||
claimPairingCode(
|
||||
rawCode: string,
|
||||
@@ -66,22 +70,10 @@ export class Devices {
|
||||
const hash = sha256(normalizeCode(rawCode));
|
||||
return this.db.transaction(() => {
|
||||
const live = this.db
|
||||
.prepare('SELECT id, code_hash, failed_attempts FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?')
|
||||
.all(now) as Array<{ id: number; code_hash: string; failed_attempts: number }>;
|
||||
.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 }>;
|
||||
const match = live.find((row) => safeEqualHex(row.code_hash, hash));
|
||||
if (!match) {
|
||||
let locked = false;
|
||||
for (const row of live) {
|
||||
const failures = row.failed_attempts + 1;
|
||||
if (failures >= this.config.credentials.pairingCodeMaxFailures) {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ?, used_at = ? WHERE id = ?').run(failures, now, row.id);
|
||||
locked = true;
|
||||
} else {
|
||||
this.db.prepare('UPDATE pairing_codes SET failed_attempts = ? WHERE id = ?').run(failures, row.id);
|
||||
}
|
||||
}
|
||||
return { ok: false as const, reason: locked ? ('pairing_locked' as const) : ('pairing_invalid' as const) };
|
||||
}
|
||||
if (!match) return { ok: false as const, reason: 'pairing_invalid' as const };
|
||||
this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE id = ?').run(now, match.id);
|
||||
const token = newToken();
|
||||
const device: DeviceRow = {
|
||||
@@ -130,11 +122,21 @@ export class Devices {
|
||||
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 {
|
||||
const now = this.now();
|
||||
return this.db.transaction(() => {
|
||||
const res = this.db.prepare('UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').run(now, deviceId);
|
||||
this.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
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;
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -11,14 +11,25 @@ async function main(): Promise<void> {
|
||||
});
|
||||
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
|
||||
// slowed by it. On a first start this downloads the model files.
|
||||
if (bridge.stt instanceof BuiltinWhisperStt) {
|
||||
// Verify and load the built-in speech model in the background so the first spoken question
|
||||
// is not slowed by it. Nothing is downloaded here: the files must already be in the model
|
||||
// store (`bridge:cli fetch-model`) and must match their pinned hashes.
|
||||
const stt = bridge.stt;
|
||||
if (stt instanceof BuiltinWhisperStt) {
|
||||
const started = Date.now();
|
||||
bridge.app.log.info({ model: config.stt.model, dtype: config.stt.dtype }, 'stt.loading');
|
||||
bridge.stt.warm().then(
|
||||
() => bridge.app.log.info({ load_ms: Date.now() - started }, 'stt.ready'),
|
||||
() => bridge.app.log.error({ model: config.stt.model }, 'stt.load_failed'),
|
||||
const pin = { model: config.stt.manifest!.model, revision: config.stt.manifest!.revision };
|
||||
bridge.app.log.info(pin, 'stt.loading');
|
||||
stt.warm().then(
|
||||
() => 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',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -171,12 +171,8 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device');
|
||||
if (!result.ok) {
|
||||
req.log.warn({ reason: result.reason }, 'pairing.rejected');
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'pairing_locked'
|
||||
? 'Too many wrong codes. Generate a new pairing code on the bridge.'
|
||||
: 'Pairing code is not valid.',
|
||||
);
|
||||
// One answer for wrong, expired and used codes: the response reveals nothing about which.
|
||||
throw new ApiError('pairing_invalid', 'Pairing code is not valid.');
|
||||
}
|
||||
req.log.info({ device_id: result.device.id }, 'pairing.claimed');
|
||||
return reply.code(201).send(credential(result.device, result.token));
|
||||
@@ -212,7 +208,7 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
|
||||
app.delete('/v1/device', async (req) => {
|
||||
const device = authenticate(req);
|
||||
devices.revoke(device.id);
|
||||
engine.revokeDevice(device.id);
|
||||
req.log.info({ device_id: device.id }, 'device.revoked');
|
||||
return { schema_version: SCHEMA_VERSION, revoked: true };
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { AUDIO_FORMAT } from '@hermeven/contracts';
|
||||
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
|
||||
@@ -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
|
||||
* 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
|
||||
* bridge starts and are then read from `cacheDir`.
|
||||
* The bridge never downloads anything at run time. Model files are fetched ahead of
|
||||
* 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 {
|
||||
/** Hub id, for example `onnx-community/whisper-base` (multilingual) or `...-base.en`. */
|
||||
model: string;
|
||||
/** Weight precision. `q8` is the small, CPU-friendly default. */
|
||||
dtype: string;
|
||||
cacheDir: string;
|
||||
/** What exactly to load: hub id, immutable revision, precision, and each file's hash. */
|
||||
manifest: ModelManifest;
|
||||
/** Model store directory. Read-only at run time. */
|
||||
modelDir: string;
|
||||
/** Test seam: replaces the worker thread with an in-process recogniser. */
|
||||
load?: () => Promise<Recognizer>;
|
||||
}
|
||||
@@ -58,6 +59,8 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
private recognizer: Promise<Recognizer> | null = null;
|
||||
private worker: Worker | null = null;
|
||||
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. */
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
@@ -102,9 +105,10 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
};
|
||||
worker.on('error', () => fail('worker error'));
|
||||
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') {
|
||||
loaded = true;
|
||||
this.lastLoadFailure = null;
|
||||
resolve(
|
||||
(audio, options) =>
|
||||
new Promise((res, rej) => {
|
||||
@@ -115,6 +119,7 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
}),
|
||||
);
|
||||
} else if (message.type === 'load_failed') {
|
||||
this.lastLoadFailure = message.reason ?? 'load';
|
||||
void worker.terminate();
|
||||
} else if (message.id !== undefined) {
|
||||
const pending = waiting.get(message.id);
|
||||
@@ -123,7 +128,7 @@ export class BuiltinWhisperStt implements SttAdapter {
|
||||
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
|
||||
// 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' };
|
||||
try {
|
||||
|
||||
@@ -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 }>;
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -2,27 +2,41 @@
|
||||
// directly by `new Worker(...)`, so it must run without any TypeScript loader.
|
||||
//
|
||||
// Protocol (all messages are plain objects):
|
||||
// in : { type: 'load', model, dtype, cacheDir }
|
||||
// out: { type: 'loaded' } | { type: 'load_failed' }
|
||||
// in : { type: 'load', dir, manifest }
|
||||
// out: { type: 'loaded' } | { type: 'load_failed', reason: 'missing' | 'mismatch' | 'load' }
|
||||
// in : { type: 'run', id, samples: Float32Array, options }
|
||||
// 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.
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
import { verifyModel } from './modelStore.mjs';
|
||||
|
||||
let recognizer = null;
|
||||
|
||||
parentPort.on('message', async (message) => {
|
||||
if (message.type === 'load') {
|
||||
try {
|
||||
const { pipeline } = await import('@huggingface/transformers');
|
||||
recognizer = await pipeline('automatic-speech-recognition', message.model, {
|
||||
dtype: message.dtype,
|
||||
cache_dir: message.cacheDir,
|
||||
// 1. The files on disk must be exactly the pinned ones.
|
||||
const check = await verifyModel(message.dir, message.manifest);
|
||||
if (!check.ok) {
|
||||
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' });
|
||||
} catch {
|
||||
parentPort.postMessage({ type: 'load_failed' });
|
||||
parentPort.postMessage({ type: 'load_failed', reason: 'load' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
import type { Devices } from './devices.ts';
|
||||
import {
|
||||
buildRunBody,
|
||||
HermesSubmitError,
|
||||
@@ -39,6 +40,8 @@ export interface TurnRow {
|
||||
updated_at: number;
|
||||
agent_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;
|
||||
transcribe_ms: number | null;
|
||||
agent_ms: number | null;
|
||||
@@ -118,6 +121,7 @@ export class TurnEngine {
|
||||
private readonly deps: {
|
||||
db: Db;
|
||||
config: BridgeConfig;
|
||||
devices: Devices;
|
||||
hermes: HermesAdapter;
|
||||
stt: SttAdapter;
|
||||
log: EngineLog;
|
||||
@@ -220,6 +224,7 @@ export class TurnEngine {
|
||||
updated_at: now,
|
||||
agent_started_at: null,
|
||||
approval_started_at: null,
|
||||
agent_deadline_at: null,
|
||||
completed_at: null,
|
||||
transcribe_ms: null,
|
||||
agent_ms: null,
|
||||
@@ -261,6 +266,38 @@ export class TurnEngine {
|
||||
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. */
|
||||
recover(): void {
|
||||
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;
|
||||
// Persist the exact body BEFORE the first network attempt, so a crash can replay it
|
||||
// under the same idempotency key instead of guessing.
|
||||
const agentStartedAt = this.now();
|
||||
this.setState(requestId, 'thinking', {
|
||||
pending_body: buildRunBody({
|
||||
input: row.input_text ?? '',
|
||||
sessionId: conversation.hermes_session_id,
|
||||
instructions: this.deps.config.hermes.instructions,
|
||||
}),
|
||||
agent_started_at: this.now(),
|
||||
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. */
|
||||
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise<string | null> {
|
||||
const row = this.row(requestId)!;
|
||||
const deadline = (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
const deadline = row.agent_deadline_at ?? (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let ambiguous = maybeAlreadySent;
|
||||
let notSent = 0;
|
||||
|
||||
@@ -529,8 +568,11 @@ export class TurnEngine {
|
||||
private async poll(requestId: string, active: ActiveTurn): Promise<void> {
|
||||
const start = this.row(requestId)!;
|
||||
const runId = start.hermes_run_id!;
|
||||
let deadlineAt = (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let approvalSince: number | null = null;
|
||||
// Both clocks come from the database, so a bridge restart resumes them where they were:
|
||||
// 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 stopAccepted = false;
|
||||
let graceUntil = 0;
|
||||
@@ -587,14 +629,20 @@ export class TurnEngine {
|
||||
this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
return;
|
||||
case 'waiting_for_approval':
|
||||
if (approvalSince === null) approvalSince = now;
|
||||
if (!stopReason) this.setState(requestId, 'approval_required', { approval_started_at: now });
|
||||
if (approvalSince === null) {
|
||||
// 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;
|
||||
default:
|
||||
if (approvalSince !== null) {
|
||||
// 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;
|
||||
approvalSince = null;
|
||||
this.update(requestId, { agent_deadline_at: deadlineAt, approval_started_at: null });
|
||||
}
|
||||
if (!stopReason) this.setState(requestId, 'thinking');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user