xonecas.io
64875
Mc

mini-coder / commit 3162fcc

fix: implement audit recommendations

Immediate bugs:
- Token count/context now preserved after ESC interrupt by adding
  inputTokens/outputTokens/contextTokens to TurnErrorEvent and
  capturing them in stream-render before the abort/error branch
- System prompt now includes file creation guidance so models don't
  waste tool calls trying mc-edit for new files

Code changes:
- MCP client uses shared PACKAGE_VERSION instead of hardcoded '0.1.0'
- Created src/internal/version.ts as single source for package version,
  used by both MCP client and CLI banner
- isAbortError tightened: exact 'aborted' message match and ABORT_ERR
  code check instead of broad substring match
- Shell '!' context now records '(no output, exit N)' for commands
  with empty output so the model knows the command succeeded

Polish:
- Consolidated 3 UI truncation helpers (tool-render, tool-result-renderers,
  status-bar) into shared truncateText in src/internal/text.ts
- Consolidated frontmatter parsers: parseSkillFrontmatter now delegates
  to the generic parseFrontmatter which returns Record<string, string>
- /help truncates skill descriptions to 80 chars
- Double prompt glyph after ESC: investigated and confirmed as tmux
  capture-pane artifact, not a real bug; removed from KNOWN_ISSUES

Updated KNOWN_ISSUES.md to remove resolved items.
Added tests for isAbortError and truncateText (296 total, all pass).

xonecas2026-03-21 3162fccf216edc7e429839c2823316fbd789fd1c parent 30bf69b

21 files changed

