/**
 * CredentialStore implementation backed by auth.json.
 * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.
 */
import type { ApiKeyCredential, AuthOperationOptions, Credential, CredentialInfo, CredentialStore, OAuthAuth, OAuthCredential, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
import { type CredentialKind } from "@earendil-works/pi-ai/auth/pool/kinds";
import { type CredentialSlot } from "@earendil-works/pi-ai/auth/pool/slots";
import { type AuthStoreLoadError } from "./auth-store-load-error.ts";
type AuthStorageData = Record<string, Credential>;
/** A credential problem the user should see once per change: `id` changes when the problem does. */
export type AuthNotice = {
    readonly id: string;
    readonly provider: string;
    readonly message: string;
    /** Shown at every start while the problem lasts, instead of once per change. */
    readonly repeats?: boolean;
};
export type CredentialReplacement = {
    readonly replaced: CredentialKind;
    readonly backupPath?: string;
};
/** What a login that replaced a credential of the other kind tells the user (senpi#3448, #3486). */
export declare function describeCredentialReplacement(provider: string, replacement: CredentialReplacement): string;
export type AuthCredential = Credential;
export type { ApiKeyCredential, OAuthCredential };
export type AuthStatus = {
    configured: boolean;
    source?: "stored" | "runtime" | "environment" | "fallback" | "models_json_key" | "models_json_command";
    label?: string;
};
export interface GetApiKeyOptions {
    includeFallback?: boolean;
}
type LockResult<T> = {
    result: T;
    next?: string;
};
/**
 * Outcome of a synchronous store read. `busy` means the lock stayed held past the sync
 * budget, so the in-memory credentials are a fallback rather than the store's contents;
 * `failed` is any other read error (the last valid snapshot is kept, as before).
 */
export type AuthReloadResult = "loaded" | "busy" | "failed";
export interface AuthStorageBackend extends Pick<CredentialStore, "withRefreshLock"> {
    withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
    withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>, options?: AuthOperationOptions): Promise<T>;
}
export declare class FileAuthStorageBackend implements AuthStorageBackend {
    private authPath;
    constructor(authPath?: string);
    private ensureParentDir;
    private ensureFileExists;
    /**
     * Atomic credential write: stage a 0o600 temp file beside the store and
     * rename it over the target. An existing store may carry an
     * administrator-set mode; it is copied onto the temp before the rename, so
     * preservation matches the previous in-place write (whose mode applied only
     * on creation) and the staged bytes are never wider than the file already
     * was. Cross-process writers are serialized by the proper-lockfile lock the
     * caller already holds, so the pid-suffixed temp cannot collide; a crashed
     * write leaves at worst a 0o600 temp behind.
     */
    private writeAuthFile;
    private acquireLockSyncWithRetry;
    withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
    private acquireLockAsync;
    withRefreshLock<T>(providerId: string, slotName: string, fn: (signal: AbortSignal) => Promise<T>, options?: AuthOperationOptions): Promise<T>;
    /**
     * `writeAuthFile` for an async writer: on Windows a rename over a file another process holds open
     * fails with EPERM, EACCES or EBUSY until that handle closes, so wait it out between attempts,
     * within the async lock budget (#6849 review L4). Other errors, and every error elsewhere, throw.
     */
    private writeAuthFileWhenFree;
    withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>, options?: AuthOperationOptions): Promise<T>;
}
export declare class ReadOnlyAuthStorage implements CredentialStore {
    private readonly authPath;
    private data;
    constructor(authPath?: string);
    private load;
    read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
    readSlot(providerId: string, slotName: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
    list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;
    modify(_providerId: string, _fn: (current: Credential | undefined) => Promise<Credential | undefined>, _options?: AuthOperationOptions): Promise<Credential | undefined>;
    delete(_providerId: string, _options?: AuthOperationOptions): Promise<void>;
}
export declare class InMemoryAuthStorageBackend implements AuthStorageBackend {
    private value;
    private asyncChain;
    withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
    withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>, options?: AuthOperationOptions): Promise<T>;
}
/**
 * Credential storage backed by a JSON file.
 */
