@sema-agent/core
Version:
Stateless, task-oriented AI agent core
316 lines (315 loc) • 16.6 kB
JavaScript
import { terminalProjection } from "../core/runner/terminal-projection.js";
import { releaseSession } from "./session-util.js";
import { recordsStand } from "../core/session-checkout.js";
import { mapNestedSuspend, isDurablePause, resumeNeverStarted } from "./suspend-guard.js";
import { buildCumulativeStats, emptyCumulativeUsageFacts, foldUsageFacts } from "./cumulative-stats.js";
import { closeComposition } from "../core/task-intake.js";
import { createSafeNotifier } from "../core/safe-notify.js";
import { compositionPlacement } from "./composition-placement.js";
import { identityMembersOf } from "../core/isolation-scope.js";
import { withLegIdentity } from "./leg-label.js";
import { thrownText } from "../core/thrown-value.js";
import { enteringMembersOf, withoutSessionBinding } from "../core/task-spec-members.js";
const CASCADE_ON_RUNG_SITE = "cascade.onRung";
const CASCADE_CONFIG_ERROR_CODE = "config.cascade_invalid";
const CASCADE_NO_DISPATCH_ERROR_CODE = "cascade.budget_exhausted";
function cascadeConfigError(message) {
const e = new Error(message);
e.code = CASCADE_CONFIG_ERROR_CODE;
return e;
}
function attemptTerminal(result) {
const face = terminalProjection(result.terminal);
return { status: face.status, errorCode: face.errorCode };
}
function createDefaultGate(spec) {
const requiresStructured = spec.outputSchema != null;
return (result) => result.terminal.kind === "completed" && (!requiresStructured || result.structuredOutput !== undefined);
}
export async function runCascade(runner, spec, config, internals) {
const hostSessionId = spec.sessionId || undefined;
return climbLadder("runCascade", runner, spec, config, internals, { kind: "fresh", hostSessionId });
}
export async function resumeCascade(runner, token, outcome, spec, config, parkedLeg, internals) {
const ladderLength = config.ladder?.length ?? 0;
const leg = parkedLeg;
const entry = typeof leg === "object" && leg !== null ? Reflect.get(leg, "entry") : undefined;
const index = typeof leg === "object" && leg !== null ? Reflect.get(leg, "leg") : undefined;
const host = typeof leg === "object" && leg !== null ? Reflect.get(leg, "hostSessionId") : undefined;
if (ladderLength > 0 && (entry !== "cascade" || typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= ladderLength || typeof host !== "string" || host === "")) {
throw cascadeConfigError(`resumeCascade: parkedLeg must be the card's cascade leg of this ladder — { entry: "cascade", leg: <a rung index below ${ladderLength}>, hostSessionId: <a session> } (got ${describeParkedLeg(leg)}); nothing was resumed and the checkpoint is untouched.`);
}
return climbLadder("resumeCascade", runner, spec, config, internals, { kind: "resume", token, outcome, parked: { entry: "cascade", leg: index, hostSessionId: host } });
}
function describeParkedLeg(leg) {
if (typeof leg !== "object" || leg === null)
return typeof leg;
try {
return JSON.stringify({ entry: Reflect.get(leg, "entry"), leg: Reflect.get(leg, "leg"), hostSessionId: Reflect.get(leg, "hostSessionId") }) ?? "an unreadable object";
}
catch {
return "an unreadable object";
}
}
async function climbLadder(entryName, runner, spec, config, internals, opening) {
const ladder = config.ladder;
if (!ladder || ladder.length === 0) {
throw new Error(`${entryName}: config.ladder must have at least one rung`);
}
const entering = enteringMembersOf(spec);
if (entering.length > 0) {
const names = entering.map((name) => `\`${name}\``).join(", ");
throw cascadeConfigError(`${entryName}: the task spec carries ${names} — ${entering.length === 1 ? "an operation" : "operations"} a run performs on ENTERING a session (branch it at an entry, converge its files to a history boundary, open on what is parked for it). ` +
`Every rung of a cascade is a cold re-run in a session of its own and none of them enters the session the spec's \`sessionId\` names (that id names the host's session: where the ladder is placed, whose cards its rungs park under, and the tree they stand in), so ${entering.length === 1 ? "it" : "they"} would not be applied. ` +
`Refused before any rung was dispatched and before a checkpoint was consumed. Drop ${entering.length === 1 ? "it" : "them"}, or run the leg that enters the session yourself (\`runner.runTask\`, or a composition whose first leg enters it: \`runWithVerification\`, \`runRepairLoop\`, \`runGoal\`) and give the cascade the rest.`);
}
const maxEscalations = config.maxEscalations ?? ladder.length - 1;
if (typeof maxEscalations !== "number" || !Number.isFinite(maxEscalations)) {
throw cascadeConfigError(`${entryName}: config.maxEscalations must be a finite number (got ${String(config.maxEscalations)}) — an unevaluable escalation ceiling is not a ceiling, and folding it to a default would run the cascade under a bound nobody chose.`);
}
const start = opening.kind === "resume" ? opening.parked.leg : 0;
const maxRungs = Math.min(ladder.length, start + Math.max(0, maxEscalations) + 1);
const hostSessionId = opening.kind === "resume" ? opening.parked.hostSessionId : opening.hostSessionId;
const gate = config.gate ?? createDefaultGate(spec);
const startedAt = Date.now();
const deadlineAt = config.totalTimeoutMs != null ? startedAt + config.totalTimeoutMs : undefined;
const notifier = createSafeNotifier(config.onNotifyError !== undefined ? { onError: config.onNotifyError } : undefined);
const attempts = [];
let totalCost = 0;
let ceilingCostKnown = true;
let ownTokens = 0, ownTurns = 0, ownPrompt = 0, ownCached = 0, ownOutput = 0, ownCostMicro = 0;
let ownTotalInput = 0;
let ownCacheWrite = 0, ownCacheWriteLong = 0, ownApiDuration = 0, ownFastSpeedCalls = 0;
const ownUsageFacts = emptyCumulativeUsageFacts();
let nestedTokens = 0, nestedTurns = 0, nestedTasks = 0, nestedCostMicro = 0;
let ownLlmRootMicro = 0, ownCompactionMicro = 0;
let ownSideCallMicro;
let anyRungUnpriced = false;
let hrKept = false, hrCount = 0, hrWaitMs = 0;
const hrGates = [];
const cumulativeStats = (baseStats) => buildCumulativeStats(baseStats, {
tokens: ownTokens,
turns: ownTurns,
promptTokens: ownPrompt,
totalInputTokens: ownTotalInput,
cachedTokens: ownCached,
outputTokens: ownOutput,
cacheWriteTokens: ownCacheWrite,
cacheWriteTokensLong: ownCacheWriteLong,
apiDurationMs: ownApiDuration,
fastSpeedCalls: ownFastSpeedCalls,
costMicroUsd: ownCostMicro,
anyLegUnpriced: anyRungUnpriced,
llmRootMicroUsd: ownLlmRootMicro,
compactionMicroUsd: ownCompactionMicro,
...(ownSideCallMicro !== undefined ? { sideCallMicroUsd: ownSideCallMicro } : {}),
nested: { tokens: nestedTokens, turns: nestedTurns, tasks: nestedTasks, costMicroUsd: nestedCostMicro },
humanReview: { kept: hrKept, count: hrCount, totalWaitMs: hrWaitMs, gates: hrGates },
usageFacts: ownUsageFacts,
});
let lastResult;
let passedRung = -1;
let firstLegResult;
let finalRung = -1;
const rungs = [];
const specBase = withoutSessionBinding(spec);
const placement = compositionPlacement(internals, identityMembersOf(specBase), opening.kind === "fresh" ? opening.hostSessionId : undefined);
const rungSpecOf = (rung, signal) => ({ ...specBase, model: rung.model, ...(rung.overrides ?? {}), ...(signal ? { signal } : {}) });
const resumeConfigOf = (task) => {
const { objective: _objective, userAttachments: _attachments, runOrigin: _origin, ...config } = task;
return config;
};
const legOf = (i) => (hostSessionId === undefined ? undefined : { entry: "cascade", leg: i, hostSessionId });
let heldRung;
const releaseRung = async (sessionId) => {
heldRung = sessionId;
};
const releaseHeldRung = async () => {
const sessionId = heldRung;
heldRung = undefined;
if (sessionId !== undefined)
await releaseSession(runner, sessionId);
};
const settleFinalRung = async () => {
const sessionId = heldRung;
heldRung = undefined;
if (sessionId !== undefined && !(await recordsStand(runner.sessions, sessionId)))
await releaseSession(runner, sessionId);
};
for (let i = start; i < maxRungs; i++) {
const resumed = opening.kind === "resume" && i === start ? opening : undefined;
if (resumed === undefined) {
if (deadlineAt !== undefined && Date.now() >= deadlineAt)
break;
if (i > start && config.costCeilingMicroUsd != null && (totalCost >= config.costCeilingMicroUsd || !ceilingCostKnown)) {
break;
}
}
if (heldRung !== undefined)
await releaseHeldRung();
const rung = ladder[i];
let deadlineFired = false;
const rungAbort = new AbortController();
let deadlineTimer;
if (deadlineAt !== undefined && resumed === undefined) {
deadlineTimer = setTimeout(() => {
deadlineFired = true;
rungAbort.abort(new Error(`${entryName}: totalTimeoutMs (${config.totalTimeoutMs}ms) reached`));
}, Math.max(0, deadlineAt - Date.now()));
deadlineTimer.unref?.();
}
const rungSignal = deadlineTimer === undefined
? specBase.signal
: specBase.signal
? AbortSignal.any([specBase.signal, rungAbort.signal])
: rungAbort.signal;
let result;
const placed = firstLegResult === undefined ? placement.firstLeg : placement.laterLeg(firstLegResult);
const compositionLeg = resumed !== undefined ? resumed.parked : legOf(i);
const rungTask = placement.laterIdentity(rungSpecOf(rung, rungSignal));
let rungInternals;
try {
rungInternals = withLegIdentity(compositionLeg === undefined ? placed : { ...placed, compositionLeg }, { kind: "rung", round: i }, internals, resumed !== undefined ? "resumeStream" : "runTaskStream");
result = resumed !== undefined ? await runner.resume(resumed.token, resumed.outcome, resumeConfigOf(rungTask), rungInternals) : await runner.runTask(rungTask, rungInternals);
}
finally {
if (deadlineTimer !== undefined)
clearTimeout(deadlineTimer);
}
lastResult = result;
rungs.push(result);
finalRung = i;
firstLegResult ??= result;
const s = result.stats;
const rungCostKnown = s.costMicroUsd !== undefined && (s.nested === undefined || s.nested.costMicroUsd !== undefined);
const rungCost = rungCostKnown ? (s.costMicroUsd ?? 0) + (s.nested?.costMicroUsd ?? 0) : undefined;
totalCost += rungCost ?? 0;
if (!rungCostKnown)
ceilingCostKnown = false;
ownTokens += s.tokens;
ownTurns += s.turns;
ownPrompt += s.promptTokens ?? 0;
ownTotalInput += s.totalInputTokens ?? 0;
ownCached += s.cachedTokens ?? 0;
ownOutput += s.outputTokens ?? 0;
ownCacheWrite += s.cacheWriteTokens ?? 0;
ownCacheWriteLong += s.cacheWriteTokensLong ?? 0;
ownApiDuration += s.apiDurationMs ?? 0;
ownFastSpeedCalls += s.fastSpeedCalls ?? 0;
foldUsageFacts(ownUsageFacts, s);
ownCostMicro += s.costMicroUsd ?? 0;
if (s.costMicroUsd === undefined)
anyRungUnpriced = true;
if (s.costBreakdown) {
ownLlmRootMicro += s.costBreakdown.llmRootMicroUsd;
ownCompactionMicro += s.costBreakdown.compactionMicroUsd;
if (s.costBreakdown.sideCallMicroUsd !== undefined)
ownSideCallMicro = (ownSideCallMicro ?? 0) + s.costBreakdown.sideCallMicroUsd;
}
if (s.humanReview) {
hrKept = true;
hrCount += s.humanReview.count;
hrWaitMs += s.humanReview.totalWaitMs;
hrGates.push(...s.humanReview.gates);
}
if (s.nested) {
nestedTokens += s.nested.tokens;
nestedTurns += s.nested.turns;
nestedTasks += s.nested.tasks;
nestedCostMicro += s.nested.costMicroUsd ?? 0;
}
if (isDurablePause(result.terminal) || resumeNeverStarted(result)) {
const continuable = isDurablePause(result.terminal) || (result.terminal.kind === "failed" && result.terminal.unstartedRow === "reopened");
const mapped = mapNestedSuspend(result, { door: "resumeCascade", legFrom: rungInternals?.compositionLeg === undefined ? "caller" : "card" });
attempts.push({ index: i, model: rung.model, passed: false, costMicroUsd: rungCost, status: attemptTerminal(result).status, errorCode: attemptTerminal(mapped).errorCode });
return {
...closeComposition(mapped, rungs),
stats: cumulativeStats(result.stats),
cascadeOutcome: continuable ? "suspended" : "exhausted",
...(config.costCeilingMicroUsd != null && !ceilingCostKnown ? { costCeilingUnenforceable: true } : {}),
escalated: i > 0,
finalRung: i,
attempts,
};
}
const superseded = result.terminal.kind === "failed" && result.terminal.code === "holder.superseded";
if (deadlineFired || specBase.signal?.aborted === true || superseded) {
attempts.push({
index: i,
model: rung.model,
passed: false,
costMicroUsd: rungCost,
...attemptTerminal(result),
...(deadlineFired ? { timedOut: true } : superseded ? {} : { cancelled: true }),
});
notifier.notify(() => config.onRung?.({ index: i, model: rung.model, passed: false, result }), CASCADE_ON_RUNG_SITE);
await releaseRung(result.sessionId);
break;
}
let passed = false;
let gateError;
let diagnostics;
try {
try {
const verdict = await gate(result, { index: i, model: rung.model });
if (typeof verdict === "boolean")
passed = verdict;
else {
passed = verdict.pass;
diagnostics = verdict.diagnostics;
}
}
catch (e) {
passed = false;
gateError = thrownText(e);
}
const statusRejected = passed && config.acceptPartial !== true && result.terminal.kind !== "completed";
if (statusRejected)
passed = false;
attempts.push({
index: i,
model: rung.model,
passed,
costMicroUsd: rungCost,
...attemptTerminal(result),
gateError,
diagnostics,
...(statusRejected ? { statusRejected: true } : {}),
});
notifier.notify(() => config.onRung?.({ index: i, model: rung.model, passed, result }), CASCADE_ON_RUNG_SITE);
}
finally {
await releaseRung(result.sessionId);
}
if (passed) {
passedRung = i;
break;
}
}
await settleFinalRung();
if (lastResult === undefined) {
return {
taskId: spec.taskId ?? "",
sessionId: "",
result: `runCascade: the overall wall-clock budget (totalTimeoutMs ${config.totalTimeoutMs}ms) was already spent when the ladder was entered — no rung dispatched`, resultEntryIds: [],
intake: { committed: false },
continuesFrom: { none: "nothing_taken_in" },
terminal: { kind: "failed", code: CASCADE_NO_DISPATCH_ERROR_CODE },
stats: { tokens: 0, turns: 0, costMicroUsd: 0 },
cascadeOutcome: "exhausted",
escalated: false,
finalRung: -1,
attempts,
};
}
const base = lastResult;
return {
...closeComposition(base, rungs),
stats: cumulativeStats(base.stats),
cascadeOutcome: passedRung >= 0 ? "passed" : "exhausted",
...(config.costCeilingMicroUsd != null && !ceilingCostKnown ? { costCeilingUnenforceable: true } : {}),
escalated: finalRung > 0,
finalRung,
attempts,
};
}