Skip to content
Open
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
76 changes: 75 additions & 1 deletion apps/desktop/electron/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ export async function upsertCodexConfig(
`${escapeRegExp(ROOT_START)}[\\s\\S]*?${escapeRegExp(ROOT_END)}\\n?`,
"g",
);
const clean = original.replace(managedPattern, "").replace(rootPattern, "").trim();
const unmanaged = original.replace(managedPattern, "").replace(rootPattern, "");
// The managed root block sets `model_provider` and `model`. TOML rejects a
// repeated key, so an existing root assignment of either must go first.
const clean = (setDefault ? withoutRootModelKeys(unmanaged) : unmanaged).trim();
const rootDefaults = setDefault
? `${ROOT_START}\nmodel_provider = "clawrouter"\nmodel = "${tomlString(model)}"\n${ROOT_END}\n\n`
: "";
Expand Down Expand Up @@ -257,6 +260,77 @@ function tomlString(value: string): string {
.replaceAll("\r", "\\r");
}

/**
* Drop root-level `model` and `model_provider` lines: everything before the first table header.
* Lines inside a multi-line string or array belong to a value, so they are never read as keys or headers.
*/
function withoutRootModelKeys(toml: string): string {
let inRoot = true;
let dropping = false;
let multiline = ""; // the open `"""` or `'''`
let depth = 0; // open `[` and `{` of a value that spans lines
const kept: string[] = [];
for (const line of toml.split("\n")) {
if (!multiline && depth === 0) {
if (/^\s*\[\[?(?:[^\]"']|"(?:[^"\\]|\\.)*"|'[^']*')+\]\]?\s*(#.*)?\r?$/.test(line))
inRoot = false;
const key = /^\s*("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_-]+)\s*=/.exec(line);
dropping = inRoot && !!key && ["model", "model_provider"].includes(tomlKey(key[1]));
}
for (let i = 0; i < line.length;) {
if (multiline) {
if (multiline === '"""' && line[i] === "\\") {
i += 2;
} else if (line.startsWith(multiline, i)) {
for (i += 3; line[i] === multiline[0]; i++);
multiline = "";
} else {
i++;
}
} else if (line[i] === "#") {
break;
} else if (line.startsWith('"""', i) || line.startsWith("'''", i)) {
multiline = line.slice(i, i + 3);
i += 3;
} else if (line[i] === '"') {
for (i++; i < line.length && line[i] !== '"'; i += line[i] === "\\" ? 2 : 1);
i++;
} else if (line[i] === "'") {
const end = line.indexOf("'", i + 1);
i = end < 0 ? line.length : end + 1;
} else {
if (line[i] === "[" || line[i] === "{") depth++;
if (line[i] === "]" || line[i] === "}") depth = Math.max(0, depth - 1);
i++;
}
}
if (!dropping) kept.push(line);
}
return kept.join("\n");
}

/** The name a TOML key spells. A quoted key has its escapes decoded, so "mod\u0065l" is model. */
function tomlKey(raw: string): string {
if (raw.startsWith("'")) return raw.slice(1, -1);
if (!raw.startsWith('"')) return raw;
const simple: Record<string, string> = {
b: "\b",
t: "\t",
n: "\n",
f: "\f",
r: "\r",
'"': '"',
"\\": "\\",
};
return raw.slice(1, -1).replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (all, e: string) => {
if (e.length > 1) {
const code = parseInt(e.slice(1), 16);
return code <= 0x10ffff ? String.fromCodePoint(code) : all;
}
return simple[e] ?? all;
});
}

function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
103 changes: 103 additions & 0 deletions apps/desktop/tests/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,109 @@ describe("agent configuration writers", () => {
expect(result).toContain("[profiles.clawrouter]");
});

it("replaces an existing root model and model_provider instead of repeating the key", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
await writeFile(
path,
[
'model = "gpt-5-codex"',
'model_provider = "openai"',
'model_reasoning_effort = "high"',
"",
"[profiles.fast]",
'model = "o3"',
"",
].join("\n"),
);

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", true);
const result = await readFile(path, "utf8");

expect(result.match(/^model = /gm)).toHaveLength(3);
expect(result.match(/^model_provider = /gm)).toHaveLength(2);
expect(result).toContain('model_reasoning_effort = "high"');
expect(result).toContain('model = "o3"');
expect(result).not.toContain("gpt-5-codex");
});

it("keeps multi-line strings and arrays that hold model-looking lines", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
const user = [
'developer_instructions = """',
'model = "inside a basic string"',
"[fake]",
'"""',
"notes = '''",
'model_provider = "inside a literal string"',
"'''",
"matrix = [",
" [1],",
" [2]",
"]",
].join("\n");
await writeFile(path, `${user}\nmodel = "gpt-5-codex"\n\n[profiles.fast]\nmodel = "o3"\n`);

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", true);
const result = await readFile(path, "utf8");

expect(result).toContain(user);
expect(result).not.toContain("gpt-5-codex");
expect(result).toContain('model = "o3"');
});

it("reads a quoted table header that holds an escaped quote", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
const user = '[profiles."a\\"b"]\nmodel = "o3"\nmodel_provider = "openai"';
await writeFile(path, `model = "gpt-5-codex"\n\n${user}\n`);

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", true);
const result = await readFile(path, "utf8");

expect(result).toContain(user);
expect(result).not.toContain("gpt-5-codex");
});

it("decodes escapes in a quoted root key", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
await writeFile(
path,
'"mod\\u0065l" = "gpt-5-codex"\n"model_provider" = "openai"\n"my\\u0020model" = "keep"\n',
);

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", true);
const result = await readFile(path, "utf8");

expect(result).not.toContain("gpt-5-codex");
expect(result).not.toContain('"openai"');
expect(result).toContain('"my\\u0020model" = "keep"');
});

it("drops a root model value that spans several lines", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
await writeFile(path, 'model = """\nold\n"""\nmodel_reasoning_effort = "high"\n');

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", true);
const result = await readFile(path, "utf8");

expect(result).not.toContain("old");
expect(result).toContain('model_reasoning_effort = "high"');
});

it("leaves an existing root model alone when no default is requested", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
await writeFile(path, 'model = "gpt-5-codex"\n');

await upsertCodexConfig(path, "http://127.0.0.1:8403/v1", "blockrun/auto", false);

expect(await readFile(path, "utf8")).toContain('model = "gpt-5-codex"');
});

it("escapes control characters instead of allowing TOML line injection", async () => {
const root = await mkdtemp(join(tmpdir(), "clawrouter-codex-"));
const path = join(root, "config.toml");
Expand Down
Loading