@@ -2,166 +2,100 @@ import { readFileSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
44 import {
5- createModels,
65 createProvider,
76 envApiKeyAuth,
7+ Type,
88 type Api,
99 type Model,
1010 type MutableModels,
11- type ThinkingLevel,
11+ type Static,
1212 } from "@earendil-works/pi-ai";
13+import { Value } from "typebox/value";
1314 import { builtinModels } from "@earendil-works/pi-ai/providers/all";
1415 import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
1516 import { googleGenerativeAIApi } from "@earendil-works/pi-ai/api/google-generative-ai.lazy";
1617 import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
1718 import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
1819
19-export const CUSTOM_APIS = [
20- "openai-completions",
21- "openai-responses",
22- "anthropic-messages",
23- "google-generative-ai",
24-] as const;
25-export type CustomApi = (typeof CUSTOM_APIS)[number];
26-
27-export const TOOL_NAMES = ["edit", "bash"] as const;
28-export type ToolName = (typeof TOOL_NAMES)[number];
29-
30-export interface CustomProviderConfig {
31- id: string;
32- name?: string;
33- baseUrl: string;
34- api: CustomApi;
35- models: string[];
36- envKeys?: string[];
37- headers?: Record<string, string>;
38-}
39-
40-export interface Config {
41- sessionsDir: string;
42- systemPrompt: string;
43- discoverAgentFiles: boolean;
44- skillsDirs: string[];
45- tools: ToolName[];
46- provider: string;
47- model: string;
48- thinkingEffort: ThinkingLevel;
49- customProviders: CustomProviderConfig[];
50-}
51-
52-const THINKING_LEVELS: ThinkingLevel[] = [
53- "minimal",
54- "low",
55- "medium",
56- "high",
57- "xhigh",
58- "max",
59-];
60-
61-export function configPath(): string {
20+const ToolNameSchema = Type.Union([Type.Literal("edit"), Type.Literal("bash")]);
21+export type ToolName = Static<typeof ToolNameSchema>;
22+
23+const CustomApiSchema = Type.Union([
24+ Type.Literal("openai-completions"),
25+ Type.Literal("openai-responses"),
26+ Type.Literal("anthropic-messages"),
27+ Type.Literal("google-generative-ai"),
28+]);
29+type CustomApi = Static<typeof CustomApiSchema>;
30+
31+const CustomProviderSchema = Type.Object(
32+ {
33+ id: Type.String({ minLength: 1 }),
34+ name: Type.Optional(Type.String()),
35+ baseUrl: Type.String({ minLength: 1 }),
36+ api: CustomApiSchema,
37+ models: Type.Array(Type.String(), { minItems: 1 }),
38+ envKeys: Type.Optional(Type.Array(Type.String())),
39+ headers: Type.Optional(Type.Record(Type.String(), Type.String())),
40+ },
41+ { additionalProperties: false },
42+);
43+
44+const ConfigSchema = Type.Object(
45+ {
46+ sessionsDir: Type.String({ default: join(process.cwd(), "sessions") }),
47+ systemPrompt: Type.String({ default: "" }),
48+ discoverAgentFiles: Type.Boolean({ default: true }),
49+ skillsDirs: Type.Array(Type.String(), { default: [] }),
50+ tools: Type.Array(ToolNameSchema, { default: ["edit", "bash"] }),
51+ provider: Type.String({ default: "anthropic" }),
52+ model: Type.String({ default: "claude-sonnet-4-5" }),
53+ thinkingEffort: Type.Union(
54+ [
55+ Type.Literal("minimal"),
56+ Type.Literal("low"),
57+ Type.Literal("medium"),
58+ Type.Literal("high"),
59+ Type.Literal("xhigh"),
60+ Type.Literal("max"),
61+ ],
62+ { default: "medium" },
63+ ),
64+ customProviders: Type.Array(CustomProviderSchema, { default: [] }),
65+ },
66+ { additionalProperties: false },
67+);
68+export type Config = Static<typeof ConfigSchema>;
69+
70+function configPath(): string {
6271 const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
6372 return join(base, "mini-coder", "config.json");
6473 }
6574
66-export function loadConfig(): Config {
67- let raw: Record<string, unknown> = {};
68- const path = configPath();
75+function readJson(path: string): unknown {
76+ let text: string;
6977 try {
70- raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
78+ text = readFileSync(path, "utf8");
7179 } catch (error) {
72- if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
73- throw new Error(`config ${path}: ${(error as Error).message}`);
74- }
75- }
76-
77- const tools = raw.tools === undefined ? ["edit", "bash"] : raw.tools;
78- if (!Array.isArray(tools) || tools.some((t) => !TOOL_NAMES.includes(t as ToolName))) {
79- throw new Error(`config tools: expected a subset of ${TOOL_NAMES.join(", ")}`);
80+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
81+ throw new Error(`config ${path}: ${(error as Error).message}`);
8082 }
81-
82- const thinkingEffort = raw.thinkingEffort ?? "medium";
83- if (typeof thinkingEffort !== "string" || !THINKING_LEVELS.includes(thinkingEffort as ThinkingLevel)) {
84- throw new Error(`config thinkingEffort: expected one of ${THINKING_LEVELS.join(", ")}`);
85- }
86-
87- return {
88- sessionsDir: str(raw, "sessionsDir", join(process.cwd(), "sessions")),
89- systemPrompt: str(raw, "systemPrompt", ""),
90- discoverAgentFiles: bool(raw, "discoverAgentFiles", true),
91- skillsDirs: strArray(raw, "skillsDirs", []),
92- tools: tools as ToolName[],
93- provider: str(raw, "provider", "anthropic"),
94- model: str(raw, "model", "claude-sonnet-4-5"),
95- thinkingEffort: thinkingEffort as ThinkingLevel,
96- customProviders: customProviders(raw.customProviders),
97- };
98-}
99-
100-function str(raw: Record<string, unknown>, field: string, fallback: string): string {
101- const value = raw[field];
102- if (value === undefined) return fallback;
103- if (typeof value !== "string") throw new Error(`config ${field}: expected a string`);
104- return value;
105-}
106-
107-function bool(raw: Record<string, unknown>, field: string, fallback: boolean): boolean {
108- const value = raw[field];
109- if (value === undefined) return fallback;
110- if (typeof value !== "boolean") throw new Error(`config ${field}: expected a boolean`);
111- return value;
112-}
113-
114-function strArray(raw: Record<string, unknown>, field: string, fallback: string[]): string[] {
115- const value = raw[field];
116- if (value === undefined) return fallback;
117- if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
118- throw new Error(`config ${field}: expected an array of strings`);
83+ try {
84+ return JSON.parse(text);
85+ } catch (error) {
86+ throw new Error(`config ${path}: ${(error as Error).message}`);
11987 }
120- return value as string[];
121-}
122-
123-function customProviders(value: unknown): CustomProviderConfig[] {
124- if (value === undefined) return [];
125- if (!Array.isArray(value)) throw new Error("config customProviders: expected an array");
126- return value.map((entry, index) => {
127- if (typeof entry !== "object" || entry === null) {
128- throw new Error(`config customProviders[${index}]: expected an object`);
129- }
130- const provider = entry as Record<string, unknown>;
131- const where = `config customProviders[${index}]`;
132- const id = provider.id;
133- if (typeof id !== "string" || id.length === 0) throw new Error(`${where}.id: expected a non-empty string`);
134- const baseUrl = provider.baseUrl;
135- if (typeof baseUrl !== "string" || baseUrl.length === 0) throw new Error(`${where}.baseUrl: expected a non-empty string`);
136- const api = provider.api;
137- if (typeof api !== "string" || !CUSTOM_APIS.includes(api as CustomApi)) {
138- throw new Error(`${where}.api: expected one of ${CUSTOM_APIS.join(", ")}`);
139- }
140- const models = provider.models;
141- if (!Array.isArray(models) || models.length === 0 || models.some((m) => typeof m !== "string")) {
142- throw new Error(`${where}.models: expected a non-empty array of strings`);
143- }
144- return {
145- id,
146- name: typeof provider.name === "string" ? provider.name : undefined,
147- baseUrl,
148- api: api as CustomApi,
149- models: models as string[],
150- envKeys: strArray(provider, "envKeys", []),
151- headers: headers(provider.headers, `${where}.headers`),
152- };
153- });
15488 }
15589
156-function headers(value: unknown, where: string): Record<string, string> | undefined {
157- if (value === undefined) return undefined;
158- if (typeof value !== "object" || value === null) throw new Error(`${where}: expected an object`);
159- const out: Record<string, string> = {};
160- for (const [key, val] of Object.entries(value)) {
161- if (typeof val !== "string") throw new Error(`${where}.${key}: expected a string`);
162- out[key] = val;
90+export function loadConfig(): Config {
91+ const path = configPath();
92+ const filled = Value.Default(ConfigSchema, readJson(path));
93+ try {
94+ return Value.Parse(ConfigSchema, filled);
95+ } catch {
96+ const first = [...Value.Errors(ConfigSchema, filled)][0];
97+ throw new Error(`config ${path}: ${first ? `${first.instancePath || "/"} ${first.message}` : "invalid"}`);
16398 }
164- return out;
16599 }
166100
167101 const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsApi>> = {
@@ -198,7 +132,7 @@ export function resolveModel(config: Config): ResolvedModel {
198132 provider: provider.id,
199133 baseUrl: provider.baseUrl,
200134 reasoning: false,
201- input: ["text"] as ("text" | "image")[],
135+ input: ["text"] satisfies ("text" | "image")[],
202136 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
203137 contextWindow: 200_000,
204138 maxTokens: 32_768,