xonecas.io
64875
Mc

mini-coder / commit b452dd5

refactor: remove plugin runtime wiring

xonecas2026-04-19 b452dd59b990be0eabce28c45f91ef7e3858fbd3 parent 056b0ed

14 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+3−4
@@ -13,11 +13,11 @@
1313
1414 ## Code map
1515
16-- `src/index.ts` — startup, providers, settings, AGENTS.md/skills/plugins loading, theme assembly, shared app state.
16+- `src/index.ts` — startup, providers, settings, AGENTS.md/skills loading, theme assembly, shared app state.
1717 - `src/agent.ts` — streaming model loop, tool dispatch, agent events.
1818 - `src/tools.ts` — built-in tools and truncation logic.
1919 - `src/session.ts` — SQLite persistence, turn numbering, undo/fork, prompt history, cumulative stats.
20-- `src/prompt.ts`, `src/skills.ts`, `src/plugins.ts` — prompt assembly and external context discovery/loading.
20+- `src/prompt.ts`, `src/skills.ts` — prompt assembly and external context discovery/loading.
2121 - `src/ui.ts` — cel-tui lifecycle and top-level orchestration.
2222 - `src/ui/agent.ts` — input submission, streaming state, agent-loop wiring.
2323 - `src/ui/commands.ts` — slash commands and Select overlays.
@@ -88,10 +88,9 @@
8888 - In cel-tui `onKeyPress`, return `false` only for keys you explicitly intercept. Escape often needs `onBlur`, not `onKeyPress`.
8989 - When adding provider/tool options, trace them through the full call chain (for example `apiKey` into `streamSimple`).
9090 - UI/info messages may live in the persisted log and in `state.messages`, but they must stay marked as UI-only (`role: "ui"`, `turn = NULL`) and always be filtered out of model context.
91-- Prompt context has explicit reload boundaries: AGENTS.md content, discovered skills, and plugin prompt suffixes are stable within a session and should refresh only at boundaries like `/new` or CWD change.
91+- Prompt context has explicit reload boundaries: AGENTS.md content and discovered skills are stable within a session and should refresh only at boundaries like `/new` or CWD change.
9292 - Tool safety truncation and UI `/verbose` preview are separate layers. Do not conflate them.
9393 - Avoid accretive growth. When a file starts absorbing unrelated behavior, split it at a real seam instead of appending more helpers. Prefer explicit state ownership over module globals, shared helpers over copy-modify text/state logic, and typed boundaries over `Record<string, unknown>` plus downstream casts.
94-- The plugin API is still in spec-alignment cleanup. Current repo reality is `tools` plus `toolHandlers`; treat that as temporary, not settled design.
9594 - Before 1.0, prefer correct/simple semantics over speculative compatibility shims, but call out intentional breaking changes.
9695 - TUI changes need real terminal validation in `tmux`; passing tests is not enough.
9796 - Stay within the agreed TODO scope. Do not pull in adjacent items without discussion.
TODO.md+7−10
@@ -7,6 +7,13 @@ The spec and code are the sources of truth; this file is just the verified backl
77
88 ## Open issues:
99
10+## MCP + theme config plan
11+
12+- [ ] Extend the existing `settings.json` schema/loader with `mcp` config, following the same config-file model as `customProviders` (`src/settings.ts`, `src/index.ts`, `spec.md`)
13+- [ ] Add first-party MCP client support using an official npm package and register the resulting tools from built-in runtime code instead of a plugin layer (`src/index.ts`, `src/tools.ts`, `src/agent.ts`, `spec.md`)
14+- [ ] Extend the existing `settings.json` schema/loader with `theme` overrides and merge them into the active UI theme (`src/settings.ts`, `src/theme.ts`, `src/index.ts`, `spec.md`)
15+- [ ] Update tests and user-facing docs/help for the new `settings.json`-based MCP/theme setup and remove plugin references (`src/index.test.ts`, `src/ui/help.ts`, `README.md`, `spec.md`)
16+
1017 ## Verified UX / behavior debt
1118
1219 - [ ] Prevent `/session` from switching sessions mid-run (`src/ui/commands.ts`, `src/ui/agent.ts`)
@@ -15,13 +22,3 @@ The spec and code are the sources of truth; this file is just the verified backl
1522 ## Product backlog
1623
1724 - [ ] Add first-class delegation/subagent support instead of relying on shell-level `mc -p` delegation (`src/agent.ts`, `src/tools.ts`, `src/prompt.ts`, `src/headless.ts`)
18-
19-## Plugin debt (verified, deferred)
20-
21-> We should have built the code plugin first, now we are a little bit in a corner. The only clear seam is core/UI.
22-
23-- [ ] Make plugin lifecycle match the spec: initialize once at startup and destroy on shutdown, not on prompt-context reload boundaries (`src/index.ts`, `src/plugins.ts`)
24-- [ ] Match the plugin tool execution API to the spec/docs instead of the temporary `tools` + `toolHandlers` split (`src/plugins.ts`, `src/index.ts`, `spec.md`)
25-- [ ] Keep `Plugin AgentContext.messages` current or narrow the contract so it is not stale (`src/index.ts`, `src/plugins.ts`, `spec.md`)
26-- [ ] Support package-name and config-relative plugin imports (`src/plugins.ts`)
27-- [ ] Prefix plugin tool rendering with `plugin/tool` in the log when available (`src/index.ts`, `src/ui/conversation.ts`)
package.json+2−1
@@ -21,7 +21,8 @@
2121 "@cel-tui/components": "^0.8.1",
2222 "@cel-tui/core": "^0.8.1",
2323 "@cel-tui/types": "^0.8.1",
24- "@mariozechner/pi-ai": "^0.67.68"
24+ "@mariozechner/pi-ai": "^0.67.68",
25+ "@modelcontextprotocol/sdk": "^1.29.0"
2526 },
2627 "devDependencies": {
2728 "@biomejs/biome": "^2.4.12",
spec.md+10−80
@@ -57,7 +57,7 @@ This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom
5757
5858 ## Tools
5959
60-Six built-in tools, plus a conditional read-only image tool. Plugins may add more (see [Plugins](#plugins)).
60+Six built-in tools, plus a conditional read-only image tool.
6161
6262 ### `shell`
6363
@@ -187,74 +187,13 @@ We follow the spec's progressive disclosure model:
187187
188188 Relative paths in skills are resolved against the skill's directory. The system prompt instructions explain this to the model.
189189
190-## Plugins
191-
192-Plugins extend mini-coder itself, not just the prompt. They are the mechanism for optional capabilities that don't belong in the core — MCP servers, custom tools, integrations, alternate context-management strategies, UI/theme extensions, and other agent features.
193-
194-### Interface
195-
196-A plugin is a module that exports a function conforming to a simple interface:
197-
198-```ts
199-interface Plugin {
200- name: string;
201- description: string;
202-
203- /** Called once at startup. Returns tools to register and/or context to add. */
204- init(
205- agent: AgentContext,
206- config?: Record<string, unknown>,
207- ): Promise<PluginResult>;
208-
209- /** Called on shutdown for cleanup. */
210- destroy?(): Promise<void>;
211-}
212-
213-interface PluginResult {
214- /** Additional tools the agent can use. */
215- tools?: Tool[];
216- /** Additional context to append to the system prompt. */
217- systemPromptSuffix?: string;
218- /** Partial theme override — merged on top of the default theme. */
219- theme?: Partial<Theme>;
220-}
221-
222-interface AgentContext {
223- /** The working directory. */
224- cwd: string;
225- /** Read-only access to the current session's messages. */
226- messages: readonly Message[];
227- /** The app data directory (~/.config/mini-coder/). */
228- dataDir: string;
229-}
230-```
231-
232-### Discovery
233-
234-Plugins are declared in a config file (`~/.config/mini-coder/plugins.json` or similar). Each entry points to a module path or package name:
235-
236-```json
237-{
238- "plugins": [
239- { "name": "mcp", "module": "@mini-coder/plugin-mcp", "config": { ... } },
240- { "name": "custom", "module": "./my-plugin.ts" }
241- ]
242-}
243-```
244-
245-### Why plugins
246-
247-- **Separation of concerns**: the agent loop doesn't know about specific integrations or optional behaviors — it only sees `Tool[]` and plugin-provided context/theme extensions.
248-- **Optional complexity**: capabilities are opt-in. Users only pay for what they use.
249-- **Extensibility without bloat**: third-party tools, custom integrations, project-specific helpers, and non-core agent features all go through the same interface.
250-
251190 ## Agent loop
252191
253192 The core runtime. Streaming is the default behavior throughout the turn: user-visible state should update incrementally as the model emits text, thinking, and tool-call events, rather than waiting for whole responses to complete. This is what happens while the agent is active:
254193
255194 1. **User submits a message** — the input text (plus any embedded images or skill bodies from `/skill:name`) becomes a pi-ai `UserMessage`. It is appended to the session's message history, rendered in the UI immediately, and persisted to the DB.
256195
257-2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). The prompt context snapshot is loaded once at startup or another explicit reload boundary and then reused across turns so provider prompt caching stays effective. It is refreshed only at boundaries such as `/new` or CWD change.
196+2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions. The prompt context snapshot is loaded once at startup or another explicit reload boundary and then reused across turns so provider prompt caching stays effective. It is refreshed only at boundaries such as `/new` or CWD change.
258197
259198 3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
260199 - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream raw markdown text, show thinking if enabled, accumulate tool call arguments as they arrive).
@@ -263,7 +202,7 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
263202 - `error` → display error in the log, return to the input prompt.
264203
265204 4. **Tool execution** — when the LLM requests tool calls:
266- - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `read`: read the requested file slice and include continuation guidance when needed. For `grep`: run the structured ripgrep search and return parsed match data. For `edit`: perform the replacement. For `todoWrite`: apply the incremental todo changes and return the full current list. For `todoRead`: return the full current list. For `readImage`: read and base64-encode the file. For plugin tools: del …
205+ - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `read`: read the requested file slice and include continuation guidance when needed. For `grep`: run the structured ripgrep search and return parsed match data. For `edit`: perform the replacement. For `todoWrite`: apply the incremental todo changes and return the full current list. For `todoRead`: return the full current list. For `readImage`: read and base64-encode the file.
267206 - Each result becomes a `ToolResultMessage` appended to history and DB (same turn number).
268207 - After all tool results are appended, if queued steering messages exist go to step 6; otherwise loop back to step 2 (re-stream with the updated context).
269208
@@ -287,7 +226,7 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
287226
288227 **No step limit** — the loop runs until the model stops (`stopReason: "stop"`) or the user interrupts. There is no maximum number of tool calls per turn.
289228
290-**Context limit** — mini-coder does not implement built-in context compaction. The status bar still estimates current context usage for the next request, but automatic history summarization is not a core feature. If compaction or summarization is added, it should be optional and plugin-provided rather than hardwired into the core, since users disagree about whether automatic compaction is desirable.
229+**Context limit** — mini-coder does not implement built-in context compaction. The status bar still estimates current context usage for the next request, but automatic history summarization is not a core feature. If compaction or summarization is added, it should stay optional rather than hardwired into the core, since users disagree about whether automatic compaction is desirable.
291230
292231 ## Architecture
293232
@@ -299,9 +238,8 @@ src/
299238 agent.ts — the core agent loop
300239 tools.ts — built-in tool implementations
301240 skills.ts — agentskills.io discovery, parsing, catalog
302- prompt.ts — system prompt construction (core prompt + AGENTS.md + skills + plugins + environment)
241+ prompt.ts — system prompt construction (core prompt + AGENTS.md + skills + environment)
303242 session.ts — SQLite session persistence
304- plugins.ts — plugin loader and lifecycle
305243 git.ts — git state gathering
306244 ui.ts — cel-tui UI (layout, rendering, state)
307245 types.ts — shared types
@@ -380,7 +318,7 @@ The current environment is:
380318 - Delegate when you are orchestarting a large to-do/plan execution.
381319 ```
382320
383-AGENTS.md content, skills catalog, and plugin suffixes are appended after this core prompt in that order.
321+AGENTS.md content and the skills catalog are appended after this core prompt in that order.
384322
385323 **AGENTS.md** (when present):
386324
@@ -413,7 +351,7 @@ Environment block notes:
413351 - The `Read Image` line is omitted when the active model does not support image input.
414352 - The OS value is normalized to `linux`, `mac`, or `docker`.
415353 - The static core prompt text should remain identical across turns.
416-- AGENTS.md content, skills, plugin suffixes, and the git snapshot are stable within a session, changing only on `/new` or CWD change.
354+- AGENTS.md content, skills, and the git snapshot are stable within a session, changing only on `/new` or CWD change.
417355 - Rebuilding the prompt for later turns must reuse that same session-start snapshot so provider prompt caching keeps working.
418356
419357 Git state is gathered when the session prompt context is loaded (startup, `/new`, or CWD change), not after each turn, via fast git commands:
@@ -494,7 +432,7 @@ VStack({ height: "100%" }, [
494432
495433 ### Theme
496434
497-All UI colors are defined in a single `Theme` object. The UI never hardcodes colors — it reads from the active theme. Plugins can return a `Partial<Theme>` in their `PluginResult` to override any color. Multiple plugin overrides are merged left-to-right (last wins).
435+All UI colors are defined in a single `Theme` object. The UI never hardcodes colors — it reads from the active theme. When theme overrides are applied, they merge left-to-right (last wins).
498436
499437 ```ts
500438 interface StatusTone {
@@ -596,7 +534,6 @@ Tool blocks share a common frame: a left border (`│`) plus a compact header pi
596534 - **Tool calls — edit**: rendered in the shared tool frame. The in-progress tool-call preview shows the target path followed by the streamed `oldText` and `newText` bodies. Old text is styled as removed and new text as added, but the preview does not render literal `-`/`+` diff prefixes. The preview body uses [verbose tool rendering](#verbose-tool-rendering). Successful results render a compact confirmation block (`edit <-` plus the file path); errors render the returned error text.
597535 - **Tool calls — todoWrite / todoRead**: rendered in the shared tool frame. Successful results render the full current todo list as a structured themed checklist with status markers (`[ ]`, `[~]`, `[x]`). This checklist is always shown in full and never truncated, regardless of `/verbose`. Errors render the returned error text.
598536 - **Tool calls — readImage**: rendered in the shared tool frame. The assistant tool call streams the path as it arrives. Successful results render a compact result block (`read image <-` plus the file path) rather than rendering the image itself.
599-- **Tool calls — plugin tools**: rendered in the shared tool frame, prefixed with plugin/tool name when available.
600537 - **UI messages**: internal app messages such as `/help` output, OAuth progress, `/fork` notices, and other session-local notices. They are rendered in the conversation log, persisted with the session, excluded from model context, and do not participate in conversational turn numbering. `/help` output renders as syntax-highlighted raw markdown so headings, lists, and inline code stay scannable while preserving the literal markdown markers. `/todo` output is also UI-only, but it renders using the …
601538 - **Errors**: one-line summary, styled distinctly.
602539
@@ -755,13 +692,6 @@ Representative entry shapes:
755692 │ screenshots/failing-layout.png
756693 ```
757694
758-**Plugin tool**
759-
760-```text
761- │ mcp/search <-
762- │ session persistence sqlite turn numbering
763-```
764-
765695 **UI message**
766696
767697 ```text
@@ -848,7 +778,7 @@ add tests for undo_
848778 | `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. …
849779 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
850780 | `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). …
851-| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files, discovered skills, and active plugins. …
781+| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files and discovered skills. …
852782
853783 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
854784
@@ -921,7 +851,7 @@ On launch, mini-coder:
921851 - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
922852 - `showReasoning`: if present, use it; otherwise fall back to `true`.
923853 - `verbose`: if present, use it; otherwise fall back to `false`.
924-5. Loads AGENTS.md files, skills, plugins.
854+5. Loads AGENTS.md files and skills.
925855 6. Selects the launch mode:
926856 - Interactive TUI when `stdin` and `stdout` are both TTYs and `-p` was not provided.
927857 - Headless one-shot mode otherwise.
src/headless.test.ts+0−1
@@ -43,7 +43,6 @@ function createTestState(): AppState {
4343 contextTokens: 0,
4444 agentsMd: [],
4545 skills: [],
46- plugins: [],
4746 theme: DEFAULT_THEME,
4847 git: null,
4948 providers: new Map(),
src/index.test.ts+29−70
@@ -15,7 +15,6 @@ import {
1515 reloadPromptContext,
1616 runHeadlessCli,
1717 } from "./index.ts";
18-import type { LoadedPlugin } from "./plugins.ts";
1918 import { openDatabase } from "./session.ts";
2019 import { DEFAULT_THEME } from "./theme.ts";
2120
@@ -29,7 +28,7 @@ function createTempDir(): string {
2928 return dir;
3029 }
3130
32-function createTestState(plugins: LoadedPlugin[] = []): AppState {
31+function createTestState(): AppState {
3332 const cwd = createTempDir();
3433 return {
3534 db: openDatabase(":memory:"),
@@ -41,7 +40,6 @@ function createTestState(plugins: LoadedPlugin[] = []): AppState {
4140 contextTokens: 0,
4241 agentsMd: [],
4342 skills: [],
44- plugins,
4543 theme: DEFAULT_THEME,
4644 git: null,
4745 providers: new Map(),
@@ -62,24 +60,6 @@ function createTestState(plugins: LoadedPlugin[] = []): AppState {
6260 };
6361 }
6462
65-function createLoadedPlugin(name: string): LoadedPlugin {
66- return {
67- entry: { name, module: `${name}.ts` },
68- plugin: {
69- name,
70- description: `${name} plugin`,
71- async init() {
72- return {};
73- },
74- async destroy() {},
75- },
76- result: {
77- systemPromptSuffix: `${name} suffix`,
78- theme: { accentText: "color03" },
79- },
80- };
81-}
82-
8363 afterEach(() => {
8464 for (const dir of tempDirs.splice(0)) {
8565 rmSync(dir, { recursive: true, force: true });
@@ -297,9 +277,8 @@ test("loadOAuthCredentials throws a helpful error when the auth file contains in
297277 );
298278 });
299279
300-test("loadPromptContext loads AGENTS.md, skills, plugins, and theme overrides", async () => {
280+test("loadPromptContext loads AGENTS.md, skills, and the default theme", async () => {
301281 const project = createTempDir();
302- const pluginPath = join(project, "plugin.ts");
303282
304283 writeFileSync(join(project, "AGENTS.md"), "Project instructions");
305284 mkdirSync(join(project, ".agents", "skills", "example-skill"), {
@@ -316,41 +295,25 @@ test("loadPromptContext loads AGENTS.md, skills, plugins, and theme overrides",
316295 "# Example Skill",
317296 ].join("\n"),
318297 );
319- writeFileSync(
320- pluginPath,
321- [
322- "export default {",
323- ' name: "test-plugin",',
324- ' description: "Adds prompt context.",',
325- " async init(agent) {",
326- " return {",
327- ` systemPromptSuffix: \`Plugin cwd: \${agent.cwd}\` ,`,
328- ' theme: { accentText: "color03" },',
329- " };",
330- " },",
331- "};",
332- ].join("\n"),
333- );
334298
335- const context = await loadPromptContext([], {
336- cwd: project,
337- pluginEntries: [{ name: "test-plugin", module: pluginPath }],
338- });
299+ const context = await loadPromptContext({ cwd: project });
339300
340301 expect(context.cwd).toBe(project);
341302 expect(context.agentsMd.at(-1)?.content).toBe("Project instructions");
342303 expect(context.skills.map((skill) => skill.name)).toContain("example-skill");
343- expect(context.plugins).toHaveLength(1);
344- expect(context.plugins[0]?.result.systemPromptSuffix).toBe(
345- `Plugin cwd: ${project}`,
346- );
347- expect(context.theme.accentText).toBe("color03");
304+ expect(context.theme).toBe(DEFAULT_THEME);
348305 });
349306
350-test("reloadPromptContext keeps the current plugin state when loading the replacement context fails", async () => {
351- const plugin = createLoadedPlugin("existing");
352- const state = createTestState([plugin]);
353- let destroyed = false;
307+test("reloadPromptContext keeps the current prompt context when replacement loading fails", async () => {
308+ const state = createTestState();
309+ state.agentsMd = [{ path: "/tmp/AGENTS.md", content: "current agents" }];
310+ state.skills = [
311+ {
312+ name: "existing-skill",
313+ description: "Already loaded.",
314+ path: "/tmp/existing/SKILL.md",
315+ },
316+ ];
354317
355318 try {
356319 await expect(
@@ -358,25 +321,21 @@ test("reloadPromptContext keeps the current plugin state when loading the replac
358321 loadPromptContext: async () => {
359322 throw new Error("reload failed");
360323 },
361- destroyPlugins: async () => {
362- destroyed = true;
363- },
364324 }),
365325 ).rejects.toThrow("reload failed");
366326
367- expect(destroyed).toBe(false);
368- expect(state.plugins).toEqual([plugin]);
327+ expect(state.agentsMd).toEqual([
328+ { path: "/tmp/AGENTS.md", content: "current agents" },
329+ ]);
330+ expect(state.skills.map((skill) => skill.name)).toEqual(["existing-skill"]);
369331 expect(state.theme).toBe(DEFAULT_THEME);
370332 } finally {
371333 state.db.close();
372334 }
373335 });
374336
375-test("reloadPromptContext swaps in the new context before destroying the old plugins", async () => {
376- const previousPlugin = createLoadedPlugin("previous");
377- const nextPlugin = createLoadedPlugin("next");
378- const state = createTestState([previousPlugin]);
379- let destroyedPlugins: LoadedPlugin[] = [];
337+test("reloadPromptContext replaces the current prompt context", async () => {
338+ const state = createTestState();
380339
381340 try {
382341 await reloadPromptContext(state, {
@@ -385,22 +344,22 @@ test("reloadPromptContext swaps in the new context before destroying the old plu
385344 canonicalCwd: state.canonicalCwd,
386345 git: null,
387346 agentsMd: [{ path: "/tmp/AGENTS.md", content: "next agents" }],
388- skills: [],
389- plugins: [nextPlugin],
347+ skills: [
348+ {
349+ name: "next-skill",
350+ description: "Replacement skill.",
351+ path: "/tmp/next/SKILL.md",
352+ },
353+ ],
390354 theme: { ...DEFAULT_THEME, accentText: "color05" },
391355 }),
392- destroyPlugins: async (plugins) => {
393- destroyedPlugins = [...plugins];
394- expect(state.plugins).toEqual([nextPlugin]);
395- expect(state.theme.accentText).toBe("color05");
396- },
397356 });
398357
399- expect(destroyedPlugins).toEqual([previousPlugin]);
400- expect(state.plugins).toEqual([nextPlugin]);
401358 expect(state.agentsMd).toEqual([
402359 { path: "/tmp/AGENTS.md", content: "next agents" },
403360 ]);
361+ expect(state.skills.map((skill) => skill.name)).toEqual(["next-skill"]);
362+ expect(state.theme.accentText).toBe("color05");
404363 } finally {
405364 state.db.close();
406365 }
src/index.ts+11−84
@@ -1,9 +1,9 @@
11 /**
22 * Entry point for mini-coder.
33 *
4- * Discovers available LLM providers, loads context (AGENTS.md, skills,
5- * plugins), opens the session database, selects a model, and starts
6- * the TUI.
4+ * Discovers available LLM providers, loads prompt context (AGENTS.md,
5+ * skills, and theme), opens the session database, selects a model, and
6+ * starts the TUI.
77 *
88 * @module
99 */
@@ -14,7 +14,6 @@ import { basename, dirname, join } from "node:path";
1414 import { isDeepStrictEqual } from "node:util";
1515 import type {
1616 KnownProvider,
17- Message,
1817 Model,
1918 OAuthCredentials,
2019 ThinkingLevel,
@@ -34,14 +33,6 @@ import {
3433 import { getErrorMessage } from "./errors.ts";
3534 import { type GitState, getGitState } from "./git.ts";
3635 import { canonicalizePath } from "./paths.ts";
37-import {
38- type AgentContext,
39- destroyPlugins,
40- initPlugins,
41- type LoadedPlugin,
42- loadPluginConfig,
43- type PluginEntry,
44-} from "./plugins.ts";
4536 import {
4637 type AgentsMdFile,
4738 buildSystemPrompt,
@@ -52,7 +43,6 @@ import {
5243 appendMessage,
5344 createConversationSnapshot,
5445 createSession,
55- filterModelMessages,
5646 type loadMessages,
5747 openDatabase,
5848 type Session,
@@ -66,7 +56,7 @@ import {
6656 type UserSettings,
6757 } from "./settings.ts";
6858 import { discoverSkills, type Skill } from "./skills.ts";
69-import { DEFAULT_THEME, mergeThemes, type Theme } from "./theme.ts";
59+import { DEFAULT_THEME, type Theme } from "./theme.ts";
7060 import {
7161 createTodoReadToolHandler,
7262 createTodoWriteToolHandler,
@@ -95,9 +85,6 @@ const DATA_DIR = join(homedir(), ".config", "mini-coder");
9585 /** SQLite database path. */
9686 const DB_PATH = join(DATA_DIR, "mini-coder.db");
9787
98-/** Plugin config file path. */
99-const PLUGIN_CONFIG_PATH = join(DATA_DIR, "plugins.json");
100-
10188 /** OAuth credentials file path. */
10289 const AUTH_PATH = join(DATA_DIR, "auth.json");
10390
@@ -370,7 +357,6 @@ function selectModel(
370357 */
371358 function buildTools(
372359 model: Model<string>,
373- plugins: LoadedPlugin[],
374360 messages: AppState["messages"],
375361 ): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
376362 const tools: Tool[] = [
@@ -396,20 +382,6 @@ function buildTools(
396382 toolHandlers.set(readImageTool.name, readImageToolHandler);
397383 }
398384
399- // Add plugin tools
400- for (const plugin of plugins) {
401- if (plugin.result.tools) {
402- for (const tool of plugin.result.tools) {
403- tools.push(tool);
404- }
405- }
406- if (plugin.result.toolHandlers) {
407- for (const [name, handler] of plugin.result.toolHandlers) {
408- toolHandlers.set(name, handler);
409- }
410- }
411- }
412-
413385 return { tools, toolHandlers };
414386 }
415387
@@ -429,21 +401,13 @@ function getSkillScanPaths(cwd: string, gitRoot: string | null): string[] {
429401 ];
430402 }
431403
432-/** Load AGENTS.md files, skills, plugins, git state, and the merged theme. */
433-export async function loadPromptContext(
434- messages: readonly Message[],
435- opts?: {
436- cwd?: string;
437- pluginEntries?: PluginEntry[];
438- pluginConfigPath?: string;
439- },
440-): Promise<{
404+/** Load AGENTS.md files, skills, git state, and the active theme. */
405+export async function loadPromptContext(opts?: { cwd?: string }): Promise<{
441406 cwd: string;
442407 canonicalCwd: string;
443408 git: GitState | null;
444409 agentsMd: AgentsMdFile[];
445410 skills: Skill[];
446- plugins: LoadedPlugin[];
447411 theme: Theme;
448412 }> {
449413 const cwd = opts?.cwd ?? process.cwd();
@@ -459,20 +423,6 @@ export async function loadPromptContext(
459423 );
460424 const agentsMd = discoverAgentsMd(cwd, scanRoot, join(home, ".agents"));
461425 const skills = discoverSkills(getSkillScanPaths(canonicalCwd, gitRoot));
462- const pluginEntries =
463- opts?.pluginEntries ??
464- loadPluginConfig(opts?.pluginConfigPath ?? PLUGIN_CONFIG_PATH);
465- const context: AgentContext = {
466- cwd,
467- messages,
468- dataDir: DATA_DIR,
469- };
470- const plugins = await initPlugins(pluginEntries, context, (entry, err) => {
471- console.error(`Plugin "${entry.name}" failed to init: ${err.message}`);
472- });
473- const themeOverrides = plugins
474- .map((plugin) => plugin.result.theme)
475- .filter((theme): theme is Partial<Theme> => theme != null);
476426
477427 return {
478428 cwd,
@@ -480,8 +430,7 @@ export async function loadPromptContext(
480430 git,
481431 agentsMd,
482432 skills,
483- plugins,
484- theme: mergeThemes(DEFAULT_THEME, ...themeOverrides),
433+ theme: DEFAULT_THEME,
485434 };
486435 }
487436
@@ -490,25 +439,17 @@ export async function reloadPromptContext(
490439 state: AppState,
491440 runtime?: {
492441 loadPromptContext?: typeof loadPromptContext;
493- destroyPlugins?: typeof destroyPlugins;
494442 },
495443 ): Promise<void> {
496444 const loadContext = runtime?.loadPromptContext ?? loadPromptContext;
497- const destroyLoadedPlugins = runtime?.destroyPlugins ?? destroyPlugins;
498- const previousPlugins = state.plugins;
499- const context = await loadContext(filterModelMessages(state.messages));
445+ const context = await loadContext();
500446
501447 state.cwd = context.cwd;
502448 state.canonicalCwd = context.canonicalCwd;
503449 state.git = context.git;
504450 state.agentsMd = context.agentsMd;
505451 state.skills = context.skills;
506- state.plugins = context.plugins;
507452 state.theme = context.theme;
508-
509- await destroyLoadedPlugins(previousPlugins, (entry, err) => {
510- console.error(`Plugin "${entry.name}" failed to destroy: ${err.message}`);
511- });
512453 }
513454
514455 // ---------------------------------------------------------------------------
@@ -535,9 +476,7 @@ export interface AppState {
535476 agentsMd: AgentsMdFile[];
536477 /** Discovered skills. */
537478 skills: Skill[];
538- /** Loaded plugins. */
539- plugins: LoadedPlugin[];
540- /** Active theme (default + plugin overrides). */
479+ /** Active theme. */
541480 theme: Theme;
542481 /** Version label shown in the empty conversation banner. */
543482 versionLabel: string;
@@ -614,12 +553,7 @@ export async function init(): Promise<AppState> {
614553 const db = openDatabase(DB_PATH);
615554 const effort = startup.effort;
616555 const conversation = createConversationSnapshot();
617- const promptContext = await loadPromptContext(
618- filterModelMessages(conversation.messages),
619- {
620- cwd,
621- },
622- );
556+ const promptContext = await loadPromptContext({ cwd });
623557
624558 return {
625559 db,
@@ -631,7 +565,6 @@ export async function init(): Promise<AppState> {
631565 contextTokens: conversation.contextTokens,
632566 agentsMd: promptContext.agentsMd,
633567 skills: promptContext.skills,
634- plugins: promptContext.plugins,
635568 theme: promptContext.theme,
636569 versionLabel: resolveAppVersionLabel(),
637570 git: promptContext.git,
@@ -686,9 +619,6 @@ export function buildPrompt(state: AppState): string {
686619 git: state.git,
687620 agentsMd: state.agentsMd,
688621 skills: state.skills,
689- pluginSuffixes: state.plugins
690- .map((p) => p.result.systemPromptSuffix)
691- .filter((s): s is string => s != null),
692622 });
693623 }
694624
@@ -698,7 +628,7 @@ export function buildToolList(state: AppState): {
698628 toolHandlers: Map<string, ToolHandler>;
699629 } {
700630 if (!state.model) return { tools: [], toolHandlers: new Map() };
701- return buildTools(state.model, state.plugins, state.messages);
631+ return buildTools(state.model, state.messages);
702632 }
703633
704634 /**
@@ -747,9 +677,6 @@ export function getAvailableModels(state: AppState): Model<string>[] {
747677
748678 /** Clean up resources on shutdown. */
749679 export async function shutdown(state: AppState): Promise<void> {
750- await destroyPlugins(state.plugins, (entry, err) => {
751- console.error(`Plugin "${entry.name}" failed to destroy: ${err.message}`);
752- });
753680 state.db.close();
754681 }
755682
src/plugins.test.ts+0−244
@@ -1,244 +0,0 @@
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("parses plugin entries from config file", () => {
48- const config = {
49- plugins: [
50- { name: "test", module: "./test-plugin.ts" },
51- { name: "other", module: "@scope/plugin", config: { key: "value" } },
52- ],
53- };
54- writeFileSync(join(tmp, "plugins.json"), JSON.stringify(config));
55-
56- const entries = loadPluginConfig(join(tmp, "plugins.json"));
57- expect(entries).toHaveLength(2);
58- expect(entries[0]!.name).toBe("test");
59- expect(entries[1]!.config).toEqual({ key: "value" });
60- });
61-});
62-
63-// ---------------------------------------------------------------------------
64-// initPlugins
65-// ---------------------------------------------------------------------------
66-
67-describe("initPlugins", () => {
68- test("loads and initializes a plugin module", async () => {
69- const modulePath = writePlugin(
70- "good-plugin",
71- `
72- export const name = "good";
73- export const description = "A good plugin";
74- export async function init(agent, config) {
75- return { systemPromptSuffix: "Plugin context: good" };
76- }
77- `,
78- );
79-
80- const entries: PluginEntry[] = [{ name: "good", module: modulePath }];
81-
82- const loaded = await initPlugins(entries, makeContext());
83- expect(loaded).toHaveLength(1);
84- expect(loaded[0]!.result.systemPromptSuffix).toContain("good");
85- });
86-
87- test("passes config to plugin init", async () => {
88- const modulePath = writePlugin(
89- "config-plugin",
90- `
91- export const name = "configurable";
92- export const description = "Reads config";
93- export async function init(agent, config) {
94- return { systemPromptSuffix: "key=" + config?.key };
95- }
96- `,
97- );
98-
99- const entries: PluginEntry[] = [
100- { name: "configurable", module: modulePath, config: { key: "hello" } },
101- ];
102-
103- const loaded = await initPlugins(entries, makeContext());
104- expect(loaded[0]!.result.systemPromptSuffix).toContain("hello");
105- });
106-
107- test("skips plugins that fail to load and reports error", async () => {
108- const entries: PluginEntry[] = [
109- { name: "missing", module: join(tmp, "does-not-exist.ts") },
110- ];
111-
112- const errors: Array<{ name: string; error: Error }> = [];
113- const loaded = await initPlugins(entries, makeContext(), (entry, error) => {
114- errors.push({ name: entry.name, error });
115- });
116-
117- expect(loaded).toHaveLength(0);
118- expect(errors).toHaveLength(1);
119- expect(errors[0]!.name).toBe("missing");
120- });
121-
122- test("skips plugins that fail during init and reports error", async () => {
123- const modulePath = writePlugin(
124- "bad-init",
125- `
126- export const name = "bad";
127- export const description = "Fails on init";
128- export async function init() {
129- throw new Error("init exploded");
130- }
131- `,
132- );
133-
134- const entries: PluginEntry[] = [{ name: "bad", module: modulePath }];
135-
136- const errors: Array<{ name: string; message: string }> = [];
137- const loaded = await initPlugins(entries, makeContext(), (entry, error) => {
138- errors.push({ name: entry.name, message: error.message });
139- });
140-
141- expect(loaded).toHaveLength(0);
142- expect(errors).toHaveLength(1);
143- expect(errors[0]!.message).toContain("init exploded");
144- });
145-
146- test("collects tools from plugin results", async () => {
147- const modulePath = writePlugin(
148- "tool-plugin",
149- `
150- export const name = "tools";
151- export const description = "Provides tools";
152- export async function init() {
153- return {
154- tools: [{
155- name: "custom_tool",
156- description: "A custom tool",
157- parameters: { type: "object", properties: {} },
158- }],
159- };
160- }
161- `,
162- );
163-
164- const entries: PluginEntry[] = [{ name: "tools", module: modulePath }];
165-
166- const loaded = await initPlugins(entries, makeContext());
167- expect(loaded[0]!.result.tools).toHaveLength(1);
168- expect(loaded[0]!.result.tools![0]!.name).toBe("custom_tool");
169- });
170-});
171-
172-// ---------------------------------------------------------------------------
173-// destroyPlugins
174-// ---------------------------------------------------------------------------
175-
176-describe("destroyPlugins", () => {
177- test("calls destroy on plugins that implement it", async () => {
178- // Use a file as a side-effect marker
179- const markerPath = join(tmp, "destroyed.txt");
180- const modulePath = writePlugin(
181- "destroyable",
182- `
183- import { writeFileSync } from "node:fs";
184- export const name = "destroyable";
185- export const description = "Has destroy";
186- export async function init() { return {}; }
187- export async function destroy() {
188- writeFileSync("${markerPath}", "destroyed");
189- }
190- `,
191- );
192-
193- const entries: PluginEntry[] = [
194- { name: "destroyable", module: modulePath },
195- ];
196-
197- const loaded = await initPlugins(entries, makeContext());
198- await destroyPlugins(loaded);
199-
200- const { existsSync } = await import("node:fs");
201- expect(existsSync(markerPath)).toBe(true);
202- });
203-
204- test("reports destroy errors without stopping other plugins", async () => {
205- const marker1 = join(tmp, "d1.txt");
206- const mod1 = writePlugin(
207- "p1",
208- `
209- export const name = "p1";
210- export const description = "Fails destroy";
211- export async function init() { return {}; }
212- export async function destroy() { throw new Error("destroy failed"); }
213- `,
214- );
215- const mod2 = writePlugin(
216- "p2",
217- `
218- import { writeFileSync } from "node:fs";
219- export const name = "p2";
220- export const description = "Good destroy";
221- export async function init() { return {}; }
222- export async function destroy() { writeFileSync("${marker1}", "ok"); }
223- `,
224- );
225-
226- const entries: PluginEntry[] = [
227- { name: "p1", module: mod1 },
228- { name: "p2", module: mod2 },
229- ];
230-
231- const loaded = await initPlugins(entries, makeContext());
232-
233- const errors: string[] = [];
234- await destroyPlugins(loaded, (entry, error) => {
235- errors.push(`${entry.name}: ${error.message}`);
236- });
237-
238- // p1 failed but p2 still ran
239- expect(errors).toHaveLength(1);
240- expect(errors[0]).toContain("p1");
241- const { existsSync } = await import("node:fs");
242- expect(existsSync(marker1)).toBe(true);
243- });
244-});
src/plugins.ts+0−183
@@ -1,183 +0,0 @@
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.
8- *
9- * @module
10- */
11-
12-import { existsSync, readFileSync } from "node:fs";
13-import { resolve } from "node:path";
14-import type { Message, Tool } from "@mariozechner/pi-ai";
15-import type { ToolHandler } from "./agent.ts";
16-import type { Theme } from "./theme.ts";
17-
18-// ---------------------------------------------------------------------------
19-// Types
20-// ---------------------------------------------------------------------------
21-
22-/**
23- * Context provided to plugins during initialization.
24- *
25- * Gives plugins read-only access to the agent's environment without
26- * exposing internal implementation details.
27- */
28-export interface AgentContext {
29- /** The working directory. */
30- cwd: string;
31- /** Read-only access to the current session's messages. */
32- messages: readonly Message[];
33- /** The app data directory (`~/.config/mini-coder/`). */
34- dataDir: string;
35-}
36-
37-/**
38- * Result returned by a plugin's `init` function.
39- *
40- * Contains any additional tools the agent should register and/or
41- * context to append to the system prompt.
42- */
43-export interface PluginResult {
44- /** Additional tool definitions to register with the model. */
45- tools?: Tool[];
46- /** Tool name → handler map for the tools above. */
47- toolHandlers?: Map<string, ToolHandler>;
48- /** Additional context to append to the system prompt. */
49- systemPromptSuffix?: string;
50- /** Partial theme override — merged on top of the default theme. */
51- theme?: Partial<Theme>;
52-}
53-
54-/**
55- * The interface a plugin module must implement.
56- *
57- * A plugin is a module that exports a conforming object. It is loaded
58- * dynamically from a path or package name declared in the config file.
59- */
60-export interface Plugin {
61- /** Human-readable plugin name. */
62- name: string;
63- /** Brief description of what the plugin provides. */
64- description: string;
65- /** Called once at startup. Returns tools to register and/or context to add. */
66- init(
67- agent: AgentContext,
68- config?: Record<string, unknown>,
69- ): Promise<PluginResult>;
70- /** Called on shutdown for cleanup. */
71- destroy?(): Promise<void>;
72-}
73-
74-/** A single entry in the plugins config file. */
75-export interface PluginEntry {
76- /** Plugin name (for display and error messages). */
77- name: string;
78- /** Module path or package name to import. */
79- module: string;
80- /** Optional configuration passed to the plugin's `init`. */
81- config?: Record<string, unknown>;
82-}
83-
84-/** A loaded and initialized plugin with its result. */
85-export interface LoadedPlugin {
86- /** The plugin entry from config. */
Cut short: this commit's diff is over 1000 lines.
src/prompt.ts+2−12
Cut short: this commit's diff is over 1000 lines.
src/theme.ts+2−3
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+0−1
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+0−1
Cut short: this commit's diff is over 1000 lines.
src/ui/help.ts+0−9
Cut short: this commit's diff is over 1000 lines.