xonecas.io
64875
Mc

mini-coder / commit 2774211

Merge remote-tracking branch 'origin/main'

Sean2026-07-01 2774211e3c45b49550ef8261b59d3f72a3e9c2e7 parent 5db070bparent 32cdeaf

23 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/skills/rr/SKILL.md+20−0
@@ -0,0 +1,20 @@
1+---
2+name: rr
3+description: Use this skill when explicitly requested by the user.
4+---
5+
6+# Code Review Request
7+
8+Use this skill only when explicitly asked by the user.
9+
10+## How to review
11+
12+1. Understand the codebase, read the changes in full, and determine whether you understand the direction of the changes.
13+2. Ask the user any clarifying questions if needed.
14+3. Review the code changes for alignment with the direction, code quality, and common agent-induced anti-patterns.
15+4. Present your findings in a human-readable way. Do not suggest fixes; simply expose the issues. Do not give priorities or severities.
16+
17+## Review style
18+
19+1. Do not report the same issue multiple times.
20+2. Don't be a style zealot or nitpicker. Focus on code correctness, quality, and alignment with the codebase and the user's goal for the changes.
AGENTS.md+14−1
@@ -24,6 +24,19 @@ Plain text readme file: https://raw.githubusercontent.com/badlogic/pi-mono/refs/
2424 - Typescript files should be modules with exports over classes.
2525 - Hoist variables, define helpers before using them, ensure code reads well for humans.
2626
27+## Coding style
28+
29+- Prefer small named functions and plain exported objects over classes or heavy abstractions.
30+- Keep imports grouped as node built-ins, external packages, then local modules. Use `type` imports for types.
31+- Use 2-space indentation, semicolons, double quotes, and trailing commas in multiline literals/calls.
32+- Name values with `camelCase`, types/schemas/TUI components with `PascalCase`, and fixed defaults with `SCREAMING_SNAKE_CASE`.
33+- Model state and events with explicit TypeScript types, discriminated unions, and TypeBox schemas for persisted or parsed data.
34+- Use early returns and guard clauses for validation, missing files, aborts, and fallback cases.
35+- Prefer Bun APIs (`Bun.file`, `Bun.write`, `Bun.spawn`, `Bun.Glob`) for runtime, file, and process work.
36+- Keep async flows readable with `async` functions/generators, `for await`, and explicit `AbortSignal` handling before writes or long work.
37+- In tool runners, report recoverable failures as tool result text instead of throwing; reserve thrown `Error`s for caller-facing validation failures.
38+- Comments should explain why something exists or document non-obvious behavior; use `TODO:` for known follow-up work.
39+
2740 ## Benchmarks
2841
2942 - Please see `BENCHMARK.md` for Terminal Bench benchmark info, and how to run it.
@@ -36,7 +49,7 @@ Plain text readme file: https://raw.githubusercontent.com/badlogic/pi-mono/refs/
3649 - Format root `*.md` files: `bunx prettier --write *.md`
3750 - Format typescript files: `bunx biome format --write`
3851
39-Then lint with: `bunx biome check` and `tsc --noEmit`.
52+Then lint with: `bunx biome check` and `bunx tsc --noEmit`. (Do not expect to see tsc in PATH).
4053
4154 **Do not use the `package.json` commands/scripts they are for the users.** Use the commands above instead.
4255
TODO.md+0−29
@@ -4,34 +4,5 @@
44
55 ## TODO
66
7-- [ ] Session fork/undo — either tree-view forking (like pi coding agent) or undo flow, or both. Complex feature, needs UI and storage design.
87 - [ ] Path autocomplete in TUI — `Tab` on file paths opens path picker.
98 - [ ] Status bar richness — detailed git counts (staged/modified/untracked/ahead/behind).
10-
11-## TODO: Better prompts, tools descriptions and reminder prompt engineering.
12-
13-Raw notes, references:
14-
15-### JetBrains Junie: Observation Masking
16-
17-Published research found that **simply hiding old tool outputs** matched the quality of full LLM summarization with **zero extra compute**:
18-
19-> good lessons from claude and general advice, seems good and grounded on real experience. Matches with learnings.
20-> https://www.indiehackers.com/post/the-complete-guide-to-writing-agent-system-prompts-lessons-from-reverse-engineering-claude-code-6e18d54294
21-
22-> How pi coding agent does it, minimal and structured, a good approach, but we can be even more focused and minimal.
23-> https://raw.githubusercontent.com/badlogic/pi-mono/refs/heads/main/packages/coding-agent/src/core/system-prompt.ts
24-
25-### Prompt learnings:
26-
27-> Key sentence to add:
28-
29-```
30-Prioritize technical accuracy and truthfulness over validating the user's beliefs.
31-Focus on facts and problem-solving, providing direct, objective technical info
32-without any unnecessary superlatives, praise, or emotional validation.
33-```
34-
35-More reading material:
36-
37-- https://arxiv.org/html/2601.16507v1#S3
biome.json+2−2
@@ -1,5 +1,5 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
2+ "$schema": "https://biomejs.dev/schemas/2.5.0/schema.json",
33 "assist": {
44 "actions": {
55 "source": {
@@ -14,7 +14,7 @@
1414 "linter": {
1515 "enabled": true,
1616 "rules": {
17- "recommended": true,
17+ "preset": "recommended",
1818 "suspicious": {
1919 "noExplicitAny": "off"
2020 }
bun.lock+12−12
@@ -13,9 +13,9 @@
1313 "yaml": "^2.9.0",
1414 },
1515 "devDependencies": {
16- "@biomejs/biome": "^2.4.15",
16+ "@biomejs/biome": "^2.5.0",
1717 "@types/bun": "^1.3.14",
18- "prettier": "^3.8.3",
18+ "prettier": "^3.8.4",
1919 "typescript": "^6.0.3",
2020 },
2121 },
@@ -75,23 +75,23 @@
7575
7676 "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="],
7777
78- "@biomejs/biome": ["@biomejs/biome@2.4.15", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.15", "@biomejs/cli-darwin-x64": "2.4.15", "@biomejs/cli-linux-arm64": "2.4.15", "@biomejs/cli-linux-arm64-musl": "2.4.15", "@biomejs/cli-linux-x64": "2.4.15", "@biomejs/cli-linux-x64-musl": "2.4.15", "@biomejs/cli-win32-arm64": "2.4.15", "@biomejs/cli-win32-x64": "2.4.15" }, "bin": { "biome": "bin/biome" } }, "sha512-j5VH3a/h/HXTKBM50MDMxRCzkeLv9S2XJcW2WgnZT1+xyisi+0bISrXR82gCX+8S9lv …
78+ "@biomejs/biome": ["@biomejs/biome@2.5.0", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.0", "@biomejs/cli-darwin-x64": "2.5.0", "@biomejs/cli-linux-arm64": "2.5.0", "@biomejs/cli-linux-arm64-musl": "2.5.0", "@biomejs/cli-linux-x64": "2.5.0", "@biomejs/cli-linux-x64-musl": "2.5.0", "@biomejs/cli-win32-arm64": "2.5.0", "@biomejs/cli-win32-x64": "2.5.0" }, "bin": { "biome": "bin/biome" } }, "sha512-4kURkd9hAPrdDM3C9n82ycYgx8hvQcW6MjKTEejruj8rK0N8P3OPpdy8BvI8kt3KWY4ycF5XtDOr …
7979
80- "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.15", "", { "os": "darwin", "cpu": "arm64" }, "sha512-rF3PPqLq1yoST79zaQbDjVJwsuIeci/O+9bgNmC5QpgOqz6aqYuzA4abyAGx+mgyiDXn4A049xAN8gijbuR1Qg=="],
80+ "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.5.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Mn3Fwi3SA5fgmfCPqmzpWF2DLZnms3BVAhM088nTnGrTZmHS3wwIjcoZPqpXeNgd3DrrLH6xp8vTLIBuJoZiXw=="],
8181
82- "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.15", "", { "os": "darwin", "cpu": "x64" }, "sha512-/5KHXYMfSJs1fNXiX30xFtI8JcCFV6zaVVLxOa0M2sfqBKHkpQhRTv94yxQWxeTY2lzo2OuTlNvPC+hDQt2wcQ=="],
82+ "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.5.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-rg3VPL5P8mYro6pqlXYXuJWph21slVp3SZtAqWSrkZs40d2gTzYmHF8E/X1iTID25btmNKltNDJ926sqVBp7DQ=="],
8383
84- "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-owaAMZD/T4LrD0ELNCk0Km3qrRHuM0X6EAyVE1FSqGY0rbLoiDLrO4Us2tllm6cAeB2Ioa9C2C08NZPdr8+0Ug=="],
84+ "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-tl+LW8fdD96/xdeWtWwc82LIOc5CoY7N2AsogLTp5R4ECErYt+8Jl/N68ezN9vzSiqPTxw6vjcihoLPYKZHrlw=="],
8585
86- "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-ZPcxznxm0pogHBLZhYntyR3sR+MrZjqJIKEr7ZqVen0Rl+P/4upVmfYXjftizi9RoqZntg33fv/1fbdhbYXpEQ=="],
86+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-vQdM4oSGaf7ZNeGO9w5+Y8SBtyser9M6znxYbm7Ec8wInxJu1WiKxFYZW5Auj2d80bcVvefuGGRxoFOE0eee8g=="],
8787
88- "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.15", "", { "os": "linux", "cpu": "x64" }, "sha512-0jj7THz12GbUOLmMibktK6DZjqz2zV64KFxyBtcFTKPiiOIY0a7vns1elpO1dERvxpsZ5ik0oFfz0oGwFde1+g=="],
88+ "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-zpEGf4RQbFEh8Vt7OmavLyyOzRbtcE9osCqrS1kfvt8jDvxwhKXLSf7n0ebr/ov0RJ9ssP+lhs6C8a9WwFvrQA=="],
8989
90- "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.15", "", { "os": "linux", "cpu": "x64" }, "sha512-CNq/9W38SYSH023lfcQ4KKU8K0YX8T//FZUhcgtMMRABDojx5XsMV7jlweAvGSl389wJQB29Qo6Zb/a+jdvt+w=="],
90+ "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-+9hIcMngJ+yGUahXqZuZ8CoWKJE9SAZsFsM3QDvXpNsLbXZ9lqVzgBhOk/jTSYkOA0GLP9eu3teukqpLUojHMg=="],
9191
92- "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.15", "", { "os": "win32", "cpu": "arm64" }, "sha512-ouhkYdlhp/1GghEJPdWwD/Vi3gQ1nFxuSpMolWsbq3Lsq3QUR4jl6UdhhscdCugKU5vOEuMiJhvKj66O0OCq+w=="],
92+ "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.5.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-jB0wAvTLI4itx5VidqVUejPQFhRUxiZ9l9FvZ26D5fl6t3qme+ZB4PD3bTSeL1vZ8NI2Rx/zj6H9zcESuGHKGw=="],
9393
94- "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.15", "", { "os": "win32", "cpu": "x64" }, "sha512-zBrGq5mx5wwpnow4+2BxUvleDM+GNd4sLbPaMapsSLQLD0NGRCquqPBTgN+7XkUteHvj7M+BstuI8tmnV7+HgQ=="],
94+ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.5.0", "", { "os": "win32", "cpu": "x64" }, "sha512-VT/lF+GId+67j8aDfLkxdxNoVApsPSTbyAtB3jJq0IWTrY77WXfbPfpngxq0bA6JCEv/7k8C9qWjDRKRznDlyw=="],
9595
9696 "@cel-tui/clew": ["@cel-tui/clew@0.8.3", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-7OFUe8ECleXjq9+vv2EvDcTXsiWNSQqVALD1LC/Gi9DzVp1aw0S6SloJuAv1KUVkwjZxil+mvYlk2LoC28mETQ=="],
9797
@@ -235,7 +235,7 @@
235235
236236 "path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="],
237237
238- "prettier": ["prettier@3.8.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw=="],
238+ "prettier": ["prettier@3.8.4", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q=="],
239239
240240 "protobufjs": ["protobufjs@7.5.6", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.1", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-M71sTMB146U3u0di3yup8iM+zv8yPRNQVr1KK4tyBitl3qFvEGucq/rGD …
241241
package.json+4−4
@@ -1,8 +1,8 @@
11 {
22 "name": "mini-coder",
3- "version": "0.7.0",
3+ "version": "0.7.3",
44 "type": "module",
5- "packageManager": "bun@1.3.12",
5+ "packageManager": "bun@1.3.13",
66 "bin": {
77 "mc": "bin/mc.ts"
88 },
@@ -14,9 +14,9 @@
1414 "format": "bun run prettier --write *.md && bun run biome format --write . && bun run biome check --write ."
1515 },
1616 "devDependencies": {
17- "@biomejs/biome": "^2.4.15",
17+ "@biomejs/biome": "^2.5.0",
1818 "@types/bun": "^1.3.14",
19- "prettier": "^3.8.3",
19+ "prettier": "^3.8.4",
2020 "typescript": "^6.0.3"
2121 },
2222 "dependencies": {
src/agent.ts+6−3
@@ -112,9 +112,6 @@ export async function* streamAgent(
112112 yield { type: "message_update", partial };
113113 }
114114
115- estimate = estimateTokens(JSON.stringify(llmCtx));
116- // 80k is the agreed uppon threshold to the DUMB ZONE
117- if (estimate > 80000) compactContext(llmCtx.messages);
118115 break;
119116 }
120117
@@ -133,6 +130,12 @@ export async function* streamAgent(
133130 return;
134131 }
135132 }
133+
134+ // Experiment: use this inside the inner loop for "running" compaction
135+ // after we are in the dumb zone.
136+ const estimate = estimateTokens(JSON.stringify(llmCtx));
137+ // 80k is the agreed uppon threshold to the DUMB ZONE
138+ if (estimate > 80000) compactContext(llmCtx.messages);
136139 }
137140
138141 const message = await s.result();
src/args.ts+12−1
@@ -8,6 +8,7 @@ import {
88 } from "./models.ts";
99 import { getAvailableProviders, isOAuthProvider, loginOAuth } from "./oauth";
1010 import { DATA_DIR, SETTINGS_PATH } from "./shared.ts";
11+import { DEFAULT_TUI_THEME_ID } from "./themes.ts";
1112 import {
1213 type CliOptions,
1314 CliOptionsSchema,
@@ -62,7 +63,14 @@ async function getSettings(): Promise<Settings | undefined> {
6263 }
6364
6465 const jsonText = await file.text();
65- const settings = JSON.parse(jsonText) as unknown;
66+ let settings: unknown;
67+
68+ try {
69+ settings = JSON.parse(jsonText) as unknown;
70+ } catch (err) {
71+ const message = err instanceof Error ? err.message : String(err);
72+ throw new Error(`Invalid settings JSON: ${message}`);
73+ }
6674
6775 return parseSettings(settings, "settings");
6876 }
@@ -101,6 +109,7 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
101109 ? DEFAULT_MODEL_ID
102110 : getFirstModelConfig(settingsProvider, customProviders).id);
103111 const settingsEffort = settings?.effort ?? DEFAULT_EFFORT;
112+ const settingsTheme = settings?.theme ?? DEFAULT_TUI_THEME_ID;
104113 let provider: string = settingsProvider;
105114 let modelId = settingsModelId;
106115 let effort: string = settingsEffort;
@@ -225,6 +234,7 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
225234 effort: cliSettings.effort,
226235 prompt,
227236 customProviders,
237+ theme: settingsTheme,
228238 });
229239 const nextSettings = parseSettings(
230240 {
@@ -232,6 +242,7 @@ export async function handleArgv(argv: string[]): Promise<CliOptions> {
232242 model: options.model.id,
233243 effort: options.effort,
234244 customProviders,
245+ theme: options.theme,
235246 },
236247 "settings",
237248 );
src/error-handling.test.ts+163−0
@@ -0,0 +1,163 @@
1+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { runBashTool } from "./tool-bash.ts";
6+import { runEditTool } from "./tool-edit.ts";
7+import { runReadTool } from "./tool-read.ts";
8+import type { ToolRunnerEvent } from "./types.ts";
9+
10+const originalDataDir = Bun.env.MINI_CODER_DATA_DIR;
11+const testHome = await mkdtemp(join(tmpdir(), "mini-coder-errors-"));
12+const dataDir = join(testHome, "data");
13+Bun.env.MINI_CODER_DATA_DIR = dataDir;
14+
15+const sessionsDir = join(dataDir, "sessions");
16+const { handleArgv } = await import("./args.ts");
17+const { getAvailableProviders } = await import("./oauth.ts");
18+const { getSession, listSessionsForCwd } = await import("./session.ts");
19+
20+type ResultEvent = Extract<ToolRunnerEvent, { type: "result" }>;
21+
22+async function collectToolEvents(
23+ events: AsyncGenerator<ToolRunnerEvent>,
24+): Promise<ToolRunnerEvent[]> {
25+ const collected: ToolRunnerEvent[] = [];
26+
27+ for await (const event of events) {
28+ collected.push(event);
29+ }
30+
31+ return collected;
32+}
33+
34+function resultEvent(events: ToolRunnerEvent[]): ResultEvent {
35+ const result = events.findLast(
36+ (event): event is ResultEvent => event.type === "result",
37+ );
38+
39+ if (!result) {
40+ throw new Error("Tool did not yield a result");
41+ }
42+
43+ return result;
44+}
45+
46+async function toolResult(
47+ events: AsyncGenerator<ToolRunnerEvent>,
48+): Promise<ResultEvent> {
49+ return resultEvent(await collectToolEvents(events));
50+}
51+
52+beforeEach(async () => {
53+ await rm(dataDir, { recursive: true, force: true });
54+});
55+
56+afterAll(async () => {
57+ if (originalDataDir === undefined) {
58+ delete Bun.env.MINI_CODER_DATA_DIR;
59+ } else {
60+ Bun.env.MINI_CODER_DATA_DIR = originalDataDir;
61+ }
62+
63+ await rm(testHome, { recursive: true, force: true });
64+});
65+
66+describe("tool runner error handling", () => {
67+ test("read and edit report missing files as tool results", async () => {
68+ const missingPath = join(testHome, "missing.txt");
69+
70+ const readResult = await toolResult(runReadTool({ path: missingPath }));
71+ expect(readResult.text).toBe(`File not found: ${missingPath}`);
72+
73+ const editResult = await toolResult(
74+ runEditTool({ path: missingPath, oldText: "old", newText: "new" }),
75+ );
76+ expect(editResult.text).toBe(`File not found: ${missingPath}`);
77+ });
78+
79+ test("edit refuses unsafe writes and preserves the file", async () => {
80+ const path = join(testHome, "edit.txt");
81+ await writeFile(path, "one\none\n");
82+
83+ const ambiguous = await toolResult(
84+ runEditTool({ path, oldText: "one", newText: "two" }),
85+ );
86+ expect(ambiguous.text).toContain("Multiple matches found");
87+ expect(await Bun.file(path).text()).toBe("one\none\n");
88+
89+ const missing = await toolResult(
90+ runEditTool({ path, oldText: "missing", newText: "two" }),
91+ );
92+ expect(missing.text).toBe(`Old text not found in: ${path}`);
93+ expect(await Bun.file(path).text()).toBe("one\none\n");
94+
95+ const abortController = new AbortController();
96+ abortController.abort();
97+ await writeFile(path, "hello");
98+
99+ const aborted = await toolResult(
100+ runEditTool(
101+ { path, oldText: "hello", newText: "bye" },
102+ abortController.signal,
103+ ),
104+ );
105+ expect(aborted.text).toBe("Aborted before write.");
106+ expect(await Bun.file(path).text()).toBe("hello");
107+ });
108+
109+ test("bash reports non-zero exits instead of throwing", async () => {
110+ const result = await toolResult(
111+ runBashTool({ command: 'printf "bad"; exit 7' }),
112+ );
113+
114+ expect(result.text).toBe("bad\n\nExit code: 7");
115+ });
116+});
117+
118+describe("startup file error handling", () => {
119+ test("settings JSON parse failures are labelled", async () => {
120+ await mkdir(dataDir, { recursive: true });
121+ await writeFile(join(dataDir, "settings.json"), "{");
122+
123+ await expect(handleArgv([])).rejects.toThrow("Invalid settings JSON:");
124+ });
125+
126+ test("auth JSON parse failures are labelled", async () => {
127+ await mkdir(dataDir, { recursive: true });
128+ await writeFile(join(dataDir, "auth.json"), "{");
129+
130+ await expect(getAvailableProviders()).rejects.toThrow("Invalid auth JSON:");
131+ });
132+});
133+
134+describe("session file error handling", () => {
135+ test("listSessionsForCwd ignores missing dirs and bad session files", async () => {
136+ expect(await listSessionsForCwd()).toEqual([]);
137+
138+ await mkdir(sessionsDir, { recursive: true });
139+ await writeFile(join(sessionsDir, "broken.json"), "{");
140+ await writeFile(
141+ join(sessionsDir, "elsewhere.json"),
142+ JSON.stringify({ id: "elsewhere", cwd: "/elsewhere", messages: [] }),
143+ );
144+ await writeFile(
145+ join(sessionsDir, "ok.json"),
146+ JSON.stringify({
147+ id: "ok",
148+ cwd: process.cwd(),
149+ messages: [{ role: "user", content: "hi", timestamp: 2 }],
150+ }),
151+ );
152+
153+ const sessions = await listSessionsForCwd();
154+ expect(sessions.map((session) => session.id)).toEqual(["ok"]);
155+ });
156+
157+ test("getSession returns undefined for bad session files", async () => {
158+ await mkdir(sessionsDir, { recursive: true });
159+ await writeFile(join(sessionsDir, "broken.json"), "{");
160+
161+ expect(await getSession("broken")).toBeUndefined();
162+ });
163+});
src/headless.ts+1−0
@@ -39,6 +39,7 @@ export async function streamHeadless(
3939 };
4040
4141 const agent = streamAgent(ctx);
42+
4243 for await (const ev of agent) {
4344 switch (ev.type) {
4445 case "message_end":
src/index.ts+9−1
@@ -4,10 +4,18 @@ import { getBranchLabel } from "./git.ts";
44 import { streamHeadless } from "./headless.ts";
55 import { initTUI } from "./tui.ts";
66 import type { TUIState } from "./types.ts";
7+import { updateMiniCoder } from "./update.ts";
78
89 export async function main(): Promise<void> {
10+ const argv = process.argv.slice(2);
11+
12+ if (argv.includes("--update")) {
13+ await updateMiniCoder();
14+ return;
15+ }
16+
917 const cwd = basename(process.cwd());
10- const options = await handleArgv(process.argv.slice(2));
18+ const options = await handleArgv(argv);
1119
1220 function leave(msg?: string) {
1321 if (msg) console.log(msg);
src/oauth.ts+8−1
@@ -1,3 +1,4 @@
1+import { mkdir } from "node:fs/promises";
12 import readline from "node:readline";
23
34 import {
@@ -124,13 +125,19 @@ export async function getApiKey(options: CliOptions) {
124125 export async function readCreds(): Promise<SavedOAuthCreds> {
125126 const file = Bun.file(AUTH_FILE);
126127 if (await file.exists()) {
127- return JSON.parse(await file.text());
128+ try {
129+ return JSON.parse(await file.text());
130+ } catch (err) {
131+ const message = err instanceof Error ? err.message : String(err);
132+ throw new Error(`Invalid auth JSON: ${message}`);
133+ }
128134 }
129135
130136 return {};
131137 }
132138
133139 async function writeCreds(creds: SavedOAuthCreds) {
140+ await mkdir(DATA_DIR, { recursive: true });
134141 await Bun.write(AUTH_FILE, JSON.stringify(await mergeCreds(creds)));
135142 }
136143
src/prompt.ts+1−2
@@ -11,12 +11,11 @@ export const MAIN_PROMPT = `You are a coding agent interacting with users via th
1111 - Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without unnecessary superlatives, praise, or emotional validation.
1212 - User messages and Tool results may include <system-reminder> tags. These contain system-generated reminders and bear no direct relation to the specific tool result in which they appear.
1313 - You have access to bash, read and edit tools. Prefer using read and edit for file operations, use bash for finding read candidates or to run development commands.
14-- If a tool call fails or is denied, do NOT re-attempt the exact same call. Analyze why it failed and adjust your approach.
1514 - Use recent online information, the current environment, and your training data combined for a complete answer.
1615 - Ensure that you fulfill the user's expectation, requirements and contract **exactly**.
16+- Do not overstate what changed or what was verified. Summaries must match the diff.
1717 - Use temp directory for temp files, scripts, plan files, or anything that doesn't match the requested output.
1818 - Be concise. Use a professional colleague tone: direct, never condescending, and never rude.
19-- Do not overstate what changed or what was verified. Summaries must match the diff.
2019 `;
2120
2221 async function getDir() {
src/session.ts+9−6
@@ -9,7 +9,6 @@ export async function ensureSessionsDir(): Promise<void> {
99 await mkdir(SESSIONS_DIR, { recursive: true });
1010 }
1111
12-// readSession: writes the session
1312 export async function getSession(id: string): Promise<Session | undefined> {
1413 const file = Bun.file(join(SESSIONS_DIR, `${id}.json`));
1514
@@ -17,11 +16,16 @@ export async function getSession(id: string): Promise<Session | undefined> {
1716 return;
1817 }
1918
20- const sessionJson = await file.text();
21- const parsed = JSON.parse(sessionJson) as unknown;
22- const valid = Value.Check(SessionSchema, parsed);
19+ try {
20+ const sessionJson = await file.text();
21+ const parsed = JSON.parse(sessionJson) as unknown;
22+ const valid = Value.Check(SessionSchema, parsed);
23+
24+ if (valid) return parsed;
25+ } catch {
26+ return;
27+ }
2328
24- if (valid) return parsed;
2529 return;
2630 }
2731
@@ -65,7 +69,6 @@ export async function saveSession(s: Session) {
6569 await Bun.write(file, JSON.stringify(s));
6670 }
6771
68-// updateSession: finds and appends to the existing setting file
6972 export async function updateSession(id: string, messages: Message[]) {
7073 const existing = await getSession(id);
7174 if (existing) {
src/shared.ts+2−1
@@ -4,7 +4,8 @@ import { parseDocument } from "yaml";
44
55 // Mixed bag of helpers that can be shared across the codebase
66
7-export const DATA_DIR = join(homedir(), ".config", "mini-coder");
7+export const DATA_DIR =
8+ Bun.env.MINI_CODER_DATA_DIR ?? join(homedir(), ".config", "mini-coder");
89 export const SESSIONS_DIR = join(DATA_DIR, "sessions");
910 export const AUTH_PATH = join(DATA_DIR, "auth.json");
1011 export const SETTINGS_PATH = join(DATA_DIR, "settings.json");
src/themes.ts+234−0
@@ -0,0 +1,234 @@
1+import type { SyntaxHighlightTheme } from "@cel-tui/components";
2+import type { Color, Theme } from "@cel-tui/core";
3+
4+export const TUI_THEME_IDS = [
5+ "ansi16",
6+ "molokai-dark",
7+ "molokai-light",
8+] as const;
9+
10+export type TUIThemeId = (typeof TUI_THEME_IDS)[number];
11+
12+export interface TUIThemeDefinition {
13+ id: TUIThemeId;
14+ label: string;
15+ palette: Theme;
16+ syntax: SyntaxHighlightTheme;
17+ rootFgColor?: Color;
18+ rootBgColor?: Color;
19+ userMessageBgColor?: Color;
20+}
21+
22+const ANSI_SLOT_HEX: Record<Color, string> = {
23+ color00: "#000000",
24+ color01: "#cd3131",
25+ color02: "#0dbc79",
26+ color03: "#e5e510",
27+ color04: "#2472c8",
28+ color05: "#bc3fbc",
29+ color06: "#11a8cd",
30+ color07: "#e5e5e5",
31+ color08: "#666666",
32+ color09: "#f14c4c",
33+ color10: "#23d18b",
34+ color11: "#f5f543",
35+ color12: "#3b8eea",
36+ color13: "#d670d6",
37+ color14: "#29b8db",
38+ color15: "#ffffff",
39+};
40+
41+export const theme = {
42+ black: "color00",
43+ red: "color01",
44+ green: "color02",
45+ yellow: "color03",
46+ blue: "color04",
47+ magenta: "color05",
48+ cyan: "color06",
49+ white: "color07",
50+ bblack: "color08",
51+ bred: "color09",
52+ bgreen: "color10",
53+ byellow: "color11",
54+ bblue: "color12",
55+ bmagenta: "color13",
56+ bcyan: "color14",
57+ bwhite: "color15",
58+} as const satisfies Record<string, Color>;
59+
60+const ansi16Palette: Theme = {
61+ color00: 0,
62+ color01: 1,
63+ color02: 2,
64+ color03: 3,
65+ color04: 4,
66+ color05: 5,
67+ color06: 6,
68+ color07: 7,
69+ color08: 8,
70+ color09: 9,
71+ color10: 10,
72+ color11: 11,
73+ color12: 12,
74+ color13: 13,
75+ color14: 14,
76+ color15: 15,
77+};
78+
79+const molokaiDarkPalette: Theme = {
80+ color00: "#272822",
81+ color01: "#f92672",
82+ color02: "#a6e22e",
83+ color03: "#e6db74",
84+ color04: "#66d9ef",
85+ color05: "#f92672",
86+ color06: "#66d9ef",
87+ color07: "#f8f8f2",
88+ color08: "#6f705f",
89+ color09: "#ff6188",
90+ color10: "#a6e22e",
91+ color11: "#ffd866",
92+ color12: "#78dce8",
93+ color13: "#ae81ff",
94+ color14: "#66d9ef",
95+ color15: "#ffffff",
96+};
97+
98+const molokaiLightPalette: Theme = {
99+ color00: "#272822",
100+ color01: "#ff5f87",
101+ color02: "#8bcf26",
102+ color03: "#c7a100",
103+ color04: "#61aeee",
104+ color05: "#d16dff",
105+ color06: "#00a8b5",
106+ color07: "#f2efe4",
107+ color08: "#5f6060",
108+ color09: "#b0003a",
109+ color10: "#3f7d00",
110+ color11: "#725f00",
111+ color12: "#005f9f",
112+ color13: "#7f2caf",
113+ color14: "#007885",
114+ color15: "#fffdf5",
115+};
116+
117+const slotColor = (slot: Color) => ANSI_SLOT_HEX[slot];
118+
119+function syntaxScope(
120+ scope: string | readonly string[],
121+ foreground: Color,
122+ fontStyle?: string,
123+) {
124+ return {
125+ scope,
126+ settings: {
127+ foreground: slotColor(foreground),
128+ ...(fontStyle ? { fontStyle } : {}),
129+ },
130+ };
131+}
132+
133+const molokaiDarkSyntax = {
134+ name: "mini-coder-molokai-dark",
135+ type: "dark",
136+ fg: slotColor("color07"),
137+ tokenColors: [
138+ syntaxScope(["comment", "markup.quote"], "color08", "italic"),
139+ syntaxScope(["keyword", "operator"], "color05"),
140+ syntaxScope(["string", "escape", "markup.list"], "color03"),
141+ syntaxScope(["number", "regexp"], "color13"),
142+ syntaxScope(["function", "command", "markup.code"], "color10"),
143+ syntaxScope(["builtin", "property", "type", "meta"], "color06"),
144+ syntaxScope("markup.heading", "color04", "bold"),
145+ syntaxScope(["diff.deleted", "diff.file.old"], "color09"),
146+ syntaxScope(["diff.inserted", "diff.file.new"], "color10"),
147+ syntaxScope("diff.hunk", "color13"),
148+ syntaxScope(["diff.header", "diff.no-newline"], "color08"),
149+ ],
150+} as const satisfies SyntaxHighlightTheme;
151+
152+const molokaiLightSyntax = {
153+ name: "mini-coder-molokai-light",
154+ type: "light",
155+ fg: slotColor("color00"),
156+ tokenColors: [
157+ syntaxScope(["comment", "markup.quote"], "color08", "italic"),
158+ syntaxScope(["keyword", "operator"], "color13"),
159+ syntaxScope(["string", "escape", "markup.list"], "color11"),
160+ syntaxScope(["number", "regexp"], "color09"),
161+ syntaxScope(["function", "command", "markup.code"], "color10"),
162+ syntaxScope(["builtin", "property", "type", "meta"], "color14"),
163+ syntaxScope("markup.heading", "color12", "bold"),
164+ syntaxScope(["diff.deleted", "diff.file.old"], "color09"),
165+ syntaxScope(["diff.inserted", "diff.file.new"], "color10"),
166+ syntaxScope("diff.hunk", "color13"),
167+ syntaxScope(["diff.header", "diff.no-newline"], "color08"),
168+ ],
169+} as const satisfies SyntaxHighlightTheme;
170+
171+export const DEFAULT_TUI_THEME_ID: TUIThemeId = "ansi16";
172+
173+export const TUI_THEMES = {
174+ ansi16: {
175+ id: "ansi16",
176+ label: "ansi16",
177+ palette: ansi16Palette,
178+ syntax: "default",
179+ userMessageBgColor: theme.bblack,
180+ },
181+ "molokai-dark": {
182+ id: "molokai-dark",
183+ label: "molokai dark",
184+ palette: molokaiDarkPalette,
185+ syntax: molokaiDarkSyntax,
186+ rootFgColor: theme.bwhite,
187+ rootBgColor: theme.black,
188+ userMessageBgColor: theme.bblack,
189+ },
190+ "molokai-light": {
191+ id: "molokai-light",
192+ label: "molokai light",
193+ palette: molokaiLightPalette,
194+ syntax: molokaiLightSyntax,
195+ rootFgColor: theme.black,
196+ rootBgColor: theme.bwhite,
197+ userMessageBgColor: theme.white,
198+ },
199+} as const satisfies Record<TUIThemeId, TUIThemeDefinition>;
200+
201+export const activeTuiTheme: Theme = { ...ansi16Palette };
202+
203+export function applyTUITheme(id: TUIThemeId): void {
204+ Object.assign(activeTuiTheme, TUI_THEMES[id].palette);
205+}
206+
207+export function getTUITheme(id: TUIThemeId): TUIThemeDefinition {
208+ return TUI_THEMES[id];
209+}
210+
211+export function textColorForBackground(
212+ bgColor: Color,
213+ themeId: TUIThemeId,
214+): Color {
215+ if (bgColor === theme.bblack) return theme.bwhite;
216+
217+ if (
218+ themeId === "molokai-light" &&
219+ (
220+ [
221+ theme.bred,
222+ theme.bgreen,
223+ theme.byellow,
224+ theme.bblue,
225+ theme.bmagenta,
226+ theme.bcyan,
227+ ] as readonly Color[]
228+ ).includes(bgColor)
229+ ) {
230+ return theme.bwhite;
231+ }
232+
233+ return theme.black;
234+}
src/tool-bash.ts+1−4
@@ -66,10 +66,7 @@ export async function* runBashTool(
6666
6767 const exitCode = await proc.exited;
6868
69- let result = `${output.length ? output : "(no ouput)"}\n\nExit code: ${exitCode}`;
70- if (output.length) {
71- result += `${output}`;
72- }
69+ const result = `${output.length ? output : "(no output)"}\n\nExit code: ${exitCode}`;
7370
7471 yield {
7572 type: "result",
src/tui-components.ts+4−27
@@ -1,32 +1,9 @@
11 import { type Color, HStack, Text } from "@cel-tui/core";
22 import { onceEvery } from "./shared";
3+import { textColorForBackground, theme } from "./themes";
34 import type { TUIState } from "./types";
45
5-export const theme = {
6- black: "color00" as Color,
7- bblack: "color08" as Color,
8-
9- red: "color01" as Color,
10- bred: "color09" as Color,
11-
12- green: "color02" as Color,
13- bgreen: "color10" as Color,
14-
15- yellow: "color03" as Color,
16- byellow: "color11" as Color,
17-
18- blue: "color04" as Color,
19- bblue: "color12" as Color,
20-
21- magenta: "color05" as Color,
22- bmagenta: "color13" as Color,
23-
24- cyan: "color06" as Color,
25- bcyan: "color14" as Color,
26-
27- white: "color07" as Color,
28- bwhite: "color15" as Color,
29-};
6+export { theme };
307
318 export function TextPill(
329 content: string,
@@ -100,7 +77,7 @@ export function ActivityPill(state: TUIState, spinnerFrame: string) {
10077
10178 export function ContextPill(state: TUIState) {
10279 let text = "";
103- let bg = theme.bgreen;
80+ let bg: Color = theme.bgreen;
10481 if (!state.contextSize) {
10582 text = "0%";
10683 bg = theme.bwhite;
@@ -126,7 +103,7 @@ export function ContextPill(state: TUIState) {
126103
127104 text += ` (${state.options.model.contextWindow / 1000}k)`;
128105
129- return TextPill(text, theme.black, bg);
106+ return TextPill(text, textColorForBackground(bg, state.options.theme), bg);
130107 }
131108
132109 export function GitPill(state: TUIState) {
src/tui-conversation.ts+60−16
@@ -1,44 +1,71 @@
1-import { SyntaxHighlight } from "@cel-tui/components";
2-import { HStack, type Node, Text, VStack } from "@cel-tui/core";
1+import {
2+ SyntaxHighlight,
3+ type SyntaxHighlightTheme,
4+} from "@cel-tui/components";
5+import { type Color, HStack, type Node, Text, VStack } from "@cel-tui/core";
36 import { estimateTokens } from "./shared";
7+import { getTUITheme, textColorForBackground } from "./themes";
48 import { TextPill, theme } from "./tui-components";
59 import type { TUIMessage, TUIState, TUIToolCall } from "./types";
610
7-export function emptyState(): Node {
11+export function emptyState(state: TUIState): Node {
812 const randColor = theme.bgreen;
13+ const shortcutFgColor =
14+ state.options.theme === "ansi16"
15+ ? randColor
16+ : textColorForBackground(theme.bblack, state.options.theme);
17+ const updateNotice = state.availableUpdate
18+ ? [
19+ HStack({ gap: 1 }, [
20+ TextPill("update", shortcutFgColor, theme.bblack, 13),
21+ Text(
22+ `mini-coder ${state.availableUpdate.latestVersion} is available. Run mc --update.`,
23+ { fgColor: theme.bblack },
24+ ),
25+ ]),
26+ ]
27+ : [];
928 return HStack({ flex: 1, alignItems: "center" }, [
1029 VStack({ flex: 1, alignItems: "center", gap: 1 }, [
1130 HStack({ gap: 1 }, [
1231 Text("mini"),
13- TextPill("coder", theme.black, randColor),
32+ TextPill(
33+ "coder",
34+ textColorForBackground(randColor, state.options.theme),
35+ randColor,
36+ ),
1437 ]),
1538 VStack({ gap: 1 }, [
1639 HStack({ gap: 1 }, [
17- TextPill("/new", randColor, theme.bblack, 13),
40+ TextPill("/new", shortcutFgColor, theme.bblack, 13),
1841 Text("Start a new session from the input box.", {
1942 fgColor: theme.bblack,
2043 }),
2144 ]),
2245 HStack({ gap: 1 }, [
23- TextPill("ctrl+p", randColor, theme.bblack, 13),
46+ TextPill("ctrl+p", shortcutFgColor, theme.bblack, 13),
2447 Text("Menu for session history, and settings.", {
2548 fgColor: theme.bblack,
2649 }),
2750 ]),
2851 HStack({ gap: 1 }, [
29- TextPill("ESC", randColor, theme.bblack, 13),
52+ TextPill("ESC", shortcutFgColor, theme.bblack, 13),
3053 Text("Abort agent response.", { fgColor: theme.bblack }),
3154 ]),
3255 HStack({ gap: 1 }, [
33- TextPill("ctrl+c|d|q", randColor, theme.bblack, 13),
56+ TextPill("ctrl+c|d|q", shortcutFgColor, theme.bblack, 13),
3457 Text("Quit.", { fgColor: theme.bblack }),
3558 ]),
59+ ...updateNotice,
3660 ]),
3761 ]),
3862 ]);
3963 }
4064
41-function ConversationMessageToolCall(call: TUIToolCall) {
65+function ConversationMessageToolCall(
66+ call: TUIToolCall,
67+ syntaxTheme: SyntaxHighlightTheme,
68+) {
4269 let outputNode: Node | null = null;
4370
4471 // Compress read and bash calls
@@ -64,7 +91,7 @@ function ConversationMessageToolCall(call: TUIToolCall) {
6491
6592 outputNode = VStack({ width: "100%" }, blocks);
6693 } else if (call.tool === "edit") {
67- outputNode = SyntaxHighlight(call.output, "patch");
94+ outputNode = SyntaxHighlight(call.output, "patch", { theme: syntaxTheme });
6895 } else {
6996 outputNode = Text(call.output, { wrap: "word" });
7097 }
@@ -81,7 +108,7 @@ function ConversationMessageToolCall(call: TUIToolCall) {
81108
82109 // Syntax highlight bash args
83110 if (call.tool === "bash") {
84- node = SyntaxHighlight(String(value), "bash");
111+ node = SyntaxHighlight(String(value), "bash", { theme: syntaxTheme });
85112 return node;
86113 }
87114
@@ -99,7 +126,11 @@ function ConversationMessageToolCall(call: TUIToolCall) {
99126 ]);
100127 }
101128
102-function ConversationMessage(message: TUIMessage) {
129+function ConversationMessage(
130+ message: TUIMessage,
131+ syntaxTheme: SyntaxHighlightTheme,
132+ userMessageBgColor: Color | undefined,
133+) {
103134 const blocks: Node[] = [];
104135
105136 if (message.thinking) {
@@ -118,17 +149,22 @@ function ConversationMessage(message: TUIMessage) {
118149 VStack(
119150 {
120151 width: "100%",
121- bgColor: message.role === "user" ? theme.bblack : undefined,
152+ bgColor: message.role === "user" ? userMessageBgColor : undefined,
122153 padding: { y: 1, x: message.role === "user" ? 1 : 0 },
123154 },
124- [SyntaxHighlight(message.text, "markdown")],
155+ [SyntaxHighlight(message.text, "markdown", { theme: syntaxTheme })],
125156 ),
126157 );
127158 }
128159
129160 if (message.toolCalls?.length) {
130161 blocks.push(
131- VStack({ gap: 1 }, message.toolCalls.map(ConversationMessageToolCall)),
162+ VStack(
163+ { gap: 1 },
164+ message.toolCalls.map((call) =>
165+ ConversationMessageToolCall(call, syntaxTheme),
166+ ),
167+ ),
132168 );
133169 }
134170
@@ -158,6 +194,8 @@ function ConversationMessage(message: TUIMessage) {
158194 }
159195
160196 export function Conversation(state: TUIState) {
197+ const activeTheme = getTUITheme(state.options.theme);
198+
161199 return VStack(
162200 {
163201 flex: 1,
@@ -169,6 +207,12 @@ export function Conversation(state: TUIState) {
169207 state.stickToBottom = offset >= maxOffset;
170208 },
171209 },
172- state.tuiMessages.map(ConversationMessage),
210+ state.tuiMessages.map((message) =>
211+ ConversationMessage(
212+ message,
213+ activeTheme.syntax,
214+ activeTheme.userMessageBgColor,
215+ ),
216+ ),
173217 );
174218 }
src/tui-overlay.ts+46−1
@@ -6,6 +6,7 @@ import { findModelConfig, getProviderModels } from "./models.ts";
66 import { getAvailableProviders } from "./oauth";
77 import { listSessionsForCwd } from "./session";
88 import { estimateTokens, formatTimestamp } from "./shared";
9+import { applyTUITheme, getTUITheme, TUI_THEME_IDS } from "./themes";
910 import { TextPill, theme } from "./tui-components";
1011 import type { SelectOptions, SelectState, Session, TUIState } from "./types";
1112
@@ -332,12 +333,28 @@ export function mainMenu(state: TUIState, initialPane = "main") {
332333 })),
333334 });
Cut short: this commit's diff is over 1000 lines.
src/tui.ts+26−5
Cut short: this commit's diff is over 1000 lines.
src/types.ts+14−0
Cut short: this commit's diff is over 1000 lines.
src/update.ts+171−0
Cut short: this commit's diff is over 1000 lines.