@@ -0,0 +1,465 @@
1+import * as c from "yoctocolors";
2+import { resolveModel } from "../llm-api/providers.ts";
3+import { runTurn, userMessage } from "../llm-api/turn.ts";
4+import {
5+ writeln,
6+ renderTurn,
7+ renderError,
8+ renderStatusBar,
9+ renderInfo,
10+ restoreTerminal,
11+ Spinner,
12+ PREFIX,
13+} from "../cli/output.ts";
14+import { readline } from "../cli/input.ts";
15+import { handleCommand, type CommandContext } from "../cli/commands.ts";
16+import { buildToolSet } from "./tools.ts";
17+import { connectMcpServer } from "../mcp/client.ts";
18+import {
19+ newSession,
20+ resumeSession,
21+ touchActiveSession,
22+ type ActiveSession,
23+} from "../session/manager.ts";
24+import {
25+ saveMessages,
26+ deleteLastTurn,
27+ getMaxTurnIndex,
28+ addPromptHistory,
29+ getConfigDir,
30+ listMcpServers,
31+} from "../session/db.ts";
32+import { join } from "path";
33+import { existsSync, readFileSync } from "fs";
34+import { homedir } from "os";
35+import type { Message, ToolDef } from "../llm-api/types.ts";
36+
37+// ─── Git branch detection ─────────────────────────────────────────────────────
38+
39+async function getGitBranch(cwd: string): Promise<string | null> {
40+ try {
41+ const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
42+ cwd,
43+ stdout: "pipe",
44+ stderr: "pipe",
45+ });
46+ const out = await new Response(proc.stdout).text();
47+ const code = await proc.exited;
48+ if (code !== 0) return null;
49+ return out.trim() || null;
50+ } catch {
51+ return null;
52+ }
53+}
54+
55+// ─── Context file discovery (AGENTS.md / CLAUDE.md) ──────────────────────────
56+
57+function loadContextFile(cwd: string): string | null {
58+ const candidates = [
59+ join(cwd, "AGENTS.md"),
60+ join(cwd, "CLAUDE.md"),
61+ join(cwd, ".agents", "system.md"),
62+ join(getConfigDir(), "AGENTS.md"),
63+ ];
64+ for (const p of candidates) {
65+ if (existsSync(p)) {
66+ try {
67+ return readFileSync(p, "utf-8");
68+ } catch {
69+ // skip
70+ }
71+ }
72+ }
73+ return null;
74+}
75+
76+// ─── System prompt ────────────────────────────────────────────────────────────
77+
78+function buildSystemPrompt(cwd: string): string {
79+ const contextFile = loadContextFile(cwd);
80+ const cwdDisplay = cwd.startsWith(homedir())
81+ ? "~" + cwd.slice(homedir().length)
82+ : cwd;
83+
84+ let prompt = `You are mini-coder, a small and fast CLI coding agent.
85+You have access to tools to read files, search code, make edits, run shell commands, and spawn subagents.
86+
87+Current working directory: ${cwdDisplay}
88+
89+Guidelines:
90+- Be concise and precise. Avoid unnecessary preamble.
91+- Prefer small, targeted edits over large rewrites.
92+- Always read a file before editing it.
93+- Use glob to discover files, grep to find patterns, read to inspect contents.
94+- Use shell for tests, builds, and git operations.
95+- When in doubt, ask the user before making destructive changes.`;
96+
97+ if (contextFile) {
98+ prompt += `\n\n# Project context\n\n${contextFile}`;
99+ }
100+
101+ return prompt;
102+}
103+
104+// ─── DB messages → raw ModelMessages (for session resume) ────────────────────
105+// On resume, the DB has only simple text messages (user prompts + assistant
106+// text replies). Tool-call/result parts are intentionally not reconstructed
107+// because the complex output/input shapes are opaque. The conversation context
108+// is still preserved for the model via the text content.
109+// eslint-disable-next-line @typescript-eslint/no-explicit-any
110+function dbMessagesToCore(messages: Message[]): any[] {
111+ return messages.map((m) => {
112+ if (typeof m.content === "string") {
113+ return { role: m.role, content: m.content };
114+ }
115+ if (Array.isArray(m.content)) {
116+ // Filter to text-only parts to avoid feeding malformed tool parts
117+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
118+ const textParts = (m.content as any[]).filter((p) => p.type === "text");
119+ if (textParts.length > 0) return { role: m.role, content: textParts };
120+ return { role: m.role, content: "" };
121+ }
122+ return { role: m.role, content: String(m.content) };
123+ });
124+}
125+
126+// ─── Shell passthrough (! prefix) ─────────────────────────────────────────────
127+
128+async function runShellPassthrough(command: string, cwd: string): Promise<string> {
129+ const proc = Bun.spawn(["bash", "-c", command], {
130+ cwd,
131+ stdout: "pipe",
132+ stderr: "pipe",
133+ });
134+ try {
135+ const [stdout, stderr] = await Promise.all([
136+ new Response(proc.stdout).text(),
137+ new Response(proc.stderr).text(),
138+ ]);
139+ await proc.exited;
140+ const out = [stdout, stderr].filter(Boolean).join("\n").trim();
141+ if (out) writeln(c.dim(out));
142+ return out;
143+ } finally {
144+ restoreTerminal();
145+ }
146+}
147+
148+// ─── Main agent run ───────────────────────────────────────────────────────────
149+
150+export interface AgentOptions {
151+ model: string;
152+ cwd: string;
153+ sessionId?: string; // resume existing
154+ initialPrompt?: string; // non-interactive first message
155+}
156+
157+export async function runAgent(opts: AgentOptions): Promise<void> {
158+ const cwd = opts.cwd;
159+ let currentModel = opts.model;
160+
161+ // Session setup
162+ let session: ActiveSession;
163+ if (opts.sessionId) {
164+ const resumed = resumeSession(opts.sessionId);
165+ if (!resumed) {
166+ renderError(`Session "${opts.sessionId}" not found.`);
167+ process.exit(1);
168+ }
169+ session = resumed;
170+ currentModel = session.model;
171+ renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
172+ } else {
173+ session = newSession(currentModel, cwd);
174+ }
175+
176+ // Turn counter — incremented each time processUserInput is called
177+ // Used to group user + assistant messages for undo
178+ let turnIndex = getMaxTurnIndex(session.id) + 1;
179+
180+ // Raw AI SDK ModelMessage history — fed directly to streamText each turn.
181+ // This is kept separate from session.messages (which is DB-persisted text)
182+ // to avoid lossy round-trips through our internal Message type.
183+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
184+ const coreHistory: any[] = dbMessagesToCore(session.messages);
185+
186+ // Subagent runner (recursive) — depth prevents infinite recursion
187+ const runSubagent = async (
188+ prompt: string,
189+ model?: string,
190+ depth = 0
191+ ): Promise<{ result: string; inputTokens: number; outputTokens: number }> => {
192+ const subModel = model ?? currentModel;
193+ const subMessages: Message[] = [{ role: "user", content: prompt }];
194+ const subTools = buildToolSet({ cwd, depth, runSubagent });
195+ const subLlm = resolveModel(subModel);
196+ const systemPrompt = buildSystemPrompt(cwd);
197+
198+ let result = "";
199+ let inputTokens = 0;
200+ let outputTokens = 0;
201+
202+ const events = runTurn({
203+ model: subLlm,
204+ messages: dbMessagesToCore(subMessages),
205+ tools: subTools,
206+ systemPrompt,
207+ });
208+
209+ for await (const event of events) {
210+ if (event.type === "text-delta") result += event.delta;
211+ if (event.type === "turn-complete") {
212+ inputTokens = event.inputTokens;
213+ outputTokens = event.outputTokens;
214+ }
215+ }
216+
217+ return { result, inputTokens, outputTokens };
218+ };
219+
220+ // ── MCP: load persisted servers and connect them ───────────────────────────
221+ const tools: ToolDef[] = buildToolSet({ cwd, depth: 0, runSubagent });
222+
223+ async function connectAndAddMcp(name: string): Promise<void> {
224+ const rows = listMcpServers();
225+ const row = rows.find((r) => r.name === name);
226+ if (!row) throw new Error(`MCP server "${name}" not found in DB`);
227+ const cfg: Parameters<typeof connectMcpServer>[0] = {
228+ name: row.name,
229+ transport: row.transport as "http" | "stdio",
230+ ...(row.url ? { url: row.url } : {}),
231+ ...(row.command ? { command: row.command } : {}),
232+ ...(row.args ? { args: JSON.parse(row.args) } : {}),
233+ ...(row.env ? { env: JSON.parse(row.env) } : {}),
234+ };
235+ const client = await connectMcpServer(cfg);
236+ tools.push(...client.tools);
237+ }
238+
239+ // Connect all persisted MCP servers at startup
240+ for (const row of listMcpServers()) {
241+ try {
242+ await connectAndAddMcp(row.name);
243+ renderInfo(`MCP: connected ${c.cyan(row.name)}`);
244+ } catch (e) {
245+ renderError(`MCP: failed to connect ${row.name}: ${String(e)}`);
246+ }
247+ }
248+
249+ let planMode = false;
250+
251+ const cmdCtx: CommandContext = {
252+ get currentModel() { return currentModel; },
253+ setModel: (m) => { currentModel = m; session.model = m; },
254+ get planMode() { return planMode; },
255+ setPlanMode: (v) => { planMode = v; },
256+ cwd,
257+ runSubagent: (prompt, model) => runSubagent(prompt, model),
258+ undoLastTurn: () => {
259+ // Nothing to undo if there are no messages
260+ if (session.messages.length === 0) return false;
261+
262+ // Find the message index where the last turn starts (last user message)
263+ let lastUserIdx = -1;
264+ for (let i = session.messages.length - 1; i >= 0; i--) {
265+ if (session.messages[i]?.role === "user") {
266+ lastUserIdx = i;
267+ break;
268+ }
269+ }
270+ if (lastUserIdx === -1) return false;
271+
272+ // Trim in-memory DB history
273+ session.messages.splice(lastUserIdx);
274+
275+ // Trim coreHistory to match — find last user message in coreHistory
276+ let coreLastUserIdx = -1;
277+ for (let i = coreHistory.length - 1; i >= 0; i--) {
278+ if (coreHistory[i]?.role === "user") {
279+ coreLastUserIdx = i;
280+ break;
281+ }
282+ }
283+ if (coreLastUserIdx !== -1) coreHistory.splice(coreLastUserIdx);
284+
285+ // Delete from DB and decrement turn counter
286+ const deleted = deleteLastTurn(session.id);
287+ if (turnIndex > 0) turnIndex--;
288+ return deleted;
289+ },
290+ connectMcpServer: connectAndAddMcp,
291+ };
292+ const spinner = new Spinner();
293+ let totalIn = 0;
294+ let totalOut = 0;
295+
296+ // ── Handle initial prompt (non-interactive) ────────────────────────────────
297+ if (opts.initialPrompt) {
298+ await processUserInput(opts.initialPrompt);
299+ }
300+
301+ // ── REPL ──────────────────────────────────────────────────────────────────
302+ while (true) {
303+ let input;
304+ try {
305+ input = await readline({ cwd });
306+ } catch {
307+ break;
308+ }
309+
310+ switch (input.type) {
311+ case "eof":
312+ writeln(c.dim("Goodbye."));
313+ return;
314+
315+ case "interrupt":
316+ // Just go back to prompt
317+ continue;
318+
319+ case "command": {
320+ const result = await handleCommand(input.command, input.args, cmdCtx);
321+ if (result.type === "exit") {
322+ writeln(c.dim("Goodbye."));
323+ return;
324+ }
325+ continue;
326+ }
327+
328+ case "shell": {
329+ const out = await runShellPassthrough(input.command, cwd);
330+ if (out) {
331+ const thisTurn = turnIndex++;
332+ const msg: Message = {
333+ role: "user",
334+ content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
335+ };
336+ session.messages.push(msg);
337+ saveMessages(session.id, [msg], thisTurn);
338+ coreHistory.push({ role: "user", content: msg.content });
339+ }
340+ continue;
341+ }
342+
343+ case "submit":
344+ await processUserInput(input.text);
345+ continue;
346+ }
347+ }
348+
349+ // ── Process a user message ─────────────────────────────────────────────────
350+ async function processUserInput(text: string): Promise<void> {
351+ // Resolve @file references
352+ const resolvedText = await resolveFileRefs(text, cwd);
353+
354+ // Capture turn index for this turn (user + response share the same index)
355+ const thisTurn = turnIndex++;
356+
357+ const userMsg: Message = { role: "user", content: resolvedText };
358+ session.messages.push(userMsg);
359+ saveMessages(session.id, [userMsg], thisTurn);
360+
361+ // Also push into coreHistory as a raw ModelMessage
362+ coreHistory.push({ role: "user", content: resolvedText });
363+
364+ const llm = resolveModel(currentModel);
365+ const systemPrompt = buildSystemPrompt(cwd);
366+
367+ const abortController = new AbortController();
368+ const onSigInt = () => abortController.abort();
369+ process.once("SIGINT", onSigInt);
370+
371+ spinner.start("thinking");
372+
373+ const events = runTurn({
374+ model: llm,
375+ messages: coreHistory,
376+ tools: planMode ? [] : tools,
377+ systemPrompt,
378+ signal: abortController.signal,
379+ });
380+
381+ const { inputTokens, outputTokens, newMessages } = await renderTurn(events, spinner);
382+ process.removeListener("SIGINT", onSigInt);
383+
384+ // newMessages are raw ModelMessage objects — push directly into coreHistory
385+ // so subsequent turns have the correct input/output fields.
386+ if (newMessages.length > 0) {
387+ coreHistory.push(...newMessages);
388+ // For DB persistence, store a simplified version (text only is enough
389+ // for session resume context — tool call parts are not reconstructed).
390+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
391+ const dbMsgs: Message[] = newMessages.map((m: any) => {
392+ if (typeof m.content === "string") {
393+ return { role: m.role as Message["role"], content: m.content };
394+ }
395+ if (Array.isArray(m.content)) {
396+ // Collapse to text content only for DB storage
397+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
398+ const text = (m.content as any[])
399+ .filter((p) => p.type === "text")
400+ .map((p) => p.text as string)
401+ .join("");
402+ return { role: m.role as Message["role"], content: text };
403+ }
404+ return { role: m.role as Message["role"], content: String(m.content) };
405+ });
406+ session.messages.push(...dbMsgs);
407+ saveMessages(session.id, dbMsgs, thisTurn);
408+ }
409+
410+ totalIn += inputTokens;
411+ totalOut += outputTokens;
412+ touchActiveSession(session);
413+
414+ // Render status bar
415+ const branch = await getGitBranch(cwd);
416+ const provider = currentModel.split("/")[0] ?? "";
417+ const modelShort = currentModel.split("/").slice(1).join("/");
418+ const cwdDisplay = cwd.startsWith(homedir())
419+ ? "~" + cwd.slice(homedir().length)
420+ : cwd;
421+
422+ renderStatusBar({
423+ model: modelShort,
424+ provider,
425+ cwd: cwdDisplay,
426+ gitBranch: branch,
427+ inputTokens,
428+ outputTokens,
429+ contextPercent: null,
430+ });
431+ }
432+}
433+
434+// ─── Resolve @file references in user input ────────────────────────────────────
435+
436+async function resolveFileRefs(text: string, cwd: string): Promise<string> {
437+ // Find all @<path> tokens
438+ const atPattern = /@([\w./\-_]+)/g;
439+ let result = text;
440+ const matches = [...text.matchAll(atPattern)];
441+
442+ for (const match of matches.reverse()) {
443+ const ref = match[1];
444+ if (!ref) continue;
445+ const filePath = ref.startsWith("/") ? ref : join(cwd, ref);
446+
447+ try {
448+ const content = await Bun.file(filePath).text();
449+ const lines = content.split("\n");
450+ const preview =
451+ lines.length > 200
452+ ? lines.slice(0, 200).join("\n") + "\n[truncated]"
453+ : content;
454+ const replacement = `\`${ref}\`:\n\`\`\`\n${preview}\n\`\`\``;
455+ result =
456+ result.slice(0, match.index) +
457+ replacement +
458+ result.slice((match.index ?? 0) + match[0].length);
459+ } catch {
460+ // Leave the @ref as-is if file not found
461+ }
462+ }
463+
464+ return result;
465+}