426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
193 lines
6.3 KiB
TypeScript
193 lines
6.3 KiB
TypeScript
/**
|
|
* Retry and error-formatting helpers shared by the model handlers.
|
|
* `executeWithRetry` wraps a call with exponential backoff on transient
|
|
* failures; `formatModelError` produces a caller-facing message and
|
|
* `sanitizeUrlForLogs` strips secrets from URLs before they reach the logger.
|
|
*/
|
|
import { logger } from "@elizaos/core";
|
|
|
|
interface RetryConfig {
|
|
readonly maxRetries: number;
|
|
readonly initialDelayMs: number;
|
|
readonly maxDelayMs: number;
|
|
readonly backoffFactor: number;
|
|
}
|
|
|
|
const DEFAULT_RETRY_CONFIG: RetryConfig = {
|
|
maxRetries: 3,
|
|
initialDelayMs: 500,
|
|
maxDelayMs: 4_000,
|
|
backoffFactor: 2,
|
|
};
|
|
|
|
type RetryableError = {
|
|
readonly cause?: unknown;
|
|
readonly data?: unknown;
|
|
readonly isRetryable?: boolean;
|
|
readonly message?: string;
|
|
readonly name?: string;
|
|
readonly responseBody?: unknown;
|
|
readonly status?: number;
|
|
readonly statusCode?: number;
|
|
};
|
|
|
|
function getRetryableError(error: unknown): RetryableError | null {
|
|
if (!error || typeof error !== "object") {
|
|
return null;
|
|
}
|
|
|
|
return error as RetryableError;
|
|
}
|
|
|
|
function getErrorMessage(error: unknown): string {
|
|
if (error instanceof Error) {
|
|
return error.message;
|
|
}
|
|
return String(error);
|
|
}
|
|
|
|
function readProviderErrorMessage(error: unknown): string | undefined {
|
|
const retryableError = getRetryableError(error);
|
|
const data = retryableError?.data;
|
|
if (data && typeof data === "object") {
|
|
const providerError = (data as { error?: { message?: unknown } }).error;
|
|
if (typeof providerError?.message === "string" && providerError.message.trim()) {
|
|
return providerError.message.trim();
|
|
}
|
|
}
|
|
|
|
const responseBody = retryableError?.responseBody;
|
|
if (typeof responseBody === "string" && responseBody.trim()) {
|
|
try {
|
|
const parsed = JSON.parse(responseBody) as { error?: { message?: unknown } };
|
|
if (typeof parsed.error?.message === "string" && parsed.error.message.trim()) {
|
|
return parsed.error.message.trim();
|
|
}
|
|
} catch {
|
|
// error-policy:J3 untrusted-input sanitizing — an unparseable provider
|
|
// error body falls through to the SDK error message; nothing is masked.
|
|
}
|
|
}
|
|
|
|
const message = getErrorMessage(error).trim();
|
|
return message.length > 0 ? message : undefined;
|
|
}
|
|
|
|
function getStatusCode(error: unknown): number | undefined {
|
|
const retryableError = getRetryableError(error);
|
|
return retryableError?.statusCode ?? retryableError?.status;
|
|
}
|
|
|
|
function hasTimeoutMessage(error: unknown): boolean {
|
|
const message = getErrorMessage(error).toLowerCase();
|
|
return message.includes("timed out") || message.includes("timeout");
|
|
}
|
|
|
|
function hasOverloadMessage(error: unknown): boolean {
|
|
const message = getErrorMessage(error).toLowerCase();
|
|
return (
|
|
message.includes("overload") ||
|
|
message.includes("overloaded") ||
|
|
message.includes("capacity") ||
|
|
message.includes("temporarily unavailable")
|
|
);
|
|
}
|
|
|
|
function isRetryableModelError(error: unknown): boolean {
|
|
const retryableError = getRetryableError(error);
|
|
const statusCode = getStatusCode(error);
|
|
|
|
return (
|
|
retryableError?.isRetryable === true ||
|
|
retryableError?.name === "AI_RetryError" ||
|
|
retryableError?.name === "AbortError" ||
|
|
statusCode === 408 ||
|
|
statusCode === 429 ||
|
|
statusCode === 500 ||
|
|
statusCode === 502 ||
|
|
statusCode === 503 ||
|
|
statusCode === 504 ||
|
|
statusCode === 529 ||
|
|
hasTimeoutMessage(error) ||
|
|
hasOverloadMessage(error)
|
|
);
|
|
}
|
|
|
|
function sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
export async function executeWithRetry<T>(
|
|
operationName: string,
|
|
fn: () => Promise<T>,
|
|
config: RetryConfig = DEFAULT_RETRY_CONFIG
|
|
): Promise<T> {
|
|
let delayMs = config.initialDelayMs;
|
|
|
|
for (let attempt = 0; attempt <= config.maxRetries; attempt += 1) {
|
|
try {
|
|
return await fn();
|
|
} catch (error) {
|
|
// error-policy:J2 context-adding rethrow — transient errors are retried
|
|
// with backoff; non-retryable errors and exhausted attempts rethrow the
|
|
// original provider error unchanged. No failure is converted to a result.
|
|
if (!isRetryableModelError(error) || attempt === config.maxRetries) {
|
|
throw error;
|
|
}
|
|
|
|
logger.warn(
|
|
`[Anthropic] ${operationName} failed with retryable error ` +
|
|
`(attempt ${attempt + 1} of ${config.maxRetries + 1} total): ${getErrorMessage(error)}`
|
|
);
|
|
|
|
await sleep(delayMs);
|
|
delayMs = Math.min(Math.round(delayMs * config.backoffFactor), config.maxDelayMs);
|
|
}
|
|
}
|
|
|
|
throw new Error(`[Anthropic] ${operationName} failed after exhausting retries.`);
|
|
}
|
|
|
|
export function formatModelError(operationName: string, error: unknown): Error {
|
|
const statusCode = getStatusCode(error);
|
|
const providerMessage = readProviderErrorMessage(error);
|
|
let reason = "An unexpected error occurred while processing the request.";
|
|
|
|
if (statusCode === 401) {
|
|
reason = "Authentication failed. Check the configured Anthropic API key.";
|
|
} else if (statusCode === 400 && providerMessage) {
|
|
reason = providerMessage;
|
|
} else if (statusCode === 403 && providerMessage) {
|
|
reason = providerMessage;
|
|
} else if (statusCode === 404 && providerMessage) {
|
|
reason = providerMessage;
|
|
} else if (statusCode === 413 && providerMessage) {
|
|
reason = providerMessage;
|
|
} else if (statusCode === 429) {
|
|
reason = "Anthropic rate limited the request. Retry after a short delay.";
|
|
} else if (statusCode === 504 || hasTimeoutMessage(error)) {
|
|
reason = "The request timed out. Retry with a shorter prompt or a smaller max token limit.";
|
|
} else if (statusCode === 529 || hasOverloadMessage(error)) {
|
|
reason = "Anthropic is temporarily overloaded. Retry in a moment.";
|
|
} else if (statusCode !== undefined && statusCode >= 500) {
|
|
reason = "Anthropic is temporarily unavailable. Retry in a moment.";
|
|
}
|
|
|
|
const message = `[Anthropic] ${operationName} failed: ${reason}`;
|
|
if (error instanceof Error) {
|
|
return new Error(message, { cause: error });
|
|
}
|
|
return new Error(`${message} Original error: ${getErrorMessage(error)}`);
|
|
}
|
|
|
|
export function sanitizeUrlForLogs(url: string): string {
|
|
try {
|
|
const parsed = new URL(url);
|
|
return `${parsed.origin}${parsed.pathname}`;
|
|
} catch {
|
|
// error-policy:J3 untrusted-input sanitizing — "[invalid-url]" is the
|
|
// explicit invalid marker for log output, never a fabricated URL.
|
|
return "[invalid-url]";
|
|
}
|
|
}
|