# How Kimi Code Loads Its Configuration Schema and Environment Variables

> Discover how Kimi Code loads its configuration schema and environment variables. Learn about TOML validation, Zod schemas, and typed KimiConfig objects for robust setup.

- Repository: [Moonshot AI/kimi-code](https://github.com/MoonshotAI/kimi-code)
- Tags: internals
- Published: 2026-07-22

---

**Kimi Code validates a TOML configuration file against a central Zod schema and applies environment-variable overrides through explicit bindings and a generic per-model overlay before exposing a fully typed `KimiConfig` object.**

The `MoonshotAI/kimi-code` engine stores its runtime settings in a TOML file that is parsed, merged with environment overrides, and validated at startup. This article explains how the Kimi Code configuration schema and environment variable loading work together to provide type-safe, customizable behavior without requiring constant file edits.

## The Zod Configuration Schema

All runtime settings are defined in a single source of truth: [`packages/agent-core/src/config/schema.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/schema.ts). The top-level export is `KimiConfigSchema`, a Zod object that describes every legal section of the configuration file.

The schema enforces the following major sections:

| Section | Schema Reference | Description |
| --- | --- | --- |
| `providers` | `ProviderConfigSchema` | Provider definitions covering type, API key, base URL, and OAuth. |
| `models` | `ModelAliasSchema` | Model aliases and per-model parameter overrides. |
| `thinking` | `ThinkingConfigSchema` | Flags for adaptive thinking and effort selection. |
| `permission` | `PermissionConfigSchema` | Tool usage rules (`allow`, `deny`, `ask`). |
| `loopControl` | `LoopControlSchema` | Planner limits such as max steps, retries, and compaction ratio. |
| `background` | `BackgroundConfigSchema` | Background task timeouts and auto-background behavior on Bash timeouts. |
| `image` | `ImageConfigSchema` | Image limits including `maxEdgePx` and `readByteBudget`. |
| `experimental` | `record<string, boolean>` | Feature-flag toggles for experimental behavior. |

Each subsection—such as `PermissionRuleSchema` or `LoopControlSchema`—is co-located in the same file. [`schema.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/schema.ts) also exports **patch schemas** like `KimiConfigPatchSchema`, which support incremental updates from commands such as `kimi doctor`.

If validation fails, the engine throws a `KimiError` with `ErrorCodes.CONFIG_INVALID` and the CLI prints a detailed, user-friendly message.

## Loading and Resolving the TOML File

The orchestration entry point is [`packages/agent-core/src/config/resolve.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/resolve.ts). Its exported `loadConfig` function handles the entire startup pipeline:

```ts
export async function loadConfig(
  configPath: string,
  env: NodeJS.ProcessEnv = process.env,
): Promise<KimiConfig> {
  const raw = await readFile(configPath, 'utf8');
  const toml = parseToml(raw);                // ↳ src/config/toml.ts
  const merged = mergeConfig(toml, env);      // ↳ src/config/merge.ts
  return validateConfig(merged);              // ↳ src/config/schema.ts
}

```

The loader executes four deterministic steps:

1. **`readFile`** reads the TOML text from disk.
2. **`parseToml`**—a thin wrapper around `@iarna/toml` in [`packages/agent-core/src/config/toml.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/toml.ts)—converts the text into a plain JavaScript object.
3. **`mergeConfig`** (from [`packages/agent-core/src/config/merge.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/merge.ts)) overlays any matching environment variables onto the parsed object.
4. **`validateConfig`** runs `KimiConfigSchema.parse()` and returns a strongly typed `KimiConfig` instance.

Because validation occurs after merging, environment variables are checked against the same Zod rules as file-based values.

## Environment-Variable Bindings and Overlays

Kimi Code uses a **two-stage** environment-variable system. First, explicit bindings map specific variables to schema paths. Second, a generic overlay synthesizes dynamic keys such as `KIMI_MODEL_*` for per-model tweaks.

### Section-Level Env Bindings

Explicit bindings are declared in [`packages/agent-core/src/config/kimi-env-params.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/kimi-env-params.ts). The helper `envBindings`, exported from [`packages/agent-core/src/config/config.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/config.ts), creates a typed mapping between a Zod schema and concrete environment variable names:

```ts
export const ImageEnvBindings = envBindings(ImageConfigSchema, {
  maxEdgePx: 'KIMI_IMAGE_MAX_EDGE_PX',
  readByteBudget: 'KIMI_IMAGE_READ_BYTE_BUDGET',
});

```

When `mergeConfig` runs, it scans `process.env` for the declared names. If a variable is present, its value overwrites the corresponding TOML entry **before** Zod validation occurs. This pattern is repeated across all major sections, ensuring users can override individual fields without touching the config file.

### Generic Per-Model Overlay

For model-specific overrides, [`packages/agent-core/src/config/env-model.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/env-model.ts) implements a generic overlay that is registered centrally in [`src/app/kosongConfig/envOverlay.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/app/kosongConfig/envOverlay.ts):

```ts
export const ModelEnvOverlay: ConfigEffectiveOverlay = {
  // e.g. KIMI_MODEL_GPT4_MAX_CONTEXT_SIZE → overrides models.gpt4.maxContextSize
  get(env, key) { … }
};

```

This overlay plugs into the central `IConfigRegistry` (see [`src/app/kosongConfig/kosongConfigService.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/src/app/kosongConfig/kosongConfigService.ts)). It translates variables matching the `KIMI_MODEL_*` pattern into nested property updates inside the `models` section, enabling per-model adjustments with no schema file edits.

## Practical Override Examples

### Overriding a Provider API Key

Assume your [`config.toml`](https://github.com/MoonshotAI/kimi-code/blob/main/config.toml) contains:

```toml
[providers.myOpenAI]
type = "openai"
apiKey = "default-key"

```

You can override the key at runtime by exporting a variable that follows the section binding convention:

```bash
export KIMI_PROVIDER_MYOPENAI_API_KEY="prod-secret-key"
kimi run …

```

Internally, `mergeConfig` detects the `KIMI_PROVIDER_*` variable, injects the value into the configuration object, and `validateConfig` confirms it against `ProviderConfigSchema` before the engine starts.

### Enabling Debug Logging

Logging behavior can also be controlled from the shell without modifying TOML:

```bash
export KIMI_LOG_LEVEL=debug
kimi doctor

```

The telemetry bootstrap in [`packages/telemetry/src/bootstrap.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/telemetry/src/bootstrap.ts) reads `KIMI_LOG_LEVEL` directly from `process.env`. Accepted levels are `off`, `error`, `warn`, `info`, and `debug`.

## Summary

- The **Zod schema** in [`packages/agent-core/src/config/schema.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/schema.ts) defines every legal configuration section, from providers to image limits, guaranteeing compile-time and runtime type safety.
- The **loader** in [`packages/agent-core/src/config/resolve.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/resolve.ts) reads the TOML file, parses it via `@iarna/toml`, merges environment variables, and validates the result.
- **Explicit env bindings** in [`packages/agent-core/src/config/kimi-env-params.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/kimi-env-params.ts) map precise variable names to schema fields, while the **generic overlay** in [`packages/agent-core/src/config/env-model.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/env-model.ts) enables flexible `KIMI_MODEL_*` overrides.
- A validation failure at any stage produces a `KimiError` with `ErrorCodes.CONFIG_INVALID`, preventing the engine from starting with bad state.

## Frequently Asked Questions

### What configuration file format does Kimi Code use?

Kimi Code uses a **TOML** file, typically [`config.toml`](https://github.com/MoonshotAI/kimi-code/blob/main/config.toml). The `loadConfig` function in [`packages/agent-core/src/config/resolve.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/resolve.ts) reads this file and passes it through a thin `parseToml` wrapper around the `@iarna/toml` parser.

### How does Kimi Code validate user configuration?

It validates every loaded object against `KimiConfigSchema`, a comprehensive Zod definition in [`packages/agent-core/src/config/schema.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/schema.ts). If parsing fails, the framework throws a `KimiError` carrying `ErrorCodes.CONFIG_INVALID` and surfaces a detailed error message in the CLI.

### Can any configuration setting be overridden with an environment variable?

Nearly every setting can be overridden through one of two mechanisms: **section-level bindings** declared in [`packages/agent-core/src/config/kimi-env-params.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/kimi-env-params.ts) (for example, `KIMI_IMAGE_MAX_EDGE_PX`), or the generic **`KIMI_MODEL_*` overlay** implemented in [`packages/agent-core/src/config/env-model.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/env-model.ts) for per-model parameters.

### Where does the configuration loading process begin?

The process begins in [`packages/agent-core/src/config/resolve.ts`](https://github.com/MoonshotAI/kimi-code/blob/main/packages/agent-core/src/config/resolve.ts) inside the async `loadConfig` function. This function coordinates file reading, TOML parsing, environment merging, and Zod validation into a single pipeline that returns a typed `KimiConfig` object.