@sema-agent/core
Version:
Stateless, task-oriented AI agent core
287 lines (286 loc) • 13 kB
JavaScript
import { MODEL_OUTPUT_INVALID_CAUSES } from "../../internal/llm.js";
import { isProviderEchoShape } from "../../brain/errors.js";
import { admittedProviderMessage } from "../../brain/provider-message.js";
import { isProviderCondition, isProviderConditionSource } from "../../brain/provider-dialect.js";
import { admittedRequestRoute } from "../../brain/request-route.js";
import { outputCapReportOf, REFUSED_REQUEST_PARTS } from "../terminal-cause.js";
import { readMember, thrownText } from "../thrown-value.js";
import { egressText } from "../untrusted-egress.js";
import { isSensitiveName, looksLikeCredentialValue } from "../secret-env.js";
import { isSensitiveRecordKey, REDACTION_MARKS } from "@sema-agent/primitives";
import { configInputOfRefusal, isConfigRefusalCode } from "../config-refusal-input.js";
const CREDENTIAL_LEAF = REDACTION_MARKS.bare;
const LOOP_EXIT_FAILURE = {
completed: undefined,
aborted_before_stream: undefined,
assistant_error: undefined,
stop_requested: undefined,
malformed_tool_use_exhausted: {
code: "model.malformed_tool_use_exhausted",
message: "The model's tool call could not be run because it kept arriving unreadable or naming the same missing tool, and the engine's automatic retries also failed. Try your request again or rephrase it, switch to another model, or contact your operator if that tool should be available.",
},
truncated_output_exhausted: {
code: "model.truncated_output_exhausted",
message: "The model's response kept hitting the output length limit, and the engine's automatic attempts to continue it also hit the limit. Ask for a shorter answer or break the request into smaller parts, switch to a model with a higher output limit, or try again later.",
},
};
export function loopExitFailureOf(reason) {
return reason !== undefined && Object.hasOwn(LOOP_EXIT_FAILURE, reason) ? LOOP_EXIT_FAILURE[reason] : undefined;
}
export function providerVerdictOf(final) {
const condition = readMember(final, "providerCondition");
const source = readMember(final, "providerConditionSource");
if (!isProviderCondition(condition) || !isProviderConditionSource(source))
return {};
const resetAtMs = readMember(final, "providerResetAtMs");
return { providerCondition: condition, providerConditionSource: source, ...(typeof resetAtMs === "number" && Number.isFinite(resetAtMs) ? { providerResetAtMs: resetAtMs } : {}) };
}
export function providerSentenceOf(final) {
const sentence = admittedProviderMessage(readMember(final, "providerMessage"));
return sentence === undefined ? {} : { providerMessage: sentence };
}
const REFUSED_REQUEST_PART_SET = new Set(REFUSED_REQUEST_PARTS);
export function refusedPartOf(errorKind, refusedTool, refusedOutputCap) {
if (!REFUSED_REQUEST_PART_SET.has(errorKind))
return {};
if (errorKind === "output_cap_too_large") {
const outputCap = outputCapReportOf(refusedOutputCap);
return outputCap !== undefined ? { errorKind, outputCap } : { errorKind };
}
if (errorKind !== "tool_schema_refused")
return { errorKind: errorKind };
return typeof refusedTool === "string" && refusedTool.length > 0 ? { errorKind, tool: refusedTool } : {};
}
export function requestRouteOfMessage(final) {
return admittedRequestRoute(readMember(final, "apiErrorRoute"));
}
const MODEL_OUTPUT_INVALID_CAUSE_SET = new Set(MODEL_OUTPUT_INVALID_CAUSES);
const countOf = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : undefined);
export function modelOutputInvalidOfMessage(final) {
const account = readMember(final, "modelOutputInvalid");
const cause = readMember(account, "cause");
if (!MODEL_OUTPUT_INVALID_CAUSE_SET.has(cause))
return undefined;
const limit = cause === "truncated" ? readMember(account, "outputLimit") : undefined;
const capStop = readMember(limit, "capStop");
if (typeof capStop !== "boolean")
return { cause: cause };
const outputTokens = countOf(readMember(limit, "outputTokens"));
const capTokens = countOf(readMember(limit, "capTokens"));
const outputLimit = { capStop, ...(outputTokens !== undefined ? { outputTokens } : {}), ...(capTokens !== undefined ? { capTokens } : {}) };
return { cause: cause, outputLimit };
}
const CODED_DETAIL_DEPTH = 4;
const CODED_DETAIL_ENTRIES = 64;
const CODED_DETAIL_STRING = 4_096;
const CODED_DETAIL_VALUES = 256;
const CODED_DETAIL_CHARS = 16_384;
const INDEX_KEY_RE = /^(?:0|[1-9][0-9]*)$/;
function carriesCredential(text) {
return looksLikeCredentialValue(text) || egressText("same-principal", text) !== text;
}
export function codedDetailStringOf(text) {
if (text.length > CODED_DETAIL_STRING)
return undefined;
return carriesCredential(text) ? CREDENTIAL_LEAF : text;
}
const NAME_CHARS = 128;
function namesCredential(name) {
return name.length <= NAME_CHARS && (isSensitiveName(name) || isSensitiveRecordKey(name));
}
const NAME_POSITION_KEYS = new Set(["name", "key", "header", "field"]);
const VALUE_POSITION_KEYS = new Set(["value", "val"]);
function charge(budget, chars) {
if (budget.values >= CODED_DETAIL_VALUES || budget.chars + chars > CODED_DETAIL_CHARS) {
budget.cuts++;
return false;
}
budget.values++;
budget.chars += chars;
return true;
}
function leafOf(keyContext, read, depth, budget) {
if (keyContext !== undefined && namesCredential(keyContext))
return charge(budget, CREDENTIAL_LEAF.length) ? CREDENTIAL_LEAF : undefined;
const value = read();
if (value === null || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))
return charge(budget, 0) ? value : undefined;
if (typeof value === "string") {
const shown = codedDetailStringOf(value);
if (shown === undefined) {
budget.cuts++;
return undefined;
}
return charge(budget, shown.length) ? shown : undefined;
}
if (typeof value !== "object")
return undefined;
if (depth >= CODED_DETAIL_DEPTH) {
budget.cuts++;
return undefined;
}
let isArray;
try {
if (ArrayBuffer.isView(value))
return undefined;
isArray = Array.isArray(value);
}
catch {
return undefined;
}
if (!isArray)
return recordOf(value, depth, budget);
const length = readMember(value, "length");
if (typeof length !== "number" || !Number.isInteger(length) || length < 0)
return undefined;
if (length > CODED_DETAIL_ENTRIES) {
budget.cuts++;
return undefined;
}
const entered = { values: budget.values, chars: budget.chars, cuts: budget.cuts };
if (!charge(budget, 0))
return undefined;
const items = [];
const dropped = () => {
const cutIn = budget.cuts > entered.cuts;
budget.values = entered.values;
budget.chars = entered.chars;
budget.cuts = entered.cuts + (cutIn ? 1 : 0);
return undefined;
};
const handed = Array.from({ length }, (_, i) => readMember(value, String(i)));
for (let i = 0; i < length; i++) {
const before = handed[i - 1];
const item = leafOf(typeof before === "string" && namesCredential(before) ? before : keyContext, () => handed[i], depth + 1, budget);
if (item === undefined || budget.cuts > entered.cuts)
return dropped();
items.push(item);
}
return items;
}
function pairedNameOf(value, keys, read) {
if (!keys.some((k) => VALUE_POSITION_KEYS.has(k.toLowerCase())))
return undefined;
let named;
for (const key of keys) {
if (!NAME_POSITION_KEYS.has(key.toLowerCase()))
continue;
const name = readMember(value, key);
read.set(key, name);
if (named === undefined && typeof name === "string" && namesCredential(name))
named = name;
}
return named;
}
function recordOf(value, depth, budget, reserved, cutKeys) {
let keys;
try {
keys = Object.keys(value).filter((k) => k !== reserved);
}
catch {
return undefined;
}
const nameable = (key) => isProviderEchoShape(key) && !carriesCredential(key);
if (keys.length > CODED_DETAIL_ENTRIES) {
budget.cuts++;
cutKeys?.push(...keys.filter(nameable));
return undefined;
}
if ((keys.length > 0 && keys.every((k) => INDEX_KEY_RE.test(k))) || !charge(budget, 0))
return undefined;
const nameMembers = new Map();
const paired = pairedNameOf(value, keys, nameMembers);
const out = {};
for (const key of keys) {
if (!nameable(key))
continue;
const cutsBefore = budget.cuts;
if (budget.chars + key.length > CODED_DETAIL_CHARS) {
budget.cuts++;
cutKeys?.push(key);
continue;
}
const charsBefore = budget.chars;
budget.chars += key.length;
const context = paired !== undefined && VALUE_POSITION_KEYS.has(key.toLowerCase()) ? paired : key;
const admitted = leafOf(context, () => (nameMembers.has(key) ? nameMembers.get(key) : readMember(value, key)), depth + 1, budget);
if (admitted === undefined)
budget.chars = charsBefore;
else
Object.defineProperty(out, key, { value: admitted, enumerable: true, writable: true, configurable: true });
if (budget.cuts > cutsBefore)
cutKeys?.push(key);
}
return Object.keys(out).length > 0 ? out : undefined;
}
const INPUT_MEMBER = "input";
function detailRecordOf(detail, reserved) {
try {
if (detail === null || typeof detail !== "object" || Array.isArray(detail) || ArrayBuffer.isView(detail))
return { detail: undefined, omitted: [] };
}
catch {
return { detail: undefined, omitted: [] };
}
const omitted = [];
return { detail: recordOf(detail, 0, { values: 0, chars: 0, cuts: 0 }, reserved, omitted), omitted };
}
function codedFailureDetailOf(code, link) {
const family = isConfigRefusalCode(code);
const input = family ? configInputOfRefusal(link) : undefined;
const { detail, omitted: cutNames } = detailRecordOf(readMember(link, "detail"), family ? INPUT_MEMBER : undefined);
const omitted = cutNames.slice(0, CODED_DETAIL_ENTRIES);
const cut = omitted.length > 0 ? { omitted, ...(cutNames.length > omitted.length ? { omittedMore: cutNames.length - omitted.length } : {}) } : {};
if (input === undefined)
return detail === undefined && omitted.length === 0 ? undefined : { kind: "coded", detail: detail ?? {}, ...cut };
return { kind: "coded", detail: { [INPUT_MEMBER]: input, ...detail }, ...cut };
}
export function errorCodeOf(err) {
return codedLinkOf(err)?.code;
}
function codedLinkOf(err) {
let cur = err;
let fallback;
for (let depth = 0; cur !== null && cur !== undefined && typeof cur === "object" && depth < 8; depth++) {
const code = readMember(cur, "code");
if (typeof code === "string" && code) {
if (code !== "unknown") {
return { code, link: cur };
}
fallback ??= { code, link: cur };
}
cur = readMember(cur, "cause");
}
return fallback;
}
export function thrownFailureOf(err, text) {
const message = egressText("same-principal", text);
const coded = codedLinkOf(err);
if (coded === undefined)
return { message };
const detail = codedFailureDetailOf(coded.code, coded.link);
return { code: coded.code, message, ...(detail !== undefined ? { detail } : {}) };
}
export function failedPreRunResult(err, spec) {
const { code, message, detail } = thrownFailureOf(err, thrownText(err));
const specTaskId = readMember(spec, "taskId");
const specSessionId = readMember(spec, "sessionId");
return {
taskId: typeof specTaskId === "string" && specTaskId.length > 0 ? specTaskId : "unknown",
sessionId: typeof specSessionId === "string" && specSessionId.length > 0 ? specSessionId : "unknown",
terminal: { kind: "failed", ...(code !== undefined ? { code } : {}), message, ...(detail !== undefined ? { detail } : {}) },
result: "",
resultEntryIds: [],
intake: { committed: false },
continuesFrom: { none: "unsettled" },
stats: { turns: 0, tokens: 0, toolCalls: 0, cachedTokens: 0, costMicroUsd: 0, usageMissing: true },
};
}
export function completedTerminalOf(final) {
const finishReasonUnknown = readMember(final, "finishReasonUnknown");
if (typeof finishReasonUnknown === "string" && isProviderEchoShape(finishReasonUnknown))
return { kind: "completed", detail: { kind: "finish_reason_unknown", finishReasonUnknown } };
if (readMember(final, "partialFinalized") === true)
return { kind: "completed", detail: { kind: "response_cut" } };
return { kind: "completed" };
}