64875
Mc
mini-coder / files
mini-coder / src / config.ts
5.8 KB
1import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; 2import { homedir } from "node:os"; 3import { dirname, join } from "node:path"; 4import { 5 createProvider, 6 envApiKeyAuth, 7 Type, 8 type Api, 9 type Model, 10 type ModelThinkingLevel, 11 type MutableModels, 12 type Static, 13} from "@earendil-works/pi-ai"; 14import { Value } from "typebox/value"; 15import { builtinModels } from "@earendil-works/pi-ai/providers/all"; 16import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy"; 17import { googleGenerativeAIApi } from "@earendil-works/pi-ai/api/google-generative-ai.lazy"; 18import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy"; 19import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy"; 20import { createCredentialStore } from "./auth.ts"; 21 22const ToolNameSchema = Type.Union([Type.Literal("edit"), Type.Literal("read"), Type.Literal("bash")]); 23export type ToolName = Static<typeof ToolNameSchema>; 24 25const CustomApiSchema = Type.Union([ 26 Type.Literal("openai-completions"), 27 Type.Literal("openai-responses"), 28 Type.Literal("anthropic-messages"), 29 Type.Literal("google-generative-ai"), 30]); 31type CustomApi = Static<typeof CustomApiSchema>; 32 33const CustomProviderSchema = Type.Object( 34 { 35 id: Type.String({ minLength: 1 }), 36 name: Type.Optional(Type.String()), 37 baseUrl: Type.String({ minLength: 1 }), 38 api: CustomApiSchema, 39 models: Type.Array(Type.String(), { minItems: 1 }), 40 envKeys: Type.Optional(Type.Array(Type.String())), 41 headers: Type.Optional(Type.Record(Type.String(), Type.String())), 42 }, 43 { additionalProperties: false }, 44); 45 46const ConfigSchema = Type.Object( 47 { 48 sessionsDir: Type.String({ default: join(process.cwd(), "sessions") }), 49 authFile: Type.String({ default: join(configDir(), "auth.json") }), 50 systemPrompt: Type.String({ default: "" }), 51 discoverAgentFiles: Type.Boolean({ default: true }), 52 skillsDirs: Type.Array(Type.String(), { default: [] }), 53 tools: Type.Array(ToolNameSchema, { default: ["edit", "read", "bash"] }), 54 provider: Type.Optional(Type.String()), 55 model: Type.Optional(Type.String()), 56 thinkingEffort: Type.Union( 57 [ 58 Type.Literal("off"), 59 Type.Literal("minimal"), 60 Type.Literal("low"), 61 Type.Literal("medium"), 62 Type.Literal("high"), 63 Type.Literal("xhigh"), 64 Type.Literal("max"), 65 ], 66 { default: "medium" }, 67 ), 68 customProviders: Type.Array(CustomProviderSchema, { default: [] }), 69 }, 70 { additionalProperties: false }, 71); 72export type Config = Static<typeof ConfigSchema>; 73 74function configDir(): string { 75 const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config"); 76 return join(base, "mini-coder"); 77} 78 79export function configPath(): string { 80 return join(configDir(), "config.json"); 81} 82 83function readJson(path: string): unknown { 84 let text: string; 85 try { 86 text = readFileSync(path, "utf8"); 87 } catch (error) { 88 if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; 89 throw new Error(`config ${path}: ${(error as Error).message}`); 90 } 91 try { 92 return JSON.parse(text); 93 } catch (error) { 94 throw new Error(`config ${path}: ${(error as Error).message}`); 95 } 96} 97 98export function loadConfig(): Config { 99 const path = configPath(); 100 const filled = Value.Default(ConfigSchema, readJson(path)); 101 try { 102 return Value.Parse(ConfigSchema, filled); 103 } catch { 104 const first = [...Value.Errors(ConfigSchema, filled)][0]; 105 throw new Error(`config ${path}: ${first ? `${first.instancePath || "/"} ${first.message}` : "invalid"}`); 106 } 107} 108 109/** 110 * Persist a patch to the global config, leaving every other key untouched. 111 * Written atomically: a temp file, then a rename over the target. 112 */ 113export function saveConfig(patch: { 114 provider?: string; 115 model?: string; 116 thinkingEffort?: ModelThinkingLevel; 117}): void { 118 const path = configPath(); 119 const existing = readJson(path); 120 if (typeof existing !== "object" || existing === null || Array.isArray(existing)) { 121 throw new Error(`config ${path}: not an object`); 122 } 123 const next = { ...existing, ...patch }; 124 mkdirSync(dirname(path), { recursive: true }); 125 const temp = join(dirname(path), `.${process.pid}.${Date.now()}.tmp`); 126 writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`); 127 renameSync(temp, path); 128} 129 130const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsApi>> = { 131 "openai-completions": openAICompletionsApi, 132 "openai-responses": openAIResponsesApi, 133 "anthropic-messages": anthropicMessagesApi, 134 "google-generative-ai": googleGenerativeAIApi, 135}; 136 137export function resolveModel(config: Config): { models: MutableModels; model: Model<Api> | null } { 138 const models = builtinModels({ credentials: createCredentialStore(config.authFile) }); 139 for (const provider of config.customProviders) { 140 const name = provider.name ?? provider.id; 141 models.setProvider( 142 createProvider({ 143 id: provider.id, 144 name, 145 baseUrl: provider.baseUrl, 146 headers: provider.headers, 147 auth: { 148 apiKey: provider.envKeys?.length 149 ? envApiKeyAuth(name, provider.envKeys) 150 : { name, resolve: async () => ({ auth: { apiKey: "unused" } }) }, 151 }, 152 api: API_FACTORY[provider.api](), 153 models: provider.models.map((id) => ({ 154 id, 155 name: id, 156 api: provider.api, 157 provider: provider.id, 158 baseUrl: provider.baseUrl, 159 reasoning: false, 160 input: ["text"] satisfies ("text" | "image")[], 161 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, 162 contextWindow: 200_000, 163 maxTokens: 32_768, 164 })), 165 }), 166 ); 167 } 168 169 if (!config.provider || !config.model) return { models, model: null }; 170 return { models, model: models.getModel(config.provider, config.model) ?? null }; 171}