kimi-code/packages/node-sdk/test/config.test.ts
7Sageer efac96c8a9
feat(agent-core): custom agent files and secondary model on the v1 engine (#2232)
* feat(agent-core): custom agent files and secondary model on the v1 engine

Migrate the custom agentfile and secondary-model capabilities from
agent-core-v2 to the v1 engine so they work in the TUI and plain
kimi -p sessions:

- discover Markdown agent files from user/project/extra/explicit
  directories with the v2 precedence rules, a merged session profile
  catalog replacing the hardcoded builtin profile lookups, SYSTEM.md
  main prompt override, and ${base_prompt} backed by the effective
  default
- --agent/--agent-file now work in print mode on the default engine;
  CreateSessionOptions gains agentProfile/agentFiles
- [secondary_model] config + KIMI_SECONDARY_MODEL/EFFORT bind newly
  spawned subagents to a cheaper model behind the secondary-model
  experiment flag, with primary/secondary model params on Agent and
  AgentSwarm and upfront session warnings
- full disallowedTools deny semantics (exact names + mcp__ globs)
  evaluated by the tool manager and persisted in the agent wire

* fix(cli): guard optional agentFiles in the prompt runner

runPrompt is also driven programmatically (headless goal flow) with
options that never pass through the CLI parser defaults, so agentFiles
can be undefined; mirror the addDirs optional-chaining pattern. Also
extend the SDK experimental-feature assertion with the secondary-model
flag.

* fix(agent-core): preserve custom agent bindings on v1

* fix(agent-core): narrow secondary model error hints

* fix(agent-core): persist custom agent profile bindings

* Delete .changeset/sdk-agent-profile-options.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Update v1-custom-agent-files.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Update v1-secondary-model.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* Update v1-custom-agent-files.md

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix(agent-core): keep SYSTEM.md a prompt-only overlay for delegation

* docs: update agent file and secondary model availability wording

* fix(cli): reject --agent-file combined with session resume

The resume path only forwards the agent file's name for the bound-profile
assertion; the file's content is never re-applied (the session keeps its
creation-time catalog snapshot). Previously the combination was silently
accepted, so an edited file (or a same-named one) appeared to apply but did
not. Reject it at option validation and document the constraint.

* refactor(agent-core): share prompt-section prose and note v2 twins in agentfile headers

The Windows notes, additional-dirs and skills prose blocks existed twice:
inline in the builtin default template (system.md) and as constants in the
agent-file renderer (from-file.ts). Extract them to profile/prompt-sections.ts
as the single source: system.md renders them through injected KIMI_* template
variables and from-file.ts imports the same constants. Rendered prompts are
byte-identical for all four builtin profiles across macOS/Windows and
skills/dirs on/off; a new test pins system.md to the shared constants.

Also mark each profile/agentfile file with the path of its agent-core-v2
counterpart so format/semantics changes land in both engines.

* feat(cli): add /secondary_model command for the subagent model

Mirror /model: a picker with a thinking-effort step that persists [secondary_model] and live-applies to the current session via a new Session.setSecondaryModel RPC (node-sdk wrapper included), so newly spawned subagents bind the new model right away. The /model picker now hides the synthesized __secondary__ derived entry; docs and the update-config builtin skill mention the section.

* feat(tui): show the bound model in subagent run stats

Subagents report their model alias via agent.status.updated after spawn; resolve it to a display name and surface it in tool-call subagent stats and agent-group rows.

* fix(agent-core): validate agent profile before session persistence

* fix(agent-core): refresh subagent tools after model switch

* fix(agent-core): show subagent model preferences

* fix(agent-core): preserve secondary model recipe on live apply

* fix(agent-core): make secondary model apply explicit

* fix(tui): refresh secondary model display state

* chore: merge secondary model changesets into one

* Add /secondary_model command for subagent configuration

Show each subagent's model in the subagent card header and agent-group rows. Requires the secondary-model experiment (KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL=1); run /secondary_model to pick a model and thinking effort, applied to the current session immediately.

Signed-off-by: 7Sageer <sag77r@hotmail.com>

* fix(agent-core): align explicit agent file precedence

* fix(agent-core): let disallowedTools deny select_tools

* chore(cli): drop engine mention from --agent/--agent-file help text

* feat(cli): support --agent/--agent-file in the interactive TUI

Bind the selected agent profile to the startup session when launching
the TUI with --agent/--agent-file, including the session created after
an OAuth login at startup. Sessions created later in the process (/new)
keep the default profile.

Make both flags creation-only in every mode: combining them with
--session/--continue is now rejected in print mode too, since resume
restores the bound agent from the session automatically.

* fix(agent-core): persist new secondary-model selections under env overrides

