Choose an agent with a swipe at Ready (0.2.0)
Bridge: an owner-configured list of agents (HERMEVEN_AGENTS). Each extra agent is another profile of the same Hermes gateway, reached at /p/<profile> with that profile's own key. GET /v1/agents lists ids and names; POST /v1/conversations takes an optional agent_id checked against the list. A conversation belongs to one agent (migration v3) and its turns are submitted, polled and stopped at that agent. /v1/device is unchanged so clients built earlier keep working. Client: at Ready a swipe moves between agents; the name is shown through the exchange; each agent keeps its own conversation; a follow-up goes to the agent that answered. Reopened within the conversation window it opens on the last agent, otherwise on the default. With one agent, or a bridge without /v1/agents, nothing changes. Also: contract section G, server survey and key evidence, the 0.1.2 upload, and the CODY-020 correction. Not reviewed, not deployed, not uploaded. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -55,6 +55,13 @@ export async function createBridge(
|
||||
apiKey: config.hermes.apiKey,
|
||||
requestTimeoutMs: config.hermes.requestTimeoutMs,
|
||||
});
|
||||
// One adapter per extra agent: its own address under the same gateway, and its own key.
|
||||
const agents = new Map<string, HermesAdapter>(
|
||||
config.agents.slice(1).map((agent) => [
|
||||
agent.id,
|
||||
new HermesRunsAdapter({ baseUrl: agent.baseUrl, apiKey: agent.apiKey, requestTimeoutMs: config.hermes.requestTimeoutMs }),
|
||||
]),
|
||||
);
|
||||
const stt = overrides.stt ?? sttFromConfig(config);
|
||||
const devices = new Devices(db, config);
|
||||
|
||||
@@ -65,7 +72,7 @@ export async function createBridge(
|
||||
? (given as Logger)
|
||||
: pino(given as object)
|
||||
: pino({ level: 'silent' });
|
||||
const engine = new TurnEngine({ db, config, devices, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const engine = new TurnEngine({ db, config, devices, hermes, agents, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
|
||||
const app = await buildServer({ config, devices, hermes, stt, engine, logger });
|
||||
|
||||
engine.recover();
|
||||
|
||||
@@ -3,6 +3,17 @@ import { fileURLToPath } from 'node:url';
|
||||
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
|
||||
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
|
||||
|
||||
export interface AgentConfig {
|
||||
/** `default` for the main agent; otherwise the id from HERMEVEN_AGENTS. */
|
||||
id: string;
|
||||
/** Shown on the glasses. */
|
||||
name: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_AGENT_ID = 'default';
|
||||
|
||||
export interface BridgeConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
@@ -30,6 +41,11 @@ export interface BridgeConfig {
|
||||
pollIntervalMs: number;
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
/**
|
||||
* Every agent a paired device may talk to, default first. The list is the owner's allow-list:
|
||||
* a client can only name an id from it. Each agent has its own Hermes address and its own key.
|
||||
*/
|
||||
agents: AgentConfig[];
|
||||
stt: {
|
||||
provider: 'none' | 'builtin' | 'openai-compatible';
|
||||
baseUrl: string;
|
||||
@@ -134,6 +150,49 @@ function loadModelManifest(name: string, customPath: string | undefined): ModelM
|
||||
}
|
||||
}
|
||||
|
||||
const AGENT_ID = /^[a-z][a-z0-9_-]{0,31}$/;
|
||||
|
||||
function agentName(key: string, raw: string | undefined, fallback: string): string {
|
||||
const name = (raw ?? '').trim() || fallback;
|
||||
if (name.length > 24 || /[\u0000-\u001f]/.test(name)) throw new ConfigError(`${key} must be at most 24 printable characters`);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default agent is the Hermes API server at HERMES_BASE_URL with HERMES_API_KEY. Further
|
||||
* agents are named in HERMEVEN_AGENTS (comma-separated ids) and are other profiles served by
|
||||
* the same Hermes gateway under `/p/<profile>` (gateway.multiplex_profiles). Hermes gives each
|
||||
* profile its own key and refuses the default's, so every extra agent needs
|
||||
* HERMEVEN_AGENT_<ID>_API_KEY. Optional: HERMEVEN_AGENT_<ID>_PROFILE (default: the id) and
|
||||
* HERMEVEN_AGENT_<ID>_NAME (default: the id, capitalised).
|
||||
*/
|
||||
function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: string): AgentConfig[] {
|
||||
const agents: AgentConfig[] = [
|
||||
{ id: DEFAULT_AGENT_ID, name: agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent'), baseUrl, apiKey: defaultKey },
|
||||
];
|
||||
const ids = (env.HERMEVEN_AGENTS ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const id of ids) {
|
||||
if (!AGENT_ID.test(id)) throw new ConfigError('HERMEVEN_AGENTS entries must be lower-case ids (letters, digits, - and _)');
|
||||
if (agents.some((a) => a.id === id)) throw new ConfigError(`HERMEVEN_AGENTS names "${id}" more than once (or uses the reserved id "default")`);
|
||||
const prefix = `HERMEVEN_AGENT_${id.toUpperCase().replace(/-/g, '_')}`;
|
||||
const apiKey = env[`${prefix}_API_KEY`] || '';
|
||||
if (!apiKey) throw new ConfigError(`${prefix}_API_KEY is required: Hermes gives each profile its own API key`);
|
||||
const profile = env[`${prefix}_PROFILE`] || id;
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(profile)) throw new ConfigError(`${prefix}_PROFILE is not a valid profile name`);
|
||||
agents.push({
|
||||
id,
|
||||
name: agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1)),
|
||||
baseUrl: `${baseUrl}/p/${profile}`,
|
||||
apiKey,
|
||||
});
|
||||
}
|
||||
if (agents.length > 16) throw new ConfigError('HERMEVEN_AGENTS lists too many agents (at most 15 besides the default)');
|
||||
return agents;
|
||||
}
|
||||
|
||||
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');
|
||||
@@ -146,6 +205,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
|
||||
const hermesKey = env.HERMES_API_KEY || '';
|
||||
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
|
||||
const hermesBaseUrl = httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642').replace(/\/+$/, '');
|
||||
|
||||
const originEntries = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
@@ -206,13 +266,14 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
allowNonLoopback,
|
||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||
hermes: {
|
||||
baseUrl: httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642'),
|
||||
baseUrl: hermesBaseUrl,
|
||||
apiKey: hermesKey,
|
||||
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
|
||||
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
|
||||
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 150, 20, 10_000),
|
||||
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
|
||||
},
|
||||
agents: agentsFromEnv(env, hermesBaseUrl, hermesKey),
|
||||
stt: {
|
||||
provider: sttProvider,
|
||||
baseUrl: sttBaseUrl,
|
||||
|
||||
@@ -71,6 +71,11 @@ const MIGRATIONS: string[] = [
|
||||
`
|
||||
ALTER TABLE turns ADD COLUMN agent_deadline_at INTEGER;
|
||||
`,
|
||||
// v3: a conversation belongs to one configured agent. NULL means the default agent, which is
|
||||
// what every conversation created before this was.
|
||||
`
|
||||
ALTER TABLE conversations ADD COLUMN agent_id TEXT;
|
||||
`,
|
||||
];
|
||||
|
||||
/** The database holds credential hashes and, briefly, question and answer text. */
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
AUDIO_FORMAT,
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
AgentsResponse,
|
||||
ConversationCreateRequest,
|
||||
httpStatusFor,
|
||||
isRetryable,
|
||||
@@ -17,7 +18,7 @@ import {
|
||||
type ErrorResponse,
|
||||
type Limits,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
||||
import type { DeviceRow, Devices } from './devices.ts';
|
||||
import type { HermesAdapter } from './hermes/adapter.ts';
|
||||
import { RateLimiter } from './ratelimit.ts';
|
||||
@@ -218,6 +219,16 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* The agents this device may talk to, default first. Names only: no address, profile or key
|
||||
* ever leaves the bridge. A separate route (not a field on /v1/device) so that clients built
|
||||
* before it existed, which reject unknown fields, keep working.
|
||||
*/
|
||||
app.get('/v1/agents', async (req): Promise<AgentsResponse> => {
|
||||
authenticate(req);
|
||||
return { schema_version: SCHEMA_VERSION, agents: config.agents.map(({ id, name }) => ({ id, name })) };
|
||||
});
|
||||
|
||||
app.post('/v1/device/renew', async (req) => {
|
||||
const device = authenticate(req);
|
||||
const renewed = devices.renew(device.id);
|
||||
@@ -238,7 +249,10 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const body = req.body as Record<string, unknown> | undefined;
|
||||
requireVersion(body?.schema_version);
|
||||
if (!check(ConversationCreateRequest, body)) throw new ApiError('invalid_request', 'Malformed conversation request.');
|
||||
const conversation = engine.createConversation(device.id);
|
||||
const agentId = (body as { agent_id?: string }).agent_id ?? DEFAULT_AGENT_ID;
|
||||
// Only an agent the owner listed. The id is never used to build an address here.
|
||||
if (!engine.knowsAgent(agentId)) throw new ApiError('invalid_request', 'Unknown agent.');
|
||||
const conversation = engine.createConversation(device.id, agentId);
|
||||
reply.code(201);
|
||||
return { schema_version: SCHEMA_VERSION, conversation_id: conversation.id, created_at: iso(conversation.created_at) };
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
type TurnResult,
|
||||
type TurnState,
|
||||
} from '@hermeven/contracts';
|
||||
import type { BridgeConfig } from './config.ts';
|
||||
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
|
||||
import type { Db } from './db.ts';
|
||||
import type { Devices } from './devices.ts';
|
||||
import {
|
||||
@@ -53,6 +53,8 @@ export interface ConversationRow {
|
||||
hermes_session_id: string;
|
||||
created_at: number;
|
||||
closed_at: number | null;
|
||||
/** The configured agent this conversation is with. NULL = the default agent. */
|
||||
agent_id: string | null;
|
||||
}
|
||||
|
||||
export interface EngineTiming {
|
||||
@@ -123,6 +125,8 @@ export class TurnEngine {
|
||||
config: BridgeConfig;
|
||||
devices: Devices;
|
||||
hermes: HermesAdapter;
|
||||
/** Adapters for the other configured agents, by id. The default one is `hermes`. */
|
||||
agents?: ReadonlyMap<string, HermesAdapter>;
|
||||
stt: SttAdapter;
|
||||
log: EngineLog;
|
||||
timing?: EngineTiming;
|
||||
@@ -138,8 +142,30 @@ export class TurnEngine {
|
||||
|
||||
// ------------------------------------------------------------ conversations
|
||||
|
||||
/** Start a fresh conversation for the device. Any earlier one is closed, not deleted. */
|
||||
createConversation(deviceId: string): ConversationRow {
|
||||
/** True when `agentId` names an agent this bridge is configured to reach. */
|
||||
knowsAgent(agentId: string): boolean {
|
||||
return agentId === DEFAULT_AGENT_ID || this.deps.agents?.has(agentId) === true;
|
||||
}
|
||||
|
||||
/** The Hermes adapter for a conversation's agent, or undefined if it is no longer configured. */
|
||||
private adapterFor(agentId: string | null): HermesAdapter | undefined {
|
||||
if (agentId === null || agentId === DEFAULT_AGENT_ID) return this.deps.hermes;
|
||||
return this.deps.agents?.get(agentId);
|
||||
}
|
||||
|
||||
private adapterForTurn(row: TurnRow): HermesAdapter | undefined {
|
||||
const conversation = this.deps.db.prepare('SELECT agent_id FROM conversations WHERE id = ?').get(row.conversation_id) as
|
||||
| { agent_id: string | null }
|
||||
| undefined;
|
||||
return conversation ? this.adapterFor(conversation.agent_id) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a fresh conversation for the device with one agent. Any earlier conversation with
|
||||
* THAT agent is closed, not deleted; conversations with other agents are left open.
|
||||
*/
|
||||
createConversation(deviceId: string, agentId: string = DEFAULT_AGENT_ID): ConversationRow {
|
||||
const stored = agentId === DEFAULT_AGENT_ID ? null : agentId;
|
||||
const now = this.now();
|
||||
const row: ConversationRow = {
|
||||
id: randomUUID(),
|
||||
@@ -147,20 +173,25 @@ export class TurnEngine {
|
||||
hermes_session_id: `hermeven-${randomUUID()}`,
|
||||
created_at: now,
|
||||
closed_at: null,
|
||||
agent_id: stored,
|
||||
};
|
||||
this.deps.db.transaction(() => {
|
||||
this.deps.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId);
|
||||
this.deps.db
|
||||
.prepare('INSERT INTO conversations (id, device_id, hermes_session_id, created_at) VALUES (@id, @device_id, @hermes_session_id, @created_at)')
|
||||
.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL AND agent_id IS ?')
|
||||
.run(now, deviceId, stored);
|
||||
this.deps.db
|
||||
.prepare(
|
||||
'INSERT INTO conversations (id, device_id, hermes_session_id, created_at, agent_id) VALUES (@id, @device_id, @hermes_session_id, @created_at, @agent_id)',
|
||||
)
|
||||
.run(row);
|
||||
})();
|
||||
this.deps.log.info({ device_id: deviceId, conversation_id: row.id }, 'conversation.created');
|
||||
this.deps.log.info({ device_id: deviceId, conversation_id: row.id, agent_id: agentId }, 'conversation.created');
|
||||
return row;
|
||||
}
|
||||
|
||||
activeConversation(deviceId: string): ConversationRow | undefined {
|
||||
return this.deps.db
|
||||
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL ORDER BY created_at DESC LIMIT 1')
|
||||
.prepare('SELECT * FROM conversations WHERE device_id = ? AND closed_at IS NULL AND agent_id IS NULL ORDER BY created_at DESC LIMIT 1')
|
||||
.get(deviceId) as ConversationRow | undefined;
|
||||
}
|
||||
|
||||
@@ -477,13 +508,22 @@ export class TurnEngine {
|
||||
}
|
||||
|
||||
row = this.row(requestId)!;
|
||||
const hermes = this.adapterForTurn(row);
|
||||
if (!hermes) {
|
||||
// The conversation's agent was removed from the configuration. If anything may already
|
||||
// have been sent (a recovered turn), the outcome cannot be known from here.
|
||||
this.deps.log.warn({ request_id: requestId }, 'turn.agent_not_configured');
|
||||
if (recovered && (row.hermes_run_id || row.pending_body)) this.finish(requestId, 'unknown', { code: 'outcome_unknown' });
|
||||
else this.finish(requestId, 'failed', { code: 'agent_unreachable' });
|
||||
return;
|
||||
}
|
||||
if (!row.hermes_run_id) {
|
||||
// A recovered turn may already have been sent by the previous process.
|
||||
const runId = await this.submitToHermes(requestId, active, recovered);
|
||||
const runId = await this.submitToHermes(requestId, active, recovered, hermes);
|
||||
if (runId === null) return;
|
||||
this.update(requestId, { hermes_run_id: runId, pending_body: null });
|
||||
}
|
||||
await this.poll(requestId, active);
|
||||
await this.poll(requestId, active, hermes);
|
||||
}
|
||||
|
||||
private async transcribe(requestId: string, pcm: Buffer, active: ActiveTurn, locale: string): Promise<string | null> {
|
||||
@@ -519,7 +559,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> {
|
||||
private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean, hermes: HermesAdapter): Promise<string | null> {
|
||||
const row = this.row(requestId)!;
|
||||
const deadline = row.agent_deadline_at ?? (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs;
|
||||
let ambiguous = maybeAlreadySent;
|
||||
@@ -528,7 +568,7 @@ export class TurnEngine {
|
||||
for (;;) {
|
||||
if (this.stopping) return null;
|
||||
try {
|
||||
const { runId } = await this.deps.hermes.submit({
|
||||
const { runId } = await hermes.submit({
|
||||
idempotencyKey: row.hermes_idempotency_key,
|
||||
body: row.pending_body!,
|
||||
});
|
||||
@@ -565,7 +605,7 @@ export class TurnEngine {
|
||||
}
|
||||
}
|
||||
|
||||
private async poll(requestId: string, active: ActiveTurn): Promise<void> {
|
||||
private async poll(requestId: string, active: ActiveTurn, hermes: HermesAdapter): Promise<void> {
|
||||
const start = this.row(requestId)!;
|
||||
const runId = start.hermes_run_id!;
|
||||
// Both clocks come from the database, so a bridge restart resumes them where they were:
|
||||
@@ -592,7 +632,7 @@ export class TurnEngine {
|
||||
}
|
||||
if (stopReason && !stopAccepted) {
|
||||
try {
|
||||
await this.deps.hermes.stop(runId);
|
||||
await hermes.stop(runId);
|
||||
stopAccepted = true;
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
@@ -601,7 +641,7 @@ export class TurnEngine {
|
||||
|
||||
let status: RunStatus | null = null;
|
||||
try {
|
||||
status = await this.deps.hermes.status(runId);
|
||||
status = await hermes.status(runId);
|
||||
} catch (err) {
|
||||
if (!(err instanceof HermesUnavailableError)) throw err;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user