config.ts 11 KB

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