Files
ThothII/backend/src/settings/settings-cli.ts
T

49 lines
2.0 KiB
TypeScript

/* Core-side, non-interactive installation-default writer used only through compose exec.
* It accepts no credentials and writes the same SETTINGS_FILE consumed by session creation. */
import { readFileSync } from "node:fs";
import { loadConfig } from "../config.js";
import {
captureSettingsSnapshot,
loadSettings,
restoreSettingsSnapshot,
saveSettings,
type Settings,
type SettingsSnapshot,
} from "./settings-store.js";
const choice = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
function value(args: string[], flag: string): string {
const at = args.indexOf(flag);
if (at < 0 || at + 1 >= args.length || args.filter((part) => part === flag).length !== 1) {
throw new Error(`missing ${flag}`);
}
return args[at + 1];
}
try {
const args = process.argv.slice(2);
const cfg = loadConfig(process.env);
if (args.length === 1 && args[0] === "--snapshot") {
process.stdout.write(`${JSON.stringify(captureSettingsSnapshot(cfg))}\n`);
} else if (args.length === 1 && args[0] === "--restore") {
const parsed = JSON.parse(readFileSync(0, "utf8")) as Partial<SettingsSnapshot>;
if (Object.keys(parsed).some((key) => key !== "exists" && key !== "rawBase64")) {
throw new Error("invalid settings snapshot");
}
restoreSettingsSnapshot(cfg, parsed as SettingsSnapshot);
} else {
if (args.length !== 6) throw new Error("only provider, model, and thinking may be configured");
const provider = value(args, "--provider");
const model = value(args, "--model");
const thinking = value(args, "--thinking");
if (!choice.test(provider) || !choice.test(model)) throw new Error("invalid provider or model");
if (!["low", "medium", "high"].includes(thinking)) throw new Error("invalid thinking level");
const next: Settings = { ...loadSettings(cfg), provider, model, thinking };
saveSettings(cfg, next);
}
} catch (error) {
process.stderr.write(`settings-cli: ${error instanceof Error ? error.message : "invalid configuration"}\n`);
process.exitCode = 2;
}