xonecas.io
64875
Mc

mini-coder / commit 9341709

Merge pull request #8 from andynu/feat/custom-providers

feat: support custom OpenAI-compatible providers (Ollama, LM Studio, etc.)

xonecas2026-04-11 93417098c761de3f8a4f1055a48b8577adb2b888 parent 42efa32parent 42ffd27

10 files changed

spec.md+35−20
@@ -724,19 +724,19 @@ add tests for undo_
724724
725725 ### Commands
726726
727-| Command | Description |
728-| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
729-| `/model` | Interactive model selector. Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately, and the selected model is persisted immediately as the user's global default. The session record's `model` field is not updated (it reflects the initial choice). |
730-| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. |
731-| `/new` | Start a new session. Clears conversation, resets cost/token counters. |
732-| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. |
733-| `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. |
734-| `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. |
735-| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. |
736-| `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. |
737-| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. |
738-| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). |
739-| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. |
727+| Command | Description …
728+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- …
729+| `/model` | Interactive model selector. The list includes built-in models plus any custom OpenAI-compatible models discovered from `settings.json`. Switching models mid-session is allowed — pi-ai's context is model-agnostic. The `readImage` tool is re-evaluated (added/removed based on the new model's capabilities). The status bar updates immediately, and the selected model is persisted immediately as the user's global default. The session record's `model` field is not updated (it reflects …
730+| `/session` | Interactive session manager (list, resume). Sessions scoped to CWD. …
731+| `/new` | Start a new session. Clears conversation, resets cost/token counters. …
732+| `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently. The original session is preserved. …
733+| `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. …
734+| `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. …
735+| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. …
736+| `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. …
737+| `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
738+| `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). …
739+| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. …
740740
741741 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
742742
@@ -797,19 +797,24 @@ This means headless one-shot runs appear in normal `/session` history for that w
797797
798798 On launch, mini-coder:
799799
800-1. Discovers providers (env vars, OAuth tokens).
800+1. Discovers built-in providers (env vars, OAuth tokens).
801801 2. Loads user settings from `~/.config/mini-coder/settings.json`.
802-3. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
802+3. Discovers user-configured custom OpenAI-compatible providers from `settings.json`.
803+ - Each entry is queried at `${baseUrl}/models`.
804+ - Each returned model is added to the launch's available model list as `provider/model`, where `provider` is the configured custom provider name.
805+ - Invalid entries are dropped while loading settings. Duplicate custom provider names keep the first entry.
806+ - If an endpoint is unreachable, returns a non-2xx response, or the custom provider name conflicts with an already-available built-in provider, startup continues and a warning is added to the UI log.
807+4. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
803808 - `defaultModel`: if the saved provider/model is currently available, use it; otherwise fall back to the first available model for this launch.
804809 - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
805810 - `showReasoning`: if present, use it; otherwise fall back to `true`.
806811 - `verbose`: if present, use it; otherwise fall back to `false`.
807-4. Loads AGENTS.md files, skills, plugins.
808-5. Selects the launch mode:
812+5. Loads AGENTS.md files, skills, plugins.
813+6. Selects the launch mode:
809814 - Interactive TUI when `stdin` and `stdout` are both TTYs and `-p` was not provided.
810815 - Headless one-shot mode otherwise.
811-6. In interactive mode, renders the UI with an empty conversation log and the status bar populated.
812-7. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
816+7. In interactive mode, renders the UI with an empty conversation log and the status bar populated.
817+8. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
813818
814819 No banner or splash screen. In headless mode, stdout is reserved for NDJSON event output; in interactive mode, the status bar already shows all the context the user needs.
815820
@@ -824,7 +829,13 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
824829 "defaultModel": "anthropic/claude-sonnet-4",
825830 "defaultEffort": "medium",
826831 "showReasoning": true,
827- "verbose": false
832+ "verbose": false,
833+ "customProviders": [
834+ {
835+ "name": "lm-studio",
836+ "baseUrl": "http://127.0.0.1:1234/v1"
837+ }
838+ ]
828839 }
829840 ```
830841
@@ -836,6 +847,10 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
836847 - Invalid or missing settings file content is treated as "no saved settings" rather than a fatal startup error.
837848 - `/new`, `/fork`, and `/session` do not modify global settings.
838849 - Session records remain historical: their `model` and `effort` fields reflect the values active when that session was created, not the current global defaults.
850+- `customProviders` is an optional array of user-configured OpenAI-compatible endpoints, typically local model servers.
851+- Each `customProviders` entry has a `name`, `baseUrl`, and optional `apiKey`. The `name` becomes the provider prefix shown in model ids such as `lm-studio/qwen3-coder`.
852+- Unreachable or invalid custom providers do not block startup; mini-coder skips them and shows a warning in the interactive log.
853+- Custom providers are discovered only at startup. There is currently no interactive slash command to add or remove them.
839854
840855 ## Session persistence
841856
src/headless.test.ts+2−0
@@ -56,6 +56,8 @@ function createTestState(): AppState {
5656 activeTurnPromise: null,
5757 showReasoning: true,
5858 verbose: false,
59+ customModels: [],
60+ startupWarnings: [],
5961 };
6062 states.push(state);
6163 return state;
src/index.test.ts+149−0
@@ -3,9 +3,12 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { pathToFileURL } from "node:url";
6+import type { Model } from "@mariozechner/pi-ai";
67 import {
78 type AppState,
89 didOAuthCredentialsChange,
10+ discoverCustomProviders,
11+ getAvailableModels,
912 loadOAuthCredentials,
1013 loadPromptContext,
1114 reloadPromptContext,
@@ -49,6 +52,8 @@ function createTestState(plugins: LoadedPlugin[] = []): AppState {
4952 activeTurnPromise: null,
5053 showReasoning: true,
5154 verbose: false,
55+ customModels: [],
56+ startupWarnings: [],
5257 };
5358 }
5459
@@ -295,3 +300,147 @@ test("reloadPromptContext swaps in the new context before destroying the old plu
295300 state.db.close();
296301 }
297302 });
303+
304+// ---------------------------------------------------------------------------
305+// discoverCustomProviders
306+// ---------------------------------------------------------------------------
307+
308+test("discoverCustomProviders returns models from a mock endpoint", async () => {
309+ const server = Bun.serve({
310+ port: 0,
311+ fetch() {
312+ return Response.json({
313+ data: [
314+ { id: "gemma4:31b", object: "model" },
315+ { id: "qwen3:8b", object: "model" },
316+ ],
317+ });
318+ },
319+ });
320+
321+ try {
322+ const result = await discoverCustomProviders(
323+ [{ name: "test-local", baseUrl: `http://localhost:${server.port}` }],
324+ new Set(),
325+ );
326+
327+ expect(result.warnings).toEqual([]);
328+ expect(result.models).toHaveLength(2);
329+ expect(result.models[0]).toMatchObject({
330+ id: "gemma4:31b",
331+ name: "gemma4:31b",
332+ api: "openai-completions",
333+ provider: "test-local",
334+ baseUrl: `http://localhost:${server.port}`,
335+ reasoning: false,
336+ input: ["text"],
337+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
338+ contextWindow: 131072,
339+ maxTokens: 8192,
340+ });
341+ expect(result.providers.get("test-local")).toBe("no-key");
342+ } finally {
343+ server.stop(true);
344+ }
345+});
346+
347+test("discoverCustomProviders uses configured apiKey", async () => {
348+ const server = Bun.serve({
349+ port: 0,
350+ fetch() {
351+ return Response.json({ data: [{ id: "model-1", object: "model" }] });
352+ },
353+ });
354+
355+ try {
356+ const result = await discoverCustomProviders(
357+ [
358+ {
359+ name: "keyed",
360+ baseUrl: `http://localhost:${server.port}`,
361+ apiKey: "my-secret-key",
362+ },
363+ ],
364+ new Set(),
365+ );
366+
367+ expect(result.providers.get("keyed")).toBe("my-secret-key");
368+ } finally {
369+ server.stop(true);
370+ }
371+});
372+
373+test("discoverCustomProviders returns a warning when the endpoint is unreachable", async () => {
374+ const result = await discoverCustomProviders(
375+ [{ name: "dead", baseUrl: "http://localhost:1" }],
376+ new Set(),
377+ );
378+
379+ expect(result.models).toEqual([]);
380+ expect(result.providers.size).toBe(0);
381+ expect(result.warnings).toHaveLength(1);
382+ expect(result.warnings[0]).toContain('Custom provider "dead"');
383+ expect(result.warnings[0]).toContain("http://localhost:1/models");
384+});
385+
386+test("discoverCustomProviders skips providers that collide with built-in names", async () => {
387+ const result = await discoverCustomProviders(
388+ [{ name: "openai", baseUrl: "http://localhost:11434/v1" }],
389+ new Set(["openai"]),
390+ );
391+
392+ expect(result.models).toEqual([]);
393+ expect(result.warnings).toHaveLength(1);
394+ expect(result.warnings[0]).toContain('"openai"');
395+ expect(result.warnings[0]).toContain("built-in");
396+});
397+
398+test("discoverCustomProviders handles empty model list from endpoint", async () => {
399+ const server = Bun.serve({
400+ port: 0,
401+ fetch() {
402+ return Response.json({ data: [] });
403+ },
404+ });
405+
406+ try {
407+ const result = await discoverCustomProviders(
408+ [{ name: "empty", baseUrl: `http://localhost:${server.port}` }],
409+ new Set(),
410+ );
411+
412+ expect(result.models).toEqual([]);
413+ expect(result.providers.get("empty")).toBe("no-key");
414+ expect(result.warnings).toEqual([]);
415+ } finally {
416+ server.stop(true);
417+ }
418+});
419+
420+// ---------------------------------------------------------------------------
421+// getAvailableModels with custom models
422+// ---------------------------------------------------------------------------
423+
424+test("getAvailableModels includes custom models alongside built-in models", () => {
425+ const state = createTestState();
426+ try {
427+ const customModel: Model<"openai-completions"> = {
428+ id: "gemma4:31b",
429+ name: "gemma4:31b",
430+ api: "openai-completions",
431+ provider: "ollama",
432+ baseUrl: "http://localhost:11434/v1",
433+ reasoning: false,
434+ input: ["text"],
435+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
436+ contextWindow: 131072,
437+ maxTokens: 8192,
438+ };
439+ state.customModels = [customModel];
440+
441+ const models = getAvailableModels(state);
442+ expect(models).toContainEqual(customModel);
443+ } finally {
444+ state.db.close();
445+ }
446+});
src/index.ts+118−2
@@ -57,6 +57,7 @@ import {
5757 truncateSessions,
5858 } from "./session.ts";
5959 import {
60+ type CustomProvider,
6061 loadSettings,
6162 resolveStartupSettings,
6263 type UserSettings,
@@ -208,6 +209,101 @@ async function discoverProviders(): Promise<DiscoveryResult> {
208209 return { providers, oauthCredentials };
209210 }
210211
212+// ---------------------------------------------------------------------------
213+// Custom provider discovery
214+// ---------------------------------------------------------------------------
215+
216+/** Timeout for custom provider model discovery requests. */
217+const CUSTOM_PROVIDER_TIMEOUT_MS = 3_000;
218+
219+/** Default API key for custom providers that don't require authentication. */
220+const CUSTOM_PROVIDER_DEFAULT_KEY = "no-key";
221+
222+/** Result of custom provider discovery. */
223+interface CustomDiscoveryResult {
224+ /** Discovered models from all reachable custom providers. */
225+ models: Model<"openai-completions">[];
226+ /** Provider name → API key for discovered providers. */
227+ providers: Map<string, string>;
228+ /** Warning messages for unreachable or invalid providers. */
229+ warnings: string[];
230+}
231+
232+/**
233+ * Discover models from user-configured OpenAI-compatible endpoints.
234+ *
235+ * Queries each provider's `/models` endpoint and constructs pi-ai Model
236+ * objects from the response. Unreachable endpoints produce a warning
237+ * instead of failing startup.
238+ *
239+ * @param customProviders - Configured custom provider entries.
240+ * @param builtInProviderNames - Names of built-in providers (to detect collisions).
241+ * @returns Discovered models, provider credentials, and warnings.
242+ */
243+export async function discoverCustomProviders(
244+ customProviders: readonly CustomProvider[],
245+ builtInProviderNames: ReadonlySet<string>,
246+): Promise<CustomDiscoveryResult> {
247+ const models: Model<"openai-completions">[] = [];
248+ const providers = new Map<string, string>();
249+ const warnings: string[] = [];
250+
251+ for (const entry of customProviders) {
252+ if (builtInProviderNames.has(entry.name)) {
253+ warnings.push(
254+ `Custom provider "${entry.name}" skipped: name conflicts with a built-in provider.`,
255+ );
256+ continue;
257+ }
258+
259+ const apiKey = entry.apiKey ?? CUSTOM_PROVIDER_DEFAULT_KEY;
260+ const modelsUrl = `${entry.baseUrl}/models`;
261+
262+ try {
263+ const response = await fetch(modelsUrl, {
264+ signal: AbortSignal.timeout(CUSTOM_PROVIDER_TIMEOUT_MS),
265+ });
266+
267+ if (!response.ok) {
268+ warnings.push(
269+ `Custom provider "${entry.name}": ${response.status} ${response.statusText} (${modelsUrl})`,
270+ );
271+ continue;
272+ }
273+
274+ const body = (await response.json()) as {
275+ data?: { id: string }[];
276+ };
277+ const modelList = body.data ?? [];
278+
279+ for (const item of modelList) {
280+ if (typeof item.id !== "string" || !item.id) continue;
281+
282+ models.push({
283+ id: item.id,
284+ name: item.id,
285+ api: "openai-completions",
286+ provider: entry.name,
287+ baseUrl: entry.baseUrl,
288+ reasoning: false,
289+ input: ["text"],
290+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
291+ contextWindow: 131072,
292+ maxTokens: 8192,
293+ });
294+ }
295+
296+ providers.set(entry.name, apiKey);
297+ } catch (error) {
298+ warnings.push(
299+ `Custom provider "${entry.name}": ${getErrorMessage(error)} (${modelsUrl})`,
300+ );
301+ }
302+ }
303+
304+ return { models, providers, warnings };
305+}
306+
211307 // ---------------------------------------------------------------------------
212308 // Model selection
213309 // ---------------------------------------------------------------------------
@@ -463,6 +559,10 @@ export interface AppState {
463559 showReasoning: boolean;
464560 /** Whether to show full (un-truncated) tool output. */
465561 verbose: boolean;
562+ /** Models discovered from custom OpenAI-compatible providers. */
563+ customModels: Model<string>[];
564+ /** Warnings from startup (e.g. unreachable custom providers). */
565+ startupWarnings: string[];
466566 }
467567
468568 // ---------------------------------------------------------------------------
@@ -481,7 +581,21 @@ export async function init(): Promise<AppState> {
481581
482582 // Load user settings and resolve startup defaults
483583 const settings = loadSettings(SETTINGS_PATH);
484- const availableModels = listAvailableModels(providers);
584+
585+ // Discover custom providers from settings
586+ const builtInProviderNames = new Set(providers.keys());
587+ const customResult = await discoverCustomProviders(
588+ settings.customProviders ?? [],
589+ builtInProviderNames,
590+ );
591+
592+ // Merge custom provider credentials
593+ for (const [name, key] of customResult.providers) {
594+ providers.set(name, key);
595+ }
596+
597+ const builtInModels = listAvailableModels(providers);
598+ const availableModels = [...builtInModels, ...customResult.models];
485599 const startup = resolveStartupSettings(
486600 settings,
487601 availableModels.map((model) => `${model.provider}/${model.id}`),
@@ -520,6 +634,8 @@ export async function init(): Promise<AppState> {
520634 activeTurnPromise: null,
521635 showReasoning: startup.showReasoning,
522636 verbose: startup.verbose,
637+ customModels: customResult.models,
638+ startupWarnings: customResult.warnings,
523639 };
524640 }
525641
@@ -592,7 +708,7 @@ export function ensureSession(
592708 * for, suitable for the `/model` selector.
593709 */
594710 export function getAvailableModels(state: AppState): Model<string>[] {
595- return listAvailableModels(state.providers);
711+ return [...listAvailableModels(state.providers), ...state.customModels];
596712 }
597713
598714 /** Clean up resources on shutdown. */
src/settings.test.ts+87−0
@@ -202,4 +202,91 @@ describe("settings", () => {
202202 verbose: false,
203203 });
204204 });
205+
206+ test("loadSettings parses valid customProviders entries", () => {
207+ const dir = createTempDir();
208+ const path = join(dir, "settings.json");
209+ writeFileSync(
210+ path,
211+ JSON.stringify({
212+ customProviders: [
213+ { name: "ollama", baseUrl: "http://localhost:11434/v1" },
214+ {
215+ name: "lm-studio",
216+ baseUrl: "http://localhost:1234/v1",
217+ apiKey: "lm-studio",
218+ },
219+ ],
220+ }),
221+ "utf-8",
222+ );
223+
224+ const settings = loadSettings(path);
225+ expect(settings.customProviders).toEqual([
226+ { name: "ollama", baseUrl: "http://localhost:11434/v1" },
227+ {
228+ name: "lm-studio",
229+ baseUrl: "http://localhost:1234/v1",
230+ apiKey: "lm-studio",
231+ },
232+ ]);
233+ });
234+
235+ test("loadSettings drops customProviders entries with missing or invalid fields", () => {
236+ const dir = createTempDir();
237+ const path = join(dir, "settings.json");
238+ writeFileSync(
239+ path,
240+ JSON.stringify({
241+ customProviders: [
242+ { name: "good", baseUrl: "http://localhost:11434/v1" },
243+ { name: "", baseUrl: "http://localhost:1234/v1" },
244+ { name: "no-url" },
245+ { baseUrl: "http://localhost:5678/v1" },
246+ "not-an-object",
247+ 42,
248+ null,
249+ ],
250+ }),
251+ "utf-8",
252+ );
253+
254+ const settings = loadSettings(path);
255+ expect(settings.customProviders).toEqual([
256+ { name: "good", baseUrl: "http://localhost:11434/v1" },
257+ ]);
258+ });
259+
260+ test("loadSettings drops duplicate customProviders names keeping the first", () => {
261+ const dir = createTempDir();
262+ const path = join(dir, "settings.json");
263+ writeFileSync(
264+ path,
265+ JSON.stringify({
266+ customProviders: [
267+ { name: "ollama", baseUrl: "http://localhost:11434/v1" },
268+ { name: "ollama", baseUrl: "http://localhost:9999/v1" },
269+ ],
270+ }),
271+ "utf-8",
272+ );
273+
274+ const settings = loadSettings(path);
275+ expect(settings.customProviders).toEqual([
276+ { name: "ollama", baseUrl: "http://localhost:11434/v1" },
277+ ]);
278+ });
279+
280+ test("loadSettings omits customProviders when the field is not an array", () => {
281+ const dir = createTempDir();
282+ const path = join(dir, "settings.json");
283+ writeFileSync(
284+ path,
285+ JSON.stringify({ customProviders: "not-an-array" }),
286+ "utf-8",
287+ );
288+
289+ const settings = loadSettings(path);
290+ expect(settings.customProviders).toBeUndefined();
291+ });
205292 });
src/settings.ts+65−0
@@ -12,6 +12,16 @@ import { dirname } from "node:path";
1212 import type { ThinkingLevel } from "@mariozechner/pi-ai";
1313 import { getErrorMessage } from "./errors.ts";
1414
15+/** A user-configured OpenAI-compatible provider endpoint. */
16+export interface CustomProvider {
17+ /** Provider identifier, e.g. "ollama". Shown as the provider prefix in model names. */
18+ name: string;
19+ /** OpenAI-compatible API base URL, e.g. "http://localhost:11434/v1". */
20+ baseUrl: string;
21+ /** Optional API key. Defaults to "no-key" at discovery time. */
22+ apiKey?: string;
23+}
24+
1525 /** Default reasoning effort when no saved setting exists. */
1626 const DEFAULT_EFFORT: ThinkingLevel = "medium";
1727
@@ -31,6 +41,8 @@ export interface UserSettings {
3141 showReasoning?: boolean;
3242 /** Whether full tool output is shown in the UI. */
3343 verbose?: boolean;
44+ /** Custom OpenAI-compatible provider endpoints. */
45+ customProviders?: CustomProvider[];
3446 }
3547
3648 /** Resolved startup settings after applying defaults and availability checks. */
@@ -172,9 +184,62 @@ function sanitizeSettings(value: unknown): UserSettings {
172184 settings.verbose = candidate.verbose;
173185 }
174186
187+ const customProviders = sanitizeCustomProviders(candidate.customProviders);
188+ if (customProviders) {
189+ settings.customProviders = customProviders;
190+ }
191+
175192 return settings;
176193 }
177194
195+/** Try to parse a single custom provider entry, returning null on failure. */
196+function parseCustomProvider(item: unknown): CustomProvider | null {
197+ if (item == null || typeof item !== "object" || Array.isArray(item)) {
198+ return null;
199+ }
200+
201+ const candidate = item as Record<string, unknown>;
202+ const name = typeof candidate.name === "string" ? candidate.name.trim() : "";
203+ const baseUrl =
204+ typeof candidate.baseUrl === "string" ? candidate.baseUrl.trim() : "";
205+
206+ if (!name || !baseUrl) {
207+ return null;
208+ }
209+
210+ const entry: CustomProvider = { name, baseUrl };
211+ if (typeof candidate.apiKey === "string") {
212+ entry.apiKey = candidate.apiKey;
213+ }
214+ return entry;
215+}
216+
217+/**
218+ * Validate and normalize custom provider entries.
219+ *
220+ * Drops entries with missing/empty name or baseUrl, and deduplicates by name
221+ * (first entry wins).
222+ */
223+function sanitizeCustomProviders(value: unknown): CustomProvider[] | undefined {
224+ if (!Array.isArray(value)) {
225+ return undefined;
226+ }
227+
228+ const result: CustomProvider[] = [];
229+ const seen = new Set<string>();
230+
231+ for (const item of value) {
232+ const entry = parseCustomProvider(item);
233+ if (!entry || seen.has(entry.name)) {
234+ continue;
235+ }
236+ seen.add(entry.name);
237+ result.push(entry);
238+ }
239+
240+ return result.length > 0 ? result : undefined;
241+}
242+
178243 /**
179244 * Check whether a value is a valid thinking level.
180245 *
src/ui.test.ts+2−0
@@ -192,6 +192,8 @@ function createTestState(): AppState {
192192 activeTurnPromise: null,
193193 showReasoning: DEFAULT_SHOW_REASONING,
194194 verbose: DEFAULT_VERBOSE,
195+ customModels: [],
196+ startupWarnings: [],
195197 };
196198 }
197199
src/ui.ts+5−0
@@ -691,4 +691,9 @@ export function startUI(state: AppState): void {
691691 if (state.running) {
692692 startDividerAnimation();
693693 }
694+
695+ // Show warnings from custom provider discovery
696+ for (const warning of state.startupWarnings) {
697+ appendInfoMessage(warning, state);
698+ }
694699 }
src/ui/commands.test.ts+2−0
@@ -91,6 +91,8 @@ function createTestState(): AppState {
9191 activeTurnPromise: null,
9292 showReasoning: true,
9393 verbose: false,
94+ customModels: [],
95+ startupWarnings: [],
9496 };
9597 }
9698
src/ui/status.test.ts+2−0
@@ -103,6 +103,8 @@ function createTestState(): AppState {
103103 activeTurnPromise: null,
104104 showReasoning: DEFAULT_SHOW_REASONING,
105105 verbose: DEFAULT_VERBOSE,
106+ customModels: [],
107+ startupWarnings: [],
106108 };
107109 }