openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
792 lines (791 loc) • 27.3 kB
JavaScript
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { v as AuthProfileStoreUnreadableError } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { I as OAUTH_REFRESH_CALL_TIMEOUT_MS } from "./user-model-account-authority-CRj924IP.mjs";
import { a as isPendingOAuthRefreshFence, i as isOAuthRefreshFence } from "./oauth-refresh-marker-Bm1Qb0ET.mjs";
import { c as loadPersistedAuthProfileState, n as loadPersistedAuthProfileStore } from "./persisted-Dv3zNYHi.mjs";
import { S as runAuthProfileWriteTransaction, a as inspectPersistedAuthProfileStoreRaw, b as resolveAuthProfileDatabasePath, i as inspectPersistedAuthProfileStateRaw } from "./sqlite-B2CoJ4Om.mjs";
import { a as assertAuthProfileMigrationStateAtDatabasePath, i as assertAuthProfileMigrationReady, t as AuthProfileMigrationRequiredError } from "./legacy-source-diagnostic-cbBtIQVj.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { f as createAuthProfileStoreUpdatePublisher, p as runAuthProfileStoreUpdate } from "./store-Bh2lUvOT.mjs";
import { S as saveAuthProfileStoreWithPreparedOwner, n as createAuthProfileStoreReadScopeAsync, t as createAuthProfileStoreReadScope } from "./store-runtime-dW0pXLJI.mjs";
import { i as OAuthProviderConfiguredUnavailableError, t as OAuthProviderRegistry } from "./oauth-B28cNmEb.mjs";
import { i as resolveAuthStorePathForDisplayAsync, s as normalizeOAuthRefreshCredential, u as refreshSerializedOAuthCredential } from "./paths-BSElhsGi.mjs";
import { c as resolveProviderOAuthRefreshCapabilityWithPlugin, i as loginProviderOAuthWithPlugin, s as resolveProviderOAuthCredentialWithPlugin } from "./provider-runtime.runtime.js";
import { isDeepStrictEqual } from "node:util";
import { execSync, spawnSync } from "node:child_process";
import { findEnvKeys, getEnvApiKey } from "@openclaw/ai/internal/runtime";
//#region src/agents/sessions/auth-storage-error.ts
var AuthStoragePersistenceError = class extends Error {
constructor(e, t) {
super(e, { cause: t });
this.name = "AuthStoragePersistenceError";
}
};
//#endregion
//#region src/agents/sessions/auth-storage-oauth-registry.ts
const registries = /* @__PURE__ */ new WeakMap();
function getAuthStorageOAuthProviderRegistry(e) {
let t = registries.get(e);
if (!t) {
t = new OAuthProviderRegistry();
registries.set(e, t);
}
return t;
}
async function loginAuthStorageOAuthProvider(e, t, n, r) {
const i = getAuthStorageOAuthProviderRegistry(e).get(t);
if (i) return await i.login(n);
const a = await loginProviderOAuthWithPlugin({
provider: t,
context: n,
config: r
});
if (a.status === "unowned") throw new Error(`Unknown OAuth provider: ${t}`);
if (a.status !== "available") throw new OAuthProviderConfiguredUnavailableError(t);
return a.credentials;
}
async function resolveAuthStoragePluginOAuthCredential(e, t, n, r) {
const i = await resolveProviderOAuthCredentialWithPlugin({
provider: e,
credential: {
...t,
type: "oauth",
provider: e
},
refresh: n,
config: r
});
if (i.status === "configured-unavailable") throw new OAuthProviderConfiguredUnavailableError(e);
return i.status === "available" ? {
apiKey: i.apiKey,
newCredentials: i.credential
} : null;
}
async function canResolveAuthStoragePluginOAuthRefresh(e, t) {
const n = await resolveProviderOAuthRefreshCapabilityWithPlugin({
provider: e,
config: t
});
if (n.status === "configured-unavailable") throw new OAuthProviderConfiguredUnavailableError(e);
return n.status === "available";
}
//#endregion
//#region src/agents/sessions/auth-storage-oauth-refresh.ts
function mergeResolvedOAuthCredential(e, t) {
return t ? {
apiKey: t.apiKey,
credential: {
...e,
...t.newCredentials,
type: "oauth",
provider: e.provider
}
} : null;
}
function isAuthStorageOAuthRefreshFence(e, t) {
return t?.type === "oauth" && isOAuthRefreshFence(normalizeOAuthRefreshCredential(t, e));
}
async function refreshAuthStorageOAuthCredential(e) {
const t = getAuthStorageOAuthProviderRegistry(e.authStorage).get(e.providerId);
const n = await refreshSerializedOAuthCredential({
backend: e.storage,
provider: e.providerId,
profileId: `${e.providerId}:default`,
label: `AuthStorage.refresh(${e.providerId})`,
timeoutMs: OAUTH_REFRESH_CALL_TIMEOUT_MS,
parse: e.parse,
serialize: (e) => JSON.stringify(e, null, 2),
readCredential: (t) => {
const n = t[e.providerId];
return normalizeOAuthRefreshCredential(n?.type === "oauth" ? n : void 0, e.providerId);
},
writeCredential: (t, n) => ({
...t,
[e.providerId]: n
}),
canRefresh: async () => Boolean(t) || await canResolveAuthStoragePluginOAuthRefresh(e.providerId, e.config),
commit: async (t) => {
const n = e.parse(JSON.stringify(t));
const r = await e.storage.withLock((t) => {
const r = e.parse(t);
if (!isDeepStrictEqual(r[e.providerId], n[e.providerId])) throw new AuthStoragePersistenceError("Auth storage credentials changed before refresh publication.", void 0);
return { result: r };
});
e.commit(r);
},
refresh: async (n, r) => {
const i = Object.fromEntries(Object.entries(r).filter((e) => {
return e[1].type === "oauth";
}));
return mergeResolvedOAuthCredential(n, t ? await getAuthStorageOAuthProviderRegistry(e.authStorage).getApiKey(e.providerId, i) : await resolveAuthStoragePluginOAuthCredential(e.providerId, n, true, e.config));
},
resolve: async (n) => {
if (t) return {
apiKey: t.getApiKey(n),
credential: n
};
return mergeResolvedOAuthCredential(n, await resolveAuthStoragePluginOAuthCredential(e.providerId, n, false, e.config));
}
});
return n ? { apiKey: n.apiKey } : null;
}
//#endregion
//#region src/agents/sessions/auth-storage-projection.ts
function materializeAuthStorageStore(e, t) {
if (t.length === 0) return e;
const n = Object.fromEntries(Object.entries(e.profiles).map(([e, n]) => {
return [e, t.map((t) => t.profiles[e]).find((e) => n.type === "api_key" && n.keyRef ? e?.type === "api_key" && Boolean(e.key) && e.provider === n.provider && isDeepStrictEqual(e.keyRef, n.keyRef) : n.type === "token" && n.tokenRef ? e?.type === "token" && Boolean(e.token) && e.provider === n.provider && isDeepStrictEqual(e.tokenRef, n.tokenRef) : false) ?? n];
}));
return {
...e,
profiles: n
};
}
function projectAuthoritativeAuthStorageData(e, t) {
const n = materializeAuthStorageStore(e, t);
assertAuthStorageSecretRefsMaterialized(n);
const r = {};
for (const [e, t] of Object.entries(n.profiles)) {
if (e !== `${t.provider}:default`) continue;
if (t.type === "api_key" && t.key) r[t.provider] = {
type: "api_key",
key: t.key
};
else if (t.type === "token" && t.token) r[t.provider] = {
type: "token",
token: t.token,
...t.expires !== void 0 ? { expires: t.expires } : {}
};
else if (t.type === "oauth") r[t.provider] = { ...t };
}
return r;
}
function assertAuthStorageSecretRefsMaterialized(e) {
for (const [t, n] of Object.entries(e.profiles)) {
if (t !== `${n.provider}:default`) continue;
if (n.type === "api_key" && n.keyRef && !n.key || n.type === "token" && n.tokenRef && !n.token) throw new AuthStoragePersistenceError("AuthStorage.forAgent requires the active secrets runtime to materialize SecretRef credentials.", void 0);
}
}
function applyAuthStorageData(e, t, n) {
const r = { ...e.profiles };
const i = /* @__PURE__ */ new Set([...Object.keys(n), ...Object.entries(e.profiles).flatMap(([e, t]) => e === `${t.provider}:default` ? [t.provider] : [])]);
for (const e of i) if (!t[e]) delete r[`${e}:default`];
for (const [e, i] of Object.entries(t)) {
const t = `${e}:default`;
const a = r[t];
if (i.type === "api_key" && a?.type === "api_key" && a.keyRef && n[e]?.type === "api_key" && n[e].key === i.key || i.type === "token" && a?.type === "token" && a.tokenRef && n[e]?.type === "token" && n[e].token === i.token) {
r[t] = a;
continue;
}
r[t] = i.type === "api_key" ? {
type: "api_key",
provider: e,
key: i.key
} : i.type === "token" ? {
type: "token",
provider: e,
token: i.token,
expires: i.expires
} : {
...i,
provider: e
};
}
return {
...e,
profiles: r
};
}
//#endregion
//#region src/agents/sessions/resolve-config-value.ts
/**
* Resolve configuration values that may be shell commands, environment variables, or literals.
* Used by auth-storage.ts and model-registry.ts.
*/
const commandResultCache = /* @__PURE__ */ new Map();
/**
* Resolve a config value (API key, header value, etc.) to an actual value.
* - If starts with "!", executes the rest as a shell command and uses stdout (cached)
* - Otherwise checks environment variable first, then treats as literal (not cached)
*/
async function resolveConfigValue(e, t, n) {
if (!e.startsWith("!")) return resolveConfigValueUncached(e);
const r = process.platform === "win32" ? await import("./shell-utils-DIqvzqA2.mjs") : void 0;
await n?.();
t?.();
if (!commandResultCache.has(e)) commandResultCache.set(e, executeCommandUncached(e, r));
return commandResultCache.get(e);
}
function executeWithConfiguredShell(e, t) {
try {
const n = t.getBashShellConfig();
const r = t.buildShellCommandInvocation(e, n);
const [i, ...a] = r.argv;
const o = spawnSync(i, a, {
encoding: "utf-8",
...r.input === void 0 ? {} : { input: r.input },
timeout: 1e4,
stdio: [
r.stdin,
"pipe",
"ignore"
],
shell: false,
windowsHide: true,
env: t.getBashShellEnv(n.shell)
});
if (o.error || o.status !== 0) return {
executed: o.error?.code !== "ENOENT",
value: void 0
};
return {
executed: true,
value: (o.stdout ?? "").trim() || void 0
};
} catch {
return {
executed: false,
value: void 0
};
}
}
function executeWithDefaultShell(e) {
try {
return execSync(e, {
encoding: "utf-8",
timeout: 1e4,
stdio: [
"ignore",
"pipe",
"ignore"
]
}).trim() || void 0;
} catch {
return;
}
}
function executeCommandUncached(e, t) {
const n = e.slice(1);
if (t) {
const e = executeWithConfiguredShell(n, t);
if (e.executed) return e.value;
}
return executeWithDefaultShell(n);
}
async function resolveConfigValueUncached(e) {
if (e.startsWith("!")) return executeCommandUncached(e, process.platform === "win32" ? await import("./shell-utils-DIqvzqA2.mjs") : void 0);
if (Object.hasOwn(process.env, e)) return process.env[e] || void 0;
return e;
}
async function resolveConfigValueOrThrow(e, t) {
const n = await resolveConfigValueUncached(e);
if (n !== void 0) return n;
if (e.startsWith("!")) throw new Error(`Failed to resolve ${t} from shell command: ${e.slice(1)}`);
throw new Error(`Failed to resolve ${t}`);
}
async function resolveHeadersOrThrow(e, t) {
if (!e) return;
const n = {};
for (const [r, i] of Object.entries(e)) n[r] = await resolveConfigValueOrThrow(i, `${t} header "${r}"`);
return Object.keys(n).length > 0 ? n : void 0;
}
//#endregion
//#region src/agents/sessions/auth-storage.core.ts
/**
* Credential storage facade for API keys and OAuth tokens.
* Canonical persistence is the per-agent SQLite auth-profile store.
*
* The backend contract keeps the upstream session SDK shape while OpenClaw
* projects provider-default profiles into it.
*/
function warnSynchronousAuthStorage(e, t) {
warnPluginSdkDeprecation({
family: "auth-profile-sync-operations",
method: `AuthStorage.${e}`,
replacement: `AuthStorage.${t}`
});
}
function parseStorageData(e) {
return e ? JSON.parse(e) : {};
}
function collectStateOnlyAuthProfileIds(e) {
return [.../* @__PURE__ */ new Set([
...Object.values(e.order ?? {}).flat(),
...Object.values(e.lastGood ?? {}),
...Object.keys(e.usageStats ?? {})
])].filter((t) => !e.profiles[t]);
}
function loadSqliteAuthStorageStore(e, t) {
const n = inspectPersistedAuthProfileStoreRaw(e, t);
if (n.status === "missing") {
if (inspectPersistedAuthProfileStateRaw(e, t).status === "unreadable") throw new AuthProfileStoreUnreadableError(t?.path ?? resolveAuthProfileDatabasePath(e));
return {
version: 1,
profiles: {},
...loadPersistedAuthProfileState(e, t)
};
}
const r = loadPersistedAuthProfileStore(e, t ? { database: t } : void 0);
if (n.status === "unreadable" || !r) throw new AuthProfileStoreUnreadableError(t?.path ?? resolveAuthProfileDatabasePath(e));
return r;
}
var SqliteAuthStorageBackend = class {
constructor(e, t, n = false) {
this.scope = e;
this.preparedStore = t;
this.asyncOnly = n;
this.credentialSources = /* @__PURE__ */ new Map();
this.captureCredentialSources(t);
}
get agentDir() {
return this.scope.agentDir;
}
prepareProviderReady() {
return this.scope.prepareProviderReady();
}
assertProviderReady(e, t) {
this.scope.assertProviderReady(e, t);
}
getCredentialSource(e) {
return this.credentialSources.get(e);
}
assertCredentialReady(e, t) {
this.scope.assertCredentialReady(e, t);
}
captureCredentialSources(e, t) {
const n = new Set(e.runtimePersistedProfileIds ?? []);
this.credentialSources = new Map(Object.entries(e.profiles).flatMap(([r, i]) => {
if (r !== `${i.provider}:default`) return [];
const a = t ? {
databasePath: t,
provider: i.provider
} : e.runtimeCredentialSources?.[r];
if (!a && n.has(r)) throw new AuthStoragePersistenceError("Canonical auth credential is missing its source owner.", void 0);
return a ? [[i.provider, a]] : [];
}));
}
read() {
this.assertSynchronousAccess("reloadAsync");
return this.projectRead(this.scope.read());
}
async readAsync() {
return this.projectRead(await this.scope.readAsync());
}
projectRead(e) {
const t = JSON.stringify(projectAuthoritativeAuthStorageData(e, this.resolveMaterializedRuntimeStores()));
this.captureCredentialSources(e);
return t;
}
assertSynchronousAccess(e) {
if (this.asyncOnly) throw new Error(`This AuthStorage instance requires ${e}().`);
}
resolveMaterializedRuntimeStores() {
const e = this.scope.getRuntimeSnapshots();
return e.length > 0 ? e : [this.preparedStore];
}
withLock(e) {
this.assertSynchronousAccess("setAsync() or removeAsync");
const t = this.resolveMaterializedRuntimeStores();
assertAuthProfileMigrationReady(this.agentDir);
const n = runAuthProfileWriteTransaction(this.agentDir, (n, r) => {
const i = loadSqliteAuthStorageStore(this.agentDir, n);
const a = projectAuthoritativeAuthStorageData(i, t);
const { result: o, next: s } = e(JSON.stringify(a));
let c = i;
if (s !== void 0) {
c = applyAuthStorageData(i, parseStorageData(s), a);
saveAuthProfileStoreWithPreparedOwner(c, this.agentDir, {
filterExternalAuthProfiles: false,
preserveStateProfileIds: collectStateOnlyAuthProfileIds(i),
syncExternalCli: false
}, n, r);
}
return {
result: o,
store: c,
databasePath: r.databasePath
};
});
this.captureCredentialSources(n.store, n.databasePath);
return n.result;
}
async updateAsync(e) {
let t;
await runAuthProfileStoreUpdate({
agentDir: this.agentDir,
envOnly: this.scope.envOnly,
options: { env: this.scope.env },
update: ({ store: n }, r) => {
assertAuthProfileMigrationStateAtDatabasePath(r.databasePath);
const i = projectAuthoritativeAuthStorageData(n, this.resolveMaterializedRuntimeStores());
const { result: a, next: o } = e(JSON.stringify(i));
const s = o === void 0 ? n : applyAuthStorageData(n, parseStorageData(o), i);
t = {
result: a,
store: s,
databasePath: r.databasePath
};
return o === void 0 ? { save: false } : {
save: true,
store: s,
externalProfiles: [],
options: {
filterExternalAuthProfiles: false,
preserveStateProfileIds: collectStateOnlyAuthProfileIds(n),
syncExternalCli: false
}
};
},
publish: createAuthProfileStoreUpdatePublisher()
});
this.captureCredentialSources(t.store, t.databasePath);
return t.result;
}
};
var InMemoryAuthStorageBackend = class {
withLock(e) {
const { result: t, next: n } = e(this.value);
if (n !== void 0) this.value = n;
return t;
}
};
/**
* Provider-keyed credential facade backed by the canonical auth-profile store.
*/
var AuthStorage = class AuthStorage {
static {
this.resolvePathForDisplayAsync = resolveAuthStorePathForDisplayAsync;
}
constructor(e, t, n) {
this.config = n;
this.data = {};
this.credentialSources = /* @__PURE__ */ new Map();
this.runtimeOverrides = /* @__PURE__ */ new Map();
this.loadError = null;
this.errors = [];
this.storage = e;
if (t) this.setData(t);
else this.loadFromStorage();
}
/** @deprecated Use forAgentAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
static forAgent(e, t) {
warnSynchronousAuthStorage("forAgent", "forAgentAsync");
const n = createAuthProfileStoreReadScope(e, t);
const r = materializeAuthStorageStore(n.store, n.getRuntimeSnapshots());
assertAuthStorageSecretRefsMaterialized(r);
return new AuthStorage(new SqliteAuthStorageBackend(n, r), void 0, t);
}
static async forAgentAsync(e, t) {
const n = await createAuthProfileStoreReadScopeAsync(e, t);
const r = materializeAuthStorageStore(n.store, n.getRuntimeSnapshots());
assertAuthStorageSecretRefsMaterialized(r);
const i = new SqliteAuthStorageBackend(n, r, true);
const a = projectAuthoritativeAuthStorageData(n.store, n.getRuntimeSnapshots());
return new AuthStorage(i, a, t);
}
static fromStorage(e) {
return new AuthStorage(e);
}
static inMemory(e = {}) {
const t = new InMemoryAuthStorageBackend();
t.withLock(() => ({
result: void 0,
next: JSON.stringify(e, null, 2)
}));
return new AuthStorage(t);
}
/**
* Set a runtime API key override (not persisted to disk).
* Used for CLI --api-key flag.
*/
setRuntimeApiKey(e, t) {
this.runtimeOverrides.set(e, t);
}
removeRuntimeApiKey(e) {
this.runtimeOverrides.delete(e);
}
/**
* Set a fallback resolver for API keys not found in canonical storage or env vars.
* Used for custom provider keys from models.json.
*/
setFallbackResolver(e) {
this.fallbackResolver = e;
}
recordError(e) {
const t = e instanceof Error ? e : new Error(String(e));
materializeErrorStack(t);
this.errors.push(t);
return t;
}
getCanonicalLoadError() {
if (!this.loadError) return null;
return this.storage.assertProviderReady || this.loadError instanceof AuthProfileMigrationRequiredError || this.loadError instanceof AuthProfileStoreUnreadableError ? this.loadError : null;
}
assertProviderReady(e, t) {
this.storage.assertProviderReady?.(e, t?.baseUrl);
const n = this.getCanonicalLoadError();
if (n) throw n;
}
setData(e) {
this.data = e;
this.credentialSources = new Map(Object.keys(e).flatMap((e) => {
const t = this.storage.getCredentialSource?.(e);
return t ? [[e, t]] : [];
}));
}
/** @deprecated Use reloadAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
reload() {
warnSynchronousAuthStorage("reload", "reloadAsync");
this.loadFromStorage();
}
loadFromStorage() {
try {
const e = this.storage.read ? this.storage.read() : this.storage.withLock((e) => ({ result: e }));
this.setData(parseStorageData(e));
this.loadError = null;
} catch (e) {
this.loadError = this.recordError(e);
}
}
async reloadAsync() {
try {
const e = this.storage.readAsync ? await this.storage.readAsync() : this.storage.read ? this.storage.read() : this.storage.withLock((e) => ({ result: e }));
this.setData(parseStorageData(e));
this.loadError = null;
} catch (e) {
this.loadError = this.recordError(e);
}
}
mergeProviderChange(e, t, n) {
const r = { ...parseStorageData(e) };
if (n) r[t] = n;
else delete r[t];
return {
result: r,
next: JSON.stringify(r, null, 2)
};
}
persistProviderChange(e, t) {
if (this.loadError) this.loadFromStorage();
if (this.loadError) {
const e = new AuthStoragePersistenceError(`Cannot update auth storage because it could not be loaded: ${this.loadError.message}`, this.loadError);
this.recordError(e);
throw e;
}
try {
const n = this.storage.withLock((n) => this.mergeProviderChange(n, e, t));
this.loadError = null;
this.setData(n);
} catch (t) {
this.failProviderChange(e, t);
}
}
async persistProviderChangeAsync(e, t) {
try {
const update = (n) => this.mergeProviderChange(n, e, t);
const n = this.storage.updateAsync ? await this.storage.updateAsync(update) : this.storage.withLock(update);
this.loadError = null;
this.setData(n);
} catch (t) {
this.failProviderChange(e, t);
}
}
failProviderChange(e, t) {
const n = t instanceof AuthStoragePersistenceError ? t : new AuthStoragePersistenceError(`Failed to persist auth storage update for provider "${e}": ${t instanceof Error ? t.message : String(t)}`, t);
this.recordError(n);
throw n;
}
get(e) {
const t = this.data[e];
return isAuthStorageOAuthRefreshFence(e, t) ? void 0 : t;
}
/** @deprecated Use setAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
set(e, t) {
warnSynchronousAuthStorage("set", "setAsync");
this.persistProviderChange(e, t);
}
setAsync(e, t) {
return this.persistProviderChangeAsync(e, t);
}
/** @deprecated Use removeAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
remove(e) {
warnSynchronousAuthStorage("remove", "removeAsync");
this.persistProviderChange(e, void 0);
}
removeAsync(e) {
return this.persistProviderChangeAsync(e, void 0);
}
list() {
return Object.keys(this.data).filter((e) => !isAuthStorageOAuthRefreshFence(e, this.data[e]));
}
has(e) {
return this.get(e) !== void 0;
}
/**
* Check if any form of auth is configured for a provider.
* Unlike getApiKey(), this doesn't refresh OAuth tokens.
*/
hasAuth(e) {
return Boolean(this.runtimeOverrides.has(e) || this.get(e) || getEnvApiKey(e) || this.fallbackResolver?.(e));
}
/**
* Return auth status without exposing credential values or refreshing tokens.
*/
getAuthStatus(e) {
if (this.get(e)) return {
configured: true,
source: "stored"
};
if (this.runtimeOverrides.has(e)) return {
configured: false,
source: "runtime",
label: "--api-key"
};
const t = findEnvKeys(e);
if (t?.[0]) return {
configured: false,
source: "environment",
label: t[0]
};
if (this.fallbackResolver?.(e)) return {
configured: false,
source: "fallback",
label: "custom provider config"
};
return { configured: false };
}
/**
* Get all credentials (for passing to getOAuthApiKey).
*/
getAll() {
return Object.fromEntries(Object.entries(this.data).filter(([e, t]) => !isAuthStorageOAuthRefreshFence(e, t)));
}
drainErrors() {
const e = [...this.errors];
this.errors = [];
return e;
}
async login(e, t) {
const n = await loginAuthStorageOAuthProvider(this, e, t, this.config);
await this.setAsync(e, {
type: "oauth",
...n
});
}
/** @deprecated Use logoutAsync. Supported through 2026-12-31. Removal in the first January 2027 stable release. */
logout(e) {
warnSynchronousAuthStorage("logout", "logoutAsync");
this.remove(e);
}
logoutAsync(e) {
return this.removeAsync(e);
}
/**
* Refresh OAuth token with backend locking to prevent race conditions.
* Multiple agent sessions may try to refresh simultaneously when tokens expire.
*/
async refreshOAuthTokenWithLock(e) {
let t;
const n = await refreshAuthStorageOAuthCredential({
authStorage: this,
config: this.config,
storage: { withLock: (e) => this.storage.updateAsync ? this.storage.updateAsync(e) : this.storage.withLock(e) },
providerId: e,
parse: parseStorageData,
commit: (n) => {
this.setData(n);
t = this.credentialSources.get(e);
this.loadError = null;
}
});
if (!n) {
await this.reloadAsync();
return null;
}
return {
...n,
source: t
};
}
/**
* Get API key for a provider.
* Priority:
* 1. Runtime override (CLI --api-key)
* 2. API key from canonical storage
* 3. OAuth token from canonical storage (auto-refreshed with locking)
* 4. Environment variable
* 5. Fallback resolver (models.json custom providers)
*/
async getApiKey(e, t) {
const n = this.runtimeOverrides.get(e);
if (n) return n;
if (this.storage.readAsync) await this.reloadAsync();
await this.storage.prepareProviderReady?.();
this.assertProviderReady(e, t);
const { apiKey: r, source: i } = await this.resolveStoredOrFallbackApiKey(e, t);
await this.storage.prepareProviderReady?.();
this.assertProviderReady(e, t);
if (i) this.storage.assertCredentialReady?.(i, t?.baseUrl);
return r;
}
async resolveStoredOrFallbackApiKey(e, t) {
let n = this.data[e];
if (isAuthStorageOAuthRefreshFence(e, n)) {
await this.reloadAsync();
n = this.data[e];
const t = n?.type === "oauth" ? normalizeOAuthRefreshCredential(n, e) : void 0;
if (isOAuthRefreshFence(t) && !isPendingOAuthRefreshFence(t)) n = void 0;
}
let r = this.credentialSources.get(e);
if (r) this.storage.assertCredentialReady?.(r, t?.baseUrl);
const resolved = (e) => ({
apiKey: e,
source: r
});
const beforeCommand = () => {
this.assertProviderReady(e, t);
if (r) this.storage.assertCredentialReady?.(r, t?.baseUrl);
};
if (n?.type === "api_key" && !n.nativeAuth) return resolved(await resolveConfigValue(n.key, beforeCommand, () => this.storage.prepareProviderReady?.()));
if (n?.type === "token") {
if (n.expires === void 0 || Date.now() < n.expires) return resolved(await resolveConfigValue(n.token, beforeCommand, () => this.storage.prepareProviderReady?.()));
}
if (n?.type === "oauth") {
const i = getAuthStorageOAuthProviderRegistry(this).get(e);
if (Date.now() >= n.expires) try {
const t = await this.refreshOAuthTokenWithLock(e);
if (t) return {
apiKey: t.apiKey,
source: t.source
};
} catch (n) {
if (n instanceof OAuthProviderConfiguredUnavailableError) throw n;
this.recordError(n);
await this.reloadAsync();
const a = n instanceof AuthProfileMigrationRequiredError || n instanceof AuthProfileStoreUnreadableError ? n : this.getCanonicalLoadError();
if (a) throw a;
const o = this.data[e];
r = this.credentialSources.get(e);
if (r) this.storage.assertCredentialReady?.(r, t?.baseUrl);
if (o?.type === "oauth" && Date.now() < o.expires) {
if (i) return resolved(i.getApiKey(o));
return resolved((await resolveAuthStoragePluginOAuthCredential(e, o, false, this.config))?.apiKey);
}
return resolved(void 0);
}
else {
if (i) return resolved(i.getApiKey(n));
return resolved((await resolveAuthStoragePluginOAuthCredential(e, n, false, this.config))?.apiKey);
}
}
const i = getEnvApiKey(e);
if (i) return resolved(i);
if (t?.includeFallback !== false) return resolved(this.fallbackResolver?.(e));
return resolved(void 0);
}
getOAuthProviders() {
return getAuthStorageOAuthProviderRegistry(this).getAll();
}
};
//#endregion
export { getAuthStorageOAuthProviderRegistry as a, resolveHeadersOrThrow as i, resolveConfigValueOrThrow as n, resolveConfigValueUncached as r, AuthStorage as t };