xonecas.io
64875
Mc

mini-coder / commit 6a818fa

refactor: address code quality issues — dead code, inline imports, memoization

- Extract parseFrontmatter into shared src/cli/frontmatter.ts; remove
  duplicate copies from agents.ts, custom-commands.ts, and skills.ts
- Extract tildePath() helper into output.ts; remove duplicate cwdDisplay
  expressions in agent.ts (×2) and manager.ts
- Replace all inline import() type calls with top-level import type
  statements (turn.ts, types.ts, agents.ts, commands.ts, output.ts)
- Remove dead exports: userMessage (turn.ts), saveMessage singular (db.ts),
  updateSessionTitle and deleteSession (db.ts)
- Remove unused types from types.ts: ProviderConfig, MessageRole, and
  related message content types; drop now-unused LanguageModel import
- Remove unused imports: availableProviders (commands.ts), relative and
  PREFIX (manager.ts)
- Memoize zenGoogle() provider instance to match all other zen providers
- Remove dead eslint-disable comments from mcp/client.ts (project uses Biome)
- Fix unnecessary regex escaping of double-quotes in custom-commands.ts

Sean2026-02-25 6a818fa025b2cf85ad1a64ce4e42021e4a4cb2ad parent 8634a95

16 files changed

TODO.md+1−11
@@ -1,18 +1,8 @@
11 # TODO
22
3-## Refencing custom subagents with `@` has poor UX
4-
5-- The main agent has no clue a subagent was called.
6-- When the subagent completes, the main agents just gets the result with
7-no context or relation to the user message that triggered it.
8-- This is poorly implemented and does not match how Claude Code or Opencode's custom agents work, leading to breaking on of the core premises of mini-coder: no weird setup or different standards...
9-
10-Write a plan to implement the feature properly, use opencode as the reference
11-implementation to ensure we are compatible with their custom agents.
12-
133 ## Subagents don't have access to MCP tools?
144
15-Investigate if subagents are able to see the mcp tools.
5+Investigate if subagents are able to see the mcp tools. The user reported that after adding the exa mcp tools, that the subagents claimed to not be able to search online, but the main agent could.
166
177 ## Investigate missing output?
188
code-quality-issues.md+135−0
@@ -0,0 +1,135 @@
1+# Code Quality Issues
2+
3+## 1. 🔴 Duplicate Code — `parseFrontmatter` tripled across modules
4+
5+`parseFrontmatter` (including its `Frontmatter` interface, `FM_RE` regex and YAML key-parsing loop) is **copy-pasted verbatim** in three files:
6+
7+- `src/cli/agents.ts` (lines 20–45)
8+- `src/cli/custom-commands.ts` (lines 20–45)
9+- `src/cli/skills.ts` has a partial version `parseSkillMeta` that reads `name` and `description` from the same format.
10+
11+The agents and custom-commands versions are byte-for-byte identical — same regex, same loop, same trim/strip-quotes, same `description`/`model` key handling. The only difference is the struct they populate. Fix: extract into a shared `src/cli/frontmatter.ts` utility and import it in all three.
12+
13+---
14+
15+## 2. 🔴 Duplicate Code — `loadFromDir` pattern tripled
16+
17+The `loadFromDir` function in `agents.ts` and `custom-commands.ts` is essentially the same skeleton: `existsSync` check → `readdirSync` → `.endsWith(".md")` filter → `readFileSync` → `parseFrontmatter` → `Map.set`. The `loadSkills` version differs only in that it looks for `SKILL.md` inside subdirectories instead of `.md` flat files, but the rest of the structure is the same. Same for the public `loadXxx(cwd)` function: three identical "merge global + local, local wins" patterns.
18+
19+---
20+
21+## 3. 🔴 Duplicate Code — `homedir()`-based `cwdDisplay` computed in two places in `agent.ts`
22+
23+```ts
24+// buildSystemPrompt (line 98-100)
25+const cwdDisplay = cwd.startsWith(homedir())
26+ ? `~${cwd.slice(homedir().length)}`
27+ : cwd;
28+
29+// renderStatusBarForSession (line 646-648)
30+const cwdDisplay = cwd.startsWith(homedir())
31+ ? `~${cwd.slice(homedir().length)}`
32+ : cwd;
33+```
34+
35+Also duplicated in `session/manager.ts` (line 53–55) and `cli/output.ts` already has `HOME = homedir()` cached at the top. This pattern should be a small helper function, e.g. `tildePath(p: string): string`.
36+
37+---
38+
39+## 4. 🔴 Inlined `import()` calls — violates project rule
40+
41+The rule says **"Do not inline `import` calls"**. There are 12 occurrences of dynamic inline type imports:
42+
43+- `src/agent/agent.ts` lines 197, 224, 673 — `import("../tools/subagent.ts").SubagentOutput`, `SubagentToolEntry`, `CoreMessage`
44+- `src/agent/tools.ts` line 104 — `import("../tools/subagent.ts").SubagentOutput`
45+- `src/cli/commands.ts` line 44 — `import("../tools/subagent.ts").SubagentOutput`
46+- `src/cli/output.ts` lines 332, 342, 512, 579, 597 — `SubagentToolEntry`, `SubagentOutput`, `CoreMessage`
47+- `src/llm-api/types.ts` line 81 — `import("../llm-api/turn.ts").CoreMessage`
48+- `src/llm-api/turn.ts` line 32 — `import("ai").FlexibleSchema<unknown>`
49+
50+All of these should be top-level `import type` statements.
51+
52+---
53+
54+## 5. 🟡 Dead code — `userMessage` in `turn.ts` is never called
55+
56+`src/llm-api/turn.ts` line 185 exports `userMessage(text: string): CoreMessage`. It is never imported or called anywhere in the codebase. It should be removed.
57+
58+---
59+
60+## 6. 🟡 Dead code — `availableProviders` imported but never used
61+
62+`src/cli/commands.ts` imports `availableProviders` from `providers.ts` (line 3) but it is never referenced anywhere in that file (only `fetchAvailableModels` is used). This is an unused import.
63+
64+---
65+
66+## 7. 🟡 Dead code — `saveMessage` (singular) exported but never used
67+
68+`src/session/db.ts` exports `saveMessage` (single-message variant, line 191). The entire codebase always calls `saveMessages` (plural). `saveMessage` has no callers and should be removed.
69+
70+---
71+
72+## 8. 🟡 Dead code — `updateSessionTitle` and `deleteSession` exported but never called
73+
74+`src/session/db.ts` exports `updateSessionTitle` (line 161) and `deleteSession` (line 185). Neither appears in any other file. They may be future API surface, but currently they are dead exports.
75+
76+---
77+
78+## 9. 🟡 Dead code — most of `src/llm-api/types.ts` is orphaned
79+
80+`ProviderConfig`, `MessageRole`, `TextContent`, `ToolCallContent`, `ToolResultContent`, `MessageContent`, and `Message` are all defined and exported in `types.ts` but **never imported anywhere**. The codebase uses `CoreMessage` from `turn.ts` directly for all message handling. The only things from `types.ts` that are actually used are `ToolDef` and the `TurnEvent` family. The unused types should be removed.
81+
82+---
83+
84+## 10. 🟡 Unused import — `relative` in `session/manager.ts`
85+
86+`src/session/manager.ts` line 2 imports `relative` from `"node:path"` but it is never used anywhere in the file.
87+
88+---
89+
90+## 11. 🟡 Unused import — `PREFIX` in `session/manager.ts`
91+
92+`src/session/manager.ts` line 4 imports `PREFIX` from `"../cli/output.ts"` but it is not used anywhere in the file (only `writeln` and `c` from `yoctocolors` are used in `printSessionList`).
93+
94+---
95+
96+## 12. 🟡 Bug-prone — `zenGoogle` ignores its parameter and recreates provider on each call
97+
98+`providers.ts` line 78: `zenGoogle(modelId: string)` takes `modelId` but only uses it to pass to `createGoogleGenerativeAI` (which doesn't use it — the model ID is passed to the returned function). Also unlike the other zen providers, `zenGoogle` doesn't memoize — it creates a new `createGoogleGenerativeAI` instance on every call. This is inconsistent and wasteful.
99+
100+---
101+
102+## 13. 🟡 Minor — double `homedir()` call per `cwdDisplay` computation
103+
104+In `buildSystemPrompt` and `renderStatusBarForSession` (agent.ts), `homedir()` is called twice inline:
105+```ts
106+cwd.startsWith(homedir()) ? `~${cwd.slice(homedir().length)}` : cwd
107+```
108+`homedir()` is cheap but its result is constant — it should be captured once (as `output.ts` already does with `const HOME = homedir()`).
109+
110+---
111+
112+## 14. 🟢 Style — `eslint-disable` comments in `mcp/client.ts`
113+
114+Lines 81 and 88 in `mcp/client.ts` contain `// eslint-disable-next-line @typescript-eslint/no-explicit-any` comments. The project uses Biome, not ESLint — these comments are dead noise and have no effect. They should be removed.
115+
116+---
117+
118+## Summary
119+
120+| # | Severity | File(s) | Issue |
121+|---|---|---|---|
122+| 1 | 🔴 | `agents.ts`, `custom-commands.ts`, `skills.ts` | `parseFrontmatter` duplicated 3× |
123+| 2 | 🔴 | same 3 files | `loadFromDir` + merge pattern duplicated 3× |
124+| 3 | 🔴 | `agent.ts` (×2), `manager.ts` | `cwdDisplay` tilde logic duplicated |
125+| 4 | 🔴 | 6 files (12 occurrences) | Inlined `import()` type calls — project rule violation |
126+| 5 | 🟡 | `turn.ts` | `userMessage` exported but never used |
127+| 6 | 🟡 | `commands.ts` | `availableProviders` imported but never used |
128+| 7 | 🟡 | `db.ts` | `saveMessage` (singular) exported but never called |
129+| 8 | 🟡 | `db.ts` | `updateSessionTitle`, `deleteSession` — dead exports |
130+| 9 | 🟡 | `types.ts` | `ProviderConfig`, `Message`, `MessageRole`, etc. — never imported |
131+| 10 | 🟡 | `manager.ts` | `relative` imported but not used |
132+| 11 | 🟡 | `manager.ts` | `PREFIX` imported but not used |
133+| 12 | 🟡 | `providers.ts` | `zenGoogle` doesn't memoize, ignores its parameter |
134+| 13 | 🟡 | `agent.ts` | `homedir()` called twice per expression |
135+| 14 | 🟢 | `mcp/client.ts` | Dead `eslint-disable` comments (project uses Biome) |
src/agent/agent.ts+8−14
@@ -1,5 +1,4 @@
11 import { existsSync, readFileSync } from "node:fs";
2-import { homedir } from "node:os";
32 import { join } from "node:path";
43 import * as c from "yoctocolors";
54 import { loadAgents } from "../cli/agents.ts";
@@ -10,8 +9,6 @@ import {
109 loadImageFile,
1110 } from "../cli/image-types.ts";
1211 import { readline, type InputResult } from "../cli/input.ts";
13-import { loadSkills } from "../cli/skills.ts";
14-
1512 import {
1613 PREFIX,
1714 Spinner,
@@ -21,8 +18,10 @@ import {
2118 renderStatusBar,
2219 renderTurn,
2320 restoreTerminal,
21+ tildePath,
2422 writeln,
2523 } from "../cli/output.ts";
24+import { loadSkills } from "../cli/skills.ts";
2625
2726 import { getContextWindow, resolveModel } from "../llm-api/providers.ts";
2827 import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
@@ -33,6 +32,7 @@ import {
3332 restoreSnapshot,
3433 takeSnapshot,
3534 } from "../tools/snapshot.ts";
35+import type { SubagentOutput, SubagentToolEntry } from "../tools/subagent.ts";
3636
3737 import {
3838 deleteAllSnapshots,
@@ -95,9 +95,7 @@ function loadContextFile(cwd: string): string | null {
9595
9696 function buildSystemPrompt(cwd: string): string {
9797 const contextFile = loadContextFile(cwd);
98- const cwdDisplay = cwd.startsWith(homedir())
99- ? `~${cwd.slice(homedir().length)}`
100- : cwd;
98+ const cwdDisplay = tildePath(cwd);
10199 const now = new Date().toLocaleString(undefined, { hour12: false });
102100
103101 let prompt = `You are mini-coder, a small and fast CLI coding agent.
@@ -194,7 +192,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
194192 depth = 0,
195193 agentName?: string,
196194 modelOverride?: string,
197- ): Promise<import("../tools/subagent.ts").SubagentOutput> => {
195+ ): Promise<SubagentOutput> => {
198196 // Resolve custom agent config if an agentName was specified
199197 const allAgents = loadAgents(cwd);
200198 const agentConfig = agentName ? allAgents.get(agentName) : undefined;
@@ -221,7 +219,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
221219 let result = "";
222220 let inputTokens = 0;
223221 let outputTokens = 0;
224- const activity: import("../tools/subagent.ts").SubagentToolEntry[] = [];
222+ const activity: SubagentToolEntry[] = [];
225223
226224 // Track pending tool call so we can pair it with its result
227225 const pendingCalls = new Map<string, { toolName: string; args: unknown }>();
@@ -643,9 +641,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
643641 const branch = await getGitBranch(cwd);
644642 const provider = currentModel.split("/")[0] ?? "";
645643 const modelShort = currentModel.split("/").slice(1).join("/");
646- const cwdDisplay = cwd.startsWith(homedir())
647- ? `~${cwd.slice(homedir().length)}`
648- : cwd;
644+ const cwdDisplay = tildePath(cwd);
649645
650646 renderStatusBar({
651647 model: modelShort,
@@ -669,9 +665,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
669665 * Scans every assistant message (not just the last) so that a trailing tool
670666 * call doesn't mask a `/ralph` signal that appeared in earlier text.
671667 */
672-export function extractAssistantText(
673- newMessages: import("../llm-api/turn.ts").CoreMessage[],
674-): string {
668+export function extractAssistantText(newMessages: CoreMessage[]): string {
675669 const parts: string[] = [];
676670 for (const msg of newMessages) {
677671 if (msg.role !== "assistant") continue;
src/agent/tools.ts+3−1
@@ -1,4 +1,6 @@
11 import type { ToolDef } from "../llm-api/types.ts";
2+import type { SubagentOutput } from "../tools/subagent.ts";
3+
24 import type { CreateOutput } from "../tools/create.ts";
35 import { createTool } from "../tools/create.ts";
46 import type { GlobOutput } from "../tools/glob.ts";
@@ -101,7 +103,7 @@ export function buildToolSet(opts: {
101103 prompt: string,
102104 depth?: number,
103105 agentName?: string,
104- ) => Promise<import("../tools/subagent.ts").SubagentOutput>;
106+ ) => Promise<SubagentOutput>;
105107
106108 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
107109 availableAgents: ReadonlyMap<string, { description: string }>;
src/cli/agents.ts+1−29
@@ -1,6 +1,7 @@
11 import { existsSync, readFileSync, readdirSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { basename, join } from "node:path";
4+import { parseFrontmatter } from "./frontmatter.ts";
45
56 // ─── Types ────────────────────────────────────────────────────────────────────
67
@@ -15,35 +16,6 @@ export interface AgentConfig {
1516 source: "global" | "local";
1617 }
1718
18-// ─── Frontmatter parser ───────────────────────────────────────────────────────
19-
20-interface Frontmatter {
21- description?: string;
22- model?: string;
23-}
24-
25-function parseFrontmatter(raw: string): { meta: Frontmatter; body: string } {
26- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
27- const m = raw.match(FM_RE);
28- if (!m) return { meta: {}, body: raw };
29-
30- const meta: Frontmatter = {};
31- const yamlBlock = m[1] ?? "";
32- for (const line of yamlBlock.split("\n")) {
33- const colon = line.indexOf(":");
34- if (colon === -1) continue;
35- const key = line.slice(0, colon).trim();
36- const val = line
37- .slice(colon + 1)
38- .trim()
39- .replace(/^["']|["']$/g, "");
40- if (key === "description") meta.description = val;
41- if (key === "model") meta.model = val;
42- }
43-
44- return { meta, body: (m[2] ?? "").trim() };
45-}
46-
4719 // ─── Load agents from a directory ─────────────────────────────────────────────
4820
4921 function loadFromDir(
src/cli/commands.ts+4−8
@@ -1,8 +1,7 @@
11 import * as c from "yoctocolors";
2-import {
3- availableProviders,
4- fetchAvailableModels,
5-} from "../llm-api/providers.ts";
2+import { fetchAvailableModels } from "../llm-api/providers.ts";
3+import type { SubagentOutput } from "../tools/subagent.ts";
4+
65 import {
76 deleteMcpServer,
87 listMcpServers,
@@ -38,10 +37,7 @@ export interface CommandContext {
3837 startNewSession: () => void;
3938
4039 connectMcpServer: (name: string) => Promise<void>;
41- runSubagent: (
42- prompt: string,
43- model?: string,
44- ) => Promise<import("../tools/subagent.ts").SubagentOutput>;
40+ runSubagent: (prompt: string, model?: string) => Promise<SubagentOutput>;
4541
4642 cwd: string;
4743 }
src/cli/custom-commands.ts+2−29
@@ -1,6 +1,7 @@
11 import { existsSync, readFileSync, readdirSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { basename, join } from "node:path";
4+import { parseFrontmatter } from "./frontmatter.ts";
45
56 // ─── Types ────────────────────────────────────────────────────────────────────
67
@@ -15,35 +16,6 @@ export interface CustomCommand {
1516 source: "global" | "local";
1617 }
1718
18-// ─── Frontmatter parser ───────────────────────────────────────────────────────
19-
20-interface Frontmatter {
21- description?: string;
22- model?: string;
23-}
24-
25-function parseFrontmatter(raw: string): { meta: Frontmatter; body: string } {
26- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
27- const m = raw.match(FM_RE);
28- if (!m) return { meta: {}, body: raw };
29-
30- const meta: Frontmatter = {};
31- const yamlBlock = m[1] ?? "";
32- for (const line of yamlBlock.split("\n")) {
33- const colon = line.indexOf(":");
34- if (colon === -1) continue;
35- const key = line.slice(0, colon).trim();
36- const val = line
37- .slice(colon + 1)
38- .trim()
39- .replace(/^["']|["']$/g, "");
40- if (key === "description") meta.description = val;
41- if (key === "model") meta.model = val;
42- }
43-
44- return { meta, body: (m[2] ?? "").trim() };
45-}
46-
4719 // ─── Load commands from a directory ──────────────────────────────────────────
4820
4921 function loadFromDir(
@@ -111,6 +83,7 @@ export async function expandTemplate(
11183 const tokens =
11284 args
11385 .match(/("([^"]*)")|('([^']*)')|(\S+)/g)
86+
11487 ?.map((t) => t.replace(/^["']|["']$/g, "")) ?? [];
11588
11689 // Replace positional $1 … $9
src/cli/frontmatter.ts+34−0
@@ -0,0 +1,34 @@
1+// ─── Frontmatter parser ───────────────────────────────────────────────────────
2+
3+export interface Frontmatter {
4+ description?: string;
5+ model?: string;
6+ name?: string;
7+}
8+
9+const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
10+
11+export function parseFrontmatter(raw: string): {
12+ meta: Frontmatter;
13+ body: string;
14+} {
15+ const m = raw.match(FM_RE);
16+ if (!m) return { meta: {}, body: raw };
17+
18+ const meta: Frontmatter = {};
19+ const yamlBlock = m[1] ?? "";
20+ for (const line of yamlBlock.split("\n")) {
21+ const colon = line.indexOf(":");
22+ if (colon === -1) continue;
23+ const key = line.slice(0, colon).trim();
24+ const val = line
25+ .slice(colon + 1)
26+ .trim()
27+ .replace(/^["']|["']$/g, "");
28+ if (key === "name") meta.name = val;
29+ if (key === "description") meta.description = val;
30+ if (key === "model") meta.model = val;
31+ }
32+
33+ return { meta, body: (m[2] ?? "").trim() };
34+}
src/cli/output.ts+13−5
@@ -1,7 +1,9 @@
11 import { homedir } from "node:os";
22
33 import * as c from "yoctocolors";
4+import type { CoreMessage } from "../llm-api/turn.ts";
45 import type { TurnEvent } from "../llm-api/types.ts";
6+import type { SubagentOutput, SubagentToolEntry } from "../tools/subagent.ts";
57 import { renderChunk } from "./markdown.ts";
68
79 const HOME = homedir();
@@ -9,6 +11,11 @@ declare const __PACKAGE_VERSION__: string;
911 const PACKAGE_VERSION =
1012 typeof __PACKAGE_VERSION__ !== "undefined" ? __PACKAGE_VERSION__ : "unknown";
1113
14+/** Replace the home directory prefix with `~` for display. */
15+export function tildePath(p: string): string {
16+ return p.startsWith(HOME) ? `~${p.slice(HOME.length)}` : p;
17+}
18+
1219 // ─── Terminal restore ─────────────────────────────────────────────────────────
1320
1421 export function restoreTerminal(): void {
@@ -329,7 +336,8 @@ function renderToolResultInline(
329336
330337 /** Render a subagent's activity tree, indented under its parent tool-call line. */
331338 export function renderSubagentActivity(
332- activity: import("../tools/subagent.ts").SubagentToolEntry[],
339+ activity: SubagentToolEntry[],
340+
333341 indent: string,
334342 maxDepth: number,
335343 ): void {
@@ -339,7 +347,7 @@ export function renderSubagentActivity(
339347 // For nested subagents, recurse one more level (capped at maxDepth)
340348 if (entry.toolName === "subagent" && maxDepth > 0) {
341349 const nested = entry.result as {
342- activity?: import("../tools/subagent.ts").SubagentToolEntry[];
350+ activity?: SubagentToolEntry[];
343351 };
344352 if (nested?.activity?.length) {
345353 renderSubagentActivity(nested.activity, `${indent} `, maxDepth - 1);
@@ -509,7 +517,7 @@ export function renderToolResult(
509517 }
510518
511519 if (toolName === "subagent") {
512- const r = result as import("../tools/subagent.ts").SubagentOutput;
520+ const r = result as SubagentOutput;
513521
514522 // Render the tool call tree before showing the result text
515523 if (r.activity?.length) {
@@ -576,7 +584,7 @@ export async function renderTurn(
576584 inputTokens: number;
577585 outputTokens: number;
578586 contextTokens: number;
579- newMessages: import("../llm-api/turn.ts").CoreMessage[];
587+ newMessages: CoreMessage[];
580588 }> {
581589 let inText = false;
582590 // Unprocessed raw text — only the portion from the last flush boundary
@@ -594,7 +602,7 @@ export async function renderTurn(
594602 let inputTokens = 0;
595603 let outputTokens = 0;
596604 let contextTokens = 0;
597- let newMessages: import("../llm-api/turn.ts").CoreMessage[] = [];
605+ let newMessages: CoreMessage[] = [];
598606
599607 // Append rendered ANSI text to the print queue and start the ticker if
600608 // it is not already running.
src/cli/skills.ts+2−23
@@ -1,6 +1,7 @@
11 import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
4+import { parseFrontmatter } from "./frontmatter.ts";
45
56 // ─── Types ────────────────────────────────────────────────────────────────────
67
@@ -13,28 +14,6 @@ export interface Skill {
1314 source: "global" | "local";
1415 }
1516
16-// ─── Frontmatter parser (name + description only) ────────────────────────────
17-
18-function parseSkillMeta(raw: string): { name?: string; description?: string } {
19- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
20- const m = raw.match(FM_RE);
21- if (!m) return {};
22-
23- const meta: { name?: string; description?: string } = {};
24- for (const line of (m[1] ?? "").split("\n")) {
25- const colon = line.indexOf(":");
26- if (colon === -1) continue;
27- const key = line.slice(0, colon).trim();
28- const val = line
29- .slice(colon + 1)
30- .trim()
31- .replace(/^["']|["']$/g, "");
32- if (key === "name") meta.name = val;
33- if (key === "description") meta.description = val;
34- }
35- return meta;
36-}
37-
3817 // ─── Load skills from a skills root dir ──────────────────────────────────────
3918 // Each skill lives at <dir>/<skill-name>/SKILL.md
4019
@@ -58,7 +37,7 @@ function loadFromDir(
5837 if (!statSync(join(dir, entry)).isDirectory()) continue;
5938 if (!existsSync(skillFile)) continue;
6039 const content = readFileSync(skillFile, "utf-8");
61- const meta = parseSkillMeta(content);
40+ const { meta } = parseFrontmatter(content);
6241 const name = meta.name ?? entry;
6342 skills.set(name, {
6443 name,
src/llm-api/providers.ts+12−7
@@ -45,6 +45,8 @@ const ZEN_GOOGLE_MODELS = new Set([
4545
4646 let _zenAnthropic: ReturnType<typeof createAnthropic> | null = null;
4747 let _zenOpenAI: ReturnType<typeof createOpenAI> | null = null;
48+let _zenGoogle: ReturnType<typeof createGoogleGenerativeAI> | null = null;
49+
4850 let _zenCompat: ReturnType<typeof createOpenAICompatible> | null = null;
4951
5052 function getZenApiKey(): string {
@@ -75,12 +77,15 @@ function zenOpenAI() {
7577 return _zenOpenAI;
7678 }
7779
78-function zenGoogle(modelId: string) {
79- // @ai-sdk/google constructs its own path; we pass the base up to /models
80- return createGoogleGenerativeAI({
81- apiKey: getZenApiKey(),
82- baseURL: ZEN_BASE,
83- });
80+function zenGoogle() {
81+ if (!_zenGoogle) {
82+ // @ai-sdk/google constructs its own path; we pass the base up to /models
83+ _zenGoogle = createGoogleGenerativeAI({
84+ apiKey: getZenApiKey(),
85+ baseURL: ZEN_BASE,
86+ });
87+ }
88+ return _zenGoogle;
8489 }
8590
8691 function zenCompat() {
@@ -201,7 +206,7 @@ export function resolveModel(modelString: string): LanguageModel {
201206 return zenOpenAI()(modelId);
202207 }
203208 if (ZEN_GOOGLE_MODELS.has(modelId)) {
204- return zenGoogle(modelId)(modelId);
209+ return zenGoogle()(modelId);
205210 }
206211 // Fallback: assume OpenAI-compatible (MiniMax, GLM, Kimi, Qwen, etc.)
207212 return zenCompat()(modelId);
src/llm-api/turn.ts+2−8
@@ -1,5 +1,5 @@
11 import { dynamicTool, jsonSchema, stepCountIs, streamText } from "ai";
2-import type { StepResult } from "ai";
2+import type { FlexibleSchema, StepResult } from "ai";
33 import { z } from "zod";
44 import type { ToolDef, TurnEvent } from "./types.ts";
55
@@ -29,7 +29,7 @@ function toCoreTool(def: ToolDef): ReturnType<typeof dynamicTool> {
2929 // MCP tools pass raw JSON Schema objects; the AI SDK requires them to be
3030 // wrapped with jsonSchema(). Zod schemas are passed through as-is.
3131 const schema = isZodSchema(def.schema)
32- ? (def.schema as import("ai").FlexibleSchema<unknown>)
32+ ? (def.schema as FlexibleSchema<unknown>)
3333 : jsonSchema(def.schema);
3434 return dynamicTool({
3535 description: def.description,
@@ -180,10 +180,4 @@ export async function* runTurn(options: {
180180 }
181181 }
182182
183-// ─── Message builder helpers ──────────────────────────────────────────────────
184-
185-export function userMessage(text: string): CoreMessage {
186- return { role: "user", content: text };
187-}
188-
189183 export { z };
src/llm-api/types.ts+2−46
@@ -1,48 +1,4 @@
1-import type { LanguageModel } from "ai";
2-
3-// ─── Provider config ──────────────────────────────────────────────────────────
4-
5-export interface ProviderConfig {
6- /** Human-readable label shown in the status bar */
7- label: string;
8- /** The resolved AI SDK language model */
9- model: LanguageModel;
10-}
11-
12-// ─── Messages ─────────────────────────────────────────────────────────────────
13-
14-export type MessageRole = "user" | "assistant" | "tool";
15-
16-export interface TextContent {
17- type: "text";
18- text: string;
19-}
20-
21-export interface ToolCallContent {
22- type: "tool-call";
23- toolCallId: string;
24- toolName: string;
25- args: unknown;
26-}
27-
28-export interface ToolResultContent {
29- type: "tool-result";
30- toolCallId: string;
31- toolName: string;
32- result: unknown;
33- isError?: boolean;
34-}
35-
36-export type MessageContent =
37- | TextContent
38- | ToolCallContent
39- | ToolResultContent
40- | string;
41-
42-export interface Message {
43- role: MessageRole;
44- content: MessageContent | MessageContent[];
45-}
1+import type { CoreMessage } from "./turn.ts";
462
473 // ─── Turn events (streamed to the caller) ─────────────────────────────────────
484
@@ -78,7 +34,7 @@ export interface TurnCompleteEvent {
7834 * do NOT convert them through the internal Message type or they will
7935 * lose `input`/`output` field fidelity and fail schema validation.
8036 */
81- messages: import("../llm-api/turn.ts").CoreMessage[];
37+ messages: CoreMessage[];
8238 }
8339
8440 export interface TurnErrorEvent {
src/mcp/client.ts+0−2
@@ -78,14 +78,12 @@ export async function connectMcpServer(
7878 // Use the server's declared JSON schema directly
7979 schema: t.inputSchema,
8080 execute: async (input: unknown) => {
81- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8281 const result = (await client.callTool({
8382 name: t.name,
8483 arguments: input as Record<string, unknown>,
8584 })) as { isError?: boolean; content: unknown };
8685
8786 if (result.isError) {
88- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8987 const content = result.content as Array<{
9088 type: string;
9189 text?: string;
src/session/db.ts+0−24
@@ -158,14 +158,6 @@ export function getSession(id: string): SessionRow | null {
158158 );
159159 }
160160
161-export function updateSessionTitle(id: string, title: string): void {
162- getDb().run("UPDATE sessions SET title = ?, updated_at = ? WHERE id = ?", [
163- title,
164- Date.now(),
165- id,
166- ]);
167-}
168-
169161 export function touchSession(id: string, model: string): void {
170162 getDb().run("UPDATE sessions SET updated_at = ?, model = ? WHERE id = ?", [
171163 Date.now(),
@@ -182,24 +174,8 @@ export function listSessions(limit = 20): SessionRow[] {
182174 .all(limit);
183175 }
184176
185-export function deleteSession(id: string): void {
186- getDb().run("DELETE FROM sessions WHERE id = ?", [id]);
187-}
188-
189177 // ─── Message CRUD ─────────────────────────────────────────────────────────────
190178
191-export function saveMessage(
192- sessionId: string,
193- msg: CoreMessage,
194- turnIndex = 0,
195-): void {
196- getDb().run(
197- `INSERT INTO messages (session_id, payload, turn_index, created_at)
198- VALUES (?, ?, ?, ?)`,
199- [sessionId, JSON.stringify(msg), turnIndex, Date.now()],
200- );
201-}
202-
203179 export function saveMessages(
204180 sessionId: string,
205181 msgs: CoreMessage[],
src/session/manager.ts+2−6
@@ -1,7 +1,5 @@
1-import { homedir } from "node:os";
2-import { relative } from "node:path";
31 import * as c from "yoctocolors";
4-import { PREFIX, writeln } from "../cli/output.ts";
2+import { tildePath, writeln } from "../cli/output.ts";
53 import type { CoreMessage } from "../llm-api/turn.ts";
64 import {
75 type SessionRow,
@@ -50,9 +48,7 @@ export function printSessionList(): void {
5048 writeln(`\n${c.bold("Recent sessions:")}`);
5149 for (const s of sessions) {
5250 const date = new Date(s.updated_at).toLocaleString();
53- const cwd = s.cwd.startsWith(homedir())
54- ? `~${s.cwd.slice(homedir().length)}`
55- : s.cwd;
51+ const cwd = tildePath(s.cwd);
5652 const title = s.title || c.dim("(untitled)");
5753 writeln(
5854 ` ${c.dim(s.id.padEnd(14))} ${title.padEnd(30)} ${c.cyan(s.model.split("/").pop() ?? s.model).padEnd(20)} ${c.dim(cwd)} ${c.dim(date)}`,