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:
Dan
2026-11-21 16:08:11 -08:00
co-authored by Claude Fable 5.2
parent 15714bd848
commit 9394c249ad
20 changed files with 1117 additions and 42 deletions
+128 -3
View File
@@ -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;