UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

432 lines (431 loc) • 16.9 kB
import { isErrorLike, readMember, thrownText } from "../core/thrown-value.js"; import { outputCapReportOf } from "../core/terminal-cause.js"; import { contextOverflowReportOf } from "./context-overflow.js"; import { emitBrainTelemetry } from "./status-sink.js"; import { isProviderEchoShape } from "./provider-echo-shape.js"; export const ZERO_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, }; const BRAIN_ERROR_CODES = ["auth", "rate_limit", "invalid_request", "server", "network", "http", "stream_torn", "refusal", "length_empty"]; export const ALL_BRAIN_ERROR_CODES = BRAIN_ERROR_CODES; export const IN_BAND_OUTPUT_CODES = new Set(["stream_torn", "refusal", "length_empty"]); export class BrainError extends Error { code; status; inputTooLong; inputTooLongRuledOut; apiError; providerCode; providerCondition; providerConditionSource; providerResetAtMs; providerMessage; errorBodyIncomplete; imageUnprocessable; toolSchemaRefused; outputCapTooLarge; mediaItemsRefused; contextOverflow; constructor(code, detail, status, opts) { super(`[${code}] ${detail}`); this.name = "BrainError"; this.code = code; this.status = status; if (opts?.inputTooLong === true) this.inputTooLong = true; else if (opts?.inputTooLongRuledOut === true) this.inputTooLongRuledOut = true; if (opts?.apiError === true) this.apiError = true; if (opts?.providerCode !== undefined) this.providerCode = opts.providerCode; if (opts?.verdict !== undefined) { this.providerCondition = opts.verdict.condition; this.providerConditionSource = opts.verdict.source; if (opts.verdict.resetAtMs !== undefined) this.providerResetAtMs = opts.verdict.resetAtMs; } if (typeof opts?.providerMessage === "string") this.providerMessage = opts.providerMessage; if (opts?.errorBodyIncomplete === true) this.errorBodyIncomplete = true; if (opts?.imageUnprocessable === true) this.imageUnprocessable = true; if (typeof opts?.toolSchemaRefused === "string") this.toolSchemaRefused = opts.toolSchemaRefused; const outputCap = opts?.outputCapTooLarge === true ? true : outputCapReportOf(opts?.outputCapTooLarge); if (outputCap !== undefined) this.outputCapTooLarge = outputCap; if (opts?.mediaItemsRefused === true) this.mediaItemsRefused = true; const overflow = contextOverflowReportOf(opts?.contextOverflow); if (overflow !== undefined) this.contextOverflow = overflow; } } export function providerErrorObject(body) { const trimmed = body.trim(); if (!trimmed.startsWith("{")) return undefined; let parsed; try { parsed = JSON.parse(trimmed); } catch { return undefined; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; const err = parsed.error; if (typeof err !== "object" || err === null || Array.isArray(err)) return undefined; return err; } export function providerErrorWord(err) { return typeof err?.code === "string" ? err.code : typeof err?.type === "string" ? err.type : undefined; } export function readProviderErrorCode(body) { return carriedProviderWord(statedEnvelope(body)); } export function statedEnvelope(body) { return body !== undefined && body.endedNormally ? providerErrorObject(body.text) : undefined; } export function statedSentence(body) { const sentence = statedEnvelope(body)?.message; if (body === undefined || typeof sentence !== "string") return undefined; const literal = envelopeMessageLiteral(body.text); const units = literal === undefined ? undefined : literalUnits(body.text, literal); return units !== undefined && units.text === sentence ? { sentence, written: { from: units.from, to: units.to } } : { sentence }; } const isJsonSpace = (c) => c === " " || c === "\t" || c === "\n" || c === "\r"; const skipJsonSpace = (t, i) => { while (isJsonSpace(t[i])) i++; return i; }; function jsonStringEnd(t, i) { for (let j = i + 1; j < t.length; j++) { if (t[j] === "\\") j++; else if (t[j] === '"') return j + 1; } return -1; } function jsonValueEnd(t, i) { const c = t[i]; if (c === '"') return jsonStringEnd(t, i); if (c !== "{" && c !== "[") { let j = i; while (j < t.length && !isJsonSpace(t[j]) && t[j] !== "," && t[j] !== "}" && t[j] !== "]") j++; return j > i ? j : -1; } let depth = 0; for (let j = i; j < t.length; j++) { const d = t[j]; if (d === '"') { const end = jsonStringEnd(t, j); if (end < 0) return -1; j = end - 1; } else if (d === "{" || d === "[") depth++; else if ((d === "}" || d === "]") && --depth === 0) return j + 1; } return -1; } function jsonMembers(t, i) { const members = []; let j = skipJsonSpace(t, i + 1); if (t[j] === "}") return members; for (;;) { if (t[j] !== '"') return undefined; const nameEnd = jsonStringEnd(t, j); if (nameEnd < 0) return undefined; const name = literalUnits(t, { start: j, end: nameEnd })?.text; j = skipJsonSpace(t, nameEnd); if (name === undefined || t[j] !== ":") return undefined; const start = skipJsonSpace(t, j + 1); const end = jsonValueEnd(t, start); if (end < 0) return undefined; members.push({ name, start, end }); j = skipJsonSpace(t, end); if (t[j] === "}") return members; if (t[j] !== ",") return undefined; j = skipJsonSpace(t, j + 1); } } const lastMember = (members, name) => members?.filter((m) => m.name === name).pop(); function envelopeMessageLiteral(text) { const at = text.length - text.trimStart().length; if (text[at] !== "{") return undefined; const error = lastMember(jsonMembers(text, at), "error"); if (error === undefined || text[error.start] !== "{") return undefined; const message = lastMember(jsonMembers(text, error.start), "message"); return message !== undefined && text[message.start] === '"' ? message : undefined; } const JSON_SHORT_ESCAPES = Object.freeze({ '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" }); function literalUnits(t, literal) { const from = []; const to = []; let text = ""; for (let i = literal.start + 1; i < literal.end - 1;) { if (t[i] !== "\\") { text += t[i]; from.push(i); to.push(i + 1); i += 1; continue; } const escape = t[i + 1] ?? ""; const hex = t.slice(i + 2, i + 6); const unit = escape === "u" && /^[0-9A-Fa-f]{4}$/.test(hex) ? String.fromCharCode(parseInt(hex, 16)) : JSON_SHORT_ESCAPES[escape]; if (unit === undefined) return undefined; const width = escape === "u" ? 6 : 2; text += unit; from.push(i); to.push(i + width); i += width; } return { text, from: Int32Array.from(from), to: Int32Array.from(to) }; } export function carriedProviderWord(err) { const word = providerErrorWord(err); const reading = providerEchoReading(word); if (reading === "carried") return word; if (reading === "refused") emitBrainTelemetry({ kind: "echo_dropped", field: "apiErrorCode" }); return undefined; } const REQUEST_ID_HEADERS = ["request-id", "x-request-id"]; export { isProviderEchoShape, PROVIDER_ECHO_SHAPE } from "./provider-echo-shape.js"; export function providerEchoReading(value) { if (typeof value !== "string" || value.length === 0) return "absent"; return isProviderEchoShape(value) ? "carried" : "refused"; } export function readProviderRequestId(res) { let refused = false; try { const get = res?.headers?.get; if (typeof get !== "function") return undefined; for (const name of REQUEST_ID_HEADERS) { const raw = get.call(res.headers, name); const reading = providerEchoReading(raw); if (reading === "carried") return raw; if (reading === "refused") refused = true; } } catch { } if (refused) emitBrainTelemetry({ kind: "echo_dropped", field: "requestId" }); return undefined; } export function namesTheFailure(status) { return status !== undefined && status >= 100 && !(status >= 200 && status < 300); } export function refusedTheRequest(status) { return status !== undefined && status >= 400 && status < 500; } export function classifyHttp(status) { if (status === 401 || status === 403) return "auth"; if (status === 429) return "rate_limit"; if (status === 400 || status === 422) return "invalid_request"; if (status === 408 || status === 409) return "server"; if (status >= 500) return "server"; return "http"; } const CODE_ALTERNATION = BRAIN_ERROR_CODES.join("|"); const CODE_RE = new RegExp(`^\\[(${CODE_ALTERNATION})\\]`); const CODE_PREFIX_RE = new RegExp(`^\\[(?:${CODE_ALTERNATION})\\]\\s*`); export function extractErrorCode(errorMessage) { const m = errorMessage ? CODE_RE.exec(errorMessage) : null; return m ? m[1] : undefined; } export function stripErrorCodePrefix(errorMessage) { return errorMessage.replace(CODE_PREFIX_RE, ""); } const STALE_CONNECTION_CODES = new Set([ "ECONNRESET", "EPIPE", "ConnectionClosed", "ETIMEDOUT", "ECONNABORTED", "ERR_SOCKET_CLOSED", "StreamSuspended", ]); function hasStaleConnectionCode(e) { let cur = e; for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) { const code = readMember(cur, "code"); if (typeof code === "string" && STALE_CONNECTION_CODES.has(code)) return true; cur = isErrorLike(cur) ? readMember(cur, "cause") : undefined; } return false; } export const PROXY_TUNNEL_REFUSED = "ERR_PROXY_TUNNEL_REFUSED"; const DETERMINISTIC_CONNECT_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", PROXY_TUNNEL_REFUSED]); const CONNECT_GRAPH_NODE_BUDGET = 16; function proxyStatusOf(node) { const status = readMember(node, "statusCode"); return typeof status === "number" && Number.isInteger(status) && status < 600 && namesTheFailure(status) ? status : undefined; } function walkConnectFailure(node, budget) { if (budget.left <= 0) return "indeterminate"; budget.left--; if (node === undefined || node === null) return "silent"; let verdict = "silent"; const code = readMember(node, "code"); if (typeof code === "string") { if (!DETERMINISTIC_CONNECT_CODES.has(code)) return "indeterminate"; if (code === PROXY_TUNNEL_REFUSED && budget.proxy === undefined) budget.proxy = { status: proxyStatusOf(node) }; verdict = "deterministic"; } if (!isErrorLike(node)) return verdict; const members = readMember(node, "errors"); const legCount = readMember(members, "length"); if (members !== undefined) { if (typeof legCount !== "number" || !Number.isInteger(legCount) || legCount <= 0) return "indeterminate"; for (let i = 0; i < legCount; i++) { if (walkConnectFailure(readMember(members, String(i)), budget) !== "deterministic") return "indeterminate"; } verdict = "deterministic"; } const cause = readMember(node, "cause"); if (cause !== undefined && cause !== null) { const below = walkConnectFailure(cause, budget); if (below === "indeterminate") return "indeterminate"; if (below === "deterministic") verdict = "deterministic"; } return verdict; } export function readConnectFailure(e) { const walk = { left: CONNECT_GRAPH_NODE_BUDGET }; if (walkConnectFailure(e, walk) !== "deterministic") return { verdict: "indeterminate" }; return walk.proxy === undefined ? { verdict: "deterministic" } : { verdict: "deterministic", proxyRefusal: walk.proxy }; } export function classifyConnectFailure(e) { return readConnectFailure(e).verdict; } const PROXY_TUNNEL_REFUSED_SENTENCES = new Map([ [407, "proxy authentication required (HTTP 407)"], [403, "proxy forbids this destination (HTTP 403)"], ]); export function proxyTunnelRefusedSentence(status) { if (status === undefined) return "proxy refused the tunnel"; return PROXY_TUNNEL_REFUSED_SENTENCES.get(status) ?? `proxy refused the tunnel (HTTP ${status})`; } const FETCH_TRANSPORT_SHELLS = new Set(["fetch failed", "terminated"]); const REQUEST_ARGUMENT_CODES = new Set(["ERR_INVALID_URL"]); export function classifyFetchThrow(e) { if (readMember(e, "name") !== "TypeError") return "transport"; const message = readMember(e, "message"); if (typeof message === "string" && FETCH_TRANSPORT_SHELLS.has(message)) return "transport"; if (classifyConnectFailure(e) === "deterministic") return "transport"; const cause = readMember(e, "cause"); if (cause === undefined || cause === null) return "request_unbuildable"; const code = readMember(cause, "code"); return typeof code === "string" && REQUEST_ARGUMENT_CODES.has(code) ? "request_unbuildable" : "transport"; } export function abortLikeName(err) { if (!isErrorLike(err)) return undefined; const name = readMember(err, "name"); return name === "AbortError" || name === "TimeoutError" ? name : undefined; } export function brainErrorCodeOf(e) { const code = readMember(e, "code"); return typeof code === "string" && BRAIN_ERROR_CODES.includes(code) ? code : undefined; } export function codedAbortOf(signal) { if (signal === undefined || signal.aborted !== true) return undefined; return brainErrorCodeOf(signal.reason); } export function thrownBrainFailure(e) { const code = brainErrorCodeOf(e); if (code === undefined) return {}; if (readMember(e, "inputTooLong") === true) { const contextOverflow = contextOverflowReportOf(readMember(e, "contextOverflow")); return { code, errorKind: "input_too_long", ...(contextOverflow !== undefined ? { contextOverflow } : {}) }; } const ruledOut = readMember(e, "inputTooLongRuledOut") === true; if (readMember(e, "imageUnprocessable") === true) return { code, errorKind: "image_unprocessable", ...(ruledOut ? { inputTooLongRuledOut: true } : {}) }; const refusedTool = readMember(e, "toolSchemaRefused"); if (typeof refusedTool === "string") return { code, errorKind: "tool_schema_refused", refusedTool, ...(ruledOut ? { inputTooLongRuledOut: true } : {}) }; const outputCap = readMember(e, "outputCapTooLarge"); const refusedOutputCap = outputCapReportOf(outputCap); if (outputCap === true || refusedOutputCap !== undefined) { return { code, errorKind: "output_cap_too_large", ...(refusedOutputCap !== undefined ? { refusedOutputCap } : {}), ...(ruledOut ? { inputTooLongRuledOut: true } : {}) }; } if (readMember(e, "mediaItemsRefused") === true) return { code, errorKind: "media_items_refused", ...(ruledOut ? { inputTooLongRuledOut: true } : {}) }; if (ruledOut) return { code, inputTooLongRuledOut: true }; return { code }; } export function describeNetworkError(e) { const top = thrownText(e); const parts = []; let cur = isErrorLike(e) ? readMember(e, "cause") : undefined; for (let depth = 0; depth < 4 && cur !== undefined && cur !== null; depth++) { const rawCode = readMember(cur, "code"); const code = typeof rawCode === "string" ? rawCode : undefined; const msg = thrownText(cur); const piece = code !== undefined && !msg.includes(code) ? `${code}: ${msg}` : msg; if (piece.length > 0 && piece !== top && !parts.includes(piece)) parts.push(piece); cur = isErrorLike(cur) ? readMember(cur, "cause") : undefined; } const body = parts.length > 0 ? `${top} (${parts.join(" ← ")})` : top; return hasStaleConnectionCode(e) ? `${body} — possibly a stale connection; a fresh one may succeed` : body; }