@sema-agent/core
Version:
Stateless, task-oriented AI agent core
160 lines (159 loc) • 9.26 kB
JavaScript
import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
import { appendInterruptionMarker, reconcileInterruptedSession } from "../session-reconcile.js";
import { emitTrace } from "../trace.js";
import { parkedInputIdsOf } from "../types.js";
import { answerSettled } from "./assemble-result.js";
import { errorCodeOf } from "./terminal-account.js";
import { awaitChargeWithSlowDisclosure } from "./clock-and-limits.js";
import { emitSettled, reconciledEnd } from "./tool-end-body.js";
import { costFigureOf } from "./side-call-account.js";
import { isApprovalWordsFrame } from "./approval-feedback.js";
import { asThrownError } from "../thrown-value.js";
import { raceTeardownLeg } from "./teardown-bounded.js";
export async function runTerminalAdoption(input) {
const { queue, prepared, rs, stats, ident, emitCommitted, startedToolCallIds, toolLabels, timeout, undrainedUserAtEnd, userInputLostAtEnd, final, abortedLive, userInterruptedLive, runner, sessions, next } = input;
let { threw } = input;
const settled = answerSettled(final, userInputLostAtEnd.current || prepared.undeliveredContinuationRef.current.parkedSteers.length > 0 || prepared.workCutRef.continuation || prepared.workCutRef.abortedBeforeTurnEnd);
if (threw === undefined && prepared.brainCallGuardrailRef.timedOut !== undefined) {
threw = prepared.brainCallGuardrailRef.timedOut;
}
if (threw === undefined && prepared.gateStopRef.terminal !== undefined) {
threw = prepared.gateStopRef.terminal;
}
if (threw === undefined && prepared.harness.answerRefusal !== undefined)
threw = prepared.harness.answerRefusal;
if (rs.limits.platformTerminal !== undefined) {
threw = rs.limits.platformTerminal;
}
if (prepared.usageGovernance !== undefined) {
try {
await awaitChargeWithSlowDisclosure(prepared.usageGovernance.commit(stats.tokens, costFigureOf(rs.telemetry, stats.costMicroUsd), Date.now()), () => runner.deps.onError?.(new Error("the usage ledger's FINAL charge has not settled after 10s — still waiting (a charge is never abandoned: walking away would double-charge on a later flush). A wedged ledger store wedges this teardown, now visibly."), { phase: "config", sessionId: prepared.sessionId }));
}
catch (flushErr) {
runner.deps.onError?.(flushErr, { phase: "config", sessionId: prepared.sessionId });
}
}
const committedPause = prepared.pausedRef.current;
const durablyPaused = committedPause !== undefined;
const interrupted = !durablyPaused &&
(threw !== undefined || timeout.fired || rs.limits.turnsExceeded || rs.limits.budgetHit !== undefined || abortedLive || final?.stopReason === "aborted");
let orphansClosed = 0;
let reconcileComplete = false;
if (interrupted) {
try {
const report = await reconcileInterruptedSession(prepared.session, prepared.toolEffects, undefined, startedToolCallIds, prepared.admitRows);
orphansClosed = report.recovered.length;
for (const orphan of report.recovered) {
emitSettled(prepared.toolOccurrences, { toolCallId: orphan.toolCallId, spelledName: orphan.toolName, ...(toolLabels.has(orphan.toolName) ? { label: toolLabels.get(orphan.toolName) } : {}), args: orphan.args }, reconciledEnd(orphan), { push: (f) => queue.push({ ...f, ...ident() }), structured: prepared.structuredProjector, mediaBudgetBase64Chars: runner.deps.mediaBudgetBase64Chars, reviewRequest: prepared.reviewRequestRef, verdicts: prepared.verdictLedger });
emitCommitted(orphan.entryId, "toolResult", orphan.toolCallId);
}
reconcileComplete = true;
}
catch (reconcileErr) {
runner.deps.onError?.(asThrownError(reconcileErr), {
phase: "interrupt-reconcile",
sessionId: prepared.sessionId,
});
}
if (reconcileComplete) {
try {
await prepared.harness.flushQueuedSessionWrites();
}
catch (flushErr) {
runner.deps.onError?.(asThrownError(flushErr), {
phase: "interrupt-reconcile",
sessionId: prepared.sessionId,
});
}
}
else {
for (const write of prepared.harness.heldSessionWrites()) {
const what = write.type === "message" ? `a ${write.message.role} row` : `a ${write.type} write`;
runner.deps.onError?.(new Error(`held session write not stored: ${what} queued while the turn ran — the interrupted batch was not closed, and a write after an open batch breaks the transcript`), { phase: "interrupt-reconcile", sessionId: prepared.sessionId });
}
}
}
if (interrupted && userInterruptedLive && reconcileComplete && !settled) {
try {
const entryId = await appendInterruptionMarker(prepared.session, { toolUseInFlight: orphansClosed > 0, admitRows: prepared.admitRows });
emitCommitted(entryId, "user", undefined, { origin: "interruption_marker" });
}
catch (markerErr) {
runner.deps.onError?.(asThrownError(markerErr), {
phase: "interrupt-reconcile",
sessionId: prepared.sessionId,
});
}
}
let migratedParked = { steer: 0, followUp: 0 };
let carriedContinuation = 0;
const carriedContinuationInputIds = [];
let carriedApproval = 0;
let approvalRefusal;
if (committedPause !== undefined) {
const parkToken = committedPause.cause.token;
const parkScope = committedPause.scope;
const { store, holder } = committedPause.writes;
const carried = [];
const owed = [
...prepared.undeliveredContinuationRef.current.parkedSteers.map((frame) => {
const { seq: _seq, ...input } = frame;
return { input, ...(isApprovalWordsFrame(frame) ? { approval: true } : {}) };
}),
...prepared.harness.readParkableUserInputs().map((record) => ({ input: record, live: record })),
];
for (const { input, live, approval } of owed) {
try {
if (!(await raceTeardownLeg(() => (holder !== undefined ? store.setPendingSteer(parkToken, parkScope, input, { holder }) : store.setPendingSteer(parkToken, parkScope, input)), "checkpointStore.setPendingSteer (parked-input migration leg)")))
break;
if (live !== undefined)
carried.push(live);
else if (approval)
carriedApproval += 1;
else {
carriedContinuation += 1;
if (typeof input.inputId === "string")
carriedContinuationInputIds.push(input.inputId);
}
}
catch (parkErr) {
runner.deps.onError?.(asThrownError(parkErr), {
phase: "config",
sessionId: prepared.sessionId,
});
const parkCode = errorCodeOf(parkErr);
if (parkCode === "steering.invalid_content" || parkCode === "steering.queue_full") {
if (approval)
approvalRefusal = parkCode;
continue;
}
break;
}
}
const dropped = prepared.harness.dropParkedUserInputs(carried);
migratedParked = { steer: dropped.steer, followUp: dropped.followUp, inputIds: parkedInputIdsOf(dropped.records) };
}
const owedUserInput = { held: undrainedUserAtEnd.current, migrated: migratedParked, continuation: { frames: prepared.undeliveredContinuationRef.current.parkedSteers.filter((f) => !isApprovalWordsFrame(f)), carried: carriedContinuation, carriedInputIds: carriedContinuationInputIds, approval: { owed: prepared.undeliveredContinuationRef.current.parkedSteers.filter(isApprovalWordsFrame).length, carried: carriedApproval, ...(approvalRefusal !== undefined ? { refusal: approvalRefusal } : {}) } } };
if (rs.attach.attachState?.postCompactPending === true && (rs.attach.attachmentsCfg?.backgroundTasks ?? eventDefaultOn("background_tasks")) === true) {
emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.announce_dropped", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
}
await finish(prepared, runner, sessions);
return await next({ threw, answerSettled: settled, owedUserInput });
}
async function finish(prepared, runner, sessions) {
await raceTeardownLeg(() => sessions.touch(prepared.sessionId), "sessions.touch (settle leg)").catch((err) => runner.deps.onError?.(err, { phase: "config", sessionId: prepared.sessionId }));
try {
await prepared.mcp.dispose();
}
catch (err) {
runner.deps.onError?.(err, { phase: "mcp", sessionId: prepared.sessionId });
}
if (prepared.a2a !== undefined) {
try {
await prepared.a2a.dispose();
}
catch (err) {
runner.deps.onError?.(err, { phase: "a2a", sessionId: prepared.sessionId });
}
}
}