xonecas.io
64875
Mc

mini-coder / commit 413a5bd

feat: add entry point, unify tool result types, remove AgentTool wrapper

- index.ts: provider discovery (env + OAuth), model selection (first
  available or null), context loading (AGENTS.md, skills, plugins),
  session creation, tool wiring, AppState, shutdown. No process.exit —
  TUI starts regardless so user can /login.

- tools.ts: replace ToolResult and ReadImageResult with single
  ToolExecResult. All execute functions return it directly via
  textResult() helper. No wrapper types needed at call sites.

- agent.ts: remove AgentTool interface. RunAgentOpts takes tools: Tool[]
  and toolHandlers: Map<string, ToolHandler> separately. ToolHandler is
  a plain function type. ToolExecResult re-exported from tools.ts.

- plugins.ts: PluginResult.tools stays as Tool[] (pi-ai type).
  Added optional toolHandlers field for dispatch handlers.

- Updated all tests and documentation to match.

xonecas2026-04-05 413a5bd0d943f4bd4f656d56ec2d78cd962b9a60 parent cf00575

9 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.md+1−0
@@ -83,6 +83,7 @@ We test our logic at the boundaries. Never test dependencies (pi-ai, cel-tui, bu
8383 **Agent loop** (`agent.ts`):
8484
8585 - Use pi-ai's `faux` provider for end-to-end loop tests.
86+- The loop takes `tools: Tool[]` (definitions for the model) and `toolHandlers: Map<string, ToolHandler>` (dispatch map). Tests build both via helper functions.
8687 - Verify: tool calls are executed, messages are appended in correct order, turns are numbered, interrupt preserves partial response, error handling, unknown tool self-correction, length stop reason.
8788
8889 **Input parsing** (`input.ts`):
TODO.md+17−5
@@ -13,10 +13,11 @@
1313 - `session.ts` exports: `openDatabase`, `createSession`, `getSession`, `listSessions`, `deleteSession`, `appendMessage`, `loadMessages`, `undoLastTurn`, `forkSession`, `computeStats`.
1414 - Internal row types (`SessionRow`, `MaxTurnRow`, `DataRow`) and a `SQL` constants object keep queries centralized and avoid formatter conflicts.
1515 - `@mariozechner/pi-ai` is the only runtime dependency so far. Its `Message`, `AssistantMessage`, `UserMessage`, `ToolResultMessage` types are used for session persistence.
16-- `tools.ts` exports: `executeEdit`, `executeShell`, `truncateOutput`, `editTool`, `shellTool` (pi-ai `Tool` definitions with TypeBox schemas). `ToolResult` type (`{ text, isError }`) is the common return shape.
16+- `tools.ts` exports: `ToolExecResult`, `EditArgs`, `executeEdit`, `ShellArgs`, `ShellOpts`, `executeShell`, `truncateOutput`, `editTool`, `shellTool`, `ReadImageArgs`, `executeReadImage`, `readImageTool`. All execute functions return `ToolExecResult` (`{ content: (TextContent | ImageContent)[], isError }`). pi-ai `Tool` definitions use TypeBox schemas.
1717 - `git.ts` exports: `getGitState` → `GitState | null`. Runs 4 git commands in parallel. Internal `parseStatus` parses porcelain v1 format (uses `trim=false` to preserve leading-space column).
1818 - biome `noNonNullAssertion` rule disabled globally — non-null assertions after explicit null checks are idiomatic in tests.
1919 - 57 tests total across 3 files (session: 20, tools: 27, git: 10).
20+- `diff` package added as dependency for unified diffs in edit tool output (Phase 4 UI).
2021
2122 ## Phase 2 — Context assembly
2223
@@ -44,11 +45,12 @@
4445
4546 ### Notes from Phase 3
4647
47-- `readImage` in `tools.ts` exports: `ReadImageArgs`, `ReadImageResult`, `executeReadImage`, `readImageTool`. Returns `ImageContent` on success (base64 + mimeType) or `TextContent` error. Separate result type from `ToolResult` since it carries image content — the agent loop handles mapping both into `ToolResultMessage`.
48-- `agent.ts` exports: `AgentTool`, `ToolExecResult`, `AgentEvent`, `RunAgentOpts`, `AgentLoopResult`, `runAgentLoop`. The loop streams via `streamSimple`, dispatches tool calls through a name→handler map, appends all messages to DB with the same turn number, and emits events for UI updates. Unknown tools produce error results so the model can self-correct.
49-- `plugins.ts` exports: `AgentContext`, `PluginResult`, `Plugin`, `PluginEntry`, `LoadedPlugin`, `loadPluginConfig`, `initPlugins`, `destroyPlugins`. Plugins are real modules loaded via dynamic `import()` — tested with actual `.ts` files in temp dirs (no mocks).
48+- `readImage` in `tools.ts`: `ReadImageArgs`, `executeReadImage`, `readImageTool`. Returns `ImageContent` on success (base64 + mimeType) or text error, both via `ToolExecResult`.
49+- `agent.ts` exports: `ToolHandler` (function type), `ToolExecResult` (re-exported from `tools.ts`), `AgentEvent`, `RunAgentOpts`, `AgentLoopResult`, `runAgentLoop`. `RunAgentOpts` takes `tools: Tool[]` (definitions for the model) and `toolHandlers: Map<string, ToolHandler>` (dispatch map). The loop streams via `streamSimple`, dispatches tool calls through the handler map, appends all messages to DB with the same turn number, and emits events for UI updates. Unknown tools produce error results s …
50+- `plugins.ts` exports: `AgentContext`, `PluginResult`, `Plugin`, `PluginEntry`, `LoadedPlugin`, `loadPluginConfig`, `initPlugins`, `destroyPlugins`. `PluginResult.tools` is `Tool[]` (pi-ai definitions), `PluginResult.toolHandlers` is `Map<string, ToolHandler>` (optional). Plugins are real modules loaded via dynamic `import()` — tested with actual `.ts` files in temp dirs (no mocks).
5051 - Context limit compaction is deferred — the spec notes "the specifics will be refined during development." The agent loop structure supports adding it as a pre-stream check.
5152 - Conditional `readImage` registration (only for vision-capable models) will be handled by the caller (`index.ts`) checking `Model.input.includes("image")`.
53+- `cel-tui` (`@cel-tui/core`, `@cel-tui/components`) added as dependencies for the TUI.
5254 - 123 tests total across 7 files.
5355
5456 ## Phase 4 — UI
@@ -67,9 +69,19 @@
6769 - `theme.ts` (also implemented here): `Theme` interface, `DEFAULT_THEME`, `mergeThemes(base, ...overrides)`. Uses terminal palette colors (`color01`–`color08`) for automatic light/dark adaptation. 5 tests in `theme.test.ts`.
6870 - 158 tests total across 9 files (session: 20, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
6971
72+### Notes from Phase 4b (in progress)
73+
74+- `index.ts` exports: `AppState` (all mutable app state), `init()`, `buildPrompt(state)`, `buildToolList(state)`, `shutdown(state)`. Also re-exports OAuth helpers (`loadOAuthCredentials`, `saveOAuthCredentials`, `DATA_DIR`, `AUTH_PATH`) for `/login` and `/logout` commands.
75+- Provider discovery checks env-based API keys first, then saved OAuth tokens (`~/.config/mini-coder/auth.json`). Refreshes expired tokens and persists updates.
76+- Model selection picks the first model from the first provider with models, or `null` if none. No `process.exit` — the TUI starts regardless so the user can `/login`.
77+- Tool wiring: `buildTools` returns `{ tools: Tool[], toolHandlers: Map<string, ToolHandler> }`. Built-in handlers are a plain record. Plugin tools and handlers are merged from `PluginResult`.
78+- `ToolExecResult` is now the single result type in `tools.ts`. `ToolResult` and `ReadImageResult` were removed. All execute functions return `ToolExecResult` directly.
79+- `AgentTool` wrapper type removed from `agent.ts`. The agent loop takes `tools: Tool[]` + `toolHandlers: Map<string, ToolHandler>` separately.
80+- 158 tests still pass across 9 files.
81+
7082 ### 4b — App shell (running app, no commands)
7183
72-- [ ] `index.ts` — entry point: provider discovery (env + OAuth), register built-in API providers, model selection, startup sequence
84+- [x] `index.ts` — entry point: provider discovery (env + OAuth), model selection (first available, null if none), startup sequence
7385 - [ ] `ui.ts` — cel-tui layout: conversation log (scrollable, stick-to-bottom), input area (TextInput, submit/newline), status bar (2 lines: cwd+git, model+usage), animated divider
7486 - [ ] Wire agent loop: submit → build context → stream → render events → tool results → loop
7587 - [ ] Message rendering: user (bg color), assistant (streamed Markdown), tool calls (shell: bordered output, edit: path + unified diff), errors
package.json+2−0
@@ -18,6 +18,8 @@
1818 "test": "bun test"
1919 },
2020 "dependencies": {
21+ "@cel-tui/components": "^0.3.0",
22+ "@cel-tui/core": "^0.3.0",
2123 "@mariozechner/pi-ai": "^0.65.0",
2224 "diff": "^8.0.4"
2325 },
src/agent.test.ts+44−47
@@ -3,32 +3,21 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
33 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6-import type { AssistantMessage, UserMessage } from "@mariozechner/pi-ai";
6+import type { AssistantMessage, Tool, UserMessage } from "@mariozechner/pi-ai";
77 import {
88 type FauxProviderRegistration,
99 fauxAssistantMessage,
1010 fauxToolCall,
1111 registerFauxProvider,
1212 } from "@mariozechner/pi-ai";
13-import {
14- type AgentEvent,
15- type AgentTool,
16- runAgentLoop,
17- type ToolExecResult,
18-} from "./agent.ts";
13+import { type AgentEvent, runAgentLoop, type ToolHandler } from "./agent.ts";
1914 import {
2015 appendMessage,
2116 createSession,
2217 loadMessages,
2318 openDatabase,
2419 } from "./session.ts";
25-import {
26- editTool,
27- executeEdit,
28- executeShell,
29- shellTool,
30- type ToolResult,
31-} from "./tools.ts";
20+import { editTool, executeEdit, executeShell, shellTool } from "./tools.ts";
3221
3322 // ---------------------------------------------------------------------------
3423 // Helpers
@@ -54,36 +43,32 @@ function makeUser(text: string): UserMessage {
5443 return { role: "user", content: text, timestamp: Date.now() };
5544 }
5645
57-/** Wrap a text-only ToolResult into a ToolExecResult with content blocks. */
58-function wrapResult(r: ToolResult): ToolExecResult {
59- return { content: [{ type: "text", text: r.text }], isError: r.isError };
46+/** Built-in tool definitions for tests. */
47+function builtinToolDefs(): Tool[] {
48+ return [shellTool, editTool];
6049 }
6150
62-/** Create standard built-in tools for tests. */
63-function builtinTools(): AgentTool[] {
64- return [
65- {
66- definition: shellTool,
67- execute: async (args, cwd) =>
68- wrapResult(
69- await executeShell({ command: args.command as string }, cwd),
70- ),
71- },
72- {
73- definition: editTool,
74- execute: (args, cwd) =>
75- wrapResult(
76- executeEdit(
77- {
78- path: args.path as string,
79- oldText: args.oldText as string,
80- newText: args.newText as string,
81- },
82- cwd,
83- ),
51+/** Built-in tool handlers for tests. */
52+function builtinToolHandlers(): Map<string, ToolHandler> {
53+ return new Map<string, ToolHandler>([
54+ [
55+ "shell",
56+ async (args, cwd) =>
57+ executeShell({ command: args.command as string }, cwd),
58+ ],
59+ [
60+ "edit",
61+ (args, cwd) =>
62+ executeEdit(
63+ {
64+ path: args.path as string,
65+ oldText: args.oldText as string,
66+ newText: args.newText as string,
67+ },
68+ cwd,
8469 ),
85- },
86- ];
70+ ],
71+ ]);
8772 }
8873
8974 // ---------------------------------------------------------------------------
@@ -105,6 +90,7 @@ describe("agent loop", () => {
10590 model: faux.getModel(),
10691 systemPrompt: "Test",
10792 tools: [],
93+ toolHandlers: new Map(),
10894 messages: [userMsg],
10995 cwd: tmp,
11096 });
@@ -128,6 +114,7 @@ describe("agent loop", () => {
128114 model: faux.getModel(),
129115 systemPrompt: "Test",
130116 tools: [],
117+ toolHandlers: new Map(),
131118 messages: [userMsg],
132119 cwd: tmp,
133120 });
@@ -159,7 +146,8 @@ describe("agent loop", () => {
159146 turn,
160147 model: faux.getModel(),
161148 systemPrompt: "Test",
162- tools: builtinTools(),
149+ tools: builtinToolDefs(),
150+ toolHandlers: builtinToolHandlers(),
163151 messages: [userMsg],
164152 cwd: tmp,
165153 });
@@ -207,7 +195,8 @@ describe("agent loop", () => {
207195 turn,
208196 model: faux.getModel(),
209197 systemPrompt: "Test",
210- tools: builtinTools(),
198+ tools: builtinToolDefs(),
199+ toolHandlers: builtinToolHandlers(),
211200 messages: [userMsg],
212201 cwd: tmp,
213202 });
@@ -245,7 +234,8 @@ describe("agent loop", () => {
245234 turn,
246235 model: faux.getModel(),
247236 systemPrompt: "Test",
248- tools: builtinTools(),
237+ tools: builtinToolDefs(),
238+ toolHandlers: builtinToolHandlers(),
249239 messages: [userMsg],
250240 cwd: tmp,
251241 });
@@ -273,7 +263,8 @@ describe("agent loop", () => {
273263 turn,
274264 model: faux.getModel(),
275265 systemPrompt: "Test",
276- tools: builtinTools(),
266+ tools: builtinToolDefs(),
267+ toolHandlers: builtinToolHandlers(),
277268 messages: [userMsg],
278269 cwd: tmp,
279270 });
@@ -304,6 +295,7 @@ describe("agent loop", () => {
304295 model: faux.getModel(),
305296 systemPrompt: "Test",
306297 tools: [],
298+ toolHandlers: new Map(),
307299 messages: [userMsg],
308300 cwd: tmp,
309301 onEvent: (e) => events.push(e),
@@ -336,7 +328,8 @@ describe("agent loop", () => {
336328 turn,
337329 model: faux.getModel(),
338330 systemPrompt: "Test",
339- tools: builtinTools(),
331+ tools: builtinToolDefs(),
332+ toolHandlers: builtinToolHandlers(),
340333 messages: [userMsg],
341334 cwd: tmp,
342335 onEvent: (e) => events.push(e),
@@ -368,6 +361,7 @@ describe("agent loop", () => {
368361 model: faux.getModel(),
369362 systemPrompt: "Test",
370363 tools: [],
364+ toolHandlers: new Map(),
371365 messages: [userMsg],
372366 cwd: tmp,
373367 signal: controller.signal,
@@ -408,6 +402,7 @@ describe("agent loop", () => {
408402 model: faux.getModel(),
409403 systemPrompt: "Test",
410404 tools: [],
405+ toolHandlers: new Map(),
411406 messages: [userMsg],
412407 cwd: tmp,
413408 });
@@ -433,7 +428,8 @@ describe("agent loop", () => {
433428 turn,
434429 model: faux.getModel(),
435430 systemPrompt: "Test",
436- tools: builtinTools(),
431+ tools: builtinToolDefs(),
432+ toolHandlers: builtinToolHandlers(),
437433 messages: [userMsg],
438434 cwd: tmp,
439435 });
@@ -466,6 +462,7 @@ describe("agent loop", () => {
466462 model: faux.getModel(),
467463 systemPrompt: "Test",
468464 tools: [],
465+ toolHandlers: new Map(),
469466 messages: [userMsg],
470467 cwd: tmp,
471468 });
src/agent.ts+32−45
@@ -11,40 +11,33 @@
1111 import type { Database } from "bun:sqlite";
1212 import type {
1313 AssistantMessage,
14- ImageContent,
1514 Message,
1615 Model,
17- TextContent,
1816 Tool,
1917 ToolCall,
2018 ToolResultMessage,
2119 } from "@mariozechner/pi-ai";
2220 import { streamSimple } from "@mariozechner/pi-ai";
2321 import { appendMessage } from "./session.ts";
22+import type { ToolExecResult } from "./tools.ts";
2423
2524 // ---------------------------------------------------------------------------
2625 // Types
2726 // ---------------------------------------------------------------------------
2827
29-/** A registered tool with its definition and execute function. */
30-export interface AgentTool {
31- /** pi-ai tool definition (name, description, parameters schema). */
32- definition: Tool;
33- /** Execute the tool and return content for the tool result message. */
34- execute: (
35- args: Record<string, unknown>,
36- cwd: string,
37- signal?: AbortSignal,
38- ) => Promise<ToolExecResult> | ToolExecResult;
39-}
28+/**
29+ * A tool execution handler.
30+ *
31+ * Called by the agent loop when the model invokes a tool. Arguments are
32+ * the JSON object parsed by pi-ai from the model's tool call.
33+ */
34+export type ToolHandler = (
35+ args: Record<string, unknown>,
36+ cwd: string,
37+ signal?: AbortSignal,
38+) => Promise<ToolExecResult> | ToolExecResult;
4039
41-/** Result from executing a tool. */
42-export interface ToolExecResult {
43- /** Content blocks for the tool result (text and/or images). */
44- content: (TextContent | ImageContent)[];
45- /** Whether the execution encountered an error. */
46- isError: boolean;
47-}
40+export type { ToolExecResult };
4841
4942 /** Events emitted during the agent loop for UI updates. */
5043 export type AgentEvent =
@@ -68,8 +61,10 @@ export interface RunAgentOpts {
6861 model: Model<string>;
6962 /** The assembled system prompt. */
7063 systemPrompt: string;
71- /** Registered tools (built-in + plugin). */
72- tools: AgentTool[];
64+ /** Tool definitions sent to the model. */
65+ tools: Tool[];
66+ /** Tool name → handler map for executing tool calls. */
67+ toolHandlers: Map<string, ToolHandler>;
7368 /** Current message history (mutated in-place as messages are appended). */
7469 messages: Message[];
7570 /** Working directory for tool execution. */
@@ -113,20 +108,18 @@ export async function runAgentLoop(
113108 model,
114109 systemPrompt,
115110 tools,
111+ toolHandlers,
116112 messages,
117113 cwd,
118114 signal,
119115 onEvent,
120116 } = opts;
121117
122- const toolDefs = tools.map((t) => t.definition);
123- const toolMap = new Map(tools.map((t) => [t.definition.name, t]));
124-
125118 while (true) {
126119 // Build context for this iteration
127120 const context =
128- toolDefs.length > 0
129- ? { systemPrompt, messages, tools: toolDefs }
121+ tools.length > 0
122+ ? { systemPrompt, messages, tools }
130123 : { systemPrompt, messages };
131124
132125 // Stream to LLM
@@ -188,19 +181,15 @@ export async function runAgentLoop(
188181 );
189182
190183 for (const toolCall of toolCalls) {
191- const tool = toolMap.get(toolCall.name);
192-
193- let resultContent: (TextContent | ImageContent)[];
194- let isError: boolean;
195-
196- if (!tool) {
197- resultContent = [
198- {
199- type: "text",
200- text: `Unknown tool: ${toolCall.name}`,
201- },
202- ];
203- isError = true;
184+ const handler = toolHandlers.get(toolCall.name);
185+
186+ let result: ToolExecResult;
187+
188+ if (!handler) {
189+ result = {
190+ content: [{ type: "text", text: `Unknown tool: ${toolCall.name}` }],
191+ isError: true,
192+ };
204193 } else {
205194 onEvent?.({
206195 type: "tool_start",
@@ -208,9 +197,7 @@ export async function runAgentLoop(
208197 args: toolCall.arguments,
209198 });
210199
211- const result = await tool.execute(toolCall.arguments, cwd, signal);
212- resultContent = result.content;
213- isError = result.isError;
200+ result = await handler(toolCall.arguments, cwd, signal);
214201
215202 onEvent?.({ type: "tool_end", name: toolCall.name, result });
216203 }
@@ -219,8 +206,8 @@ export async function runAgentLoop(
219206 role: "toolResult",
220207 toolCallId: toolCall.id,
221208 toolName: toolCall.name,
222- content: resultContent,
223- isError,
209+ content: result.content,
210+ isError: result.isError,
224211 timestamp: Date.now(),
225212 };
226213
src/index.ts+418−2
@@ -1,2 +1,418 @@
1-// mini-coder v2 — entry point
2-// See spec.md for the full specification.
1+/**
2+ * Entry point for mini-coder.
3+ *
4+ * Discovers available LLM providers, loads context (AGENTS.md, skills,
5+ * plugins), opens the session database, selects a model, and starts
6+ * the TUI.
7+ *
8+ * @module
9+ */
10+
11+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12+import { homedir } from "node:os";
13+import { join } from "node:path";
14+import type {
15+ KnownProvider,
16+ Model,
17+ OAuthCredentials,
18+ ThinkingLevel,
19+ Tool,
20+} from "@mariozechner/pi-ai";
21+import { getEnvApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
22+import { getOAuthApiKey, getOAuthProviders } from "@mariozechner/pi-ai/oauth";
23+import type { ToolHandler } from "./agent.ts";
24+import { type GitState, getGitState } from "./git.ts";
25+import {
26+ type AgentContext,
27+ destroyPlugins,
28+ initPlugins,
29+ type LoadedPlugin,
30+ loadPluginConfig,
31+} from "./plugins.ts";
32+import {
33+ type AgentsMdFile,
34+ buildSystemPrompt,
35+ discoverAgentsMd,
36+} from "./prompt.ts";
37+import {
38+ computeStats,
39+ createSession,
40+ loadMessages,
41+ openDatabase,
42+ type Session,
43+ type SessionStats,
44+} from "./session.ts";
45+import { discoverSkills, type Skill } from "./skills.ts";
46+import { DEFAULT_THEME, mergeThemes, type Theme } from "./theme.ts";
47+import {
48+ editTool,
49+ executeEdit,
50+ executeReadImage,
51+ executeShell,
52+ readImageTool,
53+ shellTool,
54+} from "./tools.ts";
55+
56+// ---------------------------------------------------------------------------
57+// Constants
58+// ---------------------------------------------------------------------------
59+
60+/** App data directory. */
61+const DATA_DIR = join(homedir(), ".config", "mini-coder");
62+
63+/** SQLite database path. */
64+const DB_PATH = join(DATA_DIR, "mini-coder.db");
65+
66+/** Plugin config file path. */
67+const PLUGIN_CONFIG_PATH = join(DATA_DIR, "plugins.json");
68+
69+/** OAuth credentials file path. */
70+const AUTH_PATH = join(DATA_DIR, "auth.json");
71+
72+/** Default effort level. */
73+const DEFAULT_EFFORT: ThinkingLevel = "medium";
74+
75+// ---------------------------------------------------------------------------
76+// OAuth credential persistence
77+// ---------------------------------------------------------------------------
78+
79+/** Load saved OAuth credentials from disk. */
80+function loadOAuthCredentials(): Record<string, OAuthCredentials> {
81+ if (!existsSync(AUTH_PATH)) return {};
82+ try {
83+ return JSON.parse(readFileSync(AUTH_PATH, "utf-8"));
84+ } catch {
85+ return {};
86+ }
87+}
88+
89+/** Save OAuth credentials to disk. */
90+function saveOAuthCredentials(creds: Record<string, OAuthCredentials>): void {
91+ mkdirSync(DATA_DIR, { recursive: true });
92+ writeFileSync(AUTH_PATH, JSON.stringify(creds, null, 2), "utf-8");
93+}
94+
95+// ---------------------------------------------------------------------------
96+// Provider discovery
97+// ---------------------------------------------------------------------------
98+
99+/** Result of provider discovery: available providers + OAuth state. */
100+interface DiscoveryResult {
101+ /** Provider → API key map for all ready-to-use providers. */
102+ providers: Map<string, string>;
103+ /** OAuth credentials (possibly refreshed during discovery). */
104+ oauthCredentials: Record<string, OAuthCredentials>;
105+}
106+
107+/**
108+ * Discover which providers have usable credentials.
109+ *
110+ * Checks env-based API keys first, then saved OAuth tokens. Refreshes
111+ * expired OAuth tokens and persists updated credentials.
112+ */
113+async function discoverProviders(): Promise<DiscoveryResult> {
114+ const providers = new Map<string, string>();
115+
116+ // 1. Check env-based API keys
117+ for (const provider of getProviders()) {
118+ const key = getEnvApiKey(provider);
119+ if (key) {
120+ providers.set(provider, key);
121+ }
122+ }
123+
124+ // 2. Check OAuth credentials
125+ const oauthCredentials = loadOAuthCredentials();
126+ let credsModified = false;
127+
128+ for (const oauthProvider of getOAuthProviders()) {
129+ // Skip if already available via env key
130+ if (providers.has(oauthProvider.id)) continue;
131+
132+ try {
133+ const result = await getOAuthApiKey(oauthProvider.id, oauthCredentials);
134+ if (result) {
135+ providers.set(oauthProvider.id, result.apiKey);
136+ // Update credentials if they were refreshed
137+ if (result.newCredentials !== oauthCredentials[oauthProvider.id]) {
138+ oauthCredentials[oauthProvider.id] = result.newCredentials;
139+ credsModified = true;
140+ }
141+ }
142+ } catch {
143+ // Token refresh failed — skip this provider
144+ }
145+ }
146+
147+ if (credsModified) {
148+ saveOAuthCredentials(oauthCredentials);
149+ }
150+
151+ return { providers, oauthCredentials };
152+}
153+
154+// ---------------------------------------------------------------------------
155+// Model selection
156+// ---------------------------------------------------------------------------
157+
158+/**
159+ * Select the first available model from discovered providers.
160+ *
161+ * Returns the first model from the first provider that has models
162+ * in the registry, or `null` if none are available.
163+ */
164+function selectModel(
165+ availableProviders: Map<string, string>,
166+): Model<string> | null {
167+ for (const provider of availableProviders.keys()) {
168+ const models = getModels(provider as KnownProvider);
169+ if (models.length > 0) return models[0]!;
170+ }
171+ return null;
172+}
173+
174+// ---------------------------------------------------------------------------
175+// Tool wiring
176+// ---------------------------------------------------------------------------
177+
178+/** Built-in tool handlers keyed by tool name. */
179+const BUILTIN_HANDLERS: Record<string, ToolHandler> = {
180+ edit: (args, cwd) =>
181+ executeEdit(
182+ {
183+ path: args.path as string,
184+ oldText: args.oldText as string,
185+ newText: args.newText as string,
186+ },
187+ cwd,
188+ ),
189+ shell: (args, cwd, signal) =>
190+ executeShell(
191+ { command: args.command as string },
192+ cwd,
193+ signal ? { signal } : undefined,
194+ ),
195+ readImage: (args, cwd) =>
196+ executeReadImage({ path: args.path as string }, cwd),
197+};
198+
199+/**
200+ * Build tool definitions and handler map for the current model.
201+ *
202+ * Returns the `Tool[]` to send to the model and the handler map
203+ * for the agent loop to dispatch tool calls.
204+ */
205+function buildTools(
206+ model: Model<string>,
207+ plugins: LoadedPlugin[],
208+): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
209+ const tools: Tool[] = [editTool, shellTool];
210+ const toolHandlers = new Map<string, ToolHandler>([
211+ [editTool.name, BUILTIN_HANDLERS.edit!],
212+ [shellTool.name, BUILTIN_HANDLERS.shell!],
213+ ]);
214+
215+ // Conditionally register readImage for vision-capable models
216+ if (model.input.includes("image")) {
217+ tools.push(readImageTool);
218+ toolHandlers.set(readImageTool.name, BUILTIN_HANDLERS.readImage!);
219+ }
220+
221+ // Add plugin tools
222+ for (const plugin of plugins) {
223+ if (plugin.result.tools) {
224+ for (const tool of plugin.result.tools) {
225+ tools.push(tool);
226+ }
227+ }
228+ if (plugin.result.toolHandlers) {
229+ for (const [name, handler] of plugin.result.toolHandlers) {
230+ toolHandlers.set(name, handler);
231+ }
232+ }
233+ }
234+
235+ return { tools, toolHandlers };
236+}
237+
238+// ---------------------------------------------------------------------------
239+// Skill scan paths
240+// ---------------------------------------------------------------------------
241+
242+/** Build the list of skill scan paths per the spec. */
243+function getSkillScanPaths(cwd: string, gitRoot: string | null): string[] {
244+ const home = homedir();
245+ const project = gitRoot ?? cwd;
246+ return [
247+ join(project, ".mini-coder", "skills"),
248+ join(project, ".agents", "skills"),
249+ join(home, ".mini-coder", "skills"),
250+ join(home, ".agents", "skills"),
251+ ];
252+}
253+
254+// ---------------------------------------------------------------------------
255+// App state
256+// ---------------------------------------------------------------------------
257+
258+/** All mutable application state in one place. */
259+export interface AppState {
260+ /** Open database handle. */
261+ db: ReturnType<typeof openDatabase>;
262+ /** Current session. */
263+ session: Session;
264+ /** Current model, or `null` if no providers are available yet. */
265+ model: Model<string> | null;
266+ /** Current effort level. */
267+ effort: ThinkingLevel;
268+ /** Message history for the active session. */
269+ messages: ReturnType<typeof loadMessages>;
270+ /** Cumulative usage stats. */
271+ stats: SessionStats;
272+ /** Discovered AGENTS.md files. */
273+ agentsMd: AgentsMdFile[];
274+ /** Discovered skills. */
275+ skills: Skill[];
276+ /** Loaded plugins. */
277+ plugins: LoadedPlugin[];
278+ /** Active theme (default + plugin overrides). */
279+ theme: Theme;
280+ /** Current git state (null if not in a repo). */
281+ git: GitState | null;
282+ /** Available provider credentials (provider → API key). */
283+ providers: Map<string, string>;
284+ /** OAuth credentials on disk. */
285+ oauthCredentials: Record<string, OAuthCredentials>;
286+ /** Working directory. */
287+ cwd: string;
288+ /** Whether the agent loop is currently running. */
289+ running: boolean;
290+ /** Abort controller for the current agent run. */
291+ abortController: AbortController | null;
292+ /** Whether to show thinking content. */
293+ showReasoning: boolean;
294+ /** Whether to show full (un-truncated) tool output. */
295+ verbose: boolean;
296+}
297+
298+// ---------------------------------------------------------------------------
299+// Main
300+// ---------------------------------------------------------------------------
301+
302+/** Initialize and return the full app state. */
303+export async function init(): Promise<AppState> {
304+ const cwd = process.cwd();
305+
306+ // Ensure data directory exists
307+ mkdirSync(DATA_DIR, { recursive: true });
308+
309+ // Discover providers (env + OAuth)
310+ const { providers, oauthCredentials } = await discoverProviders();
311+
312+ // Select first available model (null if no providers found)
313+ const model = selectModel(providers);
314+
315+ // Gather git state
316+ const git = await getGitState(cwd);
317+ const gitRoot = git?.root ?? null;
318+
319+ // Discover context
320+ const home = homedir();
321+ const scanRoot = gitRoot ?? home;
322+ const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
323+ const skills = discoverSkills(getSkillScanPaths(cwd, gitRoot));
324+
325+ // Load plugins
326+ const pluginEntries = loadPluginConfig(PLUGIN_CONFIG_PATH);
327+
328+ // Open database and create session
329+ const db = openDatabase(DB_PATH);
330+ const effort = DEFAULT_EFFORT;
331+ const modelLabel = model ? `${model.provider}/${model.id}` : undefined;
332+ const session = createSession(db, {
333+ cwd,
334+ model: modelLabel,
335+ effort,
336+ });
337+ const messages = loadMessages(db, session.id);
338+ const stats = computeStats(messages);
339+
340+ // Init plugins
341+ const context: AgentContext = {
342+ cwd,
343+ messages,
344+ dataDir: DATA_DIR,
345+ };
346+ const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
347+ console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
348+ });
349+
350+ // Build theme from defaults + plugin overrides
351+ const themeOverrides = plugins
352+ .map((p) => p.result.theme)
353+ .filter((t): t is Partial<Theme> => t != null);
354+ const theme = mergeThemes(DEFAULT_THEME, ...themeOverrides);
355+
356+ return {
357+ db,
358+ session,
359+ model,
360+ effort,
361+ messages,
362+ stats,
363+ agentsMd,
364+ skills,
365+ plugins,
366+ theme,
367+ git,
368+ providers,
369+ oauthCredentials,
370+ cwd,
371+ running: false,
372+ abortController: null,
373+ showReasoning: false,
374+ verbose: false,
375+ };
376+}
377+
378+/**
379+ * Build the system prompt for the current state.
380+ *
381+ * Separated from `init` because it's called on every turn (git state
382+ * may change between turns).
383+ */
384+export function buildPrompt(state: AppState): string {
385+ return buildSystemPrompt({
386+ cwd: state.cwd,
387+ date: new Date().toISOString().slice(0, 10),
388+ git: state.git,
389+ agentsMd: state.agentsMd,
390+ skills: state.skills,
391+ pluginSuffixes: state.plugins
392+ .map((p) => p.result.systemPromptSuffix)
393+ .filter((s): s is string => s != null),
394+ });
395+}
396+
397+/** Build the tool list for the current model. */
398+export function buildToolList(state: AppState): {
399+ tools: Tool[];
400+ toolHandlers: Map<string, ToolHandler>;
401+} {
402+ if (!state.model) return { tools: [], toolHandlers: new Map() };
403+ return buildTools(state.model, state.plugins);
404+}
405+
406+/** Clean up resources on shutdown. */
407+export async function shutdown(state: AppState): Promise<void> {
408+ await destroyPlugins(state.plugins, (entry, err) => {
409+ console.error(`Plugin "${entry.name}" failed to destroy: ${err.message}`);
410+ });
411+ state.db.close();
412+}
413+
414+// ---------------------------------------------------------------------------
415+// OAuth helpers (re-exported for /login and /logout commands)
416+// ---------------------------------------------------------------------------
417+
418+export { AUTH_PATH, DATA_DIR, loadOAuthCredentials, saveOAuthCredentials };
src/plugins.ts+4−1
@@ -12,6 +12,7 @@
1212 import { existsSync, readFileSync } from "node:fs";
1313 import { resolve } from "node:path";
1414 import type { Message, Tool } from "@mariozechner/pi-ai";
15+import type { ToolHandler } from "./agent.ts";
1516 import type { Theme } from "./theme.ts";
1617
1718 // ---------------------------------------------------------------------------
@@ -40,8 +41,10 @@ export interface AgentContext {
4041 * context to append to the system prompt.
4142 */
4243 export interface PluginResult {
43- /** Additional tools the agent can use. */
44+ /** Additional tool definitions to register with the model. */
4445 tools?: Tool[];
46+ /** Tool name → handler map for the tools above. */
47+ toolHandlers?: Map<string, ToolHandler>;
4548 /** Additional context to append to the system prompt. */
4649 systemPromptSuffix?: string;
4750 /** Partial theme override — merged on top of the default theme. */
src/tools.test.ts+26−22
@@ -12,9 +12,17 @@ import {
1212 executeEdit,
1313 executeReadImage,
1414 executeShell,
15+ type ToolExecResult,
1516 truncateOutput,
1617 } from "./tools.ts";
1718
19+/** Extract the text string from a text-only ToolExecResult. */
20+function resultText(r: ToolExecResult): string {
21+ const block = r.content[0];
22+ if (!block || block.type !== "text") throw new Error("Expected text content");
23+ return block.text;
24+}
25+
1826 // ---------------------------------------------------------------------------
1927 // Helpers
2028 // ---------------------------------------------------------------------------
@@ -61,7 +69,7 @@ describe("edit", () => {
6169 tmp,
6270 );
6371 expect(result.isError).toBe(true);
64- expect(result.text).toContain("not found");
72+ expect(resultText(result)).toContain("not found");
6573 // File unchanged
6674 expect(readFile("a.txt")).toBe("hello world");
6775 });
@@ -73,7 +81,7 @@ describe("edit", () => {
7381 tmp,
7482 );
7583 expect(result.isError).toBe(true);
76- expect(result.text).toContain("multiple");
84+ expect(resultText(result)).toContain("multiple");
7785 // File unchanged
7886 expect(readFile("a.txt")).toBe("aaa bbb aaa");
7987 });
@@ -103,7 +111,7 @@ describe("edit", () => {
103111 tmp,
104112 );
105113 expect(result.isError).toBe(true);
106- expect(result.text).toContain("already exists");
114+ expect(resultText(result)).toContain("already exists");
107115 // File unchanged
108116 expect(readFile("existing.txt")).toBe("already here");
109117 });
@@ -174,7 +182,7 @@ describe("edit", () => {
174182 tmp,
175183 );
176184 expect(result.isError).toBe(true);
177- expect(result.text).toContain("not found");
185+ expect(resultText(result)).toContain("not found");
178186 });
179187 });
180188
@@ -186,25 +194,25 @@ describe("shell", () => {
186194 test("returns stdout from a command", async () => {
187195 const result = await executeShell({ command: "echo hello" }, tmp);
188196 expect(result.isError).toBe(false);
189- expect(result.text).toContain("hello");
197+ expect(resultText(result)).toContain("hello");
190198 });
191199
192200 test("returns stderr from a command", async () => {
193201 const result = await executeShell({ command: "echo err >&2" }, tmp);
194202 expect(result.isError).toBe(false);
195- expect(result.text).toContain("err");
203+ expect(resultText(result)).toContain("err");
196204 });
197205
198206 test("passes through exit code", async () => {
199207 const result = await executeShell({ command: "exit 42" }, tmp);
200208 expect(result.isError).toBe(true);
201- expect(result.text).toContain("exit code 42");
209+ expect(resultText(result)).toContain("exit code 42");
202210 });
203211
204212 test("runs in the specified cwd", async () => {
205213 const result = await executeShell({ command: "pwd" }, tmp);
206214 expect(result.isError).toBe(false);
207- expect(result.text).toContain(tmp);
215+ expect(resultText(result)).toContain(tmp);
208216 });
209217
210218 test("truncates large output", async () => {
@@ -213,11 +221,12 @@ describe("shell", () => {
213221 maxLines: 100,
214222 });
215223 expect(result.isError).toBe(false);
216- expect(result.text).toContain("… truncated");
224+ const text = resultText(result);
225+ expect(text).toContain("… truncated");
217226 // Should contain head lines (near the start)
218- expect(result.text).toContain("1\n");
227+ expect(text).toContain("1\n");
219228 // Should contain tail lines (near the end)
220- expect(result.text).toContain("2000");
229+ expect(text).toContain("2000");
221230 });
222231
223232 test("does not truncate output within the limit", async () => {
@@ -225,7 +234,7 @@ describe("shell", () => {
225234 maxLines: 100,
226235 });
227236 expect(result.isError).toBe(false);
228- expect(result.text).not.toContain("truncated");
237+ expect(resultText(result)).not.toContain("truncated");
229238 });
230239
231240 test("supports abort signal", async () => {
@@ -243,8 +252,9 @@ describe("shell", () => {
243252 { command: "echo out && echo err >&2" },
244253 tmp,
245254 );
246- expect(result.text).toContain("out");
247- expect(result.text).toContain("err");
255+ const text = resultText(result);
256+ expect(text).toContain("out");
257+ expect(text).toContain("err");
248258 });
249259 });
250260
@@ -352,19 +362,13 @@ describe("readImage", () => {
352362 writeFileSync(join(tmp, "vector.svg"), "<svg></svg>");
353363 const result = executeReadImage({ path: "vector.svg" }, tmp);
354364 expect(result.isError).toBe(true);
355- expect(result.content[0]!.type).toBe("text");
356- if (result.content[0]!.type === "text") {
357- expect(result.content[0]!.text).toContain("Unsupported");
358- }
365+ expect(resultText(result)).toContain("Unsupported");
359366 });
360367
361368 test("handles missing file", () => {
362369 const result = executeReadImage({ path: "nonexistent.png" }, tmp);
363370 expect(result.isError).toBe(true);
364- expect(result.content[0]!.type).toBe("text");
365- if (result.content[0]!.type === "text") {
366- expect(result.content[0]!.text).toContain("not found");
367- }
371+ expect(resultText(result)).toContain("not found");
368372 });
369373
370374 test("resolves relative paths against cwd", () => {
src/tools.ts+36−42
@@ -18,14 +18,24 @@ import { Type } from "@mariozechner/pi-ai";
1818 // Result type
1919 // ---------------------------------------------------------------------------
Cut short: this commit's diff is over 1000 lines.