UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

131 lines (130 loc) • 7 kB
import { sameModelNamed } from "./claude-model-id.js"; import { statedEnvelope } from "./errors.js"; import { capabilityOf, capabilityTried } from "./model-capability.js"; import { routeKeyOf } from "./route-adjudicator.js"; import { reportCapabilityWithheld } from "./status-sink.js"; export const FAST_MODE_STATES = Object.freeze(["off", "cooldown", "on"]); export const FAST_MODE_UNAVAILABLE_REASONS = Object.freeze(["not_first_party", "model_not_allowed", "unknown", "preference", "extra_usage_disabled"]); export const FAST_MODE_COOLDOWN_REASONS = Object.freeze(["rate_limit", "overloaded"]); export const FAST_MODE_OVERAGE_CAUSES = Object.freeze(["out_of_credits", "org_level_disabled_until", "org_spend_cap_reached"]); export const FAST_MODE_BETA = "fast-mode-2026-02-01"; const FAST_MODE_WIRE = Object.freeze({ "anthropic-messages": Object.freeze({ bodyKey: "speed", value: "fast", beta: FAST_MODE_BETA }), }); export function fastSpeedKeyOf(api) { return FAST_MODE_WIRE[api]?.bodyKey; } export function fastModeRouteOf(model) { return routeKeyOf(model.baseUrl); } export function fastModeUnavailableFor(model) { if (FAST_MODE_WIRE[model.api] === undefined) return "not_first_party"; if (capabilityTried(model, "fast_mode")) return undefined; return capabilityOf(model, "fast_mode") === "declared_off" ? "model_not_allowed" : "unknown"; } export function fastModeReadingOf(args) { const reason = fastModeUnavailableFor(args.model) ?? args.refused; if (!args.requested || reason !== undefined) return reason !== undefined ? { state: "off", reason } : { state: "off" }; const cooldown = args.cooldown; if (cooldown !== undefined && cooldown.until > (args.now ?? Date.now())) return { state: "cooldown", cooldown: { until: cooldown.until, reason: cooldown.reason } }; return { state: "on" }; } export function observeFastMode(call, observation) { try { call?.observe(observation); } catch { } } export function requestSpeedOf(args) { const { model, call } = args; return call !== undefined && call.requested && !args.standardSpeed && fastModeUnavailableFor(model) === undefined && call.refusedFor(fastModeRouteOf(model), model.id) === undefined ? "fast" : "standard"; } export function applyFastModeToRequest(args) { const { model, call, body } = args; if (call === undefined) return { body, fastSpeed: false }; const entry = fastModeUnavailableFor(model); const spelling = FAST_MODE_WIRE[model.api]; if (entry !== undefined || spelling === undefined) { if (call.requested && entry !== undefined) reportCapabilityWithheld({ modelId: model.id, capability: "fast_mode", cause: entry, count: 1 }); return { body, fastSpeed: false }; } const route = fastModeRouteOf(model); const fastSpeed = args.speed === "fast"; return { body: fastSpeed ? { ...body, [spelling.bodyKey]: spelling.value } : body, ...((fastSpeed || call.betaLatchedOn(route)) && args.withoutBeta !== true ? { headers: { "anthropic-beta": spelling.beta } } : {}), fastSpeed, }; } export const FAST_MODE_SHORT_WAIT_MS = 20_000; export const FAST_MODE_MIN_COOLDOWN_MS = 600_000; export const FAST_MODE_DEFAULT_COOLDOWN_MS = 1_800_000; const OVERAGE_DISABLED_HEADER = "anthropic-ratelimit-unified-overage-disabled-reason"; function retryAfterSecondsMs(headers) { const raw = headers?.get("retry-after"); if (raw === null || raw === undefined) return undefined; const secs = Number.parseInt(raw, 10); return Number.isNaN(secs) ? undefined : secs * 1000; } const BETA_REFUSAL_SENTENCE = /Unexpected value\(s\) ((?:`[^`]+`(?:, )?)+) for the `anthropic[-_]beta`/; const BETA_REFUSAL_TOKEN = new RegExp(`capability_rejected: beta_header:${FAST_MODE_BETA}(?![\\w:.-])`); export function fastModeBetaRefused(status, body) { const text = body?.text ?? ""; if (BETA_REFUSAL_TOKEN.test(text)) return true; const namesTheBeta = (sentence) => sentence?.[1]?.includes(`\`${FAST_MODE_BETA}\``) === true; const stated = statedEnvelope(body)?.message; const opening = (typeof stated === "string" ? stated : text).split("\n", 1)[0] ?? ""; const opened = BETA_REFUSAL_SENTENCE.exec(opening); return (opened?.index === 0 && namesTheBeta(opened)) || (status === 400 && namesTheBeta(BETA_REFUSAL_SENTENCE.exec(text))); } function overloadedStated(status, body) { return status === 529 || statedEnvelope(body)?.type === "overloaded_error"; } export function fastModeServerError(status, body) { return status >= 500 && status < 600 && !overloadedStated(status, body); } export function fastModeFallbackOf(input) { const { status, headers, route, modelId } = input; const text = input.body?.text ?? ""; const overloaded = overloadedStated(status, input.body); const serverError = fastModeServerError(status, input.body); const waitMs = retryAfterSecondsMs(headers); const shortWait = waitMs !== undefined && waitMs < FAST_MODE_SHORT_WAIT_MS; const shouldNotRetry = headers?.get("x-should-retry") === "false"; const ruleApplies = status === 429 || overloaded || (serverError && (input.serverErrors > 1 || !input.retriesLeft || shouldNotRetry || (waitMs !== undefined && !shortWait))); if (ruleApplies) { if (!serverError) { const overage = headers?.get(OVERAGE_DISABLED_HEADER); if (overage !== null && overage !== undefined) { const cause = FAST_MODE_OVERAGE_CAUSES.find((word) => word === overage); return { kind: "standard", observation: cause !== undefined ? { kind: "overage", modelId, cause } : { kind: "refused", route, modelId, reason: "extra_usage_disabled" } }; } if (shortWait && input.retriesLeft && input.shortWaitSpentMs + input.retryWaitMs < FAST_MODE_SHORT_WAIT_MS) return { kind: "keep", shortWaitMs: input.retryWaitMs }; } if (!serverError || input.serverErrors > 1) { const ms = Math.max(waitMs ?? (serverError ? FAST_MODE_MIN_COOLDOWN_MS : FAST_MODE_DEFAULT_COOLDOWN_MS), FAST_MODE_MIN_COOLDOWN_MS); return { kind: "standard", observation: { kind: "cooldown", modelId, until: input.now + ms, reason: serverError || overloaded ? "overloaded" : "rate_limit" } }; } return { kind: "standard" }; } if (status !== 400) return { kind: "keep" }; const named = /'([^']+)' does not support the `speed` parameter/.exec(text)?.[1]; const reason = text.includes("Fast mode is not enabled") ? "preference" : named !== undefined && sameModelNamed(named, modelId) ? "model_not_allowed" : undefined; if (reason === undefined) return { kind: "keep" }; const observation = { kind: "refused", route, modelId, reason }; return input.retriesLeft ? { kind: "standard", observation, counted: true } : { kind: "end", observation }; }