import fs from "fs" import path from "path" import os from "os" const CONFIG_DIR = path.join(os.homedir(), ".llmtune") const CONFIG_FILE = path.join(CONFIG_DIR, "config.json") export interface AuthConfig { apiKey: string apiBase: string defaultModel?: string } export interface AppConfig { defaultProvider?: string providers?: Record [key: string]: unknown } export function ensureConfigDir(): void { if (!fs.existsSync(CONFIG_DIR)) { fs.mkdirSync(CONFIG_DIR, { recursive: true }) } const memDir = path.join(CONFIG_DIR, "memory") if (!fs.existsSync(memDir)) { fs.mkdirSync(memDir, { recursive: true }) } const sessionsDir = path.join(CONFIG_DIR, "sessions") if (!fs.existsSync(sessionsDir)) { fs.mkdirSync(sessionsDir, { recursive: true }) } const logsDir = path.join(CONFIG_DIR, "logs") if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }) } } export function loadConfig(): AppConfig { ensureConfigDir() if (!fs.existsSync(CONFIG_FILE)) { return {} } try { const raw = fs.readFileSync(CONFIG_FILE, "utf-8") return JSON.parse(raw) as AppConfig } catch { return {} } } export function saveConfig(config: AppConfig): void { ensureConfigDir() fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8") } export function getApiKey(): string | null { const config = loadConfig() return (config.apiKey as string) ?? null } export function getApiBase(): string { const config = loadConfig() return (config.apiBase as string) ?? "https://api.llmtune.io/api/agent/v1" } export function getDefaultModel(): string { const config = loadConfig() return (config.defaultModel as string) ?? "z-ai/GLM-5.1" } export function isLoggedIn(): boolean { return getApiKey() !== null } export function logout(): void { const config = loadConfig() delete config.apiKey delete config.apiBase delete config.defaultModel saveConfig(config) } export function getConfigPath(): string { return CONFIG_FILE } export function getConfigDir(): string { return CONFIG_DIR }