@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
165 lines • 8.99 kB
JavaScript
import { rateLimitModelFamily } from "../../../credential-pool/model-scope.js";
import { inheritAccountContext } from "./account-context.js";
const SDK_ERROR_CLASSIFICATIONS = {
authentication_failed: { kind: "auth_error", retryable: true },
oauth_org_not_allowed: { kind: "org_not_allowed", retryable: true },
billing_error: { kind: "billing", retryable: true },
rate_limit: { kind: "rate_limit", retryable: true },
overloaded: { kind: "overloaded", retryable: true },
invalid_request: { kind: "other", retryable: false },
server_error: { kind: "other", retryable: true },
account_on_hold: { kind: "billing", retryable: true },
model_not_found: { kind: "other", retryable: false },
max_output_tokens: { kind: "other", retryable: false },
};
const OTHER_ERROR = { kind: "other", retryable: false };
// Claude Code's own "You're out of extra usage" prefix (USAGE_LIMIT_ERROR_PREFIXES in the Agent SDK), matched on the raw
// SDK text. It names no window, so only the request's own [1m] flag makes it a long-context refusal (senpi#4065).
const EXTRA_USAGE_EXHAUSTED = /\byou(?:'|\u2019)re out of extra usage\b/;
function record(value) {
return value !== null && typeof value === "object" && !Array.isArray(value)
? value
: undefined;
}
/** `String()` throws for a null-prototype object or a throwing `toString`; the classifiers must never throw. */
function safeString(value) {
try {
return String(value);
}
catch {
return Object.prototype.toString.call(value);
}
}
export function errorText(error) {
if (typeof error === "string")
return error;
const value = record(error);
if (!value)
return safeString(error);
const message = value.message;
if (typeof message === "string")
return message;
if (error instanceof Error)
return safeString(message);
const code = value.error;
if (typeof code === "string")
return code;
return safeString(error);
}
export function isExtraUsageExhausted(error) {
return EXTRA_USAGE_EXHAUSTED.test(errorText(error).toLowerCase());
}
/** A failed SDK result keeps the usage it billed so every lane can account for it. */
export class SdkResultFailure extends Error {
constructor(message, usage) {
super(message);
this.name = "SdkResultFailure";
this.usage = usage;
}
}
/** The usage carried by a failed SDK result, looking through failover's classification wrapper. */
export function sdkResultFailureUsage(error) {
if (error instanceof SdkResultFailure)
return error.usage;
const wrapped = record(error)?.original;
return wrapped instanceof SdkResultFailure ? wrapped.usage : undefined;
}
export function sdkResultFailure(message) {
if (message.subtype === "success" && message.is_error !== true)
return undefined;
const errors = "errors" in message && Array.isArray(message.errors) ? message.errors : [];
const firstError = errors.find((error) => typeof error === "string" && error.length > 0);
const resultText = "result" in message && typeof message.result === "string" ? message.result.trim() : "";
const detail = firstError ??
(message.is_error === true && resultText ? resultText : undefined) ??
`Claude Code ${message.subtype}`;
const status = "api_error_status" in message && message.api_error_status != null ? `HTTP ${message.api_error_status}` : "";
const reason = "terminal_reason" in message && typeof message.terminal_reason === "string" ? message.terminal_reason : "";
const suffix = [status, reason].filter(Boolean).join(", ");
return inheritAccountContext(message, new SdkResultFailure(suffix ? `${detail} (${suffix})` : detail, message.usage));
}
export function sdkAssistantFailure(message) {
if (!message.error)
return undefined;
const content = message.message.content;
const text = (typeof content === "string"
? content
: content
.filter((block) => block.type === "text" && "text" in block && typeof block.text === "string")
.map((block) => ("text" in block && typeof block.text === "string" ? block.text : ""))
.join(" ")).trim();
return inheritAccountContext(message, new Error(text ? (message.error === "unknown" ? text : `${text} (${message.error})`) : message.error));
}
/** Classifies Anthropic Subscription error codes and HTTP-shaped fallback text in one place. */
export function classifySdkError(error, askedLegacyLongContext = false) {
const classification = classifyErrorKind(error, askedLegacyLongContext);
if (classification.kind !== "rate_limit")
return classification;
const modelFamily = rateLimitModelFamily(errorText(error));
return modelFamily === undefined ? classification : { ...classification, modelFamily };
}
function classifyErrorKind(error, askedLegacyLongContext) {
const text = errorText(error).toLowerCase();
// Claude Code reports an account without the 1M window under the rate_limit code. It is a window
// entitlement, not a limit: retry at the standard window instead of blocking the account (senpi#3408).
if (/\b(?:extra usage|usage credits) (?:is|are) required for long context\b/.test(text)) {
return { kind: "long_context_unavailable", retryable: true };
}
// Claude Code's own text when it cannot read a login (no login, or a locked macOS keychain): a fact about this
// process, not a server verdict on the account, so it never becomes a shared auth block (senpi#5630).
if (/\bnot logged in\b/.test(text))
return { kind: "login_unreadable", retryable: true };
if (/\b(enotfound|eai_again|econnreset|econnrefused|etimedout|enetunreach|ehostunreach|und_err_connect_timeout|und_err_socket)\b|fetch failed|socket hang up|connection reset by peer/.test(text)) {
return { kind: "other", retryable: true };
}
for (const [code, classification] of Object.entries(SDK_ERROR_CLASSIFICATIONS)) {
if (new RegExp(`\\b${code}\\b`).test(text))
return classification ?? OTHER_ERROR;
}
if (askedLegacyLongContext && isExtraUsageExhausted(error)) {
return { kind: "long_context_unavailable", retryable: true };
}
if (/\b(?:http\s*)?429\b|too many requests|rate[ _-]?limit/.test(text)) {
return { kind: "rate_limit", retryable: true };
}
// Claude Code signals subscription exhaustion two ways, neither of which
// carries an SDK error code or HTTP status:
// - `terminal_reason: "blocking_limit"` / `"rapid_refill_breaker"` on a
// result message (surfaced by auth-lane's sdkFailure)
// - prose in `errors[0]`, e.g. "You've hit your weekly limit · resets 5am
// (Asia/Seoul)" and the 5-hour/daily equivalents
// Without these branches both classify as non-retryable "other", so the
// exhausted account is never blocked and a pool never rotates past it.
if (/\bblocking_limit\b|\brapid_refill_breaker\b/.test(text)) {
return { kind: "rate_limit", retryable: true };
}
if (/\b(?:hit|reached|exceeded)\b[^.]*\blimit\b|\b(?:weekly|daily|hourly|usage)\s+limit\b/.test(text)) {
return { kind: "rate_limit", retryable: true };
}
if (/\b(?:http\s*)?529\b|overloaded/.test(text))
return { kind: "overloaded", retryable: true };
// A server, gateway or timeout status is the provider's fault even when its body echoes "unauthorized":
// only a 401 is a rejected token, so this must not become an auth block (senpi#2081).
if (/\bhttp\s*(?:408|5\d\d)\b/.test(text))
return { kind: "other", retryable: true };
// Claude Code's own refresh was refused: it reports this as a successful-subtype result with is_error, no HTTP
// status and terminal_reason api_error, so only the text identifies it, and `claude auth status` still says
// signed in. The login is gone; only a new sign-in brings the account back (senpi#5350).
if (/\boauth session expired and could not be refreshed\b/.test(text)) {
return { kind: "auth_error", retryable: true, signInRequired: "login_expired" };
}
if (/\binvalid_grant\b|\binvalid_token\b|\b(?:http\s*)?401\b|\bunauthorized\b/.test(text)) {
return { kind: "auth_error", retryable: true };
}
// Fable 5 and similar models are not in the subscription; Claude Code asks
// for usage credits. That is an account entitlement, not a 60s rate limit:
// blocking the only account would also block Opus fallback on it.
if (/\brequires usage credits\b|\/usage-credits\b|\bcredits_required\b/.test(text)) {
return { kind: "entitlement", retryable: false };
}
// A standard-window request was refused by billing itself: no 200k retry, Claude's reason kept as written.
if (EXTRA_USAGE_EXHAUSTED.test(text))
return { kind: "billing", retryable: false };
return OTHER_ERROR;
}
//# sourceMappingURL=errors.js.map