@@ -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 };