histoire
Version:
A fast story book powered by Vite
112 lines (111 loc) • 5.12 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { validateElicitationContent } from '@histoire/shared';
import { projectElicitation } from './elicitation-schema.js';
/** Abandoned or refused-to-show requests. */
const cancelled = { action: 'cancel' };
/** Most simultaneously open cards; extra requests are cancelled. */
const PENDING_LIMIT = 8;
/** Unanswered requests are cancelled after this delay. */
const DEFAULT_TIMEOUT = 10 * 60_000;
/**
* Mediates agent requests for user input (forms and links) for in-thread cards.
* Entered values are only forwarded to the agent; they are never emitted or stored.
*/
export function createElicitationBroker(options) {
const entries = new Map();
let closed = false;
/**
* Removes one entry, answering the agent if it still waits.
* @param requestId Broker-owned identity.
* @param response Answer for a waiting agent request.
* @param reason Removal cause sent to browsers.
*/
function finish(requestId, response, reason) {
const entry = entries.get(requestId);
if (!entry)
return;
entries.delete(requestId);
clearTimeout(entry.timer);
entry.finish?.(response);
options.resolved({ requestId, reason });
}
/** Cancels every entry of an agent, one of its sessions, or all of them. */
function cancel(agentId, sessionId) {
for (const [id, entry] of entries) {
if ((!agentId || entry.agentId === agentId) && (!sessionId || entry.sessionId === sessionId))
finish(id, cancelled, 'cancelled');
}
}
return {
/**
* Shows one agent request in its thread and waits for the user.
* @param agentId Agent preset id.
* @param request Agent elicitation request.
* @param signal Agent-side cancellation.
*/
request(agentId, request, signal) {
const sessionId = 'sessionId' in request && typeof request.sessionId === 'string' ? request.sessionId : undefined;
const threadId = sessionId && options.threadOf(agentId, sessionId);
if (closed || signal?.aborted || !sessionId || !threadId || entries.size >= PENDING_LIMIT)
return Promise.resolve(cancelled);
const projected = projectElicitation(request, options.sanitize);
if (!projected)
return Promise.resolve({ action: 'decline' });
return new Promise((resolve) => {
const requestId = randomUUID();
const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT;
const timer = setTimeout(() => finish(requestId, cancelled, 'expired'), timeout);
timer.unref?.();
const { elicitationId, ...card } = projected;
entries.set(requestId, { agentId, sessionId, fields: card.mode === 'form' ? card.fields : undefined, elicitationId, finish: resolve, timer });
signal?.addEventListener('abort', () => finish(requestId, cancelled, 'cancelled'), { once: true });
options.emit({ ...card, requestId, agentId, threadId, expiresAt: new Date(Date.now() + timeout).toISOString() });
});
},
/**
* Applies one browser answer; returns false when form content is invalid and the card stays open.
* An accepted link stays listed until the agent completes it or the turn ends.
* @param requestId Broker-owned identity.
* @param action Submit, skip, or dismiss.
* @param content Submitted form values, validated against the card's fields.
*/
reply(requestId, action, content) {
const entry = entries.get(requestId);
if (!entry)
return false;
if (!entry.finish || action !== 'accept') {
finish(requestId, { action }, 'answered');
return true;
}
if (entry.elicitationId) {
entry.finish({ action: 'accept' });
entry.finish = undefined;
return true;
}
const checked = validateElicitationContent(entry.fields ?? [], content ?? {});
if ('errors' in checked)
return false;
finish(requestId, { action: 'accept', content: checked.content }, 'answered');
return true;
},
/**
* Agent finished a link flow out of band.
* @param agentId Agent preset id.
* @param elicitationId Agent link identity.
*/
complete(agentId, elicitationId) {
for (const [id, entry] of entries) {
if (entry.agentId === agentId && entry.elicitationId === elicitationId)
finish(id, cancelled, 'completed');
}
},
cancel,
/** Ends a prompt: its unanswered cards are cancelled. */
settle(agentId, sessionId) { cancel(agentId, sessionId); },
/** Cancels everything before the runtime retires. */
close() {
closed = true;
cancel();
},
};
}