Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/config-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ import { join } from "node:path";

import type { AgentConfig } from "@opencode-ai/sdk";

import { log } from "./utils/logger";

/**
* Strip trailing commas from JSON strings to be lenient with hand-edited configs.
* Matches quoted strings first (and keeps them intact) so that commas inside
* string values like "hello, }" are never modified.
*/
function stripTrailingCommas(json: string): string {
return json.replace(/"(?:[^"\\]|\\.)*"|,\s*([\]}])/g, (match, bracket) => {
if (bracket === undefined) return match;
return bracket;
});
}

// Minimal type for provider validation - only what we need
export interface ProviderInfo {
id: string;
Expand All @@ -30,7 +44,7 @@ function loadOpencodeConfig(configDir?: string): OpencodeConfig | null {
try {
const configPath = join(baseDir, "opencode.json");
const content = readFileSync(configPath, "utf-8");
return JSON.parse(content) as OpencodeConfig;
return JSON.parse(stripTrailingCommas(content)) as OpencodeConfig;
} catch {
return null;
}
Expand Down Expand Up @@ -98,9 +112,21 @@ export async function loadMicodeConfig(configDir?: string): Promise<MicodeConfig
const baseDir = configDir ?? join(homedir(), ".config", "opencode");
const configPath = join(baseDir, "micode.json");

let content: string;
try {
const content = await readFile(configPath, "utf-8");
const parsed = JSON.parse(content) as Record<string, unknown>;
content = await readFile(configPath, "utf-8");
} catch (error: unknown) {
// File not found is expected and silent
if (error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
return null;
}
const message = error instanceof Error ? error.message : String(error);
log.warn("micode", `Failed to read micode.json: ${message}. Config overrides will be ignored.`);
return null;
}

try {
const parsed = JSON.parse(stripTrailingCommas(content)) as Record<string, unknown>;

const result: MicodeConfig = {};

Expand Down Expand Up @@ -160,7 +186,10 @@ export async function loadMicodeConfig(configDir?: string): Promise<MicodeConfig
}

return result;
} catch {
} catch (error: unknown) {
// File exists but failed to parse - warn the user
const message = error instanceof Error ? error.message : String(error);
log.warn("micode", `Failed to parse micode.json: ${message}. Config overrides will be ignored.`);
return null;
}
}
Expand All @@ -176,7 +205,7 @@ export function loadModelContextLimits(configDir?: string): Map<string, number>
try {
const configPath = join(baseDir, "opencode.json");
const content = readFileSync(configPath, "utf-8");
const config = JSON.parse(content) as {
const config = JSON.parse(stripTrailingCommas(content)) as {
provider?: Record<string, { models?: Record<string, { limit?: { context?: number } }> }>;
};

Expand Down
55 changes: 52 additions & 3 deletions tests/config-loader.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// tests/config-loader.test.ts
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
Expand Down Expand Up @@ -44,12 +44,61 @@ describe("config-loader", () => {
expect(config?.agents?.brainstormer?.temperature).toBe(0.5);
});

it("should return null for invalid JSON", async () => {
it("should return null and warn for invalid JSON", async () => {
const configPath = join(testConfigDir, "micode.json");
writeFileSync(configPath, "{ invalid json }");
writeFileSync(configPath, '{ "agents": BROKEN }');

const warnSpy = spyOn(console, "warn").mockImplementation(() => {});

const config = await loadMicodeConfig(testConfigDir);

expect(config).toBeNull();
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to parse micode.json"));

warnSpy.mockRestore();
});

it("should parse JSON with trailing commas", async () => {
const configPath = join(testConfigDir, "micode.json");
writeFileSync(
configPath,
`{
"agents": {
"commander": { "model": "openai/gpt-4o", },
"brainstormer": { "model": "anthropic/claude-opus-4-6", "temperature": 0.8, },
},
"compactionThreshold": 0.5,
}`,
);

const config = await loadMicodeConfig(testConfigDir);

expect(config).not.toBeNull();
expect(config?.agents?.commander?.model).toBe("openai/gpt-4o");
expect(config?.agents?.brainstormer?.model).toBe("anthropic/claude-opus-4-6");
expect(config?.agents?.brainstormer?.temperature).toBe(0.8);
expect(config?.compactionThreshold).toBe(0.5);
});

it("should not corrupt string values containing commas and brackets", async () => {
const configPath = join(testConfigDir, "micode.json");
writeFileSync(
configPath,
JSON.stringify({
fragments: {
brainstormer: ["hello, }", "keep this, ]too", 'escaped \\" comma, }'],
},
}),
);

const config = await loadMicodeConfig(testConfigDir);

expect(config).not.toBeNull();
expect(config?.fragments?.brainstormer).toEqual([
"hello, }",
"keep this, ]too",
'escaped \\" comma, }',
]);
});

it("should handle empty agents object", async () => {
Expand Down