AUDIT-REPORT.md+136−0
@@ -0,0 +1,136 @@
1+# Audit Report — mini-coder v0.2.0
2+
3+**Date:** 2026-03-21
4+**Auditor:** Claude Code (automated audit)
5+**Scope:** Full codebase review + multi-provider interactive testing
6+
7+---
8+
9+## Summary
10+
11+### How I tested
12+
13+- **Code review:** Read every module in `src/` (15k lines across 126 files), ran all static checks (`typecheck`, `lint`, `knip`, `jscpd`, `test`), and compared implementation against the core idea in AGENTS.md.
14+- **Multi-provider testing:** Exercised 5 SDK paths via tmux — one-shot and interactive multi-turn sessions with tool calling:
15+ - `zen/claude-haiku-4-5` — `@ai-sdk/anthropic` via Zen
16+ - `zen/gemini-3-flash` — `@ai-sdk/google` via Zen
17+ - `zen/gpt-5.4-nano` — `@ai-sdk/openai` (responses endpoint) via Zen
18+ - `zen/kimi-k2.5` — `@ai-sdk/openai-compatible` via Zen
19+ - `anthropic/claude-haiku-4-5` — direct Anthropic OAuth
20+- **Static analysis results:** 286 tests pass, 0 lint issues, 0 type errors, 0 unused exports (knip), 2 minor code clones (23 lines, 0.16%).
21+
22+### Overall assessment
23+
24+The codebase is well-structured and clean. All provider paths work correctly for both one-shot and interactive use. The architecture aligns closely with the core idea. The known issues file accurately tracks existing problems. Most findings below are minor.
25+
26+---
27+
28+## Code & Architecture
29+
30+### Correctness issues
31+
32+1. **MCP client reports hardcoded version `0.1.0`** (`src/mcp/client.ts:31`)
33+ The MCP client identifies itself as `version: "0.1.0"` while the package is at `0.2.0`. This should use the actual package version (the same `__PACKAGE_VERSION__` constant used in the banner).
34+
35+2. **`isAbortError` relies on string matching** (`src/agent/agent-helpers.ts:13–17`)
36+ `isAbortError` checks `error.name === "AbortError"` OR `error.message.toLowerCase().includes("abort")`. The message fallback is overly broad — any error mentioning "abort" (e.g. "Transaction aborted by user") would be treated as a cancellation. This hasn't caused issues in practice but is a latent correctness risk.
37+
38+3. **Shell `!` integration silently drops context for empty output** (`src/cli/input-loop.ts:98`)
39+ When a `!` shell command produces no stdout, no stderr, and exits successfully, `buildShellContext` returns an empty string and `addShellContext` is skipped entirely. The user sees the command run but nothing is recorded. For `!ls` in an empty dir this is fine, but for side-effect commands like `!git commit` the exit status context is lost.
40+
41+### KISS / DRY / YAGNI
42+
43+4. **Duplicate frontmatter parsers** (already tracked in KNOWN_ISSUES.md)
44+ `parseFrontmatter` in `cli/frontmatter.ts` and `parseSkillFrontmatter` in `cli/skills.ts` implement the same YAML-like frontmatter parsing with slightly different APIs. The skills variant reads from file descriptors for performance (only reads first 64KB), which is a good optimization, but the parsing logic itself is duplicated.
45+
46+5. **Truncation helpers are scattered** (already tracked in KNOWN_ISSUES.md)
47+ At least 4 independent truncation implementations: `truncate` in `tool-render.ts`, `truncateOneLine` in `tool-result-renderers.ts`, `truncatePlainText` in `status-bar.ts`, and `compactHeadTail` in `turn-context.ts`. The LLM-facing truncation (`compactHeadTail`) is structurally different from the UI-facing ones, so not all can be consolidated, but the three UI truncation functions share the same pattern.
48+
49+6. **`getMessageDiagnostics` builds maps that are only consumed by logging** (`src/llm-api/turn-context.ts`)
50+ The full diagnostics function (`getMessageDiagnostics`) is only called from the API logging path. The lightweight `getMessageStats` exists for the hot path. This is actually good design — no violation — but the `getMessageDiagnostics` function is quite heavyweight for diagnostic-only use; worth noting it's correctly excluded from the critical path.
51+
52+### Idea alignment
53+
54+7. **System prompt doesn't mention file creation workflow**
55+ The system prompt describes `mc-edit` for editing existing files but doesn't mention how to create new files (using shell commands like `cat >` or `printf`). During GPT Nano testing, the model tried `mc-edit` for file creation, got two errors, then self-corrected. Adding a brief note about file creation would save tokens on error recovery.
56+
57+8. **`maxOutputTokens` hardcoded to 16384** (already tracked in KNOWN_ISSUES.md)
58+ The value in `turn-request.ts:82` is a fixed constant. The core idea says to derive from model info. Model data is already available via `resolveModelInfo()`.
59+
60+9. **No conversation summary on max context** (already tracked in KNOWN_ISSUES.md)
61+ The `error-parse.ts` surfaces a "Max context size reached" error with hint "Use /new to start a fresh session". The core idea wants "a conversation summary" instead of just an error.
62+
63+---
64+
65+## UI/UX Alignment
66+
67+### Cross-provider consistency
68+
69+All five tested paths produce visually consistent output:
70+
71+- **Banner** renders correctly with model, cwd, skills count, and toggle states.
72+- **Status bar** shows model, session ID, token counts, context usage, and cwd. Format is consistent across all providers.
73+- **Tool call display** uses correct semantic glyphs (`←` for reads, `✎` for writes, `$` for exec, `?` for search). Truncation at 80 chars works.
74+- **Tool results** show structured output: exit code, stdout/stderr line counts, inline single-line results.
75+- **Assistant text** prefixed with `◆`, user prompts with `›`.
76+- **Spinner** shows during thinking, clears correctly before output.
77+
78+### Provider-specific observations
79+
80+| Provider | One-shot | Interactive | Multi-turn | Notes |
81+| ---------------------------- | -------- | ----------- | ---------- | --------------------------------------------------- |
82+| `zen/claude-haiku-4-5` | ✅ | ✅ | ✅ | Clean tool use, good output |
83+| `zen/gemini-3-flash` | ✅ | ✅ | — | Efficient: combined create+read in one tool call |
84+| `zen/gpt-5.4-nano` | ✅ | ✅ | — | Tried mc-edit for new file, self-corrected (see #7) |
85+| `zen/kimi-k2.5` | ✅ | ✅ | — | Leading whitespace in one-shot output (cosmetic) |
86+| `anthropic/claude-haiku-4-5` | ✅ | ✅ | ✅ | Clean, ESC interrupt works |
87+
88+### UI issues observed
89+
90+10. ~~**Double prompt glyph after ESC interrupt**~~ — Investigated: this is a tmux `capture-pane` rendering artifact, not an actual double prompt. Raw stdout analysis confirms only one `renderPrompt` call. Removed from KNOWN_ISSUES.
91+
92+11. **Token counts not updated after interrupted turn**
93+ After ESC interrupt, the status bar shows stale token counts from the previous completed turn, not from the interrupted one. The interrupted turn's partial usage isn't accumulated because the error path doesn't emit a `turn-complete` event with usage data.
94+
95+12. **Context window disappears from status bar after interrupt**
96+ After an ESC-interrupted turn, the status bar dropped the `ctx X/Y Z%` segment entirely. This is because `lastContextTokens` stays 0 when the turn is interrupted (the complete event is never processed), and `buildContextSegment` returns `null` for `contextTokens <= 0`.
97+
98+13. **`/help` skills section shows full descriptions without truncation**
99+ The ai-sdk skill description wraps across 3 lines in the help output. Skills with long descriptions should be truncated in the help display for consistency with the concise help format.
100+
101+14. **tmux `send-keys` triggers paste detection**
102+ When using `tmux send-keys` with multi-word text (without `-l`), the input handler detects it as a paste and shows `[pasted: "..."]`. Using `-l` (literal) mode for send-keys + separate Enter works correctly. This is technically correct behavior (tmux sends all chars in one burst) but makes automated testing harder. Not a user-facing issue.
103+
104+---
105+
106+## Recommendations
107+
108+### Immediate bugs (should fix)
109+
110+1. **Token count reset after ESC interrupt** — The interrupted turn's `inputTokens`/`outputTokens` from `turnState.getState()` are available in the `turn-error` event's `partialMessages` path, but `session-runner.ts` doesn't accumulate them because the `try` block throws before reaching the accumulation code. Move token accumulation to a `finally` block or accumulate from the error event.
111+
112+2. **Context window vanishing after interrupt** — Related to #1. When `lastContextTokens` is 0, the status bar omits the context segment. Either preserve the last known context tokens across interrupts, or include `contextTokens` in the error event.
113+
114+3. **System prompt: add file creation guidance** — Add one line to the mc-edit description: "To create new files, use shell commands (e.g. `cat > file.txt << 'EOF'`)." This will save tool-call roundtrips for all models.
115+
116+### Code changes (should address)
117+
118+4. **MCP client version** — Use `__PACKAGE_VERSION__` or read from package.json instead of hardcoding `"0.1.0"`.
119+
120+5. **`isAbortError` specificity** — Tighten the message check: look for "aborted" specifically, or check for `err.code === "ABORT_ERR"` instead of substring matching.
121+
122+6. **`!` shell: preserve exit status context** — When `buildShellContext` returns empty, still record something like `"(no output, exit 0)"` so the model knows the command succeeded.
123+
124+### Polish items (nice to have)
125+
126+7. **Consolidate UI truncation helpers** — The three UI-facing `truncate`/`truncateOneLine`/`truncatePlainText` functions can share a single helper.
127+
128+8. **Consolidate frontmatter parsers** — Make `parseSkillFrontmatter` call `parseFrontmatter` after reading the first 64KB chunk, or factor the regex/loop into a shared helper.
129+
130+9. **Help: truncate skill descriptions** — Limit skill descriptions in `/help` output to ~100 chars.
131+
132+10. **Double prompt glyph** — Suppress the extra newline in `stream-render.ts` when the turn was interrupted via ESC.
133+
134+---
135+
136+_This report covers audit findings only. No changes have been made. Review with the user before implementing._
docs/KNOWN_ISSUES.md+0−3
@@ -8,7 +8,6 @@
88 - AI SDK expands `claude-3-5-haiku` → dated variant that Zen doesn't serve (404).
99 - Shell tool max-timeout leaves the parent terminal in a broken state.
1010 - MiniMax sends empty text deltas in one-shot — renders as blank lines.
11-- Double prompt glyph after ESC — `turn-complete` newline + input loop prompt collide.
1211 - Truncated tool commands cut mid-argument (e.g. `--new '{…`). Truncate at argument boundaries instead.
1312
1413 ## Features
@@ -18,6 +17,4 @@
1817
1918 ## Refactors
2019
21-- Consolidate truncation helpers across cli modules into `cli/truncate.ts`.
22-- Consolidate `parseSkillFrontmatter` (skills.ts) with `parseFrontmatter` (frontmatter.ts).
2320 - Status bar: merge model + thinking effort into one field, drop `showReasoning` (already in banner).
src/agent/agent-helpers.ts+2−1
@@ -15,7 +15,8 @@ export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
1515 export function isAbortError(error: Error): boolean {
1616 return (
1717 error.name === "AbortError" ||
18- (error.name === "Error" && error.message.toLowerCase().includes("abort"))
18+ ("code" in error && error.code === "ABORT_ERR") ||
19+ (error.name === "Error" && error.message === "aborted")
1920 );
2021 }
2122
src/agent/agent.test.ts+30−0
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22 import type { CoreMessage } from "../llm-api/turn.ts";
33 import {
44 extractAssistantText,
5+ isAbortError,
56 makeInterruptMessage,
67 sanitizeModelAuthoredMessages,
78 } from "./agent-helpers.ts";
@@ -178,3 +179,32 @@ describe("makeInterruptMessage", () => {
178179 );
179180 });
180181 });
182+
183+// ─── isAbortError ─────────────────────────────────────────────────────────────
184+
185+describe("isAbortError", () => {
186+ test("detects AbortError by name", () => {
187+ const err = new DOMException("signal is aborted", "AbortError");
188+ expect(isAbortError(err)).toBe(true);
189+ });
190+
191+ test("detects ABORT_ERR code", () => {
192+ const err = new DOMException("aborted", "AbortError");
193+ expect(isAbortError(err)).toBe(true);
194+ });
195+
196+ test('detects exact "aborted" message', () => {
197+ const err = new Error("aborted");
198+ expect(isAbortError(err)).toBe(true);
199+ });
200+
201+ test("rejects generic error mentioning abort in text", () => {
202+ const err = new Error("Transaction aborted by user");
203+ expect(isAbortError(err)).toBe(false);
204+ });
205+
206+ test("rejects unrelated error", () => {
207+ const err = new Error("connection timeout");
208+ expect(isAbortError(err)).toBe(false);
209+ });
210+});
src/agent/system-prompt.ts+1−0
@@ -82,6 +82,7 @@ Outputs a diff of the changes and meta information.
8282 Apply one safe exact-text edit to an existing file.
8383 - The expected old text must match exactly once.
8484 - Omit --new / --new-file to delete the matched text.
85+- To create new files, use shell commands (e.g. \`cat > file.txt << 'EOF'\\n...\\nEOF\`).
8586 `;
8687
8788 prompt += AUTONOMY;
src/cli/commands-help.ts+3−1
@@ -1,4 +1,5 @@
11 import * as c from "yoctocolors";
2+import { truncateText } from "../internal/text.ts";
23 import { writeln } from "./output.ts";
34 import { loadSkillsIndex } from "./skills.ts";
45 import type { CommandContext } from "./types.ts";
@@ -51,8 +52,9 @@ export function renderHelpCommand(ctx: CommandContext): void {
5152 for (const skill of skills.values()) {
5253 const source =
5354 skill.source === "local" ? c.dim("local") : c.dim("global");
55+ const desc = truncateText(skill.description, 80);
5456 writeln(
55- ` ${c.green(`/${skill.name}`.padEnd(28))} ${c.dim(skill.description)} ${c.dim("·")} ${source}`,
57+ ` ${c.green(`/${skill.name}`.padEnd(28))} ${c.dim(desc)} ${c.dim("·")} ${source}`,
5658 );
5759 }
5860 }
src/cli/frontmatter.test.ts+2−1
@@ -27,11 +27,12 @@ describe("parseFrontmatter", () => {
2727 });
2828 });
2929
30- test("ignores unknown frontmatter keys", () => {
30+ test("preserves all frontmatter keys", () => {
3131 const raw = "---\nname: helper\nfoo: bar\n---\n\nRun it";
3232 expect(parseFrontmatter(raw)).toEqual({
3333 meta: {
3434 name: "helper",
35+ foo: "bar",
3536 },
3637 body: "Run it",
3738 });
src/cli/frontmatter.ts+7−11
@@ -1,21 +1,19 @@
11 // ─── Frontmatter parser ───────────────────────────────────────────────────────
22
3-interface Frontmatter {
4- description?: string;
5- model?: string;
6- name?: string;
7-}
8-
93 const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
104
5+/**
6+ * Parse simple YAML-like frontmatter from a text string.
7+ * Returns key-value pairs (string values only) and the body after the closing `---`.
8+ */
119 export function parseFrontmatter(raw: string): {
12- meta: Frontmatter;
10+ meta: Record<string, string>;
1311 body: string;
1412 } {
1513 const m = raw.match(FM_RE);
1614 if (!m) return { meta: {}, body: raw };
1715
18- const meta: Frontmatter = {};
16+ const meta: Record<string, string> = {};
1917 const yamlBlock = m[1] ?? "";
2018 for (const line of yamlBlock.split("\n")) {
2119 const colon = line.indexOf(":");
@@ -25,9 +23,7 @@ export function parseFrontmatter(raw: string): {
2523 .slice(colon + 1)
2624 .trim()
2725 .replace(/^["']|["']$/g, "");
28- if (key === "name") meta.name = val;
29- if (key === "description") meta.description = val;
30- if (key === "model") meta.model = val;
26+ if (key) meta[key] = val;
3127 }
3228
3329 return { meta, body: (m[2] ?? "").trim() };
src/cli/input-loop.ts+2−0
@@ -26,6 +26,8 @@ function buildShellContext(result: ShellOutput): string {
2626 if (result.stderr) sections.push(`stderr:\n${result.stderr}`);
2727 if (result.timedOut) sections.push("command timed out");
2828 if (!result.success) sections.push(`exit code: ${result.exitCode}`);
29+ if (sections.length === 0)
30+ sections.push(`(no output, exit ${result.exitCode})`);
2931 return sections.join("\n\n").trim();
3032 }
3133
src/cli/output.ts+1−3
@@ -6,6 +6,7 @@ import type {
66 StatusBarData,
77 TurnResult,
88 } from "../agent/reporter.ts";
9+import { PACKAGE_VERSION } from "../internal/version.ts";
910 import type { TurnEvent } from "../llm-api/types.ts";
1011 import { logError } from "../logging/context.ts";
1112 import {
@@ -20,9 +21,6 @@ import { renderTurn } from "./stream-render.ts";
2021 import { terminal } from "./terminal-io.ts";
2122
2223 const HOME = homedir();
23-declare const __PACKAGE_VERSION__: string;
24-const PACKAGE_VERSION =
25- typeof __PACKAGE_VERSION__ !== "undefined" ? __PACKAGE_VERSION__ : null;
2624
2725 /** Replace the home directory prefix with `~` for display. */
2826 export function tildePath(p: string): string {
src/cli/skills.ts+7−19
@@ -10,6 +10,7 @@ import {
1010 import { homedir } from "node:os";
1111 import { dirname, join, resolve } from "node:path";
1212 import * as c from "yoctocolors";
13+import { parseFrontmatter } from "./frontmatter.ts";
1314 import { G, writeln } from "./output.ts";
1415
1516 export interface SkillMeta {
@@ -56,25 +57,12 @@ function parseSkillFrontmatter(filePath: string): SkillFrontmatter {
5657 const chunk = Buffer.allocUnsafe(MAX_FRONTMATTER_BYTES);
5758 const bytesRead = readSync(fd, chunk, 0, MAX_FRONTMATTER_BYTES, 0);
5859 const text = chunk.toString("utf8", 0, bytesRead);
59- const lines = text.split("\n");
60- if ((lines[0] ?? "").trim() !== "---") return {};
61-
62- const meta: SkillFrontmatter = {};
63- for (let i = 1; i < lines.length; i++) {
64- const line = (lines[i] ?? "").replace(/\r$/, "");
65- if (line.trim() === "---") break;
66- const colon = line.indexOf(":");
67- if (colon === -1) continue;
68- const key = line.slice(0, colon).trim();
69- const value = line
70- .slice(colon + 1)
71- .trim()
72- .replace(/^["']|["']$/g, "");
73- if (key === "name") meta.name = value;
74- if (key === "description") meta.description = value;
75- if (key === "context") meta.context = value;
76- }
77- return meta;
60+ const { meta } = parseFrontmatter(text);
61+ const result: SkillFrontmatter = {};
62+ if (meta.name) result.name = meta.name;
63+ if (meta.description) result.description = meta.description;
64+ if (meta.context) result.context = meta.context;
65+ return result;
7866 } catch {
7967 return {};
8068 } finally {
src/cli/status-bar.ts+3−8
@@ -1,16 +1,11 @@
11 import * as c from "yoctocolors";
22 import type { StatusBarData } from "../agent/reporter.ts";
33 import { stripAnsi } from "../internal/ansi.ts";
4+import { truncateText } from "../internal/text.ts";
45 import { terminal } from "./terminal-io.ts";
56
67 const STATUS_SEP = c.dim(" · ");
78
8-function truncatePlainText(value: string, maxLen: number): string {
9- if (value.length <= maxLen) return value;
10- if (maxLen <= 1) return "…";
11- return `${value.slice(0, maxLen - 1)}…`;
12-}
13-
149 function fmtTokens(n: number): string {
1510 if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
1611 return String(n);
@@ -74,10 +69,10 @@ function fitStatusSegments(
7469 const plainRequired = required.map((segment) => stripAnsi(segment));
7570 const sepLen = stripAnsi(STATUS_SEP).length;
7671 const fixedPrefix = plainRequired[0] ?? "";
77- if (plainRequired.length <= 1) return truncatePlainText(fixedPrefix, cols);
72+ if (plainRequired.length <= 1) return truncateText(fixedPrefix, cols);
7873
7974 const maxTailLen = Math.max(8, cols - fixedPrefix.length - sepLen);
80- const truncatedTail = truncatePlainText(plainRequired[1] ?? "", maxTailLen);
75+ const truncatedTail = truncateText(plainRequired[1] ?? "", maxTailLen);
8176 return `${required[0]}${STATUS_SEP}${c.dim(truncatedTail)}`;
8277 }
8378
src/cli/stream-render.ts+3−0
@@ -153,6 +153,9 @@ export async function renderTurn(
153153 liveReasoning.finish();
154154 content.flushOpenContent();
155155 spinner.stop();
156+ inputTokens = event.inputTokens;
157+ outputTokens = event.outputTokens;
158+ contextTokens = event.contextTokens;
156159 if (isAbortError(event.error)) {
157160 newMessages = buildAbortMessages(
158161 event.partialMessages,
src/cli/tool-render.ts+2−5
@@ -1,4 +1,5 @@
11 import * as c from "yoctocolors";
2+import { truncateText } from "../internal/text.ts";
23 import { G, tildePath, writeln } from "./output.ts";
34 import { renderToolResultByName } from "./tool-result-renderers.ts";
45
@@ -70,16 +71,12 @@ function extractFirstCommand(cmd: string): string {
7071 return tokens[0] ?? "";
7172 }
7273
73-function truncate(s: string, max: number): string {
74- return s.length > max ? `${s.slice(0, max - 1)}…` : s;
75-}
76-
7774 function formatShellCallLine(cmd: string): string {
7875 const { cwd, rest } = parseShellCdPrefix(cmd);
7976 const firstCmd = extractFirstCommand(rest);
8077 const glyph = shellCmdGlyph(firstCmd, rest);
8178 const cwdSuffix = cwd ? ` ${c.dim(`in ${cwd}`)}` : "";
82- const display = truncate(rest, 80);
79+ const display = truncateText(rest, 80);
8380 return `${glyph} ${display}${cwdSuffix}`;
8481 }
8582
src/cli/tool-result-renderers.ts+2−1
@@ -1,4 +1,5 @@
11 import * as c from "yoctocolors";
2+import { truncateText } from "../internal/text.ts";
23 import { G, writeln } from "./output.ts";
34
45 interface ToolResultRenderOptions {
@@ -48,7 +49,7 @@ function truncateOneLine(
4849 verboseOutput = false,
4950 ): string {
5051 if (verboseOutput) return value;
51- return value.length > max ? `${value.slice(0, max - 1)}…` : value;
52+ return truncateText(value, max);
5253 }
5354
5455 function normalizeShellText(value: string): string {
src/internal/text.test.ts+24−0
@@ -0,0 +1,24 @@
1+import { describe, expect, test } from "bun:test";
2+import { truncateText } from "./text.ts";
3+
4+describe("truncateText", () => {
5+ test("returns short strings unchanged", () => {
6+ expect(truncateText("hello", 10)).toBe("hello");
7+ });
8+
9+ test("truncates at exact boundary", () => {
10+ expect(truncateText("hello", 5)).toBe("hello");
11+ });
12+
13+ test("truncates long strings with ellipsis", () => {
14+ expect(truncateText("hello world", 8)).toBe("hello w…");
15+ });
16+
17+ test("handles max=1", () => {
18+ expect(truncateText("hello", 1)).toBe("…");
19+ });
20+
21+ test("handles empty string", () => {
22+ expect(truncateText("", 5)).toBe("");
23+ });
24+});
src/internal/text.ts+6−0
@@ -0,0 +1,6 @@
1+/** Truncate a plain-text string to `max` characters, appending `…` if clipped. */
2+export function truncateText(value: string, max: number): string {
3+ if (value.length <= max) return value;
4+ if (max <= 1) return "…";
5+ return `${value.slice(0, max - 1)}…`;
6+}
src/internal/version.ts+9−0
@@ -0,0 +1,9 @@
1+import pkg from "../../package.json";
2+
3+declare const __PACKAGE_VERSION__: string;
4+
5+/** Package version — resolved at build time, falls back to package.json in dev. */
6+export const PACKAGE_VERSION: string =
7+ typeof __PACKAGE_VERSION__ !== "undefined"
8+ ? __PACKAGE_VERSION__
9+ : pkg.version;
src/llm-api/turn.ts+3−0
@@ -147,6 +147,9 @@ export async function* runTurn(options: {
147147 type: "turn-error",
148148 error: normalizedError,
149149 partialMessages: finalState.partialMessages,
150+ inputTokens: finalState.inputTokens,
151+ outputTokens: finalState.outputTokens,
152+ contextTokens: finalState.contextTokens,
150153 };
151154 }
152155 }
src/llm-api/types.ts+6−0
@@ -57,6 +57,12 @@ export interface TurnErrorEvent {
5757 error: Error;
5858 /** Messages from completed steps before the error/abort occurred. */
5959 partialMessages: CoreMessage[];
60+ /** Accumulated input tokens before the error/abort. */
61+ inputTokens: number;
62+ /** Accumulated output tokens before the error/abort. */
63+ outputTokens: number;
64+ /** Context tokens from the last completed step (0 if none completed). */
65+ contextTokens: number;
6066 }
6167
6268 export type TurnEvent =
src/mcp/client.ts+2−1
@@ -3,6 +3,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
33 import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
44 import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
55 import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
6+import { PACKAGE_VERSION } from "../internal/version.ts";
67 import type { ToolDef } from "../llm-api/types.ts";
78
89 // ─── Types ────────────────────────────────────────────────────────────────────
@@ -28,7 +29,7 @@ interface McpClient {
2829 export async function connectMcpServer(
2930 config: McpServerConfig,
3031 ): Promise<McpClient> {
31- const client = new Client({ name: "mini-coder", version: "0.1.0" });
32+ const client = new Client({ name: "mini-coder", version: PACKAGE_VERSION });
3233
3334 if (config.transport === "http") {
3435 if (!config.url) {