ollama-state.ts 2.68 KB
/**
 * In-memory mirror of whether the engine is currently pointed at a local
 * Ollama model, plus the exact model config that the next generation job
 * should use. The server owns this (not coderio's dist) so that connecting/
 * disconnecting takes effect for child-process generation without requiring a
 * coderio rebuild — `loadServerModelConfig()` reads it below.
 */
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { homedir } from 'node:os';

const PERSIST_FILE = resolve(homedir(), '.coderio', 'ollama-active.json');

export interface OllamaRuntimeConfig {
    provider: string;
    model: string;
    baseUrl: string;
    apiKey: string;
}

let connected = false;
let activeModel: string | null = null;
let activeConfig: OllamaRuntimeConfig | null = null;

export function setOllamaConnected(model: string | null): void {
    connected = model !== null;
    activeModel = model;
}

export function getOllamaState(): { connected: boolean; activeModel: string | null } {
    return { connected, activeModel };
}

/** Record the model config the engine should use while connected to Ollama. */
export function setOllamaConfig(cfg: OllamaRuntimeConfig | null): void {
    activeConfig = cfg;
}

/** The Ollama config to inject into the next generation job, or null. */
export function getOllamaConfig(): OllamaRuntimeConfig | null {
    return activeConfig;
}

/** Persist the active Ollama connection so it survives a server restart. */
export function persistOllama(cfg: OllamaRuntimeConfig): void {
    try {
        const dir = resolve(homedir(), '.coderio');
        if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
        writeFileSync(PERSIST_FILE, JSON.stringify(cfg), 'utf8');
    } catch {
        /* best-effort: ignore persistence failures */
    }
}

/** Clear the persisted connection (on disconnect). */
export function clearPersistedOllama(): void {
    try {
        if (existsSync(PERSIST_FILE)) writeFileSync(PERSIST_FILE, 'null', 'utf8');
    } catch {
        /* ignore */
    }
}

/**
 * Load a previously persisted connection. Returns null when none was saved.
 * The stored `baseUrl` keeps the `/v1` suffix (OpenAI-compatible endpoint);
 * callers that need the Ollama root (for health/model checks) strip it.
 */
export function loadPersistedOllama(): OllamaRuntimeConfig | null {
    try {
        if (!existsSync(PERSIST_FILE)) return null;
        const raw = JSON.parse(readFileSync(PERSIST_FILE, 'utf8'));
        if (raw && typeof raw === 'object' && raw.model && raw.baseUrl) {
            return raw as OllamaRuntimeConfig;
        }
    } catch {
        /* ignore unreadable/corrupt file */
    }
    return null;
}