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:
@@ -17,7 +17,7 @@ the implementer read from the server's log, and what Cody reproduced independent
|
||||
| Path | State |
|
||||
|---|---|
|
||||
| Client, bridge and contract | Implemented. |
|
||||
| Automated tests with fakes (233) | Passing. |
|
||||
| Automated tests with fakes (296) | Passing. |
|
||||
| Client in Even's official simulator | Passing (7 scenarios). Simulator only. |
|
||||
| Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. |
|
||||
| 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. |
|
||||
@@ -28,6 +28,7 @@ the implementer read from the server's log, and what Cody reproduced independent
|
||||
| Ring, paging, contextual menu, cancel, relaunch with the pairing kept, the system exit dialog on the device | **Not run.** |
|
||||
| Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. |
|
||||
| Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** |
|
||||
| More than one agent (swipe at Ready to choose) | Implemented in 0.2.0 and tested with fakes. On the server, one real question was answered by a second Hermes profile through its own address and key (`docs/evidence/droplet/2026-11-21.md`). **Not deployed, not installed on the device.** |
|
||||
| Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. |
|
||||
| Sustained load, backups, monitoring, upgrades on the server | **Not verified.** |
|
||||
| Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. |
|
||||
@@ -78,6 +79,7 @@ instructions, including building for the glasses, are in `docs/setup.md`.
|
||||
| Swipe down / up | Next / previous page of the answer. |
|
||||
| Tap on an answer | Ask a follow-up in the same conversation. |
|
||||
| Double tap | Cancel what is in progress, or go back. At "Ready" it opens the system exit dialog. |
|
||||
| Swipe at Ready | From 0.2.0, when the bridge offers more than one agent: choose who to talk to. The name is shown; on an answer a swipe still turns the page. |
|
||||
| Leave it alone | From 0.1.1: Pepper leaves the glasses by herself (20 s after an answer, 30 s at Ready, 10 s after an error), so the normal screen and notifications return. Call her back from the glasses' menu or with "Hey Even, open Pepper". |
|
||||
| Tap, then long press | The system menu, with "New conversation" and "Cancel request". |
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"package_id": "xylo.hermeven",
|
||||
"edition": "202601",
|
||||
"name": "Pepper",
|
||||
"version": "0.1.2",
|
||||
"version": "0.2.0",
|
||||
"min_sdk_version": "0.0.16",
|
||||
"entrypoint": "index.html",
|
||||
"permissions": [
|
||||
|
||||
@@ -5,7 +5,7 @@ import { BridgeApiError, BridgeClient, BridgeNetworkError } from '../net/bridgeC
|
||||
import { BODY_BOX, HUD, renderHud } from './hud.ts';
|
||||
import { paginate, type MeasureLines } from './paginate.ts';
|
||||
import { toPlainText } from './plaintext.ts';
|
||||
import { initialState, reduce, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
|
||||
import { currentAgent, initialState, reduce, type Agent, type AppEvent, type AppState, type Effect, type HudError } from './reducer.ts';
|
||||
|
||||
const STORAGE_KEY = 'hermeven.v1';
|
||||
|
||||
@@ -26,6 +26,43 @@ interface Stored {
|
||||
activeCancelled: boolean;
|
||||
/** When the last turn in `conversationId` finished (ms since epoch), if known. */
|
||||
lastTurnAt?: number;
|
||||
/**
|
||||
* The agent `conversationId` and `lastTurnAt` belong to: the one questions go to. Absent =
|
||||
* the default agent.
|
||||
*/
|
||||
agentId?: string;
|
||||
/** The same two values for every other agent that has been talked to, by agent id. */
|
||||
others?: Record<string, AgentThread>;
|
||||
/** The agent list as the bridge last gave it, used if the bridge cannot be asked at start. */
|
||||
agents?: Agent[];
|
||||
}
|
||||
|
||||
interface AgentThread {
|
||||
conversationId: string | null;
|
||||
lastTurnAt?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_AGENT = 'default';
|
||||
|
||||
function validAgents(value: unknown): Agent[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const agents = value.filter(
|
||||
(a): a is Agent => !!a && typeof (a as Agent).id === 'string' && typeof (a as Agent).name === 'string' && (a as Agent).name.length <= 24,
|
||||
);
|
||||
return agents.length === value.length && agents.length <= 16 ? agents.map(({ id, name }) => ({ id, name })) : undefined;
|
||||
}
|
||||
|
||||
function validThreads(value: unknown): Record<string, AgentThread> | undefined {
|
||||
if (!value || typeof value !== 'object') return undefined;
|
||||
const out: Record<string, AgentThread> = {};
|
||||
for (const [id, thread] of Object.entries(value as Record<string, Partial<AgentThread>>)) {
|
||||
if (!thread || typeof thread !== 'object') continue;
|
||||
out[id] = {
|
||||
conversationId: typeof thread.conversationId === 'string' ? thread.conversationId : null,
|
||||
lastTurnAt: typeof thread.lastTurnAt === 'number' ? thread.lastTurnAt : undefined,
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface DiagEntry {
|
||||
@@ -238,6 +275,8 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
}
|
||||
const agents = this.stored ? await this.loadAgents() : [];
|
||||
if (this.stored) this.settleStartingAgent(agents);
|
||||
// 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({
|
||||
@@ -247,10 +286,87 @@ export class Controller {
|
||||
captureMaxSeconds,
|
||||
resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null),
|
||||
storageFault: this.storageFault,
|
||||
agents,
|
||||
agentId: this.stored?.agentId ?? null,
|
||||
});
|
||||
if (abandoned) void this.cancelTurn(abandoned);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ agents
|
||||
|
||||
/**
|
||||
* The agents the bridge offers. A single agent, or a bridge from before agent selection
|
||||
* (`not_found`), gives an empty list: nothing about agents is then shown or sent. If the
|
||||
* bridge cannot be asked right now, the list it gave last time is used.
|
||||
*/
|
||||
private async loadAgents(): Promise<Agent[]> {
|
||||
if (!this.client || !this.stored) return [];
|
||||
let agents: Agent[];
|
||||
try {
|
||||
const listed = (await this.client.agents()).agents;
|
||||
agents = listed.length > 1 ? listed.map(({ id, name }) => ({ id, name })) : [];
|
||||
} catch (err) {
|
||||
if (err instanceof BridgeApiError && err.body.code === 'not_found') agents = [];
|
||||
else {
|
||||
this.note('agents', `agent list not available: ${describe(err)}`);
|
||||
return this.stored?.agents ?? [];
|
||||
}
|
||||
}
|
||||
if (this.stored && JSON.stringify(this.stored.agents ?? []) !== JSON.stringify(agents)) {
|
||||
this.stored = { ...this.stored, agents };
|
||||
void this.save();
|
||||
}
|
||||
return agents;
|
||||
}
|
||||
|
||||
/** Make `agentId` the stored current agent, swapping in its own conversation. No I/O. */
|
||||
private swapStoredAgent(agentId: string): void {
|
||||
if (!this.stored) return;
|
||||
const from = this.stored.agentId ?? DEFAULT_AGENT;
|
||||
if (from === agentId) return;
|
||||
const others = { ...(this.stored.others ?? {}) };
|
||||
others[from] = { conversationId: this.stored.conversationId, lastTurnAt: this.stored.lastTurnAt };
|
||||
let thread: AgentThread = others[agentId] ?? { conversationId: null };
|
||||
delete others[agentId];
|
||||
// The same rule as at start: after a long silence with that agent, the next question to it
|
||||
// starts a new conversation.
|
||||
if (thread.conversationId && thread.lastTurnAt !== undefined && this.now() - thread.lastTurnAt > this.conversationGapMs) {
|
||||
thread = { conversationId: null, lastTurnAt: thread.lastTurnAt };
|
||||
}
|
||||
this.stored = { ...this.stored, agentId, conversationId: thread.conversationId, lastTurnAt: thread.lastTurnAt, others };
|
||||
}
|
||||
|
||||
/**
|
||||
* Which agent the app opens on. It reopens on the agent last talked to only while that
|
||||
* conversation is still current (the same window that decides whether a conversation
|
||||
* continues); otherwise, or if that agent is no longer offered, it opens on the default.
|
||||
* A turn still in flight keeps its agent.
|
||||
*/
|
||||
private settleStartingAgent(agents: Agent[]): void {
|
||||
if (!this.stored) return;
|
||||
const current = this.stored.agentId ?? DEFAULT_AGENT;
|
||||
if (current === DEFAULT_AGENT) return;
|
||||
if (this.stored.activeRequestId) return;
|
||||
const offered = agents.some((a) => a.id === current);
|
||||
const recent = this.stored.lastTurnAt !== undefined && this.now() - this.stored.lastTurnAt <= this.conversationGapMs;
|
||||
if (offered && recent) return;
|
||||
this.note('agents', offered ? 'last agent was a while ago: opening on the default' : 'last agent is no longer offered: opening on the default');
|
||||
this.swapStoredAgent(DEFAULT_AGENT);
|
||||
void this.save();
|
||||
}
|
||||
|
||||
/** A swipe at Ready: move to the next or previous agent. Does nothing unless there is a choice. */
|
||||
private cycleAgent(delta: 1 | -1): void {
|
||||
const agents = this.state.agents;
|
||||
if (this.state.phase !== 'ready' || agents.length < 2 || !this.stored) return;
|
||||
const index = agents.findIndex((a) => a.id === currentAgent(this.state)?.id);
|
||||
const next = agents[(Math.max(0, index) + delta + agents.length) % agents.length]!;
|
||||
this.swapStoredAgent(next.id);
|
||||
void this.save();
|
||||
this.note('agents', `now talking to ${next.id}`);
|
||||
this.dispatch({ type: 'agent_selected', agentId: next.id, conversationId: this.stored.conversationId });
|
||||
}
|
||||
|
||||
/** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true;
|
||||
@@ -315,7 +431,8 @@ export class Controller {
|
||||
} catch (err) {
|
||||
this.note('bridge', `status check failed: ${describe(err)}`);
|
||||
}
|
||||
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null });
|
||||
const agents = await this.loadAgents();
|
||||
this.dispatch({ type: 'init', paired: true, conversationId: null, captureMaxSeconds, resumeRequestId: null, agents, agentId: null });
|
||||
}
|
||||
|
||||
/** Disconnect: revoke the credential on the bridge, then clear everything held locally. */
|
||||
@@ -602,7 +719,9 @@ export class Controller {
|
||||
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();
|
||||
// Named only when the bridge offered a choice; captured now, and the epoch check below
|
||||
// drops the result if the user has moved to another agent meanwhile.
|
||||
const created = await client.createConversation(this.state.agents.length ? (currentAgent(this.state)?.id ?? DEFAULT_AGENT) : undefined);
|
||||
// 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();
|
||||
@@ -843,8 +962,11 @@ export class Controller {
|
||||
this.heldPress = null;
|
||||
return this.dispatch({ type: 'back' });
|
||||
case 'swipe_down':
|
||||
// At Ready a swipe chooses the agent; on an answer it turns the page.
|
||||
if (this.state.phase === 'ready' && this.state.agents.length > 1) return this.cycleAgent(1);
|
||||
return this.dispatch({ type: 'next_page' });
|
||||
case 'swipe_up':
|
||||
if (this.state.phase === 'ready' && this.state.agents.length > 1) return this.cycleAgent(-1);
|
||||
return this.dispatch({ type: 'prev_page' });
|
||||
case 'menu':
|
||||
if (event.itemId === MENU_ITEM.NEW_CONVERSATION) return this.dispatch({ type: 'new_conversation' });
|
||||
@@ -972,6 +1094,9 @@ export class Controller {
|
||||
activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null,
|
||||
activeCancelled: parsed.activeCancelled === true,
|
||||
lastTurnAt: typeof parsed.lastTurnAt === 'number' ? parsed.lastTurnAt : undefined,
|
||||
agentId: typeof parsed.agentId === 'string' ? parsed.agentId : undefined,
|
||||
others: validThreads(parsed.others),
|
||||
agents: validAgents(parsed.agents),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AppState } from './reducer.ts';
|
||||
import { currentAgent, type AppState } from './reducer.ts';
|
||||
|
||||
/**
|
||||
* HUD geometry. Canvas size and line height are documented by Even
|
||||
@@ -43,6 +43,8 @@ function clock(seconds: number): string {
|
||||
|
||||
/** Pure: the complete HUD text for a state at a moment in time. */
|
||||
export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
// With more than one agent on offer, every screen of an exchange says who it is with.
|
||||
const agent = state.agents.length > 1 ? currentAgent(state) : undefined;
|
||||
switch (state.phase) {
|
||||
case 'unpaired':
|
||||
if (state.storageFault) {
|
||||
@@ -54,6 +56,12 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
return { body: 'Hermeven\n\nNot connected.\nOpen Hermeven on your phone to pair.', status: 'Double-tap: exit' };
|
||||
|
||||
case 'ready':
|
||||
if (agent) {
|
||||
return {
|
||||
body: state.notice ? `${agent.name}\n\n${state.notice}.` : `${agent.name}\n\nReady.`,
|
||||
status: 'Tap: ask · Swipe: agent · 2×: exit',
|
||||
};
|
||||
}
|
||||
return {
|
||||
body: state.notice ? `Hermeven\n\n${state.notice}.` : 'Hermeven\n\nReady.',
|
||||
status: 'Tap: ask · Double-tap: exit',
|
||||
@@ -63,7 +71,7 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
const elapsed = state.captureStartedAt === null ? 0 : (nowMs - state.captureStartedAt) / 1000;
|
||||
const cap = state.captureMaxSeconds;
|
||||
return {
|
||||
body: `Listening…\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
body: `${agent ? `${agent.name} is listening…` : 'Listening…'}\n\nRecording stops by itself after ${cap} seconds.`,
|
||||
status: `● REC ${clock(elapsed)} / ${clock(cap)} · Tap or release: send · 2×: cancel`,
|
||||
};
|
||||
}
|
||||
@@ -72,7 +80,7 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
return { body: 'Transcribing…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'thinking':
|
||||
return { body: 'Thinking…', status: 'Double-tap: cancel' };
|
||||
return { body: agent ? `${agent.name} is thinking…` : 'Thinking…', status: 'Double-tap: cancel' };
|
||||
|
||||
case 'approval':
|
||||
return {
|
||||
@@ -85,7 +93,7 @@ export function renderHud(state: AppState, nowMs: number): HudFrame {
|
||||
const page = state.pages[state.pageIndex] ?? '';
|
||||
const position = total > 1 ? `${state.pageIndex + 1}/${total} · Swipe: page · ` : '';
|
||||
const partial = state.partial ? 'PARTIAL · ' : '';
|
||||
return { body: page, status: `${partial}${position}Tap: ask` };
|
||||
return { body: page, status: `${partial}${position}${agent ? `${agent.name} · ` : ''}Tap: ask` };
|
||||
}
|
||||
|
||||
case 'cancelled':
|
||||
|
||||
@@ -29,8 +29,21 @@ export interface HudError {
|
||||
retryable: boolean;
|
||||
}
|
||||
|
||||
/** An agent the bridge lets this device talk to. */
|
||||
export interface Agent {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AppState {
|
||||
phase: Phase;
|
||||
/**
|
||||
* The agents the bridge offers, default first. Empty when there is only one (or the bridge
|
||||
* predates agent selection): nothing about agents is then shown or sent.
|
||||
*/
|
||||
agents: Agent[];
|
||||
/** The agent questions go to. Null = the default (the first in `agents`). */
|
||||
agentId: string | null;
|
||||
/**
|
||||
* Bumped whenever the user starts, cancels or abandons something. Every
|
||||
* asynchronous effect carries the generation it was issued under, and an
|
||||
@@ -64,6 +77,8 @@ export interface AppState {
|
||||
|
||||
export const initialState: AppState = {
|
||||
phase: 'unpaired',
|
||||
agents: [],
|
||||
agentId: null,
|
||||
generation: 0,
|
||||
conversationId: null,
|
||||
conversationEpoch: 0,
|
||||
@@ -82,7 +97,18 @@ export const initialState: AppState = {
|
||||
};
|
||||
|
||||
export type AppEvent =
|
||||
| { type: 'init'; paired: boolean; conversationId: string | null; captureMaxSeconds: number; resumeRequestId: string | null; storageFault?: boolean }
|
||||
| {
|
||||
type: 'init';
|
||||
paired: boolean;
|
||||
conversationId: string | null;
|
||||
captureMaxSeconds: number;
|
||||
resumeRequestId: string | null;
|
||||
storageFault?: boolean;
|
||||
agents?: Agent[];
|
||||
agentId?: string | null;
|
||||
}
|
||||
/** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */
|
||||
| { type: 'agent_selected'; agentId: string; conversationId: string | null }
|
||||
| { type: 'unpaired' }
|
||||
/** Semantic actions. `freshId` is a new UUID supplied by the caller in case a turn starts. */
|
||||
| { type: 'activate'; freshId: string }
|
||||
@@ -126,6 +152,12 @@ export interface Step {
|
||||
const IDLE: ReadonlySet<Phase> = new Set(['ready', 'answer', 'error', 'cancelled']);
|
||||
const IN_FLIGHT: ReadonlySet<Phase> = new Set(['transcribing', 'thinking', 'approval']);
|
||||
|
||||
/** The agent questions go to now, or undefined when the bridge offers no choice. */
|
||||
export function currentAgent(state: AppState): Agent | undefined {
|
||||
if (state.agents.length === 0) return undefined;
|
||||
return state.agents.find((a) => a.id === state.agentId) ?? state.agents[0];
|
||||
}
|
||||
|
||||
function clearTurn(state: AppState): AppState {
|
||||
return {
|
||||
...state,
|
||||
@@ -169,6 +201,8 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
storageFault: event.storageFault === true,
|
||||
agents: event.agents ?? [],
|
||||
agentId: event.agentId ?? null,
|
||||
};
|
||||
if (!event.paired) return same({ ...base, phase: 'unpaired' });
|
||||
if (event.resumeRequestId) {
|
||||
@@ -182,6 +216,24 @@ export function reduce(state: AppState, event: AppEvent): Step {
|
||||
return same({ ...base, phase: 'ready' });
|
||||
}
|
||||
|
||||
case 'agent_selected': {
|
||||
// Only from Ready: never while something is recording, in flight or on screen. Each agent
|
||||
// has its own conversation, so the conversation is swapped with it, under a new epoch so a
|
||||
// conversation still being created for the previous agent cannot land on this one.
|
||||
if (state.phase !== 'ready') return same(state);
|
||||
if (!state.agents.some((a) => a.id === event.agentId)) return same(state);
|
||||
if (event.agentId === currentAgent(state)?.id) return same(state);
|
||||
return same({
|
||||
...clearTurn(state),
|
||||
phase: 'ready',
|
||||
generation: state.generation + 1,
|
||||
agentId: event.agentId,
|
||||
conversationId: event.conversationId,
|
||||
conversationEpoch: state.conversationEpoch + 1,
|
||||
creatingConversation: false,
|
||||
});
|
||||
}
|
||||
|
||||
case 'unpaired': {
|
||||
const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : [];
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
check,
|
||||
AgentsResponse,
|
||||
ConversationResponse,
|
||||
DeviceCredential,
|
||||
DeviceStatusResponse,
|
||||
@@ -135,8 +136,16 @@ export class BridgeClient {
|
||||
return this.call(RevokeResponse, 'DELETE', '/v1/device');
|
||||
}
|
||||
|
||||
createConversation(): Promise<ConversationResponse> {
|
||||
return this.call(ConversationResponse, 'POST', '/v1/conversations', { json: { schema_version: SCHEMA_VERSION } });
|
||||
/** The agents this device may talk to. A bridge from before agent selection answers `not_found`. */
|
||||
agents(): Promise<AgentsResponse> {
|
||||
return this.call(AgentsResponse, 'GET', '/v1/agents');
|
||||
}
|
||||
|
||||
/** `agentId` is sent only when given, so a bridge from before agent selection still accepts the request. */
|
||||
createConversation(agentId?: string): Promise<ConversationResponse> {
|
||||
return this.call(ConversationResponse, 'POST', '/v1/conversations', {
|
||||
json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId },
|
||||
});
|
||||
}
|
||||
|
||||
submitText(args: { requestId: string; conversationId: string; locale: string; text: string }): Promise<TurnResult> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SCHEMA_VERSION, type TurnResult } from '@hermeven/contracts';
|
||||
import { pollDelay } from '../src/core/controller.ts';
|
||||
import { renderHud } from '../src/core/hud.ts';
|
||||
import { initialState, reduce, type AppEvent, type AppState, type Effect } from '../src/core/reducer.ts';
|
||||
|
||||
const ID1 = '11111111-1111-4111-8111-111111111111';
|
||||
@@ -369,3 +370,62 @@ describe('pairing, restore and conversations', () => {
|
||||
expect(step.effects).toEqual([{ type: 'discard_capture' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('choosing an agent', () => {
|
||||
const AGENTS = [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
];
|
||||
const WENDY_CONV = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
|
||||
const readyWithAgents = () =>
|
||||
run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents: AGENTS, agentId: null }).state;
|
||||
const select: AppEvent = { type: 'agent_selected', agentId: 'wendy', conversationId: WENDY_CONV };
|
||||
|
||||
it('at Ready: the agent and its own conversation are swapped in under a new conversation epoch', () => {
|
||||
const before = readyWithAgents();
|
||||
const { state, effects } = run(before, select);
|
||||
expect(effects).toEqual([]);
|
||||
expect(state.phase).toBe('ready');
|
||||
expect(state.agentId).toBe('wendy');
|
||||
expect(state.conversationId).toBe(WENDY_CONV);
|
||||
expect(state.conversationEpoch).toBe(before.conversationEpoch + 1);
|
||||
expect(state.generation).toBe(before.generation + 1);
|
||||
expect(renderHud(state, 0).body).toBe('Wendy\n\nReady.');
|
||||
});
|
||||
|
||||
it('is ignored on every other screen: listening, in flight, an answer, an error, cancelled, unpaired', () => {
|
||||
const base = readyWithAgents();
|
||||
const others: AppState[] = [
|
||||
run(base, { type: 'activate', freshId: ID1 }).state,
|
||||
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }).state,
|
||||
run(base, { type: 'submit_text', freshId: ID1, text: 'q' }, { type: 'turn_update', generation: base.generation + 1, result: result(ID1), pages: ['a'] }).state,
|
||||
run(base, { type: 'activate', freshId: ID1 }, { type: 'capture_failed', generation: base.generation + 1, reason: 'mic_refused' }).state,
|
||||
run(base, { type: 'activate', freshId: ID1 }, { type: 'cancel' }).state,
|
||||
{ ...initialState, agents: AGENTS },
|
||||
];
|
||||
expect(others.map((s) => s.phase)).toEqual(['listening', 'thinking', 'answer', 'error', 'cancelled', 'unpaired']);
|
||||
for (const state of others) expect(reduce(state, select).state, state.phase).toBe(state);
|
||||
});
|
||||
|
||||
it('an agent that is not offered, or the one already current, changes nothing', () => {
|
||||
const base = readyWithAgents();
|
||||
expect(reduce(base, { type: 'agent_selected', agentId: 'natalie', conversationId: null }).state).toBe(base);
|
||||
expect(reduce(base, { type: 'agent_selected', agentId: 'default', conversationId: null }).state).toBe(base);
|
||||
});
|
||||
|
||||
it('a conversation created for the previous agent cannot land on the new one', () => {
|
||||
const base = readyWithAgents();
|
||||
const creating = run(base, { type: 'new_conversation' }).state;
|
||||
const moved = run(creating, { type: 'agent_selected', agentId: 'wendy', conversationId: null }).state;
|
||||
const late = reduce(moved, { type: 'conversation_created', epoch: creating.conversationEpoch, conversationId: CONV }).state;
|
||||
expect(late.conversationId).toBeNull();
|
||||
expect(late.creatingConversation).toBe(false);
|
||||
});
|
||||
|
||||
it('with one agent, or none listed, no screen mentions an agent', () => {
|
||||
for (const agents of [[], [AGENTS[0]!]]) {
|
||||
const state = run(initialState, { type: 'init', paired: true, conversationId: CONV, captureMaxSeconds: 30, resumeRequestId: null, agents }).state;
|
||||
expect(renderHud(state, 0)).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,14 @@ HERMES_BASE_URL=http://127.0.0.1:8642
|
||||
HERMES_API_KEY=replace-with-the-hermes-api-server-key
|
||||
HERMES_PROFILE_LABEL=default
|
||||
|
||||
# Optional: more agents on the glasses (swipe at Ready to choose). Each is another profile of the
|
||||
# same Hermes gateway and needs its OWN key: add API_SERVER_KEY to that profile's .env on the
|
||||
# Hermes side, then repeat it here. See docs/bridge-api.md, "More than one agent".
|
||||
# HERMEVEN_AGENT_NAME=Pepper
|
||||
# HERMEVEN_AGENTS=wendy,cody
|
||||
# HERMEVEN_AGENT_WENDY_API_KEY=replace-with-wendy-profile-api-server-key
|
||||
# HERMEVEN_AGENT_CODY_API_KEY=replace-with-cody-profile-api-server-key
|
||||
|
||||
HERMEVEN_HOST=127.0.0.1
|
||||
HERMEVEN_PORT=8787
|
||||
# Caddy is in front, so the client address comes from its forwarded header.
|
||||
|
||||
+22
-1
@@ -18,7 +18,8 @@ Every error has the shape:
|
||||
| `GET /v1/device` | Pairing status, limits, whether the agent is reachable and STT is configured. | 200 |
|
||||
| `POST /v1/device/renew` | Rotate the device token. The old token stops working at once. | 200 |
|
||||
| `DELETE /v1/device` | Revoke this device and close its conversation. | 200 |
|
||||
| `POST /v1/conversations` | Start a new conversation; closes the device's previous one. | 201 |
|
||||
| `GET /v1/agents` | The agents this device may talk to, default first: `{agents: [{id, name}]}`. Ids and display names only; no address, profile or key. Added after 0.1.x: an older bridge answers 404 `not_found`, which a client must treat as "one agent". | 200 |
|
||||
| `POST /v1/conversations` | Start a new conversation. Optional `agent_id` (an id from `/v1/agents`; omitted = the default agent; anything else is 400 `invalid_request`). Closes the device's previous conversation **with that agent** only. | 201 |
|
||||
| `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate |
|
||||
| `GET /v1/turns/{request_id}` | Current state and result. | 200 |
|
||||
| `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 |
|
||||
@@ -26,6 +27,26 @@ Every error has the shape:
|
||||
There is no SSE endpoint. Streaming through the Even WebView is undocumented and untested, so
|
||||
polling is the supported path.
|
||||
|
||||
## More than one agent
|
||||
|
||||
The bridge can be given further agents besides the default one. Each is another profile served by
|
||||
the same Hermes gateway (`gateway.multiplex_profiles`), reached at `<HERMES_BASE_URL>/p/<profile>`
|
||||
with that profile's own `API_SERVER_KEY`; Hermes refuses the default profile's key there.
|
||||
|
||||
```
|
||||
HERMEVEN_AGENT_NAME=Pepper # display name of the default agent (default: Agent)
|
||||
HERMEVEN_AGENTS=wendy,cody # extra agent ids, in display order
|
||||
HERMEVEN_AGENT_WENDY_API_KEY=... # required for each extra agent
|
||||
HERMEVEN_AGENT_WENDY_PROFILE=wendy # optional; default: the id
|
||||
HERMEVEN_AGENT_WENDY_NAME=Wendy # optional; default: the id, capitalised
|
||||
```
|
||||
|
||||
The list is the owner's allow-list. A client names an agent only by id, only when creating a
|
||||
conversation, and the id is checked against the list; it is never used to build an address. A
|
||||
turn goes to the agent of its conversation. Each agent has its own conversation and its own
|
||||
Hermes session, so nothing said to one is sent to another. `/v1/device` is unchanged, and its
|
||||
`active_conversation_id` and `agent_reachable` describe the default agent.
|
||||
|
||||
## Creating a turn
|
||||
|
||||
Typed text (`Content-Type: application/json`):
|
||||
|
||||
@@ -112,6 +112,23 @@ F4 as revised (build 0.1.2): the countdown runs however the app was opened. It s
|
||||
leaves while recording, transcribing, waiting for the agent or for an approval, or while
|
||||
unpaired, and a touch on the phone page still holds it open for two minutes.
|
||||
|
||||
### G. Choosing an agent (from Dan's words on 2026-11-21)
|
||||
|
||||
A build for trial. Per Dan's standing instruction, his keep/change/remove decisions follow the
|
||||
device trial; nothing here is pre-accepted beyond what he is quoted as asking for.
|
||||
|
||||
| # | Dan said | Criterion |
|
||||
|---|---|---|
|
||||
| G1 | "what I want to build next is the ability to chat with all my agents... wendy is a sub-agent of pepper and being able to summon her through the app would be ideal." | The app can talk to more than one agent through the one bridge. |
|
||||
| G2 | "when pepper opens, and is inthe ready state, what if swiping could change the active agent? So pepper would show, but if we swipe, it would move between different available agents?" | At Ready a swipe moves to the next or previous agent; the app opens on the default agent and shows the current agent's name. |
|
||||
| G3 | "when no name is stated, then it uses pepper/default." | With no choice made, questions go to the default agent exactly as before. |
|
||||
| G4 | Asked whether to reopen on Pepper or on the last agent: "could we use the same 15 minute time out (I think that's what it is) that determines if it's a new session, or picks up from the last?" | Reopened within the conversation window (ten minutes; Dan was told it is ten, not fifteen), the app opens on the agent last talked to, in the same conversation; otherwise on the default. |
|
||||
| G5 | On the agent list coming from the bridge's settings: "Yeah, sure. that's fine." | The list is configured on the bridge; the phone can only pick from it. |
|
||||
| G6 | "Pepper, wendy and cody. yes. go for it." | The three agents for the first trial. Also Dan's go-ahead for giving the wendy and cody profiles an API key on the server. |
|
||||
| G7 | (implementer's choices, not requested) | Each agent has its own conversation. A follow-up goes to the agent that answered. On an answer a swipe still turns the page. The agent's name is shown while listening, thinking and on the answer. With only one agent the screens are unchanged. |
|
||||
|
||||
Not built: saying a name to route a question. Dan first preferred it, then proposed the swipe.
|
||||
|
||||
## Out of scope for this contract
|
||||
|
||||
Wake word ("Hey Pepper"), automatic end-of-speech detection, summoning other agents by name,
|
||||
|
||||
@@ -257,3 +257,38 @@ message by a few minutes, on the owner's instruction. `evenhub ls` at 23:21 UTC:
|
||||
0.1.1; 0.1.0 retained, on no channel. The server was not changed.
|
||||
|
||||
Build 0.1.2 has **not** been uploaded.
|
||||
|
||||
## 23:48 UTC: build 0.1.2 uploaded
|
||||
|
||||
Cody, Round 14: SHIP (trial designation SHIP FOR TRIAL) on
|
||||
`15714bd848a7bf7230bb80d187de85af4b3fa66b`. Dan: "yes, upload 0.1.2". `evenhub upload` (id 155527,
|
||||
99,892 bytes, SHA-256 `3781f3e8256f0efdba4155fbd5d0926a6726f14ca3ed89bc039d34b48a0f608b`, built from
|
||||
that commit) and `evenhub promote 0.1.2 --to beta`. Dan has not reported a trial of 0.1.2.
|
||||
|
||||
## 23:52 to 23:58 UTC: Hermes profiles surveyed; keys added for wendy and cody
|
||||
|
||||
Read-only survey (Dan: "Yes, take a read-only survey"):
|
||||
|
||||
| Found | Detail |
|
||||
|---|---|
|
||||
| Profiles | default, cody, jeanette, natalie, wendy, all with a running gateway |
|
||||
| Gateways | `hermes-gateway.service` serves default, cody, natalie and wendy (`gateway.multiplex_profiles: true`); `hermes-gateway-jeanette.service` is separate and not on port 8642 |
|
||||
| API | Hermes v0.23.1 source: named profiles are served at `/p/<profile>/...` on the same port, each authorised by that profile's own `API_SERVER_KEY`, failing closed without one |
|
||||
| Unauthenticated probes | `/p/wendy/health`, `/p/cody/health`, `/p/natalie/health`: 200. `/p/jeanette/health`, `/p/nosuch/health`: 404 |
|
||||
| Keys before | Only the default profile had `API_SERVER_KEY` |
|
||||
|
||||
Changes (Dan: "Pepper, wendy and cody. yes. go for it."):
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| `API_SERVER_KEY` (64 hex, generated on the server, never displayed) appended to `profiles/wendy/.env`; previous file kept as `.env.bak-hermeven-<time>` | File stays `hermes` 600. No gateway restart. |
|
||||
| Same for `profiles/cody/.env` | Same. |
|
||||
| Wendy's key at `/p/wendy/v1/runs/<unknown>` | 404: accepted, no such run. Effective without a restart. |
|
||||
| Wendy's key at the default address; the default key at `/p/wendy`; Cody's key at `/p/wendy` | 401 each |
|
||||
| One test question to Wendy through `POST /p/wendy/v1/runs` with an idempotency key ("connection test... Do not use any tools.") | 202; an identical resubmit returned the same run; completed in 4 s with a one-sentence answer identifying herself as Wendy. This created one session in Wendy's profile. |
|
||||
| That run looked up at the default address with the default key | 404 |
|
||||
| Cody's key at `/p/cody/v1/runs/<unknown>` | 404: accepted. No question was sent to Cody. |
|
||||
|
||||
`platforms.api_server.enabled` is `false` in wendy's and natalie's profile settings; the request
|
||||
above worked regardless. The bridge on the server was **not** changed: it still runs `d90cd89`
|
||||
with one agent, and the new keys are not yet in its settings.
|
||||
|
||||
@@ -641,7 +641,13 @@ No check was omitted.
|
||||
| Never paired: nothing leaves in 30 minutes, even with a gesture and a `glassesMenu` source | both files |
|
||||
| Simulator: opened by URL with no gesture, leaves from Ready after the shortened wait; exit confirmed; display empty | eighth simulator scenario |
|
||||
|
||||
Negative control: with the old rule restored (leave only after a `glassesMenu` launch source),
|
||||
Correction (CODY-020, Round 14): the mutation described next is **stricter** than the previous
|
||||
implementation, which also armed after any gesture. It is
|
||||
`|| this.launchSource !== 'glassesMenu'` added to the guard in `scheduleIdleExit()`. Cody restored
|
||||
the exact previous controller from `3e04688` and reported 7 failed, 62 passed of 69; the
|
||||
implementer did not re-run that.
|
||||
|
||||
Negative control (stricter mutation): leave only after a `glassesMenu` launch source,
|
||||
11 of the 69 tests in the two files fail, including all five new cases above except "never
|
||||
paired". The CODY-019 control was not re-run; `activityEpoch` and its tests are unchanged and
|
||||
pass.
|
||||
|
||||
@@ -127,8 +127,28 @@ export const RevokeResponse = Type.Object(
|
||||
export type RevokeResponse = Static<typeof RevokeResponse>;
|
||||
|
||||
// ---------------------------------------------------------- conversations
|
||||
/** Lower-case id of an agent the bridge is configured to reach. `default` is the main one. */
|
||||
const AgentId = Type.String({ pattern: '^[a-z][a-z0-9_-]{0,31}$' });
|
||||
|
||||
export const AgentsResponse = Type.Object(
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** In the order the owner configured them; the first is the default. Never empty. */
|
||||
agents: Type.Array(
|
||||
Type.Object({ id: AgentId, name: Type.String({ minLength: 1, maxLength: 24 }) }, { additionalProperties: false }),
|
||||
{ minItems: 1, maxItems: 16 },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type AgentsResponse = Static<typeof AgentsResponse>;
|
||||
|
||||
export const ConversationCreateRequest = Type.Object(
|
||||
{ schema_version: SchemaVersion },
|
||||
{
|
||||
schema_version: SchemaVersion,
|
||||
/** Which configured agent this conversation is with. Omitted = the default agent. */
|
||||
agent_id: Type.Optional(AgentId),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
export type ConversationCreateRequest = Static<typeof ConversationCreateRequest>;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ export interface FakeRun {
|
||||
body: string;
|
||||
sessionId: string;
|
||||
input: string;
|
||||
/** The profile the run was submitted under (null = default). Invisible from any other. */
|
||||
profile: string | null;
|
||||
status: string;
|
||||
output: string;
|
||||
extra: Record<string, unknown>;
|
||||
@@ -40,7 +42,12 @@ export class FakeHermes {
|
||||
private readonly byKey = new Map<string, FakeRun>();
|
||||
/** session id -> inputs seen, to prove follow-ups land in the same session. */
|
||||
readonly sessions = new Map<string, string[]>();
|
||||
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string }> = [];
|
||||
readonly requests: Array<{ method: string; path: string; idempotencyKey?: string; profile?: string | null }> = [];
|
||||
/** Named profiles served under `/p/<name>`, each with its own key. */
|
||||
readonly profiles = new Map<string, string>();
|
||||
/** Which profile each executed run belonged to (null = default), in order. */
|
||||
readonly executedBy: Array<string | null> = [];
|
||||
|
||||
private script: Script[] = [];
|
||||
private defaultScript: Script = { kind: 'complete' };
|
||||
/** Faults applied to upcoming POST /v1/runs calls, in order. */
|
||||
@@ -108,12 +115,24 @@ export class FakeHermes {
|
||||
|
||||
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const url = new URL(req.url ?? '/', 'http://x');
|
||||
const path = url.pathname;
|
||||
let path = url.pathname;
|
||||
// Like a gateway with multiplex_profiles: `/p/<profile>/...` selects a named profile, which
|
||||
// has its OWN key; the default's key is refused there, and an unserved profile is a 404.
|
||||
let profile: string | null = null;
|
||||
let expectedKey = this.apiKey;
|
||||
const prefixed = /^\/p\/([^/]+)(\/.*)$/.exec(path);
|
||||
if (prefixed) {
|
||||
profile = prefixed[1]!;
|
||||
path = prefixed[2]!;
|
||||
const profileKey = this.profiles.get(profile);
|
||||
if (profileKey === undefined) return this.json(res, 404, { error: { message: 'Unknown profile' } });
|
||||
expectedKey = profileKey;
|
||||
}
|
||||
const key = req.headers['idempotency-key'];
|
||||
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined });
|
||||
this.requests.push({ method: req.method ?? '', path, idempotencyKey: typeof key === 'string' ? key : undefined, profile });
|
||||
|
||||
if (path === '/health') return this.json(res, 200, { status: 'ok' });
|
||||
if (req.headers.authorization !== `Bearer ${this.apiKey}`) {
|
||||
if (req.headers.authorization !== `Bearer ${expectedKey}`) {
|
||||
return this.json(res, 401, { error: { message: 'Invalid API key', code: 'invalid_api_key' } });
|
||||
}
|
||||
|
||||
@@ -121,11 +140,12 @@ export class FakeHermes {
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
|
||||
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw);
|
||||
if (req.method === 'POST' && path === '/v1/runs') return this.submit(req, res, raw, profile);
|
||||
|
||||
const match = /^\/v1\/runs\/([^/]+)(\/stop)?$/.exec(path);
|
||||
if (match) {
|
||||
const run = this.runs.get(decodeURIComponent(match[1]!));
|
||||
const found = this.runs.get(decodeURIComponent(match[1]!));
|
||||
const run = found && found.profile === profile ? found : undefined;
|
||||
if (req.method === 'GET' && !match[2]) {
|
||||
if (this.statusDown) return this.json(res, 503, { error: { message: 'storage_unavailable' } });
|
||||
if (!run) return this.json(res, 404, { error: { message: 'Run not found', code: 'run_not_found' } });
|
||||
@@ -158,8 +178,10 @@ export class FakeHermes {
|
||||
this.json(res, 404, { error: { message: 'not found' } });
|
||||
}
|
||||
|
||||
private submit(req: IncomingMessage, res: ServerResponse, raw: string): void {
|
||||
private submit(req: IncomingMessage, res: ServerResponse, raw: string, runProfile: string | null): void {
|
||||
// Keys are scoped to the profile, as in Hermes: the same key under another profile is a different run.
|
||||
const key = String(req.headers['idempotency-key'] ?? '');
|
||||
const scopedKey = key && `${runProfile ?? ''}|${key}`;
|
||||
const fault = this.submitFaults.shift();
|
||||
if (fault === 'http_503') return this.json(res, 503, { error: { message: 'runtime_draining' } }, { 'Retry-After': '1' });
|
||||
if (fault === 'http_400') return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
@@ -172,7 +194,7 @@ export class FakeHermes {
|
||||
}
|
||||
if (!body.input) return this.json(res, 400, { error: { message: "Missing 'input' field" } });
|
||||
|
||||
const existing = key ? this.byKey.get(key) : undefined;
|
||||
const existing = scopedKey ? this.byKey.get(scopedKey) : undefined;
|
||||
let run: FakeRun;
|
||||
let replayed = false;
|
||||
if (existing) {
|
||||
@@ -191,6 +213,7 @@ export class FakeHermes {
|
||||
body: raw,
|
||||
sessionId,
|
||||
input: body.input,
|
||||
profile: runProfile,
|
||||
status: 'running',
|
||||
output: '',
|
||||
extra: {},
|
||||
@@ -198,9 +221,10 @@ export class FakeHermes {
|
||||
timer: null,
|
||||
};
|
||||
this.runs.set(run.runId, run);
|
||||
if (key) this.byKey.set(key, run);
|
||||
if (scopedKey) this.byKey.set(scopedKey, run);
|
||||
// The turn "executes" exactly once, at admission.
|
||||
this.executions += 1;
|
||||
this.executedBy.push(runProfile);
|
||||
const history = this.sessions.get(sessionId) ?? [];
|
||||
this.sessions.set(sessionId, history);
|
||||
const script = this.script.shift() ?? this.defaultScript;
|
||||
|
||||
@@ -0,0 +1,561 @@
|
||||
import { measureTextWrap } from '@evenrealities/pretext';
|
||||
import { SCHEMA_VERSION } from '@hermeven/contracts';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts';
|
||||
import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts';
|
||||
import { ConfigError, loadConfig } from '../../services/bridge/src/config.ts';
|
||||
import { FakeDevice } from '../fakes/fakeDevice.ts';
|
||||
import { createHarness, type Harness } from './harness.ts';
|
||||
|
||||
/**
|
||||
* More than one agent behind one bridge. The bridge is real; Hermes is the TEST FAKE, which
|
||||
* imitates a gateway with multiplexed profiles: `/p/<profile>/...`, each profile with its own
|
||||
* key, runs invisible from any other profile. No real Hermes, no glasses.
|
||||
*/
|
||||
const WENDY_KEY = 'wendy-profile-key-0123456789';
|
||||
const CODY_KEY = 'cody-profile-key-0123456789';
|
||||
const AGENT_ENV = {
|
||||
HERMEVEN_AGENT_NAME: 'Pepper',
|
||||
HERMEVEN_AGENTS: 'wendy,cody',
|
||||
HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY,
|
||||
HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY,
|
||||
HERMEVEN_AGENT_CODY_NAME: 'Cody R.',
|
||||
};
|
||||
|
||||
let h: Harness;
|
||||
|
||||
async function agentsHarness(env: Record<string, string> = AGENT_ENV): Promise<void> {
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2', ...env } });
|
||||
h.hermes.profiles.set('wendy', WENDY_KEY);
|
||||
h.hermes.profiles.set('cody', CODY_KEY);
|
||||
}
|
||||
const newConversation = (token: string, agentId?: string) =>
|
||||
h.api('POST', '/v1/conversations', { token, json: agentId === undefined ? { schema_version: SCHEMA_VERSION } : { schema_version: SCHEMA_VERSION, agent_id: agentId } });
|
||||
const runsPosted = () => h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs');
|
||||
|
||||
afterEach(async () => {
|
||||
await h?.close();
|
||||
});
|
||||
|
||||
describe('bridge: the agent list', () => {
|
||||
it('lists the configured agents, default first, by id and name only', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/agents', { token });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
schema_version: SCHEMA_VERSION,
|
||||
agents: [
|
||||
{ id: 'default', name: 'Pepper' },
|
||||
{ id: 'wendy', name: 'Wendy' },
|
||||
{ id: 'cody', name: 'Cody R.' },
|
||||
],
|
||||
});
|
||||
const raw = JSON.stringify(res.body);
|
||||
for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey, '/p/', h.hermes.url]) expect(raw).not.toContain(secret);
|
||||
});
|
||||
|
||||
it('needs a device credential', async () => {
|
||||
await agentsHarness();
|
||||
expect((await h.api('GET', '/v1/agents')).status).toBe(401);
|
||||
expect((await h.api('GET', '/v1/agents', { token: 'x'.repeat(40) })).status).toBe(401);
|
||||
});
|
||||
|
||||
it('with no extra agents configured there is exactly one, and nothing else changes', async () => {
|
||||
h = await createHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/agents', { token });
|
||||
expect(res.body.agents).toEqual([{ id: 'default', name: 'Agent' }]);
|
||||
const conversation = await h.conversation(token);
|
||||
const turn = await h.textTurn(token, conversation, 'hello');
|
||||
await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(h.hermes.executedBy).toEqual([null]);
|
||||
});
|
||||
|
||||
it('/v1/device is unchanged, so a client built before agents (which rejects unknown fields) keeps working', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const res = await h.api('GET', '/v1/device', { token });
|
||||
expect(Object.keys(res.body).sort()).toEqual(
|
||||
['active_conversation_id', 'agent_reachable', 'audio_format', 'device_id', 'device_name', 'limits', 'pairing_expires_at', 'schema_version', 'stt_configured', 'token_expires_at'].sort(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge: a turn goes to the agent its conversation belongs to', () => {
|
||||
beforeEach(() => agentsHarness());
|
||||
|
||||
it('a conversation with Wendy is submitted and polled at her address with her key, and answered', async () => {
|
||||
const { token } = await h.pair();
|
||||
const created = await newConversation(token, 'wendy');
|
||||
expect(created.status).toBe(201);
|
||||
const turn = await h.textTurn(token, created.body.conversation_id, 'hello wendy');
|
||||
const done = await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toContain('hello wendy');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
// Every request about that run went through her prefix (the fake hides it from any other).
|
||||
const about = h.hermes.requests.filter((r) => r.path.startsWith('/v1/runs'));
|
||||
expect(about.length).toBeGreaterThan(1);
|
||||
expect(about.every((r) => r.profile === 'wendy')).toBe(true);
|
||||
});
|
||||
|
||||
it('no agent named, or "default", goes to the default agent', async () => {
|
||||
const { token } = await h.pair();
|
||||
const a = await h.conversation(token);
|
||||
const t1 = await h.textTurn(token, a, 'one');
|
||||
await h.waitTerminal(token, t1.body.request_id);
|
||||
const b = await newConversation(token, 'default');
|
||||
const t2 = await h.textTurn(token, b.body.conversation_id, 'two');
|
||||
await h.waitTerminal(token, t2.body.request_id);
|
||||
expect(h.hermes.executedBy).toEqual([null, null]);
|
||||
});
|
||||
|
||||
it('an agent that is not on the list is refused, and nothing reaches Hermes', async () => {
|
||||
const { token } = await h.pair();
|
||||
for (const bad of ['natalie', 'jeanette', 'nosuch']) {
|
||||
const res = await newConversation(token, bad);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
}
|
||||
for (const malformed of ['../wendy', 'wendy/v1', 'Wendy', '', 'p/wendy', 'a'.repeat(40)]) {
|
||||
expect((await newConversation(token, malformed)).status).toBe(400);
|
||||
}
|
||||
expect(h.hermes.requests.filter((r) => r.path !== '/health')).toEqual([]);
|
||||
expect(h.bridge.db.prepare('SELECT COUNT(*) AS n FROM conversations').get()).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('each agent has its own conversation: starting one with Wendy does not close Pepper\'s', async () => {
|
||||
const { token } = await h.pair();
|
||||
const pepper = await h.conversation(token);
|
||||
const wendy1 = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const t1 = await h.textTurn(token, pepper, 'still open?');
|
||||
expect(t1.status).toBeLessThan(300);
|
||||
await h.waitTerminal(token, t1.body.request_id);
|
||||
// A NEW conversation with Wendy closes only her earlier one.
|
||||
const wendy2 = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const closed = await h.textTurn(token, wendy1, 'old thread');
|
||||
expect(closed.body.error.code).toBe('conversation_closed');
|
||||
const t2 = await h.textTurn(token, wendy2, 'new thread');
|
||||
await h.waitTerminal(token, t2.body.request_id);
|
||||
const t3 = await h.textTurn(token, pepper, 'and pepper again');
|
||||
const done = await h.waitTerminal(token, t3.body.request_id);
|
||||
expect(done.answer_text).toContain('turn=2'); // Pepper's conversation kept its history
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy', null]);
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
});
|
||||
|
||||
it('a lost reply from Hermes is retried at the same agent under the same key: one execution', async () => {
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
h.hermes.failNextSubmit('drop_response');
|
||||
const turn = await h.textTurn(token, wendy, 'do it once');
|
||||
const done = await h.waitTerminal(token, turn.body.request_id);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(h.hermes.executions).toBe(1);
|
||||
const posts = runsPosted();
|
||||
expect(posts.length).toBe(2);
|
||||
expect(new Set(posts.map((p) => p.idempotencyKey)).size).toBe(1);
|
||||
expect(posts.every((p) => p.profile === 'wendy')).toBe(true);
|
||||
});
|
||||
|
||||
it('a bridge restart mid-run re-attaches to the same run at the same agent: one execution', async () => {
|
||||
const { token } = await h.pair();
|
||||
const cody = (await newConversation(token, 'cody')).body.conversation_id as string;
|
||||
h.hermes.next({ kind: 'complete', afterMs: 400, output: 'reviewed' });
|
||||
const turn = await h.textTurn(token, cody, 'review this');
|
||||
await h.waitState(token, turn.body.request_id, 'thinking');
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(token, turn.body.request_id, 5000);
|
||||
expect(done.outcome).toBe('succeeded');
|
||||
expect(done.answer_text).toBe('reviewed');
|
||||
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||
expect(runsPosted().length).toBe(1);
|
||||
});
|
||||
|
||||
it('keys never appear in the bridge log', async () => {
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const turn = await h.textTurn(token, wendy, 'hello');
|
||||
await h.waitTerminal(token, turn.body.request_id);
|
||||
const log = h.logs.join('');
|
||||
expect(log).toContain('conversation.created');
|
||||
for (const secret of [WENDY_KEY, CODY_KEY, h.hermes.apiKey]) expect(log).not.toContain(secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge: when an agent cannot be used', () => {
|
||||
it('a wrong key for one agent fails that turn as "nothing ran" and leaves the others working', async () => {
|
||||
await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'not-her-key-0123456789' });
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const t1 = await h.textTurn(token, wendy, 'hello');
|
||||
const failed = await h.waitTerminal(token, t1.body.request_id);
|
||||
expect(failed.outcome).toBe('failed');
|
||||
expect(failed.error?.code).toBe('agent_rejected');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
const pepper = await h.conversation(token);
|
||||
const t2 = await h.textTurn(token, pepper, 'hello');
|
||||
expect((await h.waitTerminal(token, t2.body.request_id)).outcome).toBe('succeeded');
|
||||
});
|
||||
|
||||
it("the default agent's key is refused at another agent's address (the reason each needs its own)", async () => {
|
||||
await agentsHarness({ ...AGENT_ENV, HERMEVEN_AGENT_WENDY_API_KEY: 'fake-hermes-key' });
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
const turn = await h.textTurn(token, wendy, 'hello');
|
||||
expect((await h.waitTerminal(token, turn.body.request_id)).error?.code).toBe('agent_rejected');
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('an agent removed from the configuration: a turn in flight ends as unknown after a restart, never resent elsewhere', async () => {
|
||||
await agentsHarness();
|
||||
const { token } = await h.pair();
|
||||
const wendy = (await newConversation(token, 'wendy')).body.conversation_id as string;
|
||||
h.hermes.next({ kind: 'complete', afterMs: 600, output: 'late' });
|
||||
const turn = await h.textTurn(token, wendy, 'in flight');
|
||||
await h.waitState(token, turn.body.request_id, 'thinking');
|
||||
// The owner takes Wendy off the list and restarts the bridge.
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
const done = await h.waitTerminal(token, turn.body.request_id, 5000);
|
||||
expect(done.outcome).toBe('unknown');
|
||||
expect(done.error?.code).toBe('outcome_unknown');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']); // it ran once, at Wendy, and was not sent to anyone else
|
||||
expect((await newConversation(token, 'wendy')).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bridge configuration', () => {
|
||||
const base = { HERMES_API_KEY: 'k'.repeat(20), HERMEVEN_ALLOWED_ORIGINS: 'https://app.example', STT_PROVIDER: 'none' };
|
||||
it('builds each extra agent as a profile under the same gateway', () => {
|
||||
const config = loadConfig({ ...base, HERMES_BASE_URL: 'http://127.0.0.1:8642/', ...AGENT_ENV, HERMEVEN_AGENT_CODY_PROFILE: 'cody-review' });
|
||||
expect(config.agents.map((a) => [a.id, a.name, a.baseUrl])).toEqual([
|
||||
['default', 'Pepper', 'http://127.0.0.1:8642'],
|
||||
['wendy', 'Wendy', 'http://127.0.0.1:8642/p/wendy'],
|
||||
['cody', 'Cody R.', 'http://127.0.0.1:8642/p/cody-review'],
|
||||
]);
|
||||
expect(config.agents[1]!.apiKey).toBe(WENDY_KEY);
|
||||
});
|
||||
it('refuses a missing key, a repeated or reserved id, a malformed id, a bad profile and an over-long name', () => {
|
||||
const bad: Array<Record<string, string>> = [
|
||||
{ HERMEVEN_AGENTS: 'wendy' },
|
||||
{ HERMEVEN_AGENTS: 'wendy,wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: 'default', HERMEVEN_AGENT_DEFAULT_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: 'Wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY },
|
||||
{ HERMEVEN_AGENTS: '../x' },
|
||||
{ HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_PROFILE: '../default' },
|
||||
{ HERMEVEN_AGENTS: 'wendy', HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, HERMEVEN_AGENT_WENDY_NAME: 'x'.repeat(25) },
|
||||
];
|
||||
for (const env of bad) expect(() => loadConfig({ ...base, ...env }), JSON.stringify(env)).toThrow(ConfigError);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ client
|
||||
|
||||
let device: FakeDevice;
|
||||
let controller: Controller;
|
||||
let snapshot: Snapshot;
|
||||
let sent: Array<{ method: string; path: string; body: string }>;
|
||||
let agentsRoute: 'real' | 'not_found' | 'offline';
|
||||
let extras: Partial<ConstructorParameters<typeof Controller>[0]>;
|
||||
|
||||
function makeController(dev: FakeDevice): Controller {
|
||||
return new Controller({
|
||||
idleExit: null,
|
||||
...extras,
|
||||
device: dev,
|
||||
measure: (text, width) => measureTextWrap(text, width).lineCount,
|
||||
locale: 'en-US',
|
||||
pollIntervalMs: 20,
|
||||
submitAttempts: 3,
|
||||
submitRetryMs: 30,
|
||||
micStallMs: 300,
|
||||
makeClient: (baseUrl, token) =>
|
||||
new BridgeClient({
|
||||
baseUrl,
|
||||
token,
|
||||
timeoutMs: 500,
|
||||
fetchImpl: async (input, init) => {
|
||||
const path = new URL(String(input)).pathname;
|
||||
sent.push({ method: init?.method ?? 'GET', path, body: typeof init?.body === 'string' ? init.body : '' });
|
||||
if (path === '/v1/agents' && agentsRoute === 'offline') throw new TypeError('offline');
|
||||
if (path === '/v1/agents' && agentsRoute === 'not_found') {
|
||||
// What a bridge from before agent selection answers.
|
||||
return new Response(JSON.stringify({ schema_version: SCHEMA_VERSION, error: { code: 'not_found', message: 'Not found.', retryable: false } }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return fetch(input, init);
|
||||
},
|
||||
}),
|
||||
onChange: (s) => {
|
||||
snapshot = s;
|
||||
},
|
||||
});
|
||||
}
|
||||
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase} hud=${JSON.stringify(device.frame)}`);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
const phase = () => snapshot.state.phase;
|
||||
const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function paired(): Promise<void> {
|
||||
device = new FakeDevice();
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2');
|
||||
expect(phase()).toBe('ready');
|
||||
}
|
||||
/** The page is closed and opened again: same phone storage, new everything else. */
|
||||
async function relaunch(): Promise<void> {
|
||||
await controller.stop();
|
||||
const reborn = new FakeDevice();
|
||||
for (const [k, v] of device.storage) reborn.storage.set(k, v);
|
||||
device = reborn;
|
||||
controller = makeController(device);
|
||||
await controller.start();
|
||||
}
|
||||
async function ask(text: string): Promise<void> {
|
||||
controller.askText(text);
|
||||
await until('answer', () => phase() === 'answer');
|
||||
}
|
||||
const backToReady = async () => {
|
||||
device.doubleTap();
|
||||
await until('ready', () => phase() === 'ready');
|
||||
};
|
||||
|
||||
describe('glasses: choosing an agent', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('opens on the default agent and shows its name; a swipe at Ready moves through the list and wraps', async () => {
|
||||
await paired();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(device.frame.status).toContain('Swipe: agent');
|
||||
const seen: string[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
device.swipeDown();
|
||||
seen.push(device.frame.body.split('\n')[0]!);
|
||||
}
|
||||
expect(seen).toEqual(['Wendy', 'Cody R.', 'Pepper']);
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Cody R.\n\nReady.');
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
// Choosing asks the bridge for nothing and sends nothing to any agent.
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations' || s.path === '/v1/turns')).toEqual([]);
|
||||
expect(h.hermes.executions).toBe(0);
|
||||
});
|
||||
|
||||
it('a question after choosing Wendy goes to Wendy, every screen says so, and a follow-up continues with her', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250 });
|
||||
controller.askText('what is on the calendar');
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
expect(device.frame.body).toBe('Wendy is thinking…');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(device.frame.status).toContain('Wendy · Tap: ask');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await ask('and tomorrow');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']);
|
||||
expect(h.hermes.sessions.size).toBe(1);
|
||||
const creates = sent.filter((s) => s.path === '/v1/conversations');
|
||||
expect(creates.map((c) => JSON.parse(c.body).agent_id)).toEqual(['wendy']);
|
||||
});
|
||||
|
||||
it('spoken questions too: the recording goes to the chosen agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
device.swipeDown();
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
expect(device.frame.body).toContain('Cody R. is listening…');
|
||||
device.speak(0.5);
|
||||
device.tap();
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['cody']);
|
||||
});
|
||||
|
||||
it('each agent keeps its own conversation across switches', async () => {
|
||||
await paired();
|
||||
await ask('pepper one');
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await backToReady();
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
await ask('pepper two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('pepper one');
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(device.frame.body).toContain('wendy one');
|
||||
expect(h.hermes.executedBy).toEqual([null, 'wendy', null, 'wendy']);
|
||||
expect(h.hermes.sessions.size).toBe(2);
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').length).toBe(2);
|
||||
});
|
||||
|
||||
it('a swipe only chooses at Ready: on an answer it turns the page, and while busy it does nothing', async () => {
|
||||
await paired();
|
||||
device.swipeDown(); // Wendy
|
||||
h.hermes.next({ kind: 'complete', afterMs: 250, output: Array.from({ length: 80 }, (_, i) => `Sentence ${i + 1} of a long answer.`).join(' ') });
|
||||
controller.askText('long one');
|
||||
await until('thinking', () => phase() === 'thinking');
|
||||
device.swipeDown();
|
||||
device.swipeUp();
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(snapshot.state.pageIndex).toBe(0);
|
||||
device.swipeDown();
|
||||
expect(snapshot.state.pageIndex).toBe(1);
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
device.tap();
|
||||
await until('listening', () => phase() === 'listening' && device.micOpen);
|
||||
device.swipeDown();
|
||||
expect(snapshot.state.agentId).toBe('wendy');
|
||||
expect(phase()).toBe('listening');
|
||||
device.doubleTap();
|
||||
});
|
||||
|
||||
it('moving to another agent while a conversation is being created does not hand it to the wrong one', async () => {
|
||||
await paired();
|
||||
device.swipeDown(); // Wendy
|
||||
controller.askText('for wendy');
|
||||
device.swipeDown(); // ignored: no longer at Ready
|
||||
await until('answer', () => phase() === 'answer');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy']);
|
||||
await backToReady();
|
||||
device.swipeDown(); // Cody
|
||||
await ask('for cody');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'cody']);
|
||||
expect(device.frame.body).toContain('turn=1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: which agent it reopens on', () => {
|
||||
beforeEach(async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('reopened soon after talking to Wendy: opens on Wendy, same conversation', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy' && typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
await ask('wendy two');
|
||||
expect(device.frame.body).toContain('turn=2');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', 'wendy']);
|
||||
});
|
||||
|
||||
it('reopened after the conversation window: opens on the default agent, and Wendy starts fresh when chosen again', async () => {
|
||||
extras = { conversationGapMs: 60 };
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
await quiet(130);
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
await ask('pepper one');
|
||||
expect(h.hermes.executedBy).toEqual(['wendy', null]);
|
||||
await backToReady();
|
||||
device.swipeDown();
|
||||
await ask('wendy again');
|
||||
expect(device.frame.body).toContain('turn=1'); // a new conversation with her
|
||||
expect(h.hermes.sessions.size).toBe(3);
|
||||
});
|
||||
|
||||
it('chosen but never asked: reopening goes back to the default agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await until('saved', () => JSON.parse(device.storage.get('hermeven.v1')!).agentId === 'wendy');
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
});
|
||||
|
||||
it('the last agent has been taken off the list: opens on the default agent', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
(h.config.agents as unknown[]).splice(1, 1);
|
||||
await h.restartBridge();
|
||||
// (same address is not guaranteed after a restart in this harness: re-point the stored URL)
|
||||
const stored = JSON.parse(device.storage.get('hermeven.v1')!);
|
||||
device.storage.set('hermeven.v1', JSON.stringify({ ...stored, bridgeUrl: h.url }));
|
||||
await relaunch();
|
||||
expect(device.frame.body).toBe('Pepper\n\nReady.');
|
||||
expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'cody']);
|
||||
});
|
||||
|
||||
it('the bridge cannot be reached for the list at start: the last known list is used', async () => {
|
||||
await paired();
|
||||
device.swipeDown();
|
||||
await ask('wendy one');
|
||||
await until('saved', () => typeof JSON.parse(device.storage.get('hermeven.v1')!).lastTurnAt === 'number');
|
||||
agentsRoute = 'offline';
|
||||
await relaunch();
|
||||
expect(snapshot.state.agents.map((a) => a.id)).toEqual(['default', 'wendy', 'cody']);
|
||||
expect(device.frame.body).toBe('Wendy\n\nReady.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('glasses: with a bridge that offers no choice', () => {
|
||||
afterEach(async () => {
|
||||
await controller?.stop();
|
||||
});
|
||||
|
||||
it('a bridge with one agent: the screen is as before, a swipe at Ready does nothing, and no agent is named in requests', async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'real';
|
||||
extras = {};
|
||||
h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } });
|
||||
await paired();
|
||||
expect(device.frame).toEqual({ body: 'Hermeven\n\nReady.', status: 'Tap: ask · Double-tap: exit' });
|
||||
device.swipeDown();
|
||||
device.swipeUp();
|
||||
expect(device.frame.body).toBe('Hermeven\n\nReady.');
|
||||
await ask('hello');
|
||||
expect(device.frame.status).toBe('Tap: ask');
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]);
|
||||
});
|
||||
|
||||
it('a bridge from before agent selection (no /v1/agents): the same, and it still answers', async () => {
|
||||
sent = [];
|
||||
agentsRoute = 'not_found';
|
||||
extras = {};
|
||||
await agentsHarness();
|
||||
await paired();
|
||||
expect(snapshot.state.agents).toEqual([]);
|
||||
expect(device.frame.body).toBe('Hermeven\n\nReady.');
|
||||
device.swipeDown();
|
||||
await ask('hello');
|
||||
expect(h.hermes.executedBy).toEqual([null]);
|
||||
expect(sent.filter((s) => s.path === '/v1/conversations').map((c) => JSON.parse(c.body))).toEqual([{ schema_version: SCHEMA_VERSION }]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user