import { describe, expect, it } from "vitest"; import { ConfigScope, DefaultRuntimeConfig } from "@zcode/contracts"; import { createConfig, updateCodingPlanProviderInFileConfig, updateModelSelectionInFileConfig, updateUiLocaleInFileConfig, } from "../src/config/index.js"; import { parseEnvConfig } from "../src/config/env-config.adapter.js"; import { addSuppressedBuiltinInFileConfig, loadFileConfig, removePluginFromFileConfig, removeSuppressedBuiltinInFileConfig, updatePluginEnabledInFileConfig, updatePluginOptionsInFileConfig, } from "../src/config/file-config.adapter.js"; import { ModelCatalogService } from "../src/model/catalog.js"; import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; describe("config adapters", () => { it("migrates the legacy official CUA plugin id to the canonical id", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-identity-")); const configPath = join(dir, "config.json"); try { await writeFile( configPath, JSON.stringify({ plugins: { enabledPlugins: { "zcode-cua@zcode-plugins-official": true, "computer-use@zcode-plugins-official": false, }, suppressedBuiltins: [ "zcode-cua@zcode-plugins-official", "computer-use@zcode-plugins-official", ], options: { "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" }, "computer-use@zcode-plugins-official": { apiKey: "canonical-key" }, }, }, }), ); const loaded = loadFileConfig(configPath); expect(loaded.config.plugins?.enabledPlugins).toEqual({ "computer-use@zcode-plugins-official": false, }); expect(loaded.config.plugins?.suppressedBuiltins).toEqual([ "computer-use@zcode-plugins-official", ]); expect(loaded.config.plugins?.options).toEqual({ "computer-use@zcode-plugins-official": { apiKey: "canonical-key" }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("persists the canonical CUA plugin id while loading legacy config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-writeback-")); const path = join(dir, "config.json"); await writeFile( path, JSON.stringify({ plugins: { enabledPlugins: { "zcode-cua@zcode-plugins-official": true }, suppressedBuiltins: ["zcode-cua@zcode-plugins-official"], options: { "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" }, }, }, }), ); loadFileConfig(path); expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ plugins: { enabledPlugins: { "computer-use@zcode-plugins-official": true }, suppressedBuiltins: ["computer-use@zcode-plugins-official"], options: { "computer-use@zcode-plugins-official": { apiKey: "legacy-key" }, }, }, }); await rm(dir, { recursive: true, force: true }); }); it("writes canonical CUA ids when removing legacy config entries", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-write-migration-")); const configPath = join(dir, "config.json"); try { await writeFile( configPath, JSON.stringify({ plugins: { enabledPlugins: { "zcode-cua@zcode-plugins-official": true }, suppressedBuiltins: ["zcode-cua@zcode-plugins-official"], }, }), ); expect( ( await removeSuppressedBuiltinInFileConfig( configPath, "computer-use@zcode-plugins-official", ) ).suppressed, ).toBe(false); expect( ( await removePluginFromFileConfig(configPath, "computer-use@zcode-plugins-official") ).removedEnabled, ).toBe(true); expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({ plugins: { enabledPlugins: {}, suppressedBuiltins: [] }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("clears only explicitly selected Plugin option keys", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-option-clear-")); const configPath = join(dir, "config.json"); const pluginId = "secret-plugin@fixture"; try { await writeFile( configPath, JSON.stringify({ plugins: { enabledPlugins: { [pluginId]: true }, options: { [pluginId]: { token: "secret", region: "us-east-1", }, }, }, }), ); await updatePluginOptionsInFileConfig(configPath, pluginId, { region: "eu-west-1" }, [ "token", ]); expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({ plugins: { enabledPlugins: { [pluginId]: true }, options: { [pluginId]: { region: "eu-west-1", }, }, }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("deep merges Workspace Plugin enablement and options over User config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-plugins-")); const userPath = join(dir, "user.json"); const workspacePath = join(dir, ".zcode", "config.json"); try { await mkdir(join(dir, ".zcode"), { recursive: true }); await writeFile( userPath, JSON.stringify({ plugins: { dirs: [join(dir, "user-plugin")], enabledPlugins: { "workspace-plugin@fixture": true, "user-only@fixture": true, }, options: { "workspace-plugin@fixture": { inherited: "user", overridden: "user", }, }, }, }), ); await writeFile( workspacePath, JSON.stringify({ plugins: { enabledPlugins: { "workspace-plugin@fixture": false, }, options: { "workspace-plugin@fixture": { overridden: "workspace", workspaceOnly: true, }, }, }, }), ); const result = createConfig({ env: {}, userConfigPath: userPath, projectConfigPath: workspacePath, workingDirectory: dir, }); expect(result.config.plugins.enabledPlugins).toEqual({ "workspace-plugin@fixture": false, "user-only@fixture": true, }); expect(result.config.plugins.options).toEqual({ "workspace-plugin@fixture": { inherited: "user", overridden: "workspace", workspaceOnly: true, }, }); expect(result.sources.project.paths).toEqual([workspacePath]); expect(result.sources.plugins.enabled).toEqual({ "user-only@fixture": "user", "workspace-plugin@fixture": "workspace", }); expect(result.sources.plugins.dirs).toEqual({ user: [join(dir, "user-plugin")], workspace: [], }); expect(result.config.plugins.dirs).toEqual([join(dir, "user-plugin")]); expect(result.sources.plugins.options).toEqual({ "workspace-plugin@fixture": { inherited: "user", overridden: "workspace", workspaceOnly: "workspace", }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps Marketplace declarations in the User config layer", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-marketplaces-")); const userPath = join(dir, "user.json"); const workspacePath = join(dir, "workspace.json"); try { await writeFile( userPath, JSON.stringify({ plugins: { extraKnownMarketplaces: { "shared-market": { source: { source: "github", repo: "example/user-market" }, }, "user-market": { source: { source: "url", url: "https://example.test/user-market.json" }, }, }, }, }), ); await writeFile( workspacePath, JSON.stringify({ plugins: { extraKnownMarketplaces: { "shared-market": { source: { source: "directory", path: "./workspace-market" }, }, "workspace-market": { source: { source: "file", path: "./workspace-market.json" }, }, }, }, }), ); const result = createConfig({ env: {}, userConfigPath: userPath, projectConfigPath: workspacePath, }); expect(result.config.plugins.extraKnownMarketplaces).toEqual({ "shared-market": { source: { source: "github", repo: "example/user-market" }, }, "user-market": { source: { source: "url", url: "https://example.test/user-market.json" }, }, }); expect(result.sources.plugins.marketplaces).toEqual({ "shared-market": "user", "user-market": "user", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps Plugin scope priority aligned with User then Workspace", () => { expect(ConfigScope.User).toBe("user"); expect(ConfigScope.Project).toBe("project"); }); it("parses the supported ZCODE environment surface", () => { const config = parseEnvConfig({ ZCODE_STORAGE_DIR: "/tmp/zcode", ZCODE_HTTP_PROXY: "http://127.0.0.1:7890", ZCODE_NO_PROXY: "localhost,127.0.0.1", ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem", ZCODE_HTTP_TIMEOUT: "1234", ZCODE_LOCALE: "zh-CN", ZCODE_LOG_FORMAT: "json", }); expect(config.model).toBeUndefined(); expect(config.storage?.dir).toBe("/tmp/zcode"); expect(config.network?.httpProxy).toBe("http://127.0.0.1:7890"); expect(config.network?.noProxy).toBe("localhost,127.0.0.1"); expect(config.network?.caCertFile).toBe("/tmp/zcode-ca.pem"); expect(config.network?.timeout).toBe(1234); expect(config.ui).toBeUndefined(); expect(config.logging?.format).toBe("json"); expect(config.logging?.level).toBeUndefined(); }); it("defaults the session database to db/db.sqlite", () => { const result = createConfig({ env: {}, skipUserConfig: true }); expect(result.config.model).toBeUndefined(); expect(DefaultRuntimeConfig.storage.sessionDbPath).toBe("~/.zcode/cli/db/db.sqlite"); expect(result.config.storage.sessionDbPath).toBe("~/.zcode/cli/db/db.sqlite"); }); it("defaults model stream idle timeout to ten minutes", () => { const result = createConfig({ env: {}, skipUserConfig: true }); expect(DefaultRuntimeConfig.modelStream.idleTimeoutMs).toBe(600_000); expect(result.config.modelStream.idleTimeoutMs).toBe(600_000); }); it("defaults the supported memory switches to enabled", () => { const result = createConfig({ env: {}, skipUserConfig: true }); expect(result.config.features.memory).toBe(true); expect(result.config.memory).toEqual({ use: true, }); }); it("loads the supported memory config fields", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ memory: { use: false, }, }), ); const loaded = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(loaded.loaded).toBe(true); expect(loaded.config.memory).toEqual({ use: false, }); expect(merged.config.memory).toEqual({ use: false, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("parses session database path environment overrides", () => { expect( parseEnvConfig({ ZCODE_SESSION_DB_PATH: "/tmp/zcode/db/db.sqlite", }).storage?.sessionDbPath, ).toBe("/tmp/zcode/db/db.sqlite"); expect( parseEnvConfig({ ZCODE_SESSION_DB: "/tmp/zcode/legacy.sqlite", }).storage?.sessionDbPath, ).toBe("/tmp/zcode/legacy.sqlite"); }); it("loads no-proxy rules from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ network: { httpProxy: "http://127.0.0.1:7890", noProxy: "localhost,127.0.0.1", caCertFile: "/tmp/zcode-ca.pem", }, }), ); const merged = createConfig({ env: {}, userConfigPath: path }); expect(merged.config.network.httpProxy).toBe("http://127.0.0.1:7890"); expect(merged.config.network.noProxy).toBe("localhost,127.0.0.1"); expect(merged.config.network.caCertFile).toBe("/tmp/zcode-ca.pem"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("ignores undeclared ZCODE environment switches", () => { const config = parseEnvConfig({ ZCODE_LOG_LEVEL: "debug", ZCODE_UNDECLARED_FLAG: "1", }); expect(config).toEqual({}); }); it("loads yolo mode from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ permission: { mode: "yolo" } })); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.permission?.mode).toBe("yolo"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads edit mode from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ permission: { mode: "edit" } })); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.permission?.mode).toBe("edit"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads skill/command enable overrides from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ skill: { "/abs/skills/demo/SKILL.md": { enable: false } }, command: { "/abs/commands/demo.md": { enable: false } }, }), ); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); // JSON 的 skill/command 字段映射到 runtime 的 skillOverrides/commandOverrides expect(result.config.skillOverrides?.["/abs/skills/demo/SKILL.md"]?.enable).toBe(false); expect(result.config.commandOverrides?.["/abs/commands/demo.md"]?.enable).toBe(false); expect(merged.config.skillOverrides["/abs/skills/demo/SKILL.md"]?.enable).toBe(false); expect(merged.config.commandOverrides["/abs/commands/demo.md"]?.enable).toBe(false); } finally { await rm(dir, { force: true, recursive: true }); } }); it("parses plugins.suppressedBuiltins as a string array", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppressed-")); const path = join(dir, "config.json"); await writeFile( path, JSON.stringify({ plugins: { suppressedBuiltins: ["skill-creator@zcode-plugins-official"] } }), ); const loaded = loadFileConfig(path); expect(loaded.config.plugins.suppressedBuiltins).toEqual([ "skill-creator@zcode-plugins-official", ]); }); it("maps skills path enable entries to skill overrides", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ skills: { enabled: true, roots: ["/abs/skills"], "/abs/skills/disabled/SKILL.md": { enable: false }, "/abs/skills/enabled/SKILL.md": { enable: true }, }, }), ); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.config.skills).toEqual({ enabled: true, roots: ["/abs/skills"], }); expect(result.config.skillOverrides?.["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false); expect(result.config.skillOverrides?.["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true); expect(merged.config.skillOverrides["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false); expect(merged.config.skillOverrides["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads top-level skills config from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ skills: { enabled: false, includeInstructions: false, metadataBudget: 1024, roots: ["/abs/skills"], }, }), ); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.config.skills).toEqual({ enabled: false, includeInstructions: false, metadataBudget: 1024, roots: ["/abs/skills"], }); expect(merged.config.skills.enabled).toBe(false); expect(merged.config.skills.includeInstructions).toBe(false); expect(merged.config.skills.metadataBudget).toBe(1024); expect(merged.config.skills.roots).toEqual(["/abs/skills"]); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads UI locale from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ ui: { locale: "zh-CN" } })); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.config.ui?.locale).toBe("zh-CN"); expect(merged.config.ui.locale).toBe("zh-CN"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads auto UI locale from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ ui: { locale: "auto" } })); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.config.ui?.locale).toBe("auto"); expect(merged.config.ui.locale).toBe("auto"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads UI theme from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ ui: { theme: "light" } })); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.config.ui?.theme).toBe("light"); expect(merged.config.ui.theme).toBe("light"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects unsupported UI theme values from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ ui: { theme: "sepia" } })); const result = loadFileConfig(path); expect(result.loaded).toBe(false); expect(result.config.ui).toBeUndefined(); } finally { await rm(dir, { force: true, recursive: true }); } }); it("patches UI locale while preserving unrelated config fields", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ model: { main: "openai/gpt-5.1", }, permission: { mode: "plan", }, ui: { density: "compact", locale: "en-US", }, }), ); const result = await updateUiLocaleInFileConfig(path, "zh-CN"); const written = JSON.parse(await readFile(path, "utf-8")); expect(result).toEqual({ locale: "zh-CN", path, }); expect(written).toMatchObject({ model: { main: "openai/gpt-5.1", }, permission: { mode: "plan", }, ui: { density: "compact", locale: "zh-CN", }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("creates config files when patching UI locale", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "nested", "config.json"); try { await updateUiLocaleInFileConfig(path, "auto"); const written = JSON.parse(await readFile(path, "utf-8")); expect(written).toEqual({ ui: { locale: "auto", }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects unsupported UI locale values from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile(path, JSON.stringify({ ui: { locale: "fr-FR" } })); const result = loadFileConfig(path); expect(result.loaded).toBe(false); expect(result.config.ui).toBeUndefined(); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads MCP server config from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ features: { mcp: true, }, mcp: { servers: { local: { type: "stdio", command: "node", args: ["server.js"], cwd: ".", env: { EXAMPLE: "1", }, }, remote: { type: "http", url: "https://example.com/mcp", headers: { Authorization: "Bearer token", }, oauth: { type: "client_credentials", clientId: "zcode-client", clientSecret: "secret", scope: "mcp:tools", }, timeoutMs: 30000, }, events: { type: "sse", url: "https://example.com/sse", oauth: { type: "authorization_code", clientName: "ZCode", redirectPath: "/oauth/callback/mcp/figma", scope: "mcp:connect", }, enabled: false, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.features?.mcp).toBe(true); expect(result.config.mcp?.servers?.local).toMatchObject({ type: "stdio", command: "node", args: ["server.js"], }); expect(result.config.mcp?.servers?.remote).toMatchObject({ type: "http", url: "https://example.com/mcp", oauth: { type: "client_credentials", clientId: "zcode-client", clientSecret: "secret", scope: "mcp:tools", }, timeoutMs: 30000, }); expect(result.config.mcp?.servers?.events).toMatchObject({ type: "sse", oauth: { type: "authorization_code", clientName: "ZCode", redirectPath: "/oauth/callback/mcp/figma", scope: "mcp:connect", }, enabled: false, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps an MCP server disabled when legacy enable:false coexists with enabled:true", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { // 桌面端「停用」写入 enable:false,而外部导入/手工编辑的同一条配置里 // 已经带着 enabled:true。禁用意图必须胜出。 playwright: { type: "stdio", command: "npx", args: ["-y", "@playwright/mcp@latest"], enable: false, enabled: true, }, }, }, }), ); const result = loadFileConfig(path); expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps an MCP server disabled when enabled:false coexists with legacy enable:true", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { playwright: { type: "stdio", command: "npx", args: ["-y", "@playwright/mcp@latest"], enable: true, enabled: false, }, }, }, }), ); const result = loadFileConfig(path); expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps an MCP server enabled when both enable and enabled are true", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { playwright: { type: "stdio", command: "npx", args: ["-y", "@playwright/mcp@latest"], enable: true, enabled: true, }, }, }, }), ); const result = loadFileConfig(path); expect(result.config.mcp?.servers?.playwright?.enabled).toBe(true); } finally { await rm(dir, { force: true, recursive: true }); } }); it("preserves fresh HTTP MCP config without writing implicit OAuth", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { notion: { type: "http", url: "https://mcp.notion.com/mcp", timeoutMs: 30000, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.mcp?.servers?.notion).toMatchObject({ type: "http", url: "https://mcp.notion.com/mcp", timeoutMs: 30000, }); expect(result.config.mcp?.servers?.notion?.oauth).toBeUndefined(); } finally { await rm(dir, { force: true, recursive: true }); } }); it("skips invalid MCP OAuth config without dropping unrelated config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { broken: { type: "http", url: "https://example.com/mcp", oauth: { type: "client_credentials", clientId: "zcode-client", }, }, }, }, plugins: { enabled: true, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.mcp?.servers).not.toHaveProperty("broken"); expect(result.config.plugins?.enabled).toBe(true); expect(result.diagnostics).toEqual([ expect.objectContaining({ code: "config_mcp_server_invalid", path: "mcp.servers.broken", severity: "warning", }), ]); } finally { await rm(dir, { force: true, recursive: true }); } }); it("normalizes app-managed MCP config aliases from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { "figma-dev-mode-mcp-server": { type: "stdio", command: "npx", args: ["-y", "figma-developer-mcp"], enable: false, }, "chrome-devtools": { command: "npx", args: ["-y", "chrome-devtools-mcp@latest"], }, node_repl: { command: "/opt/tools/node_repl", args: [], timeout: 30, startup_timeout_sec: 120, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).toMatchObject({ type: "stdio", command: "npx", enabled: false, }); expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).not.toHaveProperty( "enable", ); expect(result.config.mcp?.servers?.["chrome-devtools"]).toMatchObject({ type: "stdio", command: "npx", args: ["-y", "chrome-devtools-mcp@latest"], }); expect(result.config.mcp?.servers?.node_repl).toMatchObject({ type: "stdio", command: "/opt/tools/node_repl", }); expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("timeout"); expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("startup_timeout_sec"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("normalizes legacy MCP http_headers to runtime headers", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { web_search_prime: { type: "http", url: "https://bigmodel.example.test/mcp", http_headers: { Authorization: "Bearer token", }, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.mcp?.servers?.web_search_prime).toMatchObject({ type: "http", headers: { Authorization: "Bearer token", }, }); expect(result.config.mcp?.servers?.web_search_prime).not.toHaveProperty("http_headers"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("normalizes legacy MCP remote/environment fields without dropping plugins config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { "GLM-Image-MCP": { enabled: true, environment: { Z_AI_API_KEY: "test-key", Z_AI_MODE: "ZHIPU", }, command: "npx", args: ["-y", "@z_ai/mcp-server"], type: "stdio", }, "GLM-WebReader-MCP": { enabled: true, headers: { Authorization: "Bearer token", }, type: "remote", url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp", }, }, }, plugins: { enabledPlugins: { "superpowers@zcode-plugins-official": true, "skill-creator@zcode-plugins-official": false, }, }, }), ); const result = loadFileConfig(path); const merged = createConfig({ env: {}, userConfigPath: path }); expect(result.loaded).toBe(true); expect(result.diagnostics).toEqual([]); expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).toMatchObject({ type: "stdio", env: { Z_AI_API_KEY: "test-key", Z_AI_MODE: "ZHIPU", }, }); expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).not.toHaveProperty("environment"); expect(result.config.mcp?.servers?.["GLM-WebReader-MCP"]).toMatchObject({ headers: { Authorization: "Bearer token", }, type: "http", url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp", }); expect(merged.config.plugins.enabledPlugins).toMatchObject({ "skill-creator@zcode-plugins-official": false, "superpowers@zcode-plugins-official": true, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("keeps non-MCP config when one MCP server is invalid", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const logDir = join(dir, "log"); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ mcp: { servers: { valid: { type: "remote", url: "https://example.com/mcp", }, broken: { type: "stdio", args: ["server.js"], }, }, }, plugins: { enabledPlugins: { "android-emulator@zcode-plugins-official": true, }, }, }), ); const result = loadFileConfig(path); const merged = createConfig({ env: { ZCODE_LOG_DIR: logDir }, userConfigPath: path, }); expect(result.loaded).toBe(true); expect(result.config.mcp?.servers?.valid).toMatchObject({ type: "http", url: "https://example.com/mcp", }); expect(result.config.mcp?.servers).not.toHaveProperty("broken"); expect( result.config.plugins?.enabledPlugins?.["android-emulator@zcode-plugins-official"], ).toBe(true); expect(result.diagnostics).toEqual([ expect.objectContaining({ code: "config_mcp_server_invalid", path: "mcp.servers.broken", severity: "warning", }), ]); expect(merged.sources.user.diagnostics).toEqual(result.diagnostics); expect(merged.config.plugins.enabledPlugins["android-emulator@zcode-plugins-official"]).toBe( true, ); await expect(readLogEntries(logDir)).resolves.toEqual([ expect.objectContaining({ event: "config.mcp_server.skipped", level: "warn", message: "MCP server config skipped", module: "adapters.config", context: expect.objectContaining({ configPath: path, configScope: "user", diagnosticCode: "config_mcp_server_invalid", diagnosticPath: "mcp.servers.broken", }), }), ]); } finally { await rm(dir, { force: true, recursive: true }); } }); it("reports invalid discovered project config diagnostics", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-config-")); const logDir = join(root, "log"); const projectConfigPath = join(root, "zcode.json"); try { await mkdir(join(root, ".git")); await writeFile( projectConfigPath, JSON.stringify({ ui: { theme: "sepia", }, }), ); const result = createConfig({ env: { ZCODE_LOG_DIR: logDir }, skipUserConfig: true, workingDirectory: root, }); expect(result.sources.project.loaded).toBe(false); expect(result.sources.project.diagnostics).toEqual([ expect.objectContaining({ code: "config_file_invalid", message: expect.stringContaining("ui.theme: Invalid option: expected one of"), severity: "error", }), ]); await expect(readLogEntries(logDir)).resolves.toEqual([ expect.objectContaining({ event: "config.file.invalid", level: "warn", message: "Config file failed to load", module: "adapters.config", context: expect.objectContaining({ configPath: projectConfigPath, configScope: "project", diagnosticCode: "config_file_invalid", }), }), ]); } finally { await rm(root, { force: true, recursive: true }); } }); it("discovers project MCP config from the worktree root", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-config-")); const cwd = join(root, "packages", "app"); try { await mkdir(join(root, ".git")); await mkdir(cwd, { recursive: true }); await writeFile( join(root, "zcode.json"), JSON.stringify({ mcp: { servers: { project: { type: "stdio", command: "node", args: ["server.js"], cwd: "tools", }, }, }, }), ); const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: cwd, }); expect(result.sources.project.loaded).toBe(true); expect(result.sources.project.paths).toEqual([join(root, "zcode.json")]); expect(result.sources.project.mcpServerNames).toEqual(["project"]); expect(result.config.mcp.servers.project).toMatchObject({ type: "stdio", command: "node", cwd: join(root, "tools"), }); } finally { await rm(root, { force: true, recursive: true }); } }); it("merges project configs from root to cwd with nearest config winning", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-config-")); const cwd = join(root, "packages", "app"); const cwdConfigDir = join(cwd, ".zcode"); try { await mkdir(join(root, ".git")); await mkdir(cwdConfigDir, { recursive: true }); await writeFile( join(root, "zcode.json"), JSON.stringify({ mcp: { servers: { project: { type: "stdio", command: "root-server", }, }, }, }), ); await writeFile( join(cwdConfigDir, "config.json"), JSON.stringify({ mcp: { servers: { project: { type: "stdio", command: "nearest-server", }, }, }, }), ); const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: cwd, }); expect(result.sources.project.paths).toEqual([ join(root, "zcode.json"), join(cwdConfigDir, "config.json"), ]); expect(result.config.mcp.servers.project).toMatchObject({ type: "stdio", command: "nearest-server", cwd, }); } finally { await rm(root, { force: true, recursive: true }); } }); it("lets user MCP servers override same-name project MCP servers", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-config-")); const userConfigPath = join(root, "home", "config.json"); try { await mkdir(join(root, ".git")); await mkdir(join(root, "home"), { recursive: true }); await writeFile( join(root, "zcode.json"), JSON.stringify({ mcp: { servers: { projectOnly: { type: "stdio", command: "project-only-server", }, shared: { type: "stdio", command: "project-server", }, }, }, }), ); await writeFile( userConfigPath, JSON.stringify({ mcp: { servers: { shared: { type: "stdio", command: "user-server", }, userOnly: { type: "stdio", command: "user-only-server", }, }, }, }), ); const result = createConfig({ env: {}, userConfigPath, workingDirectory: root, }); expect(result.config.mcp.servers.shared).toMatchObject({ type: "stdio", command: "user-server", }); expect(result.config.mcp.servers.projectOnly).toMatchObject({ command: "project-only-server", }); expect(result.config.mcp.servers.userOnly).toMatchObject({ command: "user-only-server", }); expect(result.sources.user.mcpServerNames).toEqual(["shared", "userOnly"]); expect(result.sources.project.mcpServerNames.toSorted()).toEqual(["projectOnly", "shared"]); expect(result.sources.mcp.serverSources).toMatchObject({ projectOnly: "project", shared: "user", userOnly: "user", }); } finally { await rm(root, { force: true, recursive: true }); } }); it("does not scan project config above the worktree root", async () => { const parent = await mkdtemp(join(tmpdir(), "zcode-project-config-")); const root = join(parent, "repo"); const cwd = join(root, "packages", "app"); try { await mkdir(join(root, ".git"), { recursive: true }); await mkdir(cwd, { recursive: true }); await writeFile( join(parent, "zcode.json"), JSON.stringify({ mcp: { servers: { parent: { type: "stdio", command: "parent-server", }, }, }, }), ); const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: cwd, }); expect(result.sources.project.loaded).toBe(false); expect(result.config.mcp.servers.parent).toBeUndefined(); } finally { await rm(parent, { force: true, recursive: true }); } }); it("keeps CLI feature overrides above project MCP config", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-config-")); try { await mkdir(join(root, ".git")); await writeFile( join(root, "zcode.json"), JSON.stringify({ features: { mcp: true, }, }), ); const result = createConfig({ cliOverrides: { features: { mcp: false, }, }, env: {}, skipUserConfig: true, workingDirectory: root, }); expect(result.config.features.mcp).toBe(false); } finally { await rm(root, { force: true, recursive: true }); } }); it("loads process hook config from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ hooks: { enabled: true, timeoutMs: 5000, maxOutputBytes: 8192, events: { PreToolUse: [ { matcher: "Bash", hooks: [ { type: "process", command: "node", args: ["hooks/pre-tool.js"], enabled: false, customFlag: "keep", }, ], }, ], }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.hooks).toMatchObject({ enabled: true, timeoutMs: 5000, maxOutputBytes: 8192, }); expect(result.config.hooks?.events?.PreToolUse?.[0]?.hooks[0]).toMatchObject({ type: "process", command: "node", args: ["hooks/pre-tool.js"], enabled: false, customFlag: "keep", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("drops hooks from discovered project config files because project hooks are untrusted code", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-project-hooks-")); try { await mkdir(join(root, ".git")); await mkdir(join(root, ".zcode"), { recursive: true }); await writeFile( join(root, "zcode.json"), JSON.stringify({ hooks: { enabled: true, events: { SessionStart: [ { matcher: "startup", hooks: [{ type: "command", command: "echo root-project-hook" }], }, ], }, }, }), ); await writeFile( join(root, ".zcode", "config.json"), JSON.stringify({ hooks: { enabled: true, events: { SessionStart: [ { matcher: "startup", hooks: [{ type: "command", command: "echo project-hook" }], }, ], }, }, }), ); const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root, }); expect(result.sources.project.loaded).toBe(true); expect( result.sources.project.diagnostics.filter( (diagnostic) => diagnostic.code === "config_project_hooks_pending_trust", ), ).toHaveLength(2); for (const configPath of [join(root, "zcode.json"), join(root, ".zcode", "config.json")]) { expect(result.sources.project.diagnostics).toContainEqual( expect.objectContaining({ code: "config_project_hooks_pending_trust", filePath: configPath, message: "Project hooks are pending workspace trust and remain blocked", path: "hooks", severity: "warning", }), ); } expect(result.config.hooks.events.SessionStart).toBeUndefined(); expect(result.config.hooks.enabled).toBe(false); } finally { await rm(root, { force: true, recursive: true }); } }); it("keeps user hooks while dropping untrusted project hooks", async () => { const root = await mkdtemp(join(tmpdir(), "zcode-user-project-hooks-")); const userConfigPath = join(root, "user-config.json"); try { await mkdir(join(root, ".git")); await mkdir(join(root, ".zcode"), { recursive: true }); await writeFile( userConfigPath, JSON.stringify({ hooks: { enabled: true, events: { SessionStart: [ { matcher: "startup", hooks: [{ type: "command", command: "echo user-hook" }], }, ], }, }, }), ); await writeFile( join(root, ".zcode", "config.json"), JSON.stringify({ hooks: { enabled: true, events: { UserPromptSubmit: [ { matcher: "*", hooks: [{ type: "command", command: "echo project-hook" }], }, ], }, }, }), ); const result = createConfig({ env: {}, userConfigPath, workingDirectory: root, }); expect(result.sources.user.loaded).toBe(true); expect(result.sources.project.loaded).toBe(true); expect(result.sources.project.diagnostics).toContainEqual( expect.objectContaining({ code: "config_project_hooks_pending_trust", path: "hooks", severity: "warning", }), ); expect(result.config.hooks.enabled).toBe(true); expect(result.config.hooks.events.SessionStart?.[0]?.hooks[0]).toMatchObject({ type: "command", command: "echo user-hook", source: { kind: "user", path: userConfigPath }, }); expect(result.config.hooks.events.UserPromptSubmit).toBeUndefined(); } finally { await rm(root, { force: true, recursive: true }); } }); it("loads model stream idle timeout config from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ modelStream: { idleTimeoutMs: 120000, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.modelStream).toMatchObject({ idleTimeoutMs: 120000, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("merges model stream idle timeout into runtime config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ modelStream: { idleTimeoutMs: 240000, }, }), ); const result = createConfig({ env: {}, userConfigPath: path }); expect(result.config.modelStream.idleTimeoutMs).toBe(240000); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads model anomaly guard config from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ modelAnomalyGuard: { repeatedToolCallWarningThreshold: 4, maxBudgetWarningsPerTurn: 2, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.modelAnomalyGuard).toMatchObject({ repeatedToolCallWarningThreshold: 4, maxBudgetWarningsPerTurn: 2, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects unknown hook events from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ hooks: { enabled: true, events: { BeforeEverything: [ { hooks: [ { type: "process", command: "node", }, ], }, ], }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(false); expect(result.config).toEqual({}); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects inline model target config from file", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ model: { provider: "default-deepseek", model: "deepseek-V4-Pro", baseURL: "https://api.deepseek.com", apiKey: "secret", headers: { "X-Title": "Z Code", }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(false); expect(result.config).toEqual({}); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads main and lite model references from provider-first config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ model: { main: "deepseek/deepseek-v4-pro", lite: "deepseek/deepseek-chat", }, provider: { deepseek: { kind: "openai-compatible", name: "DeepSeek", options: { baseURL: "https://api.deepseek.com", apiKey: "secret", }, models: { "deepseek-v4-pro": { name: "DeepSeek V4 Pro", }, "deepseek-chat": { name: "DeepSeek Chat", }, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.model?.main).toMatchObject({ provider: "deepseek", model: "deepseek-v4-pro", kind: "openai-compatible", baseURL: "https://api.deepseek.com", apiKey: "secret", }); expect(result.config.model?.lite?.model).toBe("deepseek-chat"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("patches string model selection in file config without dropping other fields", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ model: "deepseek/deepseek-chat", mcp: { servers: { local: { type: "stdio", command: "node", }, }, }, provider: { deepseek: { kind: "openai-compatible", options: { baseURL: "https://api.deepseek.com", apiKey: "secret", }, models: { "deepseek-chat": {}, "deepseek-v4-pro": {}, }, }, }, }), ); await updateModelSelectionInFileConfig(path, "deepseek/deepseek-v4-pro"); const updated = JSON.parse(await readFile(path, "utf-8")); expect(updated.model).toBe("deepseek/deepseek-v4-pro"); expect(updated.mcp.servers.local.command).toBe("node"); expect(updated.provider.deepseek.options.apiKey).toBe("secret"); } finally { await rm(dir, { force: true, recursive: true }); } }); it("patches object model main in file config without changing lite", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ model: { main: "deepseek/deepseek-chat", lite: "deepseek/deepseek-lite", }, provider: { deepseek: { kind: "openai-compatible", options: { baseURL: "https://api.deepseek.com", }, models: { "deepseek-chat": {}, "deepseek-lite": {}, "deepseek-v4-pro": {}, }, }, }, }), ); await updateModelSelectionInFileConfig(path, "deepseek/deepseek-v4-pro"); const updated = JSON.parse(await readFile(path, "utf-8")); expect(updated.model).toEqual({ main: "deepseek/deepseek-v4-pro", lite: "deepseek/deepseek-lite", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("patches ZAI Coding Plan provider config with an API key", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { zai: { kind: "openai-compatible", options: { apiKey: "legacy-secret", baseURL: "https://legacy.example/v1", timeout: 30000, }, models: { "glm-5.1": { contextWindow: 200000, }, }, }, deepseek: { kind: "openai-compatible", options: { apiKey: "deepseek-secret", baseURL: "https://api.deepseek.example", }, models: { "deepseek-chat": {}, }, }, }, model: { main: "deepseek/deepseek-chat", lite: "deepseek/deepseek-chat", }, }), ); const result = await updateCodingPlanProviderInFileConfig({ apiKey: "zai-coding-key", filePath: path, providerId: "zai", }); const updated = JSON.parse(await readFile(path, "utf-8")); expect(result).toEqual({ mainModel: "zai/glm-5.1", path, providerId: "zai", }); expect(updated.provider.zai.kind).toBe("anthropic"); expect(updated.provider.zai.options).toEqual({ apiKey: "zai-coding-key", apiKeyRequired: true, baseURL: "https://api.z.ai/api/anthropic", timeout: 30000, }); expect(updated.provider.zai.models["glm-5.1"]).toEqual({ contextWindow: 200000, name: "GLM-5.1", }); expect(updated.provider.deepseek.options.apiKey).toBe("deepseek-secret"); expect(updated.model).toEqual({ main: "zai/glm-5.1", lite: "deepseek/deepseek-chat", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("creates default Coding Plan configs when the file is missing", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await updateCodingPlanProviderInFileConfig({ apiKey: "bigmodel-coding-key", filePath: path, providerId: "bigmodel", }); const updated = JSON.parse(await readFile(path, "utf-8")); expect(updated.model).toEqual({ main: "bigmodel/glm-5.1", lite: "bigmodel/glm-4.7", }); expect(updated.provider.bigmodel).toMatchObject({ kind: "anthropic", name: "BigModel Coding Plan", options: { apiKey: "bigmodel-coding-key", apiKeyRequired: true, baseURL: "https://open.bigmodel.cn/api/anthropic", }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads provider map config with model metadata", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ $schema: "https://zcode.ai/schema/config-v2.json", provider: { "provider-auth-zai": { kind: "openai-compatible", name: "Z.AI", options: { baseURL: "https://api.z.ai/api/coding/v1", apiKey: "secret", includeUsage: false, }, models: { "glm-5": { name: "GLM-5", reasoning: { enabled: true, levels: ["low", "medium", "high"], defaultLevel: "medium", providerOptionsByLevel: { high: { reasoningEffort: "high", }, }, }, modalities: { input: ["text", "image", "pdf", "video"], output: ["text"], }, limit: { context: 200000, output: 8192, }, tool_call: true, options: { reasoningSummary: "auto", }, }, "glm-4.7": { name: "GLM-4.7", attachment: false, reasoning: false, limit: { context: 128000, output: 4096, }, }, }, }, }, model: { main: "provider-auth-zai/glm-5", lite: "provider-auth-zai/glm-4.7", }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.model?.main).toEqual({ provider: "provider-auth-zai", model: "glm-5", kind: "openai-compatible", providerName: "Z.AI", baseURL: "https://api.z.ai/api/coding/v1", apiKey: "secret", includeUsage: false, providerOptions: { openaiCompatible: { reasoningSummary: "auto", }, }, }); expect(result.config.model?.lite?.model).toBe("glm-4.7"); expect(result.config.model?.lite?.baseURL).toBe("https://api.z.ai/api/coding/v1"); expect( result.config.model?.available?.map((target) => `${target.provider}/${target.model}`), ).toEqual(["provider-auth-zai/glm-5", "provider-auth-zai/glm-4.7"]); expect(result.config.modelCatalog?.overrides?.["provider-auth-zai/glm-5"]).toEqual({ name: "GLM-5", contextWindow: 200000, maxOutputTokens: 8192, supportsImages: true, supportsPdf: true, supportsVideo: true, supportsReasoning: true, supportsToolCall: true, reasoning: { enabled: true, levels: ["low", "medium", "high"], defaultLevel: "medium", providerOptionsByLevel: { high: { openaiCompatible: { reasoningEffort: "high", }, }, }, }, }); expect(result.config.modelCatalog?.overrides?.["provider-auth-zai/glm-4.7"]).toEqual({ name: "GLM-4.7", contextWindow: 128000, maxOutputTokens: 4096, supportsImages: false, supportsReasoning: false, reasoning: { enabled: false, }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("maps top-level model maxOutputTokens into the existing model capability override", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-model-output-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { "axec-proxy": { kind: "anthropic", name: "AxecProxy", options: { apiKey: "test-key", baseURL: "https://api.infra.example.invalid/v1", }, models: { "tob-glm-5.2-cc": { contextWindow: 1_000_000, maxOutputTokens: 64_000, name: "tob-glm-5.2-cc", }, }, }, }, model: "axec-proxy/tob-glm-5.2-cc", }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.modelCatalog.overrides["axec-proxy/tob-glm-5.2-cc"]).toMatchObject({ contextWindow: 1_000_000, maxOutputTokens: 64_000, }); expect(result.config.model?.main).toMatchObject({ model: "tob-glm-5.2-cc", provider: "axec-proxy", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("resolves output budget with limit before options.max_tokens before top-level", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-model-output-precedence-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { compatible: { kind: "openai-compatible", models: { "limit-wins": { limit: { output: 64_000 }, maxOutputTokens: 16_000, options: { max_tokens: 32_000 }, }, "options-wins": { maxOutputTokens: 16_000, options: { max_tokens: 48_000 }, }, }, }, }, model: "compatible/limit-wins", }), ); const result = loadFileConfig(path); expect(result.config.modelCatalog.overrides["compatible/limit-wins"]?.maxOutputTokens).toBe( 64_000, ); expect(result.config.modelCatalog.overrides["compatible/options-wins"]?.maxOutputTokens).toBe( 48_000, ); } finally { await rm(dir, { force: true, recursive: true }); } }); it("uses kind-aware Anthropic defaults for configured thinking models", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { zai: { kind: "anthropic", options: { baseURL: "https://api.z.ai/api/anthropic/v1", apiKey: "secret", }, models: { "deepseek-v4-pro": {}, "glm-5.1": {}, "glm-5.2": {}, "deepseek-v4-toB-glm-5.3-route": {}, "glm-0531[1m]": {}, "glm-0606[1m]": {}, "kimi-k3": {}, k3: {}, "k3-256k": {}, }, }, }, model: "zai/glm-5.1", }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.modelCatalog?.overrides?.["zai/glm-5.1"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["enabled", "disabled"], defaultLevel: "enabled", providerOptionsByLevel: { enabled: { anthropic: { thinking: { budgetTokens: 1024, type: "enabled", }, }, }, disabled: { anthropic: { thinking: { type: "disabled", }, }, }, }, }, }); expect(result.config.modelCatalog?.overrides?.["zai/deepseek-v4-pro"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["high", "max"], defaultLevel: "max", providerOptionsByLevel: { high: { anthropic: { effort: "high", thinking: { budgetTokens: 1024, type: "enabled", }, }, }, max: { anthropic: { effort: "max", thinking: { budgetTokens: 1024, type: "enabled", }, }, }, }, }, }); expect(result.config.modelCatalog?.overrides?.["zai/glm-5.2"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["max", "high", "nothink"], defaultLevel: "max", providerOptionsByLevel: { high: { anthropic: { effort: "high", thinking: { budgetTokens: 16_000, type: "enabled", }, }, }, max: { anthropic: { effort: "max", thinking: { budgetTokens: 32_000, type: "enabled", }, }, }, nothink: { anthropic: { thinking: { type: "disabled", }, }, }, }, }, }); expect(result.config.modelCatalog?.overrides?.["zai/deepseek-v4-toB-glm-5.3-route"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["low", "high", "max"], defaultLevel: "max", providerOptionsByLevel: { low: { anthropic: { effort: "low", thinking: { budgetTokens: 8_000, type: "enabled" }, }, }, high: { anthropic: { effort: "high", thinking: { budgetTokens: 16_000, type: "enabled" }, }, }, max: { anthropic: { effort: "max", thinking: { budgetTokens: 32_000, type: "enabled" }, }, }, }, }, }); expect(result.config.modelCatalog?.overrides?.["zai/glm-0531[1m]"]?.reasoning).toEqual( result.config.modelCatalog?.overrides?.["zai/glm-5.2"]?.reasoning, ); expect(result.config.modelCatalog?.overrides?.["zai/glm-0606[1m]"]?.reasoning).toEqual( result.config.modelCatalog?.overrides?.["zai/glm-5.2"]?.reasoning, ); expect(result.config.modelCatalog?.overrides?.["zai/kimi-k3"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["low", "high", "max"], defaultLevel: "max", providerOptionsByLevel: { low: { anthropic: { effort: "low" } }, high: { anthropic: { effort: "high" } }, max: { anthropic: { effort: "max" } }, }, }, }); expect(result.config.modelCatalog?.overrides?.["zai/k3"]).toEqual( result.config.modelCatalog?.overrides?.["zai/kimi-k3"], ); expect(result.config.modelCatalog?.overrides?.["zai/k3-256k"]).toEqual( result.config.modelCatalog?.overrides?.["zai/kimi-k3"], ); } finally { await rm(dir, { force: true, recursive: true }); } }); it("maps ox-alpha reasoning by configured transport without injecting unrelated defaults", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-ox-alpha-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { "openrouter-chat": { kind: "openai-compatible", models: { "vendor/ox-alpha-preview": {}, "GLM-X-PREVIEW-F": {}, "X-pReViEw-F-fReE": {}, }, }, "openrouter-anthropic": { kind: "anthropic", models: { "ox-alpha": {}, "gLm-X-pReViEw-F": {}, "x-PrEvIeW-f-FrEe": {}, }, }, "openrouter-responses": { kind: "openai", models: { "ox-alpha": {}, "GlM-x-PrEvIeW-f": {} }, }, }, model: "openrouter-chat/vendor/ox-alpha-preview", }), ); const result = loadFileConfig(path); expect( result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"], ).toEqual({ reasoning: { defaultLevel: "max", enabled: true, levels: ["low", "high", "max"], providerOptionsByLevel: { low: { openaiCompatible: { reasoningEffort: "low" } }, high: { openaiCompatible: { reasoningEffort: "high" } }, max: { openaiCompatible: { reasoningEffort: "max" } }, }, }, supportsReasoning: true, }); expect(result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"]).toEqual({ reasoning: { defaultLevel: "max", enabled: true, levels: ["low", "high", "max"], providerOptionsByLevel: { low: { anthropic: { effort: "low", thinking: { type: "adaptive" } } }, high: { anthropic: { effort: "high", thinking: { type: "adaptive" } } }, max: { anthropic: { effort: "max", thinking: { type: "adaptive" } } }, }, }, supportsReasoning: true, }); expect(result.config.modelCatalog.overrides["openrouter-responses/ox-alpha"]).toEqual({ supportsReasoning: false, }); expect(result.config.modelCatalog.overrides["openrouter-chat/GLM-X-PREVIEW-F"]).toEqual( result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"], ); expect(result.config.modelCatalog.overrides["openrouter-anthropic/gLm-X-pReViEw-F"]).toEqual( result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"], ); expect(result.config.modelCatalog.overrides["openrouter-chat/X-pReViEw-F-fReE"]).toEqual( result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"], ); expect(result.config.modelCatalog.overrides["openrouter-anthropic/x-PrEvIeW-f-FrEe"]).toEqual( result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"], ); expect(result.config.modelCatalog.overrides["openrouter-responses/GlM-x-PrEvIeW-f"]).toEqual( result.config.modelCatalog.overrides["openrouter-responses/ox-alpha"], ); const catalog = new ModelCatalogService({ modelsDev: false, overrides: result.config.modelCatalog.overrides, }); expect(catalog.getCapability("openrouter-responses", "ox-alpha")).toMatchObject({ reasoning: { enabled: false, levels: [] }, supportsReasoning: false, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects legacy small model config keys", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const smallModelPath = join(dir, "small-model.json"); const modelSmallPath = join(dir, "model-small.json"); try { await writeFile( smallModelPath, JSON.stringify({ provider: { openai: { kind: "openai", }, }, model: "openai/gpt-4o", small_model: "openai/gpt-4o-mini", }), ); await writeFile( modelSmallPath, JSON.stringify({ provider: { openai: { kind: "openai", }, }, model: { main: "openai/gpt-4o", small: "openai/gpt-4o-mini", }, }), ); expect(loadFileConfig(smallModelPath).loaded).toBe(false); expect(loadFileConfig(modelSmallPath).loaded).toBe(false); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads selectable models from multiple configured providers", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { zai: { kind: "openai-compatible", name: "Z.AI", options: { baseURL: "https://api.z.ai/api/coding/v1", apiKey: "zai-secret", }, models: { "glm-5.1": { name: "GLM-5.1", }, "glm-4.7": { name: "GLM-4.7", }, }, }, deepseek: { kind: "openai-compatible", name: "DeepSeek", options: { apiKey: "deepseek-secret", baseURL: "https://api.deepseek.example", }, models: { "deepseek-v4-pro": { name: "DeepSeek V4 Pro", }, }, }, }, model: "zai/glm-5.1", }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect( result.config.model?.available?.map((target) => `${target.provider}/${target.model}`), ).toEqual(["zai/glm-5.1", "zai/glm-4.7", "deepseek/deepseek-v4-pro"]); expect( result.config.model?.available?.find((target) => target.provider === "deepseek"), ).toMatchObject({ kind: "openai-compatible", apiKey: "deepseek-secret", baseURL: "https://api.deepseek.example", }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects file config that fails the zod schema", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ provider: { local: { models: { tiny: { limit: { context: "large", }, }, }, }, }, model: "local/tiny", }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(false); expect(result.config).toEqual({}); } finally { await rm(dir, { force: true, recursive: true }); } }); it("rejects unsupported provider kinds and npm-based provider config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const unsupportedKindPath = join(dir, "unsupported-kind.json"); const npmPath = join(dir, "npm-provider.json"); try { await writeFile( unsupportedKindPath, JSON.stringify({ provider: { local: { kind: "gateway", models: { tiny: { name: "Tiny" }, }, }, }, model: "local/tiny", }), ); await writeFile( npmPath, JSON.stringify({ provider: { local: { npm: "@ai-sdk/openai-compatible", models: { tiny: { name: "Tiny" }, }, }, }, model: "local/tiny", }), ); expect(loadFileConfig(unsupportedKindPath).loaded).toBe(false); expect(loadFileConfig(npmPath).loaded).toBe(false); } finally { await rm(dir, { force: true, recursive: true }); } }); it("loads model catalog reasoning overrides from file config", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-")); const path = join(dir, "config.json"); try { await writeFile( path, JSON.stringify({ modelCatalog: { overrides: { "openai/glm-4.7": { supportsReasoning: true, reasoning: { enabled: true, levels: ["low", "medium", "high"], defaultLevel: "medium", providerOptionsByLevel: { high: { reasoningEffort: "high", }, }, }, }, }, }, }), ); const result = loadFileConfig(path); expect(result.loaded).toBe(true); expect(result.config.modelCatalog?.overrides?.["openai/glm-4.7"]).toEqual({ supportsReasoning: true, reasoning: { enabled: true, levels: ["low", "medium", "high"], defaultLevel: "medium", providerOptionsByLevel: { high: { reasoningEffort: "high", }, }, }, }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("removes a plugin's enabled flag and options on uninstall while preserving others", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-")); const configPath = join(dir, "config.json"); try { await writeFile( configPath, JSON.stringify({ plugins: { enabledPlugins: { "hello@market": true, "keep@market": true, }, options: { "hello@market": { default_device: "iPhone 16" }, "keep@market": { foo: "bar" }, }, }, }), ); const result = await removePluginFromFileConfig(configPath, "hello@market"); expect(result.removedEnabled).toBe(true); expect(result.removedOptions).toBe(true); const parsed = JSON.parse(await readFile(configPath, "utf8")) as { plugins: { enabledPlugins: Record; options: Record; }; }; expect(parsed.plugins.enabledPlugins).toEqual({ "keep@market": true }); expect(parsed.plugins.options).toEqual({ "keep@market": { foo: "bar" } }); } finally { await rm(dir, { force: true, recursive: true }); } }); it("is a no-op when removing a plugin that has no config footprint", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-missing-")); const configPath = join(dir, "config.json"); try { await writeFile( configPath, JSON.stringify({ plugins: { enabledPlugins: { "keep@market": true } } }), ); const before = await readFile(configPath, "utf8"); const result = await removePluginFromFileConfig(configPath, "missing@market"); expect(result.removedEnabled).toBe(false); expect(result.removedOptions).toBe(false); // 未命中任何键时不应改写文件内容。 expect(await readFile(configPath, "utf8")).toBe(before); } finally { await rm(dir, { force: true, recursive: true }); } }); it("adds and removes a suppressed builtin id atomically", async () => { const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppress-patch-")); const path = join(dir, "config.json"); const id = "skill-creator@zcode-plugins-official"; const added = await addSuppressedBuiltinInFileConfig(path, id); expect(added.suppressed).toBe(true); expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]); // idempotent add await addSuppressedBuiltinInFileConfig(path, id); expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]); const removed = await removeSuppressedBuiltinInFileConfig(path, id); expect(removed.suppressed).toBe(false); expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([]); }); }); async function readLogEntries(logDir: string): Promise>> { const files = await readdir(logDir); expect(files).toHaveLength(1); const content = await readFile(join(logDir, files[0]!), "utf8"); return content.trim().split("\n").map(JSON.parse) as Array>; }