@sema-agent/core
Version:
Stateless, task-oriented AI agent core
207 lines (206 loc) • 15.4 kB
JavaScript
import { isDeploymentEnvCode } from "../remote-env.js";
import { isDegenerateCutMessage } from "../../brain/terminal-cause.js";
import { extractErrorCode, isProviderEchoShape, refusedTheRequest, stripErrorCodePrefix } from "../../brain/errors.js";
import { SPEND_ACCOUNT_CLOSED_CODE, spendRefusalOf, spendStopSentence } from "../../brain/spend-meter.js";
import { completedTerminalOf, loopExitFailureOf, modelOutputInvalidOfMessage, providerSentenceOf, providerVerdictOf, refusedPartOf, requestRouteOfMessage, thrownFailureOf } from "./terminal-account.js";
import { terminalProjection } from "./terminal-projection.js";
import { endingCutConsumed, haltConsumed, turnAbortedByOf } from "./halt-attribution.js";
import { providerReportedModel } from "../message-utils.js";
import { readMember, thrownText } from "../thrown-value.js";
import { readDenyFloorSeat } from "../../tools/fs/read-floor.js";
import { withRewindOutcome } from "./rewind-outcome.js";
const SALVAGE_ELIGIBLE_TERMINALS = new Set([
"output.degenerate",
"limits.max_tokens_exceeded",
"limits.max_cost_exceeded",
"limits.max_turns_exceeded",
"limits.max_walltime_exceeded",
"usage.window_exhausted",
]);
function stripThinkTags(text) {
let t = text.replace(/<think>[\s\S]*?<\/think>/gi, "");
const lower = t.toLowerCase();
const close = lower.lastIndexOf("</think>");
if (close !== -1 && !lower.slice(0, close).includes("<think>")) {
t = t.slice(close + "</think>".length);
}
return t.replace(/<\/?think>/gi, "").trim();
}
function assistantText(msg) {
const text = msg.content
.filter((c) => c.type === "text")
.map((c) => c.text)
.join("");
return stripThinkTags(text);
}
export function answerSettled(final, continuationCut = false) {
return final?.stopReason === "stop" && final.partialFinalized !== true && !continuationCut;
}
export function terminalCauseOf(final, stats, flags) {
let terminal;
let apiFailure;
const cutOwnsAbortedFinal = endingCutConsumed(flags.haltConsumption) &&
final?.stopReason === "aborted" &&
!flags.abortedLive &&
flags.abortedForTimeout !== true &&
flags.abortedForTurns !== true;
const errorKind = readMember(final, "errorKind");
const isDegenerate = final?.stopReason === "error" && isDegenerateCutMessage({ errorKind: errorKind });
const loopExit = loopExitFailureOf(flags.loopTerminal);
if (flags.writeRefusal === "holder.superseded" && flags.paused === undefined) {
terminal = { kind: "failed", code: "holder.superseded", message: "this leg's grant is no longer the run's current one (another leg holds the run, or the run has ended): the session refused its write and the leg stopped — nothing it wrote after that is in the session; do not retry it" };
}
else if (flags.outputInvalid) {
const refused = flags.verdictLastEndRefused === true ? flags.refusalRecords?.(true).verdictRefused : undefined;
terminal = { kind: "failed", code: "output.invalid", message: refused !== undefined ? `the structured output submissions were refused at the gate (${refused.deniedBy}) until the retry limit; no result was delivered (see verdictRefused)` : "model did not produce a valid structured output within the retry limit" };
}
else if (isDegenerate) {
terminal = { kind: "failed", code: "output.degenerate", ...(final?.errorMessage !== undefined ? { message: final.errorMessage } : {}) };
}
else if (flags.budgetHit && flags.answerSettled !== true) {
const axisName = flags.budgetAxis === "tokens" ? "limits.maxTokens" : "limits.maxCostUsd";
const up = flags.spendStop?.heldBy === "ancestor" ? flags.spendStop : undefined;
const whose = up !== undefined ? `an enclosing run's ceiling (${up.observed} / ${up.limit} ${flags.budgetAxis === "tokens" ? "tokens, input + output" : "micro-USD"})` : axisName;
const told = spendRefusalOf(final)?.sent === true ? `the model request was sent with its output ceiling narrowed to what is left of ${whose}, and it used all of it; any text it produced is kept in the result` : `the next model request did not fit what is left of ${whose}; it was not sent`;
terminal = {
kind: "failed",
code: flags.budgetAxis === "tokens" ? "limits.max_tokens_exceeded" : "limits.max_cost_exceeded",
message: flags.budgetHit === "precall" ? `${told}${up !== undefined ? ` — raising this run's ${axisName} does not help` : ""}` : `cumulative usage exceeded ${axisName}`,
};
}
else if (flags.suspendLoop) {
let message = "task suspended too many times (resume/restart loop) — exceeded the suspend limit";
const gates = stats.humanReview?.gates ?? [];
if (gates.length > 0 && gates.every((g) => g.decision === "allow")) {
message +=
`. Diagnosis: all ${gates.length} recorded gate decision(s) on this run were ALLOW — a gate that keeps ` +
`asking combined with an approver that keeps approving consumes the suspend allowance on legitimate ` +
`work. Remedies: answer asks at a LIVE onAsk (a synchronous allow parks nothing and consumes no ` +
`suspend), keep provably-benign commands inside the read boundary so the classifier auto-allows them, ` +
`or raise maxSuspends for genuinely approval-heavy tasks.`;
}
terminal = { kind: "failed", code: "suspend.loop", message };
}
else if (flags.threw) {
const thrown = thrownFailureOf(flags.threw, thrownText(flags.threw));
const axisCode = flags.abortedForTimeout ? "limits.max_walltime_exceeded" : flags.abortedForTurns ? "limits.max_turns_exceeded" : flags.writeRefusal === "conflict" ? "conflict" : undefined;
const code = axisCode ?? thrown.code;
const detail = axisCode === undefined ? thrown.detail : undefined;
terminal = { kind: "failed", ...(code !== undefined ? { code } : {}), message: thrown.message, ...(detail !== undefined ? { detail } : {}) };
}
else if (flags.blockedReason) {
terminal = { kind: "blocked", reason: flags.blockedReason, ...(flags.blockedDetail !== undefined ? { detail: flags.blockedDetail } : {}) };
}
else if (flags.paused) {
terminal = flags.paused;
}
else if ((flags.abortedLive || final?.stopReason === "aborted") && !cutOwnsAbortedFinal && flags.answerSettled !== true) {
const code = flags.abortedForTimeout ? "limits.max_walltime_exceeded" : flags.abortedForTurns ? "limits.max_turns_exceeded" : undefined;
terminal = { kind: "failed", ...(code !== undefined ? { code } : {}), message: final?.errorMessage ?? (flags.abortedForTurns ? "max turns exceeded" : "run aborted") };
}
else if (((haltConsumed(flags.haltConsumption) || endingCutConsumed(flags.haltConsumption)) && (!final || cutOwnsAbortedFinal)) || (flags.haltedOnUserRejection === true && !final)) {
terminal = { kind: "completed" };
}
else if (flags.spendStop?.reason === "closed") {
terminal = { kind: "failed", code: SPEND_ACCOUNT_CLOSED_CODE, message: spendStopSentence(flags.spendStop) };
}
else if (!final) {
terminal = { kind: "failed", message: "no assistant message produced" };
}
else if (final.stopReason === "error") {
let message = final.errorMessage ?? "model error";
let code;
const apiError = readMember(final, "isApiErrorMessage") === true;
const apiStatus = readMember(final, "apiErrorStatus");
const apiRequestId = readMember(final, "requestId");
const apiCode = readMember(final, "apiErrorCode");
if (apiError) {
apiFailure = {
...(apiStatus !== undefined ? { status: apiStatus } : {}),
...(typeof apiRequestId === "string" && isProviderEchoShape(apiRequestId) ? { requestId: apiRequestId } : {}),
};
}
let messageNamed = true;
const lifted = extractErrorCode(message);
if (lifted) {
code = lifted;
message = stripErrorCodePrefix(message);
}
else if (flags.coreOverBudget) {
code = "irreducible_core_over_budget";
messageNamed = false;
}
else if (flags.writeRefusal === "conflict") {
code = "conflict";
messageNamed = false;
}
else {
code = "provider.error";
}
const outputInvalid = apiError ? undefined : modelOutputInvalidOfMessage(final);
let detail;
if (messageNamed && apiError && typeof apiStatus === "number" && refusedTheRequest(apiStatus)) {
const route = requestRouteOfMessage(final);
detail = { kind: "provider_rejected", status: apiStatus, ...(typeof apiCode === "string" && isProviderEchoShape(apiCode) ? { code: apiCode } : {}), ...providerVerdictOf(final), ...providerSentenceOf(final), ...(route !== undefined ? { route } : {}), ...refusedPartOf(errorKind, readMember(final, "refusedTool"), readMember(final, "refusedOutputCap")) };
}
else if (messageNamed && outputInvalid !== undefined) {
detail = { kind: "model_output_invalid", ...outputInvalid };
}
terminal = { kind: "failed", code, message, ...(detail !== undefined ? { detail } : {}) };
}
else if (loopExit !== undefined) {
terminal = { kind: "failed", code: loopExit.code, message: loopExit.message };
}
else {
terminal = completedTerminalOf(final);
}
return { terminal, apiFailure };
}
export function assembleResult(leg, final, stats, flags) {
const { taskId, sessionId } = leg;
const text = final ? assistantText(final) : "";
const responseModel = final === undefined ? undefined : providerReportedModel(final);
if (!flags.unpricedSpend) {
const compactionMicroUsd = stats.compactionMicroUsd ?? 0;
const nestedSubagentMicroUsd = stats.nested?.costMicroUsd ?? 0;
stats.costBreakdown = {
llmRootMicroUsd: Math.max(0, stats.costMicroUsd - compactionMicroUsd),
nestedSubagentMicroUsd,
compactionMicroUsd,
...(stats.sideCallMicroUsd !== undefined ? { sideCallMicroUsd: stats.sideCallMicroUsd } : {}),
};
}
const result = flags.displayed !== undefined ? stripThinkTags(flags.displayed.text) : text;
let salvagedOutput;
const { terminal, apiFailure } = terminalCauseOf(final, stats, flags);
const { errorCode } = terminalProjection(terminal);
if (errorCode !== undefined && (SALVAGE_ELIGIBLE_TERMINALS.has(errorCode) || isDeploymentEnvCode(errorCode))) {
salvagedOutput = result.trim() || undefined;
}
const retryAfterMs = errorCode === "usage.window_exhausted" || errorCode === "memory.admission_required" ? flags.retryAfterMs : undefined;
const { compactionMicroUsd: _internalCompaction, sideCallMicroUsd: _internalSideCall, cacheLanes: _internalCacheLanes, ...publicStats } = stats;
void [_internalCompaction, _internalSideCall, _internalCacheLanes];
if (flags.unpricedSpend)
delete publicStats.costMicroUsd;
const stampHaltedByUser = haltConsumed(flags.haltConsumption);
const turnAbortedBy = turnAbortedByOf(flags.haltConsumption);
const records = flags.refusalRecords?.(terminal.kind !== "paused") ?? {};
const { refusedToolCalls, verdictRefused } = records;
return withRewindOutcome({ taskId, ...(flags.runId !== undefined ? { runId: flags.runId } : {}), sessionId, terminal, ...(flags.model !== undefined ? { model: flags.model } : {}), ...(responseModel !== undefined ? { responseModel } : {}), result: result.trim(), ...(flags.answerEntryIds !== undefined ? { resultEntryIds: [...flags.answerEntryIds] } : {}), ...(flags.intake !== undefined ? { intake: flags.intake } : {}), ...(flags.displayed !== undefined && flags.displayed.by.length > 0 ? { resultDisplayedBy: [...flags.displayed.by] } : {}), ...(flags.displayed?.inPart === true ? { resultDisplayedInPart: true } : {}), salvagedOutput, ...(apiFailure !== undefined ? { apiFailure } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}), ...(flags.rewindNotes !== undefined && flags.rewindNotes.length > 0 ? { rewindNotes: flags.rewindNotes } : {}), ...(flags.editedFiles !== undefined && flags.editedFiles.length > 0 ? { editedFiles: flags.editedFiles } : {}), ...(flags.haltedOnUserRejection === true ? { haltedOnUserRejection: true } : {}), ...(stampHaltedByUser ? { haltedByUser: true } : {}), ...(turnAbortedBy !== undefined ? { turnAbortedBy } : {}), ...(terminal.kind === "completed" && flags.limitCrossed !== undefined ? { limitCrossed: flags.limitCrossed } : {}), ...(terminal.kind === "failed" && flags.budgetHit === "precall" && flags.spendStop !== undefined && (terminal.code === "limits.max_tokens_exceeded" || terminal.code === "limits.max_cost_exceeded") ? { limitCrossed: { axis: flags.spendStop.axis === "tokens" ? "budget_tokens" : "budget_cost", limit: flags.spendStop.limit, observed: flags.spendStop.observed, heldBy: flags.spendStop.heldBy } } : {}), ...(flags.remoteEnvFailures !== undefined && flags.remoteEnvFailures.length > 0 ? { remoteEnvFailures: [...flags.remoteEnvFailures] } : {}), ...(flags.refusedAsks !== undefined && flags.refusedAsks.length > 0 ? { refusedAsks: [...flags.refusedAsks] } : {}), ...(refusedToolCalls !== undefined ? { refusedToolCalls } : {}), ...(verdictRefused !== undefined ? { verdictRefused } : {}), ...(flags.strandedHumanAnswers !== undefined && flags.strandedHumanAnswers.length > 0 ? { strandedHumanAnswers: flags.strandedHumanAnswers } : {}), ...resultPostureSeats(flags.posture), ...readDenyFloorSeat(flags.readDenyFloorUnkept), ...(flags.effectiveMemoryScopes !== undefined ? { effectiveMemoryScopes: flags.effectiveMemoryScopes } : {}), ...(flags.placementRoot !== undefined ? { placementRoot: flags.placementRoot } : {}), ...(flags.effectiveReasoning !== undefined ? { effectiveReasoning: flags.effectiveReasoning } : {}), ...(flags.fastMode !== undefined ? { fastMode: flags.fastMode } : {}), ...(flags.compaction !== undefined ? { compaction: flags.compaction } : {}), stats: publicStats }, flags.rewindOutcome);
}
export function resultPostureSeats(p) {
if (p === undefined)
return {};
const configRoots = p.callerPlaces?.configRoots.carried;
const homes = p.callerPlaces?.homes.carried;
return {
...(p.effectiveReadFace !== undefined ? { effectiveReadFace: p.effectiveReadFace } : {}),
...(p.effectiveWriteFace !== undefined ? { effectiveWriteFace: p.effectiveWriteFace } : {}),
...(p.effectiveReadDenyPatterns !== undefined && p.effectiveReadDenyPatterns.length > 0 ? { effectiveReadDenyPatterns: p.effectiveReadDenyPatterns } : {}),
...(configRoots !== undefined && configRoots.length > 0 ? { effectiveAgentConfigDirs: [...configRoots] } : {}),
...(homes !== undefined && homes.length > 0 ? { effectiveAgentHomeDirs: [...homes] } : {}),
...(p.effectiveBlockReadsOutsideRoots === true ? { effectiveBlockReadsOutsideRoots: true } : {}),
...(p.effectiveSandbox !== undefined ? { effectiveSandbox: structuredClone(p.effectiveSandbox) } : {}),
...(p.effectiveExternalContentTarget === true ? { effectiveExternalContentTarget: true } : {}),
};
}