xonecas.io
64875
Mc

mini-coder / commit b75f366

feat: implement Phase 3 — agent loop, readImage tool, and plugins

xonecas2026-04-05 b75f3665f5a93ed98c3d820373b2c643be11ff4d parent cfb9c9c

7 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.

TODO.md+25−8
@@ -20,19 +20,36 @@
2020
2121 ## Phase 2 — Context assembly
2222
23-- [ ] `skills.ts` — SKILL.md discovery, frontmatter parsing, catalog generation, name collision resolution
24-- [ ] `prompt.ts` — AGENTS.md discovery, system prompt construction (base + AGENTS.md + skills + plugins + git footer)
23+- [x] `skills.ts` — SKILL.md discovery, frontmatter parsing, catalog generation, name collision resolution
24+- [x] `skills.test.ts` — 14 tests: single/multi path discovery, name collision, missing dirs, frontmatter (none, missing fields, multi-line, quoted), catalog XML
25+- [x] `prompt.ts` — AGENTS.md discovery, system prompt construction (base + AGENTS.md + skills + plugins + git footer)
26+- [x] `prompt.test.ts` — 21 tests: AGENTS.md walk (5), git line formatting (6), system prompt assembly (10)
2527
26-### Phase 2 entry points
28+### Notes from Phase 2
2729
28-- `skills.ts` depends on nothing from Phase 1. It scans directories for `SKILL.md` files, parses YAML frontmatter (name, description), resolves name collisions (project-level wins over user-level), and generates the XML catalog string for the system prompt. See spec.md "Agent Skills" section.
29-- `prompt.ts` depends on `skills.ts` and `git.ts` (both done). It walks from CWD to scan root collecting `AGENTS.md`/`CLAUDE.md` files, assembles the full system prompt in construction order (base → AGENTS.md → skills catalog → plugin suffixes → session footer with date/cwd/git). See spec.md "System prompt" section.
30+- `skills.ts` exports: `Skill` interface, `discoverSkills(scanPaths)`, `buildSkillCatalog(skills)`. Minimal YAML frontmatter parser (no dependency) handles `name`, `description`, folded scalars (`>`), quoted values. Falls back to directory name when frontmatter `name` is absent.
31+- `prompt.ts` exports: `AgentsMdFile` interface, `BuildSystemPromptOpts` interface, `discoverAgentsMd(cwd, scanRoot, globalAgentsDir?)`, `formatGitLine(state)`, `buildSystemPrompt(opts)`. Both `discoverSkills` and `discoverAgentsMd` take paths as parameters — the actual scan paths (spec §"Agent Skills" discovery, §"AGENTS.md" scan root priority) are determined by the caller (`index.ts` in Phase 4).
32+- Base instructions in `prompt.ts` match spec.md §"Base instructions" verbatim.
33+- `readImage` is intentionally absent from base instructions per spec — conditionally registered via tool definitions only.
34+- 92 tests total across 5 files (session: 20, tools: 27, git: 10, skills: 14, prompt: 21).
3035
3136 ## Phase 3 — Agent loop
3237
33-- [ ] `agent.ts` — core loop: stream → handle events → execute tools → loop. Interrupt handling. Context limit / compaction.
34-- [ ] `plugins.ts` — plugin loader, init/destroy lifecycle, tool + prompt injection
35-- [ ] `readImage` tool — base64 encoding, mime detection, conditional registration
38+- [x] `readImage` tool in `tools.ts` — base64 encoding, mime detection, path resolution
39+- [x] `tools.test.ts` — 9 new readImage tests (36 total: edit 13, shell 8, truncateOutput 6, readImage 9)
40+- [x] `agent.ts` — core loop: stream → handle events → execute tools → loop. Interrupt handling.
41+- [x] `agent.test.ts` — 12 tests with faux provider: text response, tool execution, multi-tool, chaining, turn numbering, events, interrupt, error, unknown tool, length stop
42+- [x] `plugins.ts` — plugin types, config loading, init/destroy lifecycle
43+- [x] `plugins.test.ts` — 10 tests with real plugin modules in temp dirs: config loading, init, config passthrough, error handling, tool collection, destroy lifecycle
44+
45+### Notes from Phase 3
46+
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).
50+- 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.
51+- Conditional `readImage` registration (only for vision-capable models) will be handled by the caller (`index.ts`) checking `Model.input.includes("image")`.
52+- 123 tests total across 7 files.
3653
3754 ## Phase 4 — UI
3855
src/agent.test.ts+456−0
@@ -0,0 +1,456 @@
1+import type { Database } from "bun:sqlite";
2+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4+import { tmpdir } from "node:os";
5+import { join } from "node:path";
6+import type { AssistantMessage, UserMessage } from "@mariozechner/pi-ai";
7+import {
8+ type FauxProviderRegistration,
9+ fauxAssistantMessage,
10+ fauxToolCall,
11+ registerFauxProvider,
12+} from "@mariozechner/pi-ai";
13+import { type AgentEvent, type AgentTool, runAgentLoop } from "./agent.ts";
14+import {
15+ appendMessage,
16+ createSession,
17+ loadMessages,
18+ openDatabase,
19+} from "./session.ts";
20+import { editTool, executeEdit, executeShell, shellTool } from "./tools.ts";
21+
22+// ---------------------------------------------------------------------------
23+// Helpers
24+// ---------------------------------------------------------------------------
25+
26+let tmp: string;
27+let db: Database;
28+let faux: FauxProviderRegistration;
29+
30+beforeEach(() => {
31+ tmp = mkdtempSync(join(tmpdir(), "mc-agent-"));
32+ db = openDatabase(":memory:");
33+ faux = registerFauxProvider();
34+});
35+
36+afterEach(() => {
37+ faux.unregister();
38+ db.close();
39+ rmSync(tmp, { recursive: true, force: true });
40+});
41+
42+function makeUser(text: string): UserMessage {
43+ return { role: "user", content: text, timestamp: Date.now() };
44+}
45+
46+/** Create standard built-in tools for tests. */
47+function builtinTools(): AgentTool[] {
48+ return [
49+ {
50+ definition: shellTool,
51+ execute: (args, cwd) =>
52+ executeShell({ command: args.command as string }, cwd),
53+ },
54+ {
55+ definition: editTool,
56+ execute: (args, cwd) =>
57+ executeEdit(
58+ {
59+ path: args.path as string,
60+ oldText: args.oldText as string,
61+ newText: args.newText as string,
62+ },
63+ cwd,
64+ ),
65+ },
66+ ];
67+}
68+
69+// ---------------------------------------------------------------------------
70+// Tests
71+// ---------------------------------------------------------------------------
72+
73+describe("agent loop", () => {
74+ test("simple text response appends assistant message", async () => {
75+ faux.setResponses([fauxAssistantMessage("Hello back!")]);
76+
77+ const session = createSession(db, { cwd: tmp });
78+ const userMsg = makeUser("hello");
79+ const turn = appendMessage(db, session.id, userMsg);
80+
81+ const result = await runAgentLoop({
82+ db,
83+ sessionId: session.id,
84+ turn,
85+ model: faux.getModel(),
86+ systemPrompt: "Test",
87+ tools: [],
88+ messages: [userMsg],
89+ cwd: tmp,
90+ });
91+
92+ expect(result.messages).toHaveLength(2);
93+ expect(result.messages[1]!.role).toBe("assistant");
94+ const am = result.messages[1] as AssistantMessage;
95+ expect(am.stopReason).toBe("stop");
96+ });
97+
98+ test("simple text response persists to DB", async () => {
99+ faux.setResponses([fauxAssistantMessage("Hello back!")]);
100+ const session = createSession(db, { cwd: tmp });
101+ const userMsg = makeUser("hello");
102+ const turn = appendMessage(db, session.id, userMsg);
103+
104+ await runAgentLoop({
105+ db,
106+ sessionId: session.id,
107+ turn,
108+ model: faux.getModel(),
109+ systemPrompt: "Test",
110+ tools: [],
111+ messages: [userMsg],
112+ cwd: tmp,
113+ });
114+
115+ const dbMessages = loadMessages(db, session.id);
116+ expect(dbMessages).toHaveLength(2);
117+ expect(dbMessages[0]!.role).toBe("user");
118+ expect(dbMessages[1]!.role).toBe("assistant");
119+ });
120+
121+ test("executes tool calls and appends results", async () => {
122+ faux.setResponses([
123+ // First response: call shell tool
124+ fauxAssistantMessage(
125+ [fauxToolCall("shell", { command: "echo tool-output" })],
126+ { stopReason: "toolUse" },
127+ ),
128+ // Second response: after tool result, reply with text
129+ fauxAssistantMessage("Done! The output was tool-output."),
130+ ]);
131+
132+ const session = createSession(db, { cwd: tmp });
133+ const userMsg = makeUser("run echo");
134+ const turn = appendMessage(db, session.id, userMsg);
135+
136+ const result = await runAgentLoop({
137+ db,
138+ sessionId: session.id,
139+ turn,
140+ model: faux.getModel(),
141+ systemPrompt: "Test",
142+ tools: builtinTools(),
143+ messages: [userMsg],
144+ cwd: tmp,
145+ });
146+
147+ // user → assistant(toolCall) → toolResult → assistant(text)
148+ expect(result.messages).toHaveLength(4);
149+ expect(result.messages[0]!.role).toBe("user");
150+ expect(result.messages[1]!.role).toBe("assistant");
151+ expect(result.messages[2]!.role).toBe("toolResult");
152+ expect(result.messages[3]!.role).toBe("assistant");
153+ expect((result.messages[3] as AssistantMessage).stopReason).toBe("stop");
154+
155+ // DB should match
156+ const dbMessages = loadMessages(db, session.id);
157+ expect(dbMessages).toHaveLength(4);
158+ });
159+
160+ test("handles multiple tool calls in a single response", async () => {
161+ writeFileSync(join(tmp, "file.txt"), "original content");
162+
163+ faux.setResponses([
164+ // One response with two tool calls
165+ fauxAssistantMessage(
166+ [
167+ fauxToolCall("shell", { command: "echo first" }),
168+ fauxToolCall("edit", {
169+ path: "file.txt",
170+ oldText: "original",
171+ newText: "modified",
172+ }),
173+ ],
174+ { stopReason: "toolUse" },
175+ ),
176+ // Follow-up
177+ fauxAssistantMessage("Both done."),
178+ ]);
179+
180+ const session = createSession(db, { cwd: tmp });
181+ const userMsg = makeUser("do both");
182+ const turn = appendMessage(db, session.id, userMsg);
183+
184+ const result = await runAgentLoop({
185+ db,
186+ sessionId: session.id,
187+ turn,
188+ model: faux.getModel(),
189+ systemPrompt: "Test",
190+ tools: builtinTools(),
191+ messages: [userMsg],
192+ cwd: tmp,
193+ });
194+
195+ // user → assistant(2 toolCalls) → toolResult × 2 → assistant(text)
196+ expect(result.messages).toHaveLength(5);
197+ expect(result.messages[2]!.role).toBe("toolResult");
198+ expect(result.messages[3]!.role).toBe("toolResult");
199+ expect(result.messages[4]!.role).toBe("assistant");
200+ });
201+
202+ test("chains multiple tool-use rounds", async () => {
203+ faux.setResponses([
204+ // Round 1: tool call
205+ fauxAssistantMessage(
206+ [fauxToolCall("shell", { command: "echo round1" })],
207+ { stopReason: "toolUse" },
208+ ),
209+ // Round 2: another tool call after seeing result
210+ fauxAssistantMessage(
211+ [fauxToolCall("shell", { command: "echo round2" })],
212+ { stopReason: "toolUse" },
213+ ),
214+ // Round 3: done
215+ fauxAssistantMessage("All rounds complete."),
216+ ]);
217+
218+ const session = createSession(db, { cwd: tmp });
219+ const userMsg = makeUser("chain");
220+ const turn = appendMessage(db, session.id, userMsg);
221+
222+ const result = await runAgentLoop({
223+ db,
224+ sessionId: session.id,
225+ turn,
226+ model: faux.getModel(),
227+ systemPrompt: "Test",
228+ tools: builtinTools(),
229+ messages: [userMsg],
230+ cwd: tmp,
231+ });
232+
233+ // user → assistant(tc) → toolResult → assistant(tc) → toolResult → assistant(text)
234+ expect(result.messages).toHaveLength(6);
235+ expect(result.stopReason).toBe("stop");
236+ });
237+
238+ test("all messages in loop share the same turn number", async () => {
239+ faux.setResponses([
240+ fauxAssistantMessage([fauxToolCall("shell", { command: "echo hi" })], {
241+ stopReason: "toolUse",
242+ }),
243+ fauxAssistantMessage("Done."),
244+ ]);
245+
246+ const session = createSession(db, { cwd: tmp });
247+ const userMsg = makeUser("test turns");
248+ const turn = appendMessage(db, session.id, userMsg);
249+
250+ await runAgentLoop({
251+ db,
252+ sessionId: session.id,
253+ turn,
254+ model: faux.getModel(),
255+ systemPrompt: "Test",
256+ tools: builtinTools(),
257+ messages: [userMsg],
258+ cwd: tmp,
259+ });
260+
261+ // All messages should be in the same turn — undo should remove everything
262+ const dbMessages = loadMessages(db, session.id);
263+ expect(dbMessages).toHaveLength(4); // user + assistant + toolResult + assistant
264+
265+ // Undo should remove all of them (same turn)
266+ const { undoLastTurn } = await import("./session.ts");
267+ undoLastTurn(db, session.id);
268+ expect(loadMessages(db, session.id)).toHaveLength(0);
269+ });
270+
271+ test("emits events during streaming", async () => {
272+ faux.setResponses([fauxAssistantMessage("Hello world")]);
273+
274+ const events: AgentEvent[] = [];
275+
276+ const session = createSession(db, { cwd: tmp });
277+ const userMsg = makeUser("hi");
278+ const turn = appendMessage(db, session.id, userMsg);
279+
280+ await runAgentLoop({
281+ db,
282+ sessionId: session.id,
283+ turn,
284+ model: faux.getModel(),
285+ systemPrompt: "Test",
286+ tools: [],
287+ messages: [userMsg],
288+ cwd: tmp,
289+ onEvent: (e) => events.push(e),
290+ });
291+
292+ const textDeltas = events.filter((e) => e.type === "text_delta");
293+ expect(textDeltas.length).toBeGreaterThan(0);
294+
295+ const doneEvents = events.filter((e) => e.type === "done");
296+ expect(doneEvents).toHaveLength(1);
297+ });
298+
299+ test("emits tool events during tool execution", async () => {
300+ faux.setResponses([
301+ fauxAssistantMessage([fauxToolCall("shell", { command: "echo test" })], {
302+ stopReason: "toolUse",
303+ }),
304+ fauxAssistantMessage("Done."),
305+ ]);
306+
307+ const events: AgentEvent[] = [];
308+
309+ const session = createSession(db, { cwd: tmp });
310+ const userMsg = makeUser("go");
311+ const turn = appendMessage(db, session.id, userMsg);
312+
313+ await runAgentLoop({
314+ db,
315+ sessionId: session.id,
316+ turn,
317+ model: faux.getModel(),
318+ systemPrompt: "Test",
319+ tools: builtinTools(),
320+ messages: [userMsg],
321+ cwd: tmp,
322+ onEvent: (e) => events.push(e),
323+ });
324+
325+ const toolStarts = events.filter((e) => e.type === "tool_start");
326+ const toolEnds = events.filter((e) => e.type === "tool_end");
327+ expect(toolStarts).toHaveLength(1);
328+ expect(toolEnds).toHaveLength(1);
329+ });
330+
331+ test("interrupt preserves partial response", async () => {
332+ faux.setResponses([
333+ fauxAssistantMessage("This response will be interrupted"),
334+ ]);
335+
336+ // Pre-abort so the faux provider immediately returns an aborted message
337+ const controller = new AbortController();
338+ controller.abort();
339+
340+ const session = createSession(db, { cwd: tmp });
341+ const userMsg = makeUser("long task");
342+ const turn = appendMessage(db, session.id, userMsg);
343+
344+ const result = await runAgentLoop({
345+ db,
346+ sessionId: session.id,
347+ turn,
348+ model: faux.getModel(),
349+ systemPrompt: "Test",
350+ tools: [],
351+ messages: [userMsg],
352+ cwd: tmp,
353+ signal: controller.signal,
354+ });
355+
356+ expect(result.stopReason).toBe("aborted");
357+ // Partial message should be in messages
358+ expect(result.messages).toHaveLength(2);
359+ const lastMsg = result.messages[
360+ result.messages.length - 1
361+ ] as AssistantMessage;
362+ expect(lastMsg.role).toBe("assistant");
363+ expect(lastMsg.stopReason).toBe("aborted");
364+
365+ // Should be persisted to DB
366+ const dbMessages = loadMessages(db, session.id);
367+ const dbLast = dbMessages[dbMessages.length - 1] as AssistantMessage;
368+ expect(dbLast.role).toBe("assistant");
369+ expect(dbLast.stopReason).toBe("aborted");
370+ });
371+
372+ test("handles LLM error gracefully", async () => {
373+ faux.setResponses([
374+ fauxAssistantMessage("", {
375+ stopReason: "error",
376+ errorMessage: "Rate limit exceeded",
377+ }),
378+ ]);
379+
380+ const session = createSession(db, { cwd: tmp });
381+ const userMsg = makeUser("trigger error");
382+ const turn = appendMessage(db, session.id, userMsg);
383+
384+ const result = await runAgentLoop({
385+ db,
386+ sessionId: session.id,
387+ turn,
388+ model: faux.getModel(),
389+ systemPrompt: "Test",
390+ tools: [],
391+ messages: [userMsg],
392+ cwd: tmp,
393+ });
394+
395+ expect(result.stopReason).toBe("error");
396+ });
397+
398+ test("handles unknown tool name gracefully", async () => {
399+ faux.setResponses([
400+ fauxAssistantMessage([fauxToolCall("nonexistent_tool", { foo: "bar" })], {
401+ stopReason: "toolUse",
402+ }),
403+ fauxAssistantMessage("I see the error, let me try again."),
404+ ]);
405+
406+ const session = createSession(db, { cwd: tmp });
407+ const userMsg = makeUser("test unknown tool");
408+ const turn = appendMessage(db, session.id, userMsg);
409+
410+ const result = await runAgentLoop({
411+ db,
412+ sessionId: session.id,
413+ turn,
414+ model: faux.getModel(),
415+ systemPrompt: "Test",
416+ tools: builtinTools(),
417+ messages: [userMsg],
418+ cwd: tmp,
419+ });
420+
421+ // Should still complete — the error tool result lets the model self-correct
422+ expect(result.messages.length).toBeGreaterThanOrEqual(4);
423+ // The tool result should be an error
424+ const toolResult = result.messages.find((m) => m.role === "toolResult");
425+ expect(toolResult).toBeDefined();
426+ if (toolResult?.role === "toolResult") {
427+ expect(toolResult.isError).toBe(true);
428+ }
429+ });
430+
431+ test("stopReason 'length' returns without looping", async () => {
432+ faux.setResponses([
433+ fauxAssistantMessage("Partial response that hit the token limit", {
434+ stopReason: "length",
435+ }),
436+ ]);
437+
438+ const session = createSession(db, { cwd: tmp });
439+ const userMsg = makeUser("big question");
440+ const turn = appendMessage(db, session.id, userMsg);
441+
442+ const result = await runAgentLoop({
443+ db,
444+ sessionId: session.id,
445+ turn,
446+ model: faux.getModel(),
447+ systemPrompt: "Test",
448+ tools: [],
449+ messages: [userMsg],
450+ cwd: tmp,
451+ });
452+
453+ expect(result.stopReason).toBe("length");
454+ expect(result.messages).toHaveLength(2);
455+ });
456+});
src/agent.ts+233−0
@@ -0,0 +1,233 @@
1+/**
2+ * Core agent loop.
3+ *
4+ * Streams LLM responses, executes tool calls, appends messages to the
5+ * session history, and loops until the model stops or the user interrupts.
6+ * Uses pi-ai's {@link streamSimple} for model communication.
7+ *
8+ * @module
9+ */
10+
11+import type { Database } from "bun:sqlite";
12+import type {
13+ AssistantMessage,
14+ ImageContent,
15+ Message,
16+ Model,
17+ TextContent,
18+ Tool,
19+ ToolCall,
20+ ToolResultMessage,
21+} from "@mariozechner/pi-ai";
22+import { streamSimple } from "@mariozechner/pi-ai";
23+import { appendMessage } from "./session.ts";
24+
25+// ---------------------------------------------------------------------------
26+// Types
27+// ---------------------------------------------------------------------------
28+
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+}
40+
41+/** Result from executing a tool. */
42+export interface ToolExecResult {
43+ /** Text result. */
44+ text: string;
45+ /** Whether the execution encountered an error. */
46+ isError: boolean;
47+}
48+
49+/** Events emitted during the agent loop for UI updates. */
50+export type AgentEvent =
51+ | { type: "text_delta"; delta: string }
52+ | { type: "thinking_delta"; delta: string }
53+ | { type: "tool_start"; name: string; args: Record<string, unknown> }
54+ | { type: "tool_end"; name: string; result: ToolExecResult }
55+ | { type: "done"; message: AssistantMessage }
56+ | { type: "error"; message: AssistantMessage }
57+ | { type: "aborted"; message: AssistantMessage };
58+
59+/** Options for the agent loop. */
60+export interface RunAgentOpts {
61+ /** Open database handle. */
62+ db: Database;
63+ /** Current session ID. */
64+ sessionId: string;
65+ /** Turn number for this agent loop (all messages share this turn). */
66+ turn: number;
67+ /** The model to stream with. */
68+ model: Model<string>;
69+ /** The assembled system prompt. */
70+ systemPrompt: string;
71+ /** Registered tools (built-in + plugin). */
72+ tools: AgentTool[];
73+ /** Current message history (mutated in-place as messages are appended). */
74+ messages: Message[];
75+ /** Working directory for tool execution. */
76+ cwd: string;
77+ /** Abort signal for interruption. */
78+ signal?: AbortSignal;
79+ /** Callback for UI events. */
80+ onEvent?: (event: AgentEvent) => void;
81+}
82+
83+/** Result of the agent loop. */
84+export interface AgentLoopResult {
85+ /** The updated message history. */
86+ messages: Message[];
87+ /** How the loop ended. */
88+ stopReason: "stop" | "length" | "error" | "aborted";
89+}
90+
91+// ---------------------------------------------------------------------------
92+// Agent loop
93+// ---------------------------------------------------------------------------
94+
95+/**
96+ * Run the agent loop for a single turn.
97+ *
98+ * Streams an LLM response, executes any tool calls, appends all messages
99+ * to the session (sharing the same turn number), and loops back when the
100+ * model requests tool use. Returns when the model stops, hits a length
101+ * limit, errors, or is aborted.
102+ *
103+ * @param opts - Agent loop options.
104+ * @returns The loop result with updated messages and stop reason.
105+ */
106+export async function runAgentLoop(
107+ opts: RunAgentOpts,
108+): Promise<AgentLoopResult> {
109+ const {
110+ db,
111+ sessionId,
112+ turn,
113+ model,
114+ systemPrompt,
115+ tools,
116+ messages,
117+ cwd,
118+ signal,
119+ onEvent,
120+ } = opts;
121+
122+ const toolDefs = tools.map((t) => t.definition);
123+ const toolMap = new Map(tools.map((t) => [t.definition.name, t]));
124+
125+ while (true) {
126+ // Build context for this iteration
127+ const context =
128+ toolDefs.length > 0
129+ ? { systemPrompt, messages, tools: toolDefs }
130+ : { systemPrompt, messages };
131+
132+ // Stream to LLM
133+ const streamOpts = signal ? { signal } : {};
134+ const eventStream = streamSimple(model, context, streamOpts);
135+ let assistantMessage: AssistantMessage | undefined;
136+
137+ for await (const event of eventStream) {
138+ switch (event.type) {
139+ case "text_delta":
140+ onEvent?.({ type: "text_delta", delta: event.delta });
141+ break;
142+ case "thinking_delta":
143+ onEvent?.({ type: "thinking_delta", delta: event.delta });
144+ break;
145+ case "toolcall_end":
146+ // Tool calls are collected from the final assistant message
147+ break;
148+ case "done":
149+ assistantMessage = event.message;
150+ break;
151+ case "error":
152+ assistantMessage = event.error;
153+ break;
154+ }
155+ }
156+
157+ // If somehow we got no message, fall back to the stream result
158+ if (!assistantMessage) {
159+ assistantMessage = await eventStream.result();
160+ }
161+
162+ // Append assistant message to history and DB
163+ messages.push(assistantMessage);
164+ appendMessage(db, sessionId, assistantMessage, turn);
165+
166+ // Handle stop reasons
167+ if (
168+ assistantMessage.stopReason === "error" ||
169+ assistantMessage.stopReason === "aborted"
170+ ) {
171+ const eventType =
172+ assistantMessage.stopReason === "error" ? "error" : "aborted";
173+ onEvent?.({ type: eventType, message: assistantMessage });
174+ return { messages, stopReason: assistantMessage.stopReason };
175+ }
176+
177+ if (
178+ assistantMessage.stopReason === "stop" ||
179+ assistantMessage.stopReason === "length"
180+ ) {
181+ onEvent?.({ type: "done", message: assistantMessage });
182+ return { messages, stopReason: assistantMessage.stopReason };
183+ }
184+
185+ // stopReason === "toolUse" — execute tool calls and loop
186+ const toolCalls = assistantMessage.content.filter(
187+ (c): c is ToolCall => c.type === "toolCall",
188+ );
189+
190+ 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;
204+ } else {
205+ onEvent?.({
206+ type: "tool_start",
207+ name: toolCall.name,
208+ args: toolCall.arguments,
209+ });
210+
211+ const result = await tool.execute(toolCall.arguments, cwd, signal);
212+ resultContent = [{ type: "text", text: result.text }];
213+ isError = result.isError;
214+
215+ onEvent?.({ type: "tool_end", name: toolCall.name, result });
216+ }
217+
218+ const toolResultMessage: ToolResultMessage = {
219+ role: "toolResult",
220+ toolCallId: toolCall.id,
221+ toolName: toolCall.name,
222+ content: resultContent,
223+ isError,
224+ timestamp: Date.now(),
225+ };
226+
227+ messages.push(toolResultMessage);
228+ appendMessage(db, sessionId, toolResultMessage, turn);
229+ }
230+
231+ // Loop back to stream with updated context
232+ }
233+}
src/plugins.test.ts+255−0
@@ -0,0 +1,255 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import {
6+ type AgentContext,
7+ destroyPlugins,
8+ initPlugins,
9+ loadPluginConfig,
10+ type PluginEntry,
11+} from "./plugins.ts";
12+
13+// ---------------------------------------------------------------------------
14+// Helpers
15+// ---------------------------------------------------------------------------
16+
17+let tmp: string;
18+
19+beforeEach(() => {
20+ tmp = mkdtempSync(join(tmpdir(), "mc-plugins-"));
21+});
22+
23+afterEach(() => {
24+ rmSync(tmp, { recursive: true, force: true });
25+});
26+
27+function makeContext(): AgentContext {
28+ return {
29+ cwd: tmp,
30+ messages: [],
31+ dataDir: join(tmp, ".config"),
32+ };
33+}
34+
35+/** Write a plugin module file and return its path. */
36+function writePlugin(name: string, code: string): string {
37+ const path = join(tmp, `${name}.ts`);
38+ writeFileSync(path, code);
39+ return path;
40+}
41+
42+// ---------------------------------------------------------------------------
43+// loadPluginConfig
44+// ---------------------------------------------------------------------------
45+
46+describe("loadPluginConfig", () => {
47+ test("returns empty array when config file does not exist", () => {
48+ const entries = loadPluginConfig(join(tmp, "nonexistent.json"));
49+ expect(entries).toEqual([]);
50+ });
51+
52+ test("parses plugin entries from config file", () => {
53+ const config = {
54+ plugins: [
55+ { name: "test", module: "./test-plugin.ts" },
56+ { name: "other", module: "@scope/plugin", config: { key: "value" } },
57+ ],
58+ };
59+ writeFileSync(join(tmp, "plugins.json"), JSON.stringify(config));
60+
61+ const entries = loadPluginConfig(join(tmp, "plugins.json"));
62+ expect(entries).toHaveLength(2);
63+ expect(entries[0]!.name).toBe("test");
64+ expect(entries[1]!.config).toEqual({ key: "value" });
65+ });
66+
67+ test("returns empty array when config has no plugins key", () => {
68+ writeFileSync(join(tmp, "plugins.json"), "{}");
69+ const entries = loadPluginConfig(join(tmp, "plugins.json"));
70+ expect(entries).toEqual([]);
71+ });
72+});
73+
74+// ---------------------------------------------------------------------------
75+// initPlugins
76+// ---------------------------------------------------------------------------
77+
78+describe("initPlugins", () => {
79+ test("loads and initializes a plugin module", async () => {
80+ const modulePath = writePlugin(
81+ "good-plugin",
82+ `
83+ export const name = "good";
84+ export const description = "A good plugin";
85+ export async function init(agent, config) {
86+ return { systemPromptSuffix: "Plugin context: good" };
87+ }
88+ `,
89+ );
90+
91+ const entries: PluginEntry[] = [{ name: "good", module: modulePath }];
92+
93+ const loaded = await initPlugins(entries, makeContext());
94+ expect(loaded).toHaveLength(1);
95+ expect(loaded[0]!.result.systemPromptSuffix).toBe("Plugin context: good");
96+ });
97+
98+ test("passes config to plugin init", async () => {
99+ const modulePath = writePlugin(
100+ "config-plugin",
101+ `
102+ export const name = "configurable";
103+ export const description = "Reads config";
104+ export async function init(agent, config) {
105+ return { systemPromptSuffix: "key=" + config?.key };
106+ }
107+ `,
108+ );
109+
110+ const entries: PluginEntry[] = [
111+ { name: "configurable", module: modulePath, config: { key: "hello" } },
112+ ];
113+
114+ const loaded = await initPlugins(entries, makeContext());
115+ expect(loaded[0]!.result.systemPromptSuffix).toBe("key=hello");
116+ });
117+
118+ test("skips plugins that fail to load and reports error", async () => {
119+ const entries: PluginEntry[] = [
120+ { name: "missing", module: join(tmp, "does-not-exist.ts") },
121+ ];
122+
123+ const errors: Array<{ name: string; error: Error }> = [];
124+ const loaded = await initPlugins(entries, makeContext(), (entry, error) => {
125+ errors.push({ name: entry.name, error });
126+ });
127+
128+ expect(loaded).toHaveLength(0);
129+ expect(errors).toHaveLength(1);
130+ expect(errors[0]!.name).toBe("missing");
131+ });
132+
133+ test("skips plugins that fail during init and reports error", async () => {
134+ const modulePath = writePlugin(
135+ "bad-init",
136+ `
137+ export const name = "bad";
138+ export const description = "Fails on init";
139+ export async function init() {
140+ throw new Error("init exploded");
141+ }
142+ `,
143+ );
144+
145+ const entries: PluginEntry[] = [{ name: "bad", module: modulePath }];
146+
147+ const errors: Array<{ name: string; message: string }> = [];
148+ const loaded = await initPlugins(entries, makeContext(), (entry, error) => {
149+ errors.push({ name: entry.name, message: error.message });
150+ });
151+
152+ expect(loaded).toHaveLength(0);
153+ expect(errors).toHaveLength(1);
154+ expect(errors[0]!.message).toContain("init exploded");
155+ });
156+
157+ test("collects tools from plugin results", async () => {
158+ const modulePath = writePlugin(
159+ "tool-plugin",
160+ `
161+ export const name = "tools";
162+ export const description = "Provides tools";
163+ export async function init() {
164+ return {
165+ tools: [{
166+ name: "custom_tool",
167+ description: "A custom tool",
168+ parameters: { type: "object", properties: {} },
169+ }],
170+ };
171+ }
172+ `,
173+ );
174+
175+ const entries: PluginEntry[] = [{ name: "tools", module: modulePath }];
176+
177+ const loaded = await initPlugins(entries, makeContext());
178+ expect(loaded[0]!.result.tools).toHaveLength(1);
179+ expect(loaded[0]!.result.tools![0]!.name).toBe("custom_tool");
180+ });
181+});
182+
183+// ---------------------------------------------------------------------------
184+// destroyPlugins
185+// ---------------------------------------------------------------------------
186+
187+describe("destroyPlugins", () => {
188+ test("calls destroy on plugins that implement it", async () => {
189+ // Use a file as a side-effect marker
190+ const markerPath = join(tmp, "destroyed.txt");
191+ const modulePath = writePlugin(
192+ "destroyable",
193+ `
194+ import { writeFileSync } from "node:fs";
195+ export const name = "destroyable";
196+ export const description = "Has destroy";
197+ export async function init() { return {}; }
198+ export async function destroy() {
199+ writeFileSync("${markerPath}", "destroyed");
200+ }
201+ `,
202+ );
203+
204+ const entries: PluginEntry[] = [
205+ { name: "destroyable", module: modulePath },
206+ ];
207+
208+ const loaded = await initPlugins(entries, makeContext());
209+ await destroyPlugins(loaded);
210+
211+ const { existsSync } = await import("node:fs");
212+ expect(existsSync(markerPath)).toBe(true);
213+ });
214+
215+ test("reports destroy errors without stopping other plugins", async () => {
216+ const marker1 = join(tmp, "d1.txt");
217+ const mod1 = writePlugin(
218+ "p1",
219+ `
220+ export const name = "p1";
221+ export const description = "Fails destroy";
222+ export async function init() { return {}; }
223+ export async function destroy() { throw new Error("destroy failed"); }
224+ `,
225+ );
226+ const mod2 = writePlugin(
227+ "p2",
228+ `
229+ import { writeFileSync } from "node:fs";
230+ export const name = "p2";
231+ export const description = "Good destroy";
232+ export async function init() { return {}; }
233+ export async function destroy() { writeFileSync("${marker1}", "ok"); }
234+ `,
235+ );
236+
237+ const entries: PluginEntry[] = [
238+ { name: "p1", module: mod1 },
239+ { name: "p2", module: mod2 },
240+ ];
241+
242+ const loaded = await initPlugins(entries, makeContext());
243+
244+ const errors: string[] = [];
245+ await destroyPlugins(loaded, (entry, error) => {
246+ errors.push(`${entry.name}: ${error.message}`);
247+ });
248+
249+ // p1 failed but p2 still ran
250+ expect(errors).toHaveLength(1);
251+ expect(errors[0]).toContain("p1");
252+ const { existsSync } = await import("node:fs");
253+ expect(existsSync(marker1)).toBe(true);
254+ });
255+});
src/plugins.ts+177−0
@@ -0,0 +1,177 @@
1+/**
2+ * Plugin loader and lifecycle management.
3+ *
4+ * Plugins extend mini-coder with additional tools and system prompt context.
5+ * They are declared in a config file and loaded as modules at startup.
6+ * Each plugin's `init` is called once, and `destroy` (if present) is called
7+ * on shutdown.
Cut short: this commit's diff is over 1000 lines.
src/tools.test.ts+96−1
Cut short: this commit's diff is over 1000 lines.
src/tools.ts+95−7
Cut short: this commit's diff is over 1000 lines.