histoire
Version:
A fast story book powered by Vite
53 lines (52 loc) • 2.64 kB
JavaScript
import { createAgentRuntime } from './agent-runtime.js';
/** Coalesced startup owns its record before any package download or SDK await. */
export async function startAgentRecord(record, preset, options) {
/** Only the record's live prompt may ask the user anything. */
const active = (sessionId) => options.owned() && Boolean(sessionId) && record.active?.sessionId === sessionId;
try {
const prepared = await options.prepare();
if (!options.owned())
throw new Error('Agent runtime closed');
record.environment = prepared.environment;
record.runtime = createAgentRuntime(prepared.preset, {
root: options.root,
environment: record.environment,
sanitize: options.sanitize,
timeout: options.timeout,
log(lines) {
if (options.owned()) {
record.status.logs = lines;
options.changed();
}
},
failed(error, missing) {
if (options.owned()) {
record.status.state = missing ? 'not-installed' : 'error';
record.status.error = error;
options.brokers.cancel(preset.id);
options.changed();
}
},
permission: (request, signal) => active(request.sessionId) ? options.brokers.permissions.request(preset.id, request, signal) : Promise.resolve({ outcome: { outcome: 'cancelled' } }),
elicitation: (request, signal) => active('sessionId' in request ? request.sessionId : undefined) ? options.brokers.elicitations.request(preset.id, request, signal) : Promise.resolve({ action: 'cancel' }),
elicitationComplete: (params) => { if (options.owned())
options.brokers.elicitations.complete(preset.id, params.elicitationId); },
update: (notification) => { if (options.owned())
options.update(notification); },
});
await record.runtime.ready;
if (!options.owned())
throw new Error('Agent runtime closed');
record.status.state = 'connected';
options.changed();
}
catch (error) {
const message = await record.runtime?.failureMessage() ?? options.sanitize(error instanceof Error ? error.message : String(error));
record.status.state = record.status.state === 'not-installed' ? 'not-installed' : 'error';
record.status.error = message;
await record.runtime?.stop();
if (options.owned())
options.changed();
throw new Error(message);
}
}