openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
102 lines (101 loc) • 4.12 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { g as normalizeUniqueStringEntries, v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { t as getProviderEnvVarsCore } from "./provider-env-vars-DPvuIf4v.mjs";
import "./backoff-B-fIQi7C.mjs";
import { n as classifyFailoverSignal } from "./classify-o7Whl-By.mjs";
import { a as resolveTransientProviderDelayMs, i as resolveTransientProviderAttempts, o as resolveTransientProviderRetryOptions, s as shouldRetrySameKeyProviderOperation } from "./operation-retry-CNR4uE0x.mjs";
//#region src/agents/live-auth-keys.ts
/**
* Live-test provider API-key discovery.
* Reads provider-specific and manifest-declared env names without logging or
* exposing secret values, with explicit single-key pins for flaky live lanes.
*/
const KEY_SPLIT_RE = /[\s,;]+/g;
const PROVIDER_PREFIX_OVERRIDES = {
google: "GEMINI",
"google-vertex": "GEMINI"
};
/** Collect configured API keys for live provider tests without exposing values. */
function collectProviderApiKeys(e, t = {}) {
const n = t.env ?? process.env;
const r = normalizeProviderId(e);
const i = PROVIDER_PREFIX_OVERRIDES[r] ?? r.toUpperCase().replace(/-/g, "_");
const a = normalizeOptionalString(n[`OPENCLAW_LIVE_${i}_KEY`]);
if (a) return [a];
const o = r === "anthropic" ? "OPENCLAW_LIVE_ANTHROPIC_KEYS" : `${i}_API_KEYS`;
const s = t.providerEnvVars ?? getProviderEnvVarsCore(r);
return normalizeUniqueTrimmedStringList([
...n[o]?.split(KEY_SPLIT_RE) ?? [],
n[`${i}_API_KEY`],
...Object.entries(n).filter(([e]) => e.startsWith(`${i}_API_KEY_`)).map(([, e]) => e),
...r === "google" || r === "google-vertex" ? [n.GOOGLE_API_KEY] : [],
...s.map((e) => n[e])
]);
}
/** Return whether a provider error message indicates API-key rate limiting. */
function isApiKeyRateLimitError(e) {
const t = classifyFailoverSignal({ message: e });
return t?.kind === "reason" && t.reason === "rate_limit";
}
//#endregion
//#region src/agents/api-key-rotation.ts
/**
* Provider API-key rotation wrapper.
* Runs provider calls across configured keys on rate-limit failures and keeps
* same-key transient retries separate from key rotation.
*/
/** Collect primary and live-discovered provider keys in stable de-duped order. */
function collectProviderApiKeysForExecution(e) {
const { primaryApiKey: t, provider: n } = e;
return normalizeUniqueStringEntries([t?.trim() ?? "", ...collectProviderApiKeys(n)]);
}
async function executeWithApiKeyRotation(e) {
const t = normalizeUniqueStringEntries(e.apiKeys);
if (t.length === 0) throw new Error(`No API keys configured for provider "${e.provider}".`);
let n;
const r = resolveTransientProviderRetryOptions(e.transientRetry);
keyLoop: for (const [i, a] of t.entries()) {
const o = resolveTransientProviderAttempts(r);
for (let s = 1; s <= o; s += 1) {
r?.signal?.throwIfAborted();
try {
return await e.execute(a);
} catch (c) {
r?.signal?.throwIfAborted();
n = c;
const l = formatErrorMessage(c);
const u = {
apiKey: a,
error: c,
attempt: s,
apiKeyIndex: i,
message: l
};
if (e.shouldRetry?.(u) ?? isApiKeyRateLimitError(l)) {
if (i + 1 >= t.length) break;
e.onRetry?.(u);
break;
}
if (!r || !shouldRetrySameKeyProviderOperation({
options: r,
error: c,
message: l,
provider: e.provider,
apiKeyIndex: i,
attemptNumber: s,
maxAttempts: o
})) break keyLoop;
const d = resolveTransientProviderDelayMs(r, s);
await (r.sleep ?? sleepWithAbort)(d, r.signal);
}
}
}
if (n === void 0) throw new Error(`Failed to run API request for ${e.provider}.`);
throw toErrorObject(n, "Non-Error thrown");
}
//#endregion
export { executeWithApiKeyRotation as n, collectProviderApiKeysForExecution as t };