config.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { Command } from "commander";
  2. import { readFile, writeFile, mkdir } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { findProjectRoot, log, logError, GLOBAL_CONFIG_DIR, GLOBAL_ENV_PATH } from "../utils.js";
  5. export const configCommand = new Command("config")
  6. .description("Manage project configuration");
  7. configCommand
  8. .command("set")
  9. .description("Set a configuration value")
  10. .argument("<key>", "Config key (e.g., llm.apiKey)")
  11. .argument("<value>", "Config value")
  12. .action(async (key: string, value: string) => {
  13. const root = findProjectRoot();
  14. const configPath = join(root, "inkos.json");
  15. try {
  16. const raw = await readFile(configPath, "utf-8");
  17. const config = JSON.parse(raw);
  18. const keys = key.split(".");
  19. const KNOWN_KEYS = new Set([
  20. "llm.provider", "llm.baseUrl", "llm.model", "llm.temperature",
  21. "llm.maxTokens", "llm.thinkingBudget", "llm.reasoningEffort", "llm.apiFormat", "llm.stream",
  22. "daemon.schedule.radarCron", "daemon.schedule.writeCron",
  23. "daemon.maxConcurrentBooks", "daemon.chaptersPerCycle",
  24. "daemon.retryDelayMs", "daemon.cooldownAfterChapterMs",
  25. "daemon.maxChaptersPerDay",
  26. ]);
  27. if (!KNOWN_KEYS.has(key)) {
  28. // Find closest match by edit distance on the last segment
  29. const candidates = [...KNOWN_KEYS];
  30. const inputParts = key.split(".");
  31. const samePrefixCandidates = candidates.filter(k => {
  32. const parts = k.split(".");
  33. return parts.length === inputParts.length && parts.slice(0, -1).join(".") === inputParts.slice(0, -1).join(".");
  34. });
  35. const editDist = (a: string, b: string): number => {
  36. const m = a.length, n = b.length;
  37. const dp = Array.from({ length: m + 1 }, (_, i) => Array.from({ length: n + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
  38. for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)
  39. dp[i]![j] = Math.min(dp[i-1]![j]! + 1, dp[i]![j-1]! + 1, dp[i-1]![j-1]! + (a[i-1] !== b[j-1] ? 1 : 0));
  40. return dp[m]![n]!;
  41. };
  42. const inputLast = inputParts[inputParts.length - 1]!;
  43. const suggestion = samePrefixCandidates
  44. .map(k => ({ k, d: editDist(k.split(".").pop()!, inputLast) }))
  45. .sort((a, b) => a.d - b.d)
  46. .find(x => x.d <= 3)?.k;
  47. logError(`Unknown config key "${key}".${suggestion ? ` Did you mean "${suggestion}"?` : ""}`);
  48. log(`Known keys: ${candidates.join(", ")}`);
  49. process.exit(1);
  50. }
  51. let target = config;
  52. for (let i = 0; i < keys.length - 1; i++) {
  53. const k = keys[i]!;
  54. if (!(k in target)) {
  55. target[k] = {};
  56. }
  57. target = target[k];
  58. }
  59. const finalKey = keys[keys.length - 1]!;
  60. // Auto-coerce types: numbers and booleans shouldn't be stored as strings
  61. if (/^\d+(\.\d+)?$/.test(value)) {
  62. target[finalKey] = parseFloat(value);
  63. } else if (value === "true") {
  64. target[finalKey] = true;
  65. } else if (value === "false") {
  66. target[finalKey] = false;
  67. } else {
  68. target[finalKey] = value;
  69. }
  70. await writeFile(configPath, JSON.stringify(config, null, 2), "utf-8");
  71. log(`Set ${key} = ${value}`);
  72. } catch (e) {
  73. logError(`Failed to update config: ${e}`);
  74. process.exit(1);
  75. }
  76. });
  77. configCommand
  78. .command("set-global")
  79. .description("Set global LLM config (~/.inkos/.env), shared by all projects")
  80. .requiredOption("--provider <provider>", "LLM provider (openai / anthropic)")
  81. .requiredOption("--base-url <url>", "API base URL")
  82. .requiredOption("--api-key <key>", "API key")
  83. .requiredOption("--model <model>", "Model name")
  84. .option("--temperature <n>", "Temperature")
  85. .option("--max-tokens <n>", "Max output tokens")
  86. .option("--thinking-budget <n>", "Anthropic thinking budget")
  87. .option("--api-format <format>", "API format (chat / responses)")
  88. .option("--lang <language>", "Default writing language: zh (Chinese) or en (English)")
  89. .action(async (opts) => {
  90. try {
  91. await mkdir(GLOBAL_CONFIG_DIR, { recursive: true });
  92. const lines = [
  93. "# InkOS Global LLM Configuration",
  94. `INKOS_LLM_PROVIDER=${opts.provider}`,
  95. `INKOS_LLM_BASE_URL=${opts.baseUrl}`,
  96. `INKOS_LLM_API_KEY=${opts.apiKey}`,
  97. `INKOS_LLM_MODEL=${opts.model}`,
  98. ];
  99. if (opts.temperature) lines.push(`INKOS_LLM_TEMPERATURE=${opts.temperature}`);
  100. if (opts.maxTokens) lines.push(`INKOS_LLM_MAX_TOKENS=${opts.maxTokens}`);
  101. if (opts.thinkingBudget) lines.push(`INKOS_LLM_THINKING_BUDGET=${opts.thinkingBudget}`);
  102. if (opts.apiFormat) lines.push(`INKOS_LLM_API_FORMAT=${opts.apiFormat}`);
  103. if (opts.lang) lines.push(`INKOS_DEFAULT_LANGUAGE=${opts.lang}`);
  104. await writeFile(GLOBAL_ENV_PATH, lines.join("\n") + "\n", "utf-8");
  105. log(`Global config saved to ${GLOBAL_ENV_PATH}`);
  106. log("All projects will use this config unless overridden by project .env");
  107. } catch (e) {
  108. logError(`Failed to set global config: ${e}`);
  109. process.exit(1);
  110. }
  111. });
  112. configCommand
  113. .command("show-global")
  114. .description("Show global LLM config (~/.inkos/.env)")
  115. .action(async () => {
  116. try {
  117. const content = await readFile(GLOBAL_ENV_PATH, "utf-8");
  118. const masked = content.replace(
  119. /(INKOS_LLM_API_KEY=)(.{8})(.*)(.{4})/,
  120. "$1$2...$4",
  121. );
  122. log(masked);
  123. } catch {
  124. log("No global config found. Run 'inkos config set-global' to create one.");
  125. }
  126. });
  127. configCommand
  128. .command("show")
  129. .description("Show current project configuration")
  130. .action(async () => {
  131. const root = findProjectRoot();
  132. const configPath = join(root, "inkos.json");
  133. try {
  134. const raw = await readFile(configPath, "utf-8");
  135. const config = JSON.parse(raw);
  136. // Mask API key
  137. if (config.llm?.apiKey) {
  138. const key = config.llm.apiKey;
  139. config.llm.apiKey = key.slice(0, 8) + "..." + key.slice(-4);
  140. }
  141. log(JSON.stringify(config, null, 2));
  142. } catch (e) {
  143. logError(`Failed to read config: ${e}`);
  144. process.exit(1);
  145. }
  146. });
  147. const KNOWN_AGENTS = ["writer", "auditor", "reviser", "architect", "radar", "chapter-analyzer"] as const;
  148. configCommand
  149. .command("set-model")
  150. .description("Set model override for a specific agent (with optional provider routing)")
  151. .argument("<agent>", `Agent name (${KNOWN_AGENTS.join(", ")})`)
  152. .argument("<model>", "Model name (e.g., gpt-4o, gemini-2.5-flash)")
  153. .option("--base-url <url>", "API base URL (for different provider)")
  154. .option("--provider <provider>", "Provider type (openai / anthropic / custom)")
  155. .option("--api-key-env <envVar>", "Env variable name for API key (e.g., PACKYAPI_KEY)")
  156. .option("--stream", "Enable streaming (default)")
  157. .option("--no-stream", "Disable streaming")
  158. .action(async (agent: string, model: string, opts: { baseUrl?: string; provider?: string; apiKeyEnv?: string; stream?: boolean }) => {
  159. if (!KNOWN_AGENTS.includes(agent as typeof KNOWN_AGENTS[number])) {
  160. logError(`Unknown agent "${agent}". Valid agents: ${KNOWN_AGENTS.join(", ")}`);
  161. process.exit(1);
  162. }
  163. const root = findProjectRoot();
  164. const configPath = join(root, "inkos.json");
  165. try {
  166. const raw = await readFile(configPath, "utf-8");
  167. const config = JSON.parse(raw);
  168. const overrides = config.modelOverrides ?? {};
  169. const hasProviderOpts = opts.baseUrl || opts.provider || opts.apiKeyEnv || opts.stream === false;
  170. if (hasProviderOpts) {
  171. const override: Record<string, unknown> = { model };
  172. if (opts.baseUrl) override.baseUrl = opts.baseUrl;
  173. if (opts.provider) override.provider = opts.provider;
  174. if (opts.apiKeyEnv) override.apiKeyEnv = opts.apiKeyEnv;
  175. if (opts.stream === false) override.stream = false;
  176. config.modelOverrides = { ...overrides, [agent]: override };
  177. } else {
  178. config.modelOverrides = { ...overrides, [agent]: model };
  179. }
  180. await writeFile(configPath, JSON.stringify(config, null, 2), "utf-8");
  181. log(`Model override: ${agent} → ${model}${opts.baseUrl ? ` (${opts.baseUrl})` : ""}`);
  182. } catch (e) {
  183. logError(`Failed to update config: ${e}`);
  184. process.exit(1);
  185. }
  186. });
  187. configCommand
  188. .command("remove-model")
  189. .description("Remove model override for a specific agent (falls back to default)")
  190. .argument("<agent>", "Agent name")
  191. .action(async (agent: string) => {
  192. const root = findProjectRoot();
  193. const configPath = join(root, "inkos.json");
  194. try {
  195. const raw = await readFile(configPath, "utf-8");
  196. const config = JSON.parse(raw);
  197. const overrides = config.modelOverrides;
  198. if (!overrides || !(agent in overrides)) {
  199. log(`No model override for "${agent}".`);
  200. return;
  201. }
  202. const { [agent]: _, ...rest } = overrides;
  203. config.modelOverrides = Object.keys(rest).length > 0 ? rest : undefined;
  204. await writeFile(configPath, JSON.stringify(config, null, 2), "utf-8");
  205. log(`Removed model override for ${agent}. Will use default model.`);
  206. } catch (e) {
  207. logError(`Failed to update config: ${e}`);
  208. process.exit(1);
  209. }
  210. });
  211. configCommand
  212. .command("show-models")
  213. .description("Show model routing for all agents")
  214. .option("--json", "Output JSON")
  215. .action(async (opts) => {
  216. const root = findProjectRoot();
  217. const configPath = join(root, "inkos.json");
  218. try {
  219. const raw = await readFile(configPath, "utf-8");
  220. const config = JSON.parse(raw);
  221. const defaultModel = config.llm?.model ?? "(not set)";
  222. const overrides: Record<string, unknown> = config.modelOverrides ?? {};
  223. if (opts.json) {
  224. log(JSON.stringify({ defaultModel, overrides }, null, 2));
  225. return;
  226. }
  227. log(`Default model: ${defaultModel}\n`);
  228. if (Object.keys(overrides).length === 0) {
  229. log("No agent-specific overrides. All agents use the default model.");
  230. return;
  231. }
  232. log("Agent overrides:");
  233. for (const [agent, value] of Object.entries(overrides)) {
  234. if (typeof value === "string") {
  235. log(` ${agent} → ${value}`);
  236. } else {
  237. const o = value as Record<string, unknown>;
  238. const parts = [o.model as string];
  239. if (o.baseUrl) parts.push(`@ ${o.baseUrl}`);
  240. if (o.stream === false) parts.push("[no-stream]");
  241. log(` ${agent} → ${parts.join(" ")}`);
  242. }
  243. }
  244. log("");
  245. const usingDefault = KNOWN_AGENTS.filter((a) => !(a in overrides));
  246. if (usingDefault.length > 0) {
  247. log(`Using default: ${usingDefault.join(", ")}`);
  248. }
  249. } catch (e) {
  250. logError(`Failed to read config: ${e}`);
  251. process.exit(1);
  252. }
  253. });