xonecas.io
64875
Mc

mini-coder / commit 4b60f71

fix: align provider discovery and session teardown

xonecas2026-03-31 4b60f71b043a512f27234a22dc5d24fb9b5a101c parent 0665816

28 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.agents/skills/audit/SKILL.md+3−3
@@ -1,7 +1,7 @@
11 ---
22 name: audit
33 description: "Full codebase audit — code review, multi-provider UI testing, and combined report. Use when the user asks to audit, test across providers, or validate the full implementation. Triggers on: audit, full review, test providers, validate implementation."
4-compatibility: "Requires tmux, bun, git, and active provider credentials (Anthropic OAuth and/or Opencode zen)"
4+compatibility: "Requires tmux, bun, git, and active provider credentials (OpenAI OAuth and/or Opencode zen)"
55 ---
66
77 Run a complete audit of the mini-coder implementation.
@@ -35,7 +35,7 @@ Use `tmux` so you can test interactive sessions properly.
3535
3636 ### Models to use (one per SDK path)
3737
38-Opencode zen and Anthropic login are available in this environment.
38+Opencode zen and Openai login are available in this environment.
3939 Pick cheap options. Verify available models at https://opencode.ai/docs/zen/, then choose:
4040
4141 - `@ai-sdk/anthropic` path → a `zen/claude-*` haiku-class model
@@ -44,7 +44,7 @@ Pick cheap options. Verify available models at https://opencode.ai/docs/zen/, th
4444 - `@ai-sdk/openai-compatible` path → `zen/*` or similar small low-cost model
4545
4646 Avoid free models due to rate limit issues.
47-Also use an Anthropic OAuth model for completeness.
47+Also use an Openai OAuth model for completeness.
4848
4949 ### Prompts
5050
.agents/skills/mini-coder/SKILL.md+0−1
@@ -36,7 +36,6 @@ Inside `mc`:
3636 | `/verbose` | Toggle output truncation |
3737 | `/undo` | Remove last turn (does not revert filesystem) |
3838 | `/new` | Start a fresh session |
39-| `/review` | Review recent changes |
4039 | `/mcp list` | List MCP servers |
4140 | `/mcp add <name> http <url>` | Add HTTP MCP server |
4241 | `/mcp add <name> stdio <cmd> [args...]` | Add stdio MCP server |
README.md+2−2
@@ -46,13 +46,13 @@ Useful flags: `-c` continue last session, `-r <id>` resume, `-l` list sessions,
4646
4747 ## 🔑 OAuth Login
4848
49-Use `/login` inside the REPL to authenticate via browser-based OAuth. Supported providers: `anthropic` and `openai` (`/login openai` uses the Codex / ChatGPT Plus/Pro flow). No need to manage API keys manually.
49+Use `/login` inside the REPL to authenticate via browser-based OAuth. Currently supported: `openai` (`/login openai` uses the Codex / ChatGPT Plus/Pro flow). No need to manage API keys manually.
5050
5151 ---
5252
5353 ## 🛠️ Features
5454
55-- **Multi-provider** — supports Anthropic and OpenAI (direct + OAuth), plus Gemini and Ollama
55+- **Multi-provider** — supports Anthropic, OpenAI (direct + OAuth), Gemini, and Ollama
5656 - **Session memory** — SQLite-backed. Resume with `-c` or `-r <id>`
5757 - **Shell integration** — `!` prefix for inline commands, `@` to reference files with tab completion
5858 - **Web search** — `webSearch` + `webContent` tools when `EXA_API_KEY` is set
TODO.md+1−1
@@ -1,3 +1,3 @@
11 # mini-coder TODO
22
3-Nothing pending.
3+_No open items._
docs/mini-coder.1.md+7−6
@@ -177,16 +177,17 @@ Local discovery walks up from cwd to the git worktree root.
177177
178178 Config roots: `.agents/`, `.claude/` — local (repo) or global (`~/`).
179179
180-**Context files** (one global + one local loaded into the system prompt):
180+**Context files** (global files first, then the nearest local directory with context files):
181181
182-- Global: `~/.agents/AGENTS.md` → `~/.agents/CLAUDE.md`
183-- Local: `./.agents/AGENTS.md` → `./CLAUDE.md` → `./AGENTS.md`
182+- Global files concatenate in this order: `~/.agents/AGENTS.md` → `~/.agents/CLAUDE.md` → `~/.claude/CLAUDE.md`
183+- Local files concatenate in this order within the nearest matching directory: `./.agents/AGENTS.md` → `./.agents/CLAUDE.md` → `./.claude/CLAUDE.md` → `./CLAUDE.md` → `./AGENTS.md`
184184
185185 **Precedence:**
186186
187-1. Local overrides global.
188-2. Same scope: `.agents` wins over `.claude`.
189-3. Skills: nearest ancestor directory wins.
187+1. Local context is loaded from the nearest directory between cwd and the git root.
188+2. Within one scope, matching files are concatenated in the order above.
189+3. Global context appears before local context in the system prompt.
190+4. Skills: nearest ancestor directory wins.
190191
191192 ## ENVIRONMENT
192193
src/agent/agent.ts+34−4
@@ -3,6 +3,8 @@ import type { CommandContext } from "../cli/types.ts";
33 import type { ThinkingEffort } from "../llm-api/providers.ts";
44 import type { ToolDef } from "../llm-api/types.ts";
55 import { connectMcpServer } from "../mcp/client.ts";
6+import { McpClientRegistry } from "../mcp/client-registry.ts";
7+import { reconnectMcpTools } from "../mcp/tool-sync.ts";
68 import {
79 listMcpServers,
810 setPreferredModel,
@@ -31,8 +33,9 @@ export async function initAgent(opts: AgentOptions): Promise<{
3133 const cwd = opts.cwd;
3234 const tools: ToolDef[] = buildToolSet({ cwd });
3335 const mcpTools: ToolDef[] = [];
36+ const mcpClients = new McpClientRegistry();
3437
35- async function connectAndAddMcp(name: string): Promise<void> {
38+ async function connectMcpClient(name: string) {
3639 const rows = listMcpServers();
3740 const row = rows.find((r) => r.name === name);
3841 if (!row) throw new Error(`MCP server "${name}" not found in DB`);
@@ -44,11 +47,29 @@ export async function initAgent(opts: AgentOptions): Promise<{
4447 ...(row.args ? { args: JSON.parse(row.args) } : {}),
4548 ...(row.env ? { env: JSON.parse(row.env) } : {}),
4649 };
47- const client = await connectMcpServer(cfg);
50+ return connectMcpServer(cfg);
51+ }
52+
53+ async function connectAndAddMcp(name: string): Promise<void> {
54+ const client = await connectMcpClient(name);
55+ mcpClients.add(client);
4856 tools.push(...client.tools);
4957 mcpTools.push(...client.tools);
5058 }
5159
60+ async function reconnectConfiguredMcpServers(): Promise<void> {
61+ await reconnectMcpTools({
62+ tools,
63+ mcpTools,
64+ clients: mcpClients,
65+ names: listMcpServers().map((row) => row.name),
66+ connectByName: connectMcpClient,
67+ onError: (name, error) => {
68+ opts.reporter.error(`MCP: failed to connect ${name}: ${String(error)}`);
69+ },
70+ });
71+ }
72+
5273 for (const row of listMcpServers()) {
5374 try {
5475 await connectAndAddMcp(row.name);
@@ -68,6 +89,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
6889 initialShowReasoning: opts.initialShowReasoning,
6990 initialVerboseOutput: opts.initialVerboseOutput,
7091 sessionId: opts.sessionId,
92+ onTeardown: () => mcpClients.closeAll(),
7193 });
7294
7395 const cmdCtx: CommandContext = {
@@ -105,8 +127,16 @@ export async function initAgent(opts: AgentOptions): Promise<{
105127 connectMcpServer: connectAndAddMcp,
106128 startSpinner: (label?: string) => opts.reporter.startSpinner(label),
107129 stopSpinner: () => opts.reporter.stopSpinner(),
108- startNewSession: () => runner.startNewSession(),
109- switchSession: (id: string) => runner.switchSession(id),
130+ startNewSession: async () => {
131+ runner.startNewSession();
132+ await reconnectConfiguredMcpServers();
133+ },
134+ switchSession: async (id: string) => {
135+ const switched = runner.switchSession(id);
136+ if (!switched) return false;
137+ await reconnectConfiguredMcpServers();
138+ return true;
139+ },
110140 };
111141
112142 return { runner, cmdCtx };
src/agent/run-with-teardown.test.ts+93−0
@@ -0,0 +1,93 @@
1+import { describe, expect, test } from "bun:test";
2+import { RenderedError } from "../cli/output.ts";
3+import { runWithTeardown } from "./run-with-teardown.ts";
4+
5+describe("runWithTeardown", () => {
6+ test("runs teardown after success", async () => {
7+ const events: string[] = [];
8+
9+ await runWithTeardown({
10+ run: async () => {
11+ events.push("run");
12+ },
13+ teardown: async () => {
14+ events.push("teardown");
15+ },
16+ renderError: () => {
17+ events.push("render");
18+ },
19+ });
20+
21+ expect(events).toEqual(["run", "teardown"]);
22+ });
23+
24+ test("renders once, wraps, and still tears down on ordinary errors", async () => {
25+ const events: string[] = [];
26+
27+ await expect(
28+ runWithTeardown({
29+ run: async () => {
30+ events.push("run");
31+ throw new Error("boom");
32+ },
33+ teardown: async () => {
34+ events.push("teardown");
35+ },
36+ renderError: () => {
37+ events.push("render");
38+ },
39+ }),
40+ ).rejects.toBeInstanceOf(RenderedError);
41+
42+ expect(events).toEqual(["run", "render", "teardown"]);
43+ });
44+
45+ test("passes through RenderedError without double-rendering and still tears down", async () => {
46+ const events: string[] = [];
47+ const rendered = new RenderedError(new Error("already rendered"));
48+
49+ await expect(
50+ runWithTeardown({
51+ run: async () => {
52+ events.push("run");
53+ throw rendered;
54+ },
55+ teardown: async () => {
56+ events.push("teardown");
57+ },
58+ renderError: () => {
59+ events.push("render");
60+ },
61+ }),
62+ ).rejects.toBe(rendered);
63+
64+ expect(events).toEqual(["run", "teardown"]);
65+ });
66+
67+ test("preserves the primary rendered failure when teardown also fails", async () => {
68+ const events: string[] = [];
69+
70+ await expect(
71+ runWithTeardown({
72+ run: async () => {
73+ events.push("run");
74+ throw new Error("primary");
75+ },
76+ teardown: async () => {
77+ events.push("teardown");
78+ throw new Error("teardown");
79+ },
80+ renderError: (error) => {
81+ events.push(
82+ `render:${error instanceof Error ? error.message : String(error)}`,
83+ );
84+ },
85+ }),
86+ ).rejects.toMatchObject({
87+ name: "RenderedError",
88+ cause: expect.objectContaining({ message: "primary" }),
89+ });
90+
91+ expect(events).toEqual(["run", "render:primary", "teardown"]);
92+ });
93+});
src/agent/run-with-teardown.ts+36−0
@@ -0,0 +1,36 @@
1+import { RenderedError } from "../cli/output.ts";
2+
3+interface RunWithTeardownOptions<T> {
4+ run: () => Promise<T>;
5+ teardown?: () => Promise<void>;
6+ renderError: (error: unknown) => void;
7+}
8+
9+export async function runWithTeardown<T>(
10+ opts: RunWithTeardownOptions<T>,
11+): Promise<T> {
12+ let hasPrimaryError = false;
13+ let primaryError: unknown;
14+ let result: T | undefined;
15+
16+ try {
17+ result = await opts.run();
18+ } catch (error) {
19+ hasPrimaryError = true;
20+ if (error instanceof RenderedError) {
21+ primaryError = error;
22+ } else {
23+ opts.renderError(error);
24+ primaryError = new RenderedError(error);
25+ }
26+ }
27+
28+ try {
29+ await opts.teardown?.();
30+ } catch (teardownError) {
31+ if (!hasPrimaryError) throw teardownError;
32+ }
33+
34+ if (hasPrimaryError) throw primaryError;
35+ return result as T;
36+}
src/agent/session-runner.test.ts+125−0
@@ -0,0 +1,125 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+
6+const sessionRunnerModuleUrl = new URL("./session-runner.ts", import.meta.url)
7+ .href;
8+const skillsModuleUrl = new URL("../tools/skills.ts", import.meta.url).href;
9+
10+function runInHome(
11+ home: string,
12+ cwd: string,
13+ script: string,
14+): {
15+ exitCode: number;
16+ stdout: string;
17+ stderr: string;
18+} {
19+ const scriptPath = join(
20+ tmpdir(),
21+ `mc-session-runner-test-${process.pid}-${Date.now()}.mjs`,
22+ );
23+ writeFileSync(scriptPath, script);
24+ try {
25+ const result = Bun.spawnSync([process.execPath, scriptPath], {
26+ cwd,
27+ env: { ...process.env, HOME: home },
28+ stdout: "pipe",
29+ stderr: "pipe",
30+ });
31+ return {
32+ exitCode: result.exitCode,
33+ stdout: result.stdout.toString(),
34+ stderr: result.stderr.toString(),
35+ };
36+ } finally {
37+ rmSync(scriptPath, { force: true });
38+ }
39+}
40+
41+describe("SessionRunner session switching", () => {
42+ let cwd = "";
43+ let fakeHome = "";
44+
45+ beforeEach(() => {
46+ cwd = mkdtempSync(join(tmpdir(), "mc-session-runner-cwd-"));
47+ fakeHome = mkdtempSync(join(tmpdir(), "mc-session-runner-home-"));
48+ const skillDir = join(cwd, ".agents", "skills", "deploy");
49+ mkdirSync(skillDir, { recursive: true });
50+ writeFileSync(
51+ join(skillDir, "SKILL.md"),
52+ "---\nname: deploy\ndescription: Deploy app\n---\n\nFull body",
53+ );
54+ });
55+
56+ afterEach(() => {
57+ rmSync(cwd, { recursive: true, force: true });
58+ rmSync(fakeHome, { recursive: true, force: true });
59+ });
60+
61+ test("switchSession resets activated skill state", () => {
62+ const result = runInHome(
63+ fakeHome,
64+ cwd,
65+ `
66+ import { SessionRunner } from ${JSON.stringify(sessionRunnerModuleUrl)};
67+ import { readSkillTool } from ${JSON.stringify(skillsModuleUrl)};
68+
69+ const reporter = {
70+ info() {},
71+ error() {},
72+ warn() {},
73+ writeText() {},
74+ startSpinner() {},
75+ stopSpinner() {},
76+ async renderTurn() {
77+ throw new Error("renderTurn should not be called in this test");
78+ },
79+ renderStatusBar() {},
80+ restoreTerminal() {},
81+ };
82+
83+ const runner = new SessionRunner({
84+ cwd: ${JSON.stringify(cwd)},
85+ reporter,
86+ tools: [],
87+ mcpTools: [],
88+ initialModel: "ollama/llama3.2",
89+ initialThinkingEffort: null,
90+ initialShowReasoning: false,
91+ initialVerboseOutput: false,
92+ });
93+
94+ const firstSessionId = runner.session.id;
95+ const firstRead = await readSkillTool.execute({ cwd: ${JSON.stringify(cwd)}, name: "deploy" });
96+ const cachedRead = await readSkillTool.execute({ cwd: ${JSON.stringify(cwd)}, name: "deploy" });
97+ runner.startNewSession();
98+ const secondSessionId = runner.session.id;
99+ const secondRead = await readSkillTool.execute({ cwd: ${JSON.stringify(cwd)}, name: "deploy" });
100+ const switched = runner.switchSession(firstSessionId);
101+ const afterSwitchRead = await readSkillTool.execute({ cwd: ${JSON.stringify(cwd)}, name: "deploy" });
102+
103+ console.log(JSON.stringify({
104+ firstSessionId,
105+ secondSessionId,
106+ switched,
107+ firstRead: firstRead.skill?.name ?? null,
108+ cachedRead: cachedRead.skill?.name ?? null,
109+ secondRead: secondRead.skill?.name ?? null,
110+ afterSwitchRead: afterSwitchRead.skill?.name ?? null,
111+ }));
112+ `,
113+ );
114+
115+ expect(result.exitCode).toBe(0);
116+ expect(result.stderr).toBe("");
117+ expect(JSON.parse(result.stdout)).toMatchObject({
118+ switched: true,
119+ firstRead: "deploy",
120+ cachedRead: null,
121+ secondRead: "deploy",
122+ afterSwitchRead: "deploy",
123+ });
124+ });
125+});
src/agent/session-runner.ts+8−0
@@ -40,6 +40,7 @@ interface SessionRunnerOptions {
4040 initialShowReasoning: boolean;
4141 initialVerboseOutput: boolean;
4242 sessionId?: string | undefined;
43+ onTeardown?: () => Promise<void>;
4344 }
4445
4546 interface RunnerStatusInfo {
@@ -71,6 +72,7 @@ export class SessionRunner {
7172 private totalOut = 0;
7273 private lastContextTokens = 0;
7374 private _systemPrompt: string | undefined;
75+ private readonly onTeardown: (() => Promise<void>) | undefined;
7476
7577 constructor(opts: SessionRunnerOptions) {
7678 this.cwd = opts.cwd;
@@ -81,6 +83,7 @@ export class SessionRunner {
8183 this.currentThinkingEffort = opts.initialThinkingEffort;
8284 this.showReasoning = opts.initialShowReasoning;
8385 this.verboseOutput = opts.initialVerboseOutput;
86+ this.onTeardown = opts.onTeardown;
8487 this.initSession(opts.sessionId);
8588 }
8689
@@ -134,6 +137,7 @@ export class SessionRunner {
134137 this.session = resumed;
135138 this.currentModel = resumed.model;
136139 this.coreHistory = [...resumed.messages];
140+ resetActivatedSkills();
137141 this.turnIndex = getMaxTurnIndex(resumed.id) + 1;
138142 this.totalIn = 0;
139143 this.totalOut = 0;
@@ -143,6 +147,10 @@ export class SessionRunner {
143147 return true;
144148 }
145149
150+ public async teardown(): Promise<void> {
151+ await this.onTeardown?.();
152+ }
153+
146154 public addShellContext(command: string, output: string): void {
147155 const thisTurn = this.turnIndex++;
148156 const msg: CoreMessage = {
src/cli/commands-session.ts+2−2
@@ -12,7 +12,7 @@ export async function handleSessionCommand(
1212 const id = args.trim();
1313 if (id) {
1414 ctx.startSpinner("switching session");
15- const ok = ctx.switchSession(id);
15+ const ok = await ctx.switchSession(id);
1616 ctx.stopSpinner();
1717 if (ok) {
1818 writeln(
@@ -51,7 +51,7 @@ export async function handleSessionCommand(
5151 }
5252 if (!picked) return;
5353
54- const ok = ctx.switchSession(picked);
54+ const ok = await ctx.switchSession(picked);
5555 if (ok) {
5656 writeln(
5757 `${PREFIX.success} switched to session ${c.cyan(picked)} (${c.cyan(ctx.currentModel)})`,
src/cli/commands.ts+4−4
@@ -37,11 +37,11 @@ async function handleUndo(ctx: CommandContext): Promise<void> {
3737 }
3838 }
3939
40-function handleNew(ctx: CommandContext): void {
41- ctx.startNewSession();
40+async function handleNew(ctx: CommandContext): Promise<void> {
41+ await ctx.startNewSession();
4242 // Clear terminal and reprint banner for a fresh session feel
4343 process.stdout.write("\x1b[2J\x1b[H");
44- renderBanner(ctx.currentModel, ctx.cwd);
44+ await renderBanner(ctx.currentModel, ctx.cwd);
4545 }
4646
4747 // ─── Dispatch ─────────────────────────────────────────────────────────────────
@@ -87,7 +87,7 @@ export async function handleCommand(
8787 return { type: "handled" };
8888
8989 case "new":
90- handleNew(ctx);
90+ await handleNew(ctx);
9191 return { type: "handled" };
9292
9393 case "help":
src/cli/output.test.ts+4−2
@@ -32,10 +32,12 @@ describe("renderUserMessage", () => {
3232 });
3333
3434 describe("renderBanner", () => {
35- test("uses a tilde path in the header", () => {
35+ test("uses a tilde path in the header", async () => {
3636 captureStdout();
3737
38- renderBanner("zen/gpt-5.4", `${process.env.HOME}/src/mini-coder`);
38+ await renderBanner("zen/gpt-5.4", `${process.env.HOME}/src/mini-coder`, [
39+ { name: "zen", via: "env" },
40+ ]);
3941
4042 expect(stripAnsi(getCapturedStdout())).toContain(
4143 "zen/gpt-5.4 · ~/src/mini-coder",
src/cli/output.ts+10−3
@@ -7,6 +7,7 @@ import type {
77 TurnResult,
88 } from "../agent/reporter.ts";
99 import { PACKAGE_VERSION } from "../internal/version.ts";
10+import type { ConnectedProvider } from "../llm-api/provider-discovery.ts";
1011 import { discoverConnectedProviders } from "../llm-api/providers.ts";
1112 import type { TurnEvent } from "../llm-api/types.ts";
1213 import { logError } from "../logging/context.ts";
@@ -108,7 +109,11 @@ export function renderError(err: unknown, context = "render"): void {
108109
109110 // ─── Banner ───────────────────────────────────────────────────────────────────
110111
111-export function renderBanner(model: string, cwd: string): void {
112+export async function renderBanner(
113+ model: string,
114+ cwd: string,
115+ connectedProviders?: ConnectedProvider[],
116+): Promise<void> {
112117 writeln();
113118 const title = PACKAGE_VERSION
114119 ? `mini-coder · v${PACKAGE_VERSION}`
@@ -132,8 +137,10 @@ export function renderBanner(model: string, cwd: string): void {
132137 }
133138
134139 const connParts: string[] = [];
135- for (const p of discoverConnectedProviders()) {
136- connParts.push(p.via === "oauth" ? `${p.name} (oauth)` : p.name);
140+ for (const p of connectedProviders ?? (await discoverConnectedProviders())) {
141+ if (p.via === "oauth") connParts.push(`${p.name} (oauth)`);
142+ else if (p.via === "local") connParts.push(`${p.name} (local)`);
143+ else connParts.push(p.name);
137144 }
138145 const mcpCount = listMcpServers().length;
139146 if (mcpCount > 0) connParts.push(`${mcpCount} mcp`);
src/cli/skills.ts+2−0
@@ -25,6 +25,7 @@ export interface SkillMeta {
2525
2626 export interface LoadedSkillContent {
2727 name: string;
28+ description: string;
2829 content: string;
2930 source: "global" | "local";
3031 skillDir: string;
@@ -339,6 +340,7 @@ export function loadSkillContentFromMeta(
339340 const skillDir = dirname(skill.filePath);
340341 return {
341342 name: skill.name,
343+ description: skill.description,
342344 content,
343345 source: skill.source,
344346 skillDir,
src/cli/types.ts+2−2
@@ -9,8 +9,8 @@ export interface CommandContext {
99 verboseOutput: boolean;
1010 setVerboseOutput: (verbose: boolean) => void;
1111 undoLastTurn: () => Promise<boolean>;
12- startNewSession: () => void;
13- switchSession: (id: string) => boolean;
12+ startNewSession: () => Promise<void>;
13+ switchSession: (id: string) => Promise<boolean>;
1414
1515 connectMcpServer: (name: string) => Promise<void>;
1616
src/index.ts+61−39
@@ -5,6 +5,7 @@ globalThis.AI_SDK_LOG_WARNINGS = false;
55
66 import * as c from "yoctocolors";
77 import { initAgent } from "./agent/agent.ts";
8+import { runWithTeardown } from "./agent/run-with-teardown.ts";
89 import { parseArgs, printHelp } from "./cli/args.ts";
910
1011 import { resolveFileRefs } from "./cli/file-refs.ts";
@@ -24,7 +25,11 @@ import {
2425 initModelInfoCache,
2526 refreshModelInfoInBackground,
2627 } from "./llm-api/model-info.ts";
27-import { autoDiscoverModel } from "./llm-api/providers.ts";
28+import { getLocalProviderNames } from "./llm-api/provider-discovery.ts";
29+import {
30+ autoDiscoverModel,
31+ discoverConnectedProviders,
32+} from "./llm-api/providers.ts";
2833
2934 import {
3035 getPreferredModel,
@@ -40,7 +45,6 @@ import { getMostRecentSession, printSessionList } from "./session/manager.ts";
4045 registerTerminalCleanup();
4146 initModelInfoCache();
4247 pruneOldData();
43-void refreshModelInfoInBackground().catch(() => {});
4448
4549 type AgentInitOptions = Parameters<typeof initAgent>[0];
4650
@@ -103,50 +107,68 @@ async function main(): Promise<void> {
103107
104108 // Determine model: CLI flag > persisted user preference > auto-discover
105109 const model = args.model ?? getPreferredModel() ?? autoDiscoverModel();
110+ const connectedProviders = prompt
111+ ? undefined
112+ : await discoverConnectedProviders();
113+
114+ const startupLocalProviders = connectedProviders
115+ ? getLocalProviderNames(connectedProviders)
116+ : undefined;
117+ void refreshModelInfoInBackground(
118+ startupLocalProviders
119+ ? { localProviders: startupLocalProviders }
120+ : undefined,
121+ ).catch(() => {});
106122
107123 if (!prompt) {
108124 // Only show banner for interactive sessions, not piped/one-shot
109- renderBanner(model, args.cwd);
125+ await renderBanner(model, args.cwd, connectedProviders);
110126 }
111127
112- try {
113- const oneShot = !!prompt;
114- const agentOpts = buildAgentOptions({
115- model,
116- cwd: args.cwd,
117- reporter: new CliReporter(oneShot),
118- sessionId,
119- });
120-
121- const { runner, cmdCtx } = await initAgent(agentOpts);
122-
123- if (oneShot) {
124- const { text: resolvedText, images: refImages } = await resolveFileRefs(
125- prompt,
126- args.cwd,
127- );
128- const responseText = await runner.processUserInput(
129- resolvedText,
130- refImages,
131- );
132- if (responseText) {
133- writeln(responseText.trimStart());
128+ let runner: Awaited<ReturnType<typeof initAgent>>["runner"] | null = null;
129+ const oneShot = !!prompt;
130+ const agentOpts = buildAgentOptions({
131+ model,
132+ cwd: args.cwd,
133+ reporter: new CliReporter(oneShot),
134+ sessionId,
135+ });
136+
137+ await runWithTeardown({
138+ run: async () => {
139+ const init = await initAgent(agentOpts);
140+ runner = init.runner;
141+ const { cmdCtx } = init;
142+
143+ if (oneShot) {
144+ const { text: resolvedText, images: refImages } = await resolveFileRefs(
145+ prompt,
146+ args.cwd,
147+ );
148+ const responseText = await runner.processUserInput(
149+ resolvedText,
150+ refImages,
151+ );
152+ if (responseText) {
153+ writeln(responseText.trimStart());
154+ }
155+ return;
134156 }
135- return;
136- }
137157
138- await runInputLoop({
139- cwd: args.cwd,
140- reporter: agentOpts.reporter,
141- cmdCtx,
142- runner,
143- });
144- } catch (err) {
145- if (!(err instanceof RenderedError)) {
146- renderError(err, "agent");
147- }
148- process.exit(1);
149- }
158+ await runInputLoop({
159+ cwd: args.cwd,
160+ reporter: agentOpts.reporter,
161+ cmdCtx,
162+ runner,
163+ });
164+ },
165+ teardown: () => runner?.teardown() ?? Promise.resolve(),
166+ renderError: (err) => {
167+ if (!(err instanceof RenderedError)) {
168+ renderError(err, "agent");
169+ }
170+ },
171+ });
150172 }
151173
152174 main().then(
src/llm-api/model-info.test.ts+28−9
@@ -11,6 +11,7 @@ import {
1111 normalizeModelId,
1212 parseModelsDevCapabilities,
1313 resolveModelInfoFromRows,
14+ shouldBlockOnMissingVisibleProviderModels,
1415 } from "./model-info.ts";
1516
1617 const openAIOAuth = isLoggedIn("openai");
@@ -25,20 +26,20 @@ describe("provider sync policy", () => {
2526 ).toEqual(["openai", "google"]);
2627 });
2728
28- test("refresh providers include anthropic only from env", () => {
29+ test("refresh providers include reachable local providers only when discovered", () => {
2930 expect(getProvidersToRefreshFromEnv({ OPENAI_API_KEY: "x" })).toEqual([
3031 "openai",
31- "ollama",
3232 ]);
3333
34- expect(getProvidersToRefreshFromEnv({ ANTHROPIC_API_KEY: "x" })).toEqual([
35- "anthropic",
36- ...(openAIOAuth ? ["openai"] : []),
37- "ollama",
38- ]);
34+ expect(
35+ getProvidersToRefreshFromEnv(
36+ { ANTHROPIC_API_KEY: "x" },
37+ { localProviders: ["ollama"] },
38+ ),
39+ ).toEqual(["anthropic", ...(openAIOAuth ? ["openai"] : []), "ollama"]);
3940 });
4041
41- test("snapshot visibility tracks configured providers", () => {
42+ test("snapshot visibility tracks configured and discovered providers", () => {
4243 expect(isProviderVisibleInSnapshot("openai", { OPENAI_API_KEY: "x" })).toBe(
4344 true,
4445 );
@@ -46,12 +47,30 @@ describe("provider sync policy", () => {
4647 expect(
4748 isProviderVisibleInSnapshot("anthropic", { ANTHROPIC_API_KEY: "x" }),
4849 ).toBe(true);
49- expect(isProviderVisibleInSnapshot("ollama", {})).toBe(true);
50+ expect(isProviderVisibleInSnapshot("ollama", {})).toBe(false);
51+ expect(
52+ isProviderVisibleInSnapshot("ollama", {}, { localProviders: ["ollama"] }),
53+ ).toBe(true);
5054 expect(isProviderVisibleInSnapshot("zen", {})).toBe(false);
5155 expect(isProviderVisibleInSnapshot("zen", { OPENCODE_API_KEY: "x" })).toBe(
5256 true,
5357 );
5458 });
59+
60+ test("blocks when visible providers are missing cached models", () => {
61+ expect(
62+ shouldBlockOnMissingVisibleProviderModels({
63+ hasAnyCachedModels: true,
64+ hasCachedModelsForAllVisibleProviders: false,
65+ }),
66+ ).toBe(true);
67+ expect(
68+ shouldBlockOnMissingVisibleProviderModels({
69+ hasAnyCachedModels: true,
70+ hasCachedModelsForAllVisibleProviders: true,
71+ }),
72+ ).toBe(false);
73+ });
5574 });
5675
5776 describe("parseModelsDevCapabilities", () => {
src/llm-api/model-info.ts+87−55
@@ -29,6 +29,13 @@ import {
2929 matchCanonicalModelId,
3030 parseModelsDevCapabilities,
3131 } from "./model-info-normalize.ts";
32+import {
33+ getKnownLocalProviders,
34+ getRemoteConfiguredProviders,
35+ getVisibleProviders,
36+ isLocalProviderConnectionStateStale,
37+ refreshLocalProviderConnections,
38+} from "./provider-discovery.ts";
3239
3340 const MODELS_DEV_SYNC_KEY = "last_models_dev_sync_at";
3441 const PROVIDER_SYNC_KEY_PREFIX = "last_provider_sync_at:";
@@ -44,16 +51,6 @@ export {
4451 } from "./model-info-normalize.ts";
4552 export type { LiveModel };
4653
47-const REMOTE_PROVIDER_ENV_KEYS: ReadonlyArray<{
48- provider: string;
49- envKeys: readonly string[];
50-}> = [
51- { provider: "zen", envKeys: ["OPENCODE_API_KEY"] },
52- { provider: "openai", envKeys: ["OPENAI_API_KEY"] },
53- { provider: "anthropic", envKeys: ["ANTHROPIC_API_KEY"] },
54- { provider: "google", envKeys: ["GOOGLE_API_KEY", "GEMINI_API_KEY"] },
55-];
56-
5754 export interface AvailableModelsSnapshot {
5855 models: LiveModel[];
5956 stale: boolean;
@@ -99,52 +96,53 @@ function parseStateInt(key: string): number | null {
9996 return value;
10097 }
10198
102-function hasAnyEnvKey(
103- env: Record<string, string | undefined>,
104- keys: readonly string[],
105-): boolean {
106- for (const key of keys) {
107- if (env[key]) return true;
108- }
109- return false;
110-}
111-
11299 export function getRemoteProvidersFromEnv(
113100 env: Record<string, string | undefined>,
114101 ): string[] {
115- const providers = REMOTE_PROVIDER_ENV_KEYS.filter((entry) =>
116- hasAnyEnvKey(env, entry.envKeys),
117- ).map((entry) => entry.provider);
118-
119- // Include providers with OAuth login even without env keys.
120- if (!providers.includes("openai") && isLoggedIn("openai")) {
121- providers.push("openai");
122- }
123-
124- return providers;
102+ return getRemoteConfiguredProviders(env, {
103+ openaiLoggedIn: isLoggedIn("openai"),
104+ });
125105 }
126106
127107 export function getProvidersToRefreshFromEnv(
128108 env: Record<string, string | undefined>,
109+ opts?: { localProviders?: readonly string[] },
129110 ): string[] {
130- return [...getRemoteProvidersFromEnv(env), "ollama"];
111+ const localProviders = opts?.localProviders;
112+ return getVisibleProviders(env, {
113+ openaiLoggedIn: isLoggedIn("openai"),
114+ ...(localProviders ? { localProviders } : {}),
115+ });
131116 }
132117
133118 function getVisibleProvidersForSnapshotFromEnv(
134119 env: Record<string, string | undefined>,
120+ opts?: { localProviders?: readonly string[] },
135121 ): ReadonlySet<string> {
136- return new Set(getProvidersToRefreshFromEnv(env));
122+ const localProviders = opts?.localProviders;
123+ return new Set(
124+ getProvidersToRefreshFromEnv(
125+ env,
126+ localProviders ? { localProviders } : undefined,
127+ ),
128+ );
137129 }
138130
139131 export function isProviderVisibleInSnapshot(
140132 provider: string,
141133 env: Record<string, string | undefined>,
134+ opts?: { localProviders?: readonly string[] },
142135 ): boolean {
143- return getVisibleProvidersForSnapshotFromEnv(env).has(provider);
136+ return getVisibleProvidersForSnapshotFromEnv(env, opts).has(provider);
144137 }
145138
146-function getConfiguredProvidersForSync(): string[] {
147- return getProvidersToRefreshFromEnv(process.env);
139+function getConfiguredProvidersForSync(
140+ localProviders?: readonly string[],
141+): string[] {
142+ return getProvidersToRefreshFromEnv(
143+ process.env,
144+ localProviders ? { localProviders } : undefined,
145+ );
148146 }
149147
150148 function getProvidersRequiredForFreshness(): string[] {
@@ -159,6 +157,7 @@ function isModelInfoStale(now = Date.now()): boolean {
159157 ensureLoaded();
160158 if (parseStateInt(CACHE_VERSION_KEY) !== CACHE_VERSION) return true;
161159 if (isStaleTimestamp(parseStateInt(MODELS_DEV_SYNC_KEY), now)) return true;
160+ if (isLocalProviderConnectionStateStale(now)) return true;
162161 for (const provider of getProvidersRequiredForFreshness()) {
163162 const providerSync = parseStateInt(getProviderSyncKey(provider));
164163 if (isStaleTimestamp(providerSync, now)) return true;
@@ -193,10 +192,14 @@ function providerRowsFromCandidates(
193192 }));
194193 }
195194
196-async function refreshModelInfoInternal(): Promise<void> {
195+async function refreshModelInfoInternal(
196+ localProviders?: readonly string[],
197+): Promise<void> {
197198 ensureLoaded();
198199 const now = Date.now();
199- const providers = getConfiguredProvidersForSync();
200+ const discoveredLocalProviders =
201+ localProviders ?? (await refreshLocalProviderConnections(process.env));
202+ const providers = getConfiguredProvidersForSync(discoveredLocalProviders);
200203 const providerResults = await Promise.all(
201204 providers.map(async (provider) => ({
202205 provider,
@@ -230,14 +233,27 @@ async function refreshModelInfoInternal(): Promise<void> {
230233
231234 export function refreshModelInfoInBackground(opts?: {
232235 force?: boolean;
236+ localProviders?: readonly string[];
233237 }): Promise<void> {
234238 ensureLoaded();
235239 const force = opts?.force ?? false;
236- if (!force && !isModelInfoStale()) return Promise.resolve();
240+ if (
241+ !force &&
242+ !isModelInfoStale() &&
243+ !shouldBlockOnMissingVisibleProviderModels({
244+ hasAnyCachedModels: runtimeCache.providerModelsByKey.size > 0,
245+ hasCachedModelsForAllVisibleProviders:
246+ hasCachedModelsForAllVisibleProviders(),
247+ })
248+ ) {
249+ return Promise.resolve();
250+ }
237251 if (refreshInFlight) return refreshInFlight;
238- refreshInFlight = refreshModelInfoInternal().finally(() => {
239- refreshInFlight = null;
240- });
252+ refreshInFlight = refreshModelInfoInternal(opts?.localProviders).finally(
253+ () => {
254+ refreshInFlight = null;
255+ },
256+ );
241257 return refreshInFlight;
242258 }
243259
@@ -275,7 +291,9 @@ export function supportsThinking(modelString: string): boolean {
275291 /** Return cached model IDs synchronously (for Tab-completion). */
276292 export function getCachedModelIds(): string[] {
277293 ensureLoaded();
278- const visible = getVisibleProvidersForSnapshotFromEnv(process.env);
294+ const visible = getVisibleProvidersForSnapshotFromEnv(process.env, {
295+ localProviders: getKnownLocalProviders(),
296+ });
279297 const ids: string[] = [];
280298 for (const row of runtimeCache.providerModelsByKey.values()) {
281299 if (visible.has(row.provider)) {
@@ -287,7 +305,9 @@ export function getCachedModelIds(): string[] {
287305 }
288306
289307 function hasCachedModelsForAllVisibleProviders(): boolean {
290- const visible = getVisibleProvidersForSnapshotFromEnv(process.env);
308+ const visible = getVisibleProvidersForSnapshotFromEnv(process.env, {
309+ localProviders: getKnownLocalProviders(),
310+ });
291311 for (const provider of visible) {
292312 let found = false;
293313 for (const row of runtimeCache.providerModelsByKey.values()) {
@@ -301,24 +321,36 @@ function hasCachedModelsForAllVisibleProviders(): boolean {
301321 return true;
302322 }
303323
324+export function shouldBlockOnMissingVisibleProviderModels(opts: {
325+ hasAnyCachedModels: boolean;
326+ hasCachedModelsForAllVisibleProviders: boolean;
327+}): boolean {
328+ return (
329+ !opts.hasAnyCachedModels || !opts.hasCachedModelsForAllVisibleProviders
330+ );
331+}
332+
304333 export async function fetchAvailableModelsSnapshot(): Promise<AvailableModelsSnapshot> {
305334 ensureLoaded();
306- if (isModelInfoStale() && !isModelInfoRefreshing()) {
307- // Block when the cache is empty or a visible provider has no cached models
308- // (e.g. user just logged in via OAuth). Otherwise refresh in background.
309- if (
310- runtimeCache.providerModelsByKey.size === 0 ||
311- !hasCachedModelsForAllVisibleProviders()
312- ) {
313- await refreshModelInfoInBackground({ force: true });
314- } else {
315- void refreshModelInfoInBackground();
316- }
335+ const stale = isModelInfoStale();
336+ const shouldBlock = shouldBlockOnMissingVisibleProviderModels({
337+ hasAnyCachedModels: runtimeCache.providerModelsByKey.size > 0,
338+ hasCachedModelsForAllVisibleProviders:
339+ hasCachedModelsForAllVisibleProviders(),
Cut short: this commit's diff is over 1000 lines.
src/llm-api/provider-discovery.test.ts+81−0
Cut short: this commit's diff is over 1000 lines.
src/llm-api/provider-discovery.ts+139−0
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers-resolve.test.ts+35−1
Cut short: this commit's diff is over 1000 lines.
src/llm-api/providers.ts+11−18
Cut short: this commit's diff is over 1000 lines.
src/mcp/client-registry.test.ts+44−0
Cut short: this commit's diff is over 1000 lines.
src/mcp/client-registry.ts+17−0
Cut short: this commit's diff is over 1000 lines.
src/mcp/tool-sync.test.ts+83−0
Cut short: this commit's diff is over 1000 lines.
src/mcp/tool-sync.ts+42−0
Cut short: this commit's diff is over 1000 lines.
src/tools/skills.test.ts+2−1
Cut short: this commit's diff is over 1000 lines.