UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

1,308 lines • 67.6 kB
import { dirname, join } from "node:path";
import { clampThinkingLevel, createModels, getCurrentTools, isModelType, lazyStream, ModelsError, normalizeContext, normalizeProviderId, providerNotConfiguredMessage, setWireIdentity, wrapStreamWithModelRecovery, } from "@earendil-works/pi-ai";
import * as builtinProviderCatalog from "@earendil-works/pi-ai/providers/all";
import { setOAuthPageBrand } from "@earendil-works/pi-ai/utils/oauth-page";
import { assertChatModel, assertClassifierModel, assertImageModel, classifierErrorResult, imageErrorResult, } from "@earendil-works/pi-ai/utils/model-operations";
import { APP_NAME, BRAND, getAgentDir } from "../config.js";
import { operationSignal, raceWithAbortSignal } from "../utils/abort.js";
import { AuthStorage as DefaultAuthStorage } from "./auth-storage.js";
import { envValue } from "./brand.js";
import { signOutClaudeCliSlotsForLogout } from "./credential-accounts-logout.lazy.js";
import { discoverEnvSlots } from "./credential-pool/env-slots.js";
import { emitProviderAccountsChanged } from "./extensions/builtin/anthropic-subscription/account-events.js";
import { retryOnceOnRejectedToken } from "./credential-pool/rejected-token-retry.js";
import { ModelConfig } from "./model-config.js";
import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.js";
import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveCompatibilityRequestHeaders, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js";
import { createProviderSemaphores } from "./provider-concurrency.js";
import { configuredAuthIsHeaderOnly } from "./provider-request-auth.js";
import { providerOriginOf } from "./provider-origin.js";
import { remoteCatalogServesProvider, withRemoteCatalog } from "./remote-catalog-provider.js";
import { RuntimeCredentials } from "./runtime-credentials.js";
import { ServedCredentials } from "./served-credentials.js";
import { limitAccountOf, subscriptionLimits, withLimitCapture } from "./subscription-limits/limit-store.js";
import { createVirtualModel, findLatestResponse, isVirtualModel, withVirtualModels, } from "./virtual-models.js";
/** Sessions whose active ChatGPT account is remembered; older entries are dropped first. */
const MAX_ACTIVE_CREDENTIAL_SESSIONS = 256;
// The product's identity must ride outgoing requests. This lives here because the AI package
// is already part of this module's graph; the CLI bootstrap deliberately does not import it.
setWireIdentity(BRAND?.userAgent ?? APP_NAME);
setOAuthPageBrand({ name: APP_NAME, ...(BRAND?.logo ? { logo: BRAND.logo } : {}) });
/** Availability re-reads after a busy credential store: 250, 500, 1000, 2000, 4000 ms. */
const BUSY_AVAILABILITY_RETRY_LIMIT = 5;
const BUSY_AVAILABILITY_RETRY_BASE_MS = 250;
function mightHoldCredentialPool(providerId, credential, env, policySlots) {
    if (credential) {
        const accounts = Object.entries(credential).find(([key]) => key === "accounts")?.[1];
        if (providerId === "chatgpt-subscription" && credential.type === "oauth")
            return true;
        return (Array.isArray(accounts) && accounts.length > 1) || Object.keys(policySlots ?? {}).length > 0;
    }
    return discoverEnvSlots(providerId, env).length + Object.keys(policySlots ?? {}).length > 1;
}
/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */
export class CredentialSynchronizationError extends Error {
    constructor(providerId, operation, credential, options) {
        super(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);
        this.name = "CredentialSynchronizationError";
        this.providerId = providerId;
        this.operation = operation;
        this.credential = credential;
    }
}
function mergeHeaders(base, override) {
    if (!base && !override)
        return undefined;
    const merged = { ...base };
    for (const [name, value] of Object.entries(override ?? {})) {
        const lowerName = name.toLowerCase();
        for (const existingName of Object.keys(merged)) {
            if (existingName.toLowerCase() === lowerName)
                delete merged[existingName];
        }
        merged[name] = value;
    }
    return merged;
}
function withPayloadRequestMetadata(options, model) {
    if (!options.onPayload)
        return options;
    const onPayload = options.onPayload;
    return {
        ...options,
        onPayload: async (payload, providerModel) => await onPayload(payload, providerModel, {
            model,
            headers: options.headers ?? {},
        }),
    };
}
/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */
export class ModelRuntime {
    setSettingsManager(settingsManager) {
        if (this.settingsManager === settingsManager)
            return;
        this.unsubscribeProviderSettings?.();
        this.settingsManager = settingsManager;
        const resize = () => {
            for (const provider of this.getProviders()) {
                this.providerSemaphores.resize(provider.id, settingsManager.getProviderConcurrencyLimit(provider.id));
            }
        };
        this.unsubscribeProviderSettings = settingsManager.subscribeToProviderSettings(resize);
        resize();
    }
    getActiveCredentialAccount(providerId, sessionId) {
        return this.activeCredentialAccounts.get(`${providerId}\0${sessionId}`);
    }
    constructor(credentials, config, modelsPath, modelsStore, providers, modelNetworkEnabled, modelRefreshTimeoutMs, poolStatePath) {
        this.providerSemaphores = createProviderSemaphores((providerId) => this.settingsManager?.getProviderConcurrencyLimit(providerId) ?? Infinity);
        this.builtins = new Map();
        this.nativeExtensionProviders = new Map();
        this.extensionProviders = new Map();
        /** The extension behind each registration that named one (senpi#4328). */
        this.providerExtensionPaths = new Map();
        /** Virtual models by provider id, then model id. */
        this.virtualModels = new Map();
        this.compositionErrors = new Map();
        this.snapshot = {
            all: [],
            available: [],
            configuredProviders: new Set(),
            storedProviders: new Set(),
            auth: new Map(),
        };
        this.availabilityInitialized = false;
        this.availabilityRefreshSeq = 0;
        this.availabilityErrorSeq = 0;
        this.providerAvailabilitySeq = new Map();
        this.busyAvailabilityRetries = 0;
        this.credentialOperations = new Map();
        this.servedCredentials = new ServedCredentials();
        /**
         * Actual stored-slot attempts, scoped to the session rather than a predicted list winner. Bounded by recency:
         * sessions are never released to the runtime, and an evicted session is re-recorded on its next request.
         */
        this.activeCredentialAccounts = new Map();
        /** Providers whose stale generic-pool health was already retired in this process (senpi#2081). */
        this.outerSlotStateRetired = new Set();
        this.credentials = credentials;
        this.poolStatePath = poolStatePath;
        this.config = config;
        this.modelsPath = modelsPath;
        this.modelNetworkEnabled = modelNetworkEnabled;
        this.modelRefreshTimeoutMs = modelRefreshTimeoutMs;
        this.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));
        for (const [providerId, provider] of this.defaultBuiltins)
            this.builtins.set(providerId, provider);
        this.models = createModels({ credentials, modelsStore });
        this.rebuildProviders();
    }
    /**
     * The AuthStorage this runtime's providers register into, when it was built on one. A session
     * built on a shared runtime must read this same store, or extension OAuth providers are never
     * listed (senpi#3434).
     */
    get authStorage() {
        const store = this.credentials.backingStore;
        return store instanceof DefaultAuthStorage ? store : undefined;
    }
    static async create(options = {}) {
        const credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));
        const modelsPath = options.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), "models.json"));
        const config = await ModelConfig.load(modelsPath);
        const modelsStore = options.modelsStore ??
            (modelsPath
                ? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), "models-store.json"))
                : new InMemoryCodingAgentModelsStore());
        const builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();
        const providers = builtinProviderCatalog
            .builtinProviders()
            .map((provider) => provider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)
            ? provider
            : withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt));
        const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, envValue("OFFLINE") === undefined && options.allowModelNetwork === true, options.modelRefreshTimeoutMs ?? 15_000, options.agentDir
            ? join(options.agentDir, "credential-pool-state.json")
            : options.authPath
                ? join(dirname(options.authPath), "credential-pool-state.json")
                : undefined);
        runtime.rebuildProviders();
        if (options.settingsManager)
            runtime.setSettingsManager(options.settingsManager);
        const refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;
        const controller = refreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;
        const timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;
        const signal = controller
            ? options.signal
                ? AbortSignal.any([options.signal, controller.signal])
                : controller.signal
            : options.signal;
        try {
            if (options.refreshOnCreate !== false) {
                await runtime.refresh({ allowNetwork: refreshFromNetwork, signal });
            }
        }
        finally {
            if (timeout)
                clearTimeout(timeout);
        }
        return runtime;
    }
    /** Synchronous compatibility constructor for legacy ModelRegistry callers. */
    static createSync(options = {}) {
        const credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));
        const modelsPath = options.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), "models.json"));
        const config = ModelConfig.loadSync(modelsPath);
        const modelsStore = options.modelsStore ??
            (modelsPath
                ? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), "models-store.json"))
                : new InMemoryCodingAgentModelsStore());
        const providers = builtinProviderCatalog
            .builtinProviders()
            .map((provider) => provider.refreshModels || !remoteCatalogServesProvider(provider.id, options.catalogBaseUrl)
            ? provider
            : withRemoteCatalog(provider, options.catalogBaseUrl));
        const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, options.allowModelNetwork ?? false, options.modelRefreshTimeoutMs ?? 15_000, options.agentDir
            ? join(options.agentDir, "credential-pool-state.json")
            : options.authPath
                ? join(dirname(options.authPath), "credential-pool-state.json")
                : undefined);
        runtime.rebuildProviders();
        if (options.settingsManager)
            runtime.setSettingsManager(options.settingsManager);
        return runtime;
    }
    providerIds() {
        return new Set([
            ...this.builtins.keys(),
            ...this.nativeExtensionProviders.keys(),
            ...this.config.getProviderIds(),
            ...this.extensionProviders.keys(),
            ...this.virtualModels.keys(),
        ]);
    }
    /** Returns the provider without virtual models, or undefined when only virtual models define it. */
    recomposeProvider(rawProviderId) {
        // Read boundary (senpi#1989): compose under the canonical id so a legacy id
        // reaching this path (an extension registration, a stored overlay key) lands
        // on the same provider instead of composing a second, empty one.
        const providerId = normalizeProviderId(rawProviderId);
        if (this.config.isProviderDisabled(providerId)) {
            this.models.deleteProvider(providerId);
            this.compositionErrors.delete(providerId);
            return undefined;
        }
        const provider = this.composeProvider(providerId);
        const virtualModels = [...(this.virtualModels.get(providerId)?.values() ?? [])].map((entry) => entry.model);
        if (virtualModels.length > 0)
            this.models.setProvider(withVirtualModels(providerId, provider, virtualModels));
        else if (provider)
            this.models.setProvider(provider);
        else
            this.models.deleteProvider(providerId);
        return provider;
    }
    /** The provider without virtual models, or undefined when nothing defines it. */
    composeProvider(providerId) {
        const base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);
        const extension = this.extensionProviders.get(providerId);
        if (!this.config.getProvider(providerId) && !extension) {
            // No overlays: use the builtin untouched so its auth/login/stream behavior is exact.
            this.compositionErrors.delete(providerId);
            return base;
        }
        try {
            // The reader runs only inside ambient auth resolution; composition itself stays credential-free.
            const storedProviderEnv = async (sourceId) => {
                const credential = await this.credentials.read(sourceId);
                return credential?.type === "api_key" && credential.env ? { ...credential.env } : undefined;
            };
            const provider = composeModelProvider(providerId, base, this.config, extension, { storedProviderEnv });
            this.compositionErrors.delete(providerId);
            return provider;
        }
        catch (error) {
            this.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));
            return base;
        }
    }
    rebuildProviders() {
        this.models.clearProviders();
        this.compositionErrors.clear();
        for (const providerId of this.providerIds())
            this.recomposeProvider(providerId);
        this.updateModelSnapshot();
    }
    updateModelSnapshot() {
        const all = [...this.models.getModels()];
        this.snapshot = {
            ...this.snapshot,
            all,
            available: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),
        };
    }
    async runAvailabilityRefresh(seq, errorSeq, signal) {
        const busyReadsBefore = this.credentials.busyReadCount();
        const providers = this.models.getProviders();
        const [available, checks, credentials] = await Promise.all([
            this.models.getAvailable(undefined, { signal }),
            Promise.all(providers.map(async (provider) => [
                provider.id,
                await this.models.checkAuth(provider.id, { signal }),
            ])),
            this.credentials.list({ signal }),
        ]);
        if (seq !== this.availabilityRefreshSeq)
            return;
        if (this.answeredFromBusyStore(busyReadsBefore, errorSeq))
            return;
        const auth = new Map(checks);
        const configuredProviders = new Set(checks
            .filter((entry) => entry[1] !== undefined)
            .map(([providerId]) => providerId));
        this.snapshot = {
            all: [...this.models.getModels()],
            available: [...available],
            configuredProviders,
            storedProviders: new Set(credentials.map((entry) => entry.providerId)),
            auth,
        };
        this.availabilityInitialized = true;
        this.busyAvailabilityRetries = 0;
        if (errorSeq === this.availabilityErrorSeq)
            this.availabilityError = undefined;
    }
    queueAvailabilityRefresh(signal) {
        const seq = ++this.availabilityRefreshSeq;
        for (const [providerId, providerSeq] of this.providerAvailabilitySeq) {
            this.providerAvailabilitySeq.set(providerId, providerSeq + 1);
        }
        const errorSeq = ++this.availabilityErrorSeq;
        const effectiveSignal = operationSignal(signal);
        return this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {
            if (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {
                this.availabilityError = error instanceof Error ? error.message : String(error);
            }
            throw error;
        });
    }
    async refreshProviderAvailability(providerId, signal) {
        // Invalidate any full availability pass that started before this credential change.
        ++this.availabilityRefreshSeq;
        const providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;
        this.providerAvailabilitySeq.set(providerId, providerSeq);
        const errorSeq = ++this.availabilityErrorSeq;
        const busyReadsBefore = this.credentials.busyReadCount();
        try {
            const [available, auth, credential] = await Promise.all([
                this.models.getAvailable(providerId, { signal }),
                this.models.checkAuth(providerId, { signal }),
                this.credentials.read(providerId, { signal }),
            ]);
            signal.throwIfAborted();
            if (this.providerAvailabilitySeq.get(providerId) !== providerSeq)
                return;
            if (this.answeredFromBusyStore(busyReadsBefore, errorSeq))
                return;
            const configuredProviders = new Set(this.snapshot.configuredProviders);
            const storedProviders = new Set(this.snapshot.storedProviders);
            const authByProvider = new Map(this.snapshot.auth);
            if (auth) {
                configuredProviders.add(providerId);
                authByProvider.set(providerId, auth);
            }
            else {
                configuredProviders.delete(providerId);
                authByProvider.delete(providerId);
            }
            if (credential)
                storedProviders.add(providerId);
            else
                storedProviders.delete(providerId);
            const all = [...this.models.getModels()];
            const availableById = new Map([...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [
                `${model.provider}\0${model.id}`,
                model,
            ]));
            this.snapshot = {
                all,
                available: all.flatMap((model) => availableById.get(`${model.provider}\0${model.id}`) ?? []),
                configuredProviders,
                storedProviders,
                auth: authByProvider,
            };
            if (errorSeq === this.availabilityErrorSeq)
                this.availabilityError = undefined;
        }
        catch (error) {
            if (this.providerAvailabilitySeq.get(providerId) === providerSeq &&
                errorSeq === this.availabilityErrorSeq &&
                !signal.aborted) {
                this.availabilityError = error instanceof Error ? error.message : String(error);
            }
            throw error;
        }
    }
    /**
     * A pass whose credential reads hit a locked store saw the cached snapshot (empty in a
     * fresh process), not the store. Such a pass must not publish availability or mark it
     * initialized; it records the contention so the next refresh re-reads the store.
     */
    answeredFromBusyStore(busyReadsBefore, errorSeq) {
        if (this.credentials.busyReadCount() === busyReadsBefore)
            return false;
        if (errorSeq === this.availabilityErrorSeq) {
            this.availabilityError = "Credential store was busy; availability will be re-read on the next refresh";
        }
        this.scheduleBusyAvailabilityRetry();
        return true;
    }
    /**
     * Re-read availability after a busy store, so a lock held during startup does not leave
     * every provider unconfigured until some later caller happens to refresh. Bounded: at most
     * {@link BUSY_AVAILABILITY_RETRY_LIMIT} attempts with doubling delays, reset by a published
     * pass; the timer never keeps the process alive.
     */
    scheduleBusyAvailabilityRetry() {
        if (this.busyAvailabilityRetryTimer !== undefined)
            return;
        if (this.busyAvailabilityRetries >= BUSY_AVAILABILITY_RETRY_LIMIT)
            return;
        const delayMs = BUSY_AVAILABILITY_RETRY_BASE_MS * 2 ** this.busyAvailabilityRetries;
        this.busyAvailabilityRetries += 1;
        this.busyAvailabilityRetryTimer = setTimeout(() => {
            this.busyAvailabilityRetryTimer = undefined;
            this.queueAvailabilityRefresh().catch(() => {
                // The pass records its own availability error; a later busy read schedules the next attempt.
            });
        }, delayMs);
        this.busyAvailabilityRetryTimer.unref?.();
    }
    getProviders() {
        return this.models.getProviders();
    }
    getProvider(providerId) {
        return this.models.getProvider(providerId);
    }
    getModels(providerId) {
        return this.models.getModels(providerId);
    }
    getModel(providerId, modelId) {
        return this.models.getModel(providerId, modelId);
    }
    getModelsOfType(type, providerId) {
        return this.models.getModelsOfType(type, providerId);
    }
    getModelOfType(type, providerId, modelId) {
        return this.models.getModelOfType(type, providerId, modelId);
    }
    getAllModels(providerId) {
        return this.models.getAllModels(providerId);
    }
    getAvailableOfType(type, providerId, options) {
        return this.models.getAvailableOfType(type, providerId, options);
    }
    getAllAvailable(providerId, options) {
        return this.models.getAllAvailable(providerId, options);
    }
    async checkAuth(providerId, options) {
        return this.models.checkAuth(providerId, options);
    }
    async getAvailable(providerId, options) {
        if (providerId) {
            const errorSeq = ++this.availabilityErrorSeq;
            try {
                const available = await this.models.getAvailable(providerId, options);
                if (errorSeq === this.availabilityErrorSeq)
                    this.availabilityError = undefined;
                return available;
            }
            catch (error) {
                if (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {
                    this.availabilityError = error instanceof Error ? error.message : String(error);
                }
                throw error;
            }
        }
        await this.queueAvailabilityRefresh(options?.signal);
        return this.snapshot.available;
    }
    getAvailableSnapshot() {
        return this.snapshot.available;
    }
    /** True only when the most recent availability refresh completed without error. */
    hasFreshAvailabilitySnapshot() {
        return this.availabilityInitialized && this.availabilityError === undefined;
    }
    hasAvailabilitySnapshot() {
        return this.availabilityInitialized;
    }
    /** Non-fatal models.json notices (e.g. renamed provider ids), rendered as warnings. */
    getWarnings() {
        return this.config.getWarnings();
    }
    getError() {
        const errors = [];
        const configError = this.config.getError();
        if (configError)
            errors.push(configError);
        for (const [providerId, error] of this.compositionErrors) {
            errors.push(`Provider "${providerId}": ${error}`);
        }
        if (this.availabilityError)
            errors.push(`Availability refresh: ${this.availabilityError}`);
        return errors.length > 0 ? errors.join("\n\n") : undefined;
    }
    getRegisteredProviderConfig(providerId) {
        return this.extensionProviders.get(providerId);
    }
    getRegisteredProviderIds() {
        return [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];
    }
    getRegisteredNativeProvider(providerId) {
        return this.nativeExtensionProviders.get(providerId);
    }
    getProviderOrigin(providerId) {
        return providerOriginOf({
            builtin: this.builtins.has(providerId),
            nativeExtension: this.nativeExtensionProviders.has(providerId),
            extension: this.extensionProviders.has(providerId) || this.virtualModels.has(providerId),
            extensionPath: this.providerExtensionPaths.get(providerId),
            modelsJsonPath: this.config.getProvider(providerId) === undefined ? undefined : this.modelsPath,
        });
    }
    noteExtensionPath(providerId, extensionPath) {
        if (extensionPath === undefined)
            this.providerExtensionPaths.delete(providerId);
        else
            this.providerExtensionPaths.set(providerId, extensionPath);
    }
    /** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */
    getCompatibilityRequestConfig(model) {
        return resolveCompatibilityRequestConfig(model, this.config.getProvider(model.provider), this.extensionProviders.get(model.provider));
    }
    /** @internal Configured headers for a request the provider could not authenticate. */
    getCompatibilityRequestHeaders(model, env) {
        return resolveCompatibilityRequestHeaders(model, this.config.getProvider(model.provider), this.extensionProviders.get(model.provider), env);
    }
    isUsingOAuth(providerId) {
        return this.snapshot.auth.get(providerId)?.type === "oauth";
    }
    isUsingSubscription(providerId) {
        return this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;
    }
    hasConfiguredAuth(providerId) {
        return this.snapshot.configuredProviders.has(providerId);
    }
    /**
     * Deterministic fallback-expansion gate declared by the provider's own
     * registration. Only a definitive `false` excludes; providers without the
     * hook, and hooks that throw, stay eligible so expansion never shrinks on
     * uncertainty.
     */
    isFallbackEligible(providerId) {
        const hook = this.extensionProviders.get(providerId)?.fallbackEligible;
        if (typeof hook !== "function")
            return true;
        try {
            return hook() !== false;
        }
        catch {
            return true;
        }
    }
    async getAuth(providerOrModel, overrides = {}) {
        if (typeof providerOrModel === "string")
            return this.models.getAuth(providerOrModel, overrides);
        const resolution = await this.models.getAuth(providerOrModel, overrides);
        if (!resolution)
            return undefined;
        const configuredHeaders = await resolveConfiguredModelHeaders(providerOrModel, this.config.getProvider(providerOrModel.provider), this.extensionProviders.get(providerOrModel.provider), { ...(resolution.env ?? {}), ...(overrides.env ?? {}) });
        return {
            ...resolution,
            auth: {
                ...resolution.auth,
                headers: mergeHeaders(resolution.auth.headers, configuredHeaders),
            },
        };
    }
    /**
     * Auth for a request a session sends outside the rotation stream (compaction, /btw, look-at,
     * cache keepalive). The key must belong to the account the session's own turns use, so a pooled
     * provider resolves the slot the stream would pick for this session; without a pool, or when
     * the stream would not rotate either, it is `getAuth(model)`.
     */
    async getSessionAuth(model, sessionId) {
        return this.getAuth(model, (await this.sessionSlotAuth(model, sessionId)) ?? {});
    }
    async sessionSlotAuth(model, sessionId) {
        // The stream's own synchronous admission check, so a provider the stream would not rotate costs
        // nothing beyond getAuth. Remote compaction's before_provider_request hook calls this on every
        // request to such a model; there a pooled provider pays one extra credential read and two slot
        // listings (each reads the pool's health state) before getAuth.
        if (!this.couldRotateCredentials(model, undefined))
            return undefined;
        const sources = await this.credentialRotationSources(model, undefined);
        if (!sources)
            return undefined;
        const { rotation } = await this.loadCredentialPool();
        const { rememberedHeadroomAccount, selectSessionSlot } = await import("./credential-pool/session-slot.js");
        const slots = await rotation.listRotationSlots(sources, {
            acquireLeases: false,
            modelId: this.getCompatibilityRequestConfig(model).upstreamModelId ?? model.id,
        });
        const pooled = sources.credential;
        const strategy = sources.policy?.accountStrategy;
        const useAffinity = strategy !== undefined || sources.policy?.affinity !== false;
        const now = Date.now();
        // The stream prefers an account with headroom and remembers that move per session (omo#9234), and
        // under round-robin holds this session's turn (omo#10146); reading the same limits, memory and turn
        // keeps this the stream's own first pick.
        const { roundRobinState } = await import("./credential-pool/round-robin-state.js");
        const roundRobin = strategy === "round-robin" ? roundRobinState.session(sources.providerId, sessionId) : undefined;
        const remembered = roundRobin?.account ??
            (useAffinity ? rememberedHeadroomAccount(sources.repository, sources.providerId, sessionId) : undefined);
        const slot = selectSessionSlot(slots, {
            affinityKey: sessionId,
            useAffinity,
            hasher: rotation.sha256SlotHasher,
            ...(pooled?.order === undefined ? {} : { order: pooled.order }),
            ...(strategy === undefined ? {} : { strategy }),
            ...(roundRobin === undefined ? {} : { roundRobinOffset: roundRobin.offset }),
            headroom: {
                providerId: sources.providerId,
                limits: subscriptionLimits.snapshot(),
                now,
                ...(remembered === undefined ? {} : { remembered }),
            },
        }, now);
        if (!slot)
            return undefined;
        return slot.lane === "env" ? { apiKey: slot.envKey } : { slotName: slot.name };
    }
    enqueueCredentialOperation(providerId, signal, task) {
        const previous = this.credentialOperations.get(providerId) ?? Promise.resolve();
        let markStarted;
        const started = new Promise((resolve) => {
            markStarted = resolve;
        });
        const operation = (async () => {
            await previous.catch(() => { });
            signal.throwIfAborted();
            markStarted?.();
            return task();
        })();
        const tail = operation.catch(() => { });
        this.credentialOperations.set(providerId, tail);
        void tail.then(() => {
            if (this.credentialOperations.get(providerId) === tail)
                this.credentialOperations.delete(providerId);
        });
        return raceWithAbortSignal(started, signal).then(() => operation);
    }
    async synchronizeCredentialState(providerId, operation, credential, signal) {
        try {
            signal.throwIfAborted();
            this.recomposeProvider(providerId);
            const compositionError = this.compositionErrors.get(providerId);
            if (compositionError)
                throw new Error(compositionError);
            const result = await this.models.refresh({
                allowNetwork: false,
                providers: [providerId],
                signal,
            });
            if (result.aborted)
                signal.throwIfAborted();
            const refreshError = result.errors.get(providerId);
            if (refreshError)
                throw refreshError;
            this.updateModelSnapshot();
            await this.refreshProviderAvailability(providerId, signal);
        }
        catch (cause) {
            throw new CredentialSynchronizationError(providerId, operation, credential, { cause });
        }
    }
    setRuntimeApiKey(providerId, apiKey, options = {}) {
        const signal = operationSignal(options.signal);
        return this.enqueueCredentialOperation(providerId, signal, async () => {
            this.credentials.setRuntimeApiKey(providerId, apiKey);
            await this.synchronizeCredentialState(providerId, "setRuntimeApiKey", { type: "api_key", key: apiKey }, signal);
        });
    }
    removeRuntimeApiKey(providerId, options = {}) {
        const signal = operationSignal(options.signal);
        return this.enqueueCredentialOperation(providerId, signal, async () => {
            this.credentials.removeRuntimeApiKey(providerId);
            await this.synchronizeCredentialState(providerId, "removeRuntimeApiKey", undefined, signal);
        });
    }
    listCredentials(options) {
        return this.credentials.list(options);
    }
    getProviderAuthStatus(providerId) {
        return this.resolveProviderAuth(providerId).status;
    }
    /** Whether the provider's only credential is a configured header: no configured key, and no key of its own. */
    providerAuthIsHeaderOnly(providerId) {
        return configuredAuthIsHeaderOnly(this.config.getProvider(providerId), this.extensionProviders.get(providerId), this.snapshot.auth.get(providerId));
    }
    /**
     * The provider's auth status plus whether it is a non-stored sign-in (#3537). `signIn` is set
     * only by the last branch, the provider's own check resolving `type: "oauth"`, so a runtime key,
     * a stored credential or a configured models.json/extension key always wins first.
     */
    resolveProviderAuth(providerId) {
        if (this.credentials.hasRuntimeApiKey(providerId)) {
            return { status: { configured: true, source: "runtime" }, signIn: false };
        }
        if (this.snapshot.storedProviders.has(providerId)) {
            return { status: { configured: true, source: "stored" }, signIn: false };
        }
        const configured = configuredRequestAuthStatus(this.config.getProvider(providerId), this.extensionProviders.get(providerId));
        if (configured)
            return { status: configured, signIn: false };
        const check = this.snapshot.auth.get(providerId);
        if (!check)
            return { status: { configured: false }, signIn: false };
        return {
            status: {
                configured: true,
                source: "environment",
                label: check.source,
                ...(check.ambient ? { ambient: true } : {}),
            },
            signIn: check.type === "oauth",
        };
    }
    async prepareRequest(model, options, slotAuth) {
        const provider = this.models.getProvider(model.provider);
        if (!provider)
            throw new ModelsError("provider", `Unknown provider: ${model.provider}`);
        const resolution = await this.getAuth(model, {
            apiKey: slotAuth?.apiKey ?? options?.apiKey,
            env: options?.env,
            signal: options?.signal,
            ...(slotAuth?.slotName === undefined ? {} : { slotName: slotAuth.slotName }),
            ...(slotAuth?.rejectedAccess === undefined ? {} : { rejectedAccess: slotAuth.rejectedAccess }),
        });
        if (!resolution)
            throw new ModelsError("auth", providerNotConfiguredMessage(model.provider));
        const { transformHeaders, ...rawProviderOptions } = options ?? {};
        const providerOptions = rawProviderOptions;
        let headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);
        if (transformHeaders)
            headers = await transformHeaders(headers ?? {});
        // Configured compatibility (extraBody, upstream model id) applies to chat models only.
        const compatibility = isModelType(model, "chat")
            ? this.getCompatibilityRequestConfig(model)
            : {};
        const extraBody = compatibility.extraBody || providerOptions.extraBody
            ? { ...compatibility.extraBody, ...providerOptions.extraBody }
            : undefined;
        const env = resolution.env || providerOptions.env
            ? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }
            : undefined;
        const upstreamModelId = compatibility.upstreamModelId;
        const requestModel = resolution.auth.baseUrl || upstreamModelId || ((resolution.auth.api || resolution.auth.compat) && isModelType(model, "chat"))
            ? {
                ...model,
                ...(upstreamModelId ? { id: upstreamModelId } : {}),
                ...(resolution.auth.baseUrl ? { baseUrl: resolution.auth.baseUrl } : {}),
                ...(resolution.auth.api && isModelType(model, "chat") ? { api: resolution.auth.api } : {}),
                ...(resolution.auth.compat && isModelType(model, "chat")
                    ? { compat: { ...model.compat, ...resolution.auth.compat } }
                    : {}),
            }
            : model;
        const rejectedTokenStatuses = provider.auth.oauth?.rejectedTokenStatuses;
        const storedOAuthAccess = resolution.source === "OAuth" && (slotAuth?.apiKey ?? providerOptions.apiKey) === undefined
            ? resolution.auth.apiKey
            : undefined;
        return {
            ...(rejectedTokenStatuses !== undefined && storedOAuthAccess !== undefined
                ? { rejectableAccess: storedOAuthAccess, rejectedTokenStatuses }
                : {}),
            provider,
            model: requestModel,
            options: {
                ...providerOptions,
                apiKey: slotAuth?.apiKey ?? providerOptions.apiKey ?? resolution.auth.apiKey,
                headers,
                extraBody,
                env,
            },
        };
    }
    /**
     * Rotation engages only for a provider that actually holds more than one
     * credential slot and only when nothing pins the request to one credential
     * (a runtime key or an explicit per-request apiKey). Every single-credential
     * user therefore keeps byte-identical request behavior.
     */
    loadCredentialPool() {
        this.credentialPoolModules ??= (async () => {
            const [rotation, stateStore] = await Promise.all([
                import("./credential-pool/rotation-stream.js"),
                import("./credential-pool/state-store.js"),
            ]);
            return {
                rotation,
                repository: new stateStore.CredentialSlotRepository(this.poolStatePath),
            };
        })();
        return this.credentialPoolModules;
    }
    /**
     * Fully synchronous admission check. A provider that cannot possibly hold a
     * pool must not even reach the async rotation path: awaiting an async method
     * costs a microtask hop, which would reorder an ordinary request's provider
     * call relative to the untouched `streamSimple` path.
     */
    couldRotateCredentials(model, options) {
        if (options?.apiKey !== undefined)
            return false;
        if (this.credentials.hasRuntimeApiKey(model.provider))
            return false;
        if (this.config.getProvider(model.provider)?.credentials?.rotation === false)
            return false;
        // A provider whose lane picks its own accounts has one owner of account selection: that lane (senpi#2081).
        if (this.ownsAccountSelection(model.provider))
            return false;
        const env = (name) => options?.env?.[name] ?? process.env[name];
        if (this.snapshot.storedProviders.has(model.provider))
            return true;
        const policySlots = this.config.getProvider(model.provider)?.credentials?.slots;
        return discoverEnvSlots(model.provider, env).length + Object.keys(policySlots ?? {}).length > 1;
    }
    ownsAccountSelection(providerId) {
        return this.extensionProviders.get(providerId)?.ownsAccountSelection === true;
    }
    /**
     * Health the generic pool recorded for a provider before its lane became the only owner of account
     * selection is retired before that provider's first request in this process. Older builds pinned the
     * lane's verdicts on these slots and left them blocked; an upgrade must heal them with no re-login
     * (senpi#2081). A busy state file is retried on the next request.
     */
    async retireOuterSlotState(providerId) {
        if (this.outerSlotStateRetired.has(providerId))
            return;
        const [{ repository }, { STORE_BUSY, writeHealthUnlessStoreBusy }] = await Promise.all([
            this.loadCredentialPool(),
            import("./credential-pool/health-write.js"),
        ]);
        const outcome = await writeHealthUnlessStoreBusy(`retire generic-pool health for ${providerId}`, () => repository.clearProvider(providerId));
        if (outcome !== STORE_BUSY)
            this.outerSlotStateRetired.add(providerId);
    }
    async credentialRotationSources(model, options) {
        const env = (name) => options?.env?.[name] ?? process.env[name];
        const credential = await this.credentials.read(model.provider, {
            signal: options?.signal,
        });
        const policy = this.config.getProvider(model.provider)?.credentials;
        if (!mightHoldCredentialPool(model.provider, credential, env, policy?.slots))
            return undefined;
        const pool = await this.loadCredentialPool();
        const sources = {
            providerId: model.provider,
            credential,
            env,
            repository: pool.repository,
            policy,
        };
        const slots = await pool.rotation.listRotationSlots(sources, { acquireLeases: false });
        return slots.length > 1 || (model.provider === "chatgpt-subscription" && credential?.type === "oauth")
            ? sources
            : undefined;
    }
    stream(model, context, options) {
        const transcript = normalizeContext(context);
        return lazyStream(model, async () => {
            assertChatModel(model);
            const streamOptions = options;
            if (this.ownsAccountSelection(model.provider))
                await this.retireOuterSlotState(model.provider);
            const sources = this.couldRotateCredentials(model, streamOptions)
                ? await this.credentialRotationSources(model, streamOptions)
                : undefined;
            if (sources) {
                const { rotation } = await this.loadCredentialPool();
                return rotation.streamWithCredentialRotation({
                    sources,
                    modelId: this.getCompatibilityRequestConfig(model).upstreamModelId ?? model.id,
                    ...(streamOptions?.affinityKey !== undefined
                        ? { affinityKey: streamOptions.affinityKey }
                        : streamOptions?.sessionId !== undefined
                            ? { affinityKey: streamOptions.sessionId }
                            : {}),
                    runAttempt: (slot) => this.attemptWithTokenRecovery(model, streamOptions, slot.lane === "env"
                        ? {
                            ...(slot.envKey === undefined ? {} : { apiKey: slot.envKey }),
                        }
                        : { slotName: slot.name }, (prepared) => prepared.provider.stream(prepared.model, transcript, withPayloadRequestMetadata(prepared.options, prepared.model)), transcript),
                });
            }
            return this.attemptWithTokenRecovery(model, streamOptions, undefined, (prepared) => prepared.provider.stream(prepared.model, transcript, withPayloadRequestMetadata(prepared.options, prepared.model)), transcript);
        });
    }
    /**
     * One provider request with the #2297 recovery: a stored OAuth token the provider
     * refuses before any output is re-exchanged once and the request re-sent.
     */
    attemptWithTokenRecovery(model, options, slotAuth, send, transcript) {
        return retryOnceOnRejectedToken(async (rejectedAccess) => {
            const prepared = await this.prepareRequest(model, options, rejectedAccess === undefined ? slotAuth : { ...slotAuth, rejectedAccess });
            const sessionId = options?.affinityKey ?? options?.sessionId;
            if (model.provider === "chatgpt-subscription" && slotAuth?.slotName !== undefined && sessionId !== undefined) {
                const key = `${model.provider}\0${sessionId}`;
                if (this.activeCredentialAccounts.get(key) !== slotAuth.slotName) {
                    this.activeCredentialAccounts.delete(key);
                    this.activeCredentialAccounts.set(key, slotAuth.slotName);
                    for (const oldest of this.activeCredentialAccounts.keys()) {
                        if (this.activeCredentialAccounts.size <= MAX_ACTIVE_CREDENTIAL_SESSIONS)
                            break;
                        this.activeCredentialAccounts.delete(oldest);
                    }
                    emitProviderAccountsChanged(model.provider);
                }
            }
            const capturing = {
                ...prepared,
                options: withLimitCapture(prepared.options, prepared.model.provider, limitAccountOf(slotAuth)),
            };
            const inner = await this.providerSemaphores.bracket(prepared.model.provider, prepared.options.signal, () => send(capturing));
            const stream = wrapStreamWithModelRecovery(inner, model, getCurrentTools(transcript.messages));
            this.servedCredentials.observe(stream.result(), {
                provider: prepared.model.provider,
                baseUrl: prepared.model.baseUrl,
                apiKey: prepared.options.apiKey,
            });
            return {
                stream,
                ...(prepared.rejectableAccess === undefined ? {} : { rejectableAccess: prepared.rejectableAccess }),
                ...(prepared.rejectedTokenStatuses === undefined
                    ? {}
                    : { rejectedTokenStatuses: prepared.rejectedTokenStatuses }),
            };
        });
    }
    complete(model, context, options) {
        return this.stream(model, context, options).result();
    }
    streamSimple(model, context, options) {
        const transcript = normalizeContext(context);
        if (isVirtualModel(model)) {
            // Requests outside the agent loop are routed here. Callers sized them before routing, so
            // cap the output budget to the routed model.
            return lazyStream(model, async () => {
                const route = await this.resolveModel(model, transcript.messages, {
                    reason: "direct",
                    thinkingLevel: options?.reasoning ?? "off",
                    signal: options?.signal,
                });
                const { maxTokens: limit } = route.model;
                const maxTokens = options?.maxTokens && limit > 0 ? Math.min(options.maxTokens, limit) : options?.maxTokens;
                const reasoning = route.thinkingLevel === "off" ? undefined : route.thinkingLevel;
                // Caller credentials were resolved for the virtual model's provider. Another provider
                // resolves its own, so they are not sent to the wrong vendor.
                const { apiKey, headers, env, ...rest } = options ?? {};
                const auth = route.model.provider === model.provider ? { apiKey, headers, env } : {};
                return this.streamSimple(route.model, context, { ...rest, ...auth, maxTokens, reasoning });
            });
        }
        return lazyStream(model, async () => {
            assertChatModel(model);
            const streamOptions = options;
            if (this.ownsAccountSelection(model.provider))
                await this.retireOuterSlotState(model.provider);
            const sources = this.couldRotateCredentials(model, streamOptions)
                ? await this.credentialRotationSources(model, streamOptions)
                : undefined;
            if (sources) {
                const { rotation } = await this.loadCredentialPool();
                return rotation.streamWithCredentialRotation({
                    sources,
                    modelId: this.getCompatibilityRequestConfig(model).upstreamModelId ?? model.id,
                    ...(streamOptions?.sessionId === undefined ? {} : { affinityKey: streamOptions.sessionId }),
                    runAttempt: (slot) => this.attemptWithTokenRecovery(model, streamOptions, slot.lane === "env" ? { apiKey: slot.envKey } : { slotName: slot.name }, (prepared) => prepared.provider.streamSimple(prepared.model, transcript, withPayloadRequestMetadata(prepared.options, prepared.model)), transcript),
                });
            }
            return this.attemptWithTokenRecovery(model, options, undefined, (prepared) => prepared.provider.streamSimple(prepared.model, transcript, withPayloadRequestMetadata(prepared.options, prepared.model)), transcript);
        });
    }
    /**
     * Resolve auth, headers, `extraBody`, env, and the upstream model id exactly as a
     * single-credential `streamSimple` request does, without sending it. The session-start
     * prompt-cache prewarm (senpi#2096) builds its request from this so its prefix matches
     * the first turn's.
     */
    async prepareSimpleRequest(model, options) {
        const prepared = await this.prepareRequest(model, options);
        return {
            model: prepared.model,
            options: withPayloadRequestMetadata(prepared.options, prepared.model),
        };
    }
    completeSimple(model, context, options) {
        return this.streamSimple(model, context, options).result();
    }
    streamDeferred(model, handle, options) {
        return lazyStream(model, async () => {
            assertChatModel(model);
            const prepared = await this.prepareRequest(model, options);
            if (!prepared.provider.fetchDeferred) {
                throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
            }
            return prepared.provider.fetchDeferred(prepared.model, handle, prepared.options);
        });
    }
    async fetchDeferred(model, handle, options) {
        return this.streamDeferred(model, handle, options).result();
    }
    async cancelDeferred(model, handle, options) {
        assertChatModel(model);
        const prepared = await this.prepareRequest(model, options);
        if (!prepared.provider.cancelDeferred) {
            throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
        }
        await prepared.provider.cancelDeferred(prepared.model, handle, prepared.options);
    }
    async generateImages(model, context, options) {
        try {
            assertImageModel(model);
            const prepared = await this.prepareRequest(model, options);
            if (!prepared.provider.generateImages) {
                throw new ModelsError("provider", `Provider ${model.provider} does not support image generation`);
            }
            return await prepared.provider.generateImages(prepared.model, context, prepared.options);
        }
        catch (error) {
            return imageErrorResult(model, error, options?.signal?.aborted);
        }
    }
    async classify(model, context, options) {
        try {
            assertClassifierModel(model);
            const prepared = await this.prepareRequest(model, options);
            if (!prepared.provider.classify) {
                throw new ModelsError("provider", `Provider ${model.provider} does not support classification`);
            }
            return await prepared.provider.classify(prepared.model, context, prepared.options);
        }
        catch (error) {
            return classifierErrorResult(model, error, options?.signal?.aborted);
        }
    }
    login(providerId, type, interaction, options) {
        const signal = operationSignal(interaction.signal);
        return this.enqueueCredentialOperation(providerId, signal, async () => {
            const store = this.credentials.backingStore;
            const before = await store.read(providerId, { signal });
            const credential = await this.models.login(providerId, type, { ...interaction, signal }, { ...options, appName: APP_NAME });
            if (this.poolStatePath !== undefined) {
                const { retireLoginSlotHealth } = await import("./credential-pool/login-health.js");
                await retireLoginSlotHealth(this.poolStatePath, providerId, before, await store.read(providerId, { signal }));
            }
            await this.synchronizeCredentialState(providerId, "login", credential, signal);
            // A fresh login is the remedy a usage-limit refusal names: holds sessions keep on this provider are stale.
            emitProviderAccountsChanged(providerId, "login");
            for (const key of this.activeCredentialAccounts.keys()) {
                if (key.startsWith(`${providerId}\0`))
                    this.activeCredentialAccounts.delete(key);
            }
            return credential;
        });
    }
    async logout(providerId, options = {}) {
        return (await this.logoutProvider(providerId, options)).revocation;
    }
    /**
     * {@link logout}, answering what the user should know: an Anthropic Subscription `claude-cli` account is signed out
     * of the Claude CLI's own store before the credential is deleted (senpi#4436), and `notices` names any account that
     * could not be signed out cleanly. `revocation` reports a ChatGPT OAuth remote revocation; `slotId` signs out one
     * stored account and keeps its registration and signed-in siblings.
     */
    logoutProvider(providerId, options = {}) {
        const signal = operationSignal(options.signal);
        return this.enqueueCredentialOperation(providerId, signal, async () => {
            const storage = this.authStorage;
            // With `slotId` only that account leaves the Claude CLI store; its signed-in siblings stay.
            const notices = storage === undefined
                ? []
                : await signOutClaudeCliSlotsForLogout(storage, providerId, process.env, signal, options.slotId);
            const result = await this.models.logout(providerId, { ...options, signal });
            const surviving = await this.credentials.read(providerId, { signal });
            await this.synchronizeCredentialState(providerId, "logout", surviving, signal);
            for (const key of this.activeCredentialAccounts.keys()) {
                if (key.startsWith(`${providerId}\0`))
                    this.activeCredentialAccounts.delete(key);
            }
            return result === undefined ? { notices } : { notices, revocation: result };
        });
    }
    async reloadConfig() {
        await this.refresh({ allowNetwork: this.modelNetworkEnabled });
    }
    async refresh(options = {}) {
        this.config = await ModelConfig.load(this.modelsPath);
        if (options.providers) {
            for (const providerId of new Set(options.providers))
                this.recomposeProvider(providerId);
            this.updateModelSnapshot();
        }
        else {
            this.rebuildProviders();
        }
        const refreshOptions = {
            ...options,
            allowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,
        };
        // Published pi-ai builds before ModelsStore returned void and accepted a provider ID.
        // The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.
        const result = (await this.models.refresh(refreshOptions)) ?? {
            aborted: refreshOptions.signal?.aborted ?? false,
            errors: new Map(),
        };
        const errors = new Map(result.errors);
        this.updateModelSnapshot();
        if (options.providers) {
            await Promise.all([...new Set(options.providers)].map(async (providerId) => {
                try {
                    await this.refreshProviderAvailability(providerId, operationSignal(options.signal));
                }
                catch (error) {
                    if (!options.signal?.aborted) {
                        errors.set(providerId, error instanceof Error ? error : new Error(String(error)));
                    }
                }
            }));
        }
        else {
            try {
                await this.queueAvailabilityRefresh(options.signal);
            }
            catch {
                // Availability errors are recorded by the latest pass; refreshed models remain usable.
            }
        }
        return {
            aborted: result.aborted || (options.signal?.aborted ?? false),
            errors,
        };
    }
    /**
     * Providers registered after startup missed the create() refresh. Load their catalogs
     * under the runtime network policy, bounded like startup, so newly registered models are
     * usable without a manual refresh. Offline policy restores from the store only and never
     * touches the network.
     */
    shouldSkipRegistrationRefresh(providerId) {
        return (this.hasFreshAvailabilitySnapshot() &&
            (this.nativeExtensionProviders.has(providerId) || this.extensionProviders.has(providerId)));
    }
    refreshAfterRegistration() {
        if (!this.modelNetworkEnabled)
            return this.refresh({ allowNetwork: false });
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), this.modelRefreshTimeoutMs);
        return this.refresh({
            allowNetwork: true,
            signal: controller.signal,
        }).finally(() => clearTimeout(timeout));
    }
    registerNativeProvider(provider, options) {
        if (!provider.id.trim())
            throw new Error("Provider id must not be empty.");
        const alreadyFresh = this.shouldSkipRegistrationRefresh(provider.id);
        this.extensionProviders.delete(provider.id);
        this.nativeExtensionProviders.set(provider.id, provider);
        this.noteExtensionPath(provider.id, options?.extensionPath);
        this.recomposeProvider(provider.id);
        const composedOAuth = this.models.getProvider(provider.id)?.auth.oauth;
        if (composedOAuth)
            this.credentials.registerOAuthProvider(provider.id, composedOAuth);
        else
            this.credentials.unregisterOAuthProvider(provider.id);
        this.updateModelSnapshot();
        this.markProvisionallyConfigured(provider.id, configuredRequestAuthStatus(this.config.getProvider(provider.id), undefined), provider.auth.oauth && !provider.auth.apiKey ? "oauth" : "api_key");
        if (alreadyFresh || options?.refresh === false) {
            return Promise.resolve({ aborted: false, errors: new Map() });
        }
        return this.refreshAfterRegistration();
    }
    /**
     * Mark a newly registered provider as configured when it has a stored credential or a configured
     * API key. Availability checks run asynchronously, and callers such as initial model selection
     * read the snapshot before they finish. The next availability pass replaces this entry.
     */
    markProvisionallyConfigured(providerId, configuredStatus, type) {
        if (!this.snapshot.storedProviders.has(providerId) && !configuredStatus?.configured)
            return;
        const configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);
        const auth = new Map(this.snapshot.auth);
        // Never clobber a real check result.
        if (!auth.get(providerId))
            auth.set(providerId, { type, source: "configured provider" });
        this.snapshot = {
            ...this.snapshot,
            auth,
            configuredProviders,
            available: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),
        };
    }
    registerProvider(providerId, config, options) {
        // Validate the incoming registration on its own, like the legacy registry:
        // a broken re-registration must throw without touching the stored config.
        validateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);
        const alreadyFresh = this.shouldSkipRegistrationRefresh(providerId);
        this.nativeExtensionProviders.delete(providerId);
        // Re-registration merges defined values over the previous registration and
        // preserves undefined ones, matching the legacy ModelRegistry contract.
        const previous = this.extensionProviders.get(providerId);
        const effective = { ...previous };
        for (const [key, value] of Object.entries(config)) {
            if (value !== undefined)
                effective[key] = value;
        }
        this.extensionProviders.set(providerId, effective);
        this.noteExtensionPath(providerId, options?.extensionPath);
        this.recomposeProvider(providerId);
        const composedOAuth = this.models.getProvider(providerId)?.auth.oauth;
        if (composedOAuth)
            this.credentials.registerOAuthProvider(providerId, composedOAuth);
        else
            this.credentials.unregisterOAuthProvider(providerId);
        this.updateModelSnapshot();
        this.markProvisionallyConfigured(providerId, configuredRequestAuthStatus(this.config.getProvider(providerId), effective), effective.oauth && !effective.apiKey ? "oauth" : "api_key");
        if (alreadyFresh || options?.refresh === false) {
            return Promise.resolve({ aborted: false, errors: new Map() });
        }
        return this.refreshAfterRegistration();
    }
    unregisterProvider(providerId) {
        this.extensionProviders.delete(providerId);
        this.nativeExtensionProviders.delete(providerId);
        this.providerExtensionPaths.delete(providerId);
        this.recomposeProvider(providerId);
        this.credentials.unregisterOAuthProvider(providerId);
        this.updateModelSnapshot();
        void this.refresh({ allowNetwork: false });
    }
    /**
     * Register a virtual model under `definition.provider`, which may also list physical models or
     * several virtual models. Re-registering the same provider and id replaces the virtual model.
     * Throws when the id belongs to a physical model of that provider.
     */
    registerVirtualModel(definition) {
        const { provider: providerId, id } = definition;
        if (!providerId.trim() || !id.trim())
            throw new Error("Virtual model provider and id must not be empty.");
        const existing = this.models.getModel(providerId, id);
        if (existing && !isVirtualModel(existing)) {
            throw new Error(`Virtual model ${providerId}/${id} conflicts with a physical model.`);
        }
        const models = this.virtualModels.get(providerId) ?? new Map();
        models.set(id, { model: createVirtualModel(definition), route: (request) => definition.route(request) });
        this.virtualModels.set(providerId, models);
        if (!this.recomposeProvider(providerId) && !this.snapshot.configuredProviders.has(providerId)) {
            // A provider of only virtual models needs no credentials. Mark it configured now: session
            // restore checks auth before the refresh below lands.
            const auth = new Map(this.snapshot.auth).set(providerId, { type: "api_key", source: "virtual" });
            const configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);
            this.snapshot = { ...this.snapshot, auth, configuredProviders };
        }
        this.updateModelSnapshot();
        void this.refresh({ allowNetwork: false });
    }
    unregisterVirtualModel(providerId, id) {
        const models = this.virtualModels.get(providerId);
        if (!models?.delete(id))
            return;
        if (models.size === 0)
            this.virtualModels.delete(providerId);
        this.recomposeProvider(providerId);
        this.updateModelSnapshot();
        void this.refresh({ allowNetwork: false });
    }
    /**
     * Ask a virtual model's router for the model and thinking level of one request. The router must
     * return a physical catalog model whose provider has credentials; the thinking level is clamped
     * to that model. Throws when routing fails.
     *
     * `previous` reports the latest successful response in `messages`. A retry passes the failed
     * response as `options.failed`; `messages` no longer contains it. `options.state` is the router
     * state stored by the caller, which also stores the returned state.
     */
    async resolveModel(model, messages, options) {
        const name = `Virtual model ${model.provider}/${model.id}`;
        const virtual = this.virtualModels.get(model.provider)?.get(model.id);
        if (!virtual)
            throw new Error(`${name} is not registered.`);
        const { failed, ...request } = options;
        const latest = findLatestResponse(messages);
        const previousModel = latest && this.getPhysicalModel(latest.provider, latest.model);
        // A failed routing attempt names the virtual model; there is no physical request to report.
        const failedModel = failed && this.getPhysicalModel(failed.provider, failed.model);
        const route = await virtual.route({
            ...request,
            model,
            previous: previousModel && { model: previousModel, thinkingLevel: latest?.thinkingLevel },
            failed: failedModel && failed && { model: failedModel, thinkingLevel: failed.thinkingLevel, message: failed },
            messages,
        });
        const target = this.getPhysicalModel(route.model.provider, route.model.id);
        const routed = `${name} routed to ${route.model.provider}/${route.model.id}`;
        if (!target)
            throw new Error(`${routed}, which is not a physical model.`);
        if (!this.hasConfiguredAuth(target.provider))
            throw new Error(`${routed}, which has no credentials.`);
        return { model: target, thinkingLevel: clampThinkingLevel(target, route.thinkingLevel), state: route.state };
    }
    /** A catalog chat model that is not virtual. */
    getPhysicalModel(providerId, modelId) {
        const model = this.models.getModel(providerId, modelId);
        return model && !isVirtualModel(model) ? model : undefined;
    }
}
//# sourceMappingURL=model-runtime.js.map