import { c as isRecord } from "./record-coerce-DItp3I4t.js";
import "./utils-B2aozS-T.js";
import { d as isSecretRef } from "./types.secrets-Bre8L6Ts.js";
import { w as resolveStateDir } from "./paths-BBSTUjD5.js";
import { c as isSqliteLockError } from "./node-sqlite-GN5_mcoB.js";
import { o as resolveSharedAuthStoreOwnership, s as resolveSharedAuthStorePath } from "./path-resolve-FSTOqqc1.js";
import { E as listLegacyAuthProfileSources, _ as runAuthProfileWriteTransaction, c as inspectPersistedSharedAuthProfileStoreRaw, g as resolveAuthProfileStoreOwner, h as resolveAuthProfileDatabasePath, l as readPersistedAuthProfileStateRaw, n as deferAuthProfilePostCommitPublication, o as inspectPersistedAuthProfileStoreRaw, r as deletePersistedAuthProfileStoreRaw, u as readPersistedAuthProfileStoreRaw, v as writePersistedAuthProfileStateRaw, y as writePersistedAuthProfileStoreRaw } from "./sqlite-B1Zreme7.js";
import { A as cloneAuthProfileStore, B as authProfilesLog, O as shouldPersistRuntimeExternalOAuthProfile, a as loadPersistedAuthProfileStore, b as setRuntimeExternalCliProfileIds, c as mergeAuthProfileStores, f as loadPersistedAuthProfileState, g as getRuntimeExternalCliProfileIds, h as isLegacyOAuthRef, n as buildPersistedAuthProfileSecretsStore, o as loadPersistedAuthProfileStoreAtDatabasePath, s as loadPersistedSharedAuthProfileStore, u as buildPersistedAuthProfileState, v as mergeRuntimeExternalProfileReferences } from "./persisted-DWuu8-_3.js";
import { n as overlayExternalAuthProfiles, r as syncPersistedExternalCliAuthProfiles, t as listRuntimeExternalAuthProfiles } from "./external-auth-q57wKBhl.js";
import { a as assertAuthProfileMigrationStateAtDatabasePath, d as warnLegacyAuthProfileSourcesIgnored, i as assertAuthProfileMigrationReady, n as AuthProfileStoreUnreadableError, s as clearAuthProfileMigrationRequired, t as AuthProfileMigrationRequiredError, u as markAuthProfileMigrationRequired } from "./legacy-source-diagnostic-0891yY0U.js";
import { A as captureRuntimeAuthProfileLegacyCandidates, B as stripRuntimeExternalProfileMetadata, C as setRuntimeAuthProfileStoreSnapshot, F as mergeLocalAuthProfileStoreWithInheritedStore, H as shouldUseMainOwnerForLocalOAuthCredential, L as runtimeAuthProfileSnapshotSharesOwner, M as listRuntimeLocalProfileIds, N as loadRuntimeAuthProfileOwnerSnapshot, P as markRuntimePersistedProfiles, R as runtimeStoreInheritsMainState, S as restoreOwnedRuntimeAuthProfileStoreSnapshot, T as updateRuntimeAuthProfileStoreSnapshot, V as isInheritedMainOAuthCredentialFromStores, _ as listRuntimeAuthProfileStoreSnapshotsForSharedOwner, a as getPreparedRuntimeAuthProfileStoreSnapshotCore, f as getRuntimeAuthProfileStoreSnapshotRevisionAtDatabasePath, g as listOwnedRuntimeAuthProfileStoreSnapshots, i as getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath, j as createEmptyAuthProfileStore, l as getRuntimeAuthProfileStoreSnapshotAtDatabasePath, n as clearRuntimeAuthProfileStoreSnapshotCore, t as clearRuntimeAuthProfileStoreSnapshotAtDatabasePath, u as getRuntimeAuthProfileStoreSnapshotCore, v as noteRuntimeAuthProfileStorePersistedMutation, w as setRuntimeAuthProfileStoreSnapshotAtDatabasePath, z as setRuntimeLocalProfileMetadata } from "./runtime-snapshots-CUnHyAF9.js";
import "./source-check-CkWv8t_h.js";
import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/agents/auth-profiles/portability.ts
/**
* Auth profile portability for agent-local copies.
* Decides which credentials can be copied to spawned agents without leaking or
* duplicating unsafe OAuth refresh material.
*/
function hasAgentCopyOverride(credential) {
	return typeof credential.copyToAgents === "boolean" ? credential.copyToAgents : void 0;
}
function hasCopyableOAuthMaterial(credential) {
	if (credential.type !== "oauth") return false;
	return [credential.access, credential.refresh].some((value) => typeof value === "string" && value.trim().length > 0);
}
/** Resolves whether a credential can be copied into an agent-local store. */
function resolveAuthProfilePortability(credential) {
	const override = hasAgentCopyOverride(credential);
	if (override === false) return {
		portable: false,
		reason: "credential-opted-out"
	};
	if (credential.type === "oauth") {
		if (!hasCopyableOAuthMaterial(credential)) return {
			portable: false,
			reason: "non-portable-oauth-refresh-token"
		};
		return override === true ? {
			portable: true,
			reason: "oauth-provider-opted-in"
		} : {
			portable: false,
			reason: "non-portable-oauth-refresh-token"
		};
	}
	return {
		portable: true,
		reason: "portable-static-credential"
	};
}
/** Returns true when a credential can be copied into an agent-local store. */
function isAuthProfileCredentialPortableForAgentCopy(credential) {
	return resolveAuthProfilePortability(credential).portable;
}
/** Builds an agent-copy store containing only portable credentials and their order. */
function buildPortableAuthProfileStoreForAgentCopy(store) {
	const copiedProfileIds = [];
	const skippedProfileIds = [];
	const profiles = Object.fromEntries(Object.entries(store.profiles).flatMap(([profileId, credential]) => {
		if (!isAuthProfileCredentialPortableForAgentCopy(credential)) {
			skippedProfileIds.push(profileId);
			return [];
		}
		copiedProfileIds.push(profileId);
		return [[profileId, credential]];
	}));
	const copiedSet = new Set(copiedProfileIds);
	const order = Object.fromEntries(Object.entries(store.order ?? {}).map(([provider, ids]) => [provider, ids.filter((id) => copiedSet.has(id))]).filter(([, ids]) => ids.length > 0));
	return {
		store: {
			version: 1,
			profiles,
			...Object.keys(order).length > 0 ? { order } : {}
		},
		copiedProfileIds,
		skippedProfileIds
	};
}
//#endregion
//#region src/agents/auth-profiles/store.ts
/**
* Auth profile store orchestration.
* Merges persisted stores, runtime snapshots, inherited main-agent OAuth
* profiles, and external CLI overlays while keeping save paths local.
*/
const INLINE_OAUTH_TOKEN_FIELDS = [
	"access",
	"refresh",
	"idToken"
];
const authProfileRuntimeMode = new AsyncLocalStorage();
/** Run a bounded operation without persisted or external CLI auth profiles. */
function withEnvOnlyAuthProfileStore(run) {
	return authProfileRuntimeMode.run({ kind: "env-only" }, run);
}
/** Run a bounded operation against one existing persisted auth store. */
function withAuthProfileStoreAgentDir(agentDir, sharedStateDir, run) {
	const env = {
		...process.env,
		OPENCLAW_STATE_DIR: sharedStateDir
	};
	let sharedStore;
	if (resolveSharedAuthStoreOwnership(env).location === "state-db") {
		const shared = loadPersistedSharedAuthProfileStore(env);
		if (!shared && inspectPersistedSharedAuthProfileStoreRaw(env).status !== "missing") throw new AuthProfileStoreUnreadableError(resolveSharedAuthStorePath(env));
		sharedStore = shared ?? createEmptyAuthProfileStore();
	}
	if (sharedStore) {
		sharedStore.profiles = Object.fromEntries(Object.entries(sharedStore.profiles).filter(([, credential]) => resolveAuthProfilePortability(credential).reason === "portable-static-credential"));
		pruneAuthProfileStoreReferences(sharedStore, new Set(Object.keys(sharedStore.profiles)));
	}
	return authProfileRuntimeMode.run({
		kind: "agent-dir",
		agentDir,
		sharedStore,
		env
	}, run);
}
function getScopedAuthProfileEnv() {
	const mode = authProfileRuntimeMode.getStore();
	return mode?.kind === "agent-dir" ? mode.env : void 0;
}
function getScopedSharedAuthStore() {
	const mode = authProfileRuntimeMode.getStore();
	return mode?.kind === "agent-dir" ? mode.sharedStore : void 0;
}
function applyScopedAuthReadThrough(store) {
	const shared = getScopedSharedAuthStore();
	if (!shared) return store;
	const merged = mergeAuthProfileStores(cloneAuthProfileStore(shared), store);
	return setRuntimeLocalProfileMetadata(merged, Object.keys(store.profiles), runtimeStoreInheritsMainState(merged, store));
}
function isEnvOnlyAuthProfileRuntime() {
	return authProfileRuntimeMode.getStore()?.kind === "env-only";
}
function resolveRuntimeAuthProfileAgentDir(agentDir) {
	const mode = authProfileRuntimeMode.getStore();
	return mode?.kind === "agent-dir" ? mode.agentDir : agentDir;
}
function resolveRuntimeAuthProfileLoadOptions(options) {
	const mode = authProfileRuntimeMode.getStore();
	if (mode?.kind !== "agent-dir") return options;
	return {
		...options,
		inheritedAuthDir: mode.agentDir
	};
}
function hasInlineOAuthTokenMaterial(credential) {
	return INLINE_OAUTH_TOKEN_FIELDS.some((field) => Reflect.get(credential, field) !== void 0);
}
function hasChangedInlineOAuthTokenMaterial(params) {
	return INLINE_OAUTH_TOKEN_FIELDS.some((field) => {
		const credentialValue = Reflect.get(params.credential, field);
		if (credentialValue === void 0) return false;
		return !isDeepStrictEqual(credentialValue, Reflect.get(params.existingCredential, field));
	});
}
function preserveLegacyOAuthRefsOnSave(params) {
	if (!isRecord(params.existingRaw) || !isRecord(params.existingRaw.profiles)) return params.payload;
	let nextProfiles;
	for (const [profileId, credential] of Object.entries(params.payload.profiles)) {
		if (credential.type !== "oauth" || credential.oauthRef !== void 0) continue;
		const existingCredential = params.existingRaw.profiles[profileId];
		if (!isRecord(existingCredential) || !isLegacyOAuthRef(existingCredential.oauthRef) || existingCredential.type !== "oauth") continue;
		if (hasInlineOAuthTokenMaterial(credential) && hasChangedInlineOAuthTokenMaterial({
			credential,
			existingCredential
		})) continue;
		nextProfiles ??= { ...params.payload.profiles };
		nextProfiles[profileId] = {
			...credential,
			oauthRef: existingCredential.oauthRef
		};
	}
	return nextProfiles ? {
		...params.payload,
		profiles: nextProfiles
	} : params.payload;
}
let runtimeSnapshotPublisherForTest;
function publishRuntimeSnapshotsAfterCommit(publication) {
	if (!publication) return true;
	try {
		let converged = false;
		const publish = () => {
			converged = publication.publish();
		};
		if (runtimeSnapshotPublisherForTest) runtimeSnapshotPublisherForTest(publish);
		else publish();
		return converged;
	} catch (err) {
		clearRuntimeAuthProfileStoreSnapshotAtDatabasePath(publication.databasePath, publication.agentDir);
		authProfilesLog.warn("auth profile store committed but runtime snapshot publication failed", { err });
		return false;
	}
}
const testing = {
	resetRuntimeSnapshotPublisherForTest() {
		runtimeSnapshotPublisherForTest = void 0;
	},
	setRuntimeSnapshotPublisherForTest(publisher) {
		runtimeSnapshotPublisherForTest = publisher;
	}
};
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.authProfileStoreTestApi")] = testing;
function resolvePersistedLoadOptions(options) {
	return {
		...options?.allowKeychainPrompt !== void 0 ? { allowKeychainPrompt: options.allowKeychainPrompt } : {},
		...options?.database ? { database: options.database } : {}
	};
}
function loadPersistedAuthProfileStores(agentDir, database, owner) {
	const localStore = loadPersistedAuthProfileStore(agentDir, database ? { database } : void 0);
	const isMainStore = (owner?.databasePath ?? (agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath())) === (owner?.sharedDatabasePath ?? resolveSharedAuthStorePath());
	return {
		isMainStore,
		localStore,
		mainStore: isMainStore ? localStore : owner ? loadPersistedAuthProfileStoreAtDatabasePath(owner.sharedDatabasePath, owner.location === "state-db" ? "shared-state" : "agent") : loadPersistedAuthProfileStore()
	};
}
/**
* A non-main agent store deliberately does not persist an OAuth credential the
* main store already owns at the same or newer expiry. Callers that verify a
* write must treat such a profile as intentionally deduped rather than lost,
* otherwise the credential looks like it vanished during the write.
*/
function isInheritedMainOAuthCredential(params) {
	if (!params.agentDir || params.credential.type !== "oauth") return false;
	return isInheritedMainOAuthCredentialFromStores({
		profileId: params.profileId,
		credential: params.credential,
		persistedStores: loadPersistedAuthProfileStores(params.agentDir)
	});
}
function resolveRuntimeAuthProfileStore(agentDir, options) {
	if (getScopedSharedAuthStore()) return null;
	const mainKey = options?.inheritedAuthDir ? resolveAuthProfileDatabasePath(options.inheritedAuthDir) : resolveSharedAuthStorePath();
	const requestedKey = agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath();
	const mainStore = getRuntimeAuthProfileStoreSnapshotCore(options?.inheritedAuthDir);
	const requestedStore = getRuntimeAuthProfileStoreSnapshotCore(agentDir);
	if (!agentDir || requestedKey === mainKey) {
		if (!mainStore) return null;
		return mainStore;
	}
	if (mainStore && requestedStore) return mergeAuthProfileStores(mainStore, requestedStore, { preserveBaseRuntimeExternalProfiles: true });
	if (requestedStore) return mergeAuthProfileStores(loadAuthProfileStoreForAgent(options?.inheritedAuthDir, {
		readOnly: true,
		syncExternalCli: false,
		...resolvePersistedLoadOptions(options)
	}), requestedStore, { preserveBaseRuntimeExternalProfiles: true });
	if (mainStore) return mergeAuthProfileStores(mainStore, loadAuthProfileStoreForAgent(agentDir, {
		readOnly: true,
		syncExternalCli: false,
		...resolvePersistedLoadOptions(options)
	}), { preserveBaseRuntimeExternalProfiles: true });
	return null;
}
function resolveExternalCliOverlayOptions(options) {
	const discovery = options?.externalCli;
	if (!discovery) return {
		...options?.allowKeychainPrompt !== void 0 ? { allowKeychainPrompt: options.allowKeychainPrompt } : {},
		...options?.config ? { config: options.config } : {},
		...options?.externalCliProviderIds ? { externalCliProviderIds: options.externalCliProviderIds } : {},
		...options?.externalCliProfileIds ? { externalCliProfileIds: options.externalCliProfileIds } : {}
	};
	if (discovery.mode === "none") {
		const config = discovery.config ?? options?.config;
		return {
			allowKeychainPrompt: false,
			...config ? { config } : {},
			externalCliProviderIds: [],
			externalCliProfileIds: []
		};
	}
	if (discovery.mode === "existing") {
		const allowKeychainPrompt = discovery.allowKeychainPrompt ?? options?.allowKeychainPrompt;
		const config = discovery.config ?? options?.config;
		return {
			...allowKeychainPrompt !== void 0 ? { allowKeychainPrompt } : {},
			...config ? { config } : {}
		};
	}
	const allowKeychainPrompt = discovery.allowKeychainPrompt ?? options?.allowKeychainPrompt;
	const config = discovery.config ?? options?.config;
	return {
		...allowKeychainPrompt !== void 0 ? { allowKeychainPrompt } : {},
		...config ? { config } : {},
		...discovery.providerIds ? { externalCliProviderIds: discovery.providerIds } : {},
		...discovery.profileIds ? { externalCliProfileIds: discovery.profileIds } : {}
	};
}
function hasScopedExternalCliOverlay(options) {
	return options.externalCliProviderIds !== void 0 || options.externalCliProfileIds !== void 0;
}
function maybeSyncPersistedExternalCliAuthProfiles(params) {
	if (params.options?.readOnly === true || params.options?.syncExternalCli === false || process.env.OPENCLAW_AUTH_STORE_READONLY === "1") return {
		store: params.store,
		cacheable: true
	};
	const synced = syncPersistedExternalCliAuthProfiles(params.store, {
		agentDir: params.agentDir,
		...resolveExternalCliOverlayOptions(params.options)
	});
	if (synced === params.store) return {
		store: params.store,
		cacheable: true
	};
	const changedProfiles = Object.entries(synced.profiles).filter(([profileId, credential]) => {
		const previous = params.store.profiles[profileId];
		return !isDeepStrictEqual(previous, credential);
	});
	if (changedProfiles.length === 0) return {
		store: synced,
		cacheable: true
	};
	let publishRuntimeSnapshots;
	let result;
	try {
		result = runAuthProfileWriteTransaction(params.agentDir, (database, owner) => {
			const latestStore = loadPersistedAuthProfileStore(params.agentDir, {
				...resolvePersistedLoadOptions(params.options),
				database
			}) ?? {
				version: 1,
				profiles: {}
			};
			let changed = false;
			for (const [profileId, credential] of changedProfiles) {
				const previous = params.store.profiles[profileId];
				const latest = latestStore.profiles[profileId];
				if (!isDeepStrictEqual(latest, previous)) {
					authProfilesLog.debug("skipped persisted external cli auth sync for concurrently changed profile", { profileId });
					continue;
				}
				latestStore.profiles[profileId] = credential;
				changed = true;
			}
			if (changed) publishRuntimeSnapshots = saveAuthProfileStoreInTransaction(latestStore, params.agentDir, { filterExternalAuthProfiles: false }, database, owner);
			return {
				store: latestStore,
				cacheable: true
			};
		}, { env: getScopedAuthProfileEnv() });
	} catch (err) {
		authProfilesLog.warn("skipped persisted external cli auth sync because auth store write failed", { err });
		return {
			store: params.store,
			cacheable: false
		};
	}
	return publishRuntimeSnapshotsAfterCommit(publishRuntimeSnapshots) ? result : {
		store: result.store,
		cacheable: false
	};
}
function shouldKeepProfileInLocalStore(params) {
	const inherited = getScopedSharedAuthStore()?.profiles[params.profileId];
	if (inherited && !params.persistedStores.localStore?.profiles[params.profileId]) {
		if (isDeepStrictEqual(buildPersistedAuthProfileSecretsStore({
			version: 1,
			profiles: { [params.profileId]: params.credential }
		}).profiles[params.profileId], inherited)) return false;
	}
	if (params.credential.type !== "oauth") return true;
	if (isInheritedMainOAuthCredentialFromStores({
		profileId: params.profileId,
		credential: params.credential,
		persistedStores: params.persistedStores
	})) return false;
	if (params.options?.filterExternalAuthProfiles === false) return true;
	if (params.store.runtimeExternalProfileIds?.includes(params.profileId)) {
		if (params.persistedStores.localStore?.profiles[params.profileId]) return shouldPersistRuntimeExternalOAuthProfile({
			profileId: params.profileId,
			credential: params.credential,
			profiles: params.externalProfiles()
		});
		const runtimeCredential = getRuntimeAuthProfileStoreSnapshotAtDatabasePath(params.owner.databasePath)?.profiles[params.profileId];
		if (!runtimeCredential || isDeepStrictEqual(runtimeCredential, params.credential)) return false;
	}
	return shouldPersistRuntimeExternalOAuthProfile({
		profileId: params.profileId,
		credential: params.credential,
		profiles: params.externalProfiles()
	});
}
function pruneAuthProfileStoreReferences(store, keptProfileIds, keptOrderProfileIds = keptProfileIds) {
	store.order = store.order ? Object.fromEntries(Object.entries(store.order).map(([provider, profileIds]) => [provider, profileIds.filter((profileId) => keptOrderProfileIds.has(profileId))]).filter(([, profileIds]) => Array.isArray(profileIds) && profileIds.length > 0)) : void 0;
	store.lastGood = store.lastGood ? Object.fromEntries(Object.entries(store.lastGood).filter(([, profileId]) => keptProfileIds.has(profileId))) : void 0;
	store.usageStats = store.usageStats ? Object.fromEntries(Object.entries(store.usageStats).filter(([profileId]) => keptProfileIds.has(profileId) || profileId.startsWith("inline-api-key:"))) : void 0;
	store.runtimePersistedProfileIds = store.runtimePersistedProfileIds?.filter((profileId) => keptProfileIds.has(profileId)).toSorted();
	if (store.runtimePersistedProfileIds?.length === 0) store.runtimePersistedProfileIds = void 0;
	store.runtimeLocalProfileIds = store.runtimeLocalProfileIds?.filter((profileId) => keptProfileIds.has(profileId)).toSorted();
	store.runtimeExternalProfileIds = store.runtimeExternalProfileIds?.filter((profileId) => keptProfileIds.has(profileId)).toSorted();
	setRuntimeExternalCliProfileIds(store, getRuntimeExternalCliProfileIds(store).filter((profileId) => keptProfileIds.has(profileId)));
	if (store.runtimeExternalProfileIds?.length === 0 && store.runtimeExternalProfileIdsAuthoritative !== true) store.runtimeExternalProfileIds = void 0;
	if (store.runtimeExternalProfileIdsAuthoritative === true) store.runtimeExternalProfileIds ??= [];
}
function buildLocalAuthProfileStoreForSave(params) {
	const localStore = cloneAuthProfileStore(params.store);
	let externalProfiles;
	const getExternalProfiles = () => externalProfiles ??= listRuntimeExternalAuthProfiles({
		store: params.store,
		agentDir: params.agentDir
	});
	localStore.profiles = Object.fromEntries(Object.entries(localStore.profiles).filter(([profileId, credential]) => shouldKeepProfileInLocalStore({
		owner: params.owner,
		store: params.store,
		profileId,
		credential,
		agentDir: params.agentDir,
		options: params.options,
		persistedStores: params.persistedStores,
		externalProfiles: getExternalProfiles
	})));
	const keptProfileIds = new Set(Object.keys(localStore.profiles));
	const keptOrderProfileIds = new Set(keptProfileIds);
	for (const profileId of params.options?.preserveStateProfileIds ?? []) {
		const normalizedProfileId = profileId.trim();
		if (normalizedProfileId) {
			keptProfileIds.add(normalizedProfileId);
			keptOrderProfileIds.add(normalizedProfileId);
		}
	}
	for (const profileIds of Object.values(params.persistedStores.localStore?.order ?? {})) for (const profileId of profileIds) keptOrderProfileIds.add(profileId);
	for (const profileId of params.options?.preserveOrderProfileIds ?? []) {
		const normalizedProfileId = profileId.trim();
		if (normalizedProfileId) keptOrderProfileIds.add(normalizedProfileId);
	}
	const prunedOrderProfileIds = /* @__PURE__ */ new Set();
	for (const profileId of params.options?.pruneOrderProfileIds ?? []) {
		const normalizedProfileId = profileId.trim();
		if (normalizedProfileId) prunedOrderProfileIds.add(normalizedProfileId);
	}
	for (const profileId of prunedOrderProfileIds) keptOrderProfileIds.delete(profileId);
	pruneAuthProfileStoreReferences(localStore, keptProfileIds, keptOrderProfileIds);
	if (params.options?.filterExternalAuthProfiles !== false) {
		localStore.runtimeExternalProfileIds = void 0;
		localStore.runtimeExternalProfileIdsAuthoritative = void 0;
		setRuntimeExternalCliProfileIds(localStore, []);
	}
	return localStore;
}
function buildAuthProfileStoreWithoutExternalProfiles(params) {
	const runtimeExternalProfileIds = new Set(params.store.runtimeExternalProfileIds ?? []);
	const localStore = cloneAuthProfileStore(params.store);
	if (runtimeExternalProfileIds.size === 0) return stripRuntimeExternalProfileMetadata(localStore);
	for (const profileId of runtimeExternalProfileIds) delete localStore.profiles[profileId];
	pruneAuthProfileStoreReferences(localStore, new Set(Object.keys(localStore.profiles)));
	return stripRuntimeExternalProfileMetadata(mergeAuthProfileStores(loadAuthProfileStoreWithoutExternalProfiles(params.agentDir, params.options), localStore));
}
function buildRuntimeAuthProfileStoreForSave(params) {
	return buildLocalAuthProfileStoreForSave({
		...params,
		options: {
			...params.options,
			filterExternalAuthProfiles: false
		}
	});
}
function convergeRuntimeAuthProfileStoreSnapshot(databasePath, agentDir, operation) {
	try {
		operation();
		return true;
	} catch (err) {
		clearRuntimeAuthProfileStoreSnapshotAtDatabasePath(databasePath, agentDir);
		authProfilesLog.warn("auth profile snapshot convergence failed", { err });
		return false;
	}
}
function setRuntimeExternalProfileMetadata(params) {
	const profileIds = [...params.profileIds].toSorted();
	params.store.runtimeExternalProfileIds = profileIds.length > 0 || params.authoritative ? profileIds : void 0;
	params.store.runtimeExternalProfileIdsAuthoritative = params.authoritative ? true : void 0;
	setRuntimeExternalCliProfileIds(params.store, getRuntimeExternalCliProfileIds(params.store).filter((profileId) => params.profileIds.has(profileId)));
}
function preserveResolvedSecretBackedCredentials(params) {
	const next = cloneAuthProfileStore(params.next);
	for (const [profileId, credential] of Object.entries(next.profiles)) {
		const existing = params.existing.profiles[profileId];
		if (credential.type === "api_key" && existing?.type === "api_key" && credential.key === void 0 && existing.key !== void 0 && isSecretRef(credential.keyRef) && isDeepStrictEqual(credential.keyRef, existing.keyRef)) next.profiles[profileId] = {
			...credential,
			key: existing.key
		};
		else if (credential.type === "token" && existing?.type === "token" && credential.token === void 0 && existing.token !== void 0 && isSecretRef(credential.tokenRef) && isDeepStrictEqual(credential.tokenRef, existing.tokenRef)) next.profiles[profileId] = {
			...credential,
			token: existing.token
		};
	}
	return next;
}
function materializeRuntimeAuthProfileStoreSnapshot(next, existing) {
	return mergeRuntimeExternalProfileReferences({
		next: preserveResolvedSecretBackedCredentials({
			next,
			existing
		}),
		existing
	});
}
function mergeRuntimeExternalProfileState(params) {
	const existingRuntimeProfileIds = new Set(params.existing.runtimeExternalProfileIds ?? []);
	if (existingRuntimeProfileIds.size === 0) return params.next;
	const merged = cloneAuthProfileStore(params.next);
	const mergedRuntimeProfileIds = new Set(merged.runtimeExternalProfileIds ?? []);
	const existingRuntimeExternalCliProfileIds = new Set(getRuntimeExternalCliProfileIds(params.existing));
	const mergedRuntimeExternalCliProfileIds = new Set(getRuntimeExternalCliProfileIds(merged));
	const activeRuntimeProfileIds = /* @__PURE__ */ new Set();
	const nextRuntimeProfileIdsAuthoritative = params.next.runtimeExternalProfileIdsAuthoritative === true;
	for (const profileId of existingRuntimeProfileIds) {
		if (nextRuntimeProfileIdsAuthoritative && !mergedRuntimeProfileIds.has(profileId)) continue;
		const existingCredential = params.existing.profiles[profileId];
		if (!existingCredential) continue;
		const nextCredential = merged.profiles[profileId];
		if (nextCredential) {
			if (mergedRuntimeProfileIds.has(profileId) || isDeepStrictEqual(nextCredential, existingCredential)) {
				mergedRuntimeProfileIds.add(profileId);
				activeRuntimeProfileIds.add(profileId);
				if (existingRuntimeExternalCliProfileIds.has(profileId)) mergedRuntimeExternalCliProfileIds.add(profileId);
			}
			continue;
		}
		merged.profiles[profileId] = existingCredential;
		mergedRuntimeProfileIds.add(profileId);
		activeRuntimeProfileIds.add(profileId);
		if (existingRuntimeExternalCliProfileIds.has(profileId)) mergedRuntimeExternalCliProfileIds.add(profileId);
	}
	if (activeRuntimeProfileIds.size === 0) return params.next;
	for (const profileId of activeRuntimeProfileIds) if (params.existing.usageStats?.[profileId]) merged.usageStats = {
		...merged.usageStats,
		[profileId]: params.existing.usageStats[profileId]
	};
	for (const [provider, profileIds] of Object.entries(params.existing.order ?? {})) {
		const externalProfileIds = profileIds.filter((profileId) => activeRuntimeProfileIds.has(profileId));
		if (externalProfileIds.length === 0 || merged.order?.[provider]) continue;
		merged.order = {
			...merged.order,
			[provider]: externalProfileIds
		};
	}
	for (const [provider, profileId] of Object.entries(params.existing.lastGood ?? {})) {
		if (!activeRuntimeProfileIds.has(profileId) || merged.lastGood?.[provider]) continue;
		merged.lastGood = {
			...merged.lastGood,
			[provider]: profileId
		};
	}
	setRuntimeExternalProfileMetadata({
		store: merged,
		profileIds: mergedRuntimeProfileIds,
		authoritative: params.existing.runtimeExternalProfileIdsAuthoritative === true
	});
	setRuntimeExternalCliProfileIds(merged, mergedRuntimeExternalCliProfileIds);
	return merged;
}
/** Apply an auth store update inside the SQLite write lock; null only on lock contention. */
async function updateAuthProfileStoreWithLock(params) {
	const agentDir = resolveRuntimeAuthProfileAgentDir(params.agentDir);
	let publishRuntimeSnapshots;
	let store;
	try {
		store = runAuthProfileWriteTransaction(agentDir, (database, owner) => {
			const loadedStore = loadAuthProfileStoreForAgent(agentDir, {
				database,
				readOnly: true,
				syncExternalCli: false
			}, owner.env);
			if (params.updater(loadedStore)) publishRuntimeSnapshots = saveAuthProfileStoreInTransaction(loadedStore, agentDir, params.saveOptions, database, owner);
			return loadedStore;
		}, {
			sharedStoreWrite: params.sharedStoreWrite,
			stateDir: params.stateDir,
			env: params.stateDir ? void 0 : getScopedAuthProfileEnv()
		});
	} catch (error) {
		const message = error instanceof Error ? error.message : String(error);
		authProfilesLog.warn(`auth profile store update failed: ${message}`, {
			agentDir,
			error: message
		});
		if (!isSqliteLockError(error)) throw error;
		return null;
	}
	publishRuntimeSnapshotsAfterCommit(publishRuntimeSnapshots);
	return store;
}
/** Load the main auth profile store with runtime external profiles overlaid. */
function loadAuthProfileStore() {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const agentDir = resolveRuntimeAuthProfileAgentDir();
	return overlayExternalAuthProfiles(applyScopedAuthReadThrough(markRuntimePersistedProfiles(loadPersistedAuthProfileStore(agentDir) ?? createEmptyAuthProfileStore())), { agentDir });
}
function loadAuthProfileStoreForAgent(agentDir, options, env) {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const effectiveOptions = resolveRuntimeAuthProfileLoadOptions(options);
	assertAuthProfileMigrationReady(effectiveAgentDir, env);
	const store = !effectiveAgentDir && env && !effectiveOptions?.database ? loadPersistedSharedAuthProfileStore(env) : loadPersistedAuthProfileStore(effectiveAgentDir, resolvePersistedLoadOptions(effectiveOptions));
	if (!store && (!effectiveAgentDir && env && !effectiveOptions?.database ? inspectPersistedSharedAuthProfileStoreRaw(env) : inspectPersistedAuthProfileStoreRaw(effectiveAgentDir, effectiveOptions?.database)).status !== "missing") throw new AuthProfileStoreUnreadableError(effectiveOptions?.database?.path ?? (effectiveAgentDir ? resolveAuthProfileDatabasePath(effectiveAgentDir) : resolveSharedAuthStorePath(env)));
	const legacySources = listLegacyAuthProfileSources({
		agentDir: effectiveAgentDir,
		env
	});
	const credentialSources = legacySources.filter((source) => source.kind !== "auth-state");
	if (credentialSources.length > 0 && (!store || Object.keys(store.profiles).length === 0)) {
		const migrationError = new AuthProfileMigrationRequiredError({
			agentDir: effectiveAgentDir,
			env,
			sources: credentialSources
		});
		if (store) markAuthProfileMigrationRequired(effectiveAgentDir, migrationError, env);
		throw migrationError;
	}
	warnLegacyAuthProfileSourcesIgnored({
		agentDir: effectiveAgentDir,
		env,
		sources: legacySources
	});
	clearAuthProfileMigrationRequired(effectiveAgentDir, env);
	return applyScopedAuthReadThrough(markRuntimePersistedProfiles(maybeSyncPersistedExternalCliAuthProfiles({
		store: store ?? createEmptyAuthProfileStore(),
		agentDir: effectiveAgentDir,
		options: effectiveOptions
	}).store));
}
/** Loads the effective runtime store for an agent, including inherited main profiles. */
function loadAuthProfileStoreForRuntime(agentDir, options) {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const effectiveOptions = resolveRuntimeAuthProfileLoadOptions(options);
	const store = loadAuthProfileStoreForAgent(effectiveAgentDir, effectiveOptions);
	const authPath = effectiveAgentDir ? resolveAuthProfileDatabasePath(effectiveAgentDir) : resolveSharedAuthStorePath();
	const mainAuthPath = effectiveOptions?.inheritedAuthDir ? resolveAuthProfileDatabasePath(effectiveOptions.inheritedAuthDir) : resolveSharedAuthStorePath();
	const externalCli = resolveExternalCliOverlayOptions(effectiveOptions);
	if (!effectiveAgentDir || authPath === mainAuthPath) return setRuntimeLocalProfileMetadata(overlayExternalAuthProfiles(store, {
		agentDir: effectiveAgentDir,
		...externalCli
	}), listRuntimeLocalProfileIds(store));
	const mainStore = loadAuthProfileStoreForAgent(effectiveOptions?.inheritedAuthDir, effectiveOptions);
	const mergedStore = mergeAuthProfileStores(mainStore, store, { preserveBaseRuntimeExternalProfiles: true });
	return setRuntimeLocalProfileMetadata(overlayExternalAuthProfiles(mergedStore, {
		agentDir: effectiveAgentDir,
		...externalCli
	}), listRuntimeLocalProfileIds(store, mainStore), runtimeStoreInheritsMainState(mergedStore, store));
}
/** Load auth profiles for secret resolution without keychain prompts or writes. */
function loadAuthProfileStoreForSecretsRuntime(agentDir, options) {
	return loadAuthProfileStoreForRuntime(agentDir, {
		...options,
		readOnly: true,
		allowKeychainPrompt: false
	});
}
/** Load auth profiles with runtime external profiles removed from the result. */
function loadAuthProfileStoreWithoutExternalProfiles(agentDir, loadOptions) {
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const effectiveLoadOptions = resolveRuntimeAuthProfileLoadOptions(loadOptions);
	const options = {
		readOnly: true,
		allowKeychainPrompt: effectiveLoadOptions?.allowKeychainPrompt ?? false,
		...effectiveLoadOptions?.inheritedAuthDir ? { inheritedAuthDir: effectiveLoadOptions.inheritedAuthDir } : {}
	};
	const store = loadAuthProfileStoreForAgent(effectiveAgentDir, options);
	const authPath = effectiveAgentDir ? resolveAuthProfileDatabasePath(effectiveAgentDir) : resolveSharedAuthStorePath();
	const mainAuthPath = options.inheritedAuthDir ? resolveAuthProfileDatabasePath(options.inheritedAuthDir) : resolveSharedAuthStorePath();
	if (!effectiveAgentDir || authPath === mainAuthPath) return setRuntimeLocalProfileMetadata(stripRuntimeExternalProfileMetadata(store), listRuntimeLocalProfileIds(store));
	return mergeLocalAuthProfileStoreWithInheritedStore(store, loadAuthProfileStoreForAgent(options.inheritedAuthDir, options));
}
/** Ensure an auth store is available, including runtime/external profile overlays. */
function ensureAuthProfileStore(agentDir, options) {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const effectiveOptions = resolveRuntimeAuthProfileLoadOptions(options);
	const externalCli = resolveExternalCliOverlayOptions(effectiveOptions);
	const runtimeStore = resolveRuntimeAuthProfileStore(effectiveAgentDir, effectiveOptions);
	const store = overlayExternalAuthProfiles(ensureAuthProfileStoreWithoutExternalProfiles(effectiveAgentDir, effectiveOptions), {
		agentDir: effectiveAgentDir,
		...externalCli
	});
	if (!runtimeStore) {
		if (!getScopedSharedAuthStore() && hasScopedExternalCliOverlay(externalCli) && (store.runtimeExternalProfileIds?.length ?? 0) > 0) setRuntimeAuthProfileStoreSnapshot(store, effectiveAgentDir);
		return store;
	}
	if (hasScopedExternalCliOverlay(externalCli)) {
		const materialized = mergeRuntimeExternalProfileState({
			next: store,
			existing: runtimeStore
		});
		if (!isDeepStrictEqual(materialized, runtimeStore)) updateRuntimeAuthProfileStoreSnapshot(materialized, effectiveAgentDir);
		return store;
	}
	return mergeRuntimeExternalProfileState({
		next: store,
		existing: runtimeStore
	});
}
/** Ensure an auth store is available without external profile overlays. */
function ensureAuthProfileStoreWithoutExternalProfiles(agentDir, options) {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const effectiveOptions = resolveRuntimeAuthProfileLoadOptions(options) ?? { ...options };
	const runtimeStore = resolveRuntimeAuthProfileStore(effectiveAgentDir, effectiveOptions);
	if (runtimeStore) return buildAuthProfileStoreWithoutExternalProfiles({
		store: runtimeStore,
		agentDir: effectiveAgentDir,
		options: effectiveOptions
	});
	const store = loadAuthProfileStoreForAgent(effectiveAgentDir, effectiveOptions);
	const authPath = effectiveAgentDir ? resolveAuthProfileDatabasePath(effectiveAgentDir) : resolveSharedAuthStorePath();
	const mainAuthPath = effectiveOptions.inheritedAuthDir ? resolveAuthProfileDatabasePath(effectiveOptions.inheritedAuthDir) : resolveSharedAuthStorePath();
	if (!effectiveAgentDir || authPath === mainAuthPath) return stripRuntimeExternalProfileMetadata(store);
	return stripRuntimeExternalProfileMetadata(mergeAuthProfileStores(loadAuthProfileStoreForAgent(effectiveOptions.inheritedAuthDir, effectiveOptions), store, { preserveBaseRuntimeExternalProfiles: true }));
}
/** Whether an agent dir resolves to the shared main auth-profile owner. */
function isSharedMainAuthProfileAgentDir(agentDir) {
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	if (!effectiveAgentDir) return true;
	const mainAgentDir = resolveRuntimeAuthProfileAgentDir();
	const mainPath = mainAgentDir ? resolveAuthProfileDatabasePath(mainAgentDir) : resolveSharedAuthStorePath();
	return resolveAuthProfileDatabasePath(effectiveAgentDir) === mainPath;
}
/** Find a persisted credential in the scoped store, falling back to the main store. */
function findPersistedAuthProfileCredential(params) {
	if (isEnvOnlyAuthProfileRuntime()) return;
	const agentDir = resolveRuntimeAuthProfileAgentDir(params.agentDir);
	const requestedProfile = loadPersistedAuthProfileStore(agentDir)?.profiles[params.profileId];
	const scopedSharedStore = getScopedSharedAuthStore();
	if (scopedSharedStore) return requestedProfile ?? scopedSharedStore.profiles[params.profileId];
	if (requestedProfile || !agentDir) return requestedProfile;
	if (isSharedMainAuthProfileAgentDir(agentDir)) return requestedProfile;
	return loadPersistedAuthProfileStore(resolveRuntimeAuthProfileAgentDir())?.profiles[params.profileId];
}
/** Resolve which agent dir owns a persisted profile, accounting for inherited OAuth. */
function resolvePersistedAuthProfileOwnerAgentDir(params) {
	if (isEnvOnlyAuthProfileRuntime()) return;
	const agentDir = resolveRuntimeAuthProfileAgentDir(params.agentDir);
	if (!agentDir) return;
	const requestedStore = loadPersistedAuthProfileStore(agentDir);
	if (isSharedMainAuthProfileAgentDir(agentDir)) return;
	const mainStore = loadPersistedAuthProfileStore(resolveRuntimeAuthProfileAgentDir());
	const requestedProfile = requestedStore?.profiles[params.profileId];
	if (requestedProfile) return shouldUseMainOwnerForLocalOAuthCredential({
		local: requestedProfile,
		main: mainStore?.profiles[params.profileId]
	}) ? void 0 : agentDir;
	return mainStore?.profiles[params.profileId] ? void 0 : agentDir;
}
/** Load the store shape used when applying local-only auth updates. */
function ensureAuthProfileStoreForLocalUpdate(agentDir) {
	if (isEnvOnlyAuthProfileRuntime()) return createEmptyAuthProfileStore();
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	const store = loadAuthProfileStoreForAgent(effectiveAgentDir, { syncExternalCli: false });
	const authPath = effectiveAgentDir ? resolveAuthProfileDatabasePath(effectiveAgentDir) : resolveSharedAuthStorePath();
	const mainAgentDir = resolveRuntimeAuthProfileAgentDir();
	const mainAuthPath = mainAgentDir ? resolveAuthProfileDatabasePath(mainAgentDir) : resolveSharedAuthStorePath();
	if (!effectiveAgentDir || authPath === mainAuthPath) return store;
	return mergeAuthProfileStores(loadAuthProfileStoreForAgent(void 0, {
		readOnly: true,
		syncExternalCli: false
	}), store, { preserveBaseRuntimeExternalProfiles: true });
}
/** Return the current runtime auth-profile snapshot for an agent dir. */
function getRuntimeAuthProfileStoreSnapshot(agentDir) {
	return getRuntimeAuthProfileStoreSnapshotCore(agentDir);
}
/** Return the lifecycle-published effective auth store without persisted fallback reads. */
function getPreparedRuntimeAuthProfileStoreSnapshot(agentDir, inheritedAuthDir) {
	return getPreparedRuntimeAuthProfileStoreSnapshotCore(agentDir, inheritedAuthDir);
}
/** Clear one runtime auth-profile snapshot. */
function clearRuntimeAuthProfileStoreSnapshot(agentDir) {
	return clearRuntimeAuthProfileStoreSnapshotCore(agentDir);
}
function saveAuthProfileStoreInTransaction(store, agentDir, options, database, owner, publishFromSuppliedStore = false) {
	const persistenceAgentDir = "agentId" in database ? agentDir : void 0;
	const savedAuthPath = owner.databasePath;
	const savesMainStore = savedAuthPath === owner.sharedDatabasePath;
	const loadedPersistedStores = loadPersistedAuthProfileStores(persistenceAgentDir, database, owner);
	const persistedStores = {
		...loadedPersistedStores,
		localStore: loadedPersistedStores.localStore ?? {
			version: 1,
			profiles: {},
			...loadPersistedAuthProfileState(persistenceAgentDir, database)
		}
	};
	const localStore = buildLocalAuthProfileStoreForSave({
		owner,
		store,
		agentDir: persistenceAgentDir,
		options,
		persistedStores
	});
	const existingRaw = readPersistedAuthProfileStoreRaw(persistenceAgentDir, database);
	const payload = preserveLegacyOAuthRefsOnSave({
		payload: buildPersistedAuthProfileSecretsStore(localStore),
		existingRaw
	});
	const existingProfiles = isRecord(existingRaw) && isRecord(existingRaw.profiles) ? existingRaw.profiles : {};
	const changedProfileIds = [.../* @__PURE__ */ new Set([...Object.keys(existingProfiles), ...Object.keys(payload.profiles)])].filter((profileId) => !isDeepStrictEqual(existingProfiles[profileId], payload.profiles[profileId]));
	const profileSetChanged = changedProfileIds.some((profileId) => Object.hasOwn(existingProfiles, profileId) !== Object.hasOwn(payload.profiles, profileId));
	const credentialsChanged = !isDeepStrictEqual(existingRaw, payload);
	const statePayload = buildPersistedAuthProfileState(localStore);
	const stateChanged = !isDeepStrictEqual(readPersistedAuthProfileStateRaw(persistenceAgentDir, database), statePayload);
	const suppliedRuntimeStore = publishFromSuppliedStore ? markRuntimePersistedProfiles(buildRuntimeAuthProfileStoreForSave({
		owner,
		store,
		agentDir: persistenceAgentDir,
		options,
		persistedStores
	}), localStore) : void 0;
	if (credentialsChanged) writePersistedAuthProfileStoreRaw(payload, persistenceAgentDir, database);
	if (stateChanged) writePersistedAuthProfileStateRaw(statePayload, persistenceAgentDir, database);
	const committedSharedStore = savesMainStore ? setRuntimeLocalProfileMetadata(markRuntimePersistedProfiles(localStore), listRuntimeLocalProfileIds(localStore)) : void 0;
	const publishRuntimeSnapshots = () => {
		const derivedSnapshots = savesMainStore ? listRuntimeAuthProfileStoreSnapshotsForSharedOwner(owner) : [];
		if (credentialsChanged || stateChanged) noteRuntimeAuthProfileStorePersistedMutation(persistenceAgentDir, {
			credentialsChanged,
			profileSetChanged,
			stateChanged,
			profileIds: changedProfileIds
		}, owner);
		try {
			assertAuthProfileMigrationStateAtDatabasePath(savedAuthPath);
		} catch (error) {
			for (const derived of derivedSnapshots) clearRuntimeAuthProfileStoreSnapshotAtDatabasePath(derived.databasePath, derived.agentDir);
			throw error;
		}
		if (suppliedRuntimeStore) {
			const existing = getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath(savedAuthPath);
			if (existing) setRuntimeAuthProfileStoreSnapshotAtDatabasePath(runtimeAuthProfileSnapshotSharesOwner(existing.owner, owner) ? materializeRuntimeAuthProfileStoreSnapshot(suppliedRuntimeStore, existing.store) : suppliedRuntimeStore, savedAuthPath, persistenceAgentDir, owner);
			if (!credentialsChanged && !stateChanged) return true;
		} else if (savesMainStore) {
			const existing = getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath(savedAuthPath);
			if (existing) setRuntimeAuthProfileStoreSnapshotAtDatabasePath(runtimeAuthProfileSnapshotSharesOwner(existing.owner, owner) ? materializeRuntimeAuthProfileStoreSnapshot(committedSharedStore, existing.store) : committedSharedStore, savedAuthPath, persistenceAgentDir, owner);
		} else refreshRuntimeAuthProfileStoreSnapshot(persistenceAgentDir, owner);
		let converged = true;
		for (const derived of derivedSnapshots) converged = convergeRuntimeAuthProfileStoreSnapshot(derived.databasePath, derived.agentDir, () => rebuildRuntimeAuthProfileStoreSnapshot(derived.agentDir, derived, {
			...owner,
			databasePath: derived.databasePath
		}, void 0, committedSharedStore, derived.store.runtimeLocalProfileIds)) && converged;
		return converged;
	};
	return {
		...persistenceAgentDir ? { agentDir: persistenceAgentDir } : {},
		databasePath: savedAuthPath,
		publish: publishRuntimeSnapshots
	};
}
/** Save the auth profile store plus sidecar state, preserving runtime overlay metadata. */
function saveAuthProfileStore(store, agentDir, options, database) {
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	if (database) {
		saveAuthProfileStoreWithPreparedOwner(store, effectiveAgentDir, options, database, resolveAuthProfileStoreOwner(database, getScopedAuthProfileEnv()));
		return;
	}
	let publishRuntimeSnapshots;
	runAuthProfileWriteTransaction(effectiveAgentDir, (transactionDatabase, owner) => {
		publishRuntimeSnapshots = saveAuthProfileStoreInTransaction(store, effectiveAgentDir, options, transactionDatabase, owner);
	}, {
		sharedStoreWrite: options?.sharedStoreWrite,
		env: getScopedAuthProfileEnv()
	});
	publishRuntimeSnapshotsAfterCommit(publishRuntimeSnapshots);
}
/** Core transaction callers carry the owner already selected before opening SQLite. */
function saveAuthProfileStoreWithPreparedOwner(store, agentDir, options, database, owner) {
	const publish = saveAuthProfileStoreInTransaction(store, agentDir, options, database, owner, true);
	const publishAfterCommit = () => {
		publishRuntimeSnapshotsAfterCommit(publish);
	};
	if (!deferAuthProfilePostCommitPublication(database, publishAfterCommit)) publishAfterCommit();
}
function assertAuthProfilePersistenceOwner(owner, agentDir, stateDir) {
	if (stateDir && path.resolve(resolveStateDir({
		...owner.env,
		OPENCLAW_STATE_DIR: stateDir
	})) !== path.resolve(resolveStateDir(owner.env))) throw new Error("explicit auth state directory does not match the captured owner");
	if ((agentDir ? resolveAuthProfileDatabasePath(agentDir) : owner.sharedDatabasePath) !== owner.databasePath) throw new Error("auth profile persistence snapshot belongs to another owner");
}
function captureRuntimeAuthProfileStorePersistenceSnapshot(owner) {
	const capturedAuthPath = owner.databasePath;
	const mainAuthPath = owner.sharedDatabasePath;
	return {
		runtimeCaptured: true,
		runtimeRevision: getRuntimeAuthProfileStoreSnapshotRevisionAtDatabasePath(capturedAuthPath),
		runtimeEntry: getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath(capturedAuthPath),
		derivedRuntimeStores: capturedAuthPath === mainAuthPath ? listRuntimeAuthProfileStoreSnapshotsForSharedOwner(owner).map((entry) => Object.assign(entry, { runtimeRevision: getRuntimeAuthProfileStoreSnapshotRevisionAtDatabasePath(entry.databasePath) })) : []
	};
}
function recordRuntimeAuthProfileStoreOwnership(owned, runtime) {
	owned.runtimeCaptured = runtime.runtimeCaptured;
	if (runtime.runtimeRevision !== void 0) owned.runtimeRevision = runtime.runtimeRevision;
	if (runtime.runtimeEntry !== void 0) owned.runtimeEntry = runtime.runtimeEntry;
	if (runtime.derivedRuntimeStores !== void 0) owned.derivedRuntimeStores = runtime.derivedRuntimeStores;
}
function recordRuntimeAuthProfileStorePublicationEdge(owned, runtime) {
	if (runtime.runtimeRevision !== void 0) owned.runtimeRevisionBeforePublication = runtime.runtimeRevision;
	if (runtime.derivedRuntimeStores !== void 0) owned.derivedRuntimeRevisionsBeforePublication = runtime.derivedRuntimeStores.flatMap((entry) => typeof entry.runtimeRevision === "number" ? [{
		databasePath: entry.databasePath,
		agentDir: entry.agentDir,
		runtimeRevision: entry.runtimeRevision
	}] : []);
}
function replaceRuntimeAuthProfileStoreSnapshot(entry, agentDir, owner) {
	if (entry) {
		assertAuthProfileMigrationStateAtDatabasePath(entry.databasePath);
		if (entry.owner.kind === "resolved") assertAuthProfileMigrationStateAtDatabasePath(entry.owner.sharedDatabasePath);
		restoreOwnedRuntimeAuthProfileStoreSnapshot(entry, agentDir);
		return;
	}
	clearRuntimeAuthProfileStoreSnapshotAtDatabasePath(owner.databasePath, agentDir);
}
function refreshRuntimeAuthProfileStoreSnapshot(agentDir, owner) {
	const existing = getOwnedRuntimeAuthProfileStoreSnapshotAtDatabasePath(owner.databasePath);
	if (!existing) return;
	rebuildRuntimeAuthProfileStoreSnapshot(agentDir, existing, owner);
}
function rebuildRuntimeAuthProfileStoreSnapshot(agentDir, existing, owner, predecessor, inheritedStore, capturedLocalProfileIds) {
	const isShared = owner.databasePath === owner.sharedDatabasePath;
	const candidates = "env" in owner ? captureRuntimeAuthProfileLegacyCandidates(isShared ? void 0 : agentDir, owner.env) : runtimeAuthProfileSnapshotSharesOwner(existing.owner, owner) ? existing.legacyCandidates : void 0;
	let refreshed;
	try {
		refreshed = loadRuntimeAuthProfileOwnerSnapshot(owner, {
			candidates,
			inheritedStore
		});
	} catch (err) {
		if (!inheritedStore || err instanceof AuthProfileMigrationRequiredError) throw err;
		const localProfileIds = new Set(capturedLocalProfileIds);
		const localStore = cloneAuthProfileStore(existing.store);
		localStore.profiles = Object.fromEntries(Object.entries(localStore.profiles).filter(([profileId]) => localProfileIds.has(profileId)));
		pruneAuthProfileStoreReferences(localStore, localProfileIds);
		refreshed = mergeLocalAuthProfileStoreWithInheritedStore(localStore, inheritedStore);
		authProfilesLog.warn("derived auth profile snapshot refresh failed; preserving captured local profiles", { err });
	}
	if (!runtimeAuthProfileSnapshotSharesOwner(existing.owner, owner)) {
		setRuntimeAuthProfileStoreSnapshotAtDatabasePath(refreshed, owner.databasePath, agentDir, owner, candidates);
		return;
	}
	const currentMaterialized = preserveResolvedSecretBackedCredentials({
		next: refreshed,
		existing: existing.store
	});
	setRuntimeAuthProfileStoreSnapshotAtDatabasePath(mergeRuntimeExternalProfileReferences({
		next: predecessor ? preserveResolvedSecretBackedCredentials({
			next: currentMaterialized,
			existing: predecessor
		}) : currentMaterialized,
		existing: existing.store
	}), owner.databasePath, agentDir, owner, candidates);
}
/** Capture both persisted auth rows under one database lock. */
function captureAuthProfileStorePersistenceSnapshot(agentDir, options = {}) {
	const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
	return runAuthProfileWriteTransaction(effectiveAgentDir, (database, owner) => {
		return {
			owner,
			credentialsRaw: readPersistedAuthProfileStoreRaw(effectiveAgentDir, database),
			stateRaw: readPersistedAuthProfileStateRaw(effectiveAgentDir, database),
			...captureRuntimeAuthProfileStorePersistenceSnapshot(owner)
		};
	}, {
		...options,
		env: options.env ?? (options.stateDir ? void 0 : getScopedAuthProfileEnv())
	});
}
/**
* Commit only while both persisted auth rows still match the captured baseline.
* The caller claims `owned` before publishing because publication is fallible.
*/
function saveAuthProfileStoreIfPersistenceSnapshotMatches(params) {
	const agentDir = resolveRuntimeAuthProfileAgentDir(params.agentDir);
	assertAuthProfilePersistenceOwner(params.snapshot.owner, agentDir, params.stateDir);
	let publishRuntimeSnapshots;
	const owned = runAuthProfileWriteTransaction(agentDir, (database, owner) => {
		if (params.snapshot.owner.databasePath !== database.path) throw new Error("auth profile persistence snapshot belongs to another database");
		const currentCredentials = readPersistedAuthProfileStoreRaw(agentDir, database);
		const currentState = readPersistedAuthProfileStateRaw(agentDir, database);
		if (!isDeepStrictEqual(currentCredentials, params.snapshot.credentialsRaw) || !isDeepStrictEqual(currentState, params.snapshot.stateRaw)) throw new Error("auth profile store changed after secrets apply captured it");
		const runtimeAtSaveEdge = captureRuntimeAuthProfileStorePersistenceSnapshot(owner);
		const derivedRuntimeRevisionsAtSaveEdge = runtimeAtSaveEdge.derivedRuntimeStores?.flatMap((entry) => typeof entry.runtimeRevision === "number" ? [{
			databasePath: entry.databasePath,
			agentDir: entry.agentDir,
			runtimeRevision: entry.runtimeRevision
		}] : []);
		publishRuntimeSnapshots = saveAuthProfileStoreInTransaction(params.store, agentDir, params.options, database, owner);
		return {
			owner,
			credentialsRaw: readPersistedAuthProfileStoreRaw(agentDir, database),
			stateRaw: readPersistedAuthProfileStateRaw(agentDir, database),
			runtimeCaptured: false,
			runtimeRevisionAtSaveEdge: runtimeAtSaveEdge.runtimeRevision,
			derivedRuntimeRevisionsAtSaveEdge
		};
	}, { env: params.snapshot.owner.env });
	return {
		owned,
		publishRuntimeSnapshots: () => {
			if (!publishRuntimeSnapshots) return true;
			const publication = publishRuntimeSnapshots;
			return publishRuntimeSnapshotsAfterCommit({
				...publication,
				publish: () => {
					const owner = owned.owner;
					recordRuntimeAuthProfileStorePublicationEdge(owned, captureRuntimeAuthProfileStorePersistenceSnapshot(owner));
					const converged = publication.publish();
					recordRuntimeAuthProfileStoreOwnership(owned, captureRuntimeAuthProfileStorePersistenceSnapshot(owner));
					return converged;
				}
			});
		}
	};
}
function reconcileRuntimeAuthProfileStorePersistenceSnapshot(params) {
	if (!params.snapshot.runtimeCaptured || !params.owned.runtimeCaptured) return true;
	const rowsFullyOwned = params.credentialsOwned && params.stateOwned;
	const rowsRestored = params.credentialsRestored || params.stateRestored;
	const reconcileOne = (databasePath, agentDir, snapshotEntry, snapshotRuntimeRevision, runtimeRevisionAtSaveEdge, runtimeRevisionBeforePublication, ownedEntry, ownedRuntimeRevision, currentEntry, currentRuntimeRevision) => convergeRuntimeAuthProfileStoreSnapshot(databasePath, agentDir, () => {
		if (rowsFullyOwned && typeof snapshotRuntimeRevision === "number" && typeof runtimeRevisionAtSaveEdge === "number" && typeof runtimeRevisionBeforePublication === "number" && typeof ownedRuntimeRevision === "number" && snapshotRuntimeRevision === runtimeRevisionAtSaveEdge && runtimeRevisionAtSaveEdge === runtimeRevisionBeforePublication && currentRuntimeRevision === ownedRuntimeRevision && isDeepStrictEqual(currentEntry?.store, ownedEntry?.store) && isDeepStrictEqual(currentEntry?.owner, ownedEntry?.owner)) replaceRuntimeAuthProfileStoreSnapshot(snapshotEntry, agentDir, {
			...params.owner,
			databasePath
		});
		else if (rowsRestored && currentEntry) {
			const runtimeOwner = currentEntry.owner.kind === "resolved" ? currentEntry.owner : runtimeAuthProfileSnapshotSharesOwner(currentEntry.owner, params.owner) ? params.owner : void 0;
			if (!runtimeOwner) return;
			rebuildRuntimeAuthProfileStoreSnapshot(agentDir, currentEntry, {
				databasePath,
				sharedDatabasePath: runtimeOwner.sharedDatabasePath,
				location: runtimeOwner.location
			}, snapshotEntry && runtimeAuthProfileSnapshotSharesOwner(snapshotEntry.owner, runtimeOwner) ? snapshotEntry.store : void 0);
		}
	});
	const restoredAuthPath = params.owner.databasePath;
	const mainAuthPath = params.owner.sharedDatabasePath;
	const currentRuntimeStores = new Map(params.currentRuntimeStores.map((entry) => [entry.databasePath, entry]));
	let converged = reconcileOne(restoredAuthPath, params.agentDir, params.snapshot.runtimeEntry, params.snapshot.runtimeRevision, params.owned.runtimeRevisionAtSaveEdge, params.owned.runtimeRevisionBeforePublication, params.owned.runtimeEntry, params.owned.runtimeRevision, currentRuntimeStores.get(restoredAuthPath), params.currentRuntimeRevision);
	if (restoredAuthPath !== mainAuthPath) return converged;
	const snapshotDerived = new Map((params.snapshot.derivedRuntimeStores ?? []).map((entry) => [entry.databasePath, entry]));
	const ownedDerived = new Map((params.owned.derivedRuntimeStores ?? []).map((entry) => [entry.databasePath, entry]));
	const saveEdgeDerivedRevisions = new Map((params.owned.derivedRuntimeRevisionsAtSaveEdge ?? []).map((entry) => [entry.databasePath, entry.runtimeRevision]));
	const publicationEdgeDerivedRevisions = new Map((params.owned.derivedRuntimeRevisionsBeforePublication ?? []).map((entry) => [entry.databasePath, entry.runtimeRevision]));
	for (const [pathname, currentEntry] of currentRuntimeStores) {
		if (pathname === mainAuthPath) continue;
		const snapshotEntry = snapshotDerived.get(pathname);
		const ownedEntry = ownedDerived.get(pathname);
		converged = reconcileOne(pathname, currentEntry.agentDir, snapshotEntry, snapshotEntry?.runtimeRevision, saveEdgeDerivedRevisions.get(pathname), publicationEdgeDerivedRevisions.get(pathname), ownedEntry, ownedEntry?.runtimeRevision, currentEntry, currentEntry.runtimeRevision) && converged;
	}
	return converged;
}
/** Restore each persisted row and runtime snapshot only while apply still owns it. */
function restoreAuthProfileStorePersistenceSnapshot(snapshot, owned, agentDir, options = {}) {
	assertAuthProfilePersistenceOwner(owned.owner, agentDir, options.stateDir);
	if (snapshot.owner.databasePath !== owned.owner.databasePath || snapshot.owner.sharedDatabasePath !== owned.owner.sharedDatabasePath) throw new Error("auth profile rollback snapshots belong to different owners");
	let credentialsOwned = false;
	let stateOwned = false;
	let credentialsRestored = false;
	let stateRestored = false;
	let publishRuntimeSnapshots;
	runAuthProfileWriteTransaction(agentDir, (database, owner) => {
		if (owned.owner.databasePath !== database.path) throw new Error("auth profile rollback belongs to another database");
		const existingRaw = readPersistedAuthProfileStoreRaw(agentDir, database);
		const existingState = readPersistedAuthProfileStateRaw(agentDir, database);
		credentialsOwned = isDeepStrictEqual(existingRaw, owned.credentialsRaw);
		stateOwned = isDeepStrictEqual(existingState, owned.stateRaw);
		const beforeProfiles = isRecord(existingRaw) && isRecord(existingRaw.profiles) ? existingRaw.profiles : {};
		const restoredProfiles = isRecord(snapshot.credentialsRaw) && isRecord(snapshot.credentialsRaw.profiles) ? snapshot.credentialsRaw.profiles : {};
		const changedProfileIds = [.../* @__PURE__ */ new Set([...Object.keys(beforeProfiles), ...Object.keys(restoredProfiles)])].filter((profileId) => !isDeepStrictEqual(beforeProfiles[profileId], restoredProfiles[profileId]));
		const profileSetChanged = changedProfileIds.some((profileId) => Object.hasOwn(beforeProfiles, profileId) !== Object.hasOwn(restoredProfiles, profileId));
		credentialsRestored = credentialsOwned && !isDeepStrictEqual(existingRaw, snapshot.credentialsRaw);
		stateRestored = stateOwned && !isDeepStrictEqual(existingState, snapshot.stateRaw);
		if (credentialsRestored) if (snapshot.credentialsRaw === null) deletePersistedAuthProfileStoreRaw(agentDir, database);
		else writePersistedAuthProfileStoreRaw(snapshot.credentialsRaw, agentDir, database);
		if (stateRestored) writePersistedAuthProfileStateRaw(snapshot.stateRaw, agentDir, database);
		publishRuntimeSnapshots = {
			...agentDir ? { agentDir } : {},
			databasePath: owner.databasePath,
			publish: () => {
				const currentRuntimeStores = [...listOwnedRuntimeAuthProfileStoreSnapshots().filter((entry) => entry.databasePath === owner.databasePath), ...owner.databasePath === owner.sharedDatabasePath ? listRuntimeAuthProfileStoreSnapshotsForSharedOwner(owner) : []].map((entry) => Object.assign(entry, { runtimeRevision: getRuntimeAuthProfileStoreSnapshotRevisionAtDatabasePath(entry.databasePath) }));
				const currentRuntimePath = owner.databasePath;
				const currentRuntimeRevision = getRuntimeAuthProfileStoreSnapshotRevisionAtDatabasePath(currentRuntimePath);
				if (credentialsRestored || stateRestored) noteRuntimeAuthProfileStorePersistedMutation(agentDir, {
					credentialsChanged: credentialsRestored,
					profileSetChanged: credentialsRestored && profileSetChanged,
					stateChanged: stateRestored,
					profileIds: credentialsRestored ? changedProfileIds : []
				}, owner);
				return reconcileRuntimeAuthProfileStorePersistenceSnapshot({
					owner,
					snapshot,
					owned,
					agentDir,
					credentialsOwned,
					stateOwned,
					credentialsRestored,
					stateRestored,
					currentRuntimeStores,
					currentRuntimeRevision
				});
			}
		};
	}, { env: owned.owner.env });
	publishRuntimeSnapshotsAfterCommit(publishRuntimeSnapshots);
}
//#endregion
export { withAuthProfileStoreAgentDir as C, resolveAuthProfilePortability as D, isAuthProfileCredentialPortableForAgentCopy as E, updateAuthProfileStoreWithLock as S, buildPortableAuthProfileStoreForAgentCopy as T, resolveRuntimeAuthProfileAgentDir as _, ensureAuthProfileStoreWithoutExternalProfiles as a, saveAuthProfileStoreIfPersistenceSnapshotMatches as b, getRuntimeAuthProfileStoreSnapshot as c, loadAuthProfileStore as d, loadAuthProfileStoreForRuntime as f, resolvePersistedAuthProfileOwnerAgentDir as g, preserveResolvedSecretBackedCredentials as h, ensureAuthProfileStoreForLocalUpdate as i, isInheritedMainOAuthCredential as l, loadAuthProfileStoreWithoutExternalProfiles as m, clearRuntimeAuthProfileStoreSnapshot as n, findPersistedAuthProfileCredential as o, loadAuthProfileStoreForSecretsRuntime as p, ensureAuthProfileStore as r, getPreparedRuntimeAuthProfileStoreSnapshot as s, captureAuthProfileStorePersistenceSnapshot as t, isSharedMainAuthProfileAgentDir as u, restoreAuthProfileStorePersistenceSnapshot as v, withEnvOnlyAuthProfileStore as w, saveAuthProfileStoreWithPreparedOwner as x, saveAuthProfileStore as y };