stripSecondaryModelConfig restored secondary_model.model/default_effort
from raw whenever KIMI_SECONDARY_MODEL/KIMI_SECONDARY_EFFORT was set, so
a /secondary_model pick made under the env vars was silently discarded
on write. Restore from raw only when the value being written still
equals the env value (an overlay round-trip), mirroring the pointer
check in stripEnvModelConfig; a genuinely different selection now
reaches config.toml.

* fix(cli): report the effective secondary model when env overrides the pick

/secondary_model toasted the picked alias even when
KIMI_SECONDARY_MODEL/KIMI_SECONDARY_EFFORT made the session bind a
different model. Read the effective binding back from the reloaded
config (as /model does from session status) and warn with the
env-overridden values instead.

* feat(tui): show the bound model name in the AgentSwarm panel header

---------

Signed-off-by: 7Sageer <sag77r@hotmail.com>
2026-07-29 12:06:26 +08:00

420 lines
14 KiB
TypeScript

import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createKimiConfigRpc, createKimiHarness, KimiError } from '#/index';
import {
parseConfigString,
readConfigFile,
writeConfigFile,
} from '../../agent-core/src/config';
import { TEST_IDENTITY } from './test-identity';
// node-sdk/agent-core normalize paths to forward slashes (pathe). Mirror that
// in path assertions so they hold on Windows, where node:path produces
// backslashes.
const toPosix = (p: string): string => p.replaceAll('\\', '/');
const tempDirs: string[] = [];
afterEach(async () => {
vi.unstubAllEnvs();
for (const dir of tempDirs.splice(0)) {
await rm(dir, { recursive: true, force: true });
}
});
async function makeTempDir(): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), 'kimi-sdk-config-'));
tempDirs.push(dir);
return dir;
}
const COMPLETE_TOML = `
default_model = "kimi-for-coding"
default_permission_mode = "auto"
skip_afk_prompt_injection = false
default_plan_mode = false
default_editor = ""
theme = "dark"
show_thinking_stream = true
merge_all_available_skills = true
extra_skill_dirs = ["~/team-skills", ".agents/team-skills"]
[providers.kimi-for-coding]
type = "kimi"
base_url = "https://api.kimi.com/coding/v1"
api_key = "sk-xxx"
custom_headers = { "X-Custom-Header" = "value" }
[providers.kimi-for-coding.env]
GOOGLE_CLOUD_PROJECT = "project-1"
[models.kimi-for-coding]
provider = "kimi-for-coding"
model = "kimi-for-coding"
max_context_size = 262144
capabilities = ["image_in", "thinking", "video_in"]
display_name = "Kimi for Coding"
[loop_control]
max_retries_per_step = 3
max_ralph_iterations = 0
reserved_context_size = 50000
compaction_trigger_ratio = 0.85
[background]
max_running_tasks = 4
keep_alive_on_exit = false
kill_grace_period_ms = 2000
print_wait_ceiling_s = 3600
[services.moonshot_search]
base_url = "https://api.kimi.com/coding/v1/search"
api_key = "sk-search"
custom_headers = { "X-Search" = "1" }
[services.moonshot_fetch]
base_url = "https://api.kimi.com/coding/v1/fetch"
api_key = "sk-fetch"
[notifications]
claim_stale_after_ms = 15000
[thinking]
enabled = true
effort = "high"
`;
describe('SDK config TOML', () => {
it('resolves config paths through the config RPC wrapper', async () => {
const dir = await makeTempDir();
const rpc = createKimiConfigRpc();
await expect(rpc.resolveConfigPath({ homeDir: dir })).resolves.toBe(toPosix(join(dir, 'config.toml')));
});
it('returns structured validation issues through the config RPC wrapper', async () => {
const rpc = createKimiConfigRpc();
await expect(
rpc.validateConfigToml({
text: `
[providers.kimi]
type = "kimi"
[models.kimi]
provider = "kimi"
model = "kimi"
max_context_size = "large"
`,
filePath: 'broken.toml',
}),
).rejects.toMatchObject({
details: {
validationIssues: [
{
path: ['models', 'kimi', 'maxContextSize'],
},
],
},
});
});
it('parses the documented config shape and keeps TUI-only fields in raw', () => {
const config = parseConfigString(COMPLETE_TOML, 'complete.toml');
expect(config.defaultModel).toBe('kimi-for-coding');
expect(config.thinking?.enabled).toBe(true);
expect(config.thinking?.effort).toBe('high');
expect(config.defaultPermissionMode).toBe('auto');
expect(config.defaultPlanMode).toBe(false);
expect(config.mergeAllAvailableSkills).toBe(true);
expect(config.extraSkillDirs).toEqual(['~/team-skills', '.agents/team-skills']);
const provider = config.providers['kimi-for-coding'];
expect(provider).toMatchObject({
type: 'kimi',
baseUrl: 'https://api.kimi.com/coding/v1',
apiKey: 'sk-xxx',
customHeaders: { 'X-Custom-Header': 'value' },
env: { GOOGLE_CLOUD_PROJECT: 'project-1' },
});
expect(config.models?.['kimi-for-coding']).toMatchObject({
provider: 'kimi-for-coding',
model: 'kimi-for-coding',
maxContextSize: 262144,
capabilities: ['image_in', 'thinking', 'video_in'],
displayName: 'Kimi for Coding',
});
expect(config.loopControl).toEqual({
maxRetriesPerStep: 3,
maxRalphIterations: 0,
reservedContextSize: 50000,
compactionTriggerRatio: 0.85,
});
expect(config.background).toEqual({
maxRunningTasks: 4,
keepAliveOnExit: false,
killGracePeriodMs: 2000,
printWaitCeilingS: 3600,
});
expect(config.services?.moonshotSearch?.customHeaders).toEqual({ 'X-Search': '1' });
expect(config.services?.moonshotFetch?.apiKey).toBe('sk-fetch');
expect('theme' in config).toBe(false);
expect(config.raw?.['theme']).toBe('dark');
expect(config.raw?.['skip_afk_prompt_injection']).toBe(false);
expect(config.raw?.['show_thinking_stream']).toBe(true);
expect(config.raw?.['notifications']).toEqual({ claim_stale_after_ms: 15000 });
});
it('writes typed fields in snake_case and preserves unknown raw sections', async () => {
const dir = await makeTempDir();
const configPath = join(dir, 'config.toml');
const config = parseConfigString(COMPLETE_TOML, configPath);
await writeConfigFile(configPath, {
...config,
defaultModel: 'kimi-for-coding',
loopControl: {
...config.loopControl,
maxStepsPerTurn: 42,
},
});
const text = await readFile(configPath, 'utf-8');
expect(text).toContain('default_model = "kimi-for-coding"');
expect(text).toContain('default_permission_mode = "auto"');
expect(text).toContain('extra_skill_dirs = [ "~/team-skills", ".agents/team-skills" ]');
expect(text).not.toContain('default_yolo');
expect(text).toContain('max_steps_per_turn = 42');
expect(text).toContain('display_name = "Kimi for Coding"');
expect(text).toContain('GOOGLE_CLOUD_PROJECT = "project-1"');
expect(text).toContain('claim_stale_after_ms = 15000');
expect(text).toContain('theme = "dark"');
const reloaded = readConfigFile(configPath);
expect(reloaded.loopControl?.maxStepsPerTurn).toBe(42);
expect(reloaded.raw?.['theme']).toBe('dark');
});
it('accepts camelCase aliases without keeping unknown fields in typed config', () => {
const config = parseConfigString(`
defaultModel = "camel-model"
[providers.local]
type = "openai"
baseUrl = "https://example.test/v1"
apiKey = "sk-test"
unsupported_provider_field = "raw-only"
[models.camel-model]
provider = "local"
model = "gpt-test"
maxContextSize = 128000
displayName = "Camel Model"
custom_model_field = "raw-only"
[services.moonshotSearch]
baseUrl = "https://example.test/search"
apiKey = "sk-search"
[loopControl]
maxStepsPerRun = 7
[background]
maxRunningTasks = 2
`);
expect(config.defaultModel).toBe('camel-model');
expect(config.providers['local']).toMatchObject({
type: 'openai',
baseUrl: 'https://example.test/v1',
apiKey: 'sk-test',
});
expect(config.models?.['camel-model']).toMatchObject({
maxContextSize: 128000,
displayName: 'Camel Model',
});
expect(config.services?.moonshotSearch).toMatchObject({
baseUrl: 'https://example.test/search',
apiKey: 'sk-search',
});
expect(config.loopControl?.maxStepsPerTurn).toBe(7);
expect(config.background?.maxRunningTasks).toBe(2);
expect('unsupportedProviderField' in config.providers['local']!).toBe(false);
expect('customModelField' in config.models!['camel-model']!).toBe(false);
const rawProviders = config.raw?.['providers'] as Record<string, Record<string, unknown>>;
const rawModels = config.raw?.['models'] as Record<string, Record<string, unknown>>;
expect(rawProviders['local']?.['unsupported_provider_field']).toBe('raw-only');
expect(rawModels['camel-model']?.['custom_model_field']).toBe('raw-only');
});
});
describe('KimiHarness config API', () => {
it('loads default config when missing and deep-merges setConfig patches from disk', async () => {
const homeDir = await makeTempDir();
const configPath = join(homeDir, 'config.toml');
await writeFile(configPath, COMPLETE_TOML, 'utf-8');
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
await harness.setConfig({
providers: {
'kimi-for-coding': {
apiKey: 'sk-updated',
},
},
services: {
moonshotSearch: {
apiKey: 'sk-search-updated',
},
},
});
const config = await harness.getConfig({ reload: true });
expect(config.providers['kimi-for-coding']).toMatchObject({
type: 'kimi',
baseUrl: 'https://api.kimi.com/coding/v1',
apiKey: 'sk-updated',
env: { GOOGLE_CLOUD_PROJECT: 'project-1' },
});
expect(config.services?.moonshotSearch?.apiKey).toBe('sk-search-updated');
expect(config.raw?.['theme']).toBe('dark');
const text = await readFile(configPath, 'utf-8');
expect(text).toContain('theme = "dark"');
expect(text).toContain('GOOGLE_CLOUD_PROJECT = "project-1"');
expect(text).toContain('claim_stale_after_ms = 15000');
});
it('does not write invalid config patches', async () => {
const homeDir = await makeTempDir();
const configPath = join(homeDir, 'config.toml');
await writeFile(configPath, COMPLETE_TOML, 'utf-8');
const before = await readFile(configPath, 'utf-8');
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
const setInvalidConfig = harness.setConfig({
providers: {
bad: {
type: 'not-a-provider',
},
},
} as never);
await expect(setInvalidConfig).rejects.toBeInstanceOf(KimiError);
await expect(setInvalidConfig).rejects.toMatchObject({
code: 'config.invalid',
} satisfies Partial<KimiError>);
await expect(readFile(configPath, 'utf-8')).resolves.toBe(before);
});
it('uses default config when the config file is absent', async () => {
const homeDir = await makeTempDir();
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
await expect(harness.getConfig()).resolves.toEqual({ providers: {} });
});
it('returns experimental feature metadata through the harness', async () => {
vi.stubEnv('KIMI_CODE_EXPERIMENTAL_FLAG', '0');
const homeDir = await makeTempDir();
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
const features = await harness.getExperimentalFeatures();
expect(features).toEqual([
{
id: 'tool-select',
title: 'Tool select (progressive tool disclosure)',
description:
'Keep MCP tool schemas out of the immutable top-level tools[]; the model loads them on demand via the select_tools tool. Only takes effect on models whose capability catalog declares dynamically loaded tools.',
surface: 'core',
env: 'KIMI_CODE_EXPERIMENTAL_TOOL_SELECT',
defaultEnabled: false,
enabled: false,
source: 'default',
},
{
id: 'secondary-model',
title: 'Secondary model for subagents',
description:
'Let newly spawned subagents use a separately configured secondary model by default, with an explicit primary-model override for quality-sensitive tasks.',
surface: 'core',
env: 'KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL',
defaultEnabled: false,
enabled: false,
source: 'default',
},
]);
});
it('can create the default config scaffold without selecting a model', async () => {
const homeDir = await makeTempDir();
const configPath = join(homeDir, 'config.toml');
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
await harness.ensureConfigFile();
const text = await readFile(configPath, 'utf-8');
expect(text).toContain('Runtime settings for Kimi Code.');
expect(text).not.toMatch(/^default_thinking =/m);
expect(text).not.toMatch(/^default_model =/m);
const config = await harness.getConfig({ reload: true });
expect(config.providers).toEqual({});
expect(config.defaultModel).toBeUndefined();
expect(config.thinking?.enabled).toBeUndefined();
});
it('reloads an active session without closing the SDK session wrapper', async () => {
const homeDir = await makeTempDir();
const workDir = join(homeDir, 'work');
const configPath = join(homeDir, 'config.toml');
await writeFile(configPath, COMPLETE_TOML, 'utf-8');
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
const session = await harness.createSession({
id: 'session-sdk-reload',
workDir,
model: 'kimi-for-coding',
});
expect(session.getResumeState()).toBeUndefined();
const reloaded = await harness.reloadSession({ id: session.id });
expect(reloaded).toBe(session);
expect(harness.getSession(session.id)).toBe(session);
expect(session.getResumeState()?.agents['main']).toBeDefined();
await expect(session.getStatus()).resolves.toMatchObject({ model: 'kimi-for-coding' });
});
it('forwards forcePluginSessionStartReminder to the active session reload', async () => {
const homeDir = await makeTempDir();
const workDir = join(homeDir, 'work');
const configPath = join(homeDir, 'config.toml');
await writeFile(configPath, COMPLETE_TOML, 'utf-8');
const harness = createKimiHarness({ homeDir, identity: TEST_IDENTITY });
const session = await harness.createSession({
id: 'session-sdk-reload-forward',
workDir,
model: 'kimi-for-coding',
});
const reloadSpy = vi.spyOn(session, 'reloadSession').mockResolvedValue({} as never);
await harness.reloadSession({ id: session.id, forcePluginSessionStartReminder: true });
expect(reloadSpy).toHaveBeenCalledWith({ forcePluginSessionStartReminder: true });
});
});