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:
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user