export declare class AuthStorage implements CredentialStore {
    readonly withRefreshLock?: CredentialStore["withRefreshLock"];
    private data;
    private readonly runtimeOverrides;
    private readonly extensionOAuthProviders;
    private errors;
    private readonly reportedMigrationSkips;
    private notices;
    private readonly seenInMemory;
    private readonly takenNotices;
    private readonly replacements;
    private storage;
    private authPath;
    private readState;
    private busyReads;
    private dataLoaded;
    private dataFromBusyRead;
    private loadError;
    private constructor();
    static create(authPath?: string): AuthStorage;
    getStoragePath(): string | undefined;
    static fromStorage(storage: AuthStorageBackend): AuthStorage;
    static inMemory(data?: AuthStorageData): AuthStorage;
    private parseStorageData;
    /**
     * Reports whether the parse healed poisoned pool slots or moved legacy
     * provider keys, so a load can write the result back exactly once. Repair
     * runs FIRST, while the entry still sits under its legacy key, so poisoned
     * sentinel slots heal with old-key derivation semantics; the sentinel
     * matcher accepts legacy materials too, so a later load of an already
     * migrated credential heals the same way.
     */
    private parseStorageContent;
    private recordError;
    /**
     * Timestamped 0o600 copy of the pre-migration bytes, written inside the
     * held store lock before the migrated document replaces them. A migration
     * re-run after a crash between backup and rewrite writes another backup;
     * the loop suffix keeps same-millisecond names from overwriting each other.
     */
    private backupAuthFile;
    private updateReadState;
    /** The shared read state holds the store's current contents: this instance answers from it again. */
    private adoptReadState;
    /** A sync write that parsed and saved the locked store proves it loads again. */
    private writeLocked;
    /**
     * Reload credentials from storage.
     */
    reload(): AuthReloadResult;
    /**
     * True while the store has never loaded because every read found it locked, so the
     * in-memory credentials are not the store's: empty, or auth.json as `readWhileBusy()` read it
     * without the lock; `reload()` retries. A readable empty store, or a busy read after a
     * successful load, is not busy.
     */
    isCredentialStoreBusy(): boolean;
    /**
     * Why the store could not be loaded on its last read, or undefined once any read or write of this
     * instance finds it good again (senpi#4413). While set, the in-memory credentials are not the store's
     * contents; a store that cannot be read or parsed also refuses every write.
     */
    getLoadError(): AuthStoreLoadError | undefined;
    /**
     * Records a failed read; returns false when it repeats the load error already reported, so a store
     * that stays broken is not re-recorded on every status read that retries it.
     */
    private noteLoadFailure;
    /**
     * Monotonic count of reads (sync or async) that found the store locked before it ever
     * loaded and answered from credentials that are not the store's (empty, or read without the
     * lock). A change across an operation means its credentials may not reflect the store.
     */
    getBusyReadCount(): number;
    /**
     * While another process holds auth.json's lock and this store has never loaded, fills its credentials
     * from the file read without the lock, asynchronously and within the sync lock budget (#6841). Writes
     * replace the file by rename, so this sees a whole old or new store; it is never written back, and the
     * store stays busy, so the next read still takes the lock. A file that cannot be read in time, or does
     * not parse, leaves the credentials as they were. Like a locked read, the parse also refreshes the
     * store's notices and records a migration it had to skip.
     */
    readWhileBusy(): Promise<void>;
    private noteBusyFallback;
    /** Set a non-persistent API key used ahead of stored credentials. */
    setRuntimeApiKey(provider: string, apiKey: string): void;
    removeRuntimeApiKey(provider: string): void;
    get(provider: string): Credential | undefined;
    getProviderEnv(provider: string): Record<string, string> | undefined;
    /**
     * Stores a login. A login of the other kind replaces the provider's credential (senpi#3448); the
     * previous bytes are backed up first, and the replacement is returned and kept for
     * `takeReplacement`, so no credential disappears without the user being told where it went.
     */
    set(provider: string, credential: Credential): CredentialReplacement | undefined;
    /** The last replacement a login made for this provider, once; the caller shows it to the user. */
    takeReplacement(provider: string): CredentialReplacement | undefined;
    /** Credential notices not yet marked seen; a changed problem gets a new id and shows again. */
    pendingNotices(): ReadonlyArray<AuthNotice>;
    /**
     * Hands out each pending notice once per process, so a run that reports auth problems at several
     * points shows it once (senpi#3486). With `persistSeen`, the notices are also recorded as seen, so
     * the next launch stays quiet until the problem changes; a run nobody reads (RPC) leaves them pending.
     */
    takePendingNotices(options: {
        persistSeen: boolean;
    }): ReadonlyArray<AuthNotice>;
    /**
     * Records notices as shown, so the next launch stays quiet until the problem changes. Ids of
     * problems that no longer exist are dropped. A failed write never aborts startup: it is reported,
     * and the notice may be shown once more.
     */
    markNoticesSeen(ids: readonly string[]): void;
    private seenNoticesPath;
    private seenNoticeIds;
    private noteReplacement;
    remove(provider: string): void;
    listSlots(provider: string): CredentialSlot[];
    /** Adding a new slot is a sign-in and stamps a fresh `loginId`; updating an existing slot keeps it (senpi#4099). */
    setSlot(provider: string, slot: CredentialSlot): void;
    removeSlot(provider: string, name: string): void;
    has(provider: string): boolean;
    hasAuth(provider: string): boolean;
    getAuthStatus(provider: string): AuthStatus;
    getAll(): AuthStorageData;
    drainErrors(): Error[];
    private reloadFromStorageAsync;
    private reloadLockedAsync;
    private readLatestData;
    read(provider: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
    readSlot(provider: string, slotName: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
    modify(provider: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>, options?: AuthOperationOptions): Promise<Credential | undefined>;
    delete(provider: string, options?: AuthOperationOptions): Promise<void>;
    /** List credential metadata without resolving configured key values. */
    list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;
    getApiKey(providerId: string, options?: GetApiKeyOptions): Promise<string | undefined>;
    /**
     * Refreshes the stored OAuth credential when it has expired. It delegates to pi-ai's `refreshOAuthCredential`,
     * the path request-time resolution uses: the exchange runs under this store's per-account refresh lock and the
     * expiry is checked again once that lock is held, so callers in any process share one token exchange.
     */
    refreshOAuthCredential(providerId: string, oauth: OAuthAuth, signal?: AbortSignal): Promise<OAuthCredential | undefined>;
    registerOAuthProvider(providerId: string, oauth: OAuthAuth): void;
    unregisterOAuthProvider(providerId: string): void;
    getOAuthProviders(): Array<{
        id: string;
        name: string;
    }>;
    private oauthAuth;
    login(providerId: string, callbacks: OAuthLoginCallbacks): Promise<void>;
    logout(provider: string): void;
    private handleLegacyPrompt;
    private handleLegacyEvent;
}
/**
 * One-off synchronous read of a stored credential from an auth.json file,
 * without instantiating a store or resolving configured key values.
 */
export declare function readStoredCredential(providerId: string, authPath?: string): Credential | undefined;
//# sourceMappingURL=auth-storage.d.ts.map