config.ts 6.46 KB
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'fs';
import { resolve } from 'path';
import { homedir } from 'os';
import yaml from 'js-yaml';

// Configuration directory in user's home
export const CONFIG_DIR = resolve(homedir(), '.coderio');
const CONFIG_FILE = resolve(CONFIG_DIR, 'config.yaml');

/**
 * Model configuration interface
 */
export interface ModelConfig {
    provider: string;
    model: string;
    baseUrl: string;
    apiKey: string;
    /** Force non-streaming mode. evoltagent's default streaming hangs against
     *  some OpenAI-compatible endpoints (e.g. Aliyun MAAS Qwen) that stream
     *  `reasoning_content`, so we disable it globally here. */
    stream?: boolean;
}

/**
 * Figma configuration interface
 */
export interface FigmaConfig {
    token: string;
}

/**
 * Debug configuration interface
 */
export interface DebugConfig {
    enabled: boolean;
    outputDir?: string;
}

/**
 * Configuration file structure
 */
interface Config {
    model: ModelConfig;
    figma: FigmaConfig;
    debug?: DebugConfig;
}

// Cache for loaded configuration
let cachedConfig: Config | null = null;

/**
 * Load configuration from user's config directory
 * The configuration is cached after first load
 * @returns Full configuration object
 */
export function loadConfig(): Config {
    if (cachedConfig) {
        return cachedConfig;
    }

    if (!existsSync(CONFIG_FILE)) {
        throw new Error(`Configuration file not found at: ${CONFIG_FILE}\n` + `Please create the configuration file.`);
    }

    try {
        const fileContent = readFileSync(CONFIG_FILE, 'utf8');
        const rawConfig = yaml.load(fileContent) as Config;

        if (!rawConfig) {
            throw new Error('Invalid config.yaml structure: configuration is empty');
        }

        cachedConfig = rawConfig;
        return cachedConfig;
    } catch (error) {
        if (error instanceof Error) {
            throw new Error(`Failed to load config.yaml: ${error.message}`);
        }
        throw error;
    }
}

/**
 * Get model configuration from config.yaml
 * @returns Model configuration
 * @throws Error if configuration is invalid
 */
export function getModelConfig(): ModelConfig {
    if (runtimeModel) {
        return { ...runtimeModel, stream: false };
    }
    const config = loadConfig();
    if (!config.model) {
        throw new Error('Model configuration not found in config.yaml');
    }
    // Disable streaming globally: evoltagent defaults to streaming, which hangs
    // against OpenAI-compatible endpoints that emit `reasoning_content` chunks
    // (e.g. Aliyun MAAS Qwen). Non-streaming is verified working for those.
    return { ...config.model, stream: false };
}

/**
 * Get Figma configuration from config.yaml
 * @returns Figma configuration
 * @throws Error if configuration is invalid
 */
export function getFigmaConfig(): FigmaConfig {
    if (runtimeFigma) {
        return runtimeFigma;
    }
    const config = loadConfig();
    if (!config.figma) {
        throw new Error('Figma configuration not found in config.yaml');
    }
    return config.figma;
}

/**
 * Get debug configuration from config.yaml
 * @returns Debug configuration (defaults to disabled if not specified)
 */
export function getDebugConfig(): DebugConfig {
    const config = loadConfig();
    return config.debug || { enabled: false };
}

/**
 * Get the path to the configuration file
 */
export function getConfigPath(): string {
    return CONFIG_FILE;
}

/**
 * Check if configuration file exists
 */
export function configExists(): boolean {
    return existsSync(CONFIG_FILE);
}
/**
 * Clear the configuration cache
 * Useful for testing or when configuration needs to be reloaded
 */
export function clearConfigCache(): void {
    cachedConfig = null;
}

/**
 * Runtime configuration override injected by the orchestration backend
 * (apps/server). When set, `getModelConfig()` / `getFigmaConfig()` return it
 * instead of the file-based config, so the backend can own credentials per
 * request without relying on a global `~/.coderio/config.yaml`.
 */
let runtimeModel: ModelConfig | null = null;
let runtimeFigma: FigmaConfig | null = null;

export function setRuntimeConfig(override: {
    model?: Partial<ModelConfig>;
    figma?: Partial<FigmaConfig>;
}): void {
    if (override.model) {
        runtimeModel = {
            ...(runtimeModel ?? { provider: '', model: '', baseUrl: '', apiKey: '' }),
            ...override.model,
        } as ModelConfig;
    }
    if (override.figma) {
        runtimeFigma = { ...(runtimeFigma ?? { token: '' }), ...override.figma } as FigmaConfig;
    }
}

export function clearRuntimeConfig(): void {
    runtimeModel = null;
    runtimeFigma = null;
}

/**
 * Read the currently-injected runtime override (or null if none). Used by the
 * server's `loadServerModelConfig()` so that an explicit "connect to local
 * Ollama" action wins over the file/env defaults for the next generation job.
 */
export function getRuntimeConfig(): {
    model: ModelConfig | null;
    figma: FigmaConfig | null;
} {
    return { model: runtimeModel, figma: runtimeFigma };
}

/**
 * Merge a partial configuration into the existing config.yaml and persist it.
 *
 * Only the provided top-level keys are merged (shallow per section), so callers
 * can update `model` without touching `figma`. The in-memory cache is cleared
 * afterwards so subsequent `loadConfig()` reads the new values.
 *
 * @param partial - Sections to merge (e.g. `{ model: {...}, figma: {...} }`)
 */
export function saveConfig(partial: Partial<Config>): void {
    let existing: Partial<Config> = {};
    if (configExists()) {
        try {
            const raw = yaml.load(readFileSync(CONFIG_FILE, 'utf8')) as Partial<Config> | null;
            if (raw && typeof raw === 'object') {
                existing = raw;
            }
        } catch {
            existing = {};
        }
    }

    const merged: Config = {
        model: { ...(existing.model as ModelConfig), ...(partial.model as Partial<ModelConfig>) } as ModelConfig,
        figma: { ...(existing.figma as FigmaConfig), ...(partial.figma as Partial<FigmaConfig>) } as FigmaConfig,
    };

    if (partial.debug !== undefined) {
        merged.debug = { ...(existing.debug as DebugConfig), ...partial.debug } as DebugConfig;
    } else if (existing.debug) {
        merged.debug = existing.debug;
    }

    if (!existsSync(CONFIG_DIR)) {
        mkdirSync(CONFIG_DIR, { recursive: true });
    }

    writeFileSync(CONFIG_FILE, yaml.dump(merged), 'utf8');
    clearConfigCache();
}