import { DEFAULTS, loadConfig } from "./config.js";
export class Runtime {
    config = { ...DEFAULTS };
    configLoaded = false;
    observerInFlight = false;
    observerPromise = null;
    compactInFlight = false;
    compactHookInFlight = false;
    resolveFailureNotified = false;
    ensureConfig(cwd) {
        if (this.configLoaded)
            return;
        this.config = loadConfig(cwd);
        this.configLoaded = true;
    }
    async resolveModel(ctx) {
        let model = ctx.model;
        if (this.config.compactionModel) {
            const configured = ctx.modelRegistry.find(this.config.compactionModel.provider, this.config.compactionModel.id);
            if (configured) {
                model = configured;
            }
            else if (ctx.hasUI && ctx.ui) {
                ctx.ui.notify(`Observational memory: configured model ${this.config.compactionModel.provider}/${this.config.compactionModel.id} not found, using session model`, "warning");
            }
        }
        if (!model)
            return { ok: false, reason: "no model available (session has no model and no compactionModel configured)" };
        const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
        if (!auth.ok || !auth.apiKey) {
            const provider = model.provider ?? "unknown";
            return { ok: false, reason: `no API key for provider "${provider}"` };
        }
        return { ok: true, model, apiKey: auth.apiKey, headers: auth.headers };
    }
    launchObserverTask(ctx, label, work) {
        this.observerInFlight = true;
        // Capture ctx properties synchronously — after `await work()` the extension ctx
        // may be stale (e.g. after ctx.newSession/fork/switchSession/reload), and accessing
        // ctx.hasUI or ctx.ui on a stale proxy throws.
        const hasUI = ctx.hasUI;
        const ui = ctx.ui;
        let promise;
        promise = (async () => {
            try {
                await work();
            }
            catch (error) {
                const msg = error instanceof Error ? error.message : String(error);
                if (hasUI && ui)
                    ui.notify(`Observational memory: ${label} failed: ${msg}`, "warning");
            }
            finally {
                this.observerInFlight = false;
                if (this.observerPromise === promise)
                    this.observerPromise = null;
            }
        })();
        this.observerPromise = promise;
        return promise;
    }
}
