--- url: /en/reference/kimi-acp.md --- # `kimi acp` Subcommand The `kimi acp` command starts a multi-session ACP (Agent Client Protocol) server. ```sh kimi acp ``` ## Description ACP is a standardized protocol that allows IDEs and other clients to interact with AI agents. ## Use cases * IDE plugin integration (e.g., JetBrains, Zed) * Custom ACP client development * Multi-session concurrent processing For using Kimi Code CLI in IDEs, see [Using in IDEs](../guides/ides.md). ## Authentication The ACP server checks user authentication status before creating or loading sessions. If the user is not logged in, the server returns an `AUTH_REQUIRED` error (code `-32000`) with available authentication method details. Upon receiving this error, the client should guide the user to run the `kimi login` command in the terminal to complete login. Once logged in, subsequent ACP requests will proceed normally. --- --- url: /zh/reference/kimi-acp.md --- # `kimi acp` 子命令 `kimi acp` 命令启动一个支持多会话的 ACP (Agent Client Protocol) 服务器。 ```sh kimi acp ``` ## 说明 ACP 是一种标准化协议,允许 IDE 和其他客户端与 AI Agent 进行交互。 ## 使用场景 * IDE 插件集成(如 JetBrains、Zed) * 自定义 ACP 客户端开发 * 多会话并发处理 如需在 IDE 中使用 Kimi Code CLI,请参阅 [在 IDE 中使用](../guides/ides.md)。 ## 认证 ACP 服务器在创建或加载会话前会检查用户认证状态。如果未登录,服务器会返回 `AUTH_REQUIRED` 错误(错误码 `-32000`),并携带可用的认证方式信息。 客户端收到此错误后,应引导用户在终端中执行 `kimi login` 命令完成登录。登录成功后,后续的 ACP 请求即可正常执行。 --- --- url: /en/reference/kimi-info.md --- # `kimi info` Subcommand `kimi info` displays version and protocol information for Kimi Code CLI. ```sh kimi info [--json] ``` ## Options | Option | Description | |--------|-------------| | `--json` | Output in JSON format | ## Output | Field | Description | |-------|-------------| | `kimi_cli_version` | Kimi Code CLI version number | | `agent_spec_versions` | List of supported agent spec versions | | `wire_protocol_version` | Wire protocol version | | `python_version` | Python runtime version | ## Examples **Text output** ```sh $ kimi info kimi-cli version: 1.20.0 agent spec versions: 1 wire protocol: 1.10 python version: 3.13.1 ``` **JSON output** ```sh $ kimi info --json {"kimi_cli_version": "1.20.0", "agent_spec_versions": ["1"], "wire_protocol_version": "1.10", "python_version": "3.13.1"} ``` --- --- url: /zh/reference/kimi-info.md --- # `kimi info` 子命令 `kimi info` 显示 Kimi Code CLI 的版本和协议信息。 ```sh kimi info [--json] ``` ## 选项 | 选项 | 说明 | |------|------| | `--json` | 以 JSON 格式输出 | ## 输出内容 | 字段 | 说明 | |------|------| | `kimi_cli_version` | Kimi Code CLI 版本号 | | `agent_spec_versions` | 支持的 Agent 规格版本列表 | | `wire_protocol_version` | Wire 协议版本 | | `python_version` | Python 运行时版本 | ## 示例 **文本输出** ```sh $ kimi info kimi-cli version: 1.20.0 agent spec versions: 1 wire protocol: 1.10 python version: 3.13.1 ``` **JSON 输出** ```sh $ kimi info --json {"kimi_cli_version": "1.20.0", "agent_spec_versions": ["1"], "wire_protocol_version": "1.10", "python_version": "3.13.1"} ``` --- --- url: /en/reference/kimi-mcp.md --- # `kimi mcp` Subcommand `kimi mcp` is used to manage MCP (Model Context Protocol) server configurations. For concepts and usage of MCP, see [Model Context Protocol](../customization/mcp.md). ```sh kimi mcp COMMAND [ARGS] ``` ## `add` Add an MCP server configuration. ```sh kimi mcp add [OPTIONS] NAME [TARGET_OR_COMMAND...] ``` **Arguments** | Argument | Description | |----------|-------------| | `NAME` | Server name, used for identification and reference | | `TARGET_OR_COMMAND...` | URL for `http` mode; command for `stdio` mode (must start with `--`) | **Options** | Option | Short | Description | |--------|-------|-------------| | `--transport TYPE` | `-t` | Transport type: `stdio` (default) or `http` | | `--env KEY=VALUE` | `-e` | Environment variable (`stdio` only), can be specified multiple times | | `--header KEY:VALUE` | `-H` | HTTP header (`http` only), can be specified multiple times | | `--auth TYPE` | `-a` | Authentication type (e.g., `oauth`, `http` only) | ## `list` List all configured MCP servers. ```sh kimi mcp list ``` Output includes: * Configuration file path * Name, transport type, and target for each server * Authorization status for OAuth servers ## `remove` Remove an MCP server configuration. ```sh kimi mcp remove NAME ``` **Arguments** | Argument | Description | |----------|-------------| | `NAME` | Name of server to remove | ## `auth` Authorize an MCP server that uses OAuth. ```sh kimi mcp auth NAME ``` This will open a browser for the OAuth authorization flow. After successful authorization, the token is cached in `~/.kimi/mcp-oauth/` for future use. **Arguments** | Argument | Description | |----------|-------------| | `NAME` | Name of server to authorize | ::: tip Only servers added with `--auth oauth` require this command. ::: ## `reset-auth` Clear the cached OAuth token for an MCP server. ```sh kimi mcp reset-auth NAME ``` **Arguments** | Argument | Description | |----------|-------------| | `NAME` | Name of server to reset authorization | After clearing, you need to run `kimi mcp auth` again to re-authorize. After upgrading from older versions that used FastMCP 2.x, existing OAuth MCP tokens are not migrated automatically; if `kimi mcp list` shows that authorization is required, run `kimi mcp auth NAME` again. ## `test` Test connection to an MCP server and list available tools. ```sh kimi mcp test NAME ``` **Arguments** | Argument | Description | |----------|-------------| | `NAME` | Name of server to test | Output includes: * Connection status * Number of available tools * Tool names and descriptions --- --- url: /zh/reference/kimi-mcp.md --- # `kimi mcp` 子命令 `kimi mcp` 用于管理 MCP (Model Context Protocol) 服务器配置。关于 MCP 的概念和使用方式,详见 [Model Context Protocol](../customization/mcp.md)。 ```sh kimi mcp COMMAND [ARGS] ``` ## `add` 添加 MCP 服务器配置。 ```sh kimi mcp add [OPTIONS] NAME [TARGET_OR_COMMAND...] ``` **参数** | 参数 | 说明 | |------|------| | `NAME` | 服务器名称,用于标识和引用 | | `TARGET_OR_COMMAND...` | `http` 模式为 URL;`stdio` 模式为命令(需以 `--` 开头) | **选项** | 选项 | 简写 | 说明 | |------|------|------| | `--transport TYPE` | `-t` | 传输类型:`stdio`(默认)或 `http` | | `--env KEY=VALUE` | `-e` | 环境变量(仅 `stdio`),可多次指定 | | `--header KEY:VALUE` | `-H` | HTTP Header(仅 `http`),可多次指定 | | `--auth TYPE` | `-a` | 认证类型(如 `oauth`,仅 `http`) | ## `list` 列出所有已配置的 MCP 服务器。 ```sh kimi mcp list ``` 输出包括: * 配置文件路径 * 每个服务器的名称、传输类型和目标 * OAuth 服务器的授权状态 ## `remove` 移除 MCP 服务器配置。 ```sh kimi mcp remove NAME ``` **参数** | 参数 | 说明 | |------|------| | `NAME` | 要移除的服务器名称 | ## `auth` 对使用 OAuth 的 MCP 服务器进行授权。 ```sh kimi mcp auth NAME ``` 执行后会打开浏览器进行 OAuth 授权流程。授权成功后,token 会缓存在 `~/.kimi/mcp-oauth/` 以供后续使用。 **参数** | 参数 | 说明 | |------|------| | `NAME` | 要授权的服务器名称 | ::: tip 提示 只有使用 `--auth oauth` 添加的服务器才需要执行此命令。 ::: ## `reset-auth` 清除 MCP 服务器的 OAuth 缓存 token。 ```sh kimi mcp reset-auth NAME ``` **参数** | 参数 | 说明 | |------|------| | `NAME` | 要重置授权的服务器名称 | 清除后需要重新执行 `kimi mcp auth` 进行授权。 从使用 FastMCP 2.x 的旧版本升级后,已有 OAuth MCP token 不会自动迁移;如果 `kimi mcp list` 显示需要授权,请重新运行 `kimi mcp auth NAME`。 ## `test` 测试与 MCP 服务器的连接并列出可用工具。 ```sh kimi mcp test NAME ``` **参数** | 参数 | 说明 | |------|------| | `NAME` | 要测试的服务器名称 | 输出包括: * 连接状态 * 可用工具数量 * 工具名称和描述 --- --- url: /en/reference/kimi-term.md --- # `kimi term` Subcommand The `kimi term` command launches the [Toad](https://github.com/batrachianai/toad) terminal UI, a modern terminal interface built with [Textual](https://textual.textualize.io/). ```sh kimi term [OPTIONS] ``` ## Description [Toad](https://github.com/batrachianai/toad) is a graphical terminal interface for Kimi Code CLI that communicates with the Kimi Code CLI backend via the ACP protocol. It provides a richer interactive experience with better output rendering and layout. When you run `kimi term`, it automatically starts a `kimi acp` server in the background, and Toad connects to it as an ACP client. ## Options All extra options are passed through to the internal `kimi acp` command. For example: ```sh kimi term --work-dir /path/to/project --model kimi-k2 ``` Common options: | Option | Description | |--------|-------------| | `--work-dir PATH` | Specify working directory | | `--model NAME` | Specify model | | `--yolo` | Auto-approve all tool calls | For the full list of options, see [`kimi` command](./kimi-command.md). ## System requirements ::: warning Note `kimi term` requires Python 3.14+. If you installed Kimi Code CLI with an older Python version, you need to reinstall with Python 3.14: ```sh uv tool install --python 3.14 kimi-cli ``` ::: --- --- url: /zh/reference/kimi-term.md --- # `kimi term` 子命令 `kimi term` 命令启动 [Toad](https://github.com/batrachianai/toad) 终端 UI,这是一个基于 [Textual](https://textual.textualize.io/) 的现代终端界面。 ```sh kimi term [OPTIONS] ``` ## 说明 [Toad](https://github.com/batrachianai/toad) 是 Kimi Code CLI 的图形化终端界面,通过 ACP 协议与 Kimi Code CLI 后端通信。它提供了更丰富的交互体验,包括更好的输出渲染和界面布局。 运行 `kimi term` 时,会自动在后台启动一个 `kimi acp` 服务器,Toad 作为 ACP 客户端连接到该服务器。 ## 选项 所有额外的选项会透传给内部的 `kimi acp` 命令。例如: ```sh kimi term --work-dir /path/to/project --model kimi-k2 ``` 常用选项: | 选项 | 说明 | |------|------| | `--work-dir PATH` | 指定工作目录 | | `--model NAME` | 指定模型 | | `--yolo` | 自动批准所有工具调用 | 完整选项请参阅 [`kimi` 命令](./kimi-command.md)。 ## 系统要求 ::: warning 注意 `kimi term` 需要 Python 3.14+。如果你使用较低版本的 Python 安装了 Kimi Code CLI,需要重新用 Python 3.14 安装才能使用此功能: ```sh uv tool install --python 3.14 kimi-cli ``` ::: --- --- url: /en/reference/kimi-command.md --- # `kimi` Command `kimi` is the main command for Kimi Code CLI, used to start interactive sessions or execute single queries. ```sh kimi [OPTIONS] COMMAND [ARGS] ``` ## Basic information | Option | Short | Description | |--------|-------|-------------| | `--version` | `-V` | Show version number and exit | | `--help` | `-h` | Show help message and exit | | `--verbose` | | Output detailed runtime information | | `--debug` | | Log debug information (output to `~/.kimi/logs/kimi.log`) | ## Agent configuration | Option | Description | |--------|-------------| | `--agent NAME` | Use built-in agent, options: `default`, `okabe` | | `--agent-file PATH` | Use custom agent file | `--agent` and `--agent-file` are mutually exclusive. See [Agents and Subagents](../customization/agents.md) for details. ## Configuration files | Option | Description | |--------|-------------| | `--config STRING` | Load TOML/JSON configuration string | | `--config-file PATH` | Load configuration file (default `~/.kimi/config.toml`) | `--config` and `--config-file` are mutually exclusive. Both configuration strings and files support TOML and JSON formats. See [Config Files](../configuration/config-files.md) for details. ## Model selection | Option | Short | Description | |--------|-------|-------------| | `--model NAME` | `-m` | Specify LLM model, overrides default model in config file | ## Working directory | Option | Short | Description | |--------|-------|-------------| | `--work-dir PATH` | `-w` | Specify working directory (default current directory) | | `--add-dir PATH` | | Add an additional directory to the workspace scope, can be specified multiple times | The working directory determines the root directory for file operations. Relative paths work within the working directory; absolute paths are required to access files outside it. `--add-dir` expands the workspace scope to include directories outside the working directory, making all file tools able to access files in those directories. Added directories are persisted with the session state. You can also add directories at runtime via the [`/add-dir`](./slash-commands.md#add-dir) slash command. ## Session management | Option | Short | Description | |--------|-------|-------------| | `--continue` | `-C` | Continue the previous session in the current working directory | | `--session [ID]` / `--resume [ID]` | `-S` / `-r` | Resume a session. With ID: resume that session (creates new if not found). Without ID: open interactive session picker (shell mode only) | `--continue` and `--session`/`--resume` are mutually exclusive. ## Input and commands | Option | Short | Description | |--------|-------|-------------| | `--prompt TEXT` | `-p` | Pass user prompt, doesn't enter interactive mode | | `--command TEXT` | `-c` | Alias for `--prompt` | When using `--prompt` (or `--command`), Kimi Code CLI exits after processing the query (unless `--print` is specified, results are still displayed in interactive mode). ## Loop control | Option | Description | |--------|-------------| | `--max-steps-per-turn N` | Maximum steps per turn, overrides `loop_control.max_steps_per_turn` in config file | | `--max-retries-per-step N` | Maximum retries per step, overrides `loop_control.max_retries_per_step` in config file | | `--max-ralph-iterations N` | Number of iterations for Ralph Loop mode; `0` disables; `-1` is unlimited | ### Ralph Loop [Ralph](https://ghuntley.com/ralph/) is a technique that puts an agent in a loop: the same prompt is fed again and again so the agent can keep iterating one big task. When `--max-ralph-iterations` is not `0`, Kimi Code CLI enters Ralph Loop mode and automatically loops through task execution until the agent outputs `STOP` or the iteration limit is reached. ## UI modes | Option | Description | |--------|-------------| | `--print` | Run in print mode (non-interactive), implicitly enables `--afk` | | `--quiet` | Shortcut for `--print --output-format text --final-message-only` | | `--acp` | Run in ACP server mode (deprecated, use `kimi acp` instead) | | `--wire` | Run in Wire server mode (experimental) | The four options are mutually exclusive, only one can be selected. Default is shell mode. See [Print Mode](../customization/print-mode.md) and [Wire Mode](../customization/wire-mode.md) for details. ## Print mode options The following options are only effective in `--print` mode: | Option | Description | |--------|-------------| | `--input-format FORMAT` | Input format: `text` (default) or `stream-json` | | `--output-format FORMAT` | Output format: `text` (default) or `stream-json` | | `--final-message-only` | Only output the final assistant message | `stream-json` format uses JSONL (one JSON object per line) for programmatic integration. ## MCP configuration | Option | Description | |--------|-------------| | `--mcp-config-file PATH` | Load MCP config file, can be specified multiple times | | `--mcp-config JSON` | Load MCP config JSON string, can be specified multiple times | Default loads `~/.kimi/mcp.json` (if exists). See [Model Context Protocol](../customization/mcp.md) for details. ## Approval control | Option | Short | Description | |--------|-------|-------------| | `--yolo` | `-y` | Auto-approve all tool calls (user still reachable for `AskUserQuestion`) | | `--yes` | | Alias for `--yolo` | | `--auto-approve` | | Alias for `--yolo` | | `--afk` | | Away-from-keyboard: auto-approve tool calls and auto-dismiss `AskUserQuestion`. Use when no user will be at the terminal | ::: warning Note In YOLO or AFK mode, all file modifications and shell commands are automatically executed. Use with caution. ::: ## Plan mode | Option | Description | |--------|-------------| | `--plan` | Start a new session in plan mode | When started with `--plan`, the AI can only use read-only tools to explore the codebase and write an implementation plan. When resuming an existing session, `--plan` forces plan mode on; resuming without `--plan` preserves the session's existing state. You can also set `default_plan_mode = true` in the config file to start new sessions in plan mode by default. See [Configuration files](../configuration/config-files.md). ## Thinking mode | Option | Description | |--------|-------------| | `--thinking` | Enable thinking mode | | `--no-thinking` | Disable thinking mode | Thinking mode requires model support. If not specified, uses the last session's setting. ## Skills configuration | Option | Description | |--------|-------------| | `--skills-dir PATH` | Append additional skills directories (repeatable) | When not specified, Kimi Code CLI automatically discovers user-level and project-level skills directories in priority order. See [Agent Skills](../customization/skills.md) for details. ## Subcommands | Subcommand | Description | |------------|-------------| | [`kimi login`](#kimi-login) | Log in to your Kimi account | | [`kimi logout`](#kimi-logout) | Log out from your Kimi account | | [`kimi info`](./kimi-info.md) | Display version and protocol information | | [`kimi acp`](./kimi-acp.md) | Start multi-session ACP server | | [`kimi mcp`](./kimi-mcp.md) | Manage MCP server configuration | | [`kimi plugin`](../customization/plugins.md) | Manage plugins (Beta) | | [`kimi term`](./kimi-term.md) | Launch the Toad terminal UI | | [`kimi export`](#kimi-export) | Export a session as a ZIP file | | [`kimi vis`](./kimi-vis.md) | Launch the Agent Tracing Visualizer (Technical Preview) | | [`kimi web`](./kimi-web.md) | Start the Web UI server | ### `kimi login` Log in to your Kimi account. This automatically opens a browser; complete account authorization and available models will be automatically configured. ```sh kimi login ``` ### `kimi logout` Log out from your Kimi account. This clears stored OAuth credentials and removes related configuration from the config file. ```sh kimi logout ``` ### `kimi export` Export session data as a ZIP file. The ZIP contains all files in the session directory (`context.jsonl`, `wire.jsonl`, `state.json`, etc.) and related diagnostic logs. ```sh kimi export [] [-o ] [--yes] ``` | Argument / Option | Description | |--------|-------------| | `` | Session ID to export. If omitted, the CLI previews the previous session for the current working directory and asks for confirmation before exporting | | `--output, -o` | Output ZIP file path (defaults to `session-.zip` in the current directory) | | `--yes, -y` | Skip the confirmation prompt when exporting the default previous session | ::: info Added Added in version 1.20. ::: ### `kimi vis` ::: warning Note Technical Preview feature, may be unstable. ::: Launch the Agent Tracing Visualizer to view and analyze session traces in a browser. ```sh kimi vis [OPTIONS] ``` | Option | Short | Description | |--------|-------|-------------| | `--host TEXT` | `-h` | Host address to bind to (default: `127.0.0.1`) | | `--network` | `-n` | Listen on all network interfaces (bind to `0.0.0.0`) with auto-detected LAN IP display | | `--port INTEGER` | `-p` | Port number to bind to (default: `5495`) | | `--open / --no-open` | | Automatically open browser (default: enabled) | | `--reload` | | Enable auto-reload (development mode) | See [Agent Tracing Visualizer](./kimi-vis.md) for details. ### `kimi web` Start the Web UI server to access Kimi Code CLI through a browser. ```sh kimi web [OPTIONS] ``` If the default port is in use, the server will pick the next available port (by default `5494`–`5503`) and print a notice in the terminal. | Option | Short | Description | |--------|-------|-------------| | `--host TEXT` | `-h` | Host address to bind to (default: `127.0.0.1`) | | `--network` | `-n` | Listen on all network interfaces (bind to `0.0.0.0`) with auto-detected LAN IP display | | `--port INTEGER` | `-p` | Port number to bind to (default: `5494`) | | `--reload` | | Enable auto-reload (development mode) | | `--open / --no-open` | | Automatically open browser (default: enabled) | Examples: ```sh # Default startup, automatically opens browser kimi web # Specify port kimi web --port 8080 # Don't automatically open browser kimi web --no-open # Bind to all network interfaces (allow LAN access) kimi web --host 0.0.0.0 ``` See [Web UI](./kimi-web.md) for details. --- --- url: /zh/reference/kimi-command.md --- # `kimi` 命令 `kimi` 是 Kimi Code CLI 的主命令,用于启动交互式会话或执行单次查询。 ```sh kimi [OPTIONS] COMMAND [ARGS] ``` ## 基本信息 | 选项 | 简写 | 说明 | |------|------|------| | `--version` | `-V` | 显示版本号并退出 | | `--help` | `-h` | 显示帮助信息并退出 | | `--verbose` | | 输出详细运行信息 | | `--debug` | | 记录调试日志(输出到 `~/.kimi/logs/kimi.log`) | ## Agent 配置 | 选项 | 说明 | |------|------| | `--agent NAME` | 使用内置 Agent,可选值:`default`、`okabe` | | `--agent-file PATH` | 使用自定义 Agent 文件 | `--agent` 和 `--agent-file` 互斥,不能同时使用。详见 [Agent 与子 Agent](../customization/agents.md)。 ## 配置文件 | 选项 | 说明 | |------|------| | `--config STRING` | 加载 TOML/JSON 配置字符串 | | `--config-file PATH` | 加载配置文件(默认 `~/.kimi/config.toml`) | `--config` 和 `--config-file` 互斥。配置字符串和文件均支持 TOML 和 JSON 格式。详见 [配置文件](../configuration/config-files.md)。 ## 模型选择 | 选项 | 简写 | 说明 | |------|------|------| | `--model NAME` | `-m` | 指定 LLM 模型,覆盖配置文件中的默认模型 | ## 工作目录 | 选项 | 简写 | 说明 | |------|------|------| | `--work-dir PATH` | `-w` | 指定工作目录(默认当前目录) | | `--add-dir PATH` | | 添加额外目录到工作区范围,可多次指定 | 工作目录决定了文件操作的根目录。在工作目录内可使用相对路径,操作工作目录外的文件需使用绝对路径。 `--add-dir` 可以将工作目录之外的目录纳入工作区范围,使所有文件工具可以访问该目录中的文件。添加的目录会随会话状态持久化。运行中也可以通过 [`/add-dir`](./slash-commands.md#add-dir) 斜杠命令添加。 ## 会话管理 | 选项 | 简写 | 说明 | |------|------|------| | `--continue` | `-C` | 继续当前工作目录的上一个会话 | | `--session [ID]` / `--resume [ID]` | `-S` / `-r` | 恢复会话。带 ID 时恢复指定会话(不存在则创建新会话);不带 ID 时打开交互式会话选择器(仅 Shell 模式) | `--continue` 和 `--session`/`--resume` 互斥。 ## 输入与命令 | 选项 | 简写 | 说明 | |------|------|------| | `--prompt TEXT` | `-p` | 传入用户提示,不进入交互模式 | | `--command TEXT` | `-c` | `--prompt` 的别名 | 使用 `--prompt`(或 `--command`)时,Kimi Code CLI 会处理完查询后退出(除非指定 `--print`,否则仍以交互模式显示结果)。 ## 循环控制 | 选项 | 说明 | |------|------| | `--max-steps-per-turn N` | 单轮最大步数,覆盖配置文件中的 `loop_control.max_steps_per_turn` | | `--max-retries-per-step N` | 单步最大重试次数,覆盖配置文件中的 `loop_control.max_retries_per_step` | | `--max-ralph-iterations N` | Ralph 循环模式的迭代次数;`0` 表示关闭;`-1` 表示无限 | ### Ralph 循环 [Ralph](https://ghuntley.com/ralph/) 是一种把 Agent 放进循环的技术:同一条提示词会被反复喂给 Agent,让它围绕一个任务持续迭代。 当 `--max-ralph-iterations` 非 `0` 时,Kimi Code CLI 会进入 Ralph 循环模式,自动循环执行任务,直到 Agent 输出 `STOP` 或达到迭代上限。 ## UI 模式 | 选项 | 说明 | |------|------| | `--print` | 以 Print 模式运行(非交互式),隐式启用 `--afk` | | `--quiet` | `--print --output-format text --final-message-only` 的快捷方式 | | `--acp` | 以 ACP 服务器模式运行(已弃用,请使用 `kimi acp`) | | `--wire` | 以 Wire 服务器模式运行(实验性) | 四个选项互斥,只能选择一个。默认使用 Shell 模式。详见 [Print 模式](../customization/print-mode.md) 和 [Wire 模式](../customization/wire-mode.md)。 ## Print 模式选项 以下选项仅在 `--print` 模式下有效: | 选项 | 说明 | |------|------| | `--input-format FORMAT` | 输入格式:`text`(默认)或 `stream-json` | | `--output-format FORMAT` | 输出格式:`text`(默认)或 `stream-json` | | `--final-message-only` | 仅输出最终的 assistant 消息 | `stream-json` 格式使用 JSONL(每行一个 JSON 对象),用于程序化集成。 ## MCP 配置 | 选项 | 说明 | |------|------| | `--mcp-config-file PATH` | 加载 MCP 配置文件,可多次指定 | | `--mcp-config JSON` | 加载 MCP 配置 JSON 字符串,可多次指定 | 默认加载 `~/.kimi/mcp.json`(如果存在)。详见 [Model Context Protocol](../customization/mcp.md)。 ## 审批控制 | 选项 | 简写 | 说明 | |------|------|------| | `--yolo` | `-y` | 自动批准所有工具调用(用户仍可回应 `AskUserQuestion`) | | `--yes` | | `--yolo` 的别名 | | `--auto-approve` | | `--yolo` 的别名 | | `--afk` | | Away-from-keyboard 模式:自动批准所有工具调用,并自动 dismiss `AskUserQuestion`,适用于无人值守场景 | ::: warning 注意 YOLO 或 AFK 模式下,所有文件修改和 Shell 命令都会自动执行,请谨慎使用。 ::: ## 计划模式 | 选项 | 说明 | |------|------| | `--plan` | 以计划模式启动新会话 | 使用 `--plan` 启动时,AI 只能使用只读工具探索代码库并编写实现计划。恢复已有会话时,`--plan` 会强制开启计划模式;不带 `--plan` 恢复的会话保留其原有状态。 也可以在配置文件中设置 `default_plan_mode = true`,每次启动新会话时默认进入计划模式。详见 [配置文件](../configuration/config-files.md)。 ## Thinking 模式 | 选项 | 说明 | |------|------| | `--thinking` | 启用 thinking 模式 | | `--no-thinking` | 禁用 thinking 模式 | Thinking 模式需要模型支持。如果不指定,使用上次会话的设置。 ## Skills 配置 | 选项 | 说明 | |------|------| | `--skills-dir PATH` | 追加额外的 skills 目录(可重复指定) | 不指定时,Kimi Code CLI 会按优先级自动发现用户级和项目级 Skills 目录。详见 [Agent Skills](../customization/skills.md)。 ## 子命令 | 子命令 | 说明 | |--------|------| | [`kimi login`](#kimi-login) | 登录 Kimi 账号 | | [`kimi logout`](#kimi-logout) | 登出 Kimi 账号 | | [`kimi info`](./kimi-info.md) | 显示版本和协议信息 | | [`kimi acp`](./kimi-acp.md) | 启动多会话 ACP 服务器 | | [`kimi mcp`](./kimi-mcp.md) | 管理 MCP 服务器配置 | | [`kimi plugin`](../customization/plugins.md) | 管理插件(Beta) | | [`kimi term`](./kimi-term.md) | 启动 Toad 终端 UI | | [`kimi export`](#kimi-export) | 导出会话为 ZIP 文件 | | [`kimi vis`](./kimi-vis.md) | 启动 Agent Tracing Visualizer(技术预览) | | [`kimi web`](./kimi-web.md) | 启动 Web UI 服务器 | ### `kimi login` 登录 Kimi 账号。执行后会自动打开浏览器,完成账号授权后自动配置可用的模型。 ```sh kimi login ``` ### `kimi logout` 登出 Kimi 账号。会清理存储的 OAuth 凭据并移除配置文件中的相关配置。 ```sh kimi logout ``` ### `kimi export` 将会话数据导出为 ZIP 文件。ZIP 中包含会话目录下的所有文件(`context.jsonl`、`wire.jsonl`、`state.json` 等)及相关的诊断日志。 ```sh kimi export [] [-o ] [--yes] ``` | 参数 / 选项 | 说明 | |------|------| | `` | 要导出的会话 ID。省略时,CLI 会预览并确认当前工作目录的上一个会话,然后再导出 | | `--output, -o` | 输出 ZIP 文件路径(默认为当前目录下的 `session-.zip`) | | `--yes, -y` | 跳过默认会话的确认提示,直接导出 | ::: info 新增 新增于 1.20 版本。 ::: ### `kimi vis` ::: warning 注意 技术预览功能,可能不稳定。 ::: 启动 Agent Tracing Visualizer,通过浏览器查看和分析会话追踪数据。 ```sh kimi vis [OPTIONS] ``` | 选项 | 简写 | 说明 | |------|------|------| | `--host TEXT` | `-h` | 绑定的主机地址(默认:`127.0.0.1`) | | `--network` | `-n` | 监听所有网络接口(绑定到 `0.0.0.0`),自动检测并显示局域网 IP | | `--port INTEGER` | `-p` | 绑定的端口号(默认:`5495`) | | `--open / --no-open` | | 自动打开浏览器(默认:启用) | | `--reload` | | 启用自动重载(开发模式) | 详见 [Agent Tracing Visualizer](./kimi-vis.md)。 ### `kimi web` 启动 Web UI 服务器,通过浏览器访问 Kimi Code CLI。 ```sh kimi web [OPTIONS] ``` 如果默认端口被占用,服务器会自动尝试下一个可用端口(默认范围 `5494`–`5503`),并在终端打印提示。 | 选项 | 简写 | 说明 | |------|------|------| | `--host TEXT` | `-h` | 绑定的主机地址(默认:`127.0.0.1`) | | `--network` | `-n` | 监听所有网络接口(绑定到 `0.0.0.0`),自动检测并显示局域网 IP | | `--port INTEGER` | `-p` | 绑定的端口号(默认:`5494`) | | `--reload` | | 启用自动重载(开发模式) | | `--open / --no-open` | | 自动打开浏览器(默认:启用) | 示例: ```sh # 默认启动,自动打开浏览器 kimi web # 指定端口 kimi web --port 8080 # 不自动打开浏览器 kimi web --no-open # 绑定到所有网络接口(允许局域网访问) kimi web --host 0.0.0.0 ``` 详见 [Web UI](./kimi-web.md)。 --- --- url: /en/customization/skills.md --- # Agent Skills [Agent Skills](https://agentskills.io/) is an open format for adding specialized knowledge and workflows to AI agents. Kimi Code CLI supports loading Agent Skills to extend AI capabilities. ## What are Agent Skills A skill is a directory containing a `SKILL.md` file. When Kimi Code CLI starts, it discovers all skills and injects their names, paths, and descriptions into the system prompt. The AI will decide on its own whether to read the specific `SKILL.md` file to get detailed guidance based on the current task's needs. For example, you can create a "code style" skill to tell the AI your project's naming conventions, comment styles, etc.; or create a "security audit" skill to have the AI focus on specific security issues when reviewing code. **Skills vs plugins** Kimi Code CLI supports two extension mechanisms: * **Skills**: Provide knowledge-based guidance through `SKILL.md`; the AI reads and follows the specifications. Suitable for defining code styles, workflows, and best practices. * **Plugins**: Declare executable tools through `plugin.json`; the AI can directly invoke tools to get results. Suitable for wrapping scripts, API calls, and database queries. For details about plugins, see the [Plugins](./plugins.md) documentation. ## Skill discovery Kimi Code CLI uses a layered loading mechanism to discover skills. Roots are scanned in priority order — when a skill name is defined in more than one scope, the more specific scope wins: **Project > User > Extra > Built-in** **Built-in skills** Skills shipped with the package, providing basic capabilities. Lowest priority. **User-level skills** Stored in the user's home directory, effective across all projects. Candidate directories are split into two groups; within each group, the first existing directory is selected, and results from both groups are merged independently (brand group has higher specificity and priority): * **Brand group** (mutually exclusive): 1. `~/.kimi/skills/` 2. `~/.claude/skills/` 3. `~/.codex/skills/` * **Generic group** (mutually exclusive): 1. `~/.config/agents/skills/` (recommended) 2. `~/.agents/skills/` Both groups are searched independently and results are merged. When a skill with the same name exists in both groups, the brand group version takes priority. By default, **all existing brand directories are loaded and merged**, with same-name skills resolved by priority: kimi > claude > codex. The generic group is not affected. This "merge everything" behaviour is controlled by `merge_all_available_skills`, which defaults to `true`: ```toml # Default; merges every brand directory that exists. merge_all_available_skills = true ``` Set it to `false` to restore the older first-match-only behaviour, where only the highest-priority existing brand directory is used (kimi, or claude if kimi is absent, and so on): ```toml merge_all_available_skills = false ``` **Project-level skills** Stored in the project directory, effective within that project. Candidate paths are resolved relative to the **project root** (the nearest `.git` ancestor of the work directory, falling back to the work directory itself when there is no `.git` marker), so launching kimi-cli from a subdirectory of a monorepo still surfaces skills defined at the repository root. The same two-group split as user-level skills applies: * **Brand group** (mutually exclusive): 1. `.kimi/skills/` 2. `.claude/skills/` 3. `.codex/skills/` * **Generic group**: `.agents/skills/` The `merge_all_available_skills` config applies to project-level skills as well. You can also specify additional skills directories with the `--skills-dir` flag. This flag can be specified multiple times, and the directories override the auto-discovered user/project directories: ```sh kimi --skills-dir /path/to/my-skills --skills-dir /path/to/more-skills ``` **Extra skills directories (additive)** To add custom skills directories **on top of** the built-in / user / project discovery (not instead of them), set `extra_skill_dirs` in your config: ```toml extra_skill_dirs = [ "~/my-skills-collection", # `~` is expanded to $HOME ".claude/plugins/my-skills", # relative entries resolve against the project root "/opt/team-shared/skills", # absolute paths are used as-is ] ``` Each entry can be an absolute path, a `~`-prefixed path, or a path relative to the project root (the nearest `.git` directory above the work directory). Non-existent entries are silently skipped. Skills discovered from these directories are grouped under the `Extra` scope in the system prompt. **How skills are presented to the AI** Discovered skills are injected into the system prompt grouped by origin scope (`Project` / `User` / `Extra` / `Built-in`). Empty groups are omitted. This lets the AI distinguish project-specific skills from user-level ones when you refer to "the skill in this project" vs. "the user-scope skill". **Flat `.md` skills** In addition to the canonical `/SKILL.md` subdirectory layout, a single `.md` file placed directly in a skills directory is also recognised as a skill. Its `name` defaults to the filename without the `.md` extension. ``` ~/my-skills-collection/ ├── demo-ui-components.md # flat: name = "demo-ui-components" └── deploy/ # subdirectory: name = "deploy" └── SKILL.md ``` If a flat `.md` and a subdirectory share the same name in the same directory, the subdirectory wins and a warning is logged. **Description resolution** Regardless of form (subdirectory or flat), each skill's `description` is resolved by the same chain: 1. Frontmatter `description:` field (preferred — follow the [SKILL.md spec](https://agentskills.io/specification)) 2. First non-empty line of the body (fallback; truncated at 240 characters) 3. `"No description provided."` (last resort) ::: tip Skills paths are independent of [`KIMI_SHARE_DIR`](../configuration/env-vars.md#kimi-share-dir). `KIMI_SHARE_DIR` customizes the storage location for configuration, sessions, logs, and other runtime data, but does not affect Skills search paths. Skills are cross-tool shared capability extensions (compatible with Kimi CLI, Claude, Codex, and others), which is a different type of data from application runtime data. To specify custom skills paths, use the `--skills-dir` flag or `extra_skill_dirs` config. ::: ## Built-in skills Kimi Code CLI includes the following built-in skills: * **kimi-cli-help**: Kimi Code CLI help. Answers questions about Kimi Code CLI installation, configuration, slash commands, keyboard shortcuts, MCP integration, providers, environment variables, and more. * **skill-creator**: Guide for creating skills. When you need to create a new skill (or update an existing skill) to extend Kimi's capabilities, you can use this skill to get detailed creation guidance and best practices. ## Creating a skill Creating a skill only requires two steps: 1. Create a subdirectory in the skills directory 2. Create a `SKILL.md` file in the subdirectory **Directory structure** A skill directory needs at least a `SKILL.md` file, and can also include auxiliary directories to organize more complex content: ``` ~/.config/agents/skills/ └── my-skill/ ├── SKILL.md # Required: main file ├── scripts/ # Optional: script files ├── references/ # Optional: reference documents └── assets/ # Optional: other resources ``` **`SKILL.md` format** `SKILL.md` uses YAML frontmatter to define metadata, followed by prompt content in Markdown format: ```markdown --- name: code-style description: My project's code style guidelines --- ## Code Style In this project, please follow these conventions: - Use 4-space indentation - Variable names use camelCase - Function names use snake_case - Every function needs a docstring - Lines should not exceed 100 characters ``` **Frontmatter fields** | Field | Description | Required | |-------|-------------|----------| | `name` | Skill name, 1-64 characters, only lowercase letters, numbers, and hyphens allowed; defaults to directory name if omitted | No | | `description` | Skill description, 1-1024 characters, explaining the skill's purpose and use cases; shows "No description provided." if omitted | No | | `license` | License name or file reference | No | | `compatibility` | Environment requirements, up to 500 characters | No | | `metadata` | Additional key-value attributes | No | **Best practices** * Keep `SKILL.md` under 500 lines, move detailed content to `scripts/`, `references/`, or `assets/` directories * Use relative paths in `SKILL.md` to reference other files * Provide clear step-by-step instructions, input/output examples, and edge case explanations ## Example skills **PowerPoint creation** ```markdown --- name: pptx description: Create and edit PowerPoint presentations --- ## PPT Creation Workflow When creating presentations, follow these steps: 1. Analyze content structure, plan slide outline 2. Choose appropriate color scheme and fonts 3. Use python-pptx library to generate .pptx files ## Design Principles - Each slide focuses on one topic - Keep text concise, use bullet points instead of long paragraphs - Maintain clear visual hierarchy with distinct titles, body, and notes - Use consistent colors, avoid more than 3 main colors ``` **Python project standards** ```markdown --- name: python-project description: Python project development standards, including code style, testing, and dependency management --- ## Python Development Standards - Use Python 3.14+ - Use ruff for code formatting and linting - Use pyright for type checking - Use pytest for testing - Use uv for dependency management Code style: - Line length limit 100 characters - Use type annotations - Public functions need docstrings ``` **Git commit conventions** ```markdown --- name: git-commits description: Git commit message conventions using Conventional Commits format --- ## Git Commit Conventions Use Conventional Commits format: type(scope): description Allowed types: feat, fix, docs, style, refactor, test, chore Examples: - feat(auth): add OAuth login support - fix(api): fix user query returning null - docs(readme): update installation instructions ``` ## Using slash commands to load a skill The `/skill:` slash command lets you save commonly used prompt templates as skills and quickly invoke them when needed. When you enter the command, Kimi Code CLI reads the corresponding `SKILL.md` file content and sends it to the Agent as a prompt. For example: * `/skill:code-style`: Load code style guidelines * `/skill:pptx`: Load PPT creation workflow * `/skill:git-commits fix user login issue`: Load Git commit conventions with an additional task description You can append additional text after the slash command, which will be added to the skill prompt as the user's specific request. ::: tip For regular conversations, the Agent will automatically decide whether to read skill content based on context, so you don't need to invoke it manually. ::: Skills allow you to codify your team's best practices and project standards, ensuring the AI always follows consistent standards. ## Flow skills Flow skills are a special skill type that embed an Agent Flow diagram in `SKILL.md`, used to define multi-step automated workflows. Unlike standard skills, flow skills are invoked via `/flow:` commands and automatically execute multiple conversation turns following the flow diagram. **Creating a flow skill** To create a flow skill, set `type: flow` in the frontmatter and include a Mermaid or D2 code block in the content: ````markdown --- name: code-review description: Code review workflow type: flow --- ```mermaid flowchart TD A([BEGIN]) --> B[Analyze code changes, list all modified files and features] B --> C{Is code quality acceptable?} C -->|Yes| D[Generate code review report] C -->|No| E[List issues and propose improvements] E --> B D --> F([END]) ``` ```` **Flow diagram format** Both Mermaid and D2 formats are supported: * **Mermaid**: Use ` ```mermaid ` code block, [Mermaid Playground](https://www.mermaidchart.com/play) can be used for editing and preview * **D2**: Use ` ```d2 ` code block, [D2 Playground](https://play.d2lang.com) can be used for editing and preview Flow diagrams must contain one `BEGIN` node and one `END` node. Regular node text is sent to the Agent as a prompt; decision nodes require the Agent to output `branch name` in the output to select the next step. **D2 format example** ``` BEGIN -> B -> C B: Analyze existing code, write design doc for XXX feature C: Review if design doc is detailed enough C -> B: No C -> D: Yes D: Start implementation D -> END ``` For multiline labels, you can use D2's block string syntax (`|md`): ``` BEGIN -> step -> END step: |md # Detailed instructions 1. Analyze code structure 2. Check for potential issues 3. Generate report | ``` **Executing a flow skill** Flow skills can be invoked in two ways: * `/flow:`: Execute the flow. The Agent will start from the `BEGIN` node and process each node according to the flow diagram definition until reaching the `END` node * `/skill:`: Like a standard skill, sends the `SKILL.md` content to the Agent as a prompt (does not automatically execute the flow) ```sh # Execute the flow /flow:code-review # Load as a standard skill /skill:code-review ``` --- --- url: /zh/customization/skills.md --- # Agent Skills [Agent Skills](https://agentskills.io/) 是一个开放格式,用于为 AI Agent 添加专业知识和工作流程。Kimi Code CLI 支持加载 Agent Skills,扩展 AI 的能力。 ## Agent Skills 是什么 一个 Skill 就是一个包含 `SKILL.md` 文件的目录。Kimi Code CLI 启动时会发现所有 Skills,并将它们的名称、路径和描述注入到系统提示词中。AI 会根据当前任务的需要,自行决定是否读取具体的 `SKILL.md` 文件来获取详细指引。 例如,你可以创建一个「代码风格」Skill,告诉 AI 你项目的命名规范、注释风格等;或者创建一个「安全审计」Skill,让 AI 在审查代码时关注特定的安全问题。 **Skills 与插件的区别** Kimi Code CLI 支持两种扩展机制: * **Skills**:通过 `SKILL.md` 提供知识性指导,AI 读取后遵循其中的规范。适合定义代码风格、工作流程、最佳实践等。 * **插件**:通过 `plugin.json` 声明可执行工具,AI 可以直接调用工具获取结果。适合封装脚本、API 调用、数据库查询等。 如需了解插件的详细信息,请参阅 [插件](./plugins.md) 文档。 ## Skill 发现 Kimi Code CLI 采用分层加载机制发现 Skills。当同名 Skill 存在于多个作用域时,越具体的作用域优先: **Project > User > Extra > Built-in** **内置 Skills** 随软件包安装的 Skills,提供基础能力。优先级最低。 **用户级 Skills** 存放在用户主目录中,在所有项目中生效。候选目录分为两组,每组内按优先级选取第一个存在的目录,两组的结果独立合并(品牌组特异性更高,优先级更高): * **品牌组**(互斥选一): 1. `~/.kimi/skills/` 2. `~/.claude/skills/` 3. `~/.codex/skills/` * **通用组**(互斥选一): 1. `~/.config/agents/skills/`(推荐) 2. `~/.agents/skills/` 两组分别选出目录后合并加载。当同名 Skill 同时存在于品牌组和通用组时,品牌组的版本优先。 默认情况下,**所有存在的品牌目录都会被加载并合并**,同名 Skill 按 kimi > claude > codex 的优先级解析(通用组不受影响)。这一行为由 `merge_all_available_skills` 控制,其默认值为 `true`: ```toml # 默认值;合并所有已存在的品牌目录。 merge_all_available_skills = true ``` 如需恢复旧的"仅取优先级最高的那个品牌目录"行为(例如只使用 kimi,缺失时回退到 claude,再缺失时回退到 codex),可将其显式设为 `false`: ```toml merge_all_available_skills = false ``` **项目级 Skills** 存放在项目目录中,在该项目内生效。候选路径以**项目根**为起点(即工作目录向上最近的包含 `.git` 的祖先目录;找不到时回退到工作目录本身),这样即使从 monorepo 的某个子 package 内启动 kimi-cli,仓库根目录下的 Skills 也能被正确识别。同样分为两组独立查找: * **品牌组**(互斥选一): 1. `.kimi/skills/` 2. `.claude/skills/` 3. `.codex/skills/` * **通用组**:`.agents/skills/` `merge_all_available_skills` 配置对项目层同样生效。 你也可以通过 `--skills-dir` 参数指定额外的 Skills 目录。该参数可重复指定,指定后将替代自动发现的用户级和项目级目录: ```sh kimi --skills-dir /path/to/my-skills --skills-dir /path/to/more-skills ``` **额外 Skills 目录(追加式)** 如果希望在**内置 / 用户级 / 项目级**自动发现的基础上**追加**自定义 Skills 目录(而不是替代它们),可在配置中设置 `extra_skill_dirs`: ```toml extra_skill_dirs = [ "~/my-skills-collection", # `~` 会展开为 $HOME ".claude/plugins/my-skills", # 相对路径以“项目根”为基准解析 "/opt/team-shared/skills", # 绝对路径原样使用 ] ``` 每一项可以是绝对路径、`~` 前缀路径,或相对于项目根(即 `work_dir` 向上第一个包含 `.git` 的目录)的相对路径。不存在的条目会被静默跳过。从这些目录发现的 Skills 在系统提示中归入 `Extra` 作用域。 **Skills 在系统提示中的呈现** 发现的 Skills 按作用域分组注入系统提示(`Project` / `User` / `Extra` / `Built-in`);空分组不渲染。这样 AI 就能区分"项目里的 skill"和"用户级的 skill",避免推理时把两者混为一谈。 **扁平 `.md` 形式的 Skill** 除了标准的 `/SKILL.md` 子目录结构,Skills 目录下单个 `.md` 文件也会被识别为一个 Skill。`name` 默认取文件名去掉 `.md`。 ``` ~/my-skills-collection/ ├── demo-ui-components.md # 扁平:name = "demo-ui-components" └── deploy/ # 子目录:name = "deploy" └── SKILL.md ``` 当同一目录下扁平 `.md` 和子目录形式同名时,以子目录为准,并记录一条警告日志。 **description 解析规则** 无论子目录还是扁平形式,每个 Skill 的 `description` 都走同一条链: 1. Frontmatter 的 `description:` 字段(推荐 —— 遵循 [SKILL.md 规范](https://agentskills.io/specification)) 2. 正文第一个非空行(回退;超过 240 字符会被截断) 3. `"No description provided."`(兜底) ::: tip 提示 Skills 路径独立于 [`KIMI_SHARE_DIR`](../configuration/env-vars.md#kimi-share-dir)。`KIMI_SHARE_DIR` 用于自定义配置、会话、日志等运行时数据的存储位置,不影响 Skills 的搜索路径。Skills 是跨工具共享的能力扩展(支持 Kimi CLI、Claude、Codex 等多个工具共用),与应用运行时数据是不同类型的数据。如需自定义 Skills 路径,请使用 `--skills-dir` 参数或 `extra_skill_dirs` 配置。 ::: ## 内置 Skills Kimi Code CLI 内置了以下 Skills: * **kimi-cli-help**:Kimi Code CLI 帮助。解答关于 Kimi Code CLI 安装、配置、斜杠命令、键盘快捷键、MCP 集成、供应商、环境变量等问题。 * **skill-creator**:Skill 创建指南。当你需要创建新的 Skill(或更新现有 Skill)来扩展 Kimi 的能力时,可以使用此 Skill 获取详细的创建指导和最佳实践。 ## 创建 Skill 创建一个 Skill 只需要两步: 1. 在 skills 目录下创建一个子目录 2. 在子目录中创建 `SKILL.md` 文件 **目录结构** 一个 Skill 目录至少需要包含 `SKILL.md` 文件,也可以包含辅助目录来组织更复杂的内容: ``` ~/.config/agents/skills/ └── my-skill/ ├── SKILL.md # 必需:主文件 ├── scripts/ # 可选:脚本文件 ├── references/ # 可选:参考文档 └── assets/ # 可选:其他资源 ``` **`SKILL.md` 格式** `SKILL.md` 使用 YAML Frontmatter 定义元数据,后面是 Markdown 格式的提示词内容: ```markdown --- name: code-style description: 我的项目代码风格规范 --- ## 代码风格 在这个项目中,请遵循以下规范: - 使用 4 空格缩进 - 变量名使用 camelCase - 函数名使用 snake_case - 每个函数都需要 docstring - 单行不超过 100 字符 ``` **Frontmatter 字段** | 字段 | 说明 | 是否必填 | |------|------|----------| | `name` | Skill 名称,1-64 字符,只能使用小写字母、数字和连字符;省略时默认使用目录名 | 否 | | `description` | Skill 描述,1-1024 字符,说明 Skill 的用途和使用场景;省略时显示 "No description provided." | 否 | | `license` | 许可证名称或文件引用 | 否 | | `compatibility` | 环境要求说明,最多 500 字符 | 否 | | `metadata` | 额外的键值对属性 | 否 | **最佳实践** * 保持 `SKILL.md` 在 500 行以内,将详细内容移到 `scripts/`、`references/` 或 `assets/` 目录 * 在 `SKILL.md` 中使用相对路径引用其他文件 * 提供清晰的步骤指引、输入输出示例和边界情况说明 ## 示例 Skill **PPT 制作** ```markdown --- name: pptx description: 创建和编辑 PowerPoint 演示文稿 --- ## PPT 制作流程 创建演示文稿时,遵循以下步骤: 1. 分析内容结构,规划幻灯片大纲 2. 选择合适的配色方案和字体 3. 使用 python-pptx 库生成 .pptx 文件 ## 设计原则 - 每页幻灯片聚焦一个主题 - 文字简洁,使用要点而非长段落 - 保持视觉层次清晰,标题、正文、注释有明确区分 - 配色统一,避免超过 3 种主色 ``` **Python 项目规范** ```markdown --- name: python-project description: Python 项目开发规范,包括代码风格、测试和依赖管理 --- ## Python 开发规范 - 使用 Python 3.14+ - 使用 ruff 进行代码格式化和 lint - 使用 pyright 进行类型检查 - 测试使用 pytest - 依赖管理使用 uv 代码风格: - 行长度限制 100 字符 - 使用类型注解 - 公开函数需要 docstring ``` **Git 提交规范** ```markdown --- name: git-commits description: Git 提交信息规范,使用 Conventional Commits 格式 --- ## Git 提交规范 使用 Conventional Commits 格式: 类型(范围): 描述 允许的类型:feat, fix, docs, style, refactor, test, chore 示例: - feat(auth): 添加 OAuth 登录支持 - fix(api): 修复用户查询返回空值的问题 - docs(readme): 更新安装说明 ``` ## 使用斜杠命令加载 Skill `/skill:` 斜杠命令让你可以将常用的提示词模板保存为 Skill,需要时快速调用。输入命令后,Kimi Code CLI 会读取对应的 `SKILL.md` 文件内容,并将其作为提示词发送给 Agent。 例如: * `/skill:code-style`:加载代码风格规范 * `/skill:pptx`:加载 PPT 制作流程 * `/skill:git-commits 修复用户登录问题`:加载 Git 提交规范,同时附带额外的任务描述 斜杠命令后面可以附带额外的文本,这些内容会追加到 Skill 提示词之后,作为用户的具体请求。 ::: tip 提示 如果只是普通对话,Agent 会根据上下文自动判断是否需要读取 Skill 内容,不需要手动调用。 ::: Skills 让你可以将团队的最佳实践和项目规范固化下来,确保 AI 始终遵循一致的标准。 ## Flow Skills Flow Skill 是一种特殊的 Skill 类型,它在 `SKILL.md` 中内嵌 Agent Flow 流程图,用于定义多步骤的自动化工作流。与普通 Skill 不同,Flow Skill 通过 `/flow:` 命令调用,会按照流程图自动执行多个对话轮次。 **创建 Flow Skill** 创建 Flow Skill 需要在 Frontmatter 中设置 `type: flow`,并在内容中包含 Mermaid 或 D2 格式的流程图代码块: ````markdown --- name: code-review description: 代码审查工作流 type: flow --- ```mermaid flowchart TD A([BEGIN]) --> B[分析代码变更,列出所有修改的文件和功能] B --> C{代码质量是否达标?} C -->|是| D[生成代码审查报告] C -->|否| E[列出问题并提出改进建议] E --> B D --> F([END]) ``` ```` **流程图格式** 支持 Mermaid 和 D2 两种格式: * **Mermaid**:使用 ` ```mermaid ` 代码块,[Mermaid Playground](https://www.mermaidchart.com/play) 可用于编辑和预览 * **D2**:使用 ` ```d2 ` 代码块,[D2 Playground](https://play.d2lang.com) 可用于编辑和预览 流程图必须包含一个 `BEGIN` 节点和一个 `END` 节点。普通节点的文本作为提示词发送给 Agent;分支节点需要 Agent 在输出中使用 `分支名` 选择下一步。 **D2 格式示例** ``` BEGIN -> B -> C B: 分析现有代码,为 XXX 功能编写设计文档 C: Review 设计文档是否足够详细 C -> B: 否 C -> D: 是 D: 开始实现 D -> END ``` 对于多行标签,可以使用 D2 的块字符串语法(`|md`): ``` BEGIN -> step -> END step: |md # 详细指引 1. 分析代码结构 2. 检查潜在问题 3. 生成报告 | ``` **执行 Flow Skill** Flow Skill 可以通过两种方式调用: * `/flow:`:执行流程,Agent 会从 `BEGIN` 节点开始,按照流程图定义依次处理每个节点,直到到达 `END` 节点 * `/skill:`:与普通 Skill 一样,将 `SKILL.md` 内容作为提示词发送给 Agent(不自动执行流程) ```sh # 执行流程 /flow:code-review # 作为普通 Skill 加载 /skill:code-review ``` --- --- url: /en/reference/kimi-vis.md --- # Agent Tracing Visualizer ::: warning Note Agent Tracing Visualizer is currently in Technical Preview and may be unstable. Features and interface may change in future releases. ::: Agent Tracing Visualizer is a browser-based visualization dashboard for inspecting and analyzing Kimi Code CLI session traces. It helps you understand agent behavior, view Wire event timelines, analyze context usage, and browse historical sessions. ## Launch Run `kimi vis` in the terminal to start the Visualizer: ```sh kimi vis ``` The server automatically opens a browser after startup. The default address is `http://127.0.0.1:5495`. If the default port is in use, the server will pick the next available port (by default `5495`–`5504`) and print the access URL in the terminal. You can also type `/vis` in the interactive shell to switch directly from the current session to the Visualizer. ## Command-line options | Option | Short | Description | |--------|-------|-------------| | `--host TEXT` | `-h` | Bind to a specific IP address | | `--network` | `-n` | Enable network access (bind to `0.0.0.0`), auto-detects and displays LAN IP | | `--port INTEGER` | `-p` | Port number to bind to (default: `5495`) | | `--open / --no-open` | | Automatically open browser (default: `--open`) | | `--reload` | | Enable auto-reload (development mode) | Examples: ```sh # Specify port kimi vis --port 8080 # Don't automatically open browser kimi vis --no-open # Share on LAN (auto-detects and displays LAN IP) kimi vis -n ``` ## Features ### Wire event timeline Displays the complete Wire event flow as a timeline, including turn start/end, step execution, tool calls and results. Supports event filtering and detailed information viewing. ### Context viewer Visualizes session context content, including user messages, assistant messages, and tool calls. Helps you understand what the agent "sees" at each step. ### Session explorer Browse and search all historical sessions, grouped by project. View detailed information for each session, including working directory, creation time, and message count. ### Session directory shortcuts At the top of the session detail page, you can use `Open Dir` to open the current session directory directly. On macOS this opens Finder; on Windows it opens Explorer. `Copy DIR` copies the raw session directory path so you can continue debugging in a terminal, editor, or issue report. ### Session download and export You can export session data as a ZIP file for offline analysis or sharing. * **ZIP download**: Click the download button in the session explorer or session detail page to download the session directory as a ZIP file * **CLI export**: Use `kimi export []` to export a session as a ZIP file; when `` is omitted, the CLI previews the previous session for the current working directory and asks for confirmation ### Session import Supports importing ZIP-format session data into the Visualizer for viewing. Imported sessions are stored in a dedicated `~/.kimi/imported_sessions/` directory, separate from regular sessions. In the session explorer, you can use the "Imported" filter toggle to switch between viewing imported sessions. Imported sessions support deletion, with a confirmation dialog before removal. ### Usage statistics Displays token usage statistics and charts, including input/output token distribution and cache hit rates. --- --- url: /zh/reference/kimi-vis.md --- # Agent Tracing Visualizer ::: warning 注意 Agent Tracing Visualizer 目前为技术预览版(Technical Preview),功能和界面可能在后续版本中发生变化。 ::: Agent Tracing Visualizer 是一个基于浏览器的可视化仪表板,用于检查和分析 Kimi Code CLI 的会话追踪数据。它可以帮助你理解 Agent 的行为、查看 Wire 事件时间线、分析上下文使用情况,以及浏览历史会话。 ## 启动 在终端中运行 `kimi vis` 命令启动 Visualizer: ```sh kimi vis ``` 服务器启动后会自动打开浏览器。默认地址为 `http://127.0.0.1:5495`。 如果默认端口被占用,服务器会自动尝试下一个可用端口(默认范围 `5495`–`5504`),并在终端打印访问地址。 你也可以在交互式 Shell 中输入 `/vis` 斜杠命令,直接从当前会话切换到 Visualizer。 ## 命令行选项 | 选项 | 简写 | 说明 | |------|------|------| | `--host TEXT` | `-h` | 绑定到指定 IP 地址 | | `--network` | `-n` | 启用网络访问(绑定到 `0.0.0.0`),自动探测并显示 LAN IP | | `--port INTEGER` | `-p` | 指定端口号(默认:`5495`) | | `--open / --no-open` | | 启动时自动打开浏览器(默认:`--open`) | | `--reload` | | 启用自动重载(用于开发调试) | 示例: ```sh # 指定端口 kimi vis --port 8080 # 不自动打开浏览器 kimi vis --no-open # 在局域网中共享(自动探测并显示 LAN IP) kimi vis -n ``` ## 功能 ### Wire 事件时间线 以时间线形式展示 Wire 事件的完整流程,包括轮次(Turn)的开始和结束、步骤(Step)的执行、工具调用和返回结果等。支持事件过滤和详细信息查看。 ### 上下文查看器 可视化展示会话的上下文内容,包括 User 消息、Assistant 消息和工具调用。帮助理解 Agent 在每个步骤中 "看到" 的信息。 ### 会话浏览器 浏览和搜索所有历史会话,按项目分组展示。可以查看每个会话的详细信息,包括工作目录、创建时间和消息数量。 ### 会话目录快捷操作 在会话详情页顶部,可以使用 `Open Dir` 直接打开当前会话目录。该操作在 macOS 上调用 Finder,在 Windows 上调用 Explorer。`Copy DIR` 会复制当前会话目录的原始路径,便于你在终端、编辑器或问题报告中继续排查。 ### 会话下载与导出 可以将会话数据导出为 ZIP 文件,方便离线分析或分享。 * **ZIP 下载**:在会话浏览器和会话详情页中点击下载按钮,即可将会话目录打包为 ZIP 文件下载 * **CLI 导出**:使用 `kimi export []` 命令导出会话为 ZIP 文件;省略 `` 时会预览并确认当前工作目录的上一个会话 ### 会话导入 支持将 ZIP 格式的会话数据导入到 Visualizer 中查看。导入的会话存储在独立的 `~/.kimi/imported_sessions/` 目录中,不会与正常会话混淆。 在会话浏览器中可以通过 "Imported" 筛选器切换查看导入的会话。导入的会话支持删除操作,删除前会弹出确认对话框。 ### 用量统计 展示 Token 用量的统计数据和图表,包括输入和输出 Token 的分布、缓存命中率等信息。 --- --- url: /zh/customization/agents.md --- # Agent 与子 Agent Agent 定义了 AI 的行为方式,包括系统提示词、可用工具和子 Agent。你可以使用内置 Agent,也可以创建自定义 Agent。 ## 内置 Agent Kimi Code CLI 提供两个内置 Agent。启动时可以通过 `--agent` 参数选择: ```sh kimi --agent okabe ``` ### `default` 默认 Agent,适合通常情况使用。启用的工具: `Agent`、`AskUserQuestion`、`SetTodoList`、`Shell`、`ReadFile`、`ReadMediaFile`、`Glob`、`Grep`、`WriteFile`、`StrReplaceFile`、`SearchWeb`、`FetchURL`、`EnterPlanMode`、`ExitPlanMode`、`TaskList`、`TaskOutput`、`TaskStop` ### `okabe` 实验性 Agent,用于实验新的提示词和工具。在 `default` 的基础上额外启用 `SendDMail`。 ## 自定义 Agent 文件 Agent 使用 YAML 格式定义。通过 `--agent-file` 参数加载自定义 Agent: ```sh kimi --agent-file /path/to/my-agent.yaml ``` **基本结构** ```yaml version: 1 agent: name: my-agent system_prompt_path: ./system.md tools: - "kimi_cli.tools.shell:Shell" - "kimi_cli.tools.file:ReadFile" - "kimi_cli.tools.file:WriteFile" ``` **继承与覆盖** 使用 `extend` 可以继承其他 Agent 的配置,只覆盖需要修改的部分: ```yaml version: 1 agent: extend: default # 继承默认 Agent system_prompt_path: ./my-prompt.md # 覆盖系统提示词 exclude_tools: # 排除某些工具 - "kimi_cli.tools.web:SearchWeb" - "kimi_cli.tools.web:FetchURL" ``` `extend: default` 会继承内置的默认 Agent。你也可以指定相对路径继承其他 Agent 文件。 **配置字段** | 字段 | 说明 | 是否必填 | |------|------|----------| | `extend` | 继承的 Agent,可以是 `default` 或相对路径 | 否 | | `name` | Agent 名称 | 是(继承时可省略) | | `system_prompt_path` | 系统提示词文件路径,相对于 Agent 文件 | 是(继承时可省略) | | `system_prompt_args` | 传递给系统提示词的自定义参数,继承时会合并 | 否 | | `tools` | 工具列表,格式为 `模块:类名` | 是(继承时可省略) | | `exclude_tools` | 要排除的工具 | 否 | | `subagents` | 子 Agent 定义 | 否 | ## 系统提示词内置参数 系统提示词文件是一个 Markdown 模板,可以使用 `${VAR}` 语法引用变量,也支持 Jinja2 的 `{% include %}` 指令来引入其他文件。内置变量包括: | 变量 | 说明 | |------|------| | `${KIMI_NOW}` | 当前时间(ISO 格式) | | `${KIMI_WORK_DIR}` | 工作目录路径 | | `${KIMI_WORK_DIR_LS}` | 工作目录文件列表 | | `${KIMI_AGENTS_MD}` | 从项目根目录到工作目录逐层合并的 `AGENTS.md` 内容(包括 `.kimi/AGENTS.md`) | | `${KIMI_SKILLS}` | 加载的 Skills 列表 | | `${KIMI_ADDITIONAL_DIRS_INFO}` | 通过 `--add-dir` 或 `/add-dir` 添加的额外目录信息 | 你也可以通过 `system_prompt_args` 定义自定义参数: ```yaml agent: system_prompt_args: MY_VAR: "自定义值" ``` 然后在提示词中使用 `${MY_VAR}`。 **系统提示词示例** ```markdown # My Agent You are a helpful assistant. Current time: ${KIMI_NOW}. Working directory: ${KIMI_WORK_DIR} ${MY_VAR} ``` ## 在 Agent 文件中定义子 Agent 子 Agent 可以处理特定类型的任务。在 Agent 文件中定义子 Agent 后,主 Agent 可以通过 `Agent` 工具启动它们: ```yaml version: 1 agent: extend: default subagents: coder: path: ./coder-sub.yaml description: "处理编码任务" reviewer: path: ./reviewer-sub.yaml description: "代码审查专家" ``` 子 Agent 文件也是标准的 Agent 格式,通常会继承主 Agent: ```yaml # coder-sub.yaml version: 1 agent: extend: ./agent.yaml # 继承主 Agent system_prompt_args: ROLE_ADDITIONAL: | 你现在作为子 Agent 运行... ``` ## 内置子 Agent 类型 默认 Agent 配置包含三种内置子 Agent 类型,各自有不同的工具策略和适用场景: | 类型 | 用途 | 可用工具 | |------|------|---------| | `coder` | 通用软件工程:读写文件、运行命令、搜索代码 | `Shell`、`ReadFile`、`ReadMediaFile`、`Glob`、`Grep`、`WriteFile`、`StrReplaceFile`、`SearchWeb`、`FetchURL` | | `explore` | 快速只读代码探索:搜索、阅读、总结 | `Shell`、`ReadFile`、`ReadMediaFile`、`Glob`、`Grep`、`SearchWeb`、`FetchURL`(无写入工具) | | `plan` | 实现规划与架构设计:分析文件、制定方案 | `ReadFile`、`ReadMediaFile`、`Glob`、`Grep`、`SearchWeb`、`FetchURL`(无 Shell、无写入工具) | 所有子 Agent 类型均不可嵌套使用 `Agent` 工具(即子 Agent 不能创建自己的子 Agent)。`Agent` 工具仅在根 Agent 中可用。 ## 子 Agent 的运行方式 通过 `Agent` 工具启动的子 Agent 会在独立的上下文中运行,完成后将结果返回给主 Agent。每个子 Agent 实例在会话目录的 `subagents//` 下维护独立的上下文历史和元数据,可以被多次恢复继续使用。这种方式的优势: * 隔离上下文,避免污染主 Agent 的对话历史 * 可以并行处理多个独立任务 * 子 Agent 可以有针对性的系统提示词 * 持久实例可跨多次调用保留上下文 ## 内置工具列表 以下是 Kimi Code CLI 内置的所有工具。 ### `Agent` * **路径**:`kimi_cli.tools.agent:Agent` * **描述**:启动或恢复子 Agent 实例处理聚焦任务。内置三种子 Agent 类型:`coder`(通用软件工程)、`explore`(快速只读代码探索)、`plan`(实现规划与架构设计)。每个实例维护独立的上下文历史,支持前台或后台运行。 | 参数 | 类型 | 说明 | |------|------|------| | `description` | string | 任务简短描述(3-5 词) | | `prompt` | string | 任务详细描述 | | `subagent_type` | string | 内置子 Agent 类型,默认 `coder` | | `model` | string | 可选的模型覆盖 | | `resume` | string | 可选的 Agent 实例 ID,用于恢复现有实例 | | `run_in_background` | bool | 是否在后台运行,默认 false | | `timeout` | int | 超时时间(秒),范围 30–3600。前台默认无超时(运行到完成),后台默认 15 分钟;超时后任务会被停止 | ### `AskUserQuestion` * **路径**:`kimi_cli.tools.ask_user:AskUserQuestion` * **描述**:在执行过程中向用户展示结构化问题和选项,收集用户偏好或决策。适用于需要用户在多个方案中做出选择、解决模糊指令或收集需求信息的场景。不应过度使用——只在用户的选择真正影响后续操作时才调用。 | 参数 | 类型 | 说明 | |------|------|------| | `questions` | array | 问题列表(1–4 个问题) | | `questions[].question` | string | 问题文本,以 `?` 结尾 | | `questions[].header` | string | 短标签,最多 12 字符(如 `Auth`、`Style`) | | `questions[].options` | array | 可选项(2–4 个),系统会自动添加 "Other" 选项 | | `questions[].options[].label` | string | 选项标签(1–5 词),推荐选项可追加 `(Recommended)` | | `questions[].options[].description` | string | 选项说明 | | `questions[].multi_select` | bool | 是否允许多选,默认 false | ### `SetTodoList` * **路径**:`kimi_cli.tools.todo:SetTodoList` * **描述**:管理待办事项列表,跟踪任务进度。支持三种使用模式:更新模式(传入 `todos` 数组替换整个列表)、查询模式(省略 `todos` 参数返回当前列表)和清空模式(传入空数组 `[]` 清空列表)。待办事项会持久化到会话状态。 | 参数 | 类型 | 说明 | |------|------|------| | `todos` | array | null | 待办事项列表。省略时查询当前列表;传入 `[]` 清空列表 | | `todos[].title` | string | 待办事项标题 | | `todos[].status` | string | 状态:`pending`、`in_progress`、`done` | ### `Shell` * **路径**:`kimi_cli.tools.shell:Shell` * **描述**:执行 Shell 命令。需要用户审批。根据操作系统使用配置的 Shell(类 Unix 平台使用 bash/sh,Windows 使用 Git Bash `bash.exe`)。 | 参数 | 类型 | 说明 | |------|------|------| | `command` | string | 要执行的命令 | | `timeout` | int | 超时时间(秒),默认 60,前台最大 300 / 后台最大 86400 | | `run_in_background` | bool | 是否作为后台任务运行,默认 false | | `description` | string | 后台任务的简短描述,`run_in_background=true` 时必填 | 设置 `run_in_background=true` 后,命令会作为后台任务启动,工具立即返回任务 ID,AI 可以继续执行其他操作。任务完成时系统自动发送通知。适用于耗时的构建、测试、监控等场景。 ### `ReadFile` * **路径**:`kimi_cli.tools.file:ReadFile` * **描述**:读取文本文件内容。单次最多读取 1000 行,每行最多 2000 字符。工作目录外的文件需使用绝对路径。每次读取都会在消息中返回文件总行数。敏感文件(如 `.env`、SSH 私钥、云凭据)会被拒绝读取。 | 参数 | 类型 | 说明 | |------|------|------| | `path` | string | 文件路径 | | `line_offset` | int | 起始行号,默认 1。支持负数表示从文件末尾读取(如 `-100` 读取最后 100 行),绝对值不超过 1000 | | `n_lines` | int | 读取行数,默认/最大 1000 | ### `ReadMediaFile` * **路径**:`kimi_cli.tools.file:ReadMediaFile` * **描述**:读取图片或视频文件。文件最大 100MB。仅当模型支持图片/视频输入时可用。工作目录外的文件需使用绝对路径。 | 参数 | 类型 | 说明 | |------|------|------| | `path` | string | 文件路径 | ### `Glob` * **路径**:`kimi_cli.tools.file:Glob` * **描述**:按模式匹配文件和目录。最多返回 1000 个匹配项,不允许以 `**` 开头的模式。支持搜索已发现的 Skill 根目录,路径中的 `~` 会自动展开为用户主目录。 | 参数 | 类型 | 说明 | |------|------|------| | `pattern` | string | Glob 模式(如 `*.py`、`src/**/*.ts`) | | `directory` | string | 搜索目录,默认工作目录 | | `include_dirs` | bool | 是否包含目录,默认 true | ### `Grep` * **路径**:`kimi_cli.tools.file:Grep` * **描述**:使用正则表达式搜索文件内容,基于 ripgrep 实现。默认搜索隐藏文件(dotfiles),但不搜索被 `.gitignore` 排除的文件。敏感文件(如 `.env`、SSH 私钥、云凭据)始终被过滤,即使设置了 `include_ignored` 也不会出现在结果中。 | 参数 | 类型 | 说明 | |------|------|------| | `pattern` | string | 正则表达式模式 | | `path` | string | 搜索路径,默认当前目录 | | `glob` | string | 文件过滤(如 `*.js`) | | `type` | string | 文件类型(如 `py`、`js`、`go`) | | `output_mode` | string | 输出模式:`files_with_matches`(默认)、`content`、`count_matches` | | `-B` | int | 显示匹配行前 N 行 | | `-A` | int | 显示匹配行后 N 行 | | `-C` | int | 显示匹配行前后 N 行 | | `-n` | bool | 显示行号,默认 true | | `-i` | bool | 忽略大小写 | | `multiline` | bool | 启用多行匹配 | | `head_limit` | int | 限制输出行数,默认 250 | | `offset` | int | 跳过前 N 条结果,用于分页,默认 0 | | `include_ignored` | bool | 搜索被 `.gitignore` 排除的文件(如 `node_modules`、构建产物),默认 false | ### `WriteFile` * **路径**:`kimi_cli.tools.file:WriteFile` * **描述**:写入文件。写入操作需要用户审批。写入工作目录外文件时,必须使用绝对路径。 | 参数 | 类型 | 说明 | |------|------|------| | `path` | string | 绝对路径 | | `content` | string | 文件内容 | | `mode` | string | `overwrite`(默认)或 `append` | ### `StrReplaceFile` * **路径**:`kimi_cli.tools.file:StrReplaceFile` * **描述**:使用字符串替换编辑文件。编辑操作需要用户审批。编辑工作目录外文件时,必须使用绝对路径。 | 参数 | 类型 | 说明 | |------|------|------| | `path` | string | 绝对路径 | | `edit` | object/array | 单个编辑或编辑列表 | | `edit.old` | string | 要替换的原字符串 | | `edit.new` | string | 替换后的字符串 | | `edit.replace_all` | bool | 是否替换所有匹配项,默认 false | ### `SearchWeb` * **路径**:`kimi_cli.tools.web:SearchWeb` * **描述**:搜索网页。需要配置搜索服务(Kimi Code 平台自动配置)。 | 参数 | 类型 | 说明 | |------|------|------| | `query` | string | 搜索关键词 | | `limit` | int | 结果数量,默认 5,最大 20 | | `include_content` | bool | 是否包含页面内容,默认 false | ### `FetchURL` * **路径**:`kimi_cli.tools.web:FetchURL` * **描述**:抓取网页内容,返回提取的主要文本内容。如果配置了抓取服务会优先使用,否则使用本地 HTTP 请求。 | 参数 | 类型 | 说明 | |------|------|------| | `url` | string | 要抓取的 URL | ### `Think` * **路径**:`kimi_cli.tools.think:Think` * **描述**:让 Agent 记录思考过程,适用于复杂推理场景 | 参数 | 类型 | 说明 | |------|------|------| | `thought` | string | 思考内容 | ### `SendDMail` * **路径**:`kimi_cli.tools.dmail:SendDMail` * **描述**:发送延迟消息(D-Mail),用于检查点回滚场景 | 参数 | 类型 | 说明 | |------|------|------| | `message` | string | 要发送的消息 | | `checkpoint_id` | int | 要发送回的检查点 ID(>= 0) | ### `EnterPlanMode` * **路径**:`kimi_cli.tools.plan.enter:EnterPlanMode` * **描述**:请求进入 Plan 模式。调用后通常会向用户展示审批请求;如果会话处于 YOLO 或 AFK 模式则会自动批准进入。YOLO 只自动批准进入 Plan 模式,`ExitPlanMode` 仍会把最终方案展示给用户审批。仅在用户明确要求规划或存在重大架构歧义时使用。详见 [Plan 模式](../guides/interaction.md#plan-模式)。 此工具不接受参数。 ### `ExitPlanMode` * **路径**:`kimi_cli.tools.plan:ExitPlanMode` * **描述**:在 Plan 模式下完成方案后提交审批。调用前需先将方案写入 plan 文件,此工具会读取 plan 文件内容并展示给用户审批。用户可以选择某个实施路径(退出 Plan 模式并开始执行)、拒绝(保持 Plan 模式等待反馈)或提供修改意见。详见 [Plan 模式](../guides/interaction.md#plan-模式)。 | 参数 | 类型 | 说明 | |------|------|------| | `options` | list | null | 当方案包含多个可选实施路径时,列出 2–3 个选项供用户选择。每个选项有 `label`(1–8 个词的简短标签,可附加 "(Recommended)")和可选的 `description`(方案摘要)。不可使用 "Approve"、"Reject"、"Revise" 作为标签名。 | ### `TaskList` * **路径**:`kimi_cli.tools.background:TaskList` * **描述**:列出当前会话中的后台任务。适用于上下文压缩后重新获取任务 ID,或检查哪些任务仍在运行。 | 参数 | 类型 | 说明 | |------|------|------| | `active_only` | bool | 是否仅列出活跃任务,默认 true | | `limit` | int | 返回的最大任务数(1–100),默认 20 | ### `TaskOutput` * **路径**:`kimi_cli.tools.background:TaskOutput` * **描述**:获取后台任务的输出和状态。默认为非阻塞查询,返回当前状态和输出快照;如果输出被截断,可使用 `ReadFile` 分页读取完整日志。 | 参数 | 类型 | 说明 | |------|------|------| | `task_id` | string | 要查询的任务 ID | | `block` | bool | 是否等待任务完成,默认 false | | `timeout` | int | `block=true` 时的最大等待秒数(0–3600),默认 30 | ### `TaskStop` * **路径**:`kimi_cli.tools.background:TaskStop` * **描述**:停止正在运行的后台任务。需要用户审批。仅在任务必须取消时使用;对于正常完成的任务,应等待自动通知。在 Plan 模式下不可用。 | 参数 | 类型 | 说明 | |------|------|------| | `task_id` | string | 要停止的任务 ID | | `reason` | string | 停止原因(可选),默认 "Stopped by TaskStop" | ## 工具安全边界 **工作区范围** * 文件读写通常在工作目录(及通过 `--add-dir` 或 `/add-dir` 添加的额外目录)内进行 * 读取工作区外文件需使用绝对路径 * 写入和编辑操作都需要用户审批;操作工作区外文件时,必须使用绝对路径 **审批机制** 以下操作需要用户审批: | 操作 | 审批要求 | |------|---------| | Shell 命令执行 | 每次执行 | | 文件写入/编辑 | 每次操作 | | MCP 工具调用 | 每次调用 | | 停止后台任务 | 每次停止 | --- --- url: /en/customization/agents.md --- # Agents and Subagents An agent defines the AI's behavior, including system prompts, available tools, and subagents. You can use built-in agents or create custom agents. ## Built-in agents Kimi Code CLI provides two built-in agents. You can select one at startup with the `--agent` flag: ```sh kimi --agent okabe ``` ### `default` The default agent, suitable for general use. Enabled tools: `Agent`, `AskUserQuestion`, `SetTodoList`, `Shell`, `ReadFile`, `ReadMediaFile`, `Glob`, `Grep`, `WriteFile`, `StrReplaceFile`, `SearchWeb`, `FetchURL`, `EnterPlanMode`, `ExitPlanMode`, `TaskList`, `TaskOutput`, `TaskStop` ### `okabe` An experimental agent for testing new prompts and tools. Adds `SendDMail` on top of `default`. ## Custom agent files Agents are defined in YAML format. Load a custom agent with the `--agent-file` flag: ```sh kimi --agent-file /path/to/my-agent.yaml ``` **Basic structure** ```yaml version: 1 agent: name: my-agent system_prompt_path: ./system.md tools: - "kimi_cli.tools.shell:Shell" - "kimi_cli.tools.file:ReadFile" - "kimi_cli.tools.file:WriteFile" ``` **Inheritance and overrides** Use `extend` to inherit another agent's configuration and only override what you need to change: ```yaml version: 1 agent: extend: default # Inherit from default agent system_prompt_path: ./my-prompt.md # Override system prompt exclude_tools: # Exclude certain tools - "kimi_cli.tools.web:SearchWeb" - "kimi_cli.tools.web:FetchURL" ``` `extend: default` inherits from the built-in default agent. You can also specify a relative path to inherit from another agent file. **Configuration fields** | Field | Description | Required | |-------|-------------|----------| | `extend` | Agent to inherit from, can be `default` or a relative path | No | | `name` | Agent name | Yes (optional when inheriting) | | `system_prompt_path` | System prompt file path, relative to agent file | Yes (optional when inheriting) | | `system_prompt_args` | Custom arguments passed to system prompt, merged when inheriting | No | | `tools` | Tool list, format is `module:ClassName` | Yes (optional when inheriting) | | `exclude_tools` | Tools to exclude | No | | `subagents` | Subagent definitions | No | ## System prompt built-in parameters The system prompt file is a Markdown template that can use `${VAR}` syntax to reference variables and supports the Jinja2 `{% include %}` directive to include other files. Built-in variables include: | Variable | Description | |----------|-------------| | `${KIMI_NOW}` | Current time (ISO format) | | `${KIMI_WORK_DIR}` | Working directory path | | `${KIMI_WORK_DIR_LS}` | Working directory file list | | `${KIMI_AGENTS_MD}` | Merged `AGENTS.md` content from project root to working directory (including `.kimi/AGENTS.md`) | | `${KIMI_SKILLS}` | Loaded skills list | | `${KIMI_ADDITIONAL_DIRS_INFO}` | Information about additional directories added via `--add-dir` or `/add-dir` | You can also define custom parameters via `system_prompt_args`: ```yaml agent: system_prompt_args: MY_VAR: "custom value" ``` Then use `${MY_VAR}` in the prompt. **System prompt example** ```markdown # My Agent You are a helpful assistant. Current time: ${KIMI_NOW}. Working directory: ${KIMI_WORK_DIR} ${MY_VAR} ``` ## Defining subagents in agent files Subagents can handle specific types of tasks. After defining subagents in an agent file, the main agent can launch them via the `Agent` tool: ```yaml version: 1 agent: extend: default subagents: coder: path: ./coder-sub.yaml description: "Handle coding tasks" reviewer: path: ./reviewer-sub.yaml description: "Code review expert" ``` Subagent files are also standard agent format, typically inheriting from the main agent: ```yaml # coder-sub.yaml version: 1 agent: extend: ./agent.yaml # Inherit from main agent system_prompt_args: ROLE_ADDITIONAL: | You are now running as a subagent... ``` ## Built-in subagent types The default agent configuration includes three built-in subagent types, each with different tool policies and use cases: | Type | Purpose | Available tools | |------|---------|----------------| | `coder` | General software engineering: read/write files, run commands, search code | `Shell`, `ReadFile`, `ReadMediaFile`, `Glob`, `Grep`, `WriteFile`, `StrReplaceFile`, `SearchWeb`, `FetchURL` | | `explore` | Fast read-only codebase exploration: search, read, summarize | `Shell`, `ReadFile`, `ReadMediaFile`, `Glob`, `Grep`, `SearchWeb`, `FetchURL` (no write tools) | | `plan` | Implementation planning and architecture design: analyze files, create plans | `ReadFile`, `ReadMediaFile`, `Glob`, `Grep`, `SearchWeb`, `FetchURL` (no Shell, no write tools) | All subagent types are prohibited from nesting the `Agent` tool (subagents cannot create their own subagents). The `Agent` tool is only available to the root agent. ## How subagents run Subagents launched via the `Agent` tool run in an isolated context and return results to the main agent when complete. Each subagent instance maintains its own context history and metadata under `subagents//` in the session directory, and can be resumed across multiple invocations. Advantages of this approach: * Isolated context, avoiding pollution of main agent's conversation history * Multiple independent tasks can be processed in parallel * Subagents can have targeted system prompts * Persistent instances preserve context across multiple calls ## Built-in tools list The following are all built-in tools in Kimi Code CLI. ### `Agent` * **Path**: `kimi_cli.tools.agent:Agent` * **Description**: Start or resume a subagent instance for a focused task. Three built-in subagent types are available: `coder` (general software engineering), `explore` (fast read-only codebase exploration), and `plan` (implementation planning and architecture design). Each instance maintains its own context history and supports foreground or background execution. | Parameter | Type | Description | |-----------|------|-------------| | `description` | string | Short task description (3-5 words) | | `prompt` | string | Detailed task description | | `subagent_type` | string | Built-in subagent type, default `coder` | | `model` | string | Optional model override | | `resume` | string | Optional agent instance ID to resume an existing instance | | `run_in_background` | bool | Whether to run in background, default false | | `timeout` | int | Timeout in seconds, range 30–3600. Foreground defaults to no timeout (runs until completion), background defaults to 15 minutes; the task is stopped if the limit is exceeded | ### `AskUserQuestion` * **Path**: `kimi_cli.tools.ask_user:AskUserQuestion` * **Description**: Present structured questions and options to the user during execution, collecting preferences or decisions. Suitable for scenarios where the user needs to choose between approaches, resolve ambiguous instructions, or provide requirements. Should not be overused — only call when the user's choice genuinely affects subsequent actions. | Parameter | Type | Description | |-----------|------|-------------| | `questions` | array | Questions list (1–4 questions) | | `questions[].question` | string | Question text, ending with `?` | | `questions[].header` | string | Short label, max 12 characters (e.g., `Auth`, `Style`) | | `questions[].options` | array | Available options (2–4), the system adds an "Other" option automatically | | `questions[].options[].label` | string | Option label (1–5 words), append `(Recommended)` for recommended options | | `questions[].options[].description` | string | Option description | | `questions[].multi_select` | bool | Allow multiple selections, default false | ### `SetTodoList` * **Path**: `kimi_cli.tools.todo:SetTodoList` * **Description**: Manage todo list, track task progress. Supports three usage modes: update mode (pass `todos` array to replace the entire list), query mode (omit `todos` to return the current list), and clear mode (pass an empty array `[]` to clear the list). Todo items are persisted to session state. | Parameter | Type | Description | |-----------|------|-------------| | `todos` | array | null | Todo list items. Omit to query the current list; pass `[]` to clear | | `todos[].title` | string | Todo item title | | `todos[].status` | string | Status: `pending`, `in_progress`, `done` | ### `Shell` * **Path**: `kimi_cli.tools.shell:Shell` * **Description**: Execute shell commands. Requires user approval. Uses the configured shell for the OS (bash/sh on Unix-like platforms, Git Bash `bash.exe` on Windows). | Parameter | Type | Description | |-----------|------|-------------| | `command` | string | Command to execute | | `timeout` | int | Timeout in seconds, default 60, max 300 for foreground / 86400 for background | | `run_in_background` | bool | Whether to run as a background task, default false | | `description` | string | Short description for the background task, required when `run_in_background=true` | When `run_in_background=true`, the command is launched as a background task and the tool immediately returns a task ID, allowing the AI to continue working. The system automatically sends a notification when the task completes. Ideal for long-running builds, tests, watchers, and servers. ### `ReadFile` * **Path**: `kimi_cli.tools.file:ReadFile` * **Description**: Read text file content. Max 1000 lines per read, max 2000 characters per line. Files outside working directory require absolute paths. Every read returns the total number of lines in the file. Sensitive files (such as `.env`, SSH private keys, and cloud credentials) are rejected. | Parameter | Type | Description | |-----------|------|-------------| | `path` | string | File path | | `line_offset` | int | Starting line number, default 1. Supports negative values to read from the end of the file (e.g. `-100` reads the last 100 lines); absolute value cannot exceed 1000 | | `n_lines` | int | Number of lines to read, default/max 1000 | ### `ReadMediaFile` * **Path**: `kimi_cli.tools.file:ReadMediaFile` * **Description**: Read image or video files. Max file size 100MB. Only available when the model supports image/video input. Files outside working directory require absolute paths. | Parameter | Type | Description | |-----------|------|-------------| | `path` | string | File path | ### `Glob` * **Path**: `kimi_cli.tools.file:Glob` * **Description**: Match files and directories by pattern. Returns max 1000 matches, patterns starting with `**` not allowed. Can also search within discovered skill roots, and `~` in paths is expanded to the user's home directory. | Parameter | Type | Description | |-----------|------|-------------| | `pattern` | string | Glob pattern (e.g., `*.py`, `src/**/*.ts`) | | `directory` | string | Search directory, defaults to working directory | | `include_dirs` | bool | Include directories, default true | ### `Grep` * **Path**: `kimi_cli.tools.file:Grep` * **Description**: Search file content with regular expressions, based on ripgrep. Hidden files (dotfiles) are searched by default, but files excluded by `.gitignore` are not. Sensitive files (such as `.env`, SSH private keys, and cloud credentials) are always filtered out, even when `include_ignored` is set. | Parameter | Type | Description | |-----------|------|-------------| | `pattern` | string | Regular expression pattern | | `path` | string | Search path, defaults to current directory | | `glob` | string | File filter (e.g., `*.js`) | | `type` | string | File type (e.g., `py`, `js`, `go`) | | `output_mode` | string | Output mode: `files_with_matches` (default), `content`, `count_matches` | | `-B` | int | Show N lines before match | | `-A` | int | Show N lines after match | | `-C` | int | Show N lines before and after match | | `-n` | bool | Show line numbers, default true | | `-i` | bool | Case insensitive | | `multiline` | bool | Enable multiline matching | | `head_limit` | int | Limit output lines, default 250 | | `offset` | int | Skip first N results for pagination, default 0 | | `include_ignored` | bool | Search files excluded by `.gitignore` (e.g. `node_modules`, build artifacts), default false | ### `WriteFile` * **Path**: `kimi_cli.tools.file:WriteFile` * **Description**: Write files. Requires user approval. Absolute paths are required when writing files outside the working directory. | Parameter | Type | Description | |-----------|------|-------------| | `path` | string | Absolute path | | `content` | string | File content | | `mode` | string | `overwrite` (default) or `append` | ### `StrReplaceFile` * **Path**: `kimi_cli.tools.file:StrReplaceFile` * **Description**: Edit files using string replacement. Requires user approval. Absolute paths are required when editing files outside the working directory. | Parameter | Type | Description | |-----------|------|-------------| | `path` | string | Absolute path | | `edit` | object/array | Single edit or list of edits | | `edit.old` | string | Original string to replace | | `edit.new` | string | Replacement string | | `edit.replace_all` | bool | Replace all matches, default false | ### `SearchWeb` * **Path**: `kimi_cli.tools.web:SearchWeb` * **Description**: Search the web. Requires search service configuration (auto-configured on Kimi Code platform). | Parameter | Type | Description | |-----------|------|-------------| | `query` | string | Search keywords | | `limit` | int | Number of results, default 5, max 20 | | `include_content` | bool | Include page content, default false | ### `FetchURL` * **Path**: `kimi_cli.tools.web:FetchURL` * **Description**: Fetch webpage content, returns extracted main text. Uses fetch service if configured, otherwise uses local HTTP request. | Parameter | Type | Description | |-----------|------|-------------| | `url` | string | URL to fetch | ### `Think` * **Path**: `kimi_cli.tools.think:Think` * **Description**: Let the agent record thinking process, suitable for complex reasoning scenarios | Parameter | Type | Description | |-----------|------|-------------| | `thought` | string | Thinking content | ### `SendDMail` * **Path**: `kimi_cli.tools.dmail:SendDMail` * **Description**: Send delayed message (D-Mail), for checkpoint rollback scenarios | Parameter | Type | Description | |-----------|------|-------------| | `message` | string | Message to send | | `checkpoint_id` | int | Checkpoint ID to send back to (>= 0) | ### `EnterPlanMode` * **Path**: `kimi_cli.tools.plan.enter:EnterPlanMode` * **Description**: Request to enter plan mode. After calling, an approval request is presented to the user unless the session is in YOLO or AFK mode; YOLO auto-approves entering plan mode, but `ExitPlanMode` still presents the final plan for user approval. Use this only when the user explicitly requests planning or when there is significant architectural ambiguity. See [Plan mode](../guides/interaction.md#plan-mode). This tool takes no parameters. ### `ExitPlanMode` * **Path**: `kimi_cli.tools.plan:ExitPlanMode` * **Description**: Submit a plan for user approval while in plan mode. Before calling, the plan must be written to the plan file. This tool reads the plan file content and presents it to the user for approval. The user can select an implementation path (exit plan mode and start execution), reject (stay in plan mode and wait for feedback), or provide revision comments. See [Plan mode](../guides/interaction.md#plan-mode). | Parameter | Type | Description | |-----------|------|-------------| | `options` | list | null | When the plan contains multiple alternative implementation paths, list 2–3 options for the user to choose from. Each option has a `label` (1–8 word short name, may append "(Recommended)") and an optional `description` (brief summary). The labels "Approve", "Reject", and "Revise" are reserved and cannot be used. | ### `TaskList` * **Path**: `kimi_cli.tools.background:TaskList` * **Description**: List background tasks in the current session. Useful for re-enumerating task IDs after context compaction or checking which tasks are still running. | Parameter | Type | Description | |-----------|------|-------------| | `active_only` | bool | List only active tasks, default true | | `limit` | int | Maximum number of tasks to return (1–100), default 20 | ### `TaskOutput` * **Path**: `kimi_cli.tools.background:TaskOutput` * **Description**: Retrieve output and status of a background task. Returns a non-blocking status/output snapshot by default; use `ReadFile` with the returned `output_path` to read the full log if output is truncated. | Parameter | Type | Description | |-----------|------|-------------| | `task_id` | string | Task ID to query | | `block` | bool | Whether to wait for task completion, default false | | `timeout` | int | Maximum wait time in seconds when `block=true` (0–3600), default 30 | ### `TaskStop` * **Path**: `kimi_cli.tools.background:TaskStop` * **Description**: Stop a running background task. Requires user approval. Use only when a task must be cancelled; for normal completion, wait for the automatic notification. Not available in plan mode. | Parameter | Type | Description | |-----------|------|-------------| | `task_id` | string | Task ID to stop | | `reason` | string | Reason for stopping (optional), default "Stopped by TaskStop" | ## Tool security boundaries **Workspace scope** * File reading and writing are typically done within the working directory (and additional directories added via `--add-dir` or `/add-dir`) * Absolute paths are required when reading files outside the workspace * Write and edit operations require user approval; absolute paths are required when operating on files outside the workspace **Approval mechanism** The following operations require user approval: | Operation | Approval required | |-----------|-------------------| | Shell command execution | Each execution | | File write/edit | Each operation | | MCP tool calls | Each call | | Stop background task | Each stop | --- --- url: /en/release-notes/breaking-changes.md --- # Breaking changes and migration This page documents breaking changes in Kimi Code CLI releases and provides migration guidance. ## Unreleased ## 1.51.0 ### The `kimi-code` package on PyPI no longer installs Kimi CLI The `kimi-code` package on PyPI used to be an alias of Kimi CLI. It is now a stub that only prints instructions for installing the new Kimi Code CLI and exits with status 1. Kimi CLI itself is archived and no longer maintained. * **Affected**: Users who installed Kimi CLI through the `kimi-code` package on PyPI (for example `uv tool install kimi-code`) * **Migration**: Install Kimi Code CLI with `curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash` (Windows: `irm https://code.kimi.com/kimi-code/install.ps1 | iex`), then run `kimi migrate` to migrate your config and sessions. See the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration) ## 1.49.0 ### Kimi no longer sends legacy `reasoning_effort` automatically Kimi thinking configuration now uses `thinking.type` exclusively. `Kimi.with_thinking(...)` no longer adds the legacy `reasoning_effort` parameter to requests. * **Affected**: Applications using Kosong's Kimi provider with older Kimi-compatible endpoints that require `reasoning_effort` * **Migration**: Update the endpoint to support `thinking.type`. If an older endpoint still requires the legacy parameter, pass it explicitly with `with_generation_kwargs(reasoning_effort="...")` ## 1.43.0 ### MCP OAuth token cache moved to `~/.kimi/mcp-oauth/` Kimi Code CLI now uses FastMCP 3's persistent OAuth storage API for MCP servers and stores MCP OAuth tokens under `~/.kimi/mcp-oauth/`. Tokens from the old FastMCP 2.x cache location are not migrated automatically. * **Affected**: Users who authorized OAuth MCP servers before upgrading * **Migration**: If `kimi mcp list` shows an OAuth server as requiring authorization, run `kimi mcp auth ` once to create a new token in `~/.kimi/mcp-oauth/`. Use `kimi mcp reset-auth ` before re-authorizing if the stored token becomes invalid or corrupted ## 1.42.0 ### Windows shell backend changed from PowerShell to Git Bash The Shell tool on Windows now runs commands through `bash.exe` (POSIX semantics) instead of `powershell.exe`. Windows users gain the same Unix-style command syntax as Linux/macOS, but must have Git for Windows installed. * **Affected**: All Windows users; integrations, agent specs, or saved snippets that rely on PowerShell-specific syntax (`Get-ChildItem`, `Where-Object`, `cmdlet -Foo Bar` argument style, `;`-only command chaining, `NUL` redirects, etc.) reaching the Shell tool * **Migration**: 1. Install [Git for Windows](https://git-scm.com/downloads/win) if not already installed; the bundled `bash.exe` (typically `C:\Program Files\Git\bin\bash.exe`) is auto-discovered via `where.exe git` or the standard install location 2. If `bash.exe` lives in a non-standard location, set the `KIMI_CLI_GIT_BASH_PATH` environment variable to its absolute path before launching kimi-cli 3. Update any custom prompts, agent specs, or snippets that hard-code PowerShell syntax to use Unix shell syntax instead (forward slashes inside Shell commands, `/dev/null` instead of `NUL`, `&&` and `||` for control flow, `grep`/`sed`/`awk` instead of PowerShell cmdlets) 4. Note that `python.exe`, `node.exe`, and other native Windows binaries called from inside bash still need native Windows paths (e.g. `python C:\path\to\script.py`); only POSIX-aware tools (cat, ls, grep, etc.) understand the `/c/path/...` form 5. If kimi-cli cannot find `bash.exe`, it now exits with an install hint at startup instead of falling back to PowerShell ## 1.40.0 ### `--print` now uses runtime AFK semantics instead of YOLO semantics Print mode still runs non-interactively and handles approvals automatically, but it now sets an invocation-only AFK overlay instead of enabling YOLO. This means `--print` treats the user as unavailable and auto-dismisses `AskUserQuestion`, while later interactive resumes do not inherit AFK solely because of a previous print run. * **Affected**: Scripts, wrappers, or custom integrations that inferred print-mode behavior from the explicit YOLO flag * **Migration**: Treat `--print` / `--quiet` as non-interactive AFK runs. Use `--yolo` only when you want to bypass permission approvals while a user remains reachable ### `skip_yolo_prompt_injection` replaced by `skip_afk_prompt_injection` YOLO no longer injects model guidance, so the old `skip_yolo_prompt_injection` config key is ignored. The remaining non-interactive reminder belongs to AFK mode and can be disabled with `skip_afk_prompt_injection`. * **Affected**: Config files or embedded applications that set `skip_yolo_prompt_injection` * **Migration**: Replace `skip_yolo_prompt_injection = true` with `skip_afk_prompt_injection = true` if you need to suppress AFK mode reminders ## 1.39.0 ### `merge_all_available_skills` default flipped to `true` The `merge_all_available_skills` config option default has changed from `false` to `true`. kimi-cli now merges all existing user- and project-level brand skill directories (`.kimi/skills`, `.claude/skills`, `.codex/skills`) by default instead of only using the first one found. Users who keep skills in multiple brand directories — for example both `~/.kimi/skills` and `~/.claude/skills` — will see every skill out of the box after upgrading. * **Affected**: Users who maintain multiple brand skill directories and relied on the first-match behavior to hide duplicates * **Migration**: Set `merge_all_available_skills = false` in your config to restore the previous first-match behavior ## 1.25.0 ### Wire protocol 1.6 — subagent and approval field changes The `SubagentEvent` field `task_tool_call_id` has been renamed to `parent_tool_call_id`, and new optional fields (`agent_id`, `subagent_type`) have been added. `ApprovalRequest` gains `source_kind`, `source_id`, `agent_id`, `subagent_type`, and `source_description` fields. `ApprovalResponse` gains a `feedback` field. * **Affected**: Wire mode clients that parse `SubagentEvent` or `ApprovalRequest`/`ApprovalResponse` payloads * **Migration**: Rename `task_tool_call_id` to `parent_tool_call_id` in your event handlers; handle the new optional fields as needed ### `CreateSubagent` and `Task` (multiagent) tools removed The `CreateSubagent` and `Task` tools under `kimi_cli.tools.multiagent` have been removed. Use the new `Agent` tool instead. * **Affected**: Custom agent configurations referencing `kimi_cli.tools.multiagent:Task` or `kimi_cli.tools.multiagent:CreateSubagent` * **Migration**: Replace with `kimi_cli.tools.agent:Agent` in your agent YAML `allowed_tools` ### `TaskOutput` `block` parameter default changed The `block` parameter of the `TaskOutput` tool now defaults to `false` (previously `true`). `TaskOutput` returns a non-blocking status/output snapshot by default. * **Affected**: Custom agents or Wire mode clients relying on `TaskOutput` blocking by default * **Migration**: Explicitly pass `block=true` if you need to wait for task completion ## 0.81 - Prompt Flow replaced by Flow Skills ### `--prompt-flow` option removed The `--prompt-flow` CLI option has been removed. Use flow skills instead. * **Affected**: Scripts and automation using `--prompt-flow` to load Mermaid/D2 flowcharts * **Migration**: Create a flow skill with embedded Agent Flow in `SKILL.md` and invoke via `/flow:` ### `/begin` command replaced The `/begin` slash command has been replaced with `/flow:` commands. * **Affected**: Users who used `/begin` to start a loaded Prompt Flow * **Migration**: Use `/flow:` to invoke flow skills directly ## 0.77 - Thinking mode and CLI option changes ### Thinking mode setting migration change After upgrading from `0.76`, the thinking mode setting is no longer automatically preserved. The previous `thinking` state stored in `~/.kimi/kimi.json` is no longer used; instead, thinking mode is now managed via the `default_thinking` configuration option in `~/.kimi/config.toml`, but values are not automatically migrated from legacy `metadata`. * **Affected**: Users who previously had thinking mode enabled * **Migration**: Reconfigure thinking mode after upgrading: * Use the `/model` command to select model and set thinking mode (interactive) * Or manually add to `~/.kimi/config.toml`: ```toml default_thinking = true # Set to true if you want thinking mode enabled by default ``` ### `--query` option removed The `--query` (`-q`) option has been removed. Use `--prompt` as the primary option, with `--command` as an alias. * **Affected**: Scripts and automation using `--query` or `-q` * **Migration**: * `--query` / `-q` → `--prompt` / `-p` * Or continue using `--command` / `-c` ## 0.74 - ACP command change ### `--acp` option deprecated The `--acp` option has been deprecated. Use the `kimi acp` subcommand instead. * **Affected**: Scripts and IDE configurations using `kimi --acp` * **Migration**: `kimi --acp` → `kimi acp` ## 0.66 - Config file and provider type ### Config file format migration The config file format has been migrated from JSON to TOML. * **Affected**: Users with `~/.kimi/config.json` * **Migration**: Kimi Code CLI will automatically read the old JSON config, but manual migration to TOML is recommended * **New location**: `~/.kimi/config.toml` JSON config example: ```json { "default_model": "kimi-k2-0711", "providers": { "kimi": { "type": "kimi", "base_url": "https://api.kimi.com/coding/v1", "api_key": "your-key" } } } ``` Equivalent TOML config: ```toml default_model = "kimi-k2-0711" [providers.kimi] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "your-key" ``` ### `google_genai` provider type renamed The provider type for Gemini Developer API has been renamed from `google_genai` to `gemini`. * **Affected**: Users with `type = "google_genai"` in their config * **Migration**: Change the `type` value to `"gemini"` * **Compatibility**: `google_genai` still works but updating is recommended ## 0.57 - Tool changes ### `Shell` tool The `Bash` tool (or `CMD` on Windows) has been unified and renamed to `Shell`. * **Affected**: Agent files referencing `Bash` or `CMD` tools * **Migration**: Change tool references to `Shell` ### `Task` tool moved to `multiagent` module The `Task` tool has been moved from `kimi_cli.tools.task` to `kimi_cli.tools.multiagent`. * **Affected**: Custom tools importing the `Task` tool * **Migration**: Change import path to `from kimi_cli.tools.multiagent import Task` ### `PatchFile` tool removed The `PatchFile` tool has been removed. * **Affected**: Agent configs using the `PatchFile` tool * **Alternative**: Use `StrReplaceFile` tool for file modifications ## 0.52 - CLI option changes ### `--ui` option removed The `--ui` option has been removed in favor of separate flags. * **Affected**: Scripts using `--ui print`, `--ui acp`, or `--ui wire` * **Migration**: * `--ui print` → `--print` * `--ui acp` → `kimi acp` * `--ui wire` → `--wire` ## 0.42 - Keyboard shortcut changes ### Mode switch shortcut The agent/shell mode toggle shortcut has changed from `Ctrl-K` to `Ctrl-X`. * **Affected**: Users accustomed to using `Ctrl-K` for mode switching * **Migration**: Use `Ctrl-X` to toggle modes ## 0.27 - CLI option rename ### `--agent` option renamed The `--agent` option has been renamed to `--agent-file`. * **Affected**: Scripts using `--agent` to specify custom agent files * **Migration**: Change `--agent` to `--agent-file` * **Note**: `--agent` is now used to specify built-in agents (e.g., `default`, `okabe`) ## 0.25 - Package name change ### Package renamed from `ensoul` to `kimi-cli` * **Affected**: Code or scripts using the `ensoul` package name * **Migration**: * Installation: `pip install ensoul` → `pip install kimi-cli` or `uv tool install kimi-cli` * Command: `ensoul` → `kimi` ### `ENSOUL_*` parameter prefix changed The system prompt built-in parameter prefix has changed from `ENSOUL_*` to `KIMI_*`. * **Affected**: Custom agent files using `ENSOUL_*` parameters * **Migration**: Change parameter prefix to `KIMI_*` (e.g., `ENSOUL_NOW` → `KIMI_NOW`) --- --- url: /en/release-notes/changelog.md --- # Changelog This page documents the changes in each Kimi Code CLI release. ## Unreleased ## 1.52.0 (2026-09-22) **Highlights**: Kimi CLI is archived and no longer maintained, and this is the final release. Please migrate to [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code); see the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration) * Running `kimi` with no arguments now directly downloads and runs the Kimi Code install script fetched from the CDN (no confirmation); CDN-side script updates take effect without a new package release ## 1.51.0 (2026-09-21) **Highlights**: Kimi CLI is archived and no longer maintained, and this is the final release. Please migrate to [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code); see the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration) * Build: Mark `kimi-cli` and all packages in this repository as archived — no further releases, bug fixes, or security updates are planned * Build: Stop installing the legacy CLI from the `kimi-code` package on PyPI — running `kimi-code` now prints instructions for installing the new Kimi Code CLI and exits with status 1 ## 1.50.0 (2026-09-02) * Kosong: Stop sending an empty `anthropic-beta` header when no beta features are declared — adaptive thinking removes the interleaved-thinking beta, which previously left an empty header value that some backends reject ## 1.49.0 (2026-07-16) **Highlights**: The completion-token budget for Kimi providers now adapts to the model's remaining context window, reducing context-length overflow errors on long turns * LLM: Clamp the Kimi completion-token budget to the model's remaining context window — the CLI no longer sends a fixed `max_tokens=32000` but estimates the remaining context for each request and caps `max_completion_tokens` accordingly. Set the new `KIMI_MODEL_MAX_COMPLETION_TOKENS` env var for an explicit hard cap (`KIMI_MODEL_MAX_TOKENS` remains a compatibility alias; `0` or a negative value disables clamping) * Kosong: Stop Kimi from automatically sending the legacy `reasoning_effort` parameter when configuring thinking — requests now use `thinking.type` exclusively while preserving explicit legacy passthrough * Kosong: Fix empty-string `reasoning_content` from thinking models being dropped from history — a reply that reasoned but ended with empty reasoning was recorded as having no reasoning at all, so Preserved Thinking backends that require `reasoning_content` on every assistant message rejected the next request with a 400 ## 1.47.0 (2026-06-05) * Shell: Guide users to the new standalone Kimi Code — adds a `/upgrade` command that installs it (migrating your config & sessions automatically), a welcome-screen nudge, and a once-per-day tip shown on exit * Shell: Show trailing output in tool error briefs when commands fail ## 1.46.0 (2026-05-28) * Shell: Support styled text in welcome tips * ACP: Replay session history on load * Core: Prevent TTY hang on exit * Core: Close MCP connections during shutdown ## 1.45.0 (2026-05-26) * Shell: `/clear` is now an alias for `/new` — both commands start a new session; previously `/clear` only cleared context without creating a new session * Shell: Fix misleading "Quota exceeded" prefix shown on every 403 error ## 1.44.0 (2026-05-13) * Shell: Add slash command alias resolution — aliases such as `/h`, `?`, and `status` now resolve to their canonical commands (`/help`, `/usage`); the completer and help output display alias matches as `/name (alias)` for clarity * Shell: Fix `/usage` alias registration — the alias was incorrectly stored as `"/status"` instead of `"status"`, causing alias lookup to fail ## 1.43.0 (2026-05-12) * Security: Bump pillow to 12.2.0 to address CVE-2026-25990 (out-of-bounds write when loading PSD images); unblocks installs in environments that gate on the older pinned version * Shell: Fix missing visual spacing in the shell UI — add blank lines after user input echoes, content blocks, tool call results, notifications, error panels, and steer inputs so consecutive elements no longer collapse together * Shell: Restore markdown link highlighting (bright blue underlined text and cyan underlined URLs) and add underline separators to h2-h6 headings; adjust table rendering to use square box borders with visible edges * Core: Include completion timestamp and elapsed duration in background task terminal notifications, and add `finished_at` and `duration_s` to the notification payload for easier tracking * MCP: Stop FastMCP OAuth startup from printing Authlib deprecation warnings by upgrading the MCP client stack to FastMCP 3.2.4 * MCP: Store OAuth MCP tokens in `~/.kimi/mcp-oauth/` using FastMCP 3's persistent storage API; users with existing OAuth MCP authorizations may need to run `kimi mcp auth ` once after upgrading ## 1.42.0 (2026-05-11) * Shell: Switch the Windows shell backend from PowerShell to Git Bash, so the Shell tool now runs commands through `bash.exe` (POSIX semantics) instead of `powershell.exe`. Windows users get the same Unix-style command syntax (`&&`, `||`, `|`, `/dev/null`, `grep`, `sed`, etc.) as Linux/macOS. **Requires Git for Windows installed**: kimi-cli locates `bash.exe` via the `KIMI_CLI_GIT_BASH_PATH` env override → `where.exe git` → standard install paths (`C:\Program Files\Git\bin\bash.exe`); if none resolve, kimi-cli prints an install hint and exits at startup * Shell: Defend against hallucinated CMD-style `2>nul` redirects on Windows by rewriting them to `2>/dev/null` before reaching git-bash — without this defense git-bash would create a file literally named `nul` (a Windows reserved device name) that breaks `git add .` and `git clone`; on Linux/macOS, `>nul` is a legitimate redirect to a file named `nul` and is left untouched * File: Accept POSIX-form paths on Windows in `ReadFile`, `WriteFile`, `StrReplaceFile`, `Glob`, and `Grep` — these tools now recognize `/c/Users/foo` (Git Bash style), `/cygdrive/c/Users/foo` (Cygwin style), and `\\server\share` (UNC) in addition to native Windows paths, automatically converting to native form for filesystem operations * Shell: Clear partial streamed output when an LLM step is retried — previously, if a step failed mid-stream (e.g. rate limit or server error), the incomplete text and unfinished tool-call blocks from the aborted attempt would remain on screen and be mixed with the new attempt's output. The shell UI now discards the partial state and prints a retry banner showing the reason, attempt count, and wait time; print mode also discards buffered assistant messages on retry * Wire: Bump protocol version to 1.10 — add `StepRetry` event emitted when a step attempt fails and will be retried, carrying attempt count, wait time, and error details * Core: Stop plan-mode and afk-mode workflow prompts from being injected into subagents — subagents share session-level mode state for persistence, but their YAMLs typically exclude root workflow tools such as `EnterPlanMode`, `ExitPlanMode`, and `AskUserQuestion`. These prompt injections are now root-only. Tool-level read-only checks under plan mode are unchanged, so behavior compatibility is preserved ## 1.41.0 (2026-04-30) * Plugin: Support installing plugins directly from a `.zip` URL — `kimi plugin install` now accepts HTTP(S) URLs ending in `.zip` (e.g. GitHub/GitLab archive links like `.../archive/refs/heads/main.zip`) and downloads + extracts them before resolving `plugin.json`, in addition to the existing git URL, local directory, and local zip-file sources * Shell: Enable clipboard image paste on headless Linux over SSH — when pyperclip is unavailable (e.g. DISPLAY is not set), Ctrl-V now falls back to xclip or wl-paste so remote clipboard bridges can still inject images; also prevents a UI crash from built-in clipboard shortcuts when pyperclip is broken ## 1.40.0 (2026-04-28) * Core: Fix `--yolo` mode unintentionally preventing the model from calling `AskUserQuestion` — yolo used to inject a system reminder telling the model it was in "non-interactive mode" and must not ask, and the ask-user tool auto-dismissed in yolo. Both were wrong: yolo only bypasses permission approvals; it does not mean "the user is gone". Yolo no longer injects model guidance, and the user remains reachable through `AskUserQuestion` * CLI: Split permission bypass from unattended execution — `--yolo` bypasses permission approvals while the user is still at the terminal, while `--afk` / `/afk` means away-from-keyboard: `AskUserQuestion` is auto-dismissed and approvals are handled automatically. `--print` now uses runtime AFK behavior instead of yolo, matching its non-interactive execution model. The status bar shows `yolo` and `afk` independently, and `/yolo` and `/afk` toggle their own flag without disturbing the other * Config: Replace `skip_yolo_prompt_injection` with `skip_afk_prompt_injection` now that yolo no longer injects model guidance. The old config key is ignored if present * Shell: Fix `/yolo` toggling producing misleading UI messages when afk is also active — `/yolo` used to read the combined auto-approval state, so pressing it under afk would claim approval was now required even though afk still handled approvals automatically. `/yolo` now reads and writes only the yolo flag, leaving afk alone * Web: Fix AI title generation overwriting a manually-set title when the LLM call finishes after the user has already renamed the session — the final write now reloads state and yields to a `title_generated` flag set by another request * Web: Surface session rename, archive, unarchive, and title generation failures as toast notifications instead of only logging to the console * Web: Keep tool media previews visible when tool details are collapsed — images and videos returned by tools now render below the tool card instead of inside the collapsible detail area, so preview thumbnails remain accessible after collapsing a tool * Kosong: Fix stale API key after OAuth token refresh in Kimi provider — `on_retryable_error` now reads the current `api_key` from the live client instead of the cached `_api_key`, so that OAuth token refreshes applied via `client.api_key` are preserved when the client is rebuilt after a retryable error * Core: Approval requests no longer auto-timeout after 5 minutes, which previously surfaced as `Rejected by user`; active foreground and subagent approvals now wait indefinitely for user response * Shell: Fix `/usage` remaining quota rendering — the progress bar, warning colors, and `% left` label now all use the remaining quota ratio consistently, so high remaining quota shows as green/full and near-exhausted quota shows as yellow or red * Shell: Show active background agent task count in the prompt status bar — the existing `⚙ bash: N` badge only counted background Shell tasks and filtered out background Agent subagents, so when many subagents were running the prompt looked idle and users could not tell work was in progress; the toolbar now renders `⚙ bash: N` and `⚙ agent: N` as two independent badges (each hidden when its count is 0) and drops the agent badge first when the terminal is too narrow to fit both * Auth: Fix managed model list refresh silently failing for OAuth users with expired tokens — the background `/models` sync now detects 401 responses, forces an OAuth token refresh, and retries with the refreshed token; if the refresh fails or the refreshed token is still rejected, it falls back to the originally configured static API key instead of skipping the provider * Core: Fix connection recovery not triggering OAuth refresh when the retry returns 401 — after recreating the HTTP client on `APIConnectionError` or `APITimeoutError`, the retry now re-enters the full recovery path so a subsequent 401 correctly refreshes the OAuth token instead of bubbling to the user as an unrecoverable error * Shell: Echo `/skill:*` and `/flow:*` inputs in the transcript so workflow commands stay visible after enter; operational slash commands like `/usage` and `/model` remain hidden * Core: Raise default `max_steps_per_turn` from 500 to 1000 so long-running agents are less likely to hit the per-turn limit ## 1.39.0 (2026-04-24) * Skill: Fix project-scope skills being ignored and user-scope skills silently winning name conflicts — the system prompt now groups discovered skills under `### Project` / `### User` / `### Extra` / `### Built-in` headings so the model can tell where each skill came from, and when the same name exists in multiple scopes the more specific scope wins (Project > User > Extra > Built-in) so a project's own `.kimi/skills/foo` or `.claude/skills/foo` correctly overrides a user-level or bundled `foo` instead of the other way around * Skill: Accept single-file `.md` skills alongside the canonical `/SKILL.md` subdirectory layout — useful when migrating a flat markdown collection into a skills directory; `name` defaults to the filename stem (frontmatter `name:` still wins if set), description follows the same three-step chain as subdirectory skills (frontmatter `description:` → first non-empty body line, capped at 240 characters → `"No description provided."` placeholder), and if a flat and a subdirectory skill share a name in the same directory the subdirectory wins with a warning * Skill: Add `extra_skill_dirs` config field for pulling in custom skill directories on top of the built-in / user / project auto-discovery — each entry may be an absolute path, a `~`-prefixed path (expanded against `$HOME`), or a path relative to the project root (the nearest `.git` ancestor of the work directory, not the current working directory); non-existent entries are silently skipped and symlink/trailing-slash duplicates canonicalize to a single root so a path listed twice or aliased to an already-discovered directory does not render twice in the system prompt * Skill: Harden discovery against `OSError` from `is_dir` / `iterdir` (for example when an `extra_skill_dirs` entry points at a directory with restricted permissions) — affected entries are logged and skipped instead of aborting the whole skill-discovery pass * Core: Fix DeepSeek V4 (and other OpenAI-compatible thinking-mode backends) returning 400 `The reasoning_content in the thinking mode must be passed back to the API` when a tool call follows a reasoning turn — `openai_legacy` providers now default `reasoning_key` to `"reasoning_content"` so the response's reasoning is stored in history and round-tripped automatically on subsequent turns. An optional `reasoning_key` field is also added to `LLMProvider` to override the field name (e.g. `"reasoning"` for non-standard gateways) or disable round-tripping entirely by setting it to `""` * Core: Add `skip_yolo_prompt_injection` config option to suppress the system reminder normally injected when yolo mode is active — useful when building custom applications on top of `KimiSoul` that do not need the non-interactive mode hint * Kimi: Add `KIMI_MODEL_THINKING_KEEP` environment variable that forwards its value verbatim to the Moonshot API as `thinking.keep`, enabling Preserved Thinking (e.g. `export KIMI_MODEL_THINKING_KEEP=all` to retain historical `reasoning_content` across turns); effective only for Moonshot models supporting Preserved Thinking (e.g. `kimi-k2.6` / `kimi-k2-thinking`), unset or empty string preserves the previous behavior and omits the field, and the override only applies when the current model is actually in thinking mode so the API never receives a `thinking.keep` without the companion `thinking.type`. Note that `keep=all` increases input tokens and API cost because history reasoning is resent * Kosong: Fix `Kimi.with_extra_body` silently dropping previously set `thinking.type` when a later call added another `thinking.*` field — the `thinking` sub-dict is now merged field-by-field instead of shallow-replaced, so composing `with_thinking(...)` with `with_extra_body({"thinking": {...}})` preserves both contributions * Kosong: Fix Kimi provider sending empty `content` alongside `tool_calls`, which caused 400 "text content is empty" errors from the Moonshot API. When an assistant message has tool calls and its visible content is effectively empty (no text or only whitespace/think parts), the `content` field is now omitted entirely * Shell: Fix approval request feedback text cursor rendering — the block cursor now correctly renders at the actual cursor position instead of always being pinned to the end of the line; when the cursor is in the middle of the text, the character under the cursor is drawn with reverse video (mimicking a terminal's native block cursor) * Kosong: Fix Moonshot 400 `At path 'properties.X': type is not defined` when an MCP server exposes tools whose parameter schemas have enum-only or otherwise type-less properties (seen with the JetBrains Rider MCP's `truncateMode`) — the Kimi provider now patches each tool's schema in-flight to fill in a JSON Schema `type` (inferred from `enum`/`const` values when possible, else defaulted to `"string"`), so the whole session no longer fails every request with a schema validation error; OpenAI and Anthropic paths are unaffected * Skill: Project-scope skill discovery now walks up to the nearest `.git` ancestor before looking for `.kimi/skills` / `.claude/skills` / `.codex/skills` / `.agents/skills`, so skills defined at the repository root are picked up even when kimi-cli is launched from a subdirectory (for example inside a monorepo package). Falls back to the work directory itself when no `.git` marker is found, so we never walk up into an unrelated parent tree. * Skill: Change the default of `merge_all_available_skills` from `false` to `true`. kimi-cli now merges all existing user- and project-level brand skill directories (`.kimi/skills`, `.claude/skills`, `.codex/skills`) by default instead of only using the first one found, so users who keep skills in multiple brand directories — for example both `~/.kimi/skills` and `~/.claude/skills` — see every skill out of the box. **Behavior change**: users who previously relied on the first-match default can restore it by setting `merge_all_available_skills = false` in their config. ## 1.38.0 (2026-04-22) * Shell: Fix `Rejected by user` misleading message when an approval modal times out — after the 300s safety timeout, the tool call now rejects with `Rejected: approval timed out`, so users returning to their session after stepping away can tell the rejection was a timeout rather than a manual rejection. Pass `--yolo`/`-y` to auto-approve tool calls if you regularly leave sessions unattended * Auth: Fix OAuth users being forced to `/login` again after an unrelated refresh-token rotation race — when a concurrently-running kimi-cli instance (terminal, VS Code extension, or `kimi -p` one-shot) legitimately rotated the refresh token, the current instance's now-stale refresh request would come back with a 401, and a TOCTOU window between the "did another instance rotate?" disk check and the `delete_tokens` call could wipe the credentials file even though a valid rotated token was about to be written to it; the in-memory cache is still cleared so truly revoked tokens surface on the next request, but the file is preserved so a concurrent instance's freshly-rotated token can be recovered, and an eventual `/login` still overwrites it atomically * Kosong: Fix parallel tool results being split into multiple user messages in Anthropic provider — consecutive tool-result-only user messages are now merged into a single message, complying with the Anthropic Messages API spec that all `tool_use` blocks in an assistant turn must be answered within one user message; this fixes 400 errors on strict Anthropic-compatible backends (e.g. DeepSeek `/anthropic` endpoint) and prevents the official backend from silently teaching the model to avoid parallel tool calls ## 1.37.0 (2026-04-20) * Print: Wait for background tasks before exiting — in one-shot `--print` mode, the process now waits for running background agents to finish and lets the model process their results, instead of exiting and killing them. The wait is capped at `min(max(active_task.timeout_s or agent_task_timeout_s), print_wait_ceiling_s)` (default ceiling 1h); on timeout the tasks are killed and the model gets one more turn via a `` to summarise before exit * Shell/Print: On exit the CLI now lists each background task being killed (id + description) on stderr and waits out the configured grace period before reporting any tasks that have not reached terminal state (split into "still terminating" for workers mid-shutdown vs "stop request failed" for genuinely leaking tasks); `keep_alive_on_exit=true` still skips the entire path * Auth: Auto-refresh the managed model list at startup for OAuth-logged-in users — the CLI now fetches the latest models from the provider's `/models` endpoint as a background task when the shell launches, so newly released models become available without needing to log out and log back in; failures are silent and never block startup, and custom `--config` sessions keep their previous behavior * Shell: Show the provider-supplied `display_name` (e.g. `k2.6-code-preview`) for managed models across the welcome panel, prompt status bar, `/model` picker, and `/model` switch confirmation messages; when the backend does not return one, the CLI falls back to the internal model ID as before ## 1.36.0 (2026-04-17) * Anthropic: Fix Claude Opus 4.7 returning `invalid_request_error` — Opus 4.7 (which rejects the legacy `{type: "enabled", budget_tokens: N}` thinking config) now correctly uses adaptive thinking, and the client explicitly sets `display: "summarized"` so thinking content still streams back (Opus 4.7 silently changed the default to `"omitted"`); Bedrock/Vertex name variants (e.g., `aws/claude-opus-4-7`, `anthropic.claude-opus-4-7-v1:0`) and `claude-mythos-preview` are also recognised, and future Claude versions ≥ 4.6 are detected automatically via version extrapolation instead of hard-coded substring matching * Web: Fix markdown rendering spacing in the web UI — restore proper vertical spacing between paragraphs, lists, code blocks, blockquotes, and headings instead of collapsing all margins to zero * Shell: Fix missing loading indicator during active turns — the moon spinner now shows as a fallback whenever the model is working but no other indicator is visible, covering gaps after tool calls finish, between turn start and first step, and when an empty thinking block arrives from the provider * Core: Increase default `max_steps_per_turn` from 100 to 500 to allow longer uninterrupted agent runs out of the box * Web: Fix unresponsive copy, download, and preview buttons on rendered code blocks ## 1.35.0 (2026-04-15) * Shell: Flip `show_thinking_stream` default to `true` so fresh installs see the streaming reasoning preview out of the box; set it to `false` in your config to keep the compact 1.32 indicator * Web: Prevent stream watchdog from reconnecting during pending approval or question — the 45-second inactivity watchdog no longer triggers a reconnect while the user is actively handling an approval request or answering a question, preventing interrupted interactions * Web: Fix session recovery after stream errors — when a session process exits or hits a read-loop error, stale in-flight prompt IDs are now cleared before broadcasting the error, allowing the frontend to send new messages instead of getting "Session is busy"; the activity status indicator also surfaces the actual error message from the stream * Core: Fix Wire server prompt handler leaving sessions stuck busy on uncaught exceptions — SSL errors, connection errors, and other unexpected failures are now caught by a fallback handler and returned as `INTERNAL_ERROR`, allowing the session to recover instead of hanging indefinitely ## 1.34.0 (2026-04-14) * Core: Fix CLI crash on `TaskStop` — stopping a stuck background agent no longer prints `Unhandled exception in event loop / Exception None` and freezes the terminal; the cancelled task is now kept in the manager's live-tasks dict until its runner finishes cleaning up, preventing Python's GC from reaping the still-pending task * Shell: Fix inline diff highlights misaligned on lines containing tabs — raw-code diff offsets are now mapped to rendered positions via expandtabs column tracking so highlight spans land correctly after tab expansion * Shell: Add `show_thinking_stream` config option to opt back into the legacy streaming reasoning preview — when set to `true`, the live area shows the classic `Thinking...` spinner above a 6-line scrolling preview of the raw reasoning text and the full reasoning markdown is committed to history when the block ends; defaults to `false` to keep the compact 1.32 indicator ## 1.33.0 (2026-04-13) * Shell: Unify managed model display as "Kimi for Code" and drop hardcoded `kimi-k2.5` version references from the welcome screen and `/login` tip ## 1.32.0 (2026-04-13) * Core: Truncate MCP tool output to 100K characters to prevent context overflow — all content types (text and inline media such as image/audio/video data URLs) share a single character budget; tools like Playwright that return full DOMs (500KB+) or large base64 screenshots are now capped with a truncation notice; oversized media parts are dropped; unsupported MCP content types are gracefully handled instead of crashing the turn * CLI: Fix PyInstaller binary missing lazy CLI subcommands — `kimi info`, `kimi export`, `kimi mcp`, `kimi plugin`, `kimi vis`, and `kimi web` now work correctly in the standalone binary distribution * Shell: Streamline the thinking indicator into a compact single-line layout — shows a `Thinking` label with animated dots, elapsed time, token count, and a live tokens/second pulse; finalises with a `Thought for Xs · N tokens` trace in history ## 1.31.0 (2026-04-10) * Core: Cap `list_directory` output as a depth-limited tree to prevent token-limit blowup in large directories — replaces the unbounded flat listing with a 2-level tree (root: 30 entries, child: 10 per subdirectory), dirs-first alphabetical sorting, and `"... and N more"` truncation hints so the model knows to explore further (fixes #1809) * Shell: Add blocking update gate on interactive shell startup — when a newer version is detected (from the existing background check cache), a blocking prompt appears before the shell loads, offering `[Enter]` to upgrade immediately, `[q]` to continue and be reminded next time, or `[s]` to skip reminders for that version; respects the `KIMI_CLI_NO_AUTO_UPDATE` environment variable; replaces the previous repeating toast notification for available updates * Auth: Harden OAuth token refresh to prevent unnecessary re-login — 401 errors now trigger automatic token refresh and retry instead of forcing `/login`; multiple simultaneous CLI instances coordinate refresh via a cross-process file lock to avoid race conditions; token persistence uses atomic writes with `fsync` to prevent corruption; adds dynamic refresh threshold, 5xx retry during token refresh, and proper token revocation cleanup * Core: Fix agent loop silently stopping when model response contains only thinking content — detect think-only responses (reasoning content with no text or tool calls) as an incomplete response error and retry automatically * Core: Fix crash on streaming mid-flight network disconnection — when the OpenAI SDK raises a base `APIError` (instead of `APIConnectionError`) during long-running streams, the error is now correctly classified as retryable, enabling automatic retry and connection recovery instead of an unrecoverable crash * Shell: Exclude empty current session from `/sessions` picker — completely empty sessions (no conversation history and no custom title) are no longer shown in the session list; sessions with a custom title are still displayed * Shell: Fix slash command completion Enter key behavior — accepting a completion now submits in a single Enter press; auto-submit is limited to slash command completions only; file mention completions (`@`) accept without submitting so the user can continue editing; re-completion after accepting is suppressed to prevent stale completion state * Shell: Add directory scope toggle to `/sessions` picker — press `Ctrl+A` to switch between showing sessions for the current working directory only or across all known directories; uses a new full-screen session picker UI with header scope indicator and footer hint bar * Shell: Add `/btw` side question command — ask a quick question during streaming without interrupting the main conversation; uses the same system prompt and tool definitions for prompt cache alignment; responses display in a scrollable modal panel with streaming support * Shell: Redesign bottom dynamic area — split the monolithic `visualize.py` (1865 lines) into a modular package (`visualize/`) with dedicated modules for input routing, interactive prompts, approval/question panels, and btw modal; unify input semantics with `classify_input()` for consistent command routing * Shell: Add queue and steer dual-channel input during streaming — Enter queues messages for delivery after the current turn; Ctrl+S injects messages immediately into the running turn's context; queued messages display in the prompt area with count indicator and can be recalled with ↑ * Shell: Add `BtwBegin`/`BtwEnd` wire events for cross-client side question support * Shell: Improve elapsed time formatting in spinners — durations over 60 seconds now display as `"1m 23s"` instead of `"83s"`; sub-second durations show `"<1s"` * Shell: Fix Rich markup injection in btw panel — user questions containing `[`/`]` characters are now escaped to prevent broken rendering or style injection in spinner text and panel titles * Core: Improve error diagnostics — enrich internal logging coverage, include relevant log files and system manifest in `kimi export` archives, and surface actionable error messages for common failures (auth, network, timeout, quota) * Shell: Gracefully exit with crash report when working directory becomes inaccessible during session — detects CWD loss (external drive unplugged, directory deleted, or filesystem unmounted) and prints a session recovery panel with session ID and work directory before exiting cleanly * Shell: Use `git ls-files` for `@` file mention discovery — file completer now queries `git ls-files --recurse-submodules` with a 5-second timeout as the primary discovery mechanism, falling back to `os.walk` for non-git repositories; this fixes large repositories (e.g., apache/superset with 65k+ files) where the 1000-file limit caused late-alphabetical directories to be unreachable (fixes #1375) * Core: Add shared `file_filter` module — unifies file mention logic between shell and web UIs via `src/kimi_cli/utils/file_filter.py`, providing consistent path filtering, ignored directory exclusion, and git-aware file discovery * Shell: Prevent path traversal in file mention scope parameter — the `scope` parameter in file completer requests is now validated to prevent directory traversal attacks * Web: Restore unfiltered directory listing in file browser API — file browser endpoint no longer applies git-aware filtering, ensuring all files are visible in the web UI file picker * Todo: Refactor SetTodoList to persist state and prevent tool call storms — todos are now persisted to session state (root agent) and independent state files (sub-agents); adds query mode (omit `todos` to read current state) and clear mode (pass `[]`); includes anti-storm guidance in tool description to prevent repeated calls without progress (fixes #1710) * ReadFile: Add total line count to every read response and support negative `line_offset` for tail mode — the tool now reports `Total lines in file: N.` in its message so the model can plan subsequent reads; negative `line_offset` (e.g. `-100`) reads the last N lines using a sliding window, useful for viewing recent log output without shell commands; the absolute value is capped at 1000 (MAX\_LINES) * Shell: Fix black background on inline code and code blocks in Markdown rendering — `NEUTRAL_MARKDOWN_THEME` now overrides all Rich default `markdown.*` styles to `"none"`, preventing Rich's built-in `"cyan on black"` from leaking through on non-black terminals ## 1.30.0 (2026-04-02) * Shell: Refine idle background completion auto-trigger — resumed shell sessions no longer auto-start a foreground turn from stale pending background notifications before the user sends a message, and fresh background completions now wait briefly while the user is actively typing to avoid stealing the prompt or breaking CJK IME composition * Core: Fix interrupted foreground turns leaving unbalanced wire events — `TurnEnd` is now emitted even when a turn exits via cancellation or step interruption, preventing dirty session wire logs from accumulating across resume cycles * Core: Improve session startup resilience — `--continue`/`--resume` now tolerate malformed `context.jsonl` records and corrupted subagent, background-task, or notification artifacts; the CLI skips invalid persisted state where possible instead of failing to restore the session * CLI: Improve `kimi export` session export UX — `kimi export` now previews the previous session for the current working directory and asks for confirmation, showing the session ID, title, and last user-message time; adds `--yes` to skip confirmation; also fixes explicit session-ID invocations where `--output` after the argument was incorrectly parsed as a subcommand * Grep: Add `include_ignored` parameter to search files excluded by `.gitignore` — when set to `true`, ripgrep's `--no-ignore` flag is enabled, allowing searches in gitignored artifacts such as build outputs or `node_modules`; sensitive files (like `.env`) remain filtered by the sensitive-file protection layer; defaults to `false` to preserve existing behavior * Core: Add sensitive file protection to Grep and Read tools — `.env`, SSH private keys (`id_rsa`, `id_ed25519`, `id_ecdsa`), and cloud credentials (`.aws/credentials`, `.gcp/credentials`) are now detected and blocked; Grep filters them from results with a warning, Read rejects them outright; `.env.example`/`.env.sample`/`.env.template` are exempted * Core: Fix parallel foreground subagent approval requests hanging the session — in interactive shell mode, `_set_active_approval_sink` no longer flushes pending approval requests to the live view sink (which cannot render approval modals); requests stay in the pending queue for the prompt modal path; also adds a 300-second timeout to `wait_for_response` so that any unresolved approval request eventually raises `ApprovalCancelledError` instead of hanging forever * CLI: Add `--session`/`--resume` (`-S`/`-r`) flag to resume sessions — without an argument opens an interactive session picker (shell UI only); with a session ID resumes that specific session; replaces the reverted `--pick-session`/`--list-sessions` design with a unified optional-value flag * CLI: Add CJK-safe `shorten()` utility — replaces all `textwrap.shorten` calls so that CJK text without spaces is truncated gracefully instead of collapsing to just the placeholder * Core: Fix skills in brand directories (e.g. `~/.kimi/skills/`) silently disappearing when a generic directory (`~/.config/agents/skills/`) exists but is empty — skill directory discovery now searches brand and generic directory groups independently and merges both results, instead of stopping at the first existing directory across all candidates * Core: Add `merge_all_available_skills` config option — when enabled, skills from all existing brand directories (`~/.kimi/skills/`, `~/.claude/skills/`, `~/.codex/skills/`) are loaded and merged instead of using only the first one found; same-name skills follow priority order kimi > claude > codex; disabled by default * CLI: Add `--plan` flag and `default_plan_mode` config option — start new sessions in plan mode via `kimi --plan` or by setting `default_plan_mode = true` in `~/.kimi/config.toml`; resumed sessions preserve their existing plan mode state * Shell: Add `/undo` and `/fork` commands for session forking — `/undo` lets you pick a previous turn and fork a new session with the selected message pre-filled for re-editing; `/fork` duplicates the entire session history into a new session; the original session is always preserved * CLI: Add `-r` as a short alias for `--session` and print a resume hint (`kimi -r `) whenever a session exits — covers normal exit, Ctrl-C, `/undo`, `/fork`, and `/sessions` switch so users can always find their way back * Core: Fix `custom_headers` not being passed to non-Kimi providers — OpenAI, Anthropic, Google GenAI, and Vertex AI providers now correctly forward custom headers configured in `providers.*.custom_headers` ## 1.29.0 (2026-04-01) * Core: Support hierarchical `AGENTS.md` loading — the CLI now discovers and merges `AGENTS.md` files from the git project root down to the working directory, including `.kimi/AGENTS.md` at each level; deeper files take priority under a 32 KiB budget cap, ensuring the most specific instructions are never truncated * Core: Fix empty sessions lingering on disk after exit — sessions created but never used are now cleaned up on all exit paths (failure exit, session switch, unexpected errors), not just on successful exit * Shell: Add `KIMI_CLI_PASTE_CHAR_THRESHOLD` and `KIMI_CLI_PASTE_LINE_THRESHOLD` environment variables to control when pasted text is folded into a placeholder — lowering these thresholds works around CJK input method breakage after multiline paste on some terminals (e.g., XShell over SSH) * Shell: Fix diff panel rendering corruption on terminals without truecolor support (e.g. Xshell) — `render_to_ansi` no longer hardcodes 24-bit color; Rich now auto-detects terminal capability via `COLORTERM`/`TERM` environment variables * Web: Fix white screen after CLI upgrade caused by browser caching stale `index.html` — the server now returns `Cache-Control: no-cache` for HTML and `immutable` for hashed assets, preventing 404s on renamed chunks * Core: Fix file write converting LF to CRLF on Windows — `writetext` now opens files with `newline=""` to prevent Python's universal newline translation from silently converting `\n` to `\r\n` * Core: Support `socks://` proxy scheme — proxy tools like V2RayN set `ALL_PROXY=socks://...` which httpx/aiohttp don't recognise; the CLI now normalises `socks://` to `socks5://` at startup so all HTTP clients and subprocesses work correctly behind a SOCKS proxy * Shell: Add `/title` (alias `/rename`) command to manually set session titles — titles are now stored in `state.json` alongside other session state; legacy `metadata.json` is automatically migrated on first load * Shell: Fix garbled pager output when `MANPAGER` is set (e.g. `bat`) — the console pager now ignores `MANPAGER` and delegates to `pydoc.pager()`, preserving `PAGER` and all platform-specific fallbacks * Explore: Enhance explore agent with specialist role, thoroughness levels, and automatic environment context — explore agents now gather repository environment information at launch to improve investigation quality; the main agent is guided to prefer explore for codebase research and plan mode encourages explore-first investigation * Shell: Fix tool call display showing raw OSC 8 escape bytes (e.g. `8;id=391551;https://…`) instead of clean text — hyperlink sequences are now wrapped as zero-width escapes for prompt\_toolkit compatibility, preserving clickable links in supported terminals * Core: Add OS and shell information to the system prompt — the model now knows which platform it is running on and receives a Windows-specific instruction to prefer built-in tools over Shell commands, preventing Linux command errors in PowerShell * Shell: Fix `command` parameter description saying "bash command" regardless of platform — the description is now platform-neutral * Web: Fix auto-title overwriting manual session rename — when a user renames a session through the web UI, the new title is now preserved and no longer replaced by the auto-generated title ## 1.28.0 (2026-03-30) * Core: Fix file write/replace tools freezing the event loop — diff computation (`build_diff_blocks`) is now offloaded to a thread via `asyncio.to_thread`, preventing the UI from hanging when editing large files * Shell: Fix `_watch_root_wire_hub` silently dying on handler exceptions — the watcher now catches and logs exceptions (matching the pattern in `wire/server.py`) and handles `QueueShutDown` gracefully, preventing approval flow from silently breaking mid-session * Core: Skip O(n²) diff computation for huge files (>10 000 lines) — files above the threshold now show a summary block instead of computing a full diff, and unchanged files short-circuit immediately * Wire: Add `is_summary` field to `DiffDisplayBlock` (Wire 1.8) — marks diff blocks that contain a line-count summary instead of actual diff content, allowing clients to render them appropriately * Web: Render large-file diff summaries — when a diff block is marked `is_summary`, the web UI shows a compact "File too large for inline diff" notice with line counts instead of attempting to compute a diff * Auth: Fix OAuth users getting "incorrect API KEY" when running skills or after idle — 401 errors now show a clear "please /login" message instead of the raw API error; the ACP layer correctly triggers re-login flow for VS Code extension users * Web: Fix session title generation always failing for OAuth users — the title generator now uses OAuth tokens and refreshes them before calling the model * Core: Add timeout protection for Agent tool and HTTP requests — all `aiohttp` sessions now default to 120 s total / 60 s read timeout; the Agent tool gains an optional `timeout` parameter (foreground default 10 min, background default 15 min); background agent tasks are marked `timed_out` on expiry with proper notification semantics * Grep: Fix tool hanging and becoming uninterruptible — replaced blocking `ripgrepy.run()` with async subprocess execution; the tool now responds to Ctrl-C immediately and has a 20-second timeout with partial result return * Grep: Add token efficiency improvements — default `head_limit` of 250 with `offset` pagination, `--hidden` search with VCS directory exclusion, `files_with_matches` sorted by modification time, relative path output, and `--max-columns 500` for non-content modes * Grep: `line_number` (`-n`) now defaults to `true` in content mode — line numbers are included by default so the model can reference precise code locations * Grep: `count_matches` mode now includes a summary in the message — e.g. "Found 30 total occurrences across 10 files." * ACP: Fix `ValueError: list.index(x): x not in list` crash when ACP is launched via `kimi-code` or `kimi-cli` entry-points (e.g. JetBrains AI Assistant) * Core: Fix OpenAI-compatible APIs (e.g. One API) returning 400 errors in multi-turn conversations when the server returns `reasoning_content` by default — `reasoning_effort` is now auto-set to `"medium"` when history contains thinking content and `reasoning_key` is configured * Shell: Add `/theme` command and dark/light theme support — users with light terminal backgrounds can now switch to a light color palette via `/theme light` or `theme = "light"` in `config.toml`; diff highlights, task browser, prompt UI, and MCP status colors all adapt to the selected theme * Core: Fix context overflow before compaction — tool result tokens are now estimated and included in the auto-compaction trigger check, preventing "exceeded model token limit" errors when large tool outputs push the context beyond the model limit between API calls * Core: Add hooks system (Beta) — configure `[[hooks]]` in `config.toml` to run custom shell commands at 13 lifecycle events including `PreToolUse`, `PostToolUse`, `SessionStart`, `Stop`, etc.; supports regex matching, timeout handling, and blocking operations via exit code 2 * Shell: Add `/hooks` command — list all configured hooks with event counts * Wire: Add `HookTriggered` and `HookResolved` event types (Wire 1.7) — notify clients when hooks start and finish executing, including event type, target, action (allow/block), and duration * Wire: Add `HookRequest` and `HookResponse` message types — allow wire clients to subscribe to hook events and provide their own handling logic with allow/block decisions * CLI: `--skills-dir` now supports multiple directories and overrides default discovery — when specified, the directories replace user/project skills discovery (repeatable flag) * Shell: Fix notification messages leaking into session replay and export — background task notification tags (``, ``) are now filtered out when resuming a session (`/sessions`) and when exporting (`/export`) or importing (`/import`) conversation history * Web: The "Open" button in the workspace header now remembers the last-used application — clicking "Open" directly opens with the previous choice, while the dropdown arrow lets you pick a different app * Web: Fix archived sessions count badge showing only the loaded page size — the badge now displays "100+" when more archived sessions exist beyond the first page * Shell: Fix pasted text placeholders not expanded in modal answers — clipboard content pasted into approval or question panels is now correctly interpolated before being sent to the model * Vis: Add `--network / -n` flag — launch the visualizer on all network interfaces with auto-detected LAN IP display, matching `kimi web` behavior * Vis: Add `/vis` slash command — switch from the interactive shell to the tracing visualizer in one step, mirroring the existing `/web` command * Vis: Improve session list performance — async backend scanning, request concurrency limiting, and infinite-scroll pagination prevent browser freezes on large session stores * Vis: Add 7 missing wire event types — `SteerInput`, `MCPLoadingBegin/End`, `Notification`, `PlanDisplay`, `ToolCallRequest`, and `QuestionRequest` now display with proper colors and summaries * Vis: Show token and cache details in StatusUpdate — each status update now displays context token count, max tokens, input token breakdown with cache hit rate, and MCP connection status * Vis: Show structured tool call summaries — `ReadFile`, `Shell`, `Glob`, `Grep`, `Agent`, and other tool calls display file paths, commands, or patterns inline instead of just the function name * Vis: Add System Prompt card in Context Messages — the `_system_prompt` entry is rendered as a dedicated blue card showing estimated token count and expandable full content * Vis: Show cache hit rate in session header — the stats bar now displays overall cache efficiency (e.g., `89% cache`) alongside token counts * Vis: Highlight slow operations — time deltas exceeding 10 s appear in amber and those exceeding 60 s in red, making performance bottlenecks immediately visible * Vis: Prefer human-readable `message` field in ToolResult summaries — results now show descriptive text like "Command executed successfully" instead of raw output * Vis: Show approval rejection feedback — `ApprovalResponse` summaries include the user's correction text when a tool call is rejected ## 1.27.0 (2026-03-28) * Shell: Add `/feedback` command — submit feedback directly from the CLI session; the command falls back to opening GitHub Issues on network errors or timeouts * Shell: Redesign diff rendering for tool results — file diffs now display with line numbers, background colors (green/red), syntax highlighting, and inline word-level change markers; approval previews show only changed lines for a compact view; Ctrl-E pager uses the same unified style * Shell: Update syntax highlighting theme — replace the magenta-heavy color scheme with a more balanced palette mapped to ANSI colors for terminal compatibility; improved color diversity and readability across dark and light terminal backgrounds * Shell: Fix approval panel not visible when multiple subagents are running — approval and question panels are now rendered at the top of the live view, ensuring they remain visible even when tool-call output exceeds the terminal height * CLI: Fix `--print` mode returning exit code 0 on errors — print mode now exits with code 1 for permanent failures (auth errors, invalid config, etc.) and code 75 for retryable failures (429 rate limit, 5xx server errors, connection timeouts), enabling CI/eval runners to detect failures and decide whether to retry * Plan: Display plan content inline in the chat instead of hiding behind a pager — plans are now rendered as a bordered panel directly in the conversation history, with the plan file path shown for reference * Plan: Add "Reject and Exit" option to plan approval — users can now reject a plan and exit plan mode in one step, in addition to the existing Approve, Revise, and Reject options * Wire: Add `PlanDisplay` event type (Wire 1.7) — carries plan content and file path for inline rendering by clients * Shell: Stream markdown output incrementally — completed markdown blocks (paragraphs, lists, code fences, tables) are now rendered and printed to the terminal as they arrive during streaming, instead of being buffered until the turn ends * Shell: Show elapsed time and estimated token count on thinking/composing spinners — the spinner now displays `Thinking... 5s · 312 tokens` with a live-updating counter during generation * Shell: Add scrolling preview for thinking content — the last 6 lines of the model's thinking process are shown in real time as a grey italic preview beneath the spinner * Shell: Reduce prompt input area reserved space from 10 to 6 lines * Glob: Allow `Glob` tool to access skills directories — the tool can now search within discovered skill roots in addition to the workspace * Glob: Expand `~` in directory path before validation — the Glob tool now resolves the tilde to the user's home directory before checking path validity ## 1.26.0 (2026-03-25) * Kosong: Fix Google GenAI provider sending `id` in `FunctionCall`/`FunctionResponse` parts — Gemini API returns HTTP 400 when `id` is included; remove the field from wire format while keeping internal `tool_call_id` tracking unchanged * Core: Fix MCP server stderr pollution — stderr redirection is now installed before MCP servers start, so subprocess logs (e.g., OAuth debug output from `mcp-remote`) are captured into the log file instead of being printed to the terminal * Shell: Fix subprocess hang on interactive prompts — the `Shell` tool now closes stdin immediately and sets `GIT_TERMINAL_PROMPT=0` so commands that require credentials (e.g. `git push` over HTTPS) fail fast instead of blocking until timeout * Core: Fix JSON parsing error when LLM tool call arguments contain unescaped control characters — use `json.loads(strict=False)` across all LLM output parsing paths to prevent tool execution failure and session corruption * Shell: Auto-trigger agent when background tasks complete while idle — the shell now detects when a background bash command or agent task finishes and automatically starts a new agent turn to process the results, instead of waiting for the user to type something * Core: Fix `QuestionRequest` hanging in print mode — `AskUserQuestion`, `EnterPlanMode`, and `ExitPlanMode` now auto-resolve when running in non-interactive (yolo) mode, preventing indefinite tool call hangs in `--print` sessions * Core: Fix background agent task output not visible until completion — `/task` browser and `TaskOutput` tool now show real-time output while background agent tasks are running, by tee-writing to the task log during execution instead of copying on completion * Core: Strengthen system prompt to encourage tool use for coding tasks — the agent now defaults to taking action with tools instead of outputting code as plain text * Core: Retry `httpx.ProtocolError` and `504 Gateway Timeout` during generation — streaming protocol disconnects and transient 504 responses now follow the existing retry path instead of aborting the turn immediately on unstable networks * Kosong: Fix `httpx.ReadTimeout` leaking through Anthropic provider during streaming — the exception now correctly converts to `APITimeoutError`, enabling retry logic that was previously bypassed ## 1.25.0 (2026-03-23) * Core: Add plugin system (Skills + Tools) — plugins extend Kimi Code CLI with custom tools packaged as `plugin.json`; tools are commands that run in isolated subprocesses and return their stdout to the agent; plugins support automatic credential injection via `inject` configuration * Core: Support multi-plugin repositories — `kimi plugin install` accepts git URLs with subpath to install a specific plugin from a monorepo (e.g., `https://github.com/org/repo.git/plugins/my-plugin`); when no subpath is provided and no root `plugin.json` exists, the CLI lists available plugins in immediate subdirectories * Core: Unify plugin credential injection — plugins can declare `inject` fields in `plugin.json` to receive `api_key` and `base_url` from the host's configured LLM provider; works with both OAuth-managed tokens and static API keys * Core: Add `Agent` tool for subagent delegation — the agent can now spawn persistent subagent instances with three built-in types (`coder`, `explore`, `plan`) to handle focused subtasks; each instance maintains its own context history within the session and can run in foreground or background with automatic result summarization * Core: Unified approval runtime — approval requests from both foreground tool calls and background subagents are now coordinated through a single runtime and surfaced through the root UI channel; rejection responses can include feedback text to guide the model's next attempt * Shell: Add interactive approval request panel — a new inline panel displays tool call details (diffs, shell commands) with options to approve once, approve for session, reject, or reject with written feedback to instruct the model on what to do instead * Wire: Bump protocol version to 1.6 — `SubagentEvent` now includes `agent_id`, `subagent_type`, and `parent_tool_call_id` fields; `ApprovalRequest` includes source metadata (`source_kind`, `source_id`); `ApprovalResponse` supports a `feedback` field * Vis: Add agents panel — new "Agents" tab in `kimi vis` to inspect subagent instances, view their events, and filter the wire timeline by agent scope * Core: Change `TaskOutput` `block` parameter default from `true` to `false` — `TaskOutput` now returns a non-blocking status/output snapshot by default; set `block=true` only when you intentionally want to wait for task completion * Shell: Show the current working directory, git branch, dirty state, and ahead/behind sync status directly in the prompt toolbar * Shell: Surface active background bash task counts in the toolbar, rotate shortcut tips on a timer, and gracefully truncate the toolbar on narrow terminals to avoid overflow * Web: Fix tool execution status synchronization on cancel and approval — tools now correctly transition to `output-denied` state when generation is stopped, and show the loading spinner (instead of checkmark) while executing after approval * Web: Dismiss stale approval and question dialogs on session replay — when replaying a session or when the backend reports idle/stopped/error status, any pending approval/question dialogs are now properly dismissed to prevent orphaned interactive elements * Web: Enable inline math formula rendering — single-dollar inline math (`$...$`) is now supported in addition to block math (`$$...$$`) * Web: Improve Switch toggle proportions and alignment — the toggle track is now larger (36×20) with a consistent 16px thumb and smoother 16px travel animation * Web: Show subagent type labels in activity panels — subagent activities now display their type (e.g. "Coder agent working") instead of the generic "Agent" label * Web: Add feedback mode to approval dialog — press `4` to reject with written feedback text that guides the model's next attempt; approval requests from subagents show a source label and preview content (diffs, commands) * Web: Visually distinguish sub-agent origin tool calls — tool messages originating from a subagent are rendered with a left border and a source type label for clearer attribution ## 1.24.0 (2026-03-18) * Shell: Increase pasted text placeholder thresholds to 1000 characters or 15 lines (previously 300 characters or 3 lines), making voice/typeless workflows less disruptive * Core: Plan mode now supports multiple selectable approach options — when the agent's plan contains distinct alternative paths, `ExitPlanMode` can present 2–3 labeled choices for the user to pick which approach to execute; the chosen option is returned to the agent as the selected approach * Core: Persist plan session ID and file path across process restarts — the plan session identifier and file slug are saved to `SessionState`, so restarting Kimi Code mid-plan resumes the same plan file in `~/.kimi/plans/` instead of creating a new one * Core: Plan mode now supports incremental plan edits — the agent can use `StrReplaceFile` to surgically update sections of the plan file instead of rewriting the entire file with `WriteFile`, and non-plan file edits are now hard-blocked rather than requiring approval * Core: Defer MCP startup and surface loading progress — MCP servers now initialize asynchronously after the shell UI starts, with live progress indicators showing connection status; Shell displays connecting and ready states in the status area, Web shows server connection status * Core: Optimize lightweight startup paths — implement lazy-loading for CLI subcommands and version metadata, significantly reducing startup time for common commands like `--version` and `--help` * Build: Fix Nix `FileCollisionError` for `bin/kimi` — remove duplicate entry point from `kimi-code` package so `kimi-cli` owns `bin/kimi` exclusively * Shell: Preserve unsubmitted input across agent turns — text typed in the prompt while the agent is running is no longer lost when the turn ends; the user can press Enter to submit the draft as the next message * Shell: Fix Ctrl-C and Ctrl-D not working correctly after an agent run completes — keyboard interrupts and EOF were silently swallowed instead of showing the tip or exiting the shell ## 1.23.0 (2026-03-17) * Shell: Add background bash — the `Shell` tool now accepts `run_in_background=true` to launch long-running commands (builds, tests, servers) as background tasks, freeing the agent to continue working; new `TaskList`, `TaskOutput`, and `TaskStop` tools manage task lifecycle, and the system automatically notifies the agent when tasks reach a terminal state * Shell: Add `/task` slash command with interactive task browser — a three-column TUI to view, monitor, and manage background tasks with real-time refresh, output preview, and keyboard-driven stopping * Web: Fix global config not refreshing on other tabs when model is changed — when the model is changed in one tab, other tabs now detect the config update and automatically refresh their global config ## 1.22.0 (2026-03-13) * Shell: Collapse long pasted text into `[Pasted text #n]` placeholders — text pasted via `Ctrl-V` or bracketed paste that exceeds 300 characters or 3 lines is displayed as a compact placeholder token in the prompt buffer while the full content is sent to the model; the external editor (`Ctrl-O`) expands placeholders for editing and re-folds them on save * Shell: Cache pasted images as attachment placeholders — images pasted from the clipboard are stored on disk and shown as `[image:…]` tokens in the prompt, keeping the input buffer readable * Shell: Fix UTF-16 surrogate characters in pasted text causing serialization errors — lone surrogates from Windows clipboard data are now sanitized before storage, preventing `UnicodeEncodeError` in history writes and JSON serialization * Shell: Redesign slash command completion menu — replace the default completion popup with a full-width custom menu that shows command names and multi-line descriptions, with highlight and scroll support * Shell: Fix cancelled shell commands not properly terminating child processes — when a running command is cancelled, the subprocess is now explicitly killed to prevent orphaned processes ## 1.21.0 (2026-03-12) * Shell: Add inline running prompt with steer input — agent output is now rendered inside the prompt area while the model is running, and users can type and send follow-up messages (steers) without waiting for the turn to finish; approval requests and question panels are handled inline with keyboard navigation * Core: Change steer injection from synthetic tool calls to regular user messages — steer content is now appended as a standard user message instead of a fake `_steer` tool-call/tool-result pair, improving compatibility with context serialization and visualization * Wire: Add `SteerInput` event — a new Wire protocol event emitted when the user sends a follow-up steer message during a running turn * Shell: Echo user input after submission in agent mode — the prompt symbol and entered text are printed back to the terminal for a clearer conversation transcript * Shell: Improve session replay with steer inputs — replay now correctly reconstructs and displays steer messages alongside regular turns, and filters out internal system-reminder messages * Shell: Fix upgrade command in toast notifications — the upgrade command text is now sourced from a single `UPGRADE_COMMAND` constant for consistency * Core: Persist system prompt in `context.jsonl` — the system prompt is now written as the first record of the context file and frozen per session, so visualization tools can read the full conversation context and session restores reuse the original prompt instead of regenerating it * Vis: Add session directory shortcuts in `kimi vis` — open the current session folder directly from the session page, copy the raw session directory path with `Copy DIR`, and support opening directories on both macOS and Windows * Shell: Improve API key login UX — show a spinner during key verification, display a helpful hint when a 401 error suggests the wrong platform was selected, show a setup summary on success, and default thinking mode to "on" ## 1.20.0 (2026-03-11) * Web: Add plan mode toggle in web UI — switch control in the input toolbar with a dashed blue border on the composer when plan mode is active, and support setting plan mode via the `set_plan_mode` Wire protocol method * Core: Persist plan mode state across session restarts — `plan_mode` is saved to `SessionState` and restored when a session resumes * Core: Fix StatusUpdate not reflecting plan mode changes triggered by tools — send a corrected `StatusUpdate` after `EnterPlanMode`/`ExitPlanMode` tool execution so the client sees the up-to-date state * Core: Fix HTTP header values containing trailing whitespace/newlines on certain Linux systems (e.g. kernel 6.8.0-101) causing connection errors — strip whitespace from ASCII header values before sending * Core: Fix OpenAI Responses provider sending implicit `reasoning.effort=null` which breaks Responses-compatible endpoints that require reasoning — reasoning parameters are now omitted unless explicitly set * Vis: Add session download, import, export and delete — one-click ZIP download from session explorer and detail page, ZIP import into a dedicated `~/.kimi/imported_sessions/` directory with "Imported" filter toggle, `kimi export ` CLI command, and delete support for imported sessions with AlertDialog confirmation * Core: Fix context compaction failing when conversation contains media parts (images, audio, video) — switch from blacklist filtering (exclude `ThinkPart`) to whitelist filtering (only keep `TextPart`) to prevent unsupported content types from being sent to the compaction API * Web: Fix `@` file mention index not refreshing after switching sessions or when workspace files change — reset index on session switch, auto-refresh after 30s staleness, and support path-prefix search beyond the 500-file limit ## 1.19.0 (2026-03-10) * Core: Add plan mode — the agent can enter a planning phase (`EnterPlanMode`) where only read-only tools (Glob, Grep, ReadFile) are available, write a structured plan to a file, and present it for user approval (`ExitPlanMode`) before executing; toggle manually via `/plan` slash command or `Shift-Tab` keyboard shortcut * Vis: Add `kimi vis` command for launching an interactive visualization dashboard to inspect session traces — includes wire event timeline, context viewer, session explorer, and usage statistics * Web: Fix session stream state management — guard against null reference errors during state resets and preserve slash commands across session switches to avoid a brief empty gap ## 1.18.0 (2026-03-09) * ACP: Support embedded resource content in ACP mode so that Zed's `@` file references correctly include file contents * Core: Use `parameters_json_schema` instead of `parameters` in Google GenAI provider to bypass Pydantic validation that rejects standard JSON Schema metadata fields in MCP tools * Shell: Enhance `Ctrl-V` clipboard paste to support video files in addition to images — video file paths are inserted as text, and a crash when clipboard data is `None` is fixed * Core: Pass session ID as `user_id` metadata to Anthropic API * Web: Preserve slash commands on WebSocket reconnect and add automatic retry logic for session initialization ## 1.17.0 (2026-03-03) * Core: Add `/export` command to export current session context (messages, metadata) to a Markdown file, and `/import` command to import context from a file or another session ID into the current session * Shell: Show token counts (used/total) alongside context usage percentage in the status bar (e.g., `context: 42.0% (4.2k/10.0k)`) * Shell: Rotate keyboard shortcut tips in the toolbar — tips cycle through available shortcuts on each prompt submission to save horizontal space * MCP: Add loading indicators for MCP server connections — Shell displays a "Connecting to MCP servers..." spinner and Web shows a status message while MCP tools are being loaded * Web: Fix scrollable file list overflow in the toolbar changes panel * Core: Add `compaction_trigger_ratio` config option (default `0.85`) to control when auto-compaction triggers — compaction now fires when context usage reaches the configured ratio or when remaining space falls below `reserved_context_size`, whichever comes first * Core: Support custom instructions in `/compact` command (e.g., `/compact keep database discussions`) to guide what the compaction preserves * Web: Add URL action parameters (`?action=create` to open create-session dialog, `?action=create-in-dir&workDir=xxx` to create a session directly) for external integrations, and support Cmd/Ctrl+Click on new-session buttons to open session creation in a new browser tab * Web: Add todo list display in prompt toolbar — shows task progress with expandable panel when the `SetTodoList` tool is active * ACP: Add authentication check for session operations with `AUTH_REQUIRED` error responses for terminal-based login flow ## 1.16.0 (2026-02-27) * Web: Update ASCII logo banner to a new styled design * Core: Add `--add-dir` CLI option and `/add-dir` slash command to expand the workspace scope with additional directories — added directories are accessible to all file tools (read, write, glob, replace), persisted across sessions, and shown in the system prompt * Shell: Add `Ctrl-O` keyboard shortcut to open the current input in an external editor (`$VISUAL`/`$EDITOR`), with auto-detection fallback to VS Code, Vim, Vi, or Nano * Shell: Add `/editor` slash command to configure and switch the default external editor, with interactive selection and persistent config storage * Shell: Add `/new` slash command to create and switch to a new session without restarting Kimi Code CLI * Wire: Auto-hide `AskUserQuestion` tool when the client does not support the `supports_question` capability, preventing the LLM from invoking unsupported interactions * Core: Estimate context token count after compaction so context usage percentage is not reported as 0% * Web: Show context usage percentage with one decimal place for better precision ## 1.15.0 (2026-02-27) * Shell: Simplify input prompt by removing username prefix for a cleaner appearance * Shell: Add horizontal separator line and expanded keyboard shortcut hints to the toolbar * Shell: Add number key shortcuts (1–5) for quick option selection in question and approval panels, with redesigned bordered panel UI and keyboard hints * Shell: Add tab-style navigation for multi-question panels — use Left/Right arrows or Tab to switch between questions, with visual indicators for answered, current, and pending states, and automatic state restoration when revisiting a question * Shell: Allow Space key to submit single-select questions in the question panel * Web: Add tab-style navigation for multi-question dialogs with clickable tab bar, keyboard navigation, and state restoration when revisiting a question * Core: Set process title to "Kimi Code" (visible in `ps` / Activity Monitor / terminal tab title) and label web worker subprocesses as "kimi-code-worker" ## 1.14.0 (2026-02-26) * Shell: Make FetchURL tool's URL parameter a clickable hyperlink in the terminal * Tool: Add `AskUserQuestion` tool for presenting structured questions with predefined options during execution, supporting single-select, multi-select, and custom text input * Wire: Add `QuestionRequest` / `QuestionResponse` message types and capability negotiation for structured question interactions * Shell: Add interactive question panel for `AskUserQuestion` with keyboard-driven option selection * Web: Add `QuestionDialog` component for answering structured questions inline, replacing the prompt composer when a question is pending * Core: Persist session state across sessions — approval decisions (YOLO mode, auto-approved actions) and dynamic subagents are now saved and restored when resuming a session * Core: Use atomic JSON writes for metadata and session state files to prevent data corruption on crash * Wire: Add `steer` request to inject user messages into an active agent turn (protocol version 1.4) * Web: Allow Cmd/Ctrl+Click on FetchURL tool's URL parameter to open the link in a new browser tab, with platform-appropriate tooltip hint ## 1.13.0 (2026-02-24) * Core: Add automatic connection recovery that recreates the HTTP client on connection and timeout errors before retrying, improving resilience against transient network failures ## 1.12.0 (2026-02-11) * Web: Add subagent activity rendering to display subagent steps (thinking, tool calls, text) inside Task tool messages * Web: Add Think tool rendering as a lightweight reasoning-style block * Web: Replace emoji status indicators with Lucide icons for tool states and add category-specific icons for tool names * Web: Enhance Reasoning component with improved thinking labels and status icons * Web: Enhance Todo component with status icons and improved styling * Web: Implement WebSocket reconnection with automatic request resending and stale connection watchdog * Web: Enhance session creation dialog with command value handling * Web: Support tilde (`~`) expansion in session work directory paths * Web: Fix assistant message content overflow clipping * Wire: Fix deadlock when multiple subagents run concurrently by not blocking the UI loop on approval and tool-call requests * Wire: Clean up stale pending requests after agent turn ends * Web: Show placeholder text in prompt input with hints for slash commands and file mentions * Web: Fix Ctrl+C not working in uvicorn web server by restoring default SIGINT handler and terminal state after shell mode exits * Web: Improve session stop handling with proper async cleanup and timeout * ACP: Add protocol version negotiation framework for client-server compatibility * ACP: Add session resume method to restore session state (experimental) ## 1.11.0 (2026-02-10) * Web: Move context usage indicator from workspace header to prompt toolbar with a hover card showing detailed token usage breakdown * Web: Add folder indicator with work directory path to the bottom of the file changes panel * Web: Fix stderr not being restored when switching to web mode, which could suppress web server error output * Web: Fix port availability check by setting SO\_REUSEADDR on the test socket ## 1.10.0 (2026-02-09) * Web: Add copy and fork action buttons to assistant messages for quick content copying and session forking * Web: Add keyboard shortcuts for approval actions — press `1` to approve, `2` to approve for session, `3` to decline * Web: Add message queueing — queue follow-up messages while the AI is processing; queued messages are sent automatically when the response completes * Web: Replace Git diff status bar with unified prompt toolbar showing activity status, message queue, and file changes in collapsible tabs * Web: Load global MCP configuration in web worker so web sessions can use MCP tools * Web: Improve mobile prompt input UX — reduce textarea min-height, add `autoComplete="off"`, and disable focus ring on small screens * Web: Handle models that stream text before thinking by ensuring thinking messages always appear before text in the message list * Web: Show more specific status messages during session connection ("Loading history...", "Starting environment..." instead of generic "Connecting...") * Web: Send error status when session environment initialization fails instead of leaving UI in a waiting state * Web: Auto-reconnect when no session status received within 15 seconds after history replay completes * Web: Use non-blocking file I/O in session streaming to avoid blocking the event loop during history replay ## 1.9.0 (2026-02-06) * Config: Add `default_yolo` config option to enable YOLO (auto-approve) mode by default * Config: Accept both `max_steps_per_turn` and `max_steps_per_run` as aliases for the loop control setting * Wire: Add `replay` request to stream recorded Wire events (protocol version 1.3) * Web: Add session fork feature to branch off a new session from any assistant response * Web: Add session archive feature with auto-archive for sessions older than 15 days * Web: Add multi-select mode for bulk archive, unarchive, and delete operations * Web: Add media preview for tool results (images/videos from ReadMediaFile) with clickable thumbnails * Web: Add shell command and todo list display components for tool outputs * Web: Add activity status indicator showing agent state (processing, waiting for approval, etc.) * Web: Add error fallback UI when images fail to load * Web: Redesign tool input UI with expandable parameters and syntax highlighting for long values * Web: Show compaction indicator when context is being compacted * Web: Improve auto-scroll behavior in chat for smoother following of new content * Web: Update `last_session_id` for work directory when session stream starts * Shell: Remove `Ctrl-/` keyboard shortcut that triggered `/help` command * Rust: Move the Rust implementation to `MoonshotAI/kimi-agent-rs` with independent releases; binary renamed to `kimi-agent` * Core: Preserve session id when reloading configuration so the session resumes correctly * Shell: Fix session replay showing messages that were cleared by `/clear` or `/reset` * Web: Fix approval request states not updating when session is interrupted or cancelled * Web: Fix IME composition issue when selecting slash commands * Web: Fix UI not clearing messages after `/clear`, `/reset`, or `/compact` commands ## 1.8.0 (2026-02-05) * CLI: Fix startup errors (e.g. invalid config files) being silently swallowed instead of displayed ## 1.7.0 (2026-02-05) * Rust: Add `kagent`, the Rust implementation of Kimi agent kernel with wire-mode support (experimental) * Auth: Fix OAuth token refresh conflicts when running multiple sessions simultaneously * Web: Add file mention menu (`@`) to reference uploaded attachments and workspace files with autocomplete * Web: Add slash command menu in chat input with autocomplete, keyboard navigation, and alias support * Web: Prompt to create directory when specified path doesn't exist during session creation * Web: Fix authentication token persistence by switching from sessionStorage to localStorage with 24-hour expiry * Web: Add server-side pagination for session list with virtualized scrolling for better performance * Web: Improve session and work directories loading with smarter caching and invalidation * Web: Fix WebSocket errors during history replay by checking connection state before sending * Web: Git diff status bar now shows untracked files (new files not yet added to git) * Web: Restrict sensitive APIs only in public mode; update origin enforcement logic ## 1.6 (2026-02-03) * Web: Add token-based authentication and access control for network mode (`--network`, `--lan-only`, `--public`) * Web: Add security options: `--auth-token`, `--allowed-origins`, `--restrict-sensitive-apis`, `--dangerously-omit-auth` * Web: Change `--host` option to bind to specific IP address; add automatic network address detection * Web: Fix WebSocket disconnect when creating new sessions * Web: Increase maximum image dimension from 1024 to 4096 pixels * Web: Improve UI responsiveness with enhanced hover effects and better layout handling * Wire: Add `TurnEnd` event to signal the completion of an agent turn (protocol version 1.2) * Core: Fix custom agent prompt files containing `$` causing silent startup failure ## 1.5 (2026-01-30) * Web: Add Git diff status bar showing uncommitted changes in session working directory * Web: Add "Open in" menu for opening files/directories in Terminal, VS Code, Cursor, or other local applications * Web: Add search functionality to filter sessions by title or working directory * Web: Improve session title display with proper overflow handling ## 1.4 (2026-01-30) * Shell: Merge `/login` and `/setup` commands; `/setup` is now an alias for `/login` * Shell: `/usage` now shows remaining quota percentage; add `/status` alias * Config: Add `KIMI_SHARE_DIR` environment variable to customize the share directory path (default: `~/.kimi`) * Web: Add new Web UI for browser-based interaction * CLI: Add `kimi web` subcommand to launch the Web UI server * Auth: Fix encoding error when device name or OS version contains non-ASCII characters * Auth: OAuth credentials are now stored in files instead of keyring; existing tokens are automatically migrated on startup * Auth: Fix authorization failure after the system sleeps or hibernates ## 1.3 (2026-01-28) * Auth: Fix authentication issue during agent turns * Tool: Wrap media content with descriptive tags in `ReadMediaFile` for better path traceability ## 1.2 (2026-01-27) * UI: Show description for `kimi-for-coding` model ## 1.1 (2026-01-27) * LLM: Fix `kimi-for-coding` model's capabilities ## 1.0 (2026-01-27) * Shell: Add `/login` and `/logout` slash commands for login and logout * CLI: Add `kimi login` and `kimi logout` subcommands * Core: Fix subagent approval request handling ## 0.88 (2026-01-26) * MCP: Remove `Mcp-Session-Id` header when connecting to MCP servers to fix compatibility ## 0.87 (2026-01-25) * Shell: Fix Markdown rendering error when HTML blocks appear outside any element * Skills: Add more user-level and project-level skills directory candidates * Core: Improve system prompt guidance for media file generation and processing tasks * Shell: Fix image pasting from clipboard on macOS ## 0.86 (2026-01-24) * Build: Fix binary builds ## 0.85 (2026-01-24) * Shell: Cache pasted images to disk for persistence across sessions * Shell: Deduplicate cached attachments based on content hash * Shell: Fix display of image/audio/video attachments in message history * Tool: Use file path as media identifier in `ReadMediaFile` for better traceability * Tool: Fix some MP4 files not being recognized as videos * Shell: Handle Ctrl-C during slash command execution * Shell: Fix shlex parsing error in shell mode when input contains invalid shell syntax * Shell: Fix stderr output from MCP servers and third-party libraries polluting shell UI * Wire: Graceful shutdown with proper cleanup of pending requests when connection closes or Ctrl-C is received ## 0.84 (2026-01-22) * Build: Add cross-platform standalone binary builds for Windows, macOS (with code signing and notarization), and Linux (x86\_64 and ARM64) * Shell: Fix slash command autocomplete showing suggestions for exact command/alias matches * Tool: Treat SVG files as text instead of images * Flow: Support D2 markdown block strings (`|md` syntax) for multiline node labels in flow skills * Core: Fix possible "event loop is closed" error after running `/reload`, `/setup`, or `/clear` * Core: Fix panic when `/clear` is used in a continued session ## 0.83 (2026-01-21) * Tool: Add `ReadMediaFile` tool for reading image/video files; `ReadFile` now focuses on text files only * Skills: Flow skills now also register as `/skill:` commands (in addition to `/flow:`) ## 0.82 (2026-01-21) * Tool: Allow `WriteFile` and `StrReplaceFile` tools to edit/write files outside the working directory when using absolute paths * Tool: Upload videos to Kimi files API when using Kimi provider, replacing inline data URLs with `ms://` references * Config: Add `reserved_context_size` setting to customize auto-compaction trigger threshold (default: 50000 tokens) ## 0.81 (2026-01-21) * Skills: Add flow skill type with embedded Agent Flow (Mermaid/D2) in SKILL.md, invoked via `/flow:` commands * CLI: Remove `--prompt-flow` option; use flow skills instead * Core: Replace `/begin` command with `/flow:` commands for flow skills ## 0.80 (2026-01-20) * Wire: Add `initialize` method for exchanging client/server info, external tools registration and slash commands advertisement * Wire: Support external tool calls via Wire protocol * Wire: Rename `ApprovalRequestResolved` to `ApprovalResponse` (backwards-compatible) ## 0.79 (2026-01-19) * Skills: Add project-level skills support, discovered from `.agents/skills/` (or `.kimi/skills/`, `.claude/skills/`) * Skills: Unified skills discovery with layered loading (builtin → user → project); user-level skills now prefer `~/.config/agents/skills/` * Shell: Support fuzzy matching for slash command autocomplete * Shell: Enhanced approval request preview with shell command and diff content display, use `Ctrl-E` to expand full content * Wire: Add `ShellDisplayBlock` type for shell command display in approval requests * Shell: Reorder `/help` to show keyboard shortcuts before slash commands * Wire: Return proper JSON-RPC 2.0 error responses for invalid requests ## 0.78 (2026-01-16) * CLI: Add D2 flowchart format support for Prompt Flow (`.d2` extension) ## 0.77 (2026-01-15) * Shell: Fix line breaking in `/help` and `/changelog` fullscreen pager display * Shell: Use `/model` to toggle thinking mode instead of Tab key * Config: Add `default_thinking` config option (need to run `/model` to select thinking mode after upgrade) * LLM: Add `always_thinking` capability for models that always use thinking mode * CLI: Rename `--command`/`-c` to `--prompt`/`-p`, keep `--command`/`-c` as alias, remove `--query`/`-q` * Wire: Fix approval requests not responding properly in Wire mode * CLI: Add `--prompt-flow` option to load a Mermaid flowchart file as a Prompt Flow * Core: Add `/begin` slash command if a Prompt Flow is loaded to start the flow * Core: Replace Ralph Loop with Prompt Flow-based implementation ## 0.76 (2026-01-12) * Tool: Make `ReadFile` tool description reflect model capabilities for image/video support * Tool: Fix TypeScript files (`.ts`, `.tsx`, `.mts`, `.cts`) being misidentified as video files * Shell: Allow slash commands (`/help`, `/exit`, `/version`, `/changelog`, `/feedback`) in shell mode * Shell: Improve `/help` with fullscreen pager, showing slash commands, skills, and keyboard shortcuts * Shell: Improve `/changelog` and `/mcp` display with consistent bullet-style formatting * Shell: Show current model name in the bottom status bar * Shell: Add `Ctrl-/` shortcut to show help ## 0.75 (2026-01-09) * Tool: Improve `ReadFile` tool description * Skills: Add built-in `kimi-cli-help` skill to answer Kimi Code CLI usage and configuration questions ## 0.74 (2026-01-09) * ACP: Allow ACP clients to select and switch models (with thinking variants) * ACP: Add `terminal-auth` authentication method for setup flow * CLI: Deprecate `--acp` option in favor of `kimi acp` subcommand * Tool: Support reading image and video files in `ReadFile` tool ## 0.73 (2026-01-09) * Skills: Add built-in skill-creator skill shipped with the package * Tool: Expand `~` to the home directory in `ReadFile` paths * MCP: Ensure MCP tools finish loading before starting the agent loop * Wire: Fix Wire mode failing to accept valid `cancel` requests * Setup: Allow `/model` to switch between all available models for the selected provider * Lib: Re-export all Wire message types from `kimi_cli.wire.types`, as a replacement of `kimi_cli.wire.message` * Loop: Add `max_ralph_iterations` loop control config to limit extra Ralph iterations * Config: Rename `max_steps_per_run` to `max_steps_per_turn` in loop control config (backward-compatible) * CLI: Add `--max-steps-per-turn`, `--max-retries-per-step` and `--max-ralph-iterations` options to override loop control config * SlashCmd: Make `/yolo` toggle auto-approve mode * UI: Show a YOLO badge in the shell prompt ## 0.72 (2026-01-04) * Python: Fix installation on Python 3.14. ## 0.71 (2026-01-04) * ACP: Route file reads/writes and shell commands through ACP clients for synced edits/output * Shell: Add `/model` slash command to switch default models and reload when using the default config * Skills: Add `/skill:` slash commands to load `SKILL.md` instructions on demand * CLI: Add `kimi info` subcommand for version/protocol details (supports `--json`) * CLI: Add `kimi term` to launch the Toad terminal UI * Python: Bump the default tooling/CI version to 3.14 ## 0.70 (2025-12-31) * CLI: Add `--final-message-only` (and `--quiet` alias) to only output the final assistant message in print UI * LLM: Add `video_in` model capability and support video inputs ## 0.69 (2025-12-29) * Core: Support discovering skills in `~/.kimi/skills` or `~/.claude/skills` * Python: Lower the minimum required Python version to 3.12 * Nix: Add flake packaging; install with `nix profile install .#kimi-cli` or run `nix run .#kimi-cli` * CLI: Add `kimi-cli` script alias for invoking the CLI; can be run via `uvx kimi-cli` * Lib: Move LLM config validation into `create_llm` and return `None` when missing config ## 0.68 (2025-12-24) * CLI: Add `--config` and `--config-file` options to pass in config JSON/TOML * Core: Allow `Config` in addition to `Path` for the `config` parameter of `KimiCLI.create` * Tool: Include diff display blocks in `WriteFile` and `StrReplaceFile` approvals/results * Wire: Add display blocks to approval requests (including diffs) with backward-compatible defaults * ACP: Show file diff previews in tool results and approval prompts * ACP: Connect to MCP servers managed by ACP clients * ACP: Run shell commands in ACP client terminal if supported * Lib: Add `KimiToolset.find` method to find tools by class or name * Lib: Add `ToolResultBuilder.display` method to append display blocks to tool results * MCP: Add `kimi mcp auth` and related subcommands to manage MCP authorization ## 0.67 (2025-12-22) * ACP: Advertise slash commands in single-session ACP mode (`kimi --acp`) * MCP: Add `mcp.client` config section to configure MCP tool call timeout and other future options * Core: Improve default system prompt and `ReadFile` tool * UI: Fix Ctrl-C not working in some rare cases ## 0.66 (2025-12-19) * Lib: Provide `token_usage` and `message_id` in `StatusUpdate` Wire message * Lib: Add `KimiToolset.load_tools` method to load tools with dependency injection * Lib: Add `KimiToolset.load_mcp_tools` method to load MCP tools * Lib: Move `MCPTool` from `kimi_cli.tools.mcp` to `kimi_cli.soul.toolset` * Lib: Add `InvalidToolError`, `MCPConfigError` and `MCPRuntimeError` * Lib: Make the detailed Kimi Code CLI exception classes extend `ValueError` or `RuntimeError` * Lib: Allow passing validated `list[fastmcp.mcp_config.MCPConfig]` as `mcp_configs` for `KimiCLI.create` and `load_agent` * Lib: Fix exception raising for `KimiCLI.create`, `load_agent`, `KimiToolset.load_tools` and `KimiToolset.load_mcp_tools` * LLM: Add provider type `vertexai` to support Vertex AI * LLM: Rename Gemini Developer API provider type from `google_genai` to `gemini` * Config: Migrate config file from JSON to TOML * MCP: Connect to MCP servers in background and parallel to reduce startup time * MCP: Add `mcp-session-id` HTTP header when connecting to MCP servers * Lib: Split slash commands (prev "meta commands") into two groups: Shell-level and KimiSoul-level * Lib: Add `available_slash_commands` property to `Soul` protocol * ACP: Advertise slash commands `/init`, `/compact` and `/yolo` to ACP clients * SlashCmd: Add `/mcp` slash command to display MCP server and tool status ## 0.65 (2025-12-16) * Lib: Support creating named sessions via `Session.create(work_dir, session_id)` * CLI: Automatically create new session when specified session ID is not found * CLI: Delete empty sessions on exit and ignore sessions whose context file is empty when listing * UI: Improve session replaying * Lib: Add `model_config: LLMModel | None` and `provider_config: LLMProvider | None` properties to `LLM` class * MetaCmd: Add `/usage` meta command to show API usage for Kimi Code users ## 0.64 (2025-12-15) * UI: Fix UTF-16 surrogate characters input on Windows * Core: Add `/sessions` meta command to list existing sessions and switch to a selected one * CLI: Add `--session/-S` option to specify session ID to resume * MCP: Add `kimi mcp` subcommand group to manage global MCP config file `~/.kimi/mcp.json` ## 0.63 (2025-12-12) * Tool: Fix `FetchURL` tool incorrect output when fetching via service fails * Tool: Use `bash` instead of `sh` in `Shell` tool for better compatibility * Tool: Fix `Grep` tool unicode decoding error on Windows * ACP: Support ACP session continuation (list/load sessions) with `kimi acp` subcommand * Lib: Add `Session.find` and `Session.list` static methods to find and list sessions * ACP: Update agent plans on the client side when `SetTodoList` tool is called * UI: Prevent normal messages starting with `/` from being treated as meta commands ## 0.62 (2025-12-08) * ACP: Fix tool results (including Shell tool output) not being displayed in ACP clients like Zed * ACP: Fix compatibility with the latest version of Zed IDE (0.215.3) * Tool: Use PowerShell instead of CMD on Windows for better usability * Core: Fix startup crash when there is broken symbolic link in the working directory * Core: Add builtin `okabe` agent file with `SendDMail` tool enabled * CLI: Add `--agent` option to specify builtin agents like `default` and `okabe` * Core: Improve compaction logic to better preserve relevant information ## 0.61 (2025-12-04) * Lib: Fix logging when used as a library * Tool: Harden file path check to protect against shared-prefix escape * LLM: Improve compatibility with some third-party OpenAI Responses and Anthropic API providers ## 0.60 (2025-12-01) * LLM: Fix interleaved thinking for Kimi and OpenAI-compatible providers ## 0.59 (2025-11-28) * Core: Move context file location to `.kimi/sessions/{workdir_md5}/{session_id}/context.jsonl` * Lib: Move `WireMessage` type alias to `kimi_cli.wire.message` * Lib: Add `kimi_cli.wire.message.Request` type alias request messages (which currently only includes `ApprovalRequest`) * Lib: Add `kimi_cli.wire.message.is_event`, `is_request` and `is_wire_message` utility functions to check the type of wire messages * Lib: Add `kimi_cli.wire.serde` module for serialization and deserialization of wire messages * Lib: Change `StatusUpdate` Wire message to not using `kimi_cli.soul.StatusSnapshot` * Core: Record Wire messages to a JSONL file in session directory * Core: Introduce `TurnBegin` Wire message to mark the beginning of each agent turn * UI: Print user input again with a panel in shell mode * Lib: Add `Session.dir` property to get the session directory path * UI: Improve "Approve for session" experience when there are multiple parallel subagents * Wire: Reimplement Wire server mode (which is enabled with `--wire` option) * Lib: Rename `ShellApp` to `Shell`, `PrintApp` to `Print`, `ACPServer` to `ACP` and `WireServer` to `WireOverStdio` for better consistency * Lib: Rename `KimiCLI.run_shell_mode` to `run_shell`, `run_print_mode` to `run_print`, `run_acp_server` to `run_acp`, and `run_wire_server` to `run_wire_stdio` for better consistency * Lib: Add `KimiCLI.run` method to run a turn with given user input and yield Wire messages * Print: Fix stream-json print mode not flushing output properly * LLM: Improve compatibility with some OpenAI and Anthropic API providers * Core: Fix chat provider error after compaction when using Anthropic API ## 0.58 (2025-11-21) * Core: Fix field inheritance of agent spec files when using `extend` * Core: Support using MCP tools in subagents * Tool: Add `CreateSubagent` tool to create subagents dynamically (not enabled in default agent) * Tool: Use MoonshotFetch service in `FetchURL` tool for Kimi Code plan * Tool: Truncate Grep tool output to avoid exceeding token limit ## 0.57 (2025-11-20) * LLM: Fix Google GenAI provider when thinking toggle is not on * UI: Improve approval request wordings * Tool: Remove `PatchFile` tool * Tool: Rename `Bash`/`CMD` tool to `Shell` tool * Tool: Move `Task` tool to `kimi_cli.tools.multiagent` module ## 0.56 (2025-11-19) * LLM: Add support for Google GenAI provider ## 0.55 (2025-11-18) * Lib: Add `kimi_cli.app.enable_logging` function to enable logging when directly using `KimiCLI` class * Core: Fix relative path resolution in agent spec files * Core: Prevent from panic when LLM API connection failed * Tool: Optimize `FetchURL` tool for better content extraction * Tool: Increase MCP tool call timeout to 60 seconds * Tool: Provide better error message in `Glob` tool when pattern is `**` * ACP: Fix thinking content not displayed properly * UI: Minor UI improvements in shell mode ## 0.54 (2025-11-13) * Lib: Move `WireMessage` from `kimi_cli.wire.message` to `kimi_cli.wire` * Print: Fix `stream-json` output format missing the last assistant message * UI: Add warning when API key is overridden by `KIMI_API_KEY` environment variable * UI: Make a bell sound when there's an approval request * Core: Fix context compaction and clearing on Windows ## 0.53 (2025-11-12) * UI: Remove unnecessary trailing spaces in console output * Core: Throw error when there are unsupported message parts * MetaCmd: Add `/yolo` meta command to enable YOLO mode after startup * Tool: Add approval request for MCP tools * Tool: Disable `Think` tool in default agent * CLI: Restore thinking mode from last time when `--thinking` is not specified * CLI: Fix `/reload` not working in binary packed by PyInstaller ## 0.52 (2025-11-10) * CLI: Remove `--ui` option in favor of `--print`, `--acp`, and `--wire` flags (shell is still the default) * CLI: More intuitive session continuation behavior * Core: Add retry for LLM empty responses * Tool: Change `Bash` tool to `CMD` tool on Windows * UI: Fix completion after backspacing * UI: Fix code block rendering issues on light background colors ## 0.51 (2025-11-08) * Lib: Rename `Soul.model` to `Soul.model_name` * Lib: Rename `LLMModelCapability` to `ModelCapability` and move to `kimi_cli.llm` * Lib: Add `"thinking"` to `ModelCapability` * Lib: Remove `LLM.supports_image_in` property * Lib: Add required `Soul.model_capabilities` property * Lib: Rename `KimiSoul.set_thinking_mode` to `KimiSoul.set_thinking` * Lib: Add `KimiSoul.thinking` property * UI: Better checks and notices for LLM model capabilities * UI: Clear the screen for `/clear` meta command * Tool: Support auto-downloading ripgrep on Windows * CLI: Add `--thinking` option to start in thinking mode * ACP: Support thinking content in ACP mode ## 0.50 (2025-11-07) * Improve UI look and feel * Improve Task tool observability ## 0.49 (2025-11-06) * Minor UX improvements ## 0.48 (2025-11-06) * Support Kimi K2 thinking mode ## 0.47 (2025-11-05) * Fix Ctrl-W not working in some environments * Do not load SearchWeb tool when the search service is not configured ## 0.46 (2025-11-03) * Introduce Wire over stdio for local IPC (experimental, subject to change) * Support Anthropic provider type * Fix binary packed by PyInstaller not working due to wrong entrypoint ## 0.45 (2025-10-31) * Allow `KIMI_MODEL_CAPABILITIES` environment variable to override model capabilities * Add `--no-markdown` option to disable markdown rendering * Support `openai_responses` LLM provider type * Fix crash when continuing a session ## 0.44 (2025-10-30) * Improve startup time * Fix potential invalid bytes in user input ## 0.43 (2025-10-30) * Basic Windows support (experimental) * Display warnings when base URL or API key is overridden in environment variables * Support image input if the LLM model supports it * Replay recent context history when continuing a session * Ensure new line after executing shell commands ## 0.42 (2025-10-28) * Support Ctrl-J or Alt-Enter to insert a new line * Change mode switch shortcut from Ctrl-K to Ctrl-X * Improve overall robustness * Fix ACP server `no attribute` error ## 0.41 (2025-10-26) * Fix a bug for Glob tool when no matching files are found * Ensure reading files with UTF-8 encoding * Disable reading command/query from stdin in shell mode * Clarify the API platform selection in `/setup` meta command ## 0.40 (2025-10-24) * Support `ESC` key to interrupt the agent loop * Fix SSL certificate verification error in some rare cases * Fix possible decoding error in Bash tool ## 0.39 (2025-10-24) * Fix context compaction threshold check * Fix panic when SOCKS proxy is set in the shell session ## 0.38 (2025-10-24) * Minor UX improvements ## 0.37 (2025-10-24) * Fix update checking ## 0.36 (2025-10-24) * Add `/debug` meta command to debug the context * Add auto context compaction * Add approval request mechanism * Add `--yolo` option to automatically approve all actions * Render markdown content for better readability * Fix "unknown error" message when interrupting a meta command ## 0.35 (2025-10-22) * Minor UI improvements * Auto download ripgrep if not found in the system * Always approve tool calls in `--print` mode * Add `/feedback` meta command ## 0.34 (2025-10-21) * Add `/update` meta command to check for updates and auto-update in background * Support running interactive shell commands in raw shell mode * Add `/setup` meta command to setup LLM provider and model * Add `/reload` meta command to reload configuration ## 0.33 (2025-10-18) * Add `/version` meta command * Add raw shell mode, which can be switched to by Ctrl-K * Show shortcuts in bottom status line * Fix logging redirection * Merge duplicated input histories ## 0.32 (2025-10-16) * Add bottom status line * Support file path auto-completion (`@filepath`) * Do not auto-complete meta command in the middle of user input ## 0.31 (2025-10-14) * Fix step interrupting by Ctrl-C, for real ## 0.30 (2025-10-14) * Add `/compact` meta command to allow manually compacting context * Fix `/clear` meta command when context is empty ## 0.29 (2025-10-14) * Support Enter key to accept completion in shell mode * Remember user input history across sessions in shell mode * Add `/reset` meta command as an alias for `/clear` * Fix step interrupting by Ctrl-C * Disable `SendDMail` tool in Kimi Koder agent ## 0.28 (2025-10-13) * Add `/init` meta command to analyze the codebase and generate an `AGENTS.md` file * Add `/clear` meta command to clear the context * Fix `ReadFile` output ## 0.27 (2025-10-11) * Add `--mcp-config-file` and `--mcp-config` options to load MCP configs * Rename `--agent` option to `--agent-file` ## 0.26 (2025-10-11) * Fix possible encoding error in `--output-format stream-json` mode ## 0.25 (2025-10-11) * Rename package name `ensoul` to `kimi-cli` * Rename `ENSOUL_*` builtin system prompt arguments to `KIMI_*` * Further decouple `App` with `Soul` * Split `Soul` protocol and `KimiSoul` implementation for better modularity ## 0.24 (2025-10-10) * Fix ACP `cancel` method ## 0.23 (2025-10-09) * Add `extend` field to agent file to support agent file extension * Add `exclude_tools` field to agent file to support excluding tools * Add `subagents` field to agent file to support defining subagents ## 0.22 (2025-10-09) * Improve `SearchWeb` and `FetchURL` tool call visualization * Improve search result output format ## 0.21 (2025-10-09) * Add `--print` option as a shortcut for `--ui print`, `--acp` option as a shortcut for `--ui acp` * Support `--output-format stream-json` to print output in JSON format * Add `SearchWeb` tool with `services.moonshot_search` configuration. You need to configure it with `"services": {"moonshot_search": {"api_key": "your-search-api-key"}}` in your config file. * Add `FetchURL` tool * Add `Think` tool * Add `PatchFile` tool, not enabled in Kimi Koder agent * Enable `SendDMail` and `Task` tool in Kimi Koder agent with better tool prompts * Add `ENSOUL_NOW` builtin system prompt argument * Better-looking `/release-notes` * Improve tool descriptions * Improve tool output truncation ## 0.20 (2025-09-30) * Add `--ui acp` option to start Agent Client Protocol (ACP) server ## 0.19 (2025-09-29) * Support piped stdin for print UI * Support `--input-format=stream-json` for piped JSON input * Do not include `CHECKPOINT` messages in the context when `SendDMail` is not enabled ## 0.18 (2025-09-29) * Support `max_context_size` in LLM model configurations to configure the maximum context size (in tokens) * Improve `ReadFile` tool description ## 0.17 (2025-09-29) * Fix step count in error message when exceeded max steps * Fix history file assertion error in `kimi_run` * Fix error handling in print mode and single command shell mode * Add retry for LLM API connection errors and timeout errors * Increase default max-steps-per-run to 100 ## 0.16.0 (2025-09-26) * Add `SendDMail` tool (disabled in Kimi Koder, can be enabled in custom agent) * Session history file can be specified via `_history_file` parameter when creating a new session ## 0.15.0 (2025-09-26) * Improve tool robustness ## 0.14.0 (2025-09-25) * Add `StrReplaceFile` tool * Emphasize the use of the same language as the user ## 0.13.0 (2025-09-25) * Add `SetTodoList` tool * Add `User-Agent` in LLM API calls * Better system prompt and tool description * Better error messages for LLM ## 0.12.0 (2025-09-24) * Add `print` UI mode, which can be used via `--ui print` option * Add logging and `--debug` option * Catch EOF error for better experience ## 0.11.1 (2025-09-22) * Rename `max_retry_per_step` to `max_retries_per_step` ## 0.11.0 (2025-09-22) * Add `/release-notes` command * Add retry for LLM API errors * Add loop control configuration, e.g. `{"loop_control": {"max_steps_per_run": 50, "max_retry_per_step": 3}}` * Better extreme cases handling in `read_file` tool * Prevent Ctrl-C from exiting the CLI, force the use of Ctrl-D or `exit` instead ## 0.10.1 (2025-09-18) * Make slash commands look slightly better * Improve `glob` tool ## 0.10.0 (2025-09-17) * Add `read_file` tool * Add `write_file` tool * Add `glob` tool * Add `task` tool * Improve tool call visualization * Improve session management * Restore context usage when `--continue` a session ## 0.9.0 (2025-09-15) * Remove `--session` and `--continue` options ## 0.8.1 (2025-09-14) * Fix config model dumping ## 0.8.0 (2025-09-14) * Add `shell` tool and basic system prompt * Add tool call visualization * Add context usage count * Support interrupting the agent loop * Support project-level `AGENTS.md` * Support custom agent defined with YAML * Support oneshot task via `kimi -c` --- --- url: /en/guides/use-cases.md --- # Common Use Cases Kimi Code CLI can help you complete various software development and general tasks. Here are some typical scenarios. ## Implementing new features When you need to add new features to your project, simply describe your requirements in natural language. Kimi Code CLI will automatically read relevant code, understand the project structure, and then make modifications. ``` Add pagination to the user list page, showing 20 records per page ``` Kimi Code CLI typically works through a "Read → Edit → Verify" workflow: 1. **Read**: Search and read relevant code, understand existing implementation 2. **Edit**: Write or modify code, following the project's coding style 3. **Verify**: Run tests or builds to ensure changes don't introduce issues If you're not satisfied with the changes, you can tell Kimi Code CLI to adjust: ``` The pagination component style doesn't match the rest of the project, reference the Button component's style ``` ## Fixing bugs Describe the problem you're encountering, and Kimi Code CLI will help you locate the cause and fix it: ``` After user login, when redirecting to the home page, it occasionally shows logged out status. Help me investigate ``` For problems with clear error messages, you can paste the error log directly: ``` When running npm test, I get this error: TypeError: Cannot read property 'map' of undefined at UserList.render (src/components/UserList.jsx:15:23) Please fix it ``` You can also have Kimi Code CLI run commands to reproduce and verify the issue: ``` Run the tests, and if there are any failing cases, fix them ``` ## Understanding projects Kimi Code CLI can help you explore and understand unfamiliar codebases: ``` What's the overall architecture of this project? Where is the entry file? ``` ``` How is the user authentication flow implemented? What files are involved? ``` ``` Explain what the src/core/scheduler.py file does ``` If you encounter parts you don't understand while reading code, you can ask anytime: ``` What's the difference between useCallback and useMemo? Why use useCallback here? ``` ## Automating small tasks Kimi Code CLI can perform various repetitive small tasks: ``` Change all var declarations to const or let in .js files under the src directory ``` ``` Add documentation comments to all public functions without docstrings ``` ``` Generate unit tests for this API module ``` ``` Update all dependencies in package.json to the latest version, then run tests to make sure there are no issues ``` ## Automating general tasks Beyond code-related tasks, Kimi Code CLI can also handle some general scenarios. **Research tasks** ``` Research Python async web frameworks for me, compare the pros and cons of FastAPI, Starlette, and Sanic ``` **Data analysis** ``` Analyze the access logs in the logs directory, count the call frequency and average response time for each endpoint ``` **Batch file processing** ``` Convert all PNG images in the images directory to JPEG format, save to the output directory ``` --- --- url: /en/configuration/config-files.md --- # Config Files Kimi Code CLI uses configuration files to manage API providers, models, services, and runtime parameters, supporting both TOML and JSON formats. ## Config file location The default configuration file is located at `~/.kimi/config.toml`. On first run, if the configuration file doesn't exist, Kimi Code CLI will automatically create a default configuration file. You can specify a different configuration file (TOML or JSON format) with the `--config-file` flag: ```sh kimi --config-file /path/to/config.toml ``` When calling Kimi Code CLI programmatically, you can also pass the complete configuration content directly via the `--config` flag: ```sh kimi --config '{"default_model": "kimi-for-coding", "providers": {...}, "models": {...}}' ``` ## Config items The configuration file contains the following top-level configuration items: | Item | Type | Description | | --- | --- | --- | | `default_model` | `string` | Default model name, must be a model defined in `models` | | `default_thinking` | `boolean` | Whether to enable thinking mode by default (defaults to `false`) | | `default_yolo` | `boolean` | Whether to enable YOLO (auto-approve) mode by default (defaults to `false`) | | `skip_afk_prompt_injection` | `boolean` | Whether to suppress the AFK mode system reminder (defaults to `false`) | | `default_plan_mode` | `boolean` | Whether to start new sessions in plan mode by default (defaults to `false`); resumed sessions preserve their existing state | | `default_editor` | `string` | Default external editor command (e.g. `"vim"`, `"code --wait"`), auto-detects when empty | | `theme` | `string` | Terminal color theme, either `"dark"` or `"light"` (defaults to `"dark"`) | | `show_thinking_stream` | `boolean` | Whether to stream the raw reasoning text in the live area as a 6-line scrolling preview and commit the full reasoning markdown to history when the block ends (defaults to `true`; set to `false` to show only the compact `Thinking ...` indicator and a one-line trace summary) | | `merge_all_available_skills` | `boolean` | Whether to merge skills from all brand directories (defaults to `true`); see [Skills configuration](../customization/skills.md) | | `telemetry` | `boolean` | Whether to enable anonymous telemetry to help improve kimi-cli (defaults to `true`; set to `false` to disable) | | `providers` | `table` | API provider configuration | | `models` | `table` | Model configuration | | `loop_control` | `table` | Agent loop control parameters | | `background` | `table` | Background task runtime parameters | | `services` | `table` | External service configuration (search, fetch) | | `mcp` | `table` | MCP client configuration | ### Complete configuration example ```toml default_model = "kimi-for-coding" default_thinking = false default_yolo = false skip_afk_prompt_injection = false default_plan_mode = false default_editor = "" theme = "dark" show_thinking_stream = true merge_all_available_skills = true telemetry = true [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-xxx" [models.kimi-for-coding] provider = "kimi-for-coding" model = "kimi-for-coding" max_context_size = 262144 [loop_control] max_steps_per_turn = 1000 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 agent_task_timeout_s = 900 [services.moonshot_search] base_url = "https://api.kimi.com/coding/v1/search" api_key = "sk-xxx" [services.moonshot_fetch] base_url = "https://api.kimi.com/coding/v1/fetch" api_key = "sk-xxx" [mcp.client] tool_call_timeout_ms = 60000 ``` ### `providers` `providers` defines API provider connection information. Each provider uses a unique name as key. | Field | Type | Required | Description | | --- | --- | --- | --- | | `type` | `string` | Yes | Provider type, see [Providers](./providers.md) for details | | `base_url` | `string` | Yes | API base URL | | `api_key` | `string` | Yes | API key | | `env` | `table` | No | Environment variables to set before creating provider instance | | `custom_headers` | `table` | No | Custom HTTP headers to attach to requests | Example: ```toml [providers.moonshot-cn] type = "kimi" base_url = "https://api.moonshot.cn/v1" api_key = "sk-xxx" custom_headers = { "X-Custom-Header" = "value" } ``` ### `models` `models` defines available models. Each model uses a unique name as key. ::: warning Note If a `providers` or `models` key contains `.`, you must use a quoted TOML key. Otherwise, TOML treats `.` as a path separator and parses the key as nested tables. ::: | Field | Type | Required | Description | | --- | --- | --- | --- | | `provider` | `string` | Yes | Provider name to use, must be defined in `providers` | | `model` | `string` | Yes | Model identifier (model name used in API) | | `max_context_size` | `integer` | Yes | Maximum context length (in tokens) | | `capabilities` | `array` | No | Model capability list, see [Providers](./providers.md#model-capabilities) for details | | `display_name` | `string` | No | Human-readable model name shown in the welcome panel, prompt status bar, `/model` picker, and switch confirmations; falls back to `model` when unset. For OAuth-logged-in managed models, this field is auto-refreshed from the provider's `/models` endpoint at startup | Example: ```toml [models.kimi-k2-thinking-turbo] provider = "moonshot-cn" model = "kimi-k2-thinking-turbo" max_context_size = 262144 capabilities = ["thinking", "image_in"] ``` If the model name contains `.`, use a quoted key: ```toml [models."gpt-4.1"] provider = "openai" model = "gpt-4.1" max_context_size = 1047576 capabilities = ["thinking"] ``` ### `loop_control` `loop_control` controls agent execution loop behavior. | Field | Type | Default | Description | | --- | --- | --- | --- | | `max_steps_per_turn` | `integer` | `1000` | Maximum steps per turn (alias: `max_steps_per_run`) | | `max_retries_per_step` | `integer` | `3` | Maximum retries per step | | `max_ralph_iterations` | `integer` | `0` | Extra iterations after each user message; `0` disables; `-1` is unlimited | | `reserved_context_size` | `integer` | `50000` | Reserved token count for LLM response generation; auto-compaction triggers when `context_tokens + reserved_context_size >= max_context_size` | | `compaction_trigger_ratio` | `float` | `0.85` | Context usage ratio threshold for auto-compaction (0.5–0.99); auto-compaction triggers when `context_tokens >= max_context_size * compaction_trigger_ratio`, whichever condition is met first with `reserved_context_size` | ### `background` `background` controls background task runtime behavior. Background tasks are launched via the `Shell` tool or the `Agent` tool with `run_in_background=true`. | Field | Type | Default | Description | | --- | --- | --- | --- | | `max_running_tasks` | `integer` | `4` | Maximum number of concurrent background tasks | | `keep_alive_on_exit` | `boolean` | `false` | Whether to keep background tasks running when CLI exits; default is to terminate all background tasks on exit | | `kill_grace_period_ms` | `integer` | `2000` | Grace period (in milliseconds) to wait after sending SIGTERM during CLI shutdown before reporting any shell workers that have not yet written terminal state. Agent tasks transition to terminal synchronously on kill and do not use this grace period | | `agent_task_timeout_s` | `integer` | `900` | Maximum runtime in seconds for a background agent task; timed-out tasks are marked as failed and the main agent is notified | | `print_wait_ceiling_s` | `integer` | `3600` | Hard ceiling (in seconds) for how long one-shot `--print` mode waits for background tasks to finish before killing them and exiting. The effective wait is the longest remaining task budget, clipped by this ceiling | ### `services` `services` configures external services used by Kimi Code CLI. #### `moonshot_search` Configures web search service. When enabled, the `SearchWeb` tool becomes available. | Field | Type | Required | Description | | --- | --- | --- | --- | | `base_url` | `string` | Yes | Search service API URL | | `api_key` | `string` | Yes | API key | | `custom_headers` | `table` | No | Custom HTTP headers to attach to requests | #### `moonshot_fetch` Configures web fetch service. When enabled, the `FetchURL` tool prioritizes using this service to fetch webpage content. | Field | Type | Required | Description | | --- | --- | --- | --- | | `base_url` | `string` | Yes | Fetch service API URL | | `api_key` | `string` | Yes | API key | | `custom_headers` | `table` | No | Custom HTTP headers to attach to requests | ::: tip When configuring the Kimi Code platform using the `/login` command, search and fetch services are automatically configured. ::: ### `mcp` `mcp` configures MCP client behavior. | Field | Type | Default | Description | | --- | --- | --- | --- | | `client.tool_call_timeout_ms` | `integer` | `60000` | MCP tool call timeout (milliseconds) | ### `hooks` `hooks` configures lifecycle hooks (Beta feature). See [Hooks](../customization/hooks.md) for details. Use the `[[hooks]]` array syntax to define multiple hooks: ```toml [[hooks]] event = "PreToolUse" matcher = "Shell" command = ".kimi/hooks/safety-check.sh" timeout = 10 [[hooks]] event = "PostToolUse" matcher = "WriteFile" command = "prettier --write" ``` | Field | Type | Required | Description | | --- | --- | --- | --- | | `event` | `string` | Yes | Event type, e.g., `PreToolUse`, `Stop`, etc. | | `command` | `string` | Yes | Shell command to execute | | `matcher` | `string` | No | Regex filter condition | | `timeout` | `integer` | No | Timeout in seconds, default 30 | ## JSON configuration migration If `~/.kimi/config.toml` doesn't exist but `~/.kimi/config.json` exists, Kimi Code CLI will automatically migrate the JSON configuration to TOML format and backup the original file as `config.json.bak`. `--config-file` specified configuration files are parsed based on file extension. `--config` passed configuration content is first attempted as JSON, then falls back to TOML if that fails. --- --- url: /en/configuration/overrides.md --- # Config Overrides Kimi Code CLI configuration can be set through multiple methods, with different sources overriding each other by priority. ## Priority Configuration priority from highest to lowest: 1. **Environment variables** - Highest priority, for temporary overrides or CI/CD environments 2. **CLI flags** - Flags specified at startup 3. **Configuration file** - `~/.kimi/config.toml` or file specified via `--config-file` ## CLI flags ### Configuration file related | Flag | Description | | --- | --- | | `--config ` | Pass configuration content directly, overrides default config file | | `--config-file ` | Specify configuration file path, replaces default `~/.kimi/config.toml` | `--config` and `--config-file` cannot be used together. ### Model related | Flag | Description | | --- | --- | | `--model, -m ` | Specify model name to use | The model specified by `--model` must be defined in the configuration file's `models`. If not specified, uses `default_model` from the configuration file. ### Behavior related | Flag | Description | | --- | --- | | `--thinking` | Enable thinking mode | | `--no-thinking` | Disable thinking mode | | `--yolo, --yes, -y` | Auto-approve all tool calls (user still reachable for `AskUserQuestion`) | | `--afk` | Away-from-keyboard: auto-approve all tool calls and auto-dismiss `AskUserQuestion` | | `--plan` | Start in plan mode | `--thinking` / `--no-thinking` overrides the thinking state saved from the last session. If not specified, uses the last session's state. `--plan` enables plan mode for new sessions; when resuming an existing session, it forces plan mode on. You can also set `default_plan_mode = true` in the config file to start new sessions in plan mode by default. ## Environment variable overrides Environment variables can override provider and model settings without modifying the configuration file. This is particularly useful in the following scenarios: * Injecting keys in CI/CD environments * Temporarily testing different API endpoints * Switching between multiple environments Environment variables take effect based on the current provider type: * `kimi` type providers: Use `KIMI_*` environment variables * `openai_legacy` or `openai_responses` type providers: Use `OPENAI_*` environment variables * Other provider types: Environment variable overrides not supported See [Environment Variables](./env-vars.md) for the complete list. Example: ```sh KIMI_API_KEY="sk-xxx" KIMI_MODEL_NAME="kimi-k2-thinking-turbo" kimi ``` ## Configuration priority example Assume the configuration file `~/.kimi/config.toml` contains: ```toml default_model = "kimi-for-coding" [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-config" [models.kimi-for-coding] provider = "kimi-for-coding" model = "kimi-for-coding" max_context_size = 262144 ``` Here are the configuration sources in different scenarios: | Scenario | `base_url` | `api_key` | `model` | | --- | --- | --- | --- | | `kimi` | Config file | Config file | Config file | | `KIMI_API_KEY=sk-env kimi` | Config file | Environment variable | Config file | | `kimi --model other` | Config file | Config file | CLI flag | | `KIMI_MODEL_NAME=k2 kimi` | Config file | Config file | Environment variable | --- --- url: /en/configuration/data-locations.md --- # Data Locations Kimi Code CLI stores all data in the `~/.kimi/` directory under the user's home directory. This page describes the locations and purposes of various data files. ::: tip You can customize the share directory path by setting the `KIMI_SHARE_DIR` environment variable. See [Environment Variables](./env-vars.md#kimi-share-dir) for details. Note: `KIMI_SHARE_DIR` only affects the storage location of the runtime data listed above, not the [Agent Skills](../customization/skills.md) search paths. Skills, as cross-tool shared capability extensions, are a different type of data from application runtime data. ::: ## Directory structure ``` ~/.kimi/ ├── config.toml # Main configuration file ├── kimi.json # Metadata ├── mcp.json # MCP server configuration ├── credentials/ # OAuth credentials │ └── .json ├── mcp-oauth/ # MCP OAuth tokens ├── sessions/ # Session data │ └── / │ └── / │ ├── context.jsonl │ ├── wire.jsonl │ └── state.json ├── imported_sessions/ # Imported session data (via kimi vis) │ └── / │ ├── context.jsonl │ ├── wire.jsonl │ └── state.json ├── plans/ # Plan mode plan files │ └── .md ├── user-history/ # Input history │ └── .jsonl └── logs/ # Logs └── kimi.log ``` ## Configuration and metadata ### `config.toml` Main configuration file, stores providers, models, services, and runtime parameters. See [Config Files](./config-files.md) for details. You can specify a configuration file at a different location with the `--config-file` flag. ### `kimi.json` Metadata file, stores Kimi Code CLI's runtime state, including: * `work_dirs`: List of working directories and their last used session IDs * `thinking`: Whether thinking mode was enabled in the last session This file is automatically managed by Kimi Code CLI and typically doesn't need manual editing. ### `mcp.json` MCP server configuration file, stores MCP servers added via the `kimi mcp add` command. See [MCP](../customization/mcp.md) for details. Example structure: ```json { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "transport": "http", "headers": { "CONTEXT7_API_KEY": "ctx7sk-xxx" } } } } ``` ## Credentials OAuth credentials are stored in the `~/.kimi/credentials/` directory. After logging in to your Kimi account via `/login`, OAuth tokens are saved in this directory. OAuth tokens for MCP servers are stored separately in `~/.kimi/mcp-oauth/`. After authorizing an MCP server added with `--auth oauth` via `kimi mcp auth `, later sessions reuse the tokens from this directory. Use `kimi mcp reset-auth ` to clear the MCP OAuth token for one server. Files in the `credentials/` directory have permissions set to read/write for the current user only (600) to protect sensitive information. ## Session data Session data is grouped by working directory and stored under `~/.kimi/sessions/`. Each working directory corresponds to a subdirectory named with the path's MD5 hash, and each session corresponds to a subdirectory named with the session ID. ### `context.jsonl` Context history file, stores the session's full context in JSON Lines (JSONL) format. The first line is a system prompt record (`_system_prompt`), followed by messages (user input, model response, tool calls, etc.) and internal records (checkpoints, token usage, etc.). The system prompt is generated and frozen at session creation time, and reused on session restore instead of being regenerated. Kimi Code CLI uses this file to restore session context when using `--continue` or `--session`. ### `wire.jsonl` Wire message log file, stores Wire events during the session in JSON Lines (JSONL) format. Used for session replay and extracting session titles. ### `state.json` Session state file, stores the session's runtime state, including: * `title`: User-set session title * `approval`: Approval decision state (YOLO and AFK mode on/off, auto-approved operation types) * `plan_mode`: Plan mode on/off status * `plan_session_id`: Unique identifier for the current plan session, used to associate the plan file * `plan_slug`: The file path identifier for the plan (the slug in `~/.kimi/plans/.md`), preserved so restarts resume the same file * `subagent_instances`: Subagent instance state and metadata * `additional_dirs`: Additional workspace directories added via `--add-dir` or `/add-dir` When resuming a session, Kimi Code CLI reads this file to restore the session state. This file uses atomic writes to prevent data corruption on crash. ### `subagents//` Each subagent instance created via the `Agent` tool has its own storage directory under the session directory, containing: * `context.jsonl`: Subagent conversation history * `wire.jsonl`: Subagent Wire event log * `meta.json`: Instance metadata (status, type, creation time, etc.) * `prompt.txt`: Last executed prompt * `output`: Execution output When resuming a session, subagent instance context and state are automatically restored, allowing continuation via the `resume` parameter. ## Plan files Plan mode plan files are stored in the `~/.kimi/plans/` directory. Each plan session corresponds to a randomly named Markdown file (e.g. `.md`). The `plan_slug` is saved in `state.json`, so the same plan file is resumed after a process restart. Use `/plan clear` to delete the current plan session's file. ## Input history User input history is stored in the `~/.kimi/user-history/` directory. Each working directory corresponds to a `.jsonl` file named with the path's MD5 hash. Input history is used for history browsing (up/down arrow keys) and search (Ctrl-R) in shell mode. ## Logs Runtime logs are stored in `~/.kimi/logs/kimi.log`. Default log level is INFO, use the `--debug` flag to enable TRACE level. Log files are used for troubleshooting. When reporting bugs, please include relevant log content. ## Cleaning data Deleting the share directory (default `~/.kimi/`, or the path specified by `KIMI_SHARE_DIR`) completely clears all Kimi Code CLI data, including configuration, sessions, and history. To clean only specific data: | Need | Action | | --- | --- | | Reset configuration | Delete `~/.kimi/config.toml` | | Clear all sessions | Delete `~/.kimi/sessions/` directory | | Clear sessions for specific working directory | Use `/sessions` in shell mode to view and delete | | Clear plan files | Delete `~/.kimi/plans/` directory, or use `/plan clear` in plan mode | | Clear input history | Delete `~/.kimi/user-history/` directory | | Clear logs | Delete `~/.kimi/logs/` directory | | Clear MCP configuration | Delete `~/.kimi/mcp.json` or use `kimi mcp remove` | | Clear login credentials | Delete `~/.kimi/credentials/` directory or use `/logout` | --- --- url: /AGENTS.md --- # Documentation Agent Guide This repository uses VitePress for the documentation site. The current docs are structural scaffolds only; everything beyond the headings is placeholder guidance. The `Reference Code` blocks are there to guide future writing and should be removed once the docs are complete. ## Structure * Locales live under `docs/en/` and `docs/zh/` with mirrored paths and filenames. * Main sections (nav + sidebar) are: * Guides: getting-started, use-cases, interaction, sessions, ides, integrations * Customization: mcp, skills, agents, print-mode, wire-mode * Configuration: config-files, providers, overrides, env-vars, data-locations * Reference: kimi-command, kimi-acp, kimi-mcp, slash-commands, keyboard, tools, exit-codes * FAQ: setup, interaction, acp, mcp, print-wire, updates * Release notes: changelog, breaking-changes * Navigation and sidebar are defined in `docs/.vitepress/config.ts`. Any new or renamed page must be wired there for both locales. ## Source of truth * **Changelog page**: The English version (`docs/en/release-notes/changelog.md`) is the source of truth. It is auto-synced from the root `CHANGELOG.md` via script. The Chinese changelog should be translated from the English version. * **All other pages**: The Chinese version (`docs/zh/`) is the source of truth. English translations should be based on the Chinese docs. Only the Chinese documentation and the English changelog are manually reviewed. Other translations (e.g., English versions of non-changelog pages) may be auto-generated by AI agents. ## Authoring workflow * Each page is a scaffold: expand the bullets into prose while keeping the section ordering, and keep the `::: info Reference Code` blocks aligned with the relevant section. * For changelog: edit the root `CHANGELOG.md`, then run `npm run sync` to update the English docs. * For other pages: edit the Chinese version first, then translate to English. ## Naming conventions * Filenames are kebab-case and mirror across locales (same slug in `docs/en/` and `docs/zh/`). * Use consistent section labels that match the sidebar titles. * Use backticks for flags, commands, subcommands, command arguments, file paths, code identifiers, type names, field names, field values, and keyboard shortcuts. ## Wording conventions * Do not change H1 titles or nav/sidebar labels. * English H2+ headings use sentence case (only the first word capitalized unless it is a proper noun). Treat "Wire" as a proper noun; do not treat "agent", "shell mode", or "print mode" as proper nouns. * Chinese H2+ headings keep English words in sentence case; preserve proper nouns listed in the term table below. * Use `API key` in English and `API 密钥` in Chinese; keep `JSON`, `JSONL`, `OAuth`, `macOS`, and `uv` as-is. * Use straight double quotes with spaces for quoted content: `"被引内容"` (not curly quotes). Add a space before and after the quoted text when adjacent to CJK characters. Use corner brackets `「」` for special terms (e.g., `「工具」`, `「会话」`). * Prefer "终端" over "命令行" in Chinese when both are applicable (e.g., "运行在终端中", "终端界面", "终端操作"). * Use "工具调用" / "tool call", not "工具使用" / "tool use". * Use inline code for tool names (e.g., `Task`, `ReadFile`, `Shell`). Term mapping (Chinese <-> English, and proper noun handling): | Chinese | English | Proper noun (zh) | Proper noun (en) | | --- | --- | --- | --- | | Agent | agent | yes | no | | Shell | shell | yes | no | | Shell 模式 | shell mode | yes | no | | Print 模式 | print mode | yes | no | | Wire 模式 | Wire mode | yes | yes (Wire) | | Thinking 模式 | thinking mode | yes | no | | MCP | MCP | yes | yes | | ACP | ACP | yes | yes | | Kimi Code CLI | Kimi Code CLI | yes | yes | | Agent Skills | Agent Skills | yes | yes | | Skill | skill | yes | no | | 系统提示词 | system prompt | no | no | | 提示词 | prompt | no | no | | 会话 | session | no | no | | 上下文 | context | no | no | | 子 Agent | subagent | yes (Agent) | no | | API 密钥 | API key | yes | no | | JSON | JSON | yes | yes | | JSONL | JSONL | yes | yes | | OAuth | OAuth | yes | yes | | macOS | macOS | yes | yes | | uv | uv | yes | yes | | 审批请求 | approval request | no | no | | 斜杠命令 | slash command | no | no | | 工具调用 | tool call | no | no | | Frontmatter | frontmatter | yes | no | | User 消息 | user message | yes (User) | no | | Assistant 消息 | assistant message | yes (Assistant) | no | | Tool 消息 | tool message | yes (Tool) | no | | 轮次 | turn | no | no | | 供应商 | provider | no | no | | Prompt Flow | Prompt Flow | yes | yes | | Ralph 循环 | Ralph Loop | yes | yes | | Diff | diff | yes | no | JetBrains IDE terminology (Chinese UI translations): | English | Chinese | | --- | --- | | AI Chat | AI 聊天 | | Registry | 注册表 | | Configure ACP agents | (未翻译) | ## Typography * **Spacing around mixed content**: Add a space between Chinese characters and English words, numbers, inline code, or links. Exception: no space before full-width punctuation. * ✓ 在 Python 中使用 \`class\` 关键字 * ✗ 在Python中使用\`class\`关键字 * ✓ 详见 \[配置文件]\(./config.md)。 * ✗ 详见\[配置文件]\(./config.md)。 * **Full-width punctuation**: Use full-width punctuation in Chinese text: `,。;:?!()` not `, . ; : ? ! ( )`. * **Code block language**: Always specify language for fenced code blocks (e.g., ` ```sh `, ` ```toml `, ` ```json `). Exception: natural language examples (user prompts) may omit the language. * **Callout titles**: Use short category titles for callout blocks (`::: tip`, `::: warning`, `::: info`, `::: danger`). Put the detailed description in the block content, not the title. * Chinese: use `提示` for tip, `注意` for warning, `说明` for info, `警告` for danger. * English: use no title or short words like `Note` for warning. * ✓ `::: tip 提示` + content starting with the key point * ✓ `::: warning 注意` + content `\`KIMI\_SHARE\_DIR\` 不影响 Skills 的搜索路径。...\` * ✗ `::: warning 不影响 Skills` (title too long, should be in content) * ✗ `::: tip Skills 路径独立于 KIMI_SHARE_DIR` (title too long) * **Version info blocks**: For version change callouts, use `::: info` with a category title (Added/Changed/Removed in English; 新增/变更/移除 in Chinese). The content should be a complete sentence. * ✓ `::: info 新增` + content `新增于 Wire 1.2。` * ✗ `::: info 新增于 Wire 1.2` (title too long) * ✓ `::: info Changed` + content `Renamed in Wire 1.1. ...` * ✗ `::: info Renamed in Wire 1.1` (title too long) ## Writing style * **Natural narrative**: Organize content like writing an article, guiding readers smoothly through the material. * **Avoid fragmentation**: Don't turn every point into a subheading; use paragraph transitions instead. * **Global perspective**: "Getting Started" introduces core concepts only; detailed usage belongs in later pages. * **Progressive depth**: Guides → Customization → Configuration → Reference, information deepens gradually. * **No "next steps"**: VitePress already provides prev/next navigation; don't add manual `::: tip 接下来` blocks at page end. ### Example: good vs bad Outline prompt: ``` * Install and upgrade * System requirements: Python 3.12+, recommend uv * Install, upgrade, uninstall steps ``` **Bad** (mechanical conversion to headings): ```markdown ## Install and upgrade ### System requirements - Python 3.12+ - Recommend uv ### Install ... ### Upgrade ... ``` **Good** (natural narrative): ```markdown ## Install and upgrade Kimi Code CLI requires Python 3.12+. We recommend using uv for installation and management. If you haven't installed uv yet, please refer to the uv installation docs first. Install Kimi Code CLI: (code block) Verify the installation: (code block) Upgrade to the latest version: (code block) ``` ## Build and preview * Docs are built with VitePress from `docs/`. * Common commands (run inside `docs/`): * `npm install` (or `bun install` if you use bun) * `npm run dev` * `npm run build` * `npm run preview` * The build output is `docs/.vitepress/dist`. ## Changelog syncing The English changelog (`docs/en/release-notes/changelog.md`) is auto-generated from the root `CHANGELOG.md`. Do not edit it manually. * The sync script is `docs/scripts/sync-changelog.mjs`. * It runs automatically before `npm run dev` and `npm run build`. * To run manually: `npm run sync` (from the `docs/` directory). * The script converts title format (`## [0.69] - 2025-12-29` → `## 0.69 (2025-12-29)`) and removes HTML comments. --- --- url: /en/configuration/env-vars.md --- # Environment Variables Kimi Code CLI supports overriding configuration or controlling runtime behavior through environment variables. This page lists all supported environment variables. For detailed information on how environment variables override configuration files, see [Config Overrides](./overrides.md). ## Kimi environment variables The following environment variables take effect when using `kimi` type providers, used to override provider and model configuration. | Environment Variable | Description | | --- | --- | | `KIMI_BASE_URL` | API base URL | | `KIMI_API_KEY` | API key | | `KIMI_MODEL_NAME` | Model identifier | | `KIMI_MODEL_MAX_CONTEXT_SIZE` | Maximum context length (in tokens) | | `KIMI_MODEL_CAPABILITIES` | Model capabilities, comma-separated (e.g., `thinking,image_in`) | | `KIMI_MODEL_TEMPERATURE` | Generation parameter `temperature` | | `KIMI_MODEL_TOP_P` | Generation parameter `top_p` | | `KIMI_MODEL_MAX_COMPLETION_TOKENS` | Explicit hard cap for `max_completion_tokens` | | `KIMI_MODEL_MAX_TOKENS` | Compatibility alias for `KIMI_MODEL_MAX_COMPLETION_TOKENS` | | `KIMI_MODEL_THINKING_KEEP` | Moonshot `thinking.keep` switch for preserved thinking (only applied when thinking mode is active) | ### `KIMI_BASE_URL` Overrides the provider's `base_url` field in the configuration file. ```sh export KIMI_BASE_URL="https://api.moonshot.cn/v1" ``` ### `KIMI_API_KEY` Overrides the provider's `api_key` field in the configuration file. Used to inject API keys without modifying the configuration file, suitable for CI/CD environments. ```sh export KIMI_API_KEY="sk-xxx" ``` ### `KIMI_MODEL_NAME` Overrides the model's `model` field in the configuration file (the model identifier used in API calls). ```sh export KIMI_MODEL_NAME="kimi-k2-thinking-turbo" ``` ### `KIMI_MODEL_MAX_CONTEXT_SIZE` Overrides the model's `max_context_size` field in the configuration file. Must be a positive integer. ```sh export KIMI_MODEL_MAX_CONTEXT_SIZE="262144" ``` ### `KIMI_MODEL_CAPABILITIES` Overrides the model's `capabilities` field in the configuration file. Multiple capabilities are comma-separated, supported values are `thinking`, `always_thinking`, `image_in`, and `video_in`. ```sh export KIMI_MODEL_CAPABILITIES="thinking,image_in" ``` ### `KIMI_MODEL_TEMPERATURE` Sets the generation parameter `temperature`, controlling output randomness. Higher values produce more random output, lower values produce more deterministic output. ```sh export KIMI_MODEL_TEMPERATURE="0.7" ``` ### `KIMI_MODEL_TOP_P` Sets the generation parameter `top_p` (nucleus sampling), controlling output diversity. ```sh export KIMI_MODEL_TOP_P="0.9" ``` ### `KIMI_MODEL_MAX_COMPLETION_TOKENS` Sets an explicit hard cap for the generation parameter `max_completion_tokens`. When unset, Kimi Code CLI uses the model's remaining context window. The value is dynamically clamped to `max_context_size - input_tokens` for every request. ```sh export KIMI_MODEL_MAX_COMPLETION_TOKENS="4096" ``` `KIMI_MODEL_MAX_TOKENS` is still accepted. If both variables are set, `KIMI_MODEL_MAX_COMPLETION_TOKENS` takes precedence. Set either variable to `0` or a negative integer to disable completion-token clamping. ### `KIMI_MODEL_THINKING_KEEP` Forwards the value verbatim to the Moonshot API as `thinking.keep`, enabling Preserved Thinking (see the [Moonshot docs](https://platform.kimi.com/docs/guide/use-kimi-k2-thinking-model#preserved-thinking)). Setting it to `all` causes the provider to preserve the reasoning content of previous assistant turns across requests. The value is passed through unchanged, no validation or case normalization is performed. ```sh export KIMI_MODEL_THINKING_KEEP="all" ``` Empty string or unset means the field is omitted from the request (current default behavior). The override only applies when the model is actually in thinking mode; it is ignored for non-thinking runs so the API never receives a `thinking.keep` without the companion `thinking.type`. This parameter only takes effect on Moonshot models that support Preserved Thinking (e.g., `kimi-k2.6` / `kimi-k2-thinking`). Passing it to other models has no effect or may be rejected by the API; the CLI does not validate the model. ::: warning Cost `thinking.keep=all` instructs the API to retain historical reasoning content across turns, which increases input tokens and therefore API cost. Only enable it when the preserved thinking behavior is required. ::: ## OpenAI-compatible environment variables The following environment variables take effect when using `openai_legacy` or `openai_responses` type providers. | Environment Variable | Description | | --- | --- | | `OPENAI_BASE_URL` | API base URL | | `OPENAI_API_KEY` | API key | ### `OPENAI_BASE_URL` Overrides the provider's `base_url` field in the configuration file. ```sh export OPENAI_BASE_URL="https://api.openai.com/v1" ``` ### `OPENAI_API_KEY` Overrides the provider's `api_key` field in the configuration file. ```sh export OPENAI_API_KEY="sk-xxx" ``` ## Other environment variables | Environment Variable | Description | | --- | --- | | `KIMI_SHARE_DIR` | Customize the share directory path (default: `~/.kimi`) | | `KIMI_CLI_NO_AUTO_UPDATE` | Disable all update-related features | | `KIMI_CLI_PASTE_CHAR_THRESHOLD` | Character threshold for folding pasted text (default: `1000`) | | `KIMI_CLI_PASTE_LINE_THRESHOLD` | Line threshold for folding pasted text (default: `15`) | ### `KIMI_SHARE_DIR` Customize the share directory path for Kimi Code CLI. The default path is `~/.kimi`, where configuration, sessions, logs, and other runtime data are stored. ```sh export KIMI_SHARE_DIR="/path/to/custom/kimi" ``` See [Data Locations](./data-locations.md) for details. ::: warning Note `KIMI_SHARE_DIR` does not affect [Agent Skills](../customization/skills.md) search paths. Skills are cross-tool shared capability extensions (compatible with Claude, Codex, etc.), which is a different type of data from application runtime data. To override Skills paths, use the `--skills-dir` flag. ::: ### `KIMI_CLI_NO_AUTO_UPDATE` When set to `1`, `true`, `t`, `yes`, or `y` (case-insensitive), disables all update-related features, including background auto-update check, the blocking update gate on startup, and the version hint in the welcome panel. ```sh export KIMI_CLI_NO_AUTO_UPDATE="1" ``` ::: tip If you installed Kimi Code CLI via Nix or other package managers, this environment variable is typically set automatically since updates are handled by the package manager. ::: ### `KIMI_CLI_PASTE_CHAR_THRESHOLD` In Agent mode, when pasted text exceeds this character count, it is folded into a placeholder (e.g., `[Pasted text #1 +10 lines]`) and expanded to full content on submit. Default: `1000`. ```sh export KIMI_CLI_PASTE_CHAR_THRESHOLD="1000" ``` ### `KIMI_CLI_PASTE_LINE_THRESHOLD` In Agent mode, when pasted text reaches this line count, it is folded into a placeholder. Default: `15`. ```sh export KIMI_CLI_PASTE_LINE_THRESHOLD="15" ``` ::: tip Some terminals (e.g., XShell over SSH) may break CJK input methods (Chinese/Japanese/Korean IME) after pasting multiline text. Symptoms include the IME candidate window not appearing or input becoming unresponsive until Ctrl+C is pressed. This happens because multiline text in the input buffer can confuse the terminal's cursor position tracking, which affects IME composition window placement. You can work around this by lowering the line threshold to fold multiline pastes into single-line placeholders: ```sh export KIMI_CLI_PASTE_LINE_THRESHOLD="2" ``` With this setting, any paste containing a newline will be automatically folded, preventing multiline text from entering the input buffer. Single-line pastes (URLs, short commands, etc.) are not affected. Note: The two thresholds use OR logic (character count **or** line count), so lowering only the line threshold is sufficient. Avoid setting the character threshold to a very small value (e.g., `1`), as that would fold all non-empty pastes including single-line short text. ::: --- --- url: /en/faq.md --- # FAQ ## Installation and authentication ### Empty model list during `/login` If you see "No models available for the selected platform" error when running the `/login` (or `/setup`) command, it may be due to: * **Invalid or expired API key**: Check if your API key is correct and still valid. * **Network connection issues**: Confirm you can access the API service addresses (such as `api.kimi.com` or `api.moonshot.cn`). ### Invalid API key Possible reasons for an invalid API key: * **Key input error**: Check for extra spaces or missing characters. * **Key expired or revoked**: Confirm the key status in the platform console. * **Environment variable override**: Check if `KIMI_API_KEY` or `OPENAI_API_KEY` environment variables are overriding the key in the config file. You can run `echo $KIMI_API_KEY` to check. ### Membership expired or quota exhausted If you're using the Kimi Code platform, you can check your current quota and membership status with the `/usage` command. If the quota is exhausted or membership expired, you need to renew or upgrade at [Kimi Code](https://kimi.com/coding). ## Interaction issues ### `cd` command doesn't work in shell mode Executing the `cd` command in shell mode won't change Kimi Code CLI's working directory. This is because each shell command executes in an independent subprocess, and directory changes only take effect within that process. If you need to change working directory: * **Exit and restart**: Run the `kimi` command again in the target directory. * **Use `--work-dir` flag**: Specify working directory at startup, like `kimi --work-dir /path/to/project`. * **Use absolute paths in commands**: Execute commands with absolute paths directly, like `ls /path/to/dir`. ### Image paste fails When using `Ctrl-V` to paste an image, if you see "Current model does not support image input", it means the current model doesn't support image input. Solutions: * **Switch to an image-capable model**: Use a model that supports the `image_in` capability. * **Check clipboard content**: Make sure the clipboard contains actual image data, not just a file path to an image. ### Working directory deleted or removed If the working directory becomes inaccessible during a session (external drive unplugged, directory deleted, or filesystem unmounted), Kimi Code CLI detects the situation and displays a crash report containing the session ID and work directory path, then exits cleanly. You can recover the session with `kimi -r ` from the correct directory. ## ACP issues ### IDE cannot connect to Kimi Code CLI If your IDE (like Zed or JetBrains IDEs) cannot connect to Kimi Code CLI, check the following: * **Confirm Kimi Code CLI is installed**: Run `kimi --version` to confirm successful installation. * **Check configuration path**: Ensure the Kimi Code CLI path in IDE configuration is correct. You can typically use `kimi acp` as the command. * **Check uv path**: If installed via uv, ensure `~/.local/bin` is in PATH. You can use an absolute path like `/Users/yourname/.local/bin/kimi acp`. * **Check logs**: Examine error messages in `~/.kimi/logs/kimi.log`. ## MCP issues ### MCP server startup fails After adding an MCP server, if tools aren't loaded or there are errors, it may be due to: * **Command doesn't exist**: For stdio type servers, ensure the command (like `npx`) is in PATH. You can configure with an absolute path. * **Configuration format error**: Check if `~/.kimi/mcp.json` is valid JSON. Run `kimi mcp list` to view current configuration. Debugging steps: ```sh # View configured servers kimi mcp list # Test if server is working kimi mcp test ``` ### OAuth authorization fails For MCP servers that require OAuth authorization (like Linear), if authorization fails: * **Check network connection**: Ensure you can access the authorization server. * **Re-authorize**: Run `kimi mcp auth ` to authorize again. * **Reset authorization**: If authorization info is corrupted, run `kimi mcp reset-auth ` to clear it and retry. ### Header format error When adding HTTP type MCP servers, header format should be `KEY: VALUE` (with a space after the colon). For example: ```sh # Correct kimi mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY: your-key" # Wrong (missing space or using equals sign) kimi mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY=your-key" ``` ## Print/Wire mode issues ### Invalid JSONL input format When using `--input-format stream-json`, input must be valid JSONL (one JSON object per line). Common issues: * **JSON format error**: Ensure each line is a complete JSON object without syntax errors. * **Encoding issues**: Ensure input uses UTF-8 encoding. * **Line ending issues**: Windows users should check if line endings are `\n` rather than `\r\n`. Correct input format example: ```json {"role": "user", "content": "Hello"} ``` ### No output in print mode If there's no output in `--print` mode, it may be: * **No input provided**: You need to provide input via `--prompt` (or `--command`) or stdin. For example: `kimi --print --prompt "Hello"`. * **Output is buffered**: Try using `--output-format stream-json` for streaming output. * **Configuration incomplete**: Ensure API key and model are configured via `/login`. ## Updates and upgrades ### macOS slow first run macOS's Gatekeeper security mechanism checks new programs on first run, causing slow startup. Solutions: * **Wait for check to complete**: Be patient on first run; subsequent launches will return to normal. * **Add to Developer Tools**: Add your terminal application in "System Settings → Privacy & Security → Developer Tools". ### How to upgrade Kimi Code CLI Use uv to upgrade to the latest version: ```sh uv tool upgrade kimi-cli --no-cache ``` Adding `--no-cache` ensures you get the latest version. ### Update prompt on startup When a newer version is detected by the background check, Kimi Code CLI shows a blocking update prompt before the shell loads, displaying the current and latest version information. You can choose an action with the following keys: * `Enter`: Upgrade to the latest version immediately * `q`: Skip for now; you will be reminded on next startup * `s`: Skip this version and suppress future reminders (until a newer version is released) ### How to disable update reminders If you don't want Kimi Code CLI to check for updates or show update prompts on startup, set the environment variable: ```sh export KIMI_CLI_NO_AUTO_UPDATE=1 ``` This disables background update checks, the blocking update gate on startup, and the version hint in the welcome panel. You can add this line to your shell configuration file (like `~/.zshrc` or `~/.bashrc`). --- --- url: /en/guides/getting-started.md --- # Getting Started ::: danger Warning **This project is archived.** Kimi CLI is no longer maintained and will stop working. It receives no further updates or security fixes. Please install [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code) instead; see the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration). ::: ## What is Kimi Code CLI Kimi Code CLI is an AI agent that runs in the terminal, helping you complete software development tasks and terminal operations. It can read and edit code, execute shell commands, search and fetch web pages, and autonomously plan and adjust actions during execution. Kimi Code CLI is suited for: * **Writing and modifying code**: Implementing new features, fixing bugs, refactoring code * **Understanding projects**: Exploring unfamiliar codebases, answering architecture and implementation questions * **Automating tasks**: Batch processing files, running builds and tests, executing scripts Kimi Code CLI supports the following usage modes: * **[Interactive CLI (`kimi`)](../reference/kimi-command.md)**: Chat with AI in the terminal using natural language or execute shell commands directly * **[Browser UI (`kimi web`)](../reference/kimi-web.md)**: Open a graphical interface in your local browser, with session management, file references, code highlighting, and more * **[Agent integration (`kimi acp`)](../reference/kimi-acp.md)**: Run as a service and integrate with [IDEs](./ides.md) and other local agent clients via the [Agent Client Protocol] ::: info Tip If you encounter issues or have suggestions, please provide feedback on [GitHub Issues](https://github.com/MoonshotAI/kimi-cli/issues). ::: [Agent Client Protocol]: https://agentclientprotocol.com/ ## Installation Kimi CLI is archived and should no longer be installed. Install [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code) instead: ```sh # Linux / macOS curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash ``` ```powershell # Windows (PowerShell) irm https://code.kimi.com/kimi-code/install.ps1 | iex ``` If you have used Kimi CLI before, Kimi Code CLI offers to migrate your config, MCP servers, and sessions on first launch, or you can run `kimi migrate` at any time. See the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration) for details. ## Uninstall After migrating to Kimi Code CLI, uninstall Kimi CLI: ```sh uv tool uninstall kimi-cli ``` ## First run Run the `kimi` command in the project directory where you want to work to start Kimi Code CLI: ```sh cd your-project kimi ``` On first launch, you need to configure your API source. Enter the `/login` command to start configuration: ``` /login ``` After execution, first select a platform. We recommend **Kimi Code**, which automatically opens a browser for OAuth authorization; selecting other platforms requires entering an API key. After configuration, Kimi Code CLI will automatically save the settings and reload. See [Providers](../configuration/providers.md) for details. Now you can chat with Kimi Code CLI directly using natural language. Try describing a task you want to complete, for example: ``` Show me the directory structure of this project ``` ::: tip If the project doesn't have an `AGENTS.md` file, you can run the `/init` command to have Kimi Code CLI analyze the project and generate this file, helping the AI better understand the project structure and conventions. ::: Enter `/help` to view all available [slash commands](../reference/slash-commands.md) and usage tips. --- --- url: /en/customization/hooks.md --- # Hooks (Beta) ::: warning Beta feature The Hooks system is currently in Beta. Implementation details and configuration definitions may change in future versions. Use with caution in production environments and watch for updates. ::: The Hooks system allows you to execute custom commands at key points in the Agent lifecycle, enabling automated workflows, security checks, notifications, and more. ## What is a Hook A hook is a mechanism that triggers when specific events occur. You can configure a shell command that receives context information via standard input when the event fires, and the command's exit code determines subsequent behavior. Example use cases: * **Code formatting**: Automatically run `prettier` or `black` after file edits * **Security checks**: Block dangerous shell commands (like `rm -rf /`) * **Sensitive file protection**: Prevent modification of `.env` and similar files * **Desktop notifications**: Send alerts when human approval is needed * **Task verification**: Check for incomplete tasks before session ends ## Supported Hook Events Kimi Code CLI supports 13 lifecycle events: | Event | Trigger | Matcher Filter | Available Context | |-------|---------|----------------|-------------------| | `PreToolUse` | Before tool call | Tool name | `tool_name`, `tool_input`, `tool_call_id` | | `PostToolUse` | After successful tool execution | Tool name | `tool_name`, `tool_input`, `tool_output` | | `PostToolUseFailure` | After tool execution fails | Tool name | `tool_name`, `tool_input`, `error` | | `UserPromptSubmit` | Before user input is processed | None | `prompt` | | `Stop` | When Agent turn ends | None | `stop_hook_active` | | `StopFailure` | When turn ends due to error | Error type | `error_type`, `error_message` | | `SessionStart` | When session is created/resumed | Source (`startup`/`resume`) | `source` | | `SessionEnd` | When session closes | Reason | `reason` | | `SubagentStart` | When subagent starts | Agent name | `agent_name`, `prompt` | | `SubagentStop` | When subagent ends | Agent name | `agent_name`, `response` | | `PreCompact` | Before context compaction | Trigger reason | `trigger`, `token_count` | | `PostCompact` | After context compaction | Trigger reason | `trigger`, `estimated_token_count` | | `Notification` | When notification is delivered | Sink name | `sink`, `notification_type`, `title`, `body`, `severity` | ## Configuring Hooks Define hooks in `~/.kimi/config.toml` using the `[[hooks]]` array syntax: ```toml # Auto-format after file edits [[hooks]] event = "PostToolUse" matcher = "WriteFile|StrReplaceFile" command = "jq -r '.tool_input.file_path' | xargs prettier --write" # Block edits to .env files [[hooks]] event = "PreToolUse" matcher = "WriteFile|StrReplaceFile" command = ".kimi/hooks/protect-env.sh" timeout = 10 # Desktop notification when approval needed [[hooks]] event = "Notification" matcher = "permission_prompt" command = "osascript -e 'display notification \"Kimi needs attention\" with title \"Kimi CLI\"'" # Verify tasks complete before stopping [[hooks]] event = "Stop" command = ".kimi/hooks/check-complete.sh" ``` ### Configuration Fields | Field | Required | Default | Description | |-------|----------|---------|-------------| | `event` | Yes | — | Event type, must be one of the 13 supported events | | `command` | Yes | — | Shell command to execute, receives JSON via stdin | | `matcher` | No | `""` | Regex filter, empty string matches all | | `timeout` | No | `30` | Timeout in seconds, fail-open on timeout | ## Communication Protocol ### Input (Standard Input) Hook commands receive JSON context via stdin, containing common fields and event-specific fields: ```json { "session_id": "abc123", "cwd": "/path/to/project", "hook_event_name": "PreToolUse", "tool_name": "Shell", "tool_input": {"command": "rm -rf /"} } ``` ### Output (Exit Code) | Exit Code | Behavior | Feedback | |-----------|----------|----------| | `0` | Allow | stdout content (if non-empty) is added to context | | `2` | Block | stderr content is fed back to LLM as correction | | Other | Allow | stderr is logged only, not shown to LLM | ### Structured JSON Output When exiting with code 0, you can output structured JSON for more detailed information: ```json { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Please use rg instead of grep" } } ``` When `permissionDecision` is `deny`, the operation is blocked and `permissionDecisionReason` is fed back to the LLM. ## Hook Script Examples ### Protect Sensitive Files ```bash #!/bin/bash # .kimi/hooks/protect-env.sh read JSON echo "$JSON" | jq -r '.tool_input.file_path' | grep -qE '\.env$|\.env\.local$' if [ $? -eq 0 ]; then echo "Error: Direct modification of .env files is not allowed. Use .env.example instead." >&2 exit 2 fi exit 0 ``` ### Auto-format Code ```bash #!/bin/bash # .kimi/hooks/auto-format.sh FILE=$(python3 -c "import sys,json; print(json.load(sys.stdin).get('tool_input',{}).get('file_path',''))") if [[ "$FILE" == *.js ]] || [[ "$FILE" == *.ts ]]; then prettier --write "$FILE" 2>/dev/null elif [[ "$FILE" == *.py ]]; then black "$FILE" 2>/dev/null fi exit 0 ``` ### Check for Incomplete Tasks ```bash #!/bin/bash # .kimi/hooks/check-complete.sh # Check for running background tasks if kimi task list --active 2>/dev/null | grep -q "running"; then echo '{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"Background tasks are still running. Please check /task first."}}' exit 0 fi exit 0 ``` ## Viewing Configured Hooks Use the `/hooks` command in Shell mode to view currently configured hooks: ``` /hooks ``` Example output: ``` Configured Hooks: PostToolUse: 1 hook(s) PreToolUse: 1 hook(s) Notification: 1 hook(s) Stop: 1 hook(s) ``` ## Design Principles ### Fail-Open Policy All hook execution failures (timeouts, crashes, regex errors) are treated as "allow", ensuring the Agent's normal workflow is not blocked. You can check logs for failure reasons. ### Parallel Execution Multiple hooks for the same event run in parallel for better performance. Identical commands are automatically deduplicated. ### Stop Hook Anti-Loop Stop hooks can only re-trigger once to prevent infinite loops. On re-trigger, the `stop_hook_active` field is set to `true`, allowing hooks to exit early. ### Context Variables Session ID is passed via ContextVar, avoiding the need to explicitly pass parameters on every tool call. ## Comparison with Plugins | Feature | Hooks | Plugins | |---------|-------|---------| | Trigger | Lifecycle events | Tool calls | | Timing | Specific events | AI-initiated | | Interaction | No interaction, receives stdin | Receives JSON parameters | | Purpose | Automation, security, notifications | Extend AI capabilities | | Return | Exit code controls flow | stdout as result | Hooks are suitable for checks or automation at key points, while plugins provide new tool capabilities for the AI. Both can be used together—for example, using hooks to block certain operations and plugins to provide alternatives. --- --- url: /zh/customization/hooks.md --- # Hooks (Beta) ::: warning Beta 功能 Hooks 系统目前处于 Beta 阶段,具体的实现细节和配置定义可能会在未来版本中调整。请谨慎在生产环境中使用,并关注后续更新。 ::: Hooks 系统让你可以在 Agent 生命周期的关键节点执行自定义命令,实现自动化工作流、安全检查、通知提醒等功能。 ## Hook 是什么 Hook 是一种在特定事件发生时触发的机制。你可以配置一个 shell 命令,当事件发生时,Kimi Code CLI 会将事件相关的上下文信息通过标准输入传递给该命令,并根据命令的退出码决定后续行为。 使用场景示例: * **代码格式化**:在文件编辑后自动运行 `prettier` 或 `black` * **安全检查**:阻止危险的 shell 命令(如 `rm -rf /`) * **敏感文件保护**:防止修改 `.env` 等配置文件 * **桌面通知**:在需要人工审批时发送通知 * **任务验证**:在会话结束前检查是否有未完成的任务 ## 支持的 Hook 事件 Kimi Code CLI 支持 13 种生命周期事件: | 事件 | 触发时机 | Matcher 过滤 | 可用上下文 | |------|----------|--------------|------------| | `PreToolUse` | 工具调用前 | 工具名称 | `tool_name`, `tool_input`, `tool_call_id` | | `PostToolUse` | 工具成功执行后 | 工具名称 | `tool_name`, `tool_input`, `tool_output` | | `PostToolUseFailure` | 工具执行失败后 | 工具名称 | `tool_name`, `tool_input`, `error` | | `UserPromptSubmit` | 用户提交输入前 | 无 | `prompt` | | `Stop` | Agent 轮次结束时 | 无 | `stop_hook_active` | | `StopFailure` | 轮次因错误结束时 | 错误类型 | `error_type`, `error_message` | | `SessionStart` | 会话创建/恢复时 | 来源 (`startup`/`resume`) | `source` | | `SessionEnd` | 会话关闭时 | 原因 | `reason` | | `SubagentStart` | 子 Agent 启动时 | Agent 名称 | `agent_name`, `prompt` | | `SubagentStop` | 子 Agent 结束时 | Agent 名称 | `agent_name`, `response` | | `PreCompact` | 上下文压缩前 | 触发原因 | `trigger`, `token_count` | | `PostCompact` | 上下文压缩后 | 触发原因 | `trigger`, `estimated_token_count` | | `Notification` | 通知发送到 sink 时 | sink 名称 | `sink`, `notification_type`, `title`, `body`, `severity` | ## 配置 Hooks 在 `~/.kimi/config.toml` 中使用 `[[hooks]]` 数组定义 hook: ```toml # 文件编辑后自动格式化 [[hooks]] event = "PostToolUse" matcher = "WriteFile|StrReplaceFile" command = "jq -r '.tool_input.file_path' | xargs prettier --write" # 阻止修改 .env 文件 [[hooks]] event = "PreToolUse" matcher = "WriteFile|StrReplaceFile" command = ".kimi/hooks/protect-env.sh" timeout = 10 # 需要审批时发送桌面通知 [[hooks]] event = "Notification" matcher = "permission_prompt" command = "osascript -e 'display notification \"Kimi needs attention\" with title \"Kimi CLI\"'" # 会话结束前检查任务完成情况 [[hooks]] event = "Stop" command = ".kimi/hooks/check-complete.sh" ``` ### 配置字段 | 字段 | 必填 | 默认值 | 说明 | |------|------|--------|------| | `event` | 是 | — | 事件类型,必须是上述 13 种之一 | | `command` | 是 | — | 要执行的 shell 命令,通过 stdin 接收 JSON 上下文 | | `matcher` | 否 | `""` | 正则表达式过滤,空字符串匹配所有 | | `timeout` | 否 | `30` | 超时时间(秒),超时后按 fail-open 处理 | ## 通信协议 ### 输入(标准输入) Hook 命令从标准输入接收 JSON 格式的上下文信息,包含通用字段和事件特定字段: ```json { "session_id": "abc123", "cwd": "/path/to/project", "hook_event_name": "PreToolUse", "tool_name": "Shell", "tool_input": {"command": "rm -rf /"} } ``` ### 输出(退出码) | 退出码 | 行为 | 反馈 | |--------|------|------| | `0` | 允许继续 | 标准输出内容(非空时)会添加到上下文 | | `2` | 阻止操作 | 标准错误内容会反馈给 LLM 作为修正建议 | | 其他 | 允许继续 | 标准错误仅记录日志,不展示给 LLM | ### 结构化 JSON 输出 退出码 0 时,可以通过输出结构化 JSON 提供更详细的信息: ```json { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "请使用 rg 代替 grep" } } ``` 当 `permissionDecision` 为 `deny` 时,会阻止操作并将 `permissionDecisionReason` 反馈给 LLM。 ## Hook 脚本示例 ### 保护敏感文件 ```bash #!/bin/bash # .kimi/hooks/protect-env.sh read JSON echo "$JSON" | jq -r '.tool_input.file_path' | grep -qE '\.env$|\.env\.local$' if [ $? -eq 0 ]; then echo "Error: Direct modification of .env files is not allowed. Use .env.example instead." >&2 exit 2 fi exit 0 ``` ### 自动格式化代码 ```bash #!/bin/bash # .kimi/hooks/auto-format.sh FILE=$(python3 -c "import sys,json; print(json.load(sys.stdin).get('tool_input',{}).get('file_path',''))") if [[ "$FILE" == *.js ]] || [[ "$FILE" == *.ts ]]; then prettier --write "$FILE" 2>/dev/null elif [[ "$FILE" == *.py ]]; then black "$FILE" 2>/dev/null fi exit 0 ``` ### 检查未完成的任务 ```bash #!/bin/bash # .kimi/hooks/check-complete.sh # 检查是否有进行中的后台任务 if kimi task list --active 2>/dev/null | grep -q "running"; then echo '{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"还有后台任务在运行,请先检查 /task"}}' exit 0 fi exit 0 ``` ## 查看已配置的 Hooks 在 Shell 模式下使用 `/hooks` 命令查看当前配置的 hooks: ``` /hooks ``` 输出示例: ``` Configured Hooks: PostToolUse: 1 hook(s) PreToolUse: 1 hook(s) Notification: 1 hook(s) Stop: 1 hook(s) ``` ## 设计原则 ### Fail-Open 策略 所有 hook 执行失败(超时、崩溃、正则表达式错误)都按 "允许" 处理,确保不会阻塞 Agent 的正常工作。你可以通过日志查看 hook 执行失败的原因。 ### 并行执行 同一事件的多个 hook 会并行执行,提高性能。相同的命令会自动去重。 ### Stop Hook 防循环 Stop hook 最多只能重新触发一次,防止无限循环。重新触发时,`stop_hook_active` 字段会设为 `true`,hook 可以根据此标志提前退出。 ### 上下文变量 Session ID 通过 ContextVar 传递,避免在每次工具调用时显式传递参数。 ## 与插件的区别 | 特性 | Hooks | 插件 | |------|-------|------| | 触发方式 | 生命周期事件驱动 | 工具调用驱动 | | 执行时机 | 特定事件发生时 | AI 主动调用 | | 交互方式 | 无交互,接收 stdin | 接收 JSON 参数 | | 用途 | 自动化、安全检查、通知 | 扩展 AI 能力 | | 返回值 | 退出码控制流程 | 标准输出作为结果 | Hooks 适合在关键节点执行检查或自动化任务,而插件适合为 AI 提供新的工具能力。两者可以结合使用,例如通过 hook 阻止某些操作,通过插件提供替代方案。 --- --- url: /en/guides/integrations.md --- # Integrations with Tools Besides using in the terminal and IDEs, Kimi Code CLI can also be integrated with other tools. ## Zsh plugin [zsh-kimi-cli](https://github.com/MoonshotAI/zsh-kimi-cli) is a Zsh plugin that lets you quickly switch to Kimi Code CLI in Zsh. **Installation** If you use Oh My Zsh, you can install it like this: ```sh git clone https://github.com/MoonshotAI/zsh-kimi-cli.git \ ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/kimi-cli ``` Then add the plugin in `~/.zshrc`: ```sh plugins=(... kimi-cli) ``` Reload the Zsh configuration: ```sh source ~/.zshrc ``` **Usage** After installation, press `Ctrl-X` in Zsh to quickly switch to Kimi Code CLI without manually typing the `kimi` command. ::: tip If you use other Zsh plugin managers (like zinit, zplug, etc.), please refer to the [zsh-kimi-cli repository](https://github.com/MoonshotAI/zsh-kimi-cli) README for installation instructions. ::: --- --- url: /en/guides/interaction.md --- # Interaction and Input Kimi Code CLI provides rich interaction features to help you collaborate efficiently with AI. ## Agent and shell mode Kimi Code CLI has two input modes: * **Agent mode**: The default mode, where input is sent to the AI for processing * **Shell mode**: Execute shell commands directly without leaving Kimi Code CLI Press `Ctrl-X` to switch between the two modes. The current mode is displayed in the bottom status bar. In shell mode, you can execute commands just like in a regular terminal: ```sh $ ls -la $ git status $ npm run build ``` Shell mode also supports some slash commands, including `/help`, `/exit`, `/version`, `/editor`, `/changelog`, `/feedback`, `/export`, `/import`, and `/task`. ::: warning Note In shell mode, each command executes independently. Commands that change the environment like `cd` or `export` won't affect subsequent commands. ::: ## Plan mode Plan mode is a read-only planning mode that lets the AI design an implementation plan before writing code, preventing wasted effort in the wrong direction. In plan mode, the AI can only use read-only tools (`Glob`, `Grep`, `ReadFile`) to explore the codebase — it cannot modify any files or execute commands. The AI writes its plan to a dedicated plan file, then submits it to you for approval. You can approve, reject, or provide revision feedback. ### Entering plan mode There are four ways to enter plan mode: * **CLI flag**: Use `kimi --plan` to start a new session directly in plan mode * **Keyboard shortcut**: Press `Shift-Tab` to toggle plan mode * **Slash command**: Enter `/plan` or `/plan on` * **AI-initiated**: When facing complex tasks, the AI may request to enter plan mode via the `EnterPlanMode` tool — you can accept or decline You can also set `default_plan_mode = true` in the config file to start every new session in plan mode by default. See [Configuration files](../configuration/config-files.md). In YOLO mode, AI-initiated entry into plan mode is auto-approved, but exiting plan mode with `ExitPlanMode` still asks you to approve the plan. In AFK mode, both entering and exiting plan mode are auto-approved because no user is present. When plan mode is active, the prompt changes to `📋` and a blue `plan` badge appears in the status bar. ### Reviewing plans When the AI finishes its plan, it submits it for approval via `ExitPlanMode`. The approval panel shows the full plan content, and you can: * **Approve / select an approach**: If the plan contains multiple alternative implementation paths, the AI lists 2–3 labeled options (e.g. "Option A", "Option B (Recommended)") for you to choose from — selecting one exits plan mode and tells the AI which path to follow. If the plan has a single path, an **Approve** button is shown instead. * **Reject**: Decline the plan, stay in plan mode, and provide feedback via conversation * **Reject and Exit**: Decline the plan and exit plan mode in one step * **Revise**: Enter revision notes — the AI will update the plan and resubmit Press `Ctrl-E` to view the full plan content in a fullscreen pager. ### Managing plan mode Use the `/plan` command to manage plan mode: * `/plan`: Toggle plan mode * `/plan on`: Enable plan mode * `/plan off`: Disable plan mode * `/plan view`: View the current plan content * `/plan clear`: Clear the current plan file ## Thinking mode Thinking mode allows the AI to think more deeply before responding, suitable for handling complex problems. You can use the `/model` command to switch models and thinking mode. After selecting a model, if the model supports thinking mode, the system will ask whether to enable it. You can also enable it at startup with the `--thinking` flag: ```sh kimi --thinking ``` ::: tip Thinking mode requires support from the current model. Some models (like `kimi-k2-thinking-turbo`) always use thinking mode and cannot be disabled. ::: ## Sending messages while running While the AI is executing a task, you can send follow-up messages in two ways without waiting for the current turn to finish: * **Queue (Enter)**: Press `Enter` to queue your message for delivery after the current turn completes. The queued message count is shown in the input area title (e.g. `── input · 2 queued ──`). Press `↑` in an empty input box to recall the last queued message for editing. * **Inject immediately (Ctrl+S)**: Press `Ctrl+S` to inject your message directly into the running turn context — the model sees it right away. Approval requests and question panels are also handled inline with keyboard navigation during agent execution. ::: tip To interrupt the AI's execution immediately, use `Ctrl-C`. ::: ## Side questions While the AI is working, you can use the `/btw` command to ask a quick side question without interrupting the main conversation flow. ``` /btw What is the return type of this function? ``` Side questions run in an isolated context: they can see the conversation history but do not modify it, and tools are disabled. The response is displayed in a scrollable modal panel — use `↑`/`↓` to scroll, `Escape` to close. See [Slash commands reference](../reference/slash-commands.md#btw) for details. ## Background tasks When the AI needs to run long-running commands (such as building a project, running a test suite, or starting a development server), it can launch them as background tasks. Background tasks run in a separate process, allowing the AI to continue handling other requests without waiting for the command to finish. How background tasks work: 1. The AI uses the `Shell` tool with `run_in_background=true` to launch the command 2. The tool immediately returns a task ID, and the AI continues with other work 3. When the task completes, if the AI is idle (waiting for user input), the system automatically triggers a new agent turn to process the results — no manual input needed You can use the `/task` slash command to open the interactive task browser, where you can view the status and output of all background tasks in real time (including tasks that are still running). See [Slash commands reference](../reference/slash-commands.md#task) for details. ::: tip By default, up to 4 background tasks can run simultaneously. This can be adjusted in the `[background]` section of the config file. All background tasks are terminated when the CLI exits by default. See [Configuration files](../configuration/config-files.md#background). ::: ## Multi-line input Sometimes you need to enter multiple lines, such as pasting a code snippet or error log. Press `Ctrl-J` or `Alt-Enter` to insert a newline instead of sending the message immediately. After finishing your input, press `Enter` to send the complete message. ## Clipboard and media paste Press `Ctrl-V` to paste text, images, or video files from the clipboard. In agent mode, longer pasted text (over 1000 characters or 15 lines) is automatically collapsed into a `[Pasted text #n]` placeholder in the input box to keep the interface clean. The full content is still expanded and sent to the model when submitting. When using an external editor (`Ctrl-O`), placeholders are automatically expanded to the original text; unmodified portions are re-collapsed after saving. If the clipboard contains an image, Kimi Code CLI caches the image to disk and displays it as an `[image:…]` placeholder in the input box. After sending the message, the AI can see and analyze the image. If the clipboard contains a video file, its file path is inserted as text into the input box. ::: tip Image input requires the model to support the `image_in` capability. Video input requires the `video_in` capability. ::: ## Slash commands Slash commands are special instructions starting with `/`, used to execute Kimi Code CLI's built-in features, such as `/help`, `/login`, `/sessions`, etc. After typing `/`, a list of available commands will automatically appear. For the complete list of slash commands, see the [slash commands reference](../reference/slash-commands.md). ## @ path completion When you type `@` in a message, Kimi Code CLI will auto-complete file and directory paths in the working directory. This allows you to conveniently reference files in your project: ``` Check if there are any issues with @src/components/Button.tsx ``` After typing `@`, start entering the filename and matching completions will appear. Press `Tab` or `Enter` to select a completion. In Git repositories, file discovery uses `git ls-files` first, enabling fast lookups even in large repos with tens of thousands of files; non-Git projects fall back to directory scanning. ## Structured questions During execution, the AI may need you to make choices to determine the next direction. In such cases, the AI will use the `AskUserQuestion` tool to present structured questions and options. The question panel displays the question description and available options. You can select using the keyboard: * Use arrow keys (up / down) to navigate options * Press `Enter` to confirm selection * Press `Space` to toggle selection in multi-select mode * Select "Other" to enter custom text * Press `Esc` to skip the question Each question supports 2–4 predefined options, and the AI will set appropriate options and descriptions based on the current task context. If there are multiple questions to answer, the panel displays them as tabs — use Left/Right arrow keys or `Tab` to switch between questions. Answered questions are marked as completed, and switching back to an answered question restores the previous selection. ::: tip The AI only uses this tool when your choice genuinely affects subsequent actions. For decisions that can be inferred from context, the AI will decide on its own and continue execution. ::: ## Approvals and confirmations When the AI needs to perform operations that may have an impact (such as modifying files or running commands), Kimi Code CLI will request your confirmation. The confirmation prompt will show operation details, including shell command and file diff previews. If the content is long and truncated, you can press `Ctrl-E` to expand and view the full content. You can choose: * **Allow**: Execute this operation * **Allow for this session**: Automatically approve similar operations in the current session (this decision is persisted with the session and automatically restored when resuming) * **Reject**: Do not execute this operation * **Reject with feedback**: Decline the operation and provide written feedback telling the agent how to adjust If you trust the AI's operations, or you're running Kimi Code CLI in a safe isolated environment, you can enable "YOLO mode" to automatically approve all tool calls: ```sh # Enable at startup kimi --yolo # Or toggle during runtime /yolo ``` You can also set `default_yolo = true` in the config file to enable YOLO mode by default on every startup. See [Configuration files](../configuration/config-files.md). When YOLO mode is enabled, a yellow YOLO badge appears in the status bar at the bottom. Enter `/yolo` again to disable it. YOLO only removes approval friction — the agent still treats you as present and can reach you via `AskUserQuestion` when a decision is genuinely ambiguous. If you're actually stepping away, use AFK mode below. ::: warning Note YOLO mode skips all approval confirmations. Make sure you understand the potential risks. It's recommended to only use this in controlled environments. ::: ### AFK mode When you're stepping away from the terminal and want the agent to keep running unattended, enable "AFK mode" (away-from-keyboard): ```sh # Enable at startup kimi --afk # Or toggle during runtime /afk ``` AFK also auto-approves all tool calls, and additionally auto-dismisses any `AskUserQuestion` the model tries to send — so the agent makes its own best judgment instead of waiting for an answer that will never come. `--print` implicitly enables `--afk` for the same reason. When AFK is active, an orange AFK badge appears in the status bar, independent of the YOLO badge. Enter `/afk` again to disable it. ::: warning Note AFK skips all approval confirmations and removes the safety net of clarifying questions. Only use when you genuinely cannot be at the terminal and trust the current scope. ::: --- --- url: /en/reference/keyboard.md --- # Keyboard Shortcuts Kimi Code CLI shell mode supports the following keyboard shortcuts. ## Shortcuts list | Shortcut | Function | |----------|----------| | `Ctrl-X` | Toggle agent/shell mode | | `Shift-Tab` | Toggle plan mode (read-only research and planning) | | `Ctrl-O` | Edit in external editor (`$VISUAL`/`$EDITOR`) | | `Ctrl-J` | Insert newline | | `Alt-Enter` | Insert newline (same as `Ctrl-J`) | | `Ctrl-S` | Steer: inject input immediately into the running turn (during streaming) | | `Ctrl-V` | Paste (supports images and video files) | | `Ctrl-E` | Expand full approval request content | | `1`–`4` | Quick select approval option (`4` for decline with feedback) | | `1`–`5` | Select question option by number | | `Ctrl-D` | Exit Kimi Code CLI | | `Ctrl-C` | Interrupt current operation | ## Mode switching ### `Ctrl-X`: Toggle agent/shell mode Press `Ctrl-X` in the input box to switch between two modes: * **Agent mode**: Input is sent to AI agent for processing * **Shell mode**: Input is executed as local shell command The prompt changes based on current mode: * Agent mode: `✨` (normal) or `💫` (thinking mode) * Plan mode: `📋` * Shell mode: `$` ## Plan mode ### `Shift-Tab`: Toggle plan mode Press `Shift-Tab` to enable or disable plan mode. In plan mode, the AI can only use read-only tools to explore the codebase, writing an implementation plan to a plan file and submitting it for your approval. When enabled, the prompt changes to `📋` and a blue `plan` badge appears in the status bar. You can also use the `/plan` slash command to manage plan mode. See [Plan mode](../guides/interaction.md#plan-mode) for details. ## External editor ### `Ctrl-O`: Edit in external editor Press `Ctrl-O` to open an external editor (e.g., VS Code, Vim) to edit the current input content. The editor is selected in the following priority: 1. Editor configured via `/editor` command 2. `$VISUAL` environment variable 3. `$EDITOR` environment variable 4. Auto-detect: `code --wait` (VS Code) → `vim` → `vi` → `nano` Use the `/editor` command to interactively switch editors, or specify directly, e.g., `/editor vim`. After saving and exiting the editor, the edited content replaces the current input. If you quit without saving (e.g., `:q!` in Vim), the input remains unchanged. If the input contains pasted text placeholders, the editor automatically expands them to the original text for editing; unmodified portions are re-collapsed into placeholders after saving. Useful for writing multi-line prompts, complex code snippets, etc. ## Multi-line input ### `Ctrl-J` / `Alt-Enter`: Insert newline By default, pressing `Enter` submits the input. To enter multi-line content, use: * `Ctrl-J`: Insert newline at any position * `Alt-Enter`: Insert newline at any position Useful for entering multi-line code snippets or formatted text. ## Clipboard operations ### `Ctrl-V`: Paste Paste clipboard content into the input box. Supports: * **Text**: In agent mode, text longer than 1000 characters or 15 lines is automatically collapsed into a `[Pasted text #n]` placeholder to keep the input box clean; the full content is expanded and sent to the model when submitting. When using `Ctrl-O` to open an external editor, placeholders are automatically expanded to the original text, and unmodified portions are re-collapsed after saving * **Images**: Cached to disk and displayed as an `[image:xxx.png,WxH]` placeholder; the actual image data is sent along with the message to the model (requires model image input support) * **Video files**: File path is inserted as text into the input box (requires model video input support) ::: tip Image pasting requires the model to support `image_in` capability. Video pasting requires the model to support `video_in` capability. ::: ## Streaming input ### `Ctrl-S`: Steer During streaming, press `Ctrl-S` to submit the current input (or pop the oldest queued message) and inject it immediately into the running turn's context. The model sees your message right away without waiting for the current turn to end. If the input box is empty and there are queued messages, `Ctrl-S` pops the oldest queued message and steers it instead. ### `Enter`: Queue During streaming, pressing `Enter` queues your message for delivery after the current turn completes. The queued message count is shown in the input header (e.g., `── input · 2 queued ──`). Press `↑` on an empty input to recall the last queued message for editing. ## Approval request operations ### `Ctrl-E`: Expand full content When approval request preview content is truncated, press `Ctrl-E` to view the full content in a fullscreen pager. When preview is truncated, a "... (truncated, ctrl-e to expand)" hint is displayed. Useful for viewing longer shell commands or file diff content. ### Number key quick selection In the approval panel, press `1`–`3` to directly select and submit the corresponding approval option without navigating with arrow keys first. Press `4` to enter feedback mode, where you can type a reason for declining and press Enter to submit; the feedback text is passed to the agent to guide its next attempt. ## Structured question operations When the AI uses the `AskUserQuestion` tool to ask you a question, the question panel supports the following keyboard operations: | Shortcut | Function | |----------|----------| | `↑` / `↓` | Navigate options | | `←` / `→` / `Tab` | Switch between questions (multi-question mode) | | `1`–`5` | Select option by number (auto-submits for single-select, toggles for multi-select) | | `Space` | Submit selection in single-select mode, toggle selection in multi-select mode | | `Enter` | Confirm selection | | `Esc` | Skip question | When the AI asks multiple questions at once, the question panel displays them as tabs. Use `←` / `→` or `Tab` to switch between questions. Answered questions are marked as complete, and switching back to a previously answered question restores your earlier selection. ## Exit and interrupt ### `Ctrl-D`: Exit Press `Ctrl-D` when the input box is empty to exit Kimi Code CLI. ### `Ctrl-C`: Interrupt * In input box: Clear current input * During agent execution: Interrupt current operation * During slash command execution: Interrupt command ## Completion operations In agent mode, a completion menu is automatically displayed while typing: | Trigger | Completion content | |---------|-------------------| | `/` | Slash commands | | `@` | File paths in working directory | Completion operations: * Arrow keys to select * `Enter` to confirm selection * `Esc` to close menu * Continue typing to filter options ## Status bar The bottom status bar displays: * Current time * Current mode (agent/shell) and model name (in agent mode) * YOLO badge (yellow, when enabled) * AFK badge (orange, when enabled) * Plan badge (blue, when enabled) * Shortcut hints * Context usage The status bar automatically refreshes to update information. --- --- url: /en/customization/mcp.md --- # Model Context Protocol [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open protocol that allows AI models to safely interact with external tools and data sources. Kimi Code CLI supports connecting to MCP servers to extend AI capabilities. ## What is MCP MCP servers provide "tools" for AI to use. For example, a database MCP server can provide query tools that allow AI to execute SQL queries; a browser MCP server can let AI control browsers for automation tasks. Kimi Code CLI has built-in tools (file read/write, shell commands, web fetching, etc.). Through MCP, you can add more tools, such as: * Accessing specific APIs or databases * Controlling browsers or other applications * Integrating with third-party services (GitHub, Linear, Notion, etc.) ## MCP server management Use the [`kimi mcp`](../reference/kimi-mcp.md) command to manage MCP servers. **Add a server** Add an HTTP server: ```sh # Basic usage kimi mcp add --transport http context7 https://mcp.context7.com/mcp # With headers kimi mcp add --transport http context7 https://mcp.context7.com/mcp \ --header "CONTEXT7_API_KEY: your-key" # Using OAuth authentication kimi mcp add --transport http --auth oauth linear https://mcp.linear.app/mcp ``` Add a stdio server (local process): ```sh kimi mcp add --transport stdio chrome-devtools -- npx chrome-devtools-mcp@latest ``` **List servers** ```sh kimi mcp list ``` While Kimi Code CLI is running, you can also enter `/mcp` to view connected servers and loaded tools. **Remove a server** ```sh kimi mcp remove context7 ``` **OAuth authorization** For servers using OAuth, you need to complete authorization first: ```sh kimi mcp auth linear ``` This will open a browser to complete the OAuth flow. After successful authorization, Kimi Code CLI will save the token for future use. MCP OAuth tokens are stored in `~/.kimi/mcp-oauth/`. After upgrading from older versions that used FastMCP 2.x, the old token cache is not migrated automatically; if `kimi mcp list` shows that an OAuth server needs authorization, run `kimi mcp auth ` again. **Test a server** ```sh kimi mcp test context7 ``` ## MCP configuration file MCP server configuration is stored in `~/.kimi/mcp.json`, in a format compatible with other MCP clients: ```json { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "your-key" } }, "chrome-devtools": { "command": "npx", "args": ["chrome-devtools-mcp@latest"], "env": { "SOME_VAR": "value" } } } } ``` **Temporary configuration loading** Use the `--mcp-config-file` flag to load a configuration file from another location: ```sh kimi --mcp-config-file /path/to/mcp.json ``` Use the `--mcp-config` flag to pass JSON configuration directly: ```sh kimi --mcp-config '{"mcpServers": {"test": {"url": "https://..."}}}' ``` ## Loading status MCP servers initialize asynchronously after the shell UI starts, so the interface is usable immediately. The shell status bar shows live connection progress, automatically switching to a ready state once all servers are connected. The web interface also reflects each server's connection status in real time. If multiple MCP servers are configured, loading may take a moment. The status bar progress indicator keeps you informed while connections are being established. ## Security MCP tools may access and operate external systems. Be aware of security risks. **Approval mechanism** Kimi Code CLI requests user confirmation for sensitive operations (such as file modifications and command execution). MCP tools follow the same approval mechanism, with all MCP tool calls prompting for confirmation. **Prompt injection risks** Content returned by MCP tools may contain malicious instructions attempting to trick the AI into performing dangerous operations. Kimi Code CLI marks tool return content to help the AI distinguish between tool output and user instructions, but you should still: * Only use MCP servers from trusted sources * Check whether AI-proposed operations are reasonable * Keep manual approval for high-risk operations ::: warning Note In YOLO or AFK mode, MCP tool calls will also be automatically approved. Use these modes only when you fully trust the MCP servers. ::: --- --- url: /zh/customization/mcp.md --- # Model Context Protocol [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 是一个开放协议,让 AI 模型可以安全地与外部工具和数据源交互。Kimi Code CLI 支持连接 MCP 服务器,扩展 AI 的能力。 ## MCP 是什么 MCP 服务器提供「工具」给 AI 使用。例如,一个数据库 MCP 服务器可以提供查询工具,让 AI 能够执行 SQL 查询;一个浏览器 MCP 服务器可以让 AI 控制浏览器进行自动化操作。 Kimi Code CLI 内置了一些工具(文件读写、Shell 命令、网页抓取等),通过 MCP 你可以添加更多工具,比如: * 访问特定 API 或数据库 * 控制浏览器或其他应用 * 与第三方服务集成(GitHub、Linear、Notion 等) ## MCP 服务器管理 使用 [`kimi mcp`](../reference/kimi-mcp.md) 命令管理 MCP 服务器。 **添加服务器** 添加 HTTP 服务器: ```sh # 基本用法 kimi mcp add --transport http context7 https://mcp.context7.com/mcp # 带 Header kimi mcp add --transport http context7 https://mcp.context7.com/mcp \ --header "CONTEXT7_API_KEY: your-key" # 使用 OAuth 认证 kimi mcp add --transport http --auth oauth linear https://mcp.linear.app/mcp ``` 添加 stdio 服务器(本地进程): ```sh kimi mcp add --transport stdio chrome-devtools -- npx chrome-devtools-mcp@latest ``` **列出服务器** ```sh kimi mcp list ``` 在 Kimi Code CLI 运行时,也可以输入 `/mcp` 查看已连接的服务器和加载的工具。 **移除服务器** ```sh kimi mcp remove context7 ``` **OAuth 授权** 对于使用 OAuth 的服务器,需要先完成授权: ```sh kimi mcp auth linear ``` 这会打开浏览器完成 OAuth 流程。授权成功后,Kimi Code CLI 会保存 token 供后续使用。 MCP OAuth token 存储在 `~/.kimi/mcp-oauth/`。从使用 FastMCP 2.x 的旧版本升级后,旧的 token 缓存不会自动迁移;如果 `kimi mcp list` 显示某个 OAuth 服务器需要授权,重新运行 `kimi mcp auth ` 即可。 **测试服务器** ```sh kimi mcp test context7 ``` ## MCP 配置文件 MCP 服务器配置存储在 `~/.kimi/mcp.json`,格式与其他 MCP 客户端兼容: ```json { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "your-key" } }, "chrome-devtools": { "command": "npx", "args": ["chrome-devtools-mcp@latest"], "env": { "SOME_VAR": "value" } } } } ``` **临时加载配置** 使用 `--mcp-config-file` 参数可以加载其他位置的配置文件: ```sh kimi --mcp-config-file /path/to/mcp.json ``` 使用 `--mcp-config` 参数可以直接传入 JSON 配置: ```sh kimi --mcp-config '{"mcpServers": {"test": {"url": "https://..."}}}' ``` ## 加载状态 MCP 服务器在 Shell UI 启动后异步初始化,不会阻塞界面的使用。Shell 底部状态栏会实时显示连接进度,连接完成后自动切换为就绪状态。Web 界面也会同步显示各服务器的连接状态。 如果配置了多个 MCP 服务器,加载时间可能较长,状态栏的进度指示可以帮助你了解当前连接情况。 ## 安全性 MCP 工具可能会访问和操作外部系统,需要注意安全风险。 **审批机制** Kimi Code CLI 对敏感操作(如文件修改、命令执行)会请求用户确认。MCP 工具也遵循同样的审批机制,所有 MCP 工具调用都会弹出确认提示。 **提示词注入风险** MCP 工具返回的内容可能包含恶意指令,试图诱导 AI 执行危险操作。Kimi Code CLI 会对工具返回内容进行标记,帮助 AI 区分工具输出和用户指令,但你仍应: * 只使用可信来源的 MCP 服务器 * 检查 AI 提议的操作是否合理 * 对于高风险操作保持手动审批 ::: warning 注意 在 YOLO 或 AFK 模式下,MCP 工具调用也会被自动批准。仅在完全信任 MCP 服务器时使用这些模式。 ::: --- --- url: /en/customization/plugins.md --- # Plugins (Beta) ::: warning Beta Feature The plugin system is currently in Beta. The implementation details and configuration definitions may change in future releases. Please use with caution in production environments and stay tuned for updates. ::: The plugin system allows you to add custom tools to Kimi Code CLI, extending the AI's capabilities. Unlike MCP servers, plugins are lightweight local toolkits ideal for packaging project-specific scripts and utilities. ## What are plugins A plugin is a directory containing a `plugin.json` file. Plugins can declare multiple "tools," where each tool is an executable command (Python, TypeScript, shell script, etc.) that the AI can invoke to perform specific tasks. For example, you can create a plugin to: * Wrap internal API call scripts * Provide project-specific code generation tools * Integrate with proprietary services or database queries Difference between plugins and Agent Skills: * **Skills**: Provide knowledge-based guidance through `SKILL.md`; the AI reads and follows the specifications * **Plugins**: Declare executable tools through `plugin.json`; the AI can directly invoke tools to get results ## Installing plugins Use the `kimi plugin` command to manage plugins. **Install from a local directory** ```sh kimi plugin install /path/to/my-plugin ``` **Install from a ZIP file** ```sh # Local ZIP file kimi plugin install my-plugin.zip # Remote ZIP URL (including GitHub/GitLab archive download links) kimi plugin install https://example.com/my-plugin.zip kimi plugin install https://github.com/user/repo/archive/refs/heads/main.zip ``` **Install from a Git repository** ```sh # Install the root plugin kimi plugin install https://github.com/user/repo.git # Install a plugin from a subdirectory (multi-plugin repo) kimi plugin install https://github.com/user/repo.git/plugins/my-plugin # Specify a branch (use browser-style GitHub URL without .git) kimi plugin install https://github.com/user/repo/tree/develop/plugins/my-plugin ``` When a Git repository has no `plugin.json` at the root, Kimi Code CLI checks the root and its immediate subdirectories, then lists available plugins for you to choose from. **List installed plugins** ```sh kimi plugin list ``` **View plugin details** ```sh kimi plugin info my-plugin ``` **Remove a plugin** ```sh kimi plugin remove my-plugin ``` ## Creating a plugin Creating a plugin requires three steps: 1. Create a directory 2. Write a `plugin.json` file 3. Implement the tool scripts **Directory structure** ``` my-plugin/ ├── plugin.json # Plugin configuration (required) ├── config.json # Plugin config (optional, for credential injection) └── scripts/ # Tool scripts ├── greet.py └── calc.ts ``` **`plugin.json` format** ```json { "name": "my-plugin", "version": "1.0.0", "description": "My custom plugin for project X", "config_file": "config.json", "inject": { "api_key": "api_key", "endpoint": "base_url" }, "tools": [ { "name": "greet", "description": "Generate a greeting message", "command": ["python3", "scripts/greet.py"], "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "Name to greet" } }, "required": ["name"] } } ] } ``` **Field descriptions** | Field | Description | Required | |-------|-------------|----------| | `name` | Plugin name; lowercase letters, numbers, and hyphens only | Yes | | `version` | Plugin version; semantic version format | Yes | | `description` | Plugin description | No | | `config_file` | Config file path for credential injection | No | | `inject` | Credential injection mapping; key is target path, value is source variable name | No | | `tools` | List of tools | No | **Tool field descriptions** | Field | Description | Required | |-------|-------------|----------| | `name` | Tool name | Yes | | `description` | Tool description | Yes | | `command` | Command to execute; array of strings | Yes | | `parameters` | Parameter definition in JSON Schema format | No | ## Credential injection If your plugin needs to call LLM APIs, you can use the `inject` configuration to automatically receive Kimi Code CLI's credentials. **`inject` configuration example** ```json { "config_file": "config.json", "inject": { "llm.api_key": "api_key", "llm.endpoint": "base_url" } } ``` **Supported injection variables** | Variable | Description | |----------|-------------| | `api_key` | LLM provider API key; supports OAuth tokens and static API keys | | `base_url` | LLM API base URL | **`config.json` template** ```json { "llm": { "api_key": "", "endpoint": "" } } ``` During installation, Kimi Code CLI injects the currently configured API key and base URL into the specified config file. If OAuth is configured, a valid token is automatically obtained and injected. Later, when the application starts, Kimi Code CLI will also try to write the latest credentials (such as the refreshed OAuth token) into the configuration file of the installed plugin. ::: tip Generally, there is no need to reinstall the plugin in order to update credentials: after switching the LLM provider or re-authorizing, restarting Kimi Code CLI will automatically refresh the credentials in the configuration file. The plugin tool will also obtain the currently valid credentials through environment variables when it is actually run. The plugin needs to be reinstalled only when the configuration structure of the plugin itself (such as `config_file` or `inject` mapping) is modified. ::: ::: info About inject keys The keys under `inject` (for example, `llm.api_key`) are also exposed as environment variable names to your plugin tool subprocesses. Because these names contain dots, some runtimes cannot access them using the usual identifier syntax (for example, `$llm.api_key` is not valid in POSIX shells), but you can still read them via map/dictionary access, such as: * **Node.js**: `process.env["llm.api_key"]` * **Python**: `os.environ["llm.api_key"]` If you prefer env-var-friendly names that work smoothly across shells and tooling, consider using keys like `LLM_API_KEY` or `LLM_ENDPOINT` in your own plugins instead of dotted names, and structure your config file accordingly. ::: ## Tool script specification Tool scripts receive parameters via standard input and return results via standard output. **Input format** Scripts receive a JSON object from `stdin`: ```json { "name": "World" } ``` **Output format** Content written to `stdout` by the script is returned to the Agent as a string. If structured output is needed, emitting JSON text is recommended: ```json { "content": "Hello, World!" } ``` **Python example** ```python #!/usr/bin/env python3 import json import sys params = json.load(sys.stdin) name = params.get("name", "Guest") result = {"content": f"Hello, {name}!"} print(json.dumps(result)) ``` **TypeScript example** ```typescript #!/usr/bin/env tsx import * as readline from "readline"; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, }); let input = ""; rl.on("line", (line) => { input += line; }); rl.on("close", () => { const params = JSON.parse(input); const name = params.name || "Guest"; console.log(JSON.stringify({ content: `Hello, ${name}!` })); }); ``` ## Complete example ```json { "name": "sample-plugin", "version": "1.0.0", "description": "Sample plugin demonstrating Skills + Tools", "tools": [ { "name": "py_greet", "description": "Generate a greeting message (Python tool)", "command": ["python3", "scripts/greet.py"], "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "Name to greet" }, "lang": { "type": "string", "enum": ["en", "zh", "ja"], "description": "Language" } }, "required": ["name"] } }, { "name": "ts_calc", "description": "Evaluate a math expression (TypeScript tool)", "command": ["npx", "tsx", "scripts/calc.ts"], "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "Math expression to evaluate" } }, "required": ["expression"] } } ] } ``` ## Plugin installation location Plugins are installed in the `~/.kimi/plugins/` directory. Each plugin is an independent subdirectory containing the complete `plugin.json` and script files. ::: info Note Plugins and MCP servers are complementary extension mechanisms: * **MCP**: Suitable for services that need to run continuously, complex tool orchestration, or cross-process communication * **Plugins**: Suitable for simple script wrappers, project-specific tools, or rapid prototyping ::: --- --- url: /en/customization/print-mode.md --- # Print Mode Print mode lets Kimi Code CLI run non-interactively, suitable for scripting and automation scenarios. ## Basic usage Use the `--print` flag to enable print mode: ```sh # Pass instructions via -p (or -c) kimi --print -p "List all Python files in the current directory" # Pass instructions via stdin echo "Explain what this code does" | kimi --print ``` Print mode characteristics: * **Non-interactive**: Exits automatically after executing instructions * **Auto-approval**: Implicitly enables `--afk` mode, all tool calls are auto-approved, and interactive questions (`AskUserQuestion`) and plan mode switches are also handled automatically * **Text output**: AI responses are output to stdout ## Final message only Use the `--final-message-only` option to only output the final assistant message, skipping intermediate tool call processes: ```sh kimi --print -p "Give me a Git commit message based on the current changes" --final-message-only ``` `--quiet` is a shortcut for `--print --output-format text --final-message-only`, suitable for scenarios where only the final result is needed: ```sh kimi --quiet -p "Give me a Git commit message based on the current changes" ``` ## JSON format Print mode supports JSON format for input and output, convenient for programmatic processing. Both input and output use the [Message](#message-format) format. **JSON output** Use `--output-format=stream-json` to output in JSONL (one JSON per line) format: ```sh kimi --print -p "Hello" --output-format=stream-json ``` Example output: ```jsonl {"role":"assistant","content":"Hello! How can I help you?"} ``` If the AI called tools, assistant messages and tool messages are output sequentially: ```jsonl {"role":"assistant","content":"Let me check the current directory.","tool_calls":[{"type":"function","id":"tc_1","function":{"name":"Shell","arguments":"{\"command\":\"ls\"}"}}]} {"role":"tool","tool_call_id":"tc_1","content":"file1.py\nfile2.py"} {"role":"assistant","content":"There are two Python files in the current directory."} ``` **JSON input** Use `--input-format=stream-json` to receive JSONL format input: ```sh echo '{"role":"user","content":"Hello"}' | kimi --print --input-format=stream-json --output-format=stream-json ``` In this mode, Kimi Code CLI continuously reads from stdin, processing and outputting responses for each user message received until stdin is closed. ## Message format Both input and output use a unified message format. **User message** ```json {"role": "user", "content": "Your question or instruction"} ``` Array-form content is also supported: ```json {"role": "user", "content": [{"type": "text", "text": "Your question"}]} ``` **Assistant message** ```json {"role": "assistant", "content": "Response content"} ``` Assistant message with tool calls: ```json { "role": "assistant", "content": "Let me execute this command.", "tool_calls": [ { "type": "function", "id": "tc_1", "function": { "name": "Shell", "arguments": "{\"command\":\"ls\"}" } } ] } ``` **Tool message** ```json {"role": "tool", "tool_call_id": "tc_1", "content": "Tool execution result"} ``` ## Exit codes Print mode uses exit codes to indicate execution results, allowing scripts and CI systems to determine whether to retry: | Exit code | Meaning | Description | | --- | --- | --- | | `0` | Success | Task completed normally | | `1` | Failure (not retryable) | Configuration errors, authentication failures, quota exhaustion, and other permanent errors | | `75` | Failure (retryable) | 429 rate limits, 5xx server errors, connection timeouts, and other transient errors | Example: decide whether to retry based on exit code: ```sh kimi --print -p "Run task" code=$? if [ $code -eq 75 ]; then echo "Transient error encountered, retrying..." sleep 10 kimi --print -p "Run task" elif [ $code -ne 0 ]; then echo "Unrecoverable error, exit code: $code" exit $code fi ``` ## Use cases **CI/CD integration** Auto-generate code or perform checks in CI workflows: ```sh kimi --print -p "Check if there are any obvious security issues in the src/ directory, output a JSON format report" ``` **Batch processing** Combine with shell loops for batch file processing: ```sh for file in src/*.py; do kimi --print -p "Add type annotations to $file" done ``` **Integration with other tools** Use as a backend for other tools, communicating via JSON format: ```sh my-tool | kimi --print --input-format=stream-json --output-format=stream-json | process-output ``` --- --- url: /zh/customization/print-mode.md --- # Print 模式 Print 模式让 Kimi Code CLI 以非交互方式运行,适合脚本调用和自动化场景。 ## 基本用法 使用 `--print` 参数启用 Print 模式: ```sh # 通过 -p 传入指令(或 -c) kimi --print -p "列出当前目录的所有 Python 文件" # 通过 stdin 传入指令 echo "解释这段代码的作用" | kimi --print ``` Print 模式的特点: * **非交互**:执行完指令后自动退出 * **自动审批**:隐式启用 `--afk` 模式,所有工具调用自动批准,交互式问答(`AskUserQuestion`)和计划模式切换也会自动处理 * **文本输出**:AI 的回复输出到 stdout ## 仅输出最终消息 使用 `--final-message-only` 选项可以只输出最终的 assistant 消息,跳过中间的工具调用过程: ```sh kimi --print -p "根据当前变更给我一个 Git commit message" --final-message-only ``` `--quiet` 是 `--print --output-format text --final-message-only` 的快捷方式,适合只需要最终结果的场景: ```sh kimi --quiet -p "根据当前变更给我一个 Git commit message" ``` ## JSON 格式 Print 模式支持 JSON 格式的输入和输出,方便程序化处理。输入和输出都使用 [Message](#message-格式) 格式。 **JSON 输出** 使用 `--output-format=stream-json` 以 JSONL(每行一个 JSON)格式输出: ```sh kimi --print -p "你好" --output-format=stream-json ``` 输出示例: ```jsonl {"role":"assistant","content":"你好!有什么可以帮助你的吗?"} ``` 如果 AI 调用了工具,会依次输出 assistant 消息和 tool 消息: ```jsonl {"role":"assistant","content":"让我查看一下当前目录。","tool_calls":[{"type":"function","id":"tc_1","function":{"name":"Shell","arguments":"{\"command\":\"ls\"}"}}]} {"role":"tool","tool_call_id":"tc_1","content":"file1.py\nfile2.py"} {"role":"assistant","content":"当前目录有两个 Python 文件。"} ``` **JSON 输入** 使用 `--input-format=stream-json` 接收 JSONL 格式的输入: ```sh echo '{"role":"user","content":"你好"}' | kimi --print --input-format=stream-json --output-format=stream-json ``` 这种模式下,Kimi Code CLI 会持续读取 stdin,每收到一条用户消息就处理并输出响应,直到 stdin 关闭。 ## Message 格式 输入和输出都使用统一的 Message 格式。 **User 消息** ```json {"role": "user", "content": "你的问题或指令"} ``` 也可以使用数组形式的 content: ```json {"role": "user", "content": [{"type": "text", "text": "你的问题"}]} ``` **Assistant 消息** ```json {"role": "assistant", "content": "回复内容"} ``` 带工具调用的助手消息: ```json { "role": "assistant", "content": "让我执行这个命令。", "tool_calls": [ { "type": "function", "id": "tc_1", "function": { "name": "Shell", "arguments": "{\"command\":\"ls\"}" } } ] } ``` **Tool 消息** ```json {"role": "tool", "tool_call_id": "tc_1", "content": "工具执行结果"} ``` ## 退出码 Print 模式使用退出码表示执行结果,方便脚本和 CI 系统判断是否需要重试: | 退出码 | 含义 | 说明 | | --- | --- | --- | | `0` | 成功 | 任务正常完成 | | `1` | 失败(不可重试) | 配置错误、认证失败、额度用尽等永久性错误 | | `75` | 失败(可重试) | 429 速率限制、5xx 服务端错误、连接超时等暂时性错误 | 示例:根据退出码决定是否重试: ```sh kimi --print -p "执行任务" code=$? if [ $code -eq 75 ]; then echo "遇到暂时性错误,稍后重试..." sleep 10 kimi --print -p "执行任务" elif [ $code -ne 0 ]; then echo "遇到不可恢复的错误,退出码: $code" exit $code fi ``` ## 使用场景 **CI/CD 集成** 在 CI 流程中自动生成代码或执行检查: ```sh kimi --print -p "检查 src/ 目录下是否有明显的安全问题,输出 JSON 格式的报告" ``` **批量处理** 结合 shell 循环批量处理文件: ```sh for file in src/*.py; do kimi --print -p "为 $file 添加类型注解" done ``` **与其他工具集成** 作为其他工具的后端,通过 JSON 格式进行通信: ```sh my-tool | kimi --print --input-format=stream-json --output-format=stream-json | process-output ``` --- --- url: /en/configuration/providers.md --- # Providers and Models Kimi Code CLI supports multiple LLM platforms, which can be configured via configuration files or the `/login` command. ## Platform selection The easiest way to configure is to run the `/login` command (alias `/setup`) in shell mode and follow the wizard to select platform and model: 1. Select an API platform 2. Enter your API key 3. Select a model from the available list After configuration, Kimi Code CLI will automatically save settings to `~/.kimi/config.toml` and reload. `/login` currently supports the following platforms: | Platform | Description | | --- | --- | | Kimi Code | Kimi Code platform, supports search and fetch services | | Moonshot AI Open Platform (moonshot.cn) | China region API endpoint | | Moonshot AI Open Platform (moonshot.ai) | Global region API endpoint | For other platforms, please manually edit the configuration file. ## Provider types The `type` field in `providers` configuration specifies the API provider type. Different types use different API protocols and client implementations. | Type | Description | | --- | --- | | `kimi` | Kimi API | | `openai_legacy` | OpenAI Chat Completions API | | `openai_responses` | OpenAI Responses API | | `anthropic` | Anthropic Claude API | | `gemini` | Google Gemini API | | `vertexai` | Google Vertex AI | All provider types support adding custom HTTP headers via the `custom_headers` field. See [Configuration files](./config-files.md) for details. ### `kimi` For connecting to Kimi API, including Kimi Code and Moonshot AI Open Platform. ```toml [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-xxx" ``` ### `openai_legacy` For platforms compatible with OpenAI Chat Completions API, including the official OpenAI API and various compatible services. ```toml [providers.openai] type = "openai_legacy" base_url = "https://api.openai.com/v1" api_key = "sk-xxx" ``` ### `openai_responses` For OpenAI Responses API (newer API format). ```toml [providers.openai-responses] type = "openai_responses" base_url = "https://api.openai.com/v1" api_key = "sk-xxx" ``` ### `anthropic` For connecting to Anthropic Claude API. ```toml [providers.anthropic] type = "anthropic" base_url = "https://api.anthropic.com" api_key = "sk-ant-xxx" ``` ### `gemini` For connecting to Google Gemini API. ```toml [providers.gemini] type = "gemini" base_url = "https://generativelanguage.googleapis.com" api_key = "xxx" ``` ### `vertexai` For connecting to Google Vertex AI. Requires setting necessary environment variables via the `env` field. ```toml [providers.vertexai] type = "vertexai" base_url = "https://xxx-aiplatform.googleapis.com" api_key = "" env = { GOOGLE_CLOUD_PROJECT = "your-project-id" } ``` ## Model capabilities The `capabilities` field in model configuration declares the capabilities supported by the model. This affects feature availability in Kimi Code CLI. | Capability | Description | | --- | --- | | `thinking` | Supports thinking mode (deep reasoning), can be toggled | | `always_thinking` | Always uses thinking mode (cannot be disabled) | | `image_in` | Supports image input | | `video_in` | Supports video input | ```toml [models.gemini-3-pro-preview] provider = "gemini" model = "gemini-3-pro-preview" max_context_size = 262144 capabilities = ["thinking", "image_in"] ``` ### `thinking` Declares that the model supports thinking mode. When enabled, the model performs deeper reasoning before answering, suitable for complex problems. In shell mode, you can use the `/model` command to switch models and thinking mode, or control it at startup with `--thinking` / `--no-thinking` flags. ### `always_thinking` Indicates the model always uses thinking mode and cannot be disabled. For example, models with "thinking" in their name like `kimi-k2-thinking-turbo` typically have this capability. When using such models, the `/model` command won't prompt for thinking mode toggle. ### `image_in` When image input capability is enabled, you can paste images in conversations (`Ctrl-V`). ### `video_in` When video input capability is enabled, you can send video content in conversations. ## Search and fetch services The `SearchWeb` and `FetchURL` tools depend on external services, currently only provided by the Kimi Code platform. When selecting the Kimi Code platform using `/login`, search and fetch services are automatically configured. | Service | Corresponding tool | Behavior when not configured | | --- | --- | --- | | `moonshot_search` | `SearchWeb` | Tool unavailable | | `moonshot_fetch` | `FetchURL` | Falls back to local fetching | When using other platforms, the `FetchURL` tool is still available but will fall back to local fetching. --- --- url: /en/guides/sessions.md --- # Sessions and Context Kimi Code CLI automatically saves your conversation history, allowing you to continue previous work at any time. ## Session resuming Each time you start Kimi Code CLI, a new session is created. While running, you can also enter the `/new` command to create and switch to a new session at any time, without exiting the program. If you want to continue a previous conversation, there are several ways: **Continue the most recent session** Use the `--continue` flag to continue the most recent session in the current working directory: ```sh kimi --continue ``` **Interactively pick a session** Use `--session` (or `--resume`, `-S`, `-r`) without an argument to open an interactive session picker, where you can use arrow keys to select the session to resume: ```sh kimi --session ``` > The interactive picker is only available in shell mode. **Resume a specific session** Use `--session` (or `--resume`) with a session ID to resume that specific session: ```sh kimi -r abc123 ``` If the specified session ID does not exist, a new session is created automatically. **Switch sessions during runtime** Enter `/sessions` (or `/resume`) to view all sessions in the current working directory, and use arrow keys to select the session you want to switch to: ``` /sessions ``` The list shows each session's title and last update time, helping you find the conversation you want to continue. Press `Ctrl-A` to toggle between showing sessions for the current directory only or across all directories, making it easy to find sessions across projects. Use `/title ` to set a custom title for the session, making it easier to find later. **Resume hint on exit** When a session exits — whether through normal exit, `Ctrl-C` interruption, `/undo`, `/fork`, `/sessions` switch, or other scenarios — Kimi Code CLI automatically prints a resume command hint: ``` To resume this session: kimi -r ``` You can copy this command directly and run it in your terminal next time to quickly resume the session. Empty sessions do not show this hint. **Startup replay** When you continue an existing session, Kimi Code CLI will replay the previous conversation history so you can quickly understand the context. During replay, previous messages and AI responses will be displayed. ## Session state persistence In addition to conversation history, Kimi Code CLI also automatically saves and restores the session's runtime state. When you resume a session, the following states are automatically restored: * **Approval decisions**: YOLO and AFK mode on/off status, operation types approved via "allow for this session" * **Plan mode**: Plan mode on/off status * **Subagent instances**: Subagent instance state and context history created via the `Agent` tool during the session * **Additional directories**: Workspace directories added via `--add-dir` or `/add-dir` This means you don't need to reconfigure these settings each time you resume a session. For example, if you approved auto-execution of certain shell commands in your previous session, those approvals remain in effect after resuming. ## Export and import Kimi Code CLI supports exporting session context to a file, or importing context from external files and other sessions. **Export a session** Enter `/export` to export the current session's complete conversation history as a Markdown file: ``` /export ``` The exported file includes session metadata, a conversation overview, and the complete conversation organized by turns. You can also specify an output path: ``` /export ~/exports/my-session.md ``` **Import context** Enter `/import` to import context from a file or another session. The imported content is appended as reference information to the current session: ``` /import ./previous-session-export.md /import abc12345 ``` Common text-based file formats are supported (Markdown, source code, configuration files, etc.). You can also pass a session ID to import the complete conversation history from that session. ::: tip Exported files may contain sensitive information (such as code snippets, file paths, etc.). Please review before sharing. ::: ## Clear and compact As the conversation progresses, the context grows longer. Kimi Code CLI will automatically compress the context when needed to ensure the conversation can continue. You can also manually manage the context using slash commands: **Clear context** Enter `/clear` to clear all context in the current session and start a fresh conversation: ``` /clear ``` After clearing, the AI will forget all previous conversation content. You usually don't need to use this command; for new tasks, starting a new session is a better choice. **Compact context** Enter `/compact` to have the AI summarize the current conversation and replace the original context with the summary: ``` /compact ``` You can also append custom instructions after the command to tell the AI what content to prioritize preserving during compaction: ``` /compact keep the database-related discussion ``` Compacting preserves key information while reducing token consumption. This is useful when the conversation is long but you still want to retain some context. ::: tip The bottom status bar displays the current context usage with token counts (e.g., `context: 42.0% (4.2k/10.0k)`), helping you understand when you need to clear or compact. ::: ::: tip `/clear` and `/reset` clear the conversation context but do not reset session state (such as approval decisions, dynamic subagents, and additional directories). To start completely fresh, it's recommended to create a new session. ::: --- --- url: /en/reference/slash-commands.md --- # Slash Commands Slash commands are built-in commands for Kimi Code CLI, used to control sessions, configuration, and debugging. Enter a command starting with `/` in the input box to trigger. ::: tip Shell mode Some slash commands are also available in shell mode, including `/help`, `/exit`, `/version`, `/editor`, `/theme`, `/changelog`, `/feedback`, `/export`, `/import`, and `/task`. ::: ## Help and info ### `/help` Display help information. Shows keyboard shortcuts, all available slash commands, and loaded skills in a fullscreen pager. Press `q` to exit. Aliases: `/h`, `/?` ### `/version` Display Kimi Code CLI version number. ### `/changelog` Display the changelog for recent versions. Alias: `/release-notes` ### `/feedback` Submit feedback to help improve Kimi Code CLI. You will be prompted to enter your feedback and submit it. If the network request fails or times out, the command automatically falls back to opening the GitHub Issues page. ## Account and configuration ### `/login` Log in or configure an API platform. After execution, first select a platform: * **Kimi Code**: Automatically opens a browser for OAuth authorization * **Other platforms**: Enter an API key, then select an available model After configuration, settings are automatically saved to `~/.kimi/config.toml` and reloaded. See [Providers](../configuration/providers.md) for details. Alias: `/setup` ::: tip This command is only available when using the default configuration file. If a configuration was specified via `--config` or `--config-file`, this command cannot be used. ::: ### `/logout` Log out from the current platform. This clears stored credentials and removes related configuration from the config file. After logout, Kimi Code CLI will automatically reload the configuration. ### `/model` Switch models and thinking mode. This command first refreshes the available models list from the API platform. When called without arguments, displays an interactive selection interface where you first select a model, then choose whether to enable thinking mode (if the model supports it). After selection, Kimi Code CLI will automatically update the configuration file and reload. ::: tip This command is only available when using the default configuration file. If a configuration was specified via `--config` or `--config-file`, this command cannot be used. ::: ### `/editor` Set the external editor. When called without arguments, displays an interactive selection interface; you can also specify the editor command directly, e.g., `/editor vim`. After configuration, pressing `Ctrl-O` will open this editor to edit the current input content. See [Keyboard shortcuts](./keyboard.md#external-editor) for details. ### `/theme` Switch the terminal color theme. Kimi Code CLI provides dark and light color palettes, defaulting to dark. Usage: * `/theme`: Show the current theme * `/theme dark`: Switch to dark theme * `/theme light`: Switch to light theme After switching, the configuration is saved to `config.toml` and the shell reloads automatically. The light theme adjusts colors for diff highlights, the task browser, the prompt completion menu, the bottom toolbar, and MCP status indicators to work well on light terminal backgrounds. You can also set `theme = "light"` directly in your config file — see [Config files](../configuration/config-files.md). ### `/reload` Reload the configuration file without exiting Kimi Code CLI. ### `/debug` Display debug information for the current context, including: * Number of messages and tokens * Number of checkpoints * Complete message history Debug information is displayed in a pager, press `q` to exit. ### `/usage` Display API usage and quota information, showing quota usage with progress bars and remaining percentages. Alias: `/status` ::: tip This command only works with the Kimi Code platform. ::: ### `/mcp` Display currently connected MCP servers and loaded tools. See [Model Context Protocol](../customization/mcp.md) for details. Output includes: * Server connection status (green indicates connected) * List of tools provided by each server ### `/hooks` Display currently configured hooks. See [Hooks](../customization/hooks.md) for details. Output includes: * Event types and counts of configured hooks * Help message (if no hooks are configured) ## Session management ### `/new` Create a new session and switch to it immediately, without exiting Kimi Code CLI. If the current session has no content, the empty session directory is automatically cleaned up. ### `/sessions` List all sessions in the current working directory, allowing switching to other sessions. Alias: `/resume` Use arrow keys to select a session, press `Enter` to confirm switch, press `Ctrl-C` to cancel. Press `Ctrl-A` to toggle between showing sessions for the current directory only or across all directories. ### `/title` View or set the current session title. The configured title is shown in the `/sessions` list, making it easier to identify and find sessions. Alias: `/rename` Usage: * `/title`: Show the current session title * `/title `: Set the session title (max 200 characters) After the first conversation turn, the title is automatically derived from the user message; once manually set with this command, auto-generation will no longer overwrite it. ### `/undo` Roll back to a previous turn and retry. An interactive selector shows all historical turns with the user message (truncated to 80 characters). After selecting a turn, Kimi Code CLI forks a new session containing all conversation history **before** that turn and pre-fills the selected turn's user message into the input box for re-editing. The original session is always preserved. Use arrow keys to navigate, `Enter` to confirm, `Ctrl-C` to cancel. ::: tip Use case When the API returns a truncated or malformed response that breaks the session, use `/undo` to roll back to a turn before the problem and retry without abandoning the entire session. ::: ### `/fork` Fork a new session from the current one, copying the entire conversation history. The original session remains unchanged, and the new session becomes the active session. Useful when you want to branch out and try a different direction from the current state. ### `/export` Export the current session context to a Markdown file for archiving or sharing. Usage: * `/export`: Export to the current working directory with an auto-generated filename (format: `kimi-export--.md`) * `/export `: Export to the specified path. If the path is a directory, the filename is auto-generated; if it is a file path, the content is written directly to that file The exported file includes: * Session metadata (session ID, export time, working directory, message count, token count) * Conversation overview (topic, number of turns, tool call count) * Complete conversation history organized by turns, including user messages, AI responses, tool calls, and tool results ### `/import` Import context from a file or another session into the current session. The imported content is appended as reference context, and the AI can use this information to inform subsequent interactions. Usage: * `/import `: Import from a file. Supports common text-based formats such as Markdown, plain text, source code, and configuration files; binary files (e.g., images, PDFs, archives) are not supported * `/import `: Import from the specified session ID. Cannot import the current session into itself ### `/clear` Clear the current session's context and start a new conversation. Alias: `/reset` ### `/compact` Manually compact the context to reduce token usage. You can append custom instructions after the command to tell the AI which information to prioritize preserving during compaction, e.g., `/compact preserve database-related discussions`. When the context is too long, Kimi Code CLI will automatically trigger compaction. This command allows manually triggering the compaction process. ## Skills ### `/skill:` Load a specific skill, sending the `SKILL.md` content to the Agent as a prompt. This command works for both standard skills and flow skills. For example: * `/skill:code-style`: Load code style guidelines * `/skill:pptx`: Load PPT creation workflow * `/skill:git-commits fix user login issue`: Load the skill with an additional task description You can append additional text after the command, which will be added to the skill prompt. See [Agent Skills](../customization/skills.md) for details. ::: tip Flow skills can also be invoked via `/skill:`, which loads the content as a standard skill without automatically executing the flow. To execute the flow, use `/flow:` instead. ::: ### `/flow:` Execute a specific flow skill. Flow skills embed an Agent Flow diagram in `SKILL.md`. After execution, the Agent will start from the `BEGIN` node and process each node according to the flow diagram definition until reaching the `END` node. For example: * `/flow:pull-request`: Execute the pull-request creation workflow * `/flow:code-review`: Execute a code review workflow ::: tip Flow skills can also be invoked via `/skill:`, which loads the content as a standard skill without automatically executing the flow. ::: See [Agent Skills](../customization/skills.md#flow-skills) for details. ## Workspace ### `/add-dir` Add an additional directory to the workspace scope. Once added, the directory is accessible to all file tools (`ReadFile`, `WriteFile`, `Glob`, `Grep`, `StrReplaceFile`, etc.) and its directory listing is shown in the system prompt. Added directories are persisted with the session state and automatically restored when resuming. Usage: * `/add-dir `: Add the specified directory to the workspace * `/add-dir`: Without arguments, list already added additional directories ::: tip Directories already within the working directory do not need to be added, as they are already accessible. You can also add directories at startup via the `--add-dir` option. See [`kimi` command](./kimi-command.md#working-directory) for details. ::: ## Others ### `/btw` Ask a quick side question without interrupting the main conversation. Available both when idle and during streaming. Usage: `/btw ` The side question runs in an isolated context: it sees the conversation history but does not modify it. Tool calls are disabled — the response is text-only, based on the model's existing knowledge of the conversation. During streaming, the response appears in a scrollable modal panel overlaying the prompt area. Use `↑`/`↓` to scroll, `Escape` to dismiss. ::: tip This command is only available in interactive shell mode. Wire and ACP clients can use the `BtwBegin`/`BtwEnd` wire events with the `run_side_question()` API. ::: ### `/init` Analyze the current project and generate an `AGENTS.md` file. This command starts a temporary sub-session to analyze the codebase structure and generate a project description document, helping the Agent better understand the project. ### `/plan` Toggle plan mode. In plan mode, the AI can only use read-only tools to explore the codebase, writing an implementation plan to a plan file and submitting it for your approval. See [Plan mode](../guides/interaction.md#plan-mode) for details. Usage: * `/plan`: Toggle plan mode * `/plan on`: Enable plan mode * `/plan off`: Disable plan mode * `/plan view`: View the current plan content * `/plan clear`: Clear the current plan file When plan mode is enabled, the prompt changes to `📋` and a blue `plan` badge appears in the status bar. ### `/task` Open the interactive task browser to view, monitor, and manage background tasks. The task browser is a three-column TUI: * **Left column**: Task list showing task ID, status, and description * **Middle column**: Detailed information for the selected task, including ID, status, description, timestamps, exit code, etc. * **Right column**: Output preview showing the last few lines Supported keyboard shortcuts: | Shortcut | Action | |----------|--------| | `Enter` / `O` | View the selected task's full output in a pager | | `S` | Request to stop the selected task (requires confirmation) | | `Tab` | Toggle filter mode (all / active tasks only) | | `R` | Refresh the task list | | `Q` / `Esc` | Exit the browser | The task browser automatically refreshes every second, showing real-time task status changes. ::: tip Background tasks are started by the AI using the `Shell` tool with `run_in_background=true`. The system automatically notifies the AI when background tasks complete. ::: ### `/yolo` Toggle YOLO mode. When enabled, all tool calls are automatically approved and a yellow YOLO badge appears in the status bar; enter the command again to disable. YOLO only removes approval friction — the agent can still reach you via `AskUserQuestion`. `/yolo` and `/afk` are independent. ::: warning Note YOLO mode skips all approval confirmations. Make sure you understand the potential risks. ::: ### `/afk` Toggle AFK (away-from-keyboard) mode. When enabled, AFK auto-approves all tool calls and additionally auto-dismisses any `AskUserQuestion` the agent sends — so the agent makes its own judgment instead of waiting for a reply that will not come. An orange AFK badge appears in the status bar independently of the YOLO badge; enter the command again to disable. ::: warning Note AFK skips all approval confirmations and removes the clarifying-question safety net. Only use when you genuinely cannot be at the terminal. ::: ### `/web` Switch to Web UI. Kimi Code CLI will start a Web UI server and open the current session in your browser, allowing you to continue the conversation in the Web UI. See [Web UI](./kimi-web.md) for details. ### `/vis` Switch to the Agent Tracing Visualizer. Kimi Code CLI will start the visualizer server and open the current session's tracing view in the browser, where you can inspect Wire event timelines, context messages, and usage statistics. See [Agent Tracing Visualizer](./kimi-vis.md) for details. ### `/upgrade` Install the new Kimi Code — the faster, more powerful successor. Running it shows the install command and asks whether to install immediately: * Install now: Kimi Code CLI runs the install script, and your existing config and sessions are migrated automatically * Install later: only the install command is shown so you can run it manually After installation, open a new terminal and run `kimi` to start the new Kimi Code. ::: tip Note This command is only available in interactive shell mode. ::: ## Command completion After typing `/` in the input box, a list of available commands is automatically displayed. Continue typing to filter commands with fuzzy matching support, press Enter to select. For example, typing `/ses` will match `/sessions`, and `/clog` will match `/changelog`. Command aliases are also supported, such as typing `/h` to match `/help`. --- --- url: /en.md --- > **Kimi CLI has been archived and is no longer maintained.** It has been replaced by [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code), the next-generation terminal AI agent from the same team. Existing installations will stop working, so please migrate as soon as possible. Your config and sessions can be migrated automatically; see the [migration guide](https://moonshotai.github.io/kimi-code/en/guides/migration). --- --- url: /zh.md --- > **Kimi CLI 已归档,不再维护**。它已由同一团队打造的新一代终端 AI Agent [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code) 取代。已安装的旧版将无法继续使用,请尽快迁移,配置与会话可以自动迁移,详见 [迁移指南](https://moonshotai.github.io/kimi-code/zh/guides/migration)。 --- --- url: /en/guides/ides.md --- # Using in IDEs Kimi Code CLI supports integration with IDEs through the [Agent Client Protocol (ACP)](https://agentclientprotocol.com/), allowing you to use AI-assisted programming directly within your editor. ## Prerequisites Before configuring your IDE, make sure you have installed Kimi Code CLI and completed the `/login` configuration. ## Using in Zed [Zed](https://zed.dev/) is a modern IDE that supports ACP. Add the following to Zed's configuration file `~/.config/zed/settings.json`: ```json { "agent_servers": { "Kimi Code CLI": { "type": "custom", "command": "kimi", "args": ["acp"], "env": {} } } } ``` Configuration notes: * `type`: Fixed value `"custom"` * `command`: Path to the Kimi Code CLI command. If `kimi` is not in PATH, use the full path * `args`: Startup arguments. `acp` enables ACP mode * `env`: Environment variables, usually left empty After saving the configuration, you can create Kimi Code CLI sessions in Zed's Agent panel. ## Using in JetBrains IDEs JetBrains IDEs (IntelliJ IDEA, PyCharm, WebStorm, etc.) support ACP through the AI Chat plugin. If you don't have a JetBrains AI subscription, you can enable `llm.enable.mock.response` in the Registry to use the AI Chat feature. Press Shift twice to search for "Registry" to open it. In the AI Chat panel menu, click "Configure ACP agents" and add the following configuration: ```json { "agent_servers": { "Kimi Code CLI": { "command": "~/.local/bin/kimi", "args": ["acp"], "env": {} } } } ``` `command` needs to be the full path. You can run `which kimi` in the terminal to get it. After saving, you can select Kimi Code CLI in the AI Chat Agent selector. --- --- url: /en/reference/kimi-web.md --- # Web UI Web UI provides a browser-based interactive interface, allowing you to use all features of Kimi Code CLI in a web page. Compared to the terminal interface, Web UI offers a richer visual experience, more flexible session management, and more convenient file operations. ## Starting Web UI Run the `kimi web` command in your terminal to start the Web UI server: ```sh kimi web ``` After the server starts, it will automatically open your browser to access the Web UI. The default address is `http://127.0.0.1:5494`. If the default port is occupied, the server will automatically try the next available port (default range `5494`–`5503`) and print the access address in the terminal. ## Command line options ### Network configuration | Option | Short | Description | |--------|-------|-------------| | `--host TEXT` | `-h` | Bind to specific IP address | | `--network` | `-n` | Enable network access (bind to `0.0.0.0`) | | `--port INTEGER` | `-p` | Specify port number (default: `5494`) | By default, Web UI only listens on the local loopback address `127.0.0.1`, allowing access only from the local machine. If you want to access Web UI from a local network or the public internet, you can use the `--network` option or specify `--host`: ```sh # Bind to all network interfaces, allowing LAN access kimi web --network # Bind to a specific IP address kimi web --host 192.168.1.100 ``` ::: warning Note When enabling network access, be sure to configure access control options (such as `--auth-token` and `--lan-only`) to ensure security. See [Access control](#access-control). ::: ### Browser control | Option | Description | |--------|-------------| | `--open / --no-open` | Automatically open browser on startup (default: `--open`) | Use `--no-open` to prevent automatically opening the browser: ```sh kimi web --no-open ``` ### Development options | Option | Description | |--------|-------------| | `--reload` | Enable auto-reload (for development) | Use `--reload` to automatically restart the server after code changes: ```sh kimi web --reload ``` ::: info Note The `--reload` option is only for development purposes and is not needed for daily use. ::: ### Access control Web UI provides multi-layer access control mechanisms to ensure service security. | Option | Description | |--------|-------------| | `--auth-token TEXT` | Set Bearer Token for API authentication | | `--allowed-origins TEXT` | Set allowed Origin list (comma-separated) | | `--lan-only / --public` | Only allow LAN access (default) or allow public access | | `--restrict-sensitive-apis / --no-restrict-sensitive-apis` | Restrict sensitive API access (config write, open-in, file access limits) | | `--dangerously-omit-auth` | Disable authentication checks (dangerous, trusted networks only) | ::: info Added Access control options added in version 1.6. ::: #### Access token authentication Use `--auth-token` to set an access token. Clients need to include `Authorization: Bearer ` in the HTTP request header to access the API: ```sh kimi web --network --auth-token my-secret-token ``` ::: tip The access token should be a randomly generated string with at least 32 characters. You can use `openssl rand -hex 32` to generate a random token. ::: #### Origin checking Use `--allowed-origins` to restrict the origin domains that can access Web UI: ```sh kimi web --network --allowed-origins "https://example.com,https://app.example.com" ``` ::: tip When using `--network` or `--host` to enable network access, it is recommended to configure `--allowed-origins` to prevent Cross-Site Request Forgery (CSRF) attacks. ::: #### Network access scope By default, Web UI uses `--lan-only` mode, only allowing access from the local network (private IP address ranges). If you need to allow public access, use the `--public` option: ```sh kimi web --network --public --auth-token my-secret-token ``` ::: danger Warning Using the `--public` option will allow access from any IP address. Be sure to configure `--auth-token` and `--allowed-origins` to ensure security. ::: #### Restricting sensitive APIs Use `--restrict-sensitive-apis` to disable some sensitive API features: * Config file writing * Open-in functionality (opening local files, directories, applications) * File access restrictions ```sh kimi web --network --restrict-sensitive-apis ``` In `--public` mode, `--restrict-sensitive-apis` is enabled by default; in `--lan-only` mode (default), it is not enabled. ::: tip When you need to expose Web UI to untrusted network environments, it is recommended to enable the `--restrict-sensitive-apis` option. ::: #### Disabling authentication (not recommended) In trusted private network environments, you can use `--dangerously-omit-auth` to skip all authentication checks: ```sh kimi web --dangerously-omit-auth ``` ::: danger Warning The `--dangerously-omit-auth` option completely disables authentication and access control. It should only be used in fully trusted network environments (such as offline local development environments). Do not use this option on the public internet or untrusted local networks. ::: ## Switching from terminal to Web UI If you are using Kimi Code CLI in shell mode in the terminal, you can enter the `/web` command to quickly switch to Web UI: ``` /web ``` After execution, Kimi Code CLI will automatically start the Web UI server and open the current session in the browser. You can continue the conversation in Web UI, and the session history will remain synchronized. ## Web UI features ### Session management Web UI provides a convenient session management interface: * **Session list**: View all historical sessions, including session title and working directory * **Session search**: Quickly filter sessions by title or working directory * **Create session**: Create a new session with a specified working directory; if the specified path doesn't exist, you will be prompted to confirm creating the directory. Supports Cmd/Ctrl+Click on new-session buttons to open session creation in a new tab * **Switch session**: Switch to different sessions with one click * **Session fork**: Create a branching session from any assistant response, exploring different directions without affecting the original session * **Session archive**: Sessions older than 15 days are automatically archived. You can also archive manually. Archived sessions don't appear in the main list but can be unarchived at any time * **Bulk operations**: Bulk archive, unarchive, or delete sessions in multi-select mode ::: info Added Session search feature added in version 1.5. Directory auto-creation prompt added in version 1.7. Session fork, archive, and bulk operations added in version 1.9. ::: ### Prompt toolbar Web UI provides a unified prompt toolbar above the input box, displaying various information in collapsible tabs: * **Context usage**: Shows the current context usage percentage. Hover to view detailed token usage breakdown (including input/output tokens, cache read/write, etc.) * **Activity status**: Shows the current agent state (processing, waiting for approval, etc.) * **Message queue**: Queue follow-up messages while the AI is processing; queued messages are sent automatically when the current response completes * **File changes**: Detects Git repository status, showing the number of new, modified, and deleted files (including untracked files). Click to view a detailed list of changes * **Todo list**: When the `SetTodoList` tool is active, shows task progress with support for expanding to view the detailed list * **Plan mode**: Toggle plan mode on/off from the input toolbar. When plan mode is active, the composer displays a dashed blue border. Plan mode can also be set programmatically via the `set_plan_mode` Wire protocol method ::: info Changed Git diff status bar added in version 1.5. Activity status indicator added in version 1.9. Version 1.10 unified it into the prompt toolbar. Version 1.11 moved the context usage indicator to the prompt toolbar. Plan mode toggle added in version 1.20. ::: ### Open-in functionality Web UI supports opening files or directories in local applications: * **Open in Terminal**: Open directory in terminal * **Open in VS Code**: Open file or directory in VS Code * **Open in Cursor**: Open file or directory in Cursor * **Open in System**: Open with system default application ::: info Added Open-in functionality added in version 1.5. ::: ::: warning Note Open-in functionality requires browser support for Custom Protocol Handler. This feature is disabled when using the `--restrict-sensitive-apis` option. ::: ### Slash commands Web UI supports slash commands. Type `/` in the input box to open the command menu: * **Autocomplete**: Filter matching commands as you type * **Keyboard navigation**: Use up/down arrow keys to select commands, Enter to confirm * **Alias support**: Support command alias matching, e.g., `/h` matches `/help` ### File mentions Web UI supports file mentions. Type `@` in the input box to open the file mention menu, allowing you to reference files in your conversation: * **Uploaded attachments**: Mention files attached to the current message * **Workspace files**: Mention existing files in the current session's working directory * **Autocomplete**: Filter matching files by name or path as you type * **Keyboard navigation**: Use up/down arrow keys to select files, Enter or Tab to confirm, Escape to cancel ### Message actions Assistant messages provide the following action buttons: * **Copy**: Copy message content to clipboard with one click * **Fork**: Create a branching session from the current response ::: info Added Copy and fork buttons added in version 1.10. ::: ### Structured questions When the AI uses the `AskUserQuestion` tool, Web UI displays a structured question dialog in the chat area, replacing the input box at the bottom. The question dialog shows the question description and available options, supporting single-select, multi-select, and custom text input. When the AI asks multiple questions at once, the dialog shows a tab bar at the top listing all questions, with support for click navigation, keyboard navigation, and restoring previous selections when revisiting answered questions. After answering all questions, the dialog closes automatically and the AI continues execution based on your choices. ::: info Added Structured questions added in version 1.14. ::: ### Approval keyboard shortcuts When the agent sends an approval request, you can use keyboard shortcuts to respond quickly: | Shortcut | Action | |----------|--------| | `1` | Approve | | `2` | Approve for session | | `3` | Decline | | `4` | Decline with feedback | Press `4` to enter feedback mode, where you can type a reason for declining or instructions on how the agent should adjust, then press Enter to submit. The feedback text is passed to the agent to guide its next attempt. When an approval request originates from a subagent, the dialog shows a source label (e.g. "coder agent") so you know which agent initiated the request. ::: info Added Approval keyboard shortcuts added in version 1.10. Feedback mode added in version 1.25. ::: ### Tool output Web UI provides rich display for tool call output: * **Media preview**: Images and videos read by the `ReadMediaFile` tool are displayed as clickable thumbnails * **Shell commands**: `Shell` tool commands and output are rendered with dedicated components * **Todo list**: `SetTodoList` tool items are displayed as a structured list * **Tool input parameters**: Redesigned tool input UI with expandable parameter details and syntax highlighting for long values * **Context compaction**: A compaction indicator is shown when context compaction is in progress * **Quick URL open**: The URL parameter of the `FetchURL` tool supports Cmd/Ctrl+Click to open the link in a new tab * **Subagent origin indicators**: Tool calls originating from a subagent are rendered with a left border and a source type label (e.g. "coder agent") for clearer attribution; subagent activity panels display the specific agent type (e.g. "Coder agent working") instead of a generic label ::: info Added Media preview, shell command, and todo list display components added in version 1.9. Quick URL open added in version 1.14. Subagent origin indicators added in version 1.25. ::: ### Rich media support Web UI supports viewing and pasting various types of rich media content: * **Images**: Display images directly in the chat interface * **Code highlighting**: Automatic code block recognition and highlighting * **Markdown rendering**: Support for full Markdown syntax ### Responsive layout Web UI uses responsive design and displays well on screens of different sizes: * Desktop: Sidebar + main content area layout * Mobile: Collapsible drawer-style sidebar ::: info Changed Responsive layout improved in version 1.6 with enhanced hover effects and better layout handling. ::: ### URL action parameters Web UI supports URL parameters to trigger specific actions, making it easy to integrate from external tools or scripts: | Parameter | Description | |-----------|-------------| | `?action=create` | Open the create-session dialog | | `?action=create-in-dir&workDir=` | Directly create a session in the specified working directory | Examples: ``` http://127.0.0.1:5494?action=create http://127.0.0.1:5494?action=create-in-dir&workDir=/path/to/project ``` ## Examples ### Local use The simplest usage, accessible only from the local machine: ```sh kimi web ``` ### LAN sharing Share Web UI on the local network with access token protection: ```sh kimi web --network --auth-token $(openssl rand -hex 32) ``` After execution, the terminal will display the access address and token. Other devices can access through that address and enter the token in the browser for authentication. ### Public access Deploy Web UI in a public internet environment (requires careful security configuration): ```sh kimi web \ --host 0.0.0.0 \ --public \ --auth-token $(openssl rand -hex 32) \ --allowed-origins "https://yourdomain.com" \ --restrict-sensitive-apis ``` ### Development Enable auto-reload for development purposes: ```sh kimi web --reload --no-open ``` ## Technical details Web UI is built on the following technologies: * **Backend**: FastAPI + WebSocket * **Frontend**: React + TypeScript + Vite * **API protocol**: Complies with OpenAPI specification, see `web/openapi.json` Web UI communicates with Kimi Code CLI's Wire mode via WebSocket, enabling real-time bidirectional data transmission. --- --- url: /zh/reference/kimi-web.md --- # Web UI Web UI 提供了基于浏览器的交互界面,让你可以在网页中使用 Kimi Code CLI 的所有功能。相比终端界面,Web UI 提供了更丰富的视觉体验、更灵活的会话管理以及更便捷的文件操作。 ## 启动 Web UI 在终端中运行 `kimi web` 命令启动 Web UI 服务器: ```sh kimi web ``` 服务器启动后会自动打开浏览器访问 Web UI。默认地址为 `http://127.0.0.1:5494`。 如果默认端口被占用,服务器会自动尝试下一个可用端口(默认范围 `5494`–`5503`),并在终端打印访问地址。 ## 命令行选项 ### 网络配置 | 选项 | 简写 | 说明 | |------|------|------| | `--host TEXT` | `-h` | 绑定到指定的 IP 地址 | | `--network` | `-n` | 启用网络访问(绑定到 `0.0.0.0`) | | `--port INTEGER` | `-p` | 指定端口号(默认:`5494`) | 默认情况下,Web UI 只监听本地回环地址 `127.0.0.1`,仅允许本机访问。 如果你想在局域网或公网中访问 Web UI,可以使用 `--network` 选项或指定 `--host`: ```sh # 绑定到所有网络接口,允许局域网访问 kimi web --network # 绑定到指定 IP 地址 kimi web --host 192.168.1.100 ``` ::: warning 注意 当启用网络访问时,请务必配置访问控制选项(如 `--auth-token` 和 `--lan-only`)以确保安全。详见 [访问控制](#访问控制)。 ::: ### 浏览器控制 | 选项 | 说明 | |------|------| | `--open / --no-open` | 启动时自动打开浏览器(默认:`--open`) | 使用 `--no-open` 可以禁止自动打开浏览器: ```sh kimi web --no-open ``` ### 开发选项 | 选项 | 说明 | |------|------| | `--reload` | 启用自动重载(用于开发调试) | 使用 `--reload` 可以在代码修改后自动重启服务器: ```sh kimi web --reload ``` ::: info 说明 `--reload` 选项仅用于开发调试,日常使用不需要启用。 ::: ### 访问控制 Web UI 提供了多层访问控制机制,确保服务的安全性。 | 选项 | 说明 | |------|------| | `--auth-token TEXT` | 设置 Bearer Token 用于 API 认证 | | `--allowed-origins TEXT` | 设置允许的 Origin 列表(逗号分隔) | | `--lan-only / --public` | 仅允许局域网访问(默认)或允许公网访问 | | `--restrict-sensitive-apis / --no-restrict-sensitive-apis` | 限制敏感 API 访问(配置写入、open-in、文件访问限制) | | `--dangerously-omit-auth` | 禁用认证检查(危险,仅限受信任的网络环境) | ::: info 新增 访问控制选项新增于 1.6 版本。 ::: #### 访问令牌认证 使用 `--auth-token` 可以设置访问令牌,客户端需要在 HTTP 请求头中携带 `Authorization: Bearer ` 才能访问 API: ```sh kimi web --network --auth-token my-secret-token ``` ::: tip 提示 访问令牌应该是一个随机生成的字符串,建议至少包含 32 个字符。可以使用 `openssl rand -hex 32` 生成随机令牌。 ::: #### Origin 检查 使用 `--allowed-origins` 可以限制允许访问 Web UI 的来源域名: ```sh kimi web --network --allowed-origins "https://example.com,https://app.example.com" ``` ::: tip 提示 当使用 `--network` 或 `--host` 启用网络访问时,建议配置 `--allowed-origins` 以防止跨站请求伪造(CSRF)攻击。 ::: #### 网络访问范围 默认情况下,Web UI 使用 `--lan-only` 模式,只允许来自局域网(私有 IP 地址段)的访问。如果需要允许公网访问,可以使用 `--public` 选项: ```sh kimi web --network --public --auth-token my-secret-token ``` ::: danger 警告 使用 `--public` 选项会允许任何 IP 地址访问 Web UI,请务必配置 `--auth-token` 和 `--allowed-origins` 以确保安全。 ::: #### 限制敏感 API 使用 `--restrict-sensitive-apis` 可以禁用一些敏感的 API 功能: * 配置文件写入 * Open-in 功能(打开本地文件、目录、应用) * 文件访问限制 ```sh kimi web --network --restrict-sensitive-apis ``` 在 `--public` 模式下,`--restrict-sensitive-apis` 默认启用;在 `--lan-only` 模式(默认)下则不启用。 ::: tip 提示 当你需要将 Web UI 暴露给不受信任的网络环境时,建议启用 `--restrict-sensitive-apis` 选项。 ::: #### 禁用认证(不推荐) 在受信任的私有网络环境中,你可以使用 `--dangerously-omit-auth` 跳过所有认证检查: ```sh kimi web --dangerously-omit-auth ``` ::: danger 警告 `--dangerously-omit-auth` 选项会完全禁用认证和访问控制,仅应在完全受信任的网络环境中使用(如断网的本地开发环境)。不要在公网或不受信任的局域网中使用此选项。 ::: ## 从终端切换到 Web UI 如果你正在终端的 Shell 模式中使用 Kimi Code CLI,可以输入 `/web` 命令快速切换到 Web UI: ``` /web ``` 执行后,Kimi Code CLI 会自动启动 Web UI 服务器并在浏览器中打开当前会话。你可以继续在 Web UI 中进行对话,会话历史会保持同步。 ## Web UI 功能特性 ### 会话管理 Web UI 提供了便捷的会话管理界面: * **会话列表**:查看所有历史会话,包括会话标题和工作目录 * **会话搜索**:通过标题或工作目录快速筛选会话 * **创建会话**:指定工作目录创建新会话;如果指定的路径不存在,会提示确认是否创建目录。支持 Cmd/Ctrl+点击新建会话按钮在新标签页中打开会话创建 * **切换会话**:一键切换到不同的会话 * **会话分支**:从任意 Assistant 回复处创建分支会话,在不影响原会话的情况下探索不同方向 * **会话归档**:超过 15 天的会话会自动归档,你也可以手动归档。归档的会话不会出现在主列表中,但可以随时取消归档 * **批量操作**:在多选模式下批量归档、取消归档或删除会话 ::: info 新增 会话搜索功能新增于 1.5 版本。目录自动创建提示新增于 1.7 版本。会话分支、归档和批量操作新增于 1.9 版本。 ::: ### 提示工具栏 Web UI 在输入框上方提供统一的提示工具栏,以可折叠标签页的形式展示多种信息: * **上下文用量**:显示当前上下文的使用百分比,悬停可查看详细的 Token 用量明细(包括输入/输出 Token、缓存读取/写入等) * **活动状态**:显示 Agent 当前状态(处理中、等待审批等) * **消息队列**:在 AI 处理过程中可以排队发送后续消息,待当前回复完成后自动发送 * **文件变更**:检测 Git 仓库状态,显示新增、修改和删除的文件数量(包含未跟踪文件),点击可查看详细的变更列表 * **待办事项**:当 `SetTodoList` 工具处于活动状态时,显示任务进度,支持展开查看详细列表 * **Plan 模式**:在输入工具栏中切换 Plan 模式开关。Plan 模式激活时,输入框显示蓝色虚线边框。也可以通过 `set_plan_mode` Wire 协议方法程序化设置 ::: info 变更 Git diff 状态栏新增于 1.5 版本。1.9 版本添加了活动状态指示器。1.10 版本将其统一为提示工具栏。1.11 版本将上下文用量指示器移至提示工具栏。1.20 版本新增 Plan 模式切换。 ::: ### Open-in 功能 Web UI 支持在本地应用中打开文件或目录: * **Open in Terminal**:在终端中打开目录 * **Open in VS Code**:在 VS Code 中打开文件或目录 * **Open in Cursor**:在 Cursor 中打开文件或目录 * **Open in System**:使用系统默认应用打开 ::: info 新增 Open-in 功能新增于 1.5 版本。 ::: ::: warning 注意 Open-in 功能需要浏览器支持 Custom Protocol Handler 特性。当使用 `--restrict-sensitive-apis` 选项时,此功能会被禁用。 ::: ### 斜杠命令 Web UI 支持斜杠命令,在输入框中输入 `/` 即可打开命令菜单: * **自动补全**:输入命令名称时自动过滤匹配项 * **键盘导航**:使用上下方向键选择命令,Enter 确认 * **别名支持**:支持命令别名匹配,如 `/h` 匹配 `/help` ### 文件提及 Web UI 支持文件提及功能,在输入框中输入 `@` 即可打开文件提及菜单,可以在对话中引用文件: * **已上传附件**:提及当前消息中已添加的附件文件 * **工作区文件**:提及当前会话工作目录中的已有文件 * **自动补全**:输入时按文件名或路径自动过滤匹配项 * **键盘导航**:使用上下方向键选择文件,Enter 或 Tab 确认,Escape 取消 ### 消息操作 Assistant 消息提供以下操作按钮: * **复制**:一键复制消息内容到剪贴板 * **分支**:从当前回复处创建分支会话 ::: info 新增 复制和分支按钮新增于 1.10 版本。 ::: ### 结构化问答 当 AI 使用 `AskUserQuestion` 工具时,Web UI 会在聊天区域中展示结构化的问题对话框,替代底部的输入框。问题对话框显示问题描述和可选项,支持单选、多选以及自定义文本输入。当 AI 一次提出多个问题时,对话框顶部会以标签栏形式展示问题列表,支持点击切换、键盘导航,以及切换回已答问题时恢复之前的选择。回答所有问题后,对话框自动关闭,AI 根据你的选择继续执行。 ::: info 新增 结构化问答功能新增于 1.14 版本。 ::: ### 审批键盘快捷键 当 Agent 发起审批请求时,你可以使用键盘快捷键快速响应: | 快捷键 | 操作 | |--------|------| | `1` | 批准 | | `2` | 本次会话批准 | | `3` | 拒绝 | | `4` | 附带反馈拒绝 | 按 `4` 进入反馈模式后,可以输入文字说明拒绝的原因或期望 Agent 如何调整,然后按 Enter 提交。反馈文本会传递给 Agent 以指导下一次尝试。 当审批请求来自子 Agent 时,对话框会显示来源标签(如 "coder agent"),帮助你了解请求的发起者。 ::: info 新增 审批键盘快捷键新增于 1.10 版本。反馈模式新增于 1.25 版本。 ::: ### 工具输出 Web UI 对工具调用的输出提供了丰富的展示方式: * **媒体预览**:`ReadMediaFile` 工具读取的图片和视频会以可点击的缩略图形式展示 * **Shell 命令**:`Shell` 工具的命令和输出以专用组件渲染 * **Todo 列表**:`SetTodoList` 工具的待办事项以结构化列表展示 * **工具输入参数**:重新设计的工具输入 UI,支持展开查看参数详情,长值带有语法高亮 * **上下文压缩**:上下文压缩进行时会显示压缩指示器 * **URL 快速打开**:`FetchURL` 工具的 URL 参数支持 Cmd/Ctrl+点击在新标签页中打开链接 * **子 Agent 来源标识**:来自子 Agent 的工具调用以左边框和来源类型标签(如 "coder agent")渲染,便于区分归属;子 Agent 活动面板显示具体的 Agent 类型(如 "Coder agent working")而非通用标签 ::: info 新增 媒体预览、Shell 命令和 Todo 列表显示组件新增于 1.9 版本。URL 快速打开功能新增于 1.14 版本。子 Agent 来源标识新增于 1.25 版本。 ::: ### 富媒体支持 Web UI 支持查看和粘贴多种类型的富媒体内容: * **图片**:直接在聊天界面中显示图片 * **代码高亮**:自动识别和高亮代码块 * **Markdown 渲染**:支持完整的 Markdown 语法 ### 响应式布局 Web UI 采用响应式设计,可以在不同尺寸的屏幕上良好显示: * 桌面端:侧边栏 + 主内容区布局 * 移动端:可折叠的抽屉式侧边栏 ::: info 变更 响应式布局改进于 1.6 版本,增强了悬停效果和布局处理。 ::: ### URL 操作参数 Web UI 支持通过 URL 参数触发特定操作,方便从外部工具或脚本中集成: | 参数 | 说明 | |------|------| | `?action=create` | 打开创建会话对话框 | | `?action=create-in-dir&workDir=` | 直接在指定工作目录下创建会话 | 示例: ``` http://127.0.0.1:5494?action=create http://127.0.0.1:5494?action=create-in-dir&workDir=/path/to/project ``` ## 示例 ### 本地使用 最简单的使用方式,只在本机访问: ```sh kimi web ``` ### 局域网共享 在局域网中共享 Web UI,使用访问令牌保护: ```sh kimi web --network --auth-token $(openssl rand -hex 32) ``` 执行后,终端会显示访问地址和令牌。其他设备可以通过该地址访问,并在浏览器中输入令牌进行认证。 ### 公网访问 在公网环境中部署 Web UI(需要谨慎配置安全选项): ```sh kimi web \ --host 0.0.0.0 \ --public \ --auth-token $(openssl rand -hex 32) \ --allowed-origins "https://yourdomain.com" \ --restrict-sensitive-apis ``` ### 开发调试 启用自动重载功能,方便开发调试: ```sh kimi web --reload --no-open ``` ## 技术说明 Web UI 基于以下技术构建: * **后端**:FastAPI + WebSocket * **前端**:React + TypeScript + Vite * **API 协议**:符合 OpenAPI 规范,详见 `web/openapi.json` Web UI 通过 WebSocket 与 Kimi Code CLI 的 Wire 模式通信,实现实时的双向数据传输。 --- --- url: /en/customization/wire-mode.md --- # Wire mode Wire mode is Kimi Code CLI's low-level communication protocol for structured bidirectional communication with external programs. ## What is Wire Wire is the message-passing layer used internally by Kimi Code CLI. When you interact via terminal, the Shell UI receives AI output through Wire and displays it; when you integrate with IDEs via ACP, the ACP server also communicates with the agent core through Wire. Wire mode (`--wire`) exposes this communication protocol, allowing external programs to interact directly with Kimi Code CLI. This is suitable for building custom UIs or embedding Kimi Code CLI into other applications. ```sh kimi --wire ``` ## Use cases Wire mode is mainly used for: * **Custom UI**: Build web, desktop, or mobile frontends for Kimi Code CLI * **Application integration**: Embed Kimi Code CLI into other applications * **Automated testing**: Programmatic testing of agent behavior ::: tip If you only need simple non-interactive input/output, [print mode](./print-mode.md) is simpler. Wire mode is for scenarios requiring full control and bidirectional communication. ::: ## Wire protocol Wire uses a JSON-RPC 2.0 based protocol for bidirectional communication via stdin/stdout. The current protocol version is `1.10`. Each message is a single line of JSON conforming to the JSON-RPC 2.0 specification. ### Protocol type definitions ```typescript /** JSON-RPC 2.0 request message base structure */ interface JSONRPCRequest { jsonrpc: "2.0" method: Method id: string params: Params } /** JSON-RPC 2.0 notification message (no id, no response needed) */ interface JSONRPCNotification { jsonrpc: "2.0" method: Method params: Params } /** JSON-RPC 2.0 success response */ interface JSONRPCSuccessResponse { jsonrpc: "2.0" id: string result: Result } /** JSON-RPC 2.0 error response */ interface JSONRPCErrorResponse { jsonrpc: "2.0" id: string error: JSONRPCError } interface JSONRPCError { code: number message: string data?: unknown } ``` ### `initialize` ::: info Added Added in Wire 1.1. Legacy clients can skip this request and send `prompt` directly. ::: * **Direction**: Client → Agent * **Type**: Request (requires response) Optional handshake request for negotiating protocol version, submitting external tool definitions, and retrieving the slash command list. ```typescript /** initialize request parameters */ interface InitializeParams { /** Protocol version */ protocol_version: string /** Client info, optional */ client?: ClientInfo /** External tool definitions, optional */ external_tools?: ExternalTool[] /** Client capabilities, optional */ capabilities?: ClientCapabilities /** Hook subscriptions, optional. Declares hook events the client wants to handle */ hooks?: WireHookSubscription[] } interface ClientCapabilities { /** Whether the client can handle QuestionRequest messages */ supports_question?: boolean /** Whether the client supports plan mode */ supports_plan_mode?: boolean } interface WireHookSubscription { /** Subscription ID, referenced in HookRequest */ id: string /** Event type to subscribe to, e.g., 'PreToolUse', 'Stop' */ event: string /** Regex filter, empty string matches all */ matcher?: string /** Timeout for client response in seconds, default 30 */ timeout?: number } interface ClientInfo { name: string version?: string } interface ExternalTool { /** Tool name, must not conflict with built-in tools */ name: string /** Tool description */ description: string /** Parameter definition in JSON Schema format */ parameters: JSONSchema } /** initialize response result */ interface InitializeResult { /** Protocol version */ protocol_version: string /** Server info */ server: ServerInfo /** Available slash commands */ slash_commands: SlashCommandInfo[] /** External tool registration result, only returned when request includes external_tools */ external_tools?: ExternalToolsResult /** Server capabilities */ capabilities?: ServerCapabilities /** Hook system info, optional */ hooks?: HooksInfo } interface HooksInfo { /** List of all hook event types supported by the server */ supported_events: string[] /** Currently configured hooks statistics, key is event type, value is count */ configured: Record } interface ServerCapabilities { /** Whether the server supports sending QuestionRequest messages */ supports_question?: boolean } interface ServerInfo { name: string version: string } interface SlashCommandInfo { name: string description: string aliases: string[] } interface ExternalToolsResult { /** Successfully registered tool names */ accepted: string[] /** Failed tool registrations with reasons */ rejected: Array<{ name: string; reason: string }> } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "initialize", "id": "550e8400-e29b-41d4-a716-446655440000", "params": {"protocol_version": "1.7", "client": {"name": "my-ui", "version": "1.0.0"}, "capabilities": {"supports_question": true}, "external_tools": [{"name": "open_in_ide", "description": "Open file in IDE", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}]}} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "550e8400-e29b-41d4-a716-446655440000", "result": {"protocol_version": "1.7", "server": {"name": "Kimi Code CLI", "version": "1.14.0"}, "slash_commands": [{"name": "init", "description": "Analyze the codebase ...", "aliases": []}], "capabilities": {"supports_question": true}, "external_tools": {"accepted": ["open_in_ide"], "rejected": []}}} ``` If the server does not support the `initialize` method, the client will receive a `-32601 method not found` error and should automatically fall back to no-handshake mode. ### `prompt` * **Direction**: Client → Agent * **Type**: Request (requires response) Send user input and run an agent turn. After calling, the agent starts processing and sends `event` notifications and `request` messages during execution, returning a response only when the turn completes. ```typescript /** prompt request parameters */ interface PromptParams { /** User input, can be plain text or array of content parts */ user_input: string | ContentPart[] } /** prompt response result */ interface PromptResult { /** Turn end status */ status: "finished" | "cancelled" | "max_steps_reached" /** Number of steps executed when status is max_steps_reached */ steps?: number } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "prompt", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "params": {"user_input": "Hello"}} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "finished"}} ``` **Error response example** ```json {"jsonrpc": "2.0", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32001, "message": "LLM is not set"}} ``` | code | Description | |------|-------------| | `-32000` | A turn is already in progress | | `-32001` | LLM not configured | | `-32002` | Specified LLM not supported | | `-32003` | LLM service error | ### `replay` ::: info Added Added in Wire 1.3. ::: * **Direction**: Client → Agent * **Type**: Request (requires response) Trigger a history replay. The server reads `wire.jsonl` from the session directory and re-sends the recorded `event` and `request` messages in order. Replay is read-only; clients should not respond to replayed `request` messages. If there is no history, the server returns `events: 0` and `requests: 0`. ```typescript /** replay request has no parameters, params can be empty object or omitted */ type ReplayParams = Record /** replay response result */ interface ReplayResult { /** Replay end status */ status: "finished" | "cancelled" /** Number of replayed events */ events: number /** Number of replayed requests */ requests: number } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "replay", "id": "6ba7b812-9dad-11d1-80b4-00c04fd430c8"} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "6ba7b812-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "finished", "events": 42, "requests": 3}} ``` ### `steer` ::: info Added Added in Wire 1.4. ::: * **Direction**: Client → Agent * **Type**: Request (requires response) Inject a user message into an active agent turn. Unlike `prompt`, `steer` does not start a new turn but injects the message into the currently running turn. The injected message is appended to the context as a standard user message after the current step finishes, allowing you to "steer" the AI's behavior before the next step begins. A `SteerInput` event is emitted when the message is consumed. ```typescript /** steer request parameters */ interface SteerParams { /** User input, can be plain text or array of content parts */ user_input: string | ContentPart[] } /** steer response result */ interface SteerResult { /** Fixed as "steered" */ status: "steered" } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "steer", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "params": {"user_input": "Use Python"}} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "steered"}} ``` **Error response example** If no turn is in progress: ```json {"jsonrpc": "2.0", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "No agent turn is in progress"}} ``` ### `set_plan_mode` ::: info Added Added in Wire 1.4. ::: * **Direction**: Client → Agent * **Type**: Request (requires response) Set plan mode to a specific state. After calling, the agent updates plan mode and sends a `StatusUpdate` event with the new state. This feature requires capability negotiation: the client must declare `capabilities.supports_plan_mode: true` during `initialize` for the agent to enable plan mode tools (`EnterPlanMode`, `ExitPlanMode`). If the client does not declare support, these tools are automatically hidden from the LLM's tool list. Plan mode state is persisted to the session, so it survives process restarts and is restored when the session resumes. ```typescript /** set_plan_mode request parameters */ interface SetPlanModeParams { /** Whether to enable plan mode */ enabled: boolean } /** set_plan_mode response result */ interface SetPlanModeResult { /** Fixed as "ok" */ status: "ok" /** Plan mode state after the call */ plan_mode: boolean } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "set_plan_mode", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "params": {"enabled": true}} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "ok", "plan_mode": true}} ``` **Error response example** If plan mode is not supported in the current environment: ```json {"jsonrpc": "2.0", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "Plan mode is not supported"}} ``` ### `cancel` * **Direction**: Client → Agent * **Type**: Request (requires response) Cancel the currently running agent turn or replay. After calling, the in-progress `prompt` request will return `{"status": "cancelled"}`, and replay will return `{"status": "cancelled"}` with the message counts sent so far. ```typescript /** cancel request has no parameters, params can be empty object or omitted */ type CancelParams = Record /** cancel response result is empty object */ type CancelResult = Record ``` **Request example** ```json {"jsonrpc": "2.0", "method": "cancel", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8"} ``` **Success response example** ```json {"jsonrpc": "2.0", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8", "result": {}} ``` **Error response example** If no turn is in progress: ```json {"jsonrpc": "2.0", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "No agent turn is in progress"}} ``` ### `event` * **Direction**: Agent → Client * **Type**: Notification (no response needed) Events emitted by the agent during a turn. No `id` field, client doesn't need to respond. ```typescript /** event notification parameters, contains serialized Wire message */ interface EventParams { type: string payload: object } ``` **Example** ```json {"jsonrpc": "2.0", "method": "event", "params": {"type": "ContentPart", "payload": {"type": "text", "text": "Hello"}}} ``` ### `request` * **Direction**: Agent → Client * **Type**: Request (requires response) Requests from the agent to the client, used for approval confirmation or external tool calls. The client must respond before the agent can continue execution. ```typescript /** request parameters, contains serialized Wire message */ interface RequestParams { type: "ApprovalRequest" | "ToolCallRequest" | "QuestionRequest" payload: ApprovalRequest | ToolCallRequest | QuestionRequest } ``` **Approval request example** ```json {"jsonrpc": "2.0", "method": "request", "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "params": {"type": "ApprovalRequest", "payload": {"id": "approval-1", "tool_call_id": "tc-1", "sender": "Shell", "action": "run shell command", "description": "Run command `ls`", "display": []}}} ``` **Approval response example** ```json {"jsonrpc": "2.0", "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "result": {"request_id": "approval-1", "response": "approve"}} ``` **External tool call request example** ```json {"jsonrpc": "2.0", "method": "request", "id": "a3bb189e-8bf9-3888-9912-ace4e6543002", "params": {"type": "ToolCallRequest", "payload": {"id": "tc-1", "name": "open_in_ide", "arguments": "{\"path\":\"README.md\"}"}}} ``` **External tool call response example** ```json {"jsonrpc": "2.0", "id": "a3bb189e-8bf9-3888-9912-ace4e6543002", "result": {"tool_call_id": "tc-1", "return_value": {"is_error": false, "output": "Opened", "message": "Opened README.md in IDE", "display": []}}} ``` ### Standard error codes All requests may return JSON-RPC 2.0 standard errors: | code | Description | |------|-------------| | `-32700` | Invalid JSON format | | `-32600` | Invalid request (e.g., missing required fields) | | `-32601` | Method not found | | `-32602` | Invalid method parameters | | `-32603` | Internal error | ## Wire message types Wire messages are transmitted via `event` and `request` methods, in format `{"type": "...", "payload": {...}}`. The following describes all message types using TypeScript-style type definitions. ```typescript /** Union type of all Wire messages */ type WireMessage = Event | Request /** Events: sent via event method, no response needed */ type Event = | TurnBegin | TurnEnd | StepBegin | StepInterrupted | StepRetry | CompactionBegin | CompactionEnd | StatusUpdate | ContentPart | ToolCall | ToolCallPart | ToolResult | ApprovalResponse | SubagentEvent | BtwBegin | BtwEnd | SteerInput | PlanDisplay | HookTriggered | HookResolved /** Requests: sent via request method, require response */ type Request = ApprovalRequest | ToolCallRequest | QuestionRequest | HookRequest ``` ### `TurnBegin` Turn started. ```typescript interface TurnBegin { /** User input, can be plain text or array of content parts */ user_input: string | ContentPart[] } ``` ### `TurnEnd` ::: info Added Added in Wire 1.2. ::: Turn ended. This event is sent after all other events in the turn. If the turn is interrupted, this event may be omitted. ```typescript interface TurnEnd { // No additional fields } ``` ### `StepBegin` Step started. ```typescript interface StepBegin { /** Step number, starting from 1 */ n: number } ``` ### `StepInterrupted` Step interrupted, no additional fields. ### `StepRetry` ::: info Added Added in Wire 1.10. ::: The current step attempt failed and will be retried. This event is emitted when a step fails due to a recoverable error (such as rate limiting, connection timeout, or server error) and enters retry wait. Clients can use this to show retry status to the user, or clear incomplete state when the previous attempt already streamed partial output. ```typescript interface StepRetry { /** Step number */ n: number /** Next attempt number, 1-based */ next_attempt: number /** Maximum number of attempts for this step */ max_attempts: number /** Seconds to wait before retrying */ wait_s: number /** Exception class name that triggered the retry */ error_type: string /** HTTP status code (if available), may be absent in JSON */ status_code?: number | null } ``` ### `CompactionBegin` Context compaction started, no additional fields. ### `CompactionEnd` Context compaction ended, no additional fields. ### `StatusUpdate` Status update. ```typescript interface StatusUpdate { /** Context usage ratio, float between 0-1, may be absent in JSON */ context_usage?: number | null /** Number of tokens currently in the context, may be absent in JSON */ context_tokens?: number | null /** Maximum number of tokens the context can hold, may be absent in JSON */ max_context_tokens?: number | null /** Token usage stats for current step, may be absent in JSON */ token_usage?: TokenUsage | null /** Message ID for current step, may be absent in JSON */ message_id?: string | null /** Whether plan mode (read-only) is active, null means no change, may be absent in JSON */ plan_mode?: boolean | null } interface TokenUsage { /** Input tokens excluding input_cache_read and input_cache_creation */ input_other: number /** Total output tokens */ output: number /** Cached input tokens */ input_cache_read: number /** Input tokens used for cache creation, currently only Anthropic API supports this field */ input_cache_creation: number } ``` ### `ContentPart` Message content part. Serialized with `type` as `"ContentPart"`, specific type distinguished by `payload.type`. ```typescript type ContentPart = | TextPart | ThinkPart | ImageURLPart | AudioURLPart | VideoURLPart interface TextPart { type: "text" /** Text content */ text: string } interface ThinkPart { type: "think" /** Thinking content */ think: string /** Encrypted thinking content or signature, may be absent in JSON */ encrypted?: string | null } interface ImageURLPart { type: "image_url" image_url: { /** Image URL, can be data URI (e.g., data:image/png;base64,...) */ url: string /** Image ID for distinguishing different images, may be absent in JSON */ id?: string | null } } interface AudioURLPart { type: "audio_url" audio_url: { /** Audio URL, can be data URI (e.g., data:audio/aac;base64,...) */ url: string /** Audio ID for distinguishing different audio, may be absent in JSON */ id?: string | null } } interface VideoURLPart { type: "video_url" video_url: { /** Video URL, can be data URI (e.g., data:video/mp4;base64,...) */ url: string /** Video ID for distinguishing different video, may be absent in JSON */ id?: string | null } } ``` ### `ToolCall` Tool call. ```typescript interface ToolCall { /** Fixed as "function" */ type: "function" /** Tool call ID */ id: string function: { /** Tool name */ name: string /** JSON-format argument string, may be absent in JSON */ arguments?: string | null } /** Extra info, may be absent in JSON */ extras?: object | null } ``` ### `ToolCallPart` Tool call argument fragment (streaming). ```typescript interface ToolCallPart { /** Argument fragment for streaming tool call arguments, may be absent in JSON */ arguments_part?: string | null } ``` ### `ToolResult` Tool execution result. ```typescript interface ToolResult { /** Corresponding tool call ID */ tool_call_id: string return_value: ToolReturnValue } interface ToolReturnValue { /** Whether this is an error */ is_error: boolean /** Output content returned to model */ output: string | ContentPart[] /** Explanatory message for model */ message: string /** Display blocks shown to user */ display: DisplayBlock[] /** Extra debug info, may be absent in JSON */ extras?: object | null } ``` ### `ApprovalResponse` ::: info Changed Renamed in Wire 1.1. Formerly `ApprovalRequestResolved`. The old name is still accepted for backwards compatibility. ::: Approval response event, indicates an approval request has been completed. ```typescript interface ApprovalResponse { /** Approval request ID */ request_id: string /** Approval result */ response: "approve" | "approve_for_session" | "reject" /** Optional feedback text when rejecting, may be absent in JSON */ feedback?: string } ``` ### `BtwBegin` ::: info Added Added in Wire 1.9. ::: A side question (`/btw`) has started processing. ```typescript interface BtwBegin { /** Unique ID to pair with the corresponding BtwEnd */ id: string /** The user's original side question text */ question: string } ``` ### `BtwEnd` ::: info Added Added in Wire 1.9. ::: A side question (`/btw`) has finished processing. ```typescript interface BtwEnd { /** Unique ID matching the corresponding BtwBegin */ id: string /** The LLM's response text, or null if it failed */ response?: string | null /** Error message if the side question failed */ error?: string | null } ``` ### `SubagentEvent` ::: info Changed Changed in Wire 1.6. `task_tool_call_id` renamed to `parent_tool_call_id`; added `agent_id` and `subagent_type` fields. ::: Subagent event. ```typescript interface SubagentEvent { /** Associated parent Agent tool call ID, may be absent in JSON */ parent_tool_call_id?: string | null /** Subagent instance ID, may be absent in JSON */ agent_id?: string | null /** Built-in subagent type used by this instance, may be absent in JSON */ subagent_type?: string | null /** Event from subagent, nested Wire message format */ event: { type: string; payload: object } } ``` ### `SteerInput` ::: info Added Added in Wire 1.5. ::: Indicates that the user appended follow-up input to the current running turn. This event is emitted after the current step finishes and the input is appended to context, before the next step begins. ```typescript interface SteerInput { /** User input, can be plain text or array of content parts */ user_input: string | ContentPart[] } ``` ### `PlanDisplay` ::: info Added Added in Wire 1.7. ::: Plan content display event. When the agent calls `ExitPlanMode` to submit a plan for user approval in plan mode, this event is sent first to display the plan content inline in the chat. Clients should render it as a bordered panel or similar visually distinct element, and show the file path for reference. ```typescript interface PlanDisplay { /** Full markdown content of the plan */ content: string /** Path to the plan file */ file_path: string } ``` ### `HookTriggered` ::: info Added Added in Wire 1.7. ::: Hook execution started event. Sent when configured hooks are triggered and begin executing, to notify the client that hooks are running. ```typescript interface HookTriggered { /** Hook event type, e.g., 'PreToolUse', 'Stop' */ event: string /** Target of the hook: tool name for tool hooks, agent name for subagent hooks, etc. */ target: string /** Number of matched hooks running in parallel */ hook_count: number } ``` ### `HookResolved` ::: info Added Added in Wire 1.7. ::: Hook execution completed event. Sent when hooks finish executing, containing the result and duration information. ```typescript interface HookResolved { /** Hook event type, e.g., 'PreToolUse', 'Stop' */ event: string /** Same as HookTriggered.target */ target: string /** Aggregate decision: 'block' if any hook blocked, 'allow' otherwise */ action: "allow" | "block" /** Reason for blocking, empty if allowed */ reason: string /** Wall-clock time for the entire batch in milliseconds */ duration_ms: number } ``` ### `ApprovalRequest` ::: info Changed Changed in Wire 1.6. Added `source_kind`, `source_id`, `agent_id`, `subagent_type`, and `source_description` fields. ::: Approval request, sent via `request` method, client must respond before agent can continue. ```typescript interface ApprovalRequest { /** Request ID, used when responding */ id: string /** Associated tool call ID */ tool_call_id: string /** Sender (tool name) */ sender: string /** Action description */ action: string /** Detailed description */ description: string /** Display blocks shown to user, may be absent in JSON, defaults to [] */ display?: DisplayBlock[] /** Where the request originated: foreground turn or background agent, may be absent in JSON */ source_kind?: "foreground_turn" | "background_agent" | null /** Source identifier (e.g. background agent ID), may be absent in JSON */ source_id?: string | null /** Subagent instance ID if from a subagent, may be absent in JSON */ agent_id?: string | null /** Subagent type if from a subagent, may be absent in JSON */ subagent_type?: string | null /** Human-readable source description, may be absent in JSON */ source_description?: string | null } ``` **Response format** ::: info Changed Changed in Wire 1.6. Added optional `feedback` field. ::: Client needs to return `ApprovalResponse` as the response result: ```typescript interface ApprovalResponse { request_id: string response: "approve" | "approve_for_session" | "reject" /** Optional feedback text when rejecting, may be absent in JSON */ feedback?: string } ``` | response | Description | |----------|-------------| | `approve` | Approve this operation | | `approve_for_session` | Approve similar operations for this session | | `reject` | Reject operation; optionally include `feedback` to instruct the model on what to do instead | ### `ToolCallRequest` External tool call request, sent via `request` method. When the agent calls an external tool registered via `initialize`, this request is sent. The client must execute the tool and return a `ToolResult`. ```typescript interface ToolCallRequest { /** Tool call ID */ id: string /** Tool name */ name: string /** JSON-format argument string, may be absent in JSON */ arguments?: string | null } ``` **Response format** Client needs to return `ToolResult` as the response result: ```typescript interface ToolResult { tool_call_id: string return_value: ToolReturnValue } ``` ### `QuestionRequest` ::: info Added Added in Wire 1.4. ::: Structured question request, sent via `request` method. When the agent uses the `AskUserQuestion` tool, this request is sent. The client must respond before the agent can continue execution. This feature requires capability negotiation: the client must declare `capabilities.supports_question: true` during `initialize` for the agent to send `QuestionRequest`. If the client does not declare support, the `AskUserQuestion` tool is automatically hidden from the LLM's tool list, preventing the LLM from invoking unsupported interactions. ```typescript interface QuestionRequest { /** Request ID, used when responding */ id: string /** Associated tool call ID */ tool_call_id: string /** Questions list (1–4 questions) */ questions: QuestionItem[] } interface QuestionItem { /** Question text */ question: string /** Short label, max 12 characters */ header?: string /** Available options (2–4) */ options: QuestionOption[] /** Whether multiple options can be selected */ multi_select?: boolean } interface QuestionOption { /** Option label */ label: string /** Option description */ description?: string } ``` **Request example** ```json {"jsonrpc": "2.0", "method": "request", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "params": {"type": "QuestionRequest", "payload": {"id": "q-1", "tool_call_id": "tc-1", "questions": [{"question": "Which language should I use?", "header": "Lang", "options": [{"label": "Python", "description": "Widely used, large ecosystem"}, {"label": "Rust", "description": "High performance, memory safe"}], "multi_select": false}]}}} ``` **Response format** Client needs to return `QuestionResponse` as the response result: ```typescript interface QuestionResponse { /** Corresponding request ID */ request_id: string /** Answer mapping, key is question text, value is selected option label(s) (comma-separated for multi-select) */ answers: Record } ``` **Response example** ```json {"jsonrpc": "2.0", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "result": {"request_id": "q-1", "answers": {"Which language should I use?": "Python"}}} ``` If the client does not support structured questions or the user dismisses the question panel, return empty `answers`: ```json {"jsonrpc": "2.0", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "result": {"request_id": "q-1", "answers": {}}} ``` ### `HookRequest` ::: info Added Added in Wire 1.7. ::: Hook handling request, sent via `request` method. When a Wire client subscribes to hook events, the server sends this request to let the client handle the hook logic and return an allow/block decision. This feature requires capability negotiation: the server only sends corresponding `HookRequest` messages after the client declares subscriptions via `hooks` in `initialize`. ```typescript interface HookRequest { /** Request ID, used when responding */ id: string /** Subscription ID, identifies which subscription triggered this request */ subscription_id: string /** Hook event type, e.g., 'PreToolUse', 'Stop' */ event: string /** Target that triggered the hook: tool name, agent name, etc. */ target: string /** Full event payload (same as what shell hooks receive on stdin) */ input_data: object } ``` **Response format** The client should return a `HookResponse` as the response result: ```typescript interface HookResponse { /** Corresponding request ID */ request_id: string /** Decision: allow or block */ action: "allow" | "block" /** Reason for blocking */ reason: string } ``` ### `DisplayBlock` Display block types used in the `display` field of `ToolResult` and `ApprovalRequest`. ```typescript type DisplayBlock = | UnknownDisplayBlock | BriefDisplayBlock | DiffDisplayBlock | TodoDisplayBlock | ShellDisplayBlock /** Fallback for unrecognized display block types */ interface UnknownDisplayBlock { /** Any type identifier */ type: string /** Raw data */ data: object } interface BriefDisplayBlock { type: "brief" /** Brief text content */ text: string } interface DiffDisplayBlock { type: "diff" /** File path */ path: string /** Original content */ old_text: string /** New content */ new_text: string /** Whether this is a summary block (shows line count summary instead of actual diff for large files). May not be present in JSON. Added in Wire 1.8 */ is_summary?: boolean } interface TodoDisplayBlock { type: "todo" /** Todo list items */ items: TodoDisplayItem[] } interface TodoDisplayItem { /** Todo item title */ title: string /** Status */ status: "pending" | "in_progress" | "done" } interface ShellDisplayBlock { type: "shell" /** Language identifier for syntax highlighting (e.g., "sh", "powershell") */ language: string /** Shell command content */ command: string } ``` ## Kimi Agent (Rust) Wire server ::: warning Note Kimi Agent is currently experimental. APIs and behavior may change in future releases. ::: Kimi Agent (Rust) is the Rust implementation of the Kimi Code CLI kernel, designed specifically for Wire mode. If you only need the Wire protocol service, Kimi Agent (Rust) offers a more lightweight alternative. The Rust implementation lives in [`MoonshotAI/kimi-agent-rs`](https://github.com/MoonshotAI/kimi-agent-rs). ### Features * **Full Wire protocol compatibility**: Uses the same Wire protocol as Python's `kimi --wire`, existing clients need no modifications * **Smaller footprint**: Single statically-linked binary, no Python runtime required * **Faster startup**: Native compilation provides faster startup times * **Same configuration**: Uses the same config file (`~/.kimi/config.toml`) and session directories ### Limitations * **Wire mode only**: No Shell/Print/ACP UI * **Kimi provider only**: Does not support OpenAI, Anthropic, or other providers * **No Kimi account login**: No `login`/`logout` subcommands or `/login`, `/logout` slash commands; requires manual API key configuration * **No `--prompt`/`--command`**: Wire server does not accept initial prompts * **Local execution only**: No SSH Kaos support * **Different MCP OAuth storage**: Kimi Agent stores credentials in `~/.kimi/credentials/mcp_auth.json`, while the Python version uses `~/.kimi/mcp-oauth/`; they are incompatible ### Installation Download pre-built binaries from [GitHub Releases](https://github.com/MoonshotAI/kimi-agent-rs/releases): ```sh # macOS (Apple Silicon) curl -L https://github.com/MoonshotAI/kimi-agent-rs/releases/latest/download/kimi-agent-aarch64-apple-darwin.tar.gz | tar xz sudo mv kimi-agent /usr/local/bin/ # Linux (x86_64) curl -L https://github.com/MoonshotAI/kimi-agent-rs/releases/latest/download/kimi-agent-x86_64-unknown-linux-gnu.tar.gz | tar xz sudo mv kimi-agent /usr/local/bin/ ``` ### Usage Kimi Agent runs in Wire mode by default: ```sh kimi-agent ``` Common options are the same as the `kimi` command: ```sh # Specify work directory kimi-agent --work-dir /path/to/project # Continue previous session kimi-agent --continue # Use specific session kimi-agent --session # Use specific model kimi-agent --model k2 # YOLO mode (skip approvals) kimi-agent --yolo ``` Subcommands: ```sh # Show version and environment info kimi-agent info # Manage MCP servers kimi-agent mcp list kimi-agent mcp add [args...] kimi-agent mcp remove ``` ### Version synchronization Kimi Agent is released independently from Kimi Code CLI. See `MoonshotAI/kimi-agent-rs` release notes for compatibility and sync status. --- --- url: /zh/customization/wire-mode.md --- # Wire 模式 Wire 模式是 Kimi Code CLI 的底层通信协议,用于与外部程序进行结构化的双向通信。 ## Wire 是什么 Wire 是 Kimi Code CLI 内部使用的消息传递层。当你使用终端交互时,Shell UI 通过 Wire 接收 AI 的输出并显示;当你使用 ACP 集成到 IDE 时,ACP 服务器也通过 Wire 与 Agent 核心通信。 Wire 模式(`--wire`)将这个通信协议暴露出来,允许外部程序直接与 Kimi Code CLI 交互。这适用于构建自定义 UI 或将 Kimi Code CLI 嵌入到其他应用中。 ```sh kimi --wire ``` ## 使用场景 Wire 模式主要用于: * **自定义 UI**:构建 Web、桌面或移动端的 Kimi Code CLI 前端 * **应用集成**:将 Kimi Code CLI 嵌入到其他应用程序中 * **自动化测试**:对 Agent 行为进行程序化测试 ::: tip 提示 如果你只需要简单的非交互输入输出,使用 [Print 模式](./print-mode.md) 更简单。Wire 模式适合需要完整控制和双向通信的场景。 ::: ## Wire 协议 Wire 使用基于 JSON-RPC 2.0 的协议,通过 stdin/stdout 进行双向通信。当前协议版本为 `1.10`。每条消息是一行 JSON,符合 JSON-RPC 2.0 规范。 ### 协议类型定义 ```typescript /** JSON-RPC 2.0 请求消息基础结构 */ interface JSONRPCRequest { jsonrpc: "2.0" method: Method id: string params: Params } /** JSON-RPC 2.0 通知消息(无 id,无需响应) */ interface JSONRPCNotification { jsonrpc: "2.0" method: Method params: Params } /** JSON-RPC 2.0 成功响应 */ interface JSONRPCSuccessResponse { jsonrpc: "2.0" id: string result: Result } /** JSON-RPC 2.0 错误响应 */ interface JSONRPCErrorResponse { jsonrpc: "2.0" id: string error: JSONRPCError } interface JSONRPCError { code: number message: string data?: unknown } ``` ### `initialize` ::: info 新增 新增于 Wire 1.1。旧版 Client 可跳过此请求,直接发送 `prompt`。 ::: * **方向**:Client → Agent * **类型**:Request(需要响应) 可选握手请求,用于协商协议版本、提交外部工具定义并获取斜杠命令列表。 ```typescript /** initialize 请求参数 */ interface InitializeParams { /** 协议版本 */ protocol_version: string /** Client 信息,可选 */ client?: ClientInfo /** 外部工具定义列表,可选 */ external_tools?: ExternalTool[] /** Client 能力声明,可选 */ capabilities?: ClientCapabilities /** Hook 订阅列表,可选。声明客户端希望自行处理的 hook 事件 */ hooks?: WireHookSubscription[] } interface ClientCapabilities { /** 是否支持处理 QuestionRequest 消息 */ supports_question?: boolean /** 是否支持 Plan 模式 */ supports_plan_mode?: boolean } interface WireHookSubscription { /** 订阅 ID,在 HookRequest 中引用 */ id: string /** 订阅的事件类型,如 'PreToolUse'、'Stop' */ event: string /** 正则过滤条件,空字符串匹配所有 */ matcher?: string /** 等待客户端响应的超时时间(秒),默认 30 */ timeout?: number } interface ClientInfo { name: string version?: string } interface ExternalTool { /** 工具名称,不可与内置工具冲突 */ name: string /** 工具描述 */ description: string /** JSON Schema 格式的参数定义 */ parameters: JSONSchema } /** initialize 响应结果 */ interface InitializeResult { /** 协议版本 */ protocol_version: string /** Server 信息 */ server: ServerInfo /** 可用的斜杠命令列表 */ slash_commands: SlashCommandInfo[] /** 外部工具注册结果,仅当请求中包含 external_tools 时返回 */ external_tools?: ExternalToolsResult /** Server 能力声明 */ capabilities?: ServerCapabilities /** Hook 系统信息,可选 */ hooks?: HooksInfo } interface HooksInfo { /** Server 支持的所有 hook 事件类型列表 */ supported_events: string[] /** 当前已配置的 hook 统计,键为事件类型,值为数量 */ configured: Record } interface ServerCapabilities { /** 是否支持发送 QuestionRequest 消息 */ supports_question?: boolean } interface ServerInfo { name: string version: string } interface SlashCommandInfo { name: string description: string aliases: string[] } interface ExternalToolsResult { /** 成功注册的工具名称列表 */ accepted: string[] /** 注册失败的工具及原因 */ rejected: Array<{ name: string; reason: string }> } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "initialize", "id": "550e8400-e29b-41d4-a716-446655440000", "params": {"protocol_version": "1.7", "client": {"name": "my-ui", "version": "1.0.0"}, "capabilities": {"supports_question": true}, "external_tools": [{"name": "open_in_ide", "description": "Open file in IDE", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}]}} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "550e8400-e29b-41d4-a716-446655440000", "result": {"protocol_version": "1.7", "server": {"name": "Kimi Code CLI", "version": "1.14.0"}, "slash_commands": [{"name": "init", "description": "Analyze the codebase ...", "aliases": []}], "capabilities": {"supports_question": true}, "external_tools": {"accepted": ["open_in_ide"], "rejected": []}}} ``` 若 Server 不支持 `initialize` 方法,Client 会收到 `-32601 method not found` 错误,应自动降级到无握手模式。 ### `prompt` * **方向**:Client → Agent * **类型**:Request(需要响应) 发送用户输入并运行 Agent 轮次。调用后 Agent 开始处理,期间会发送 `event` 通知和 `request` 请求,直到轮次完成才返回响应。 ```typescript /** prompt 请求参数 */ interface PromptParams { /** 用户输入,可以是纯文本或内容片段数组 */ user_input: string | ContentPart[] } /** prompt 响应结果 */ interface PromptResult { /** 轮次结束状态 */ status: "finished" | "cancelled" | "max_steps_reached" /** 当 status 为 max_steps_reached 时,包含已执行的步数 */ steps?: number } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "prompt", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "params": {"user_input": "你好"}} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "finished"}} ``` **错误响应示例** ```json {"jsonrpc": "2.0", "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32001, "message": "LLM is not set"}} ``` | code | 说明 | |------|------| | `-32000` | 已有轮次正在进行中 | | `-32001` | 未配置 LLM | | `-32002` | 不支持指定的 LLM | | `-32003` | LLM 服务错误 | ### `replay` ::: info 新增 新增于 Wire 1.3。 ::: * **方向**:Client → Agent * **类型**:Request(需要响应) 触发历史回放。Server 读取会话目录中的 `wire.jsonl`,按顺序重新发送已记录的 `event` 和 `request` 消息。回放是只读的,Client 不应对回放中的 `request` 消息作出响应。如果没有历史记录,Server 直接返回 `events: 0`、`requests: 0`。 ```typescript /** replay 请求无参数,params 可以是空对象或省略 */ type ReplayParams = Record /** replay 响应结果 */ interface ReplayResult { /** 回放结束状态 */ status: "finished" | "cancelled" /** 回放的 event 数量 */ events: number /** 回放的 request 数量 */ requests: number } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "replay", "id": "6ba7b812-9dad-11d1-80b4-00c04fd430c8"} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "6ba7b812-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "finished", "events": 42, "requests": 3}} ``` ### `steer` ::: info 新增 新增于 Wire 1.4。 ::: * **方向**:Client → Agent * **类型**:Request(需要响应) 在 Agent 轮次进行中注入用户消息。与 `prompt` 不同,`steer` 不会开始新的轮次,而是将消息注入到当前正在进行的轮次中。注入的消息会在当前步骤完成后作为标准用户消息追加到上下文中,从而在下一步骤开始前”引导” AI 的行为。消息被消费时会发出 `SteerInput` 事件。 ```typescript /** steer 请求参数 */ interface SteerParams { /** 用户输入,可以是纯文本或内容片段数组 */ user_input: string | ContentPart[] } /** steer 响应结果 */ interface SteerResult { /** 固定为 "steered" */ status: "steered" } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "steer", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "params": {"user_input": "用 Python 实现"}} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "steered"}} ``` **错误响应示例** 如果当前没有轮次在进行: ```json {"jsonrpc": "2.0", "id": "7ca7c810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "No agent turn is in progress"}} ``` ### `set_plan_mode` ::: info 新增 新增于 Wire 1.4。 ::: * **方向**:Client → Agent * **类型**:Request(需要响应) 将 Plan 模式设置为指定状态。调用后 Agent 会更新 Plan 模式并通过 `StatusUpdate` 事件通知新的状态。 此功能需要能力协商:Client 在 `initialize` 时通过 `capabilities.supports_plan_mode: true` 声明支持后,Agent 才会启用 Plan 模式相关工具(`EnterPlanMode`、`ExitPlanMode`)。如果 Client 未声明支持,这些工具会从 LLM 的工具列表中自动隐藏。 Plan 模式状态会持久化到会话中,因此在进程重启后可以恢复。 ```typescript /** set_plan_mode 请求参数 */ interface SetPlanModeParams { /** 是否启用 Plan 模式 */ enabled: boolean } /** set_plan_mode 响应结果 */ interface SetPlanModeResult { /** 固定为 "ok" */ status: "ok" /** 调用后的 Plan 模式状态 */ plan_mode: boolean } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "set_plan_mode", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "params": {"enabled": true}} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "result": {"status": "ok", "plan_mode": true}} ``` **错误响应示例** 如果当前环境不支持 Plan 模式: ```json {"jsonrpc": "2.0", "id": "8da7d810-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "Plan mode is not supported"}} ``` ### `cancel` * **方向**:Client → Agent * **类型**:Request(需要响应) 取消当前正在进行的 Agent 轮次或回放。调用后,正在进行的 `prompt` 请求会返回 `{"status": "cancelled"}`,回放会返回 `{"status": "cancelled"}` 及已发送的消息计数。 ```typescript /** cancel 请求无参数,params 可以是空对象或省略 */ type CancelParams = Record /** cancel 响应结果为空对象 */ type CancelResult = Record ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "cancel", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8"} ``` **成功响应示例** ```json {"jsonrpc": "2.0", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8", "result": {}} ``` **错误响应示例** 如果当前没有轮次在进行: ```json {"jsonrpc": "2.0", "id": "6ba7b811-9dad-11d1-80b4-00c04fd430c8", "error": {"code": -32000, "message": "No agent turn is in progress"}} ``` ### `event` * **方向**:Agent → Client * **类型**:Notification(无需响应) Agent 在轮次进行过程中发出的事件通知。没有 `id` 字段,Client 无需响应。 ```typescript /** event 通知参数,包含序列化后的 Wire 消息 */ interface EventParams { type: string payload: object } ``` **示例** ```json {"jsonrpc": "2.0", "method": "event", "params": {"type": "ContentPart", "payload": {"type": "text", "text": "Hello"}}} ``` ### `request` * **方向**:Agent → Client * **类型**:Request(需要响应) Agent 向 Client 发出的请求,用于审批确认或外部工具调用。Client 必须响应后 Agent 才能继续执行。 ```typescript /** request 请求参数,包含序列化后的 Wire 消息 */ interface RequestParams { type: "ApprovalRequest" | "ToolCallRequest" | "QuestionRequest" payload: ApprovalRequest | ToolCallRequest | QuestionRequest } ``` **审批请求示例** ```json {"jsonrpc": "2.0", "method": "request", "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "params": {"type": "ApprovalRequest", "payload": {"id": "approval-1", "tool_call_id": "tc-1", "sender": "Shell", "action": "run shell command", "description": "Run command `ls`", "display": []}}} ``` **审批响应示例** ```json {"jsonrpc": "2.0", "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "result": {"request_id": "approval-1", "response": "approve"}} ``` **外部工具调用请求示例** ```json {"jsonrpc": "2.0", "method": "request", "id": "a3bb189e-8bf9-3888-9912-ace4e6543002", "params": {"type": "ToolCallRequest", "payload": {"id": "tc-1", "name": "open_in_ide", "arguments": "{\"path\":\"README.md\"}"}}} ``` **外部工具调用响应示例** ```json {"jsonrpc": "2.0", "id": "a3bb189e-8bf9-3888-9912-ace4e6543002", "result": {"tool_call_id": "tc-1", "return_value": {"is_error": false, "output": "Opened", "message": "Opened README.md in IDE", "display": []}}} ``` ### 标准错误码 所有请求都可能返回 JSON-RPC 2.0 标准错误: | code | 说明 | |------|------| | `-32700` | 无效的 JSON 格式 | | `-32600` | 无效的请求(如缺少必要字段) | | `-32601` | 方法不存在 | | `-32602` | 无效的方法参数 | | `-32603` | 内部错误 | ## Wire 消息类型 Wire 消息通过 `event` 和 `request` 方法传递,格式为 `{"type": "...", "payload": {...}}`。以下使用 TypeScript 风格的类型定义描述所有消息类型。 ```typescript /** 所有 Wire 消息的联合类型 */ type WireMessage = Event | Request /** 事件:通过 event 方法发送,无需响应 */ type Event = | TurnBegin | TurnEnd | StepBegin | StepInterrupted | StepRetry | CompactionBegin | CompactionEnd | StatusUpdate | ContentPart | ToolCall | ToolCallPart | ToolResult | ApprovalResponse | SubagentEvent | BtwBegin | BtwEnd | SteerInput | PlanDisplay | HookTriggered | HookResolved /** 请求:通过 request 方法发送,需要响应 */ type Request = ApprovalRequest | ToolCallRequest | QuestionRequest | HookRequest ``` ### `TurnBegin` 轮次开始。 ```typescript interface TurnBegin { /** 用户输入,可以是纯文本或内容片段数组 */ user_input: string | ContentPart[] } ``` ### `TurnEnd` ::: info 新增 新增于 Wire 1.2。 ::: 轮次结束。此事件在轮次的所有其他事件之后发送。如果轮次被中断,此事件可能不会发送。 ```typescript interface TurnEnd { // 无额外字段 } ``` ### `StepBegin` 步骤开始。 ```typescript interface StepBegin { /** 步骤编号,从 1 开始 */ n: number } ``` ### `StepInterrupted` 步骤被中断,无额外字段。 ### `StepRetry` ::: info 新增 新增于 Wire 1.10。 ::: 当前步骤尝试失败,即将重试。此事件在步骤因可恢复错误(如速率限制、连接超时、服务端错误)失败并进入重试等待时发出。Client 可以据此向用户展示重试状态,或在上一次尝试已输出部分流式内容时清除不完整状态。 ```typescript interface StepRetry { /** 步骤编号 */ n: number /** 下一次尝试的序号,从 1 开始 */ next_attempt: number /** 此步骤的最大尝试次数 */ max_attempts: number /** 等待多少秒后重试 */ wait_s: number /** 触发重试的异常类名 */ error_type: string /** HTTP 状态码(如有),JSON 中可能不存在 */ status_code?: number | null } ``` ### `CompactionBegin` 上下文压缩开始,无额外字段。 ### `CompactionEnd` 上下文压缩结束,无额外字段。 ### `StatusUpdate` 状态更新。 ```typescript interface StatusUpdate { /** 上下文使用率,0-1 之间的浮点数,JSON 中可能不存在 */ context_usage?: number | null /** 当前上下文中的 token 数量,JSON 中可能不存在 */ context_tokens?: number | null /** 上下文可容纳的最大 token 数量,JSON 中可能不存在 */ max_context_tokens?: number | null /** 当前步骤的 token 用量统计,JSON 中可能不存在 */ token_usage?: TokenUsage | null /** 当前步骤的消息 ID,JSON 中可能不存在 */ message_id?: string | null /** Plan 模式是否激活,null 表示状态未变更,JSON 中可能不存在 */ plan_mode?: boolean | null } interface TokenUsage { /** 不包括 input_cache_read 和 input_cache_creation 的输入 token 数 */ input_other: number /** 总输出 token 数 */ output: number /** 缓存的输入 token 数 */ input_cache_read: number /** 用于缓存创建的输入 token 数,目前仅 Anthropic API 支持此字段 */ input_cache_creation: number } ``` ### `ContentPart` 消息内容片段。序列化时 `type` 为 `"ContentPart"`,具体类型由 `payload.type` 区分。 ```typescript type ContentPart = | TextPart | ThinkPart | ImageURLPart | AudioURLPart | VideoURLPart interface TextPart { type: "text" /** 文本内容 */ text: string } interface ThinkPart { type: "think" /** 思考内容 */ think: string /** 加密的思考内容或签名,JSON 中可能不存在 */ encrypted?: string | null } interface ImageURLPart { type: "image_url" image_url: { /** 图片 URL,可以是 data URI(如 data:image/png;base64,...) */ url: string /** 图片 ID,用于区分不同图片,JSON 中可能不存在 */ id?: string | null } } interface AudioURLPart { type: "audio_url" audio_url: { /** 音频 URL,可以是 data URI(如 data:audio/aac;base64,...) */ url: string /** 音频 ID,用于区分不同音频,JSON 中可能不存在 */ id?: string | null } } interface VideoURLPart { type: "video_url" video_url: { /** 视频 URL,可以是 data URI(如 data:video/mp4;base64,...) */ url: string /** 视频 ID,用于区分不同视频,JSON 中可能不存在 */ id?: string | null } } ``` ### `ToolCall` 工具调用。 ```typescript interface ToolCall { /** 固定为 "function" */ type: "function" /** 工具调用 ID */ id: string function: { /** 工具名称 */ name: string /** JSON 格式的参数字符串,JSON 中可能不存在 */ arguments?: string | null } /** 额外信息,JSON 中可能不存在 */ extras?: object | null } ``` ### `ToolCallPart` 工具调用参数片段(流式)。 ```typescript interface ToolCallPart { /** 参数片段,用于流式传输工具调用参数,JSON 中可能不存在 */ arguments_part?: string | null } ``` ### `ToolResult` 工具执行结果。 ```typescript interface ToolResult { /** 对应的工具调用 ID */ tool_call_id: string return_value: ToolReturnValue } interface ToolReturnValue { /** 是否为错误 */ is_error: boolean /** 返回给模型的输出内容 */ output: string | ContentPart[] /** 给模型的解释性消息 */ message: string /** 显示给用户的内容块 */ display: DisplayBlock[] /** 额外调试信息,JSON 中可能不存在 */ extras?: object | null } ``` ### `ApprovalResponse` ::: info 变更 重命名于 Wire 1.1。原名 `ApprovalRequestResolved`,旧名称仍可使用以保持向后兼容。 ::: 审批响应事件,表示审批请求已完成。 ```typescript interface ApprovalResponse { /** 审批请求 ID */ request_id: string /** 审批结果 */ response: "approve" | "approve_for_session" | "reject" /** 拒绝时的可选反馈文本,JSON 中可能不存在 */ feedback?: string } ``` ### `BtwBegin` ::: info 新增 新增于 Wire 1.9。 ::: 侧问(`/btw`)开始处理。 ```typescript interface BtwBegin { /** 唯一 ID,用于与对应的 BtwEnd 配对 */ id: string /** 用户的侧问文本 */ question: string } ``` ### `BtwEnd` ::: info 新增 新增于 Wire 1.9。 ::: 侧问(`/btw`)处理完成。 ```typescript interface BtwEnd { /** 唯一 ID,与对应的 BtwBegin 匹配 */ id: string /** LLM 的回复文本,失败时为 null */ response?: string | null /** 失败时的错误信息 */ error?: string | null } ``` ### `SubagentEvent` ::: info 变更 变更于 Wire 1.6。`task_tool_call_id` 重命名为 `parent_tool_call_id`;新增 `agent_id` 和 `subagent_type` 字段。 ::: 子 Agent 事件。 ```typescript interface SubagentEvent { /** 关联的父 Agent 工具调用 ID,JSON 中可能不存在 */ parent_tool_call_id?: string | null /** 子 Agent 实例 ID,JSON 中可能不存在 */ agent_id?: string | null /** 此实例使用的内置子 Agent 类型,JSON 中可能不存在 */ subagent_type?: string | null /** 子 Agent 产生的事件,嵌套的 Wire 消息格式 */ event: { type: string; payload: object } } ``` ### `SteerInput` ::: info 新增 新增于 Wire 1.5。 ::: 表示用户在当前运行中的轮次追加了后续输入。此事件在当前步骤完成且输入被追加到上下文之后、下一步骤开始之前发出。 ```typescript interface SteerInput { /** 用户输入,可以是纯文本或内容片段数组 */ user_input: string | ContentPart[] } ``` ### `PlanDisplay` ::: info 新增 新增于 Wire 1.7。 ::: Plan 内容展示事件。当 Agent 在 Plan 模式下调用 `ExitPlanMode` 提交计划供用户审批时,会先发送此事件,将计划内容以内联方式展示在聊天记录中。Client 应将其渲染为带边框的面板或类似的视觉区分样式,并展示文件路径供用户参考。 ```typescript interface PlanDisplay { /** 计划的完整 Markdown 内容 */ content: string /** 计划文件的路径 */ file_path: string } ``` ### `HookTriggered` ::: info 新增 新增于 Wire 1.7。 ::: Hook 开始执行事件。当配置的 hook 被触发并开始执行时发送,用于通知客户端 hook 正在运行。 ```typescript interface HookTriggered { /** Hook 事件类型,如 'PreToolUse'、'Stop' */ event: string /** Hook 的目标:工具名称(工具 hook)、Agent 名称(子 Agent hook)等 */ target: string /** 匹配的 hook 数量(并行执行) */ hook_count: number } ``` ### `HookResolved` ::: info 新增 新增于 Wire 1.7。 ::: Hook 执行完成事件。当 hook 执行完成时发送,包含执行结果和耗时信息。 ```typescript interface HookResolved { /** Hook 事件类型,如 'PreToolUse'、'Stop' */ event: string /** 与 HookTriggered.target 相同 */ target: string /** 聚合决策:如有任一 hook 阻塞则为 'block',否则为 'allow' */ action: "allow" | "block" /** 阻塞原因,允许时为空 */ reason: string /** 整个批次的执行耗时(毫秒) */ duration_ms: number } ``` ### `ApprovalRequest` ::: info 变更 变更于 Wire 1.6。新增 `source_kind`、`source_id`、`agent_id`、`subagent_type`、`source_description` 字段。 ::: 审批请求,通过 `request` 方法发送,Client 必须响应后 Agent 才能继续。 ```typescript interface ApprovalRequest { /** 请求 ID,用于响应时引用 */ id: string /** 关联的工具调用 ID */ tool_call_id: string /** 发起者(工具名称) */ sender: string /** 操作描述 */ action: string /** 详细说明 */ description: string /** 显示给用户的内容块,JSON 中可能不存在,默认为 [] */ display?: DisplayBlock[] /** 请求来源:前台轮次或后台 Agent,JSON 中可能不存在 */ source_kind?: "foreground_turn" | "background_agent" | null /** 来源标识符(如后台 Agent ID),JSON 中可能不存在 */ source_id?: string | null /** 子 Agent 实例 ID(如来自子 Agent),JSON 中可能不存在 */ agent_id?: string | null /** 子 Agent 类型(如来自子 Agent),JSON 中可能不存在 */ subagent_type?: string | null /** 可读的来源描述,JSON 中可能不存在 */ source_description?: string | null } ``` **响应格式** ::: info 变更 变更于 Wire 1.6。新增可选的 `feedback` 字段。 ::: Client 需要返回 `ApprovalResponse` 作为响应结果: ```typescript interface ApprovalResponse { request_id: string response: "approve" | "approve_for_session" | "reject" /** 拒绝时的可选反馈文本,JSON 中可能不存在 */ feedback?: string } ``` | response | 说明 | |----------|------| | `approve` | 批准本次操作 | | `approve_for_session` | 批准本会话中的同类操作 | | `reject` | 拒绝操作;可通过 `feedback` 指示模型应如何调整 | ### `ToolCallRequest` 外部工具调用请求,通过 `request` 方法发送。当 Agent 调用 `initialize` 时注册的外部工具时,会发送此请求。Client 必须执行工具并返回 `ToolResult`。 ```typescript interface ToolCallRequest { /** 工具调用 ID */ id: string /** 工具名称 */ name: string /** JSON 格式的参数字符串,JSON 中可能不存在 */ arguments?: string | null } ``` **响应格式** Client 需要返回 `ToolResult` 作为响应结果: ```typescript interface ToolResult { tool_call_id: string return_value: ToolReturnValue } ``` ### `QuestionRequest` ::: info 新增 新增于 Wire 1.4。 ::: 结构化问答请求,通过 `request` 方法发送。当 Agent 使用 `AskUserQuestion` 工具时,会发送此请求。Client 必须响应后 Agent 才能继续执行。 此功能需要能力协商:Client 在 `initialize` 时通过 `capabilities.supports_question: true` 声明支持后,Agent 才会发送 `QuestionRequest`。如果 Client 未声明支持,`AskUserQuestion` 工具会从 LLM 的工具列表中自动隐藏,避免 LLM 调用不受支持的交互。 ```typescript interface QuestionRequest { /** 请求 ID,用于响应时引用 */ id: string /** 关联的工具调用 ID */ tool_call_id: string /** 问题列表(1–4 个问题) */ questions: QuestionItem[] } interface QuestionItem { /** 问题文本 */ question: string /** 短标签,最多 12 个字符 */ header?: string /** 可选项(2–4 个) */ options: QuestionOption[] /** 是否允许多选 */ multi_select?: boolean } interface QuestionOption { /** 选项标签 */ label: string /** 选项说明 */ description?: string } ``` **请求示例** ```json {"jsonrpc": "2.0", "method": "request", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "params": {"type": "QuestionRequest", "payload": {"id": "q-1", "tool_call_id": "tc-1", "questions": [{"question": "Which language should I use?", "header": "Lang", "options": [{"label": "Python", "description": "Widely used, large ecosystem"}, {"label": "Rust", "description": "High performance, memory safe"}], "multi_select": false}]}}} ``` **响应格式** Client 需要返回 `QuestionResponse` 作为响应结果: ```typescript interface QuestionResponse { /** 对应的请求 ID */ request_id: string /** 答案映射,键为问题文本,值为选中的选项标签(多选时用逗号分隔) */ answers: Record } ``` **响应示例** ```json {"jsonrpc": "2.0", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "result": {"request_id": "q-1", "answers": {"Which language should I use?": "Python"}}} ``` 如果 Client 不支持结构化问答或用户关闭了问题面板,可以返回空的 `answers`: ```json {"jsonrpc": "2.0", "id": "b1a2c3d4-e5f6-7890-abcd-ef1234567890", "result": {"request_id": "q-1", "answers": {}}} ``` ### `HookRequest` ::: info 新增 新增于 Wire 1.7。 ::: Hook 处理请求,通过 `request` 方法发送。当 Wire 客户端订阅了 hook 事件时,Server 会发送此请求让客户端自行处理 hook 逻辑并返回允许/阻塞决策。 此功能需要能力协商:Client 在 `initialize` 时通过 `hooks` 参数声明订阅的 hook 事件类型后,Server 才会发送对应的 `HookRequest`。 ```typescript interface HookRequest { /** 请求 ID,用于响应时引用 */ id: string /** 订阅 ID,标识哪个订阅触发了此请求 */ subscription_id: string /** Hook 事件类型,如 'PreToolUse'、'Stop' */ event: string /** 触发 hook 的目标:工具名称、Agent 名称等 */ target: string /** 完整的事件负载(与 shell hook 从 stdin 接收的内容相同) */ input_data: object } ``` **响应格式** Client 需要返回 `HookResponse` 作为响应结果: ```typescript interface HookResponse { /** 对应的请求 ID */ request_id: string /** 决策:允许或阻塞 */ action: "allow" | "block" /** 阻塞时的原因说明 */ reason: string } ``` ### `DisplayBlock` `ToolResult` 和 `ApprovalRequest` 的 `display` 字段使用的显示块类型。 ```typescript type DisplayBlock = | UnknownDisplayBlock | BriefDisplayBlock | DiffDisplayBlock | TodoDisplayBlock | ShellDisplayBlock /** 无法识别的显示块类型的 fallback */ interface UnknownDisplayBlock { /** 任意类型标识 */ type: string /** 原始数据 */ data: object } interface BriefDisplayBlock { type: "brief" /** 简短的文本内容 */ text: string } interface DiffDisplayBlock { type: "diff" /** 文件路径 */ path: string /** 原始内容 */ old_text: string /** 新内容 */ new_text: string /** 是否为摘要块(文件过大时显示行数摘要而非实际 diff),JSON 中可能不存在。新增于 Wire 1.8 */ is_summary?: boolean } interface TodoDisplayBlock { type: "todo" /** 待办事项列表 */ items: TodoDisplayItem[] } interface TodoDisplayItem { /** 待办事项标题 */ title: string /** 状态 */ status: "pending" | "in_progress" | "done" } interface ShellDisplayBlock { type: "shell" /** 语法高亮的语言标识(如 "sh"、"powershell") */ language: string /** Shell 命令内容 */ command: string } ``` ## Kimi Agent(Rust)Wire Server ::: warning 注意 Kimi Agent 目前为实验性功能,API 和行为可能在后续版本中发生变化。 ::: Kimi Agent (Rust) 是 Kimi Code CLI 内核的 Rust 实现,专为 Wire 模式设计。如果你只需要 Wire 协议服务,Kimi Agent (Rust) 提供了一个更轻量的选择。Rust 实现位于 [`MoonshotAI/kimi-agent-rs`](https://github.com/MoonshotAI/kimi-agent-rs)。 ### 特点 * **Wire 协议完全兼容**:与 Python 版 `kimi --wire` 使用相同的 Wire 协议,现有客户端无需修改 * **更小的体积**:单一静态链接二进制,无需 Python 运行时 * **更快的启动**:原生编译,启动速度更快 * **相同的配置**:使用相同的配置文件(`~/.kimi/config.toml`)和会话目录 ### 限制 * **仅支持 Wire 模式**:没有 Shell/Print/ACP UI * **仅支持 Kimi 供应商**:不支持 OpenAI、Anthropic 等其他供应商 * **无 Kimi 账号登录功能**:没有 `login`/`logout` 子命令和 `/login`、`/logout` 斜杠命令,需要手动配置 API 密钥 * **不支持 `--prompt`/`--command`**:Wire 服务器不接受初始提示词 * **仅支持本地执行**:没有 SSH Kaos 支持 * **MCP OAuth 存储位置不同**:Kimi Agent 存储在 `~/.kimi/credentials/mcp_auth.json`,Python 版存储在 `~/.kimi/mcp-oauth/`,两者不兼容 ### 安装 从 [GitHub Releases](https://github.com/MoonshotAI/kimi-agent-rs/releases) 下载预编译的二进制文件: ```sh # macOS (Apple Silicon) curl -L https://github.com/MoonshotAI/kimi-agent-rs/releases/latest/download/kimi-agent-aarch64-apple-darwin.tar.gz | tar xz sudo mv kimi-agent /usr/local/bin/ # Linux (x86_64) curl -L https://github.com/MoonshotAI/kimi-agent-rs/releases/latest/download/kimi-agent-x86_64-unknown-linux-gnu.tar.gz | tar xz sudo mv kimi-agent /usr/local/bin/ ``` ### 使用 Kimi Agent 默认运行 Wire 模式: ```sh kimi-agent ``` 常用选项与 `kimi` 命令相同: ```sh # 指定工作目录 kimi-agent --work-dir /path/to/project # 继续上一个会话 kimi-agent --continue # 使用指定会话 kimi-agent --session # 使用指定模型 kimi-agent --model k2 # YOLO 模式(跳过审批) kimi-agent --yolo ``` 子命令: ```sh # 显示版本和环境信息 kimi-agent info # 管理 MCP 服务器 kimi-agent mcp list kimi-agent mcp add [args...] kimi-agent mcp remove ``` ### 版本同步 Kimi Agent 与 Kimi Code CLI 独立发版。兼容性与同步状态以 `MoonshotAI/kimi-agent-rs` 的发布说明为准。 --- --- url: /zh/guides/interaction.md --- # 交互与输入 Kimi Code CLI 提供了丰富的交互功能,帮助你高效地与 AI 协作。 ## Agent 与 Shell 模式 Kimi Code CLI 有两种输入模式: * **Agent 模式**:默认模式,输入的内容会发送给 AI 处理 * **Shell 模式**:直接执行 Shell 命令,无需离开 Kimi Code CLI 按 `Ctrl-X` 可以在两种模式之间切换。当前模式会显示在底部状态栏中。 在 Shell 模式下,你可以像在普通终端中一样执行命令: ```sh $ ls -la $ git status $ npm run build ``` Shell 模式也支持部分斜杠命令,包括 `/help`、`/exit`、`/version`、`/editor`、`/changelog`、`/feedback`、`/export`、`/import` 和 `/task`。 ::: warning 注意 Shell 模式中每个命令独立执行,`cd`、`export` 等改变环境的命令不会影响后续命令。 ::: ## Plan 模式 Plan 模式是一种只读的规划模式,让 AI 在动手编码之前先制定实施方案,避免在错误方向上浪费精力。 在 Plan 模式下,AI 只能使用只读工具(`Glob`、`Grep`、`ReadFile`)探索代码库,不能修改任何文件或执行命令。AI 会将方案写入一个专门的 plan 文件,然后提交给你审批。你可以选择批准、拒绝或提供修改意见。 ### 进入 Plan 模式 有四种方式进入 Plan 模式: * **启动参数**:使用 `kimi --plan` 直接以 Plan 模式启动新会话 * **快捷键**:按 `Shift-Tab` 切换 Plan 模式的开关 * **斜杠命令**:输入 `/plan` 或 `/plan on` * **AI 主动触发**:面对复杂任务时,AI 可能会通过 `EnterPlanMode` 工具请求进入 Plan 模式,你可以选择同意或拒绝 你也可以在配置文件中设置 `default_plan_mode = true`,让每次新建会话都默认进入 Plan 模式。详见 [配置文件](../configuration/config-files.md)。 在 YOLO 模式下,AI 主动请求进入 Plan 模式会自动通过,但通过 `ExitPlanMode` 退出 Plan 模式时仍会请求你审批方案。在 AFK 模式下,因为用户不在场,进入和退出 Plan 模式都会自动批准。 进入 Plan 模式后,提示符会变为 `📋`,底部状态栏会显示蓝色的 `plan` 标识。 ### 审批方案 AI 完成方案后会通过 `ExitPlanMode` 提交审批。审批面板会显示完整的方案内容,你可以: * **批准执行**:如果方案包含多个可选实施路径,AI 会列出 2–3 个带标签的选项(如 "方案 A"、"方案 B (Recommended)")供你选择,选中后 AI 退出 Plan 模式并按该路径执行;如果方案只有一条路径,则显示 **Approve** 按钮 * **Reject**:拒绝方案,保持 Plan 模式,你可以在对话中提供反馈 * **Reject and Exit**:拒绝方案并退出 Plan 模式,一步完成拒绝和退出操作 * **Revise**:输入修改意见,AI 会据此修订方案并重新提交 按 `Ctrl-E` 可以在全屏分页器中查看完整方案内容。 ### 管理 Plan 模式 使用 `/plan` 命令可以管理 Plan 模式: * `/plan`:切换 Plan 模式开关 * `/plan on`:开启 Plan 模式 * `/plan off`:关闭 Plan 模式 * `/plan view`:查看当前方案内容 * `/plan clear`:清除当前方案文件 ## Thinking 模式 Thinking 模式让 AI 在回答前进行更深入的思考,适合处理复杂问题。 你可以通过 `/model` 命令切换模型和 Thinking 模式。在选择模型后,如果模型支持 Thinking 模式,系统会询问是否开启。也可以在启动时通过 `--thinking` 参数启用: ```sh kimi --thinking ``` ::: tip 提示 Thinking 模式需要当前模型支持。部分模型(如 `kimi-k2-thinking-turbo`)始终使用 Thinking 模式,无法关闭。 ::: ## 运行中发送消息 当 AI 正在执行任务时,你可以通过两种方式发送后续消息,无需等待当前轮次结束: * **排队(Enter)**:按 `Enter` 将消息放入队列,等当前轮次完成后再自动发送。排队消息数量会显示在输入区标题中(如 `── input · 2 queued ──`),在空输入框中按 `↑` 可召回最后一条排队消息进行编辑 * **立即注入(Ctrl+S)**:按 `Ctrl+S` 将消息立即注入到正在运行的轮次上下文中,模型会立即看到你的消息 在 AI 运行期间,审批请求和问答面板也支持内联键盘交互。 ::: tip 提示 如果需要立即中断 AI 的执行,请使用 `Ctrl-C`。 ::: ## 侧问 在 AI 工作期间,你可以使用 `/btw` 命令提出快速侧问,不会打断主对话流程。 ``` /btw 这个函数的返回类型是什么? ``` 侧问在隔离的上下文中运行:能看到对话历史但不会修改它,也不会调用工具。响应会显示在一个可滚动的模态面板中,使用 `↑`/`↓` 滚动,`Escape` 关闭。 详见 [斜杠命令参考](../reference/slash-commands.md#btw)。 ## 后台任务 当 AI 需要执行耗时较长的命令(如构建项目、运行测试套件、启动开发服务器)时,可以将命令作为后台任务启动。后台任务在独立进程中运行,AI 可以继续处理其他请求,无需等待命令完成。 后台任务的工作流程: 1. AI 使用 `Shell` 工具的 `run_in_background=true` 参数启动命令 2. 工具立即返回任务 ID,AI 继续处理其他工作 3. 任务完成后,如果 AI 处于空闲状态(等待用户输入),系统会自动触发新的 Agent 轮次来处理结果,无需你手动输入 你可以使用 `/task` 斜杠命令打开交互式任务浏览器,实时查看所有后台任务的状态和输出(包括正在运行中的任务)。详见 [斜杠命令参考](../reference/slash-commands.md#task)。 ::: tip 提示 默认最多同时运行 4 个后台任务,可在配置文件的 `[background]` 节中调整。CLI 退出时默认会终止所有后台任务。详见 [配置文件](../configuration/config-files.md#background)。 ::: ## 多行输入 有时你需要输入多行内容,比如贴入一段代码或错误日志。按 `Ctrl-J` 或 `Alt-Enter` 可以插入换行,而不是直接发送消息。 输入完成后,按 `Enter` 发送整条消息。 ## 剪贴板与媒体粘贴 按 `Ctrl-V` 可以粘贴剪贴板中的文本、图片或视频文件。 在 Agent 模式下,较长的粘贴文本(超过 1000 字符或 15 行)会自动折叠为 `[Pasted text #n]` 占位符显示在输入框中,保持界面整洁。完整内容仍会在发送时展开并传递给模型。使用外部编辑器(`Ctrl-O`)时,占位符会自动展开为原始文本,保存后未修改的部分重新折叠。 如果剪贴板中是图片,Kimi Code CLI 会将图片缓存到磁盘并在输入框中显示为 `[image:…]` 占位符。发送消息后,AI 可以看到并分析这张图片。如果剪贴板中是视频文件,其文件路径会以文本形式插入输入框。 ::: tip 提示 图片输入需要当前模型支持 `image_in` 能力,视频输入需要支持 `video_in` 能力。 ::: ## 斜杠命令 斜杠命令是以 `/` 开头的特殊指令,用于执行 Kimi Code CLI 的内置功能,如 `/help`、`/login`、`/sessions` 等。输入 `/` 后会自动显示可用命令列表。完整的斜杠命令列表请参考 [斜杠命令参考](../reference/slash-commands.md)。 ## @ 路径补全 在消息中输入 `@` 后,Kimi Code CLI 会自动补全工作目录中的文件和目录路径。这让你可以方便地引用项目中的文件: ``` 帮我看一下 @src/components/Button.tsx 这个文件有没有问题 ``` 输入 `@` 后开始输入文件名,会显示匹配的补全项。按 `Tab` 或 `Enter` 选择补全项。在 Git 仓库中,文件发现优先使用 `git ls-files` 查询,可以在包含数万文件的大型仓库中快速定位文件;非 Git 项目则回退到目录扫描。 ## 结构化问答 在执行过程中,AI 可能需要你做出选择来决定下一步方向。此时 AI 会使用 `AskUserQuestion` 工具向你展示结构化的问题和选项。 问题面板会显示问题描述和可选项,你可以通过键盘选择: * 使用方向键(上 / 下)浏览选项 * 按 `Enter` 确认选择 * 按 `Space` 切换多选模式下的选中状态 * 选择 "Other" 选项可以输入自定义文本 * 按 `Esc` 跳过问题 每个问题支持 2–4 个预定义选项,AI 会根据当前任务上下文设置合适的选项和说明。如果有多个问题需要回答,面板会以标签页形式展示,使用左右方向键或 `Tab` 键在问题间切换,已回答的问题会标记为已完成状态,切换回已回答的问题时会恢复之前的选择。 ::: tip 提示 AI 只会在你的选择真正影响后续操作时才使用此工具。对于能从上下文推断的决策,AI 会自行判断并继续执行。 ::: ## 审批与确认 当 AI 需要执行可能有影响的操作(如修改文件、运行命令)时,Kimi Code CLI 会请求你的确认。 确认提示会显示操作的详情,包括 Shell 命令和文件 Diff 预览。如果内容较长被截断,可以按 `Ctrl-E` 展开查看完整内容。你可以选择: * **允许**:执行这次操作 * **本会话允许**:在当前会话中自动批准同类操作(此决策会随会话持久化,恢复会话时自动还原) * **拒绝**:不执行此操作 * **附带反馈拒绝**:拒绝操作并输入文字反馈,告诉 Agent 应该如何调整 如果你信任 AI 的操作,或者你正在安全的隔离环境中运行 Kimi Code CLI,可以启用「YOLO 模式」来自动批准所有工具调用: ```sh # 启动时启用 kimi --yolo # 或在运行中切换 /yolo ``` 你也可以在配置文件中设置 `default_yolo = true`,每次启动时默认开启 YOLO 模式。详见 [配置文件](../configuration/config-files.md)。 开启 YOLO 模式后,底部状态栏会显示黄色的 YOLO 标识。再次输入 `/yolo` 可关闭。 YOLO 只解除“审批确认”的摩擦——Agent 仍然把你当作在场的用户,在关键决策点仍可能通过 `AskUserQuestion` 向你提问。如果你实际上要离开终端,请改用下面的 AFK 模式。 ::: warning 注意 YOLO 模式会跳过所有审批确认,请确保你了解可能的风险。建议仅在可控环境中使用。 ::: ### AFK 模式 当你要暂时离开终端、又希望 Agent 在你不在时也能继续运行,可以启用「AFK 模式」(away-from-keyboard): ```sh # 启动时启用 kimi --afk # 或在运行中切换 /afk ``` AFK 模式也会自动批准所有工具调用,并且会自动 dismiss 模型发出的任何 `AskUserQuestion`——让 Agent 自己做决策,而不是傻等一个永远不会到来的回答。`--print` 模式出于同样的原因会隐式启用 `--afk`。 开启 AFK 后,状态栏会显示独立的橙色 AFK 标识,与 YOLO 标识各不相干。再次输入 `/afk` 可关闭。 ::: warning 注意 AFK 会跳过所有审批确认,并且去掉了通过提问澄清的安全网。仅在你确实无法守在终端前、且信任当前任务范围时使用。 ::: --- --- url: /zh/guides/sessions.md --- # 会话与上下文 Kimi Code CLI 会自动保存你的对话历史,方便你随时继续之前的工作。 ## 会话续接 每次启动 Kimi Code CLI 时,都会创建一个新的会话。在运行过程中,你也可以输入 `/new` 命令随时创建并切换到一个新会话,无需退出程序。 如果你想继续之前的对话,有几种方式: **继续最近的会话** 使用 `--continue` 参数可以继续当前工作目录下最近的会话: ```sh kimi --continue ``` **交互式选择会话** 使用 `--session`(或 `--resume`、`-S`、`-r`)不带参数可以打开交互式会话选择器,用方向键选择要恢复的会话: ```sh kimi --session ``` > 交互式选择器仅在 Shell 模式下可用。 **恢复指定会话** 使用 `--session`(或 `--resume`)加上会话 ID 可以恢复指定的会话: ```sh kimi -r abc123 ``` 如果指定的会话 ID 不存在,会自动创建一个新会话。 **在运行中切换会话** 输入 `/sessions`(或 `/resume`)可以查看当前工作目录的所有会话列表,使用方向键选择要切换的会话: ``` /sessions ``` 列表会显示每个会话的标题和最后更新时间,帮助你找到想要继续的对话。按 `Ctrl-A` 可在 「仅当前目录」 和 「所有目录」 之间切换范围,方便跨项目查找会话。使用 `/title ` 可以为会话设置一个自定义标题,方便后续查找。 **退出时的续接提示** 当会话退出时(包括正常退出、`Ctrl-C` 中断、`/undo`、`/fork`、`/sessions` 切换等场景),Kimi Code CLI 会自动打印一条续接命令提示: ``` To resume this session: kimi -r ``` 你可以直接复制这条命令,下次在终端中运行即可快速恢复该会话。空会话不会显示此提示。 **启动回放** 当你继续一个已有会话时,Kimi Code CLI 会回放之前的对话历史,让你快速了解上下文。回放过程中会显示之前的消息和 AI 的回复。 ## 会话状态持久化 除了对话历史,Kimi Code CLI 还会自动保存和恢复会话的运行状态。当你恢复一个会话时,以下状态会自动还原: * **审批决策**:YOLO 和 AFK 模式的开关状态、通过 "本会话允许" 批准过的操作类型 * **Plan 模式**:Plan 模式的开关状态 * **子 Agent 实例**:通过 `Agent` 工具在会话中创建的子 Agent 实例状态和上下文历史 * **额外目录**:通过 `--add-dir` 或 `/add-dir` 添加的工作区目录 这意味着你不需要在每次恢复会话时重新配置这些设置。例如,如果你在上次会话中批准了某类 Shell 命令的自动执行,恢复会话后这些批准仍然有效。 ## 导出与导入 Kimi Code CLI 支持将会话上下文导出为文件,或从外部文件和其他会话导入上下文。 **导出会话** 输入 `/export` 可以将当前会话的完整对话历史导出为 Markdown 文件: ``` /export ``` 导出文件包含会话元数据、对话概览和按轮次组织的完整对话记录。你也可以指定输出路径: ``` /export ~/exports/my-session.md ``` **导入上下文** 输入 `/import` 可以从文件或其他会话导入上下文。导入的内容会作为参考信息附加到当前会话中: ``` /import ./previous-session-export.md /import abc12345 ``` 支持导入常见的文本格式文件(Markdown、代码、配置文件等)。你也可以传入一个会话 ID,从该会话导入完整的对话历史。 ::: tip 提示 导出文件可能包含敏感信息(如代码片段、文件路径等),分享前请注意检查。 ::: ## 清空与压缩 随着对话的进行,上下文会越来越长。Kimi Code CLI 会在需要的时候自动对上下文进行压缩,确保对话能够继续。 你也可以使用斜杠命令手动管理上下文: **清空上下文** 输入 `/clear` 可以清空当前会话的所有上下文,重新开始对话: ``` /clear ``` 清空后,AI 会忘记之前的所有对话内容。通常你不需要使用这个命令,对于新任务,开启新的会话会是更好的选择。 **压缩上下文** 输入 `/compact` 可以让 AI 总结当前的对话,并用总结替换原有的上下文: ``` /compact ``` 你也可以在命令后附带自定义指引,告诉 AI 在压缩时优先保留哪些内容: ``` /compact 保留数据库相关的讨论 ``` 压缩会保留关键信息,同时减少 token 消耗。这在对话很长但你还想保留一些上下文时很有用。 ::: tip 提示 底部状态栏会显示当前的上下文使用率和 Token 数量(如 `context: 42.0% (4.2k/10.0k)`),帮助你了解何时需要清空或压缩。 ::: ::: tip 提示 `/clear` 和 `/reset` 会清空对话上下文,但不会重置会话状态(如审批决策、动态子 Agent 和额外目录)。如需完全重新开始,建议创建一个新会话。 ::: --- --- url: /zh/release-notes/changelog.md --- # 变更记录 本页面记录 Kimi Code CLI 各版本的变更内容。 ## 未发布 ## 1.51.0 (2026-09-21) **亮点**:Kimi CLI 已归档,不再维护,这是最后一个版本。请迁移至 [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code),详见 [迁移指南](https://moonshotai.github.io/kimi-code/zh/guides/migration) * Build:将 `kimi-cli` 及本仓库中的所有包标记为已归档——此后不再发布新版本、Bug 修复或安全更新 * Build:PyPI 上的 `kimi-code` 包不再安装旧版 CLI——运行 `kimi-code` 时改为打印新版 Kimi Code CLI 的安装说明,并以状态码 1 退出 ## 1.50.0 (2026-09-02) * Kosong:当没有声明任何 beta 特性时不再发送值为空的 `anthropic-beta` 请求头——adaptive thinking 会移除 interleaved-thinking beta,此前会留下一个空值请求头,部分后端会拒绝该请求 ## 1.49.0 (2026-07-16) **亮点**:Kimi 供应商的补全 token 预算现在会根据模型剩余上下文窗口动态调整,减少长轮次中的上下文超限错误 * LLM:将 Kimi 的补全 token 预算钳制在模型剩余上下文窗口内——CLI 不再固定发送 `max_tokens=32000`,而是按每次请求估算剩余上下文并据此设置 `max_completion_tokens` 上限。可通过新的环境变量 `KIMI_MODEL_MAX_COMPLETION_TOKENS` 设置显式硬上限(`KIMI_MODEL_MAX_TOKENS` 仍为兼容别名;设为 `0` 或负值可关闭钳制) * Kosong:配置 Thinking 模式时不再自动向 Kimi 请求发送旧版 `reasoning_effort` 参数——请求现在仅使用 `thinking.type`,同时保留显式传递旧版参数的兼容能力 * Kosong:修复 Thinking 模型返回的空字符串 `reasoning_content` 被从历史中丢弃的问题——此前「思考过但内容为空」的回复会被当作「没有思考」,导致要求每条 Assistant 消息都携带 `reasoning_content` 的 Preserved Thinking 后端在下一次请求时返回 400 ## 1.47.0 (2026-06-05) * Shell:引导用户升级到新版独立 Kimi Code——新增 `/upgrade` 命令一键安装(自动迁移现有配置与会话),并新增欢迎界面提示与每天一次的退出提示 * Shell:命令执行失败时在工具错误简报中显示末尾输出 ## 1.46.0 (2026-05-28) * Shell:欢迎提示支持样式化文本 * ACP:加载时回放会话历史 * Core:修复退出时 TTY 挂起的问题 * Core:在关闭期间断开 MCP 连接 ## 1.45.0 (2026-05-26) * Shell:`/clear` 现在成为 `/new` 的别名——两者都会启动新会话;此前 `/clear` 仅清空上下文而不创建新会话 * Shell:修复 403 响应一律显示 "Quota exceeded" 前缀的问题 ## 1.44.0 (2026-05-13) * Shell:新增斜杠命令别名解析——别名(如 `/h`、`?`、`status`)现在能正确解析到对应的正式命令(`/help`、`/usage`);补全器和帮助输出会将别名匹配项显示为 `/name (alias)`,方便识别 * Shell:修复 `/usage` 的别名注册——别名原先被错误地登记为 `"/status"` 而非 `"status"`,导致别名查找失败 ## 1.43.0 (2026-05-12) * Security:将 pillow 升级到 12.2.0 以修复 CVE-2026-25990(加载 PSD 图像时存在越界写入);解除在依赖审查严格的环境下因旧版本被阻断而无法安装的限制 * Shell:修复终端界面中多处视觉间距丢失的问题——在用户输入回显、内容块、工具调用结果、通知、错误面板和 steer 输入等场景后补充空行,避免相邻元素挤在一起 * Shell:恢复 Markdown 链接高亮样式(链接文本为亮蓝色下划线,URL 为青色下划线),并为 h2-h6 标题添加下划线分隔符;调整表格渲染为带可见边框的方形样式 * Core:后台任务完成时的系统通知现在包含完成时间戳和运行时长,通知 payload 中新增 `finished_at` 和 `duration_s` 字段,方便追踪 * MCP:将 MCP 客户端栈升级到 FastMCP 3.2.4,避免 FastMCP OAuth 启动路径打印 Authlib 弃用警告 * MCP:使用 FastMCP 3 的持久化存储 API,将 OAuth MCP token 存储在 `~/.kimi/mcp-oauth/`;已有 OAuth MCP 授权的用户升级后可能需要重新运行一次 `kimi mcp auth ` ## 1.42.0 (2026-05-11) * Shell:把 Windows 上的 Shell 后端从 PowerShell 切换到 Git Bash——Shell 工具现在通过 `bash.exe`(POSIX 语义)执行命令,而不再使用 `powershell.exe`。Windows 用户能使用与 Linux/macOS 一致的 Unix 风格语法(`&&`、`||`、`|`、`/dev/null`、`grep`、`sed` 等)。**需要先安装 Git for Windows**:kimi-cli 按以下顺序查找 `bash.exe`:环境变量 `KIMI_CLI_GIT_BASH_PATH` → `where.exe git` → 标准安装路径(`C:\Program Files\Git\bin\bash.exe`);如果都找不到,启动时打印安装提示并退出 * Shell:防御 Windows 上模型偶尔幻觉出的 CMD 风格 `2>nul` 重定向——在命令进入 git-bash 前自动改写为 `2>/dev/null`;如果不防御,git-bash 会真的创建一个名为 `nul` 的文件(Windows 保留设备名),破坏 `git add .` 和 `git clone`。该改写仅在 Windows 上生效;Linux/macOS 上 `>nul` 是合法的写入到名为 `nul` 文件的重定向,保持原样 * File:`ReadFile`、`WriteFile`、`StrReplaceFile`、`Glob`、`Grep` 在 Windows 上接受 POSIX 形式的路径——除原生 Windows 路径外,这些工具现在能识别 `/c/Users/foo`(Git Bash 形式)、`/cygdrive/c/Users/foo`(Cygwin 形式)和 `\\server\share`(UNC 形式),并在文件系统操作前自动转换为原生形式 * Shell:在 LLM 步骤重试时清除已流式输出的不完整内容——以前,如果某个步骤在流式输出中途失败(例如触发速率限制或服务器错误),被中断尝试所产生的未完成文本和未结束的工具调用块会留在屏幕上,并与新尝试的输出混在一起。现在 Shell 界面会丢弃这部分不完整状态,并打印一条重试横幅,显示失败原因、尝试次数和等待时间;Print 模式也会在重试时丢弃已缓冲的 Assistant 消息 * Wire:协议版本升级到 1.10——新增 `StepRetry` 事件,在步骤尝试失败并即将重试时发出,携带尝试次数、等待时间和错误详情 * Core:不再向子代理注入 plan 模式和 afk 模式的工作流 prompt——子代理会共享会话级模式状态以支持持久化和恢复,但其 YAML 通常不包含 `EnterPlanMode`、`ExitPlanMode`、`AskUserQuestion` 等 root 工作流工具。现在这些 prompt injection 只注入给 root agent。Plan 模式下工具层的只读检查保持不变,行为兼容性不受影响 ## 1.41.0 (2026-04-30) * Plugin:支持直接从 `.zip` URL 安装插件——`kimi plugin install` 现在可以接受以 `.zip` 结尾的 HTTP(S) URL(例如 GitHub/GitLab 的 archive 链接 `.../archive/refs/heads/main.zip`),下载后解压再解析 `plugin.json`,与原有的 git URL、本地目录、本地 zip 文件三种来源并列 * Shell:在无显示环境的 Linux(如 SSH 远程)上启用剪贴板图片粘贴——当 pyperclip 不可用(例如 DISPLAY 未设置)时,Ctrl-V 现在会回退到 xclip 或 wl-paste,使远程剪贴板桥接仍能注入图片;同时防止 pyperclip 失效时内置剪贴板快捷键造成 UI 崩溃 ## 1.40.0 (2026-04-28) * Core:修复 `--yolo` 模式意外阻止模型调用 `AskUserQuestion` 的问题——以前 yolo 会注入一段 system reminder,告诉模型当前处于“非交互模式”,不能向用户提问;同时 ask-user 工具在 yolo 下也会自动 dismiss。这两处都是错的:yolo 只绕过权限审批,并不意味着“用户已离开”。现在 yolo 不再向模型注入指导;用户仍可通过 `AskUserQuestion` 触达 * CLI:把权限审批绕过和无人值守执行拆分为两个正交模式——`--yolo` 表示用户仍在终端前、但绕过权限审批;`--afk` / `/afk` 表示 away-from-keyboard:`AskUserQuestion` 会被自动 dismiss,审批也会自动处理。`--print` 现在使用 runtime AFK 行为而不是 yolo,更符合它的非交互执行模型。状态栏独立显示 `yolo` 和 `afk`,`/yolo` 与 `/afk` 各自切换自身的 flag,互不干扰 * Config:由于 yolo 不再向模型注入指导,`skip_yolo_prompt_injection` 替换为 `skip_afk_prompt_injection`。旧配置键如果仍存在会被忽略 * Shell:修复 afk 开启时 `/yolo` 切换产生误导性 UI 文案的问题——以前 `/yolo` 读的是 yolo 和 afk 合并后的自动审批状态,afk 开着时按 `/yolo` 会说“现在需要审批”,但 afk 仍会自动处理审批。现在 `/yolo` 只读写 yolo 自身的 flag,不碰 afk * Web:修复 AI 标题生成在用户已手动重命名后才返回时覆盖手动标题的问题——最终写入前会重新读取状态,若另一请求已将 `title_generated` 标记为完成,则尊重新标题不再覆盖 * Web:会话重命名、归档、取消归档、生成标题失败时弹出 toast 提示,而不仅仅是记录到 console * Web:折叠工具详情后仍保留工具媒体预览——工具返回的图片和视频现在渲染在工具卡片下方,而不是折叠详情区域内部,因此折叠工具后预览缩略图仍然可见 * Kosong:修复 Kimi 供应商在 OAuth 令牌刷新后仍使用过期的 API 密钥的问题——`on_retryable_error` 现在从当前 client 读取 `api_key`,而不是缓存的 `_api_key`,因此在可重试错误后重建 client 时会保留通过 `client.api_key` 应用的 OAuth 令牌刷新 * Core:修复审批请求 5 分钟自动超时并被误报为 `Rejected by user` 的问题;现在活跃的前台和子 Agent 审批请求都会无限等待用户响应 * Shell:修复 `/usage` 剩余额度渲染错误——进度条、告警颜色和 `% left` 文案现在都统一基于剩余额度比例计算,剩余额度充足时显示为绿色满格,接近耗尽时显示为黄色或红色 * Shell:在提示框状态栏显示当前正在运行的后台 Agent 任务数——原有的 `⚙ bash: N` 徽章只统计后台 Shell 任务,把后台 Agent 子代理过滤掉了,所以多个子代理同时在跑时提示框看起来像空闲,用户无法判断工作是否还在进行;现在状态栏会渲染 `⚙ bash: N` 与 `⚙ agent: N` 两个相互独立的徽章(任一计数为 0 时自动隐藏),终端太窄无法同时容纳两者时优先丢弃 agent 徽章 * Auth:修复 OAuth 用户 access token 过期时托管模型列表刷新静默失败的问题——后台 `/models` 同步任务现在会检测 401 响应,强制进行 OAuth token 刷新并用刷新后的 token 重试;如果刷新本身失败或刷新后的 token 仍被拒绝,则回退到最初配置的静态 API 密钥,而不是跳过该 provider * Core:修复连接恢复后重试返回 401 时未能触发 OAuth 刷新的问题——在 `APIConnectionError` 或 `APITimeoutError` 后重建 HTTP 客户端时,重试现在会重新进入完整恢复路径,使得后续的 401 能正确刷新 OAuth token,而不是作为不可恢复的错误直接抛给用户 * Shell:在 transcript 中回显 `/skill:*` 和 `/flow:*` 输入,工作流命令按下回车后不再消失;`/usage`、`/model` 等操作类斜杠命令仍然保持隐藏 * Core:将默认 `max_steps_per_turn` 从 500 提升到 1000,长任务更不容易撞到单轮步数上限 ## 1.39.0 (2026-04-24) * Skill:修复项目级 Skill 被忽略、用户级 Skill 在同名冲突时静默获胜的问题——系统提示现在会把发现到的 Skill 按 `### Project` / `### User` / `### Extra` / `### Built-in` 四个分组呈现,让模型能分辨出每个 Skill 来自哪一层;当同一 Skill 名称同时存在于多个作用域时,越具体的作用域优先(Project > User > Extra > Built-in),项目自身的 `.kimi/skills/foo` 或 `.claude/skills/foo` 现在能正确覆盖用户级或内置的同名 `foo`,而不是被它们覆盖 * Skill:除了标准的 `/SKILL.md` 子目录结构之外,现在也会识别 Skills 目录下的扁平 `.md` 单文件 Skill——便于将扁平 Markdown 集合迁移到 Skills 目录;`name` 默认取文件名去掉 `.md` 后的部分(frontmatter 里显式写了 `name:` 时以 frontmatter 为准),描述解析与子目录形式统一走同一条三级链(frontmatter `description:` → 正文第一个非空行,超过 240 字符会截断 → `"No description provided."` 兜底);当同目录下扁平 `.md` 和子目录形式同名时,以子目录为准,并记录一条警告日志 * Skill:新增 `extra_skill_dirs` 配置项,用于在内置 / 用户级 / 项目级自动发现的基础上追加自定义 Skills 目录——每一项可以是绝对路径、`~` 前缀路径(会按 `$HOME` 展开),或相对于项目根的路径(即 `work_dir` 向上第一个包含 `.git` 的目录,不是当前工作目录);不存在的条目会被静默跳过,同一路径的软链接或带尾部斜杠的写法会被 canonicalize 归并为一条根,避免同一目录在系统提示里重复出现 * Skill:强化 Skill 发现对 `is_dir` / `iterdir` 抛出 `OSError` 的容错(例如 `extra_skill_dirs` 指向一个权限受限的目录)——受影响的条目会被记录并跳过,不会让整轮 Skill 发现失败中断 * Core:修复 DeepSeek V4(以及其它走 `openai_legacy` 的 OpenAI 兼容 Thinking 模式后端)在思考轮次后紧跟工具调用时,被 API 以 400 `The reasoning_content in the thinking mode must be passed back to the API` 拒绝的问题——`openai_legacy` 供应商现在默认 `reasoning_key = "reasoning_content"`,模型响应中的推理内容会被正确存入历史,并在后续轮次自动回传给 API。同时给 `LLMProvider` 新增可选字段 `reasoning_key`,便于覆盖字段名(例如非标网关使用的 `"reasoning"`)或设置为 `""` 完全关闭推理内容回传 * Core:新增 `skip_yolo_prompt_injection` 配置项,用于抑制 yolo 模式下注入的系统提示词——基于 `KimiSoul` 构建自定义应用且不需要该提示时很有用 * Kimi:新增环境变量 `KIMI_MODEL_THINKING_KEEP`,将其值原样作为 `thinking.keep` 字段发送给 Moonshot API,用于启用 Preserved Thinking(例如 `export KIMI_MODEL_THINKING_KEEP=all` 可让模型在多轮之间保留历史 `reasoning_content`);仅对支持 Preserved Thinking 的 Moonshot 模型(如 `kimi-k2.6` / `kimi-k2-thinking`)生效,未设置或空字符串时请求体不携带该字段、等同当前默认行为,且仅在当前模型真正处于 Thinking 模式时才注入,以避免 API 收到只有 `thinking.keep` 而缺少 `thinking.type` 的无效请求体。注意 `keep=all` 会因为重新发送历史推理内容而显著增加输入 token 与 API 费用 * Kosong:修复 `Kimi.with_extra_body` 在后续调用新增其它 `thinking.*` 字段时静默丢掉已有 `thinking.type` 的问题——`thinking` 子对象现在按字段合并,而不是被整体浅覆盖,使得 `with_thinking(...)` 与 `with_extra_body({"thinking": {...}})` 组合使用时两次设置的字段都能保留 * Kosong:修复 Kimi provider 在 `tool_calls` 旁发送空 `content` 导致 Moonshot API 返回 400 "text content is empty" 错误的问题。当 Assistant 消息带有工具调用且可见内容实际为空(无文本或仅包含空白 / think 部分)时,现在会完全省略 `content` 字段 * Shell:修复审批请求反馈文本输入的光标渲染问题——光标块现在根据实际光标位置正确渲染,不再始终固定在行尾;当光标位于文本中间时,光标所在字符会以反色显示(模拟终端原生块光标效果) * Kosong:修复接入某些 MCP 服务端(如 JetBrains Rider MCP 的 `truncateMode`)时,Moonshot API 以 `400 At path 'properties.X': type is not defined` 拒绝每次请求导致会话完全无法使用的问题——这些 MCP 工具的参数 schema 里有仅声明 `enum`/`const` 或根本没有类型提示的属性,符合 JSON Schema 规范但过不了 Moonshot 的严格校验;现在 Kimi 供应商会在发送前为每个工具 schema 补齐 JSON Schema `type`(尽量从 `enum`/`const` 值推断,否则默认 `"string"`),OpenAI 和 Anthropic 路径不受影响 * Skill:项目级 Skill 发现现在会先向上查找最近的 `.git` 祖先目录,再查 `.kimi/skills` / `.claude/skills` / `.codex/skills` / `.agents/skills`,这样即使从子目录(例如 monorepo 的某个 package 内部)启动 kimi-cli,也能正确识别仓库根目录下定义的 Skills;找不到 `.git` 标记时,回退到工作目录本身,避免误入无关的上层目录 * Skill:`merge_all_available_skills` 的默认值从 `false` 改为 `true`。kimi-cli 现在默认会合并用户级和项目级所有已存在的品牌 Skills 目录(`.kimi/skills`、`.claude/skills`、`.codex/skills`),而不是仅使用找到的第一个——让同时拥有多个品牌目录(例如同时保留 `~/.kimi/skills` 和 `~/.claude/skills`)的用户开箱即看到所有 Skills。**行为变更**:依赖旧默认(仅取第一个)的用户可通过在配置中显式设置 `merge_all_available_skills = false` 恢复旧行为。 ## 1.38.0 (2026-04-22) * Shell:修复 approval 弹窗超时后被误报为 `Rejected by user` 的问题——300 秒安全超时后,工具调用会以 `Rejected: approval timed out` 拒绝,让离开电脑一段时间后回来的用户能分辨出这是超时而非自己的手动拒绝。经常长时间离开的话可以加 `--yolo`/`-y` 自动批准工具调用 * Auth:修复 OAuth 用户因并发实例的 refresh token 轮换竞态被反复要求 `/login` 的问题——当另一个并发运行的 kimi-cli 实例(终端、VS Code 插件或 `kimi -p` 一次性命令)合法地轮换了 refresh token,当前实例手里过期的 refresh 请求会从服务端拿回 401,“别的实例是否刚轮换过”的磁盘检查与 `delete_tokens` 调用之间存在 TOCTOU 竞态,即使磁盘上马上会被写入一份有效的新 token,凭证文件也会被误删,迫使用户重新登录;现在依旧清理内存缓存(真正失效的 token 会在下一次请求时浮现),但保留文件,让并发实例刚写入的新 token 有机会被恢复,最终的 `/login` 仍会原子覆盖该文件 * Kosong:修复 Anthropic 供应商将并行工具结果拆分到多个 user message 的问题——现在会将仅包含工具结果的连续 user message 合并为单条消息,以符合 Anthropic Messages API 规范(assistant 一轮中的所有 `tool_use` 必须在同一条 user message 内回答);修复了严格兼容后端(如 DeepSeek `/anthropic` 接口)返回 400 错误的问题,并避免官方后端静默地引导模型放弃并行工具调用 ## 1.37.0 (2026-04-20) * Print:退出前等待后台任务完成——在单次 `--print` 模式下,进程现在会等待仍在运行的后台 Agent 完成并让模型处理它们的结果,而不是直接退出并杀死它们。等待时长上限为 `min(max(active_task.timeout_s or agent_task_timeout_s), print_wait_ceiling_s)`(默认上限 1 小时);超时后杀死任务并通过 `` 给模型最后一轮机会向用户总结后再退出 * Shell/Print:退出时 CLI 会在 stderr 列出每个即将被 kill 的后台任务(id + 描述),等待配置的 grace period 后再汇报未达到终态的任务(区分为"still terminating"即 worker 正在退出 vs "stop request failed"即真正泄漏的任务);`keep_alive_on_exit=true` 仍会完全跳过此路径 * Auth:OAuth 登录用户启动时自动刷新托管模型列表——Shell 启动时会以后台任务形式请求 provider 的 `/models` 接口拉取最新模型,新上线的模型无需重新登录即可使用;失败时静默降级、不会阻塞启动;使用 `--config` 指定自定义配置文件的会话保持原有行为 * Shell:托管模型现在统一展示 provider 返回的 `display_name`(如 `k2.6-code-preview`),覆盖欢迎界面、提示框状态栏、`/model` 选单和 `/model` 切换确认消息;若后端未返回 `display_name`,则回落到内部模型 ID ## 1.36.0 (2026-04-17) * Anthropic:修复 Claude Opus 4.7 返回 `invalid_request_error` 的问题——Opus 4.7 拒绝旧的 `{type: "enabled", budget_tokens: N}` 思考配置,现在会正确路由到 adaptive thinking,并显式设置 `display: "summarized"`,使思考内容仍能通过流返回(Opus 4.7 默默将该默认值改为 `"omitted"`);Bedrock / Vertex 命名变体(如 `aws/claude-opus-4-7`、`anthropic.claude-opus-4-7-v1:0`)以及 `claude-mythos-preview` 也会被正确识别;未来的 Claude ≥ 4.6 版本会通过版本号外推自动识别,无需改代码 * Web:修复 Web 界面中 Markdown 渲染的间距问题——恢复段落、列表、代码块、引用块和标题之间的合理垂直间距,不再将所有外边距压缩为零 * Shell:修复活跃 turn 期间加载指示器缺失的问题——月亮 spinner 现在作为兜底指示器,在模型仍在工作但没有其他指示器可见时自动显示,覆盖了工具调用完成后、turn 开始到首个 step 之间、以及 provider 发送空 thinking block 时的空白期 * Core:将 `max_steps_per_turn` 默认值从 100 提高到 500,开箱即可支持更长的无中断 agent 运行 * Web:修复代码块右上角复制、下载和预览按钮点击无响应的问题 ## 1.35.0 (2026-04-15) * Shell:将 `show_thinking_stream` 默认值改为 `true`,全新安装开箱即可看到流式思考预览;如需保留 1.32 的紧凑指示器,可在配置中将其设为 `false` * Web:修复流式 watchdog 在待处理审批请求或问题时误触发重连的问题——当用户正在处理审批请求或回答问题时,45 秒无消息 watchdog 不再强制重连,避免交互被打断 * Web:修复会话流错误后的恢复问题——当会话进程退出或 read loop 发生异常时,现在在广播错误前先清除过期的 in-flight prompt ID,使前端能够发送新消息而非收到 "Session is busy";活动状态指示器现在也会显示来自流的具体错误信息 * Core:修复 Wire 服务端 prompt 处理未捕获异常导致会话永远卡在忙碌状态的问题——SSL 错误、连接错误及其他意外失败现在会被 fallback 处理器捕获并返回 INTERNAL\_ERROR,避免异常逃逸导致会话无限挂起 ## 1.34.0 (2026-04-14) * Core:修复 `TaskStop` 取消卡住的后台 agent 时 CLI 崩溃的问题——终端不再打印 `Unhandled exception in event loop / Exception None` 并冻结;已取消的 task 现在会保留在管理器的 live-tasks 字典中,直到 runner 完成清理,避免 Python GC 在 task 仍处 pending 时回收它 * Shell:修复包含 tab 的行内 Diff 高亮偏移错位的问题——原始代码的 Diff 偏移量现在通过 expandtabs 列跟踪映射到渲染后的位置,确保 tab 展开后高亮区间落在正确位置 * Shell:新增 `show_thinking_stream` 配置项,可恢复旧版的流式思考预览体验——设为 `true` 后,Live 区域会显示经典的 `Thinking...` spinner 以及 6 行原始思考文本的滚动预览,思考块结束时把完整的思考 markdown 写入历史记录;默认为 `false`,保持 1.32 版本引入的紧凑指示器 ## 1.33.0 (2026-04-13) * Shell:将托管模型显示统一为 "Kimi for Code",移除欢迎界面和 `/login` 提示中硬编码的 `kimi-k2.5` 版本号 ## 1.32.0 (2026-04-13) * Core:将 MCP 工具输出截断至 10 万字符以防止上下文溢出——所有内容类型(文本和内联媒体如 image/audio/video data URL)共享同一字符预算;Playwright 等返回完整 DOM(500KB+)或大型 base64 截图的工具现在会被截断并附加提示信息;超出预算的媒体部分会被丢弃;不支持的 MCP 内容类型会被优雅处理而非导致当前轮次崩溃 * CLI:修复 PyInstaller 二进制包缺少延迟加载 CLI 子命令的问题——`kimi info`、`kimi export`、`kimi mcp`、`kimi plugin`、`kimi vis` 和 `kimi web` 现在在独立二进制分发中可正常使用 * Shell:将思考指示器精简为紧凑的单行布局——显示 `Thinking` 标签、动画点、耗时、token 数和实时的 tokens/秒脉冲;结束后在历史中留下 `Thought for Xs · N tokens` 痕迹 ## 1.31.0 (2026-04-10) * Core:限制 `list_directory` 输出为深度受限的树形结构,防止大目录导致 token 超限——将无上限的扁平列表替换为 2 级树(根级最多 30 条、每个子目录最多 10 条),按目录优先的字母序排列,截断处显示 `"... and N more"` 提示以引导模型进一步探索(修复 #1809) * Shell:新增交互式 Shell 启动时的阻断式更新提醒——当检测到有新版本可用(来自已有的后台检查缓存)时,在 Shell 加载之前显示阻断提示,提供 `[Enter]` 立即升级、`[q]` 暂时跳过下次继续提醒、`[s]` 跳过该版本后续提醒;支持 `KIMI_CLI_NO_AUTO_UPDATE` 环境变量;替代了之前可用更新的重复 toast 通知 * Auth:加固 OAuth 令牌刷新以防止不必要的重新登录——401 错误现在会自动触发令牌刷新并重试,而非强制 `/login`;多个同时运行的 CLI 实例通过跨进程文件锁协调刷新以避免竞争条件;令牌持久化使用原子写入配合 `fsync` 防止损坏;新增动态刷新阈值、令牌刷新过程中的 5xx 重试,以及正确的令牌吊销清理 * Core:修复模型响应仅包含思考内容时 agent loop 静默停止的问题——将仅含思考内容(无文本或工具调用)的响应检测为不完整响应错误并自动重试 * Core:修复长时间 streaming 过程中网络断连导致崩溃的问题——当 OpenAI SDK 在流式传输中途抛出基类 `APIError`(而非 `APIConnectionError`)时,现在能正确识别为可重试错误,自动触发重试和连接恢复,而不再直接崩溃退出 * Shell:从 `/sessions` 选择器中排除空的当前会话——完全为空的会话(既无对话记录也无自定义标题)不再显示在会话列表中;有自定义标题的会话仍然正常显示 * Shell:修复斜杠命令补全 Enter 键行为——接受补全后现在通过一次 Enter 即可提交命令;自动提交仅限于斜杠命令补全,文件引用(`@`)补全接受后不提交以便继续编辑;接受补全时抑制重新补全,防止过时的补全状态 * Shell:为 `/sessions` 会话选择器新增目录范围切换功能——按 `Ctrl+A` 可在"仅当前工作目录"和"所有已知目录"之间切换会话列表;采用全屏会话选择器 UI,顶部显示当前范围,底部显示快捷键提示 * Shell:新增 `/btw` 侧问命令——在 streaming 期间提出快速问题,不打断主对话;使用相同的系统提示词和工具定义以对齐 Prompt 缓存;响应在可滚动的模态面板中显示,支持流式输出 * Shell:重新设计底部动态区——将单体 `visualize.py`(1865 行)拆分为模块化包(`visualize/`),包含输入路由、交互式提示、审批/提问面板和 btw 模态面板等独立模块;通过 `classify_input()` 统一输入语义,实现一致的命令路由 * Shell:新增 streaming 期间的排队和 steer 双通道输入——Enter 将消息排队,在当前轮次结束后发送;Ctrl+S 将消息立即注入到正在运行的轮次上下文中;排队消息在提示区域显示计数指示器,可通过 ↑ 键召回编辑 * Shell:新增 `BtwBegin`/`BtwEnd` Wire 事件,支持跨客户端侧问 * Shell:改进 spinner 中的耗时格式——超过 60 秒的时长现在显示为 `"1m 23s"` 而非 `"83s"`;低于 1 秒的显示为 `"<1s"` * Shell:修复 btw 面板中的 Rich markup 注入问题——包含 `[`/`]` 字符的用户问题现在会被转义,防止 spinner 文本和面板标题出现渲染错误或样式注入 * Core:改进错误诊断——丰富内部日志覆盖,在 `kimi export` 导出的归档中包含相关日志文件和系统信息,并为常见错误(认证、网络、超时、配额)提供可操作的提示消息 * Shell:当工作目录在会话期间不可访问时优雅退出并显示崩溃报告——检测 CWD 丢失场景(外置硬盘拔出、目录被删除或文件系统卸载),打印包含会话 ID 和工作目录的恢复面板后干净退出 * Shell:使用 `git ls-files` 进行 `@` 文件引用发现——文件补全器现在优先使用 `git ls-files --recurse-submodules` 查询文件列表(5 秒超时),非 Git 仓库则回退到 `os.walk`;此修复解决了大型仓库(如包含 6.5 万+文件的 apache/superset)中 1000 文件限制导致字母顺序靠后的目录无法访问的问题(修复 #1375) * Core:新增共享的 `file_filter` 模块——通过 `src/kimi_cli/utils/file_filter.py` 统一 Shell 和 Web 的文件引用逻辑,提供一致的路径过滤、忽略目录排除和 Git 感知文件发现 * Shell:防止文件引用 scope 参数的路径遍历——文件补全器请求中的 `scope` 参数现在会经过验证,防止目录遍历攻击 * Web:恢复文件浏览器 API 中的未过滤目录列表——文件浏览器端点不再应用 Git 感知过滤,确保 Web UI 文件选择器中显示所有文件 * Todo:重构 `SetTodoList` 工具,支持状态持久化并防止工具调用风暴——待办事项现在会持久化到会话状态(主 Agent)和独立状态文件(子 Agent);新增查询模式(省略 `todos` 参数可读取当前状态)和清空模式(传 `[]` 清空);工具描述中增加了防风暴指导,防止在没有实际进展的情况下反复调用(修复 #1710) * ReadFile:每次读取返回文件总行数,并支持负数 `line_offset` 实现 tail 模式——工具现在会在消息中报告 `Total lines in file: N.`,方便模型规划后续读取;负数 `line_offset`(如 `-100`)通过滑动窗口读取文件末尾 N 行,适用于无需 Shell 命令即可查看最新日志输出的场景;绝对值上限为 1000(MAX\_LINES) * Shell:修复 Markdown 渲染中行内代码和代码块出现黑色背景的问题——`NEUTRAL_MARKDOWN_THEME` 现在将所有 Rich 默认的 `markdown.*` 样式覆盖为 `"none"`,防止 Rich 内置的 `"cyan on black"` 在非黑色背景终端上泄露 ## 1.30.0 (2026-04-02) * Shell:细化空闲时后台完成的自动触发行为——恢复的 Shell 会话在用户发送消息前,不会因为历史遗留的后台通知而自动启动新的前景轮次;当用户正在输入时,新的后台完成事件也会短暂延后触发,避免抢占提示符或打断 CJK 输入法组合态 * Core:修复前景轮次在中断后残留不平衡 Wire 事件的问题——轮次因取消或步骤中断退出时,现在也会补发 `TurnEnd`,避免恢复多次后会话 `wire.jsonl` 越来越脏 * Core:提升会话启动恢复的鲁棒性——`--continue`/`--resume` 现在可容忍损坏的 `context.jsonl` 记录,以及损坏的子 Agent、后台任务或通知持久化工件;CLI 会尽可能跳过无效状态并继续恢复会话,而不是直接启动失败 * CLI:改进 `kimi export` 会话导出体验——`kimi export` 现在默认预览并确认当前工作目录的上一个会话,显示会话 ID、标题和最后一条用户消息时间;新增 `--yes` 跳过确认;同时修复显式会话 ID 时 `--output` 放在参数后面会被错误解析为子命令的问题 * Grep:新增 `include_ignored` 参数,支持搜索被 `.gitignore` 排除的文件——设为 `true` 时启用 ripgrep 的 `--no-ignore` 标志,可搜索构建产物或 `node_modules` 等通常被忽略的文件;敏感文件(如 `.env`)仍由敏感文件保护层过滤;默认 `false`,不影响现有行为 * Core:为 Grep 和 Read 工具添加敏感文件保护——`.env`、SSH 私钥(`id_rsa`、`id_ed25519`、`id_ecdsa`)和云凭据(`.aws/credentials`、`.gcp/credentials`)会被检测并拦截;Grep 从结果中过滤并显示警告,Read 直接拒绝读取;`.env.example`/`.env.sample`/`.env.template` 不受影响 * Core:修复并行 foreground 子 Agent 审批请求导致会话挂死的问题——在交互式 Shell 模式下,`_set_active_approval_sink` 不再将待处理的审批请求 flush 到 live view sink(该 sink 无法渲染审批弹窗);请求保留在 pending 队列中由 prompt modal 路径处理;同时为 `wait_for_response` 增加 300 秒超时,确保未被 resolve 的审批请求最终抛出 `ApprovalCancelledError` 而非永久挂起 * CLI:新增 `--session`/`--resume`(`-S`/`-r`)参数用于恢复会话——不带参数时打开交互式会话选择器(仅 Shell UI);带会话 ID 时恢复指定会话;以统一的可选值参数设计替代了被回退的 `--pick-session`/`--list-sessions` * CLI:新增 CJK 安全的 `shorten()` 工具函数——替换所有 `textwrap.shorten` 调用,使不含空格的中日韩文本能优雅截断,而非被折叠成仅剩省略号 * Core:修复当通用目录(如 `~/.config/agents/skills/`)存在但为空时,品牌目录(如 `~/.kimi/skills/`)中的 Skills 静默消失的问题——Skill 目录发现现在独立搜索品牌组和通用组目录并合并结果,而非在所有候选目录中找到第一个就停止 * Core:新增 `merge_all_available_skills` 配置项——启用后,所有存在的品牌目录(`~/.kimi/skills/`、`~/.claude/skills/`、`~/.codex/skills/`)中的 Skills 都会被加载并合并,而非仅使用找到的第一个;同名 Skill 按 kimi > claude > codex 的优先级解析;默认关闭 * CLI:新增 `--plan` 启动参数和 `default_plan_mode` 配置项——通过 `kimi --plan` 或在 `~/.kimi/config.toml` 中设置 `default_plan_mode = true` 可让新会话直接进入计划模式;恢复的会话保留其原有的计划模式状态 * Shell:新增 `/undo` 和 `/fork` 命令用于会话分支——`/undo` 支持选择一个历史轮次并 fork 出新会话,被选中轮次的用户消息会预填到输入框供重新编辑;`/fork` 将当前完整对话历史复制到新会话;原会话始终保留不丢失 * CLI:新增 `-r` 作为 `--session` 的简写别名,并在会话退出时输出恢复提示(`kimi -r `)——覆盖正常退出、Ctrl-C、`/undo`、`/fork` 和 `/sessions` 切换等场景,确保用户始终能找到回到会话的方式 * Core:修复 `custom_headers` 未传递给非 Kimi provider 的问题——OpenAI、Anthropic、Google GenAI 和 Vertex AI provider 现在能正确转发 `providers.*.custom_headers` 中配置的自定义请求头 ## 1.29.0 (2026-04-01) * Core:支持层级化 `AGENTS.md` 加载——CLI 现在会从 git 项目根目录到工作目录逐层发现并合并 `AGENTS.md` 文件,包括每层目录中的 `.kimi/AGENTS.md`;在 32 KiB 预算上限下,更深层目录的文件优先保留,确保最具体的指令不会被截断 * Core:修复空会话在退出后残留在磁盘上的问题——创建但未使用的会话现在会在所有退出路径(失败退出、会话切换、异常错误)中被清理,而不仅限于成功退出 * Shell:新增 `KIMI_CLI_PASTE_CHAR_THRESHOLD` 和 `KIMI_CLI_PASTE_LINE_THRESHOLD` 环境变量,控制粘贴文本折叠为占位符的阈值——降低这些阈值可规避部分终端(如通过 SSH 连接的 XShell)在粘贴多行文本后 CJK 输入法失效的问题 * Shell:修复不支持 truecolor 的终端(如 Xshell)上 diff 面板渲染异常的问题——`render_to_ansi` 不再硬编码 24 位色;Rich 现在通过 `COLORTERM`/`TERM` 环境变量自动检测终端颜色能力 * Web:修复 CLI 升级后浏览器缓存旧 `index.html` 导致白屏的问题——服务端现在对 HTML 返回 `Cache-Control: no-cache`,对带 hash 的静态资源返回 `immutable`,防止因 chunk 文件名变更而产生 404 * Core:修复 Windows 上文件写入时 LF 被转换为 CRLF 的问题——`writetext` 现在以 `newline=""` 打开文件,防止 Python 的通用换行符转换将 `\n` 静默转为 `\r\n` * Core:支持 `socks://` 代理协议——V2RayN 等代理工具会设置 `ALL_PROXY=socks://...`,但 httpx/aiohttp 不识别该协议;CLI 现在会在启动时将 `socks://` 归一化为 `socks5://`,确保所有 HTTP 客户端和子进程在 SOCKS 代理环境下正常工作 * Shell:新增 `/title`(别名 `/rename`)命令,支持手动设置会话标题——标题现在统一存储在 `state.json` 中;旧版 `metadata.json` 会在首次加载时自动迁移 * Shell:修复设置 `MANPAGER`(如 `bat`)后分页器输出乱码的问题——控制台分页器现在忽略 `MANPAGER`,委托给 `pydoc.pager()` 处理,保留 `PAGER` 及所有平台特定的回退逻辑 * Explore:增强 explore Agent 的专家角色、搜索深度等级和自动环境上下文——explore Agent 启动时会自动获取仓库环境信息以提升调研质量;主 Agent 被引导优先使用 explore 进行代码库研究,Plan 模式鼓励先用 explore 调研再制定方案 * Shell:修复工具调用显示中出现原始 OSC 8 转义字节(如 `8;id=391551;https://…`)的问题——超链接序列现在被包装为零宽转义以兼容 prompt\_toolkit,在支持的终端中保留可点击链接 * Core:在系统提示词中添加操作系统和 Shell 信息——模型现在能感知当前运行平台,Windows 上会收到优先使用内置工具而非 Shell 命令的指引,避免在 PowerShell 中执行 Linux 命令导致报错 * Shell:修复 `command` 参数描述在所有平台上都写着 "bash command" 的问题——描述现在与平台无关 * Web:修复自动标题覆盖手动会话重命名的问题——用户通过 Web UI 重命名会话后,新标题现在会被保留,不再被自动生成的标题替换 ## 1.28.0 (2026-03-30) * Core:修复文件写入/替换工具冻结事件循环的问题——diff 计算(`build_diff_blocks`)现在通过 `asyncio.to_thread` 转移到线程中执行,防止编辑大文件时 UI 卡死 * Shell:修复 `_watch_root_wire_hub` 在处理异常时静默退出的问题——观察者现在会捕获并记录异常(与 `wire/server.py` 中的模式一致),并优雅处理 `QueueShutDown`,防止审批流程在会话中途静默中断 * Core:对超大文件(>10000 行)跳过 O(n²) diff 计算——超过阈值的文件现在显示摘要块而非计算完整 diff,未变化的文件会立即短路返回 * Wire:为 `DiffDisplayBlock` 新增 `is_summary` 字段(Wire 1.8)——标记包含行数摘要而非实际 diff 内容的块,便于客户端做差异化渲染 * Web:渲染大文件 diff 摘要——当 diff 块标记为 `is_summary` 时,Web UI 显示紧凑的"文件过大无法内联 diff"提示及行数,而非尝试计算 diff * Auth:修复 OAuth 用户执行 Skill 或空闲后出现 "incorrect API KEY" 的问题——401 错误现在会显示清晰的 "请 /login" 提示,而不是原始的 API 错误信息;ACP 层会正确触发 VS Code 扩展的重新登录流程 * Web:修复 OAuth 用户的会话标题生成始终失败的问题——标题生成器现在会使用 OAuth 令牌,并在调用模型前刷新过期令牌 * Core:为 Agent 工具和 HTTP 请求添加超时保护——所有 `aiohttp` 会话现在默认 120 秒总超时 / 60 秒读取超时;Agent 工具新增可选 `timeout` 参数(前台默认 10 分钟,后台默认 15 分钟);后台 Agent 任务超时后标记为 `timed_out` 并正确触发通知 * Grep:修复工具卡死且无法中断的问题——将阻塞的 `ripgrepy.run()` 替换为异步子进程执行;工具现在可响应 Ctrl-C 立即中断,并设有 20 秒超时保护,超时后返回部分结果 * Grep:新增 Token 效率优化——默认 `head_limit` 为 250 并支持 `offset` 分页、启用 `--hidden` 搜索同时排除 VCS 目录、`files_with_matches` 按修改时间排序、输出相对路径、非 content 模式限制最大列宽 500 * Grep:content 模式的 `line_number`(`-n`)现在默认为 `true`——默认包含行号,以便模型引用精确的代码位置 * Grep:`count_matches` 模式现在在 message 中包含汇总信息——例如 "Found 30 total occurrences across 10 files." * ACP:修复通过 `kimi-code` 或 `kimi-cli` 入口启动 ACP 时 `ValueError: list.index(x): x not in list` 崩溃的问题(如 JetBrains AI Assistant 场景) * Core:修复 OpenAI 兼容 API(如 One API)在多轮对话中返回 400 错误的问题——当服务端默认返回 `reasoning_content` 时,现在会在历史消息包含思考内容且配置了 `reasoning_key` 的情况下自动设置 `reasoning_effort` 为 `"medium"` * Shell:新增 `/theme` 命令和深色/浅色主题支持——使用浅色终端背景的用户可通过 `/theme light` 或在 `config.toml` 中设置 `theme = "light"` 切换到浅色配色方案;diff 高亮、任务浏览器、提示符 UI 和 MCP 状态颜色均会跟随所选主题自动适配 * Core:修复压缩前上下文溢出问题——工具结果的 Token 数现在会被估算并纳入自动压缩触发检查,防止大量工具输出在 API 调用间隙将上下文推超模型限制时出现"exceeded model token limit"错误 * Core:新增 hooks 系统(Beta)——在 `config.toml` 中配置 `[[hooks]]`,可在 13 个生命周期事件(包括 `PreToolUse`、`PostToolUse`、`SessionStart`、`Stop` 等)运行自定义 shell 命令;支持正则匹配、超时处理和通过退出码 2 阻塞操作 * Shell:新增 `/hooks` 命令——列出所有已配置的 hooks 及其事件计数 * Wire:新增 `HookTriggered` 和 `HookResolved` 事件类型(Wire 1.7)——在 hooks 开始和完成执行时通知客户端,包含事件类型、目标、操作(允许/阻塞)和耗时 * Wire:新增 `HookRequest` 和 `HookResponse` 消息类型——允许 Wire 客户端订阅 hook 事件并提供自己的处理逻辑,返回允许或阻塞的决策 * Shell:修复通知消息泄漏到会话回放和导出中的问题——后台任务通知标签(``、``)在恢复会话(`/sessions`)以及导出(`/export`)或导入(`/import`)对话历史时现在会被正确过滤 * CLI:`--skills-dir` 现在支持多个目录并覆盖默认发现——指定后,这些目录将替代用户/项目 Skills 发现(可重复的标志) * Web:工作区顶部的 "Open" 按钮现在会记住上次使用的应用——点击 "Open" 直接以上次选择的应用打开,点击下拉箭头可重新选择其他应用 * Web:修复 Archived 会话计数仅显示已加载页面大小的问题——当存在更多 Archived 会话时,计数标签现在显示 "100+" * Shell:修复粘贴文本占位符在模态回答中未展开的问题——粘贴到审批面板或问题面板中的剪贴板内容现在会在发送给模型前正确插值 * Vis:新增 `--network / -n` 启动参数——在所有网络接口上启动可视化工具并自动探测和显示 LAN IP 地址,与 `kimi web` 行为一致 * Vis:新增 `/vis` 斜杠命令——在交互式 Shell 中一步切换到 Tracing 可视化工具,与现有 `/web` 命令对称 * Vis:改进会话列表性能——后端异步扫描、请求并发限制、无限滚动分页,防止大量会话时浏览器卡顿 * Vis:补齐 7 个缺失的 Wire 事件类型——`SteerInput`、`MCPLoadingBegin/End`、`Notification`、`PlanDisplay`、`ToolCallRequest` 和 `QuestionRequest` 现在以正确的颜色和摘要显示 * Vis:StatusUpdate 显示 Token 和缓存详情——每个状态更新现在显示上下文 Token 数、最大 Token 数、输入 Token 分解及缓存命中率、MCP 连接状态 * Vis:工具调用显示结构化摘要——`ReadFile`、`Shell`、`Glob`、`Grep`、`Agent` 等工具调用直接在行内显示文件路径、命令或搜索模式,而非仅显示函数名 * Vis:Context Messages 新增 System Prompt 卡片——`_system_prompt` 条目以专用蓝色卡片渲染,显示估算的 Token 数并支持展开查看完整内容 * Vis:会话头部显示缓存命中率——统计栏现在在 Token 数旁显示整体缓存效率(如 `89% cache`) * Vis:高亮慢操作——时间间隔超过 10 秒以琥珀色显示,超过 60 秒以红色显示,使性能瓶颈一目了然 * Vis:ToolResult 摘要优先显示人类可读的 `message` 字段——结果现在显示如 "Command executed successfully" 等描述性文本,而非原始输出 * Vis:显示审批拒绝反馈——`ApprovalResponse` 摘要在工具调用被拒绝时包含用户的修正文本 ## 1.27.0 (2026-03-28) * Shell:新增 `/feedback` 命令——可直接在 CLI 会话中提交反馈,网络错误或超时时自动回退到打开 GitHub Issues 页面 * Shell:重新设计工具结果中的 diff 渲染——文件 diff 现在显示行号、背景色(绿色/红色)、语法高亮和行内字符级变更标记;审批预览仅显示变更行以提供紧凑视图;Ctrl-E 翻页器使用相同的统一风格 * Shell:更新语法高亮主题——将原本大量使用品红色的配色方案替换为更均衡的 ANSI 调色板,兼容各种终端;改善色彩多样性和在深色/亮色终端背景下的可读性 * Shell:修复多个 Subagent 运行时审批面板不可见的问题——审批面板和问题面板现在渲染在 Live 视图顶部,确保即使工具调用输出超出终端高度时仍然可见 * CLI:修复 `--print` 模式在出错时退出码为 0 的问题——Print 模式现在对永久性错误(认证失败、配置无效等)返回退出码 1,对可重试错误(429 速率限制、5xx 服务端错误、连接超时)返回退出码 75,使 CI/Eval 运行器能够检测失败并决定是否重试 * Plan:计划内容现在直接显示在聊天记录中,而非隐藏在翻页器后——计划以带边框的面板形式渲染在对话历史中,并展示计划文件路径供参考 * Plan:Plan 审批新增 "Reject and Exit" 选项——用户现在可以一步拒绝计划并退出 Plan 模式,除现有的 Approve、Revise 和 Reject 选项外 * Wire:新增 `PlanDisplay` 事件类型(Wire 1.7)——携带计划内容和文件路径,供客户端内联渲染 * Shell:流式输出 Markdown 内容——已完成的 Markdown 块(段落、列表、代码块、表格)现在会在流式传输过程中即时渲染并输出到终端,而非缓冲到整个轮次结束后才显示 * Shell:在 Thinking/Composing 加载动画上显示耗时和估算 Token 数——加载动画现在会显示 `Thinking... 5s · 312 tokens`,计数在生成过程中实时更新 * Shell:为 Thinking 内容添加滚动预览——模型思考过程的最后 6 行会以灰色斜体实时显示在加载动画下方 * Shell:将输入区域预留空间从 10 行缩减至 6 行 * Glob:`Glob` 工具现在可以访问 Skills 目录——除工作区外,该工具现在还可以搜索已发现的 Skill 根目录 * Glob:`Glob` 工具现在在验证目录路径前会展开 `~` 为用户主目录 ## 1.26.0 (2026-03-25) * Kosong:修复 Google GenAI 提供商在 `FunctionCall`/`FunctionResponse` 中包含 `id` 字段的问题——Gemini API 在包含 `id` 时返回 HTTP 400;从 wire 格式中移除该字段,同时保持内部 `tool_call_id` 跟踪不变 * Core:修复 MCP 服务器 stderr 污染问题——stderr 重定向现在在 MCP 服务器启动前安装,子进程日志(如 `mcp-remote` 的 OAuth 调试输出)将被捕获到日志文件,而非输出到终端 * Shell:修复子进程遇到交互式提示时挂起的问题——`Shell` 工具现在会立即关闭 stdin 并设置 `GIT_TERMINAL_PROMPT=0`,使需要凭证的命令(如通过 HTTPS 执行 `git push`)快速失败,而非阻塞至超时 * Core:修复 LLM 工具调用参数包含未转义控制字符时 JSON 解析失败的问题——在所有 LLM 输出解析路径使用 `json.loads(strict=False)`,防止工具执行失败和会话永久损坏 * Shell:空闲时自动响应后台任务完成——Shell 现在会检测后台 Bash 命令或 Agent 任务的完成,并自动发起新的 Agent 轮次处理结果,无需等待用户输入 * Core:修复 Print 模式下 `QuestionRequest` 导致挂起的问题——`AskUserQuestion`、`EnterPlanMode` 和 `ExitPlanMode` 在非交互(yolo)模式下自动处理,避免 `--print` 会话中工具调用无限挂起 * Core:修复后台 Agent 任务运行期间无法查看输出的问题——`/task` 浏览器和 `TaskOutput` 工具现在可实时显示后台 Agent 任务的输出,通过在执行期间同步写入任务日志替代完成后拷贝的方式实现 * Core:增强系统提示词以鼓励工具调用——Agent 现在默认优先使用工具执行操作,而非将代码作为纯文本输出 * Core:修复生成过程中遇到 `httpx.ProtocolError` 或 `504 Gateway Timeout` 时不重试的问题——流式协议断连和瞬时 `504` 响应现在会走既有重试路径,而不是在网络不稳定时直接中断当前轮次 * Kosong:修复 Anthropic 提供商在流式传输期间 `httpx.ReadTimeout` 异常泄漏的问题——异常现在正确转换为 `APITimeoutError`,使此前被绕过的重试逻辑能够正常触发 ## 1.25.0 (2026-03-23) * Core:新增插件系统(Skills + Tools)——插件通过 `plugin.json` 为 Kimi Code CLI 扩展自定义工具;工具是在独立子进程中运行的命令,其 stdout 返回给 Agent;插件支持通过 `inject` 配置自动注入凭证 * Core:支持多插件仓库——`kimi plugin install` 接受带 subpath 的 Git URL,从 monorepo 中安装特定插件(如 `https://github.com/org/repo.git/plugins/my-plugin`);当未提供 subpath 且根目录无 `plugin.json` 时,CLI 会列出直接子目录中可用的插件 * Core:统一插件凭证注入——插件可在 `plugin.json` 中声明 `inject` 字段,从主机的 LLM 提供商配置接收 `api_key` 和 `base_url`;支持 OAuth 托管 token 和静态 API key 两种凭证类型 * Core:新增 `Agent` 工具支持子 Agent 委派——Agent 现在可以创建持久的子 Agent 实例,内置三种类型(`coder`、`explore`、`plan`)处理聚焦的子任务;每个实例在会话内维护独立的上下文历史,支持前台或后台运行并自动汇总结果 * Core:统一审批运行时——前台工具调用和后台子 Agent 的审批请求现在通过统一的运行时协调,并由根 UI 通道呈现;拒绝响应可包含反馈文本以指导模型的下一次尝试 * Shell:新增交互式审批请求面板——内联面板展示工具调用详情(Diff、Shell 命令等),提供批准一次、批准本次会话、拒绝或附带反馈文字拒绝等选项 * Wire:协议版本升级至 1.6——`SubagentEvent` 新增 `agent_id`、`subagent_type`、`parent_tool_call_id` 字段;`ApprovalRequest` 包含来源元数据(`source_kind`、`source_id`);`ApprovalResponse` 支持 `feedback` 字段 * Vis:新增 Agents 面板——`kimi vis` 中新增 "Agents" 标签页,可查看子 Agent 实例及其事件,并按 Agent 范围筛选 Wire 时间线 * Core:`TaskOutput` 的 `block` 参数默认值从 `true` 改为 `false`——`TaskOutput` 现在默认返回非阻塞的状态/输出快照;仅在需要等待任务完成时设置 `block=true` * Shell:在提示工具栏中显示当前工作目录、Git 分支、脏状态以及与远端的 ahead/behind 同步状态 * Shell:在工具栏中显示活跃后台 Bash 任务数量,按时间轮换快捷键提示,并在窄终端中优雅截断内容以避免溢出 * Web:修复取消和审批时工具执行状态同步问题——停止生成时工具现在正确过渡到 `output-denied` 状态,审批通过后执行期间显示加载动画(而非勾选图标) * Web:会话重放时消除过期的审批和问答对话框——重放会话或后端报告 idle/stopped/error 状态时,所有待处理的审批/问答对话框现在会被正确消除,防止产生孤立的交互元素 * Web:支持行内数学公式渲染——除块级数学公式(`$$...$$`)外,新增支持单美元符号行内数学公式(`$...$`) * Web:优化 Switch 切换开关的比例和对齐——切换轨道现在更大(36×20),拇指按钮保持 16px 并具备更平滑的 16px 位移动画 * Web:在活动面板中显示子 Agent 类型标签——子 Agent 活动现在显示其类型(如 "Coder agent working")而非通用的 "Agent" 标签 * Web:审批对话框新增反馈模式——按 `4` 可附带反馈文字拒绝,指导模型的下一次尝试;来自子 Agent 的审批请求会显示来源标签和预览内容(Diff、命令等) * Web:视觉区分子 Agent 来源的工具调用——来自子 Agent 的 Tool 消息以左边框和来源类型标签渲染,便于区分归属 ## 1.24.0 (2026-03-18) * Shell:提高长文本粘贴自动折叠阈值至 1000 字符或 15 行(之前为 300 字符或 3 行),改善语音/无键盘输入等场景下的体验 * Core:Plan 模式现在支持多选方案——当 Agent 的计划包含多个不同路径时,`ExitPlanMode` 可展示 2–3 个带标签的选项供用户选择执行哪一个方案;用户选择的方案会作为选定路径返回给 Agent * Core:跨进程重启持久化 Plan 会话 ID 和文件路径——Plan 会话标识符和文件 slug 保存到 `SessionState`,重启 Kimi Code 后会继续使用 `~/.kimi/plans/` 下的同一计划文件,而非创建新文件 * Core:Plan 模式现在支持增量编辑计划文件——Agent 可以使用 `StrReplaceFile` 精准更新计划文件的特定部分,而无需通过 `WriteFile` 重写整个文件;同时非计划文件的编辑现在会被直接阻止,而非弹出审批请求 * Core:延迟 MCP 启动并展示加载进度——MCP 服务器现在在 Shell UI 启动后异步初始化,并提供实时进度指示器显示连接状态;Shell 在状态区域显示连接中和就绪状态,Web 显示服务器连接状态 * Core:优化轻量级启动路径——对 CLI 子命令和版本元数据实现延迟加载,显著缩短 `--version` 和 `--help` 等常用命令的启动时间 * Build:修复 Nix `FileCollisionError` for `bin/kimi`——从 `kimi-code` 包中移除重复的入口点,使 `kimi-cli` 独占 `bin/kimi` * Shell:Agent 运行期间保留用户未提交的输入——在模型运行时在提示符中键入的文本不再在轮次结束时丢失,用户可以按回车键将草稿作为下一条消息提交 * Shell:修复 Agent 运行结束后 Ctrl-C 和 Ctrl-D 无法正常工作的问题——键盘中断和 EOF 信号被静默吞没,而非显示提示信息或退出 Shell ## 1.23.0 (2026-03-17) * Shell:新增后台 Bash——`Shell` 工具现在支持 `run_in_background=true` 参数,可将耗时命令(构建、测试、服务)作为后台任务启动,Agent 无需等待即可继续工作;新增 `TaskList`、`TaskOutput`、`TaskStop` 工具管理任务生命周期,任务到达终止态时系统自动通知 Agent * Shell:新增 `/task` 斜杠命令与交互式任务浏览器——三列 TUI 界面,支持查看、监控和管理后台任务,提供实时刷新、输出预览和键盘驱动的任务停止操作 * Web:修复切换模型后其他标签页全局配置未刷新的问题——在某个标签页中切换模型时,其他标签页现在能检测到配置更新并自动刷新全局配置 ## 1.22.0 (2026-03-13) * Shell:长文本粘贴自动折叠为 `[Pasted text #n]` 占位符——通过 `Ctrl-V` 或括号粘贴输入的超过 300 字符或 3 行的文本在提示缓冲区中显示为紧凑的占位符标记,完整内容在发送给模型时展开;外部编辑器(`Ctrl-O`)打开时自动展开占位符,保存后重新折叠 * Shell:粘贴的图片缓存为附件占位符——从剪贴板粘贴的图片存储到磁盘,在提示中显示为 `[image:…]` 标记,保持输入缓冲区整洁 * Shell:修复粘贴文本中 UTF-16 surrogate 字符导致序列化错误的问题——来自 Windows 剪贴板的孤立 surrogate 字符现在在存储前即被清洗,防止历史记录写入和 JSON 序列化时出现 `UnicodeEncodeError` * Shell:重新设计斜杠命令补全菜单——使用全宽自定义菜单替代默认的补全弹窗,展示命令名称和多行描述,支持高亮和滚动 * Shell:修复取消的 Shell 命令未正确终止子进程的问题——当运行中的命令被取消时,子进程现在会被显式杀死,防止产生孤儿进程 ## 1.21.0 (2026-03-12) * Shell:新增内联运行提示与 steer 输入——模型运行时 Agent 输出直接渲染在提示区域内,用户无需等待轮次结束即可输入并发送后续消息(steer);审批请求和问答面板支持内联键盘交互 * Core:将 steer 注入方式从合成工具调用改为常规 User 消息——steer 内容现作为标准 User 消息追加到上下文,而非伪造的 `_steer` 工具调用/工具结果对,改善了上下文序列化和可视化的兼容性 * Wire:新增 `SteerInput` 事件——当用户在运行中的轮次发送后续 steer 消息时触发的新 Wire 协议事件 * Shell:Agent 模式下提交后回显用户输入——提示符和输入文本会打印回终端,使对话记录更清晰 * Shell:改进会话回放对 steer 输入的支持——回放现在能正确重建并展示 steer 消息与常规轮次,并过滤内部 system-reminder 消息 * Shell:修复 toast 通知中升级命令不一致的问题——升级命令文本统一从 `UPGRADE_COMMAND` 常量获取 * Core:在 `context.jsonl` 中持久化系统提示词——系统提示词作为上下文文件的第一条记录写入,并在会话生命周期内冻结,使可视化工具能读取完整对话上下文,会话恢复时复用原始提示词而非重新生成 * Vis:为 `kimi vis` 新增会话目录快捷操作——可在会话页面直接打开当前会话文件夹,使用 `Copy DIR` 复制原始会话目录路径,并支持在 macOS 和 Windows 上打开目录 * Shell:优化 API 密钥登录体验——验证密钥时显示加载动画,当 401 错误可能因选错平台导致时显示提示信息,登录成功后展示配置摘要,并将 Thinking 模式默认设为开启 ## 1.20.0 (2026-03-11) * Web:新增 Web UI 中的 Plan 模式切换——在输入工具栏中添加开关控件,Plan 模式激活时输入框显示蓝色虚线边框,并支持通过 `set_plan_mode` Wire 协议方法设置 Plan 模式 * Core:Plan 模式状态跨会话持久化——将 `plan_mode` 保存到 `SessionState`,会话恢复时自动还原 * Core:修复工具触发的 Plan 模式变更未正确反映在 StatusUpdate 中的问题——在 `EnterPlanMode`/`ExitPlanMode` 工具执行后发送更新的 `StatusUpdate`,确保客户端看到最新状态 * Core:修复部分 Linux 系统(如内核版本 6.8.0-101)上 HTTP 请求头包含尾部空白/换行符导致连接错误的问题——发送前对 ASCII 请求头值执行空白裁剪 * Core:修复 OpenAI Responses provider 隐式发送 `reasoning.effort=null` 导致需要推理的 Responses 兼容端点报错的问题——现在仅在显式设置时才发送推理参数 * Vis:新增会话下载、导入、导出与删除功能——在会话浏览器和详情页支持一键 ZIP 下载,支持将 ZIP 文件导入到独立的 `~/.kimi/imported_sessions/` 目录并通过"Imported"筛选器切换查看,新增 `kimi export ` CLI 命令,支持删除导入的会话并提供 AlertDialog 二次确认 * Core:修复对话包含媒体内容(图片、音频、视频)时上下文压缩失败的问题——将过滤策略从黑名单(排除 `ThinkPart`)改为白名单(仅保留 `TextPart`),防止不支持的内容类型被发送到压缩 API * Web:修复 `@` 文件提及索引在切换会话或工作区文件变更后不刷新的问题——切换会话时重置索引,30 秒过期自动刷新,输入路径前缀可查找超出 500 文件上限的文件 ## 1.19.0 (2026-03-10) * Core:新增 Plan 模式——AI 在编码前先制定实施方案并提交审批。Plan 模式下仅允许使用只读工具(`Glob`、`Grep`、`ReadFile`)探索代码库,将方案写入 plan 文件后通过 `ExitPlanMode` 提交审批,用户可批准、拒绝或提供修改意见;支持 `Shift-Tab` 快捷键和 `/plan` 斜杠命令切换 * Vis:新增 `kimi vis` 命令,启动交互式可视化仪表板以检查会话追踪——包括 Wire 事件时间线、上下文查看器、会话浏览器和用量统计 * Web:修复会话流状态管理问题——修复状态重置时的空引用错误,并在切换会话时保留斜杠命令,避免初始化响应返回前出现短暂的空白 ## 1.18.0 (2026-03-09) * ACP:支持 ACP 模式下的嵌入式资源内容,使 Zed 的 `@` 文件引用能够正确包含文件内容 * Core:在 Google GenAI provider 中使用 `parameters_json_schema` 替代 `parameters`,绕过 Pydantic 校验对 MCP 工具中标准 JSON Schema 元数据字段的拒绝 * Shell:增强 `Ctrl-V` 剪贴板粘贴功能,支持粘贴视频文件——视频文件路径以文本形式插入输入框,同时修复剪贴板数据为 `None` 时的崩溃问题 * Core:将会话 ID 作为 `user_id` 元数据传递给 Anthropic API * Web:修复 WebSocket 重连时斜杠命令丢失的问题,并为会话初始化添加自动重试逻辑 ## 1.17.0 (2026-03-03) * Core:新增 `/export` 命令,支持将当前会话上下文(消息、元数据)导出为 Markdown 文件;新增 `/import` 命令,支持从文件或其他会话 ID 导入上下文到当前会话 * Shell:在状态栏上下文用量旁显示 Token 数量(已用/总量),如 `context: 42.0% (4.2k/10.0k)` * Shell:工具栏快捷键提示改为轮转显示——每次提交后循环展示不同快捷键提示,节省横向空间 * MCP:为 MCP 服务器连接添加加载指示器——Shell 在连接 MCP 服务器时显示 "Connecting to MCP servers..." 加载动画,Web 在 MCP 工具加载期间显示状态消息 * Web:修复工具栏变更面板中文件列表滚动溢出的问题 * Core:新增 `compaction_trigger_ratio` 配置项(默认 `0.85`),用于控制自动压缩的触发时机——当上下文用量达到配置比例或剩余空间低于 `reserved_context_size` 时触发压缩,以先满足的条件为准 * Core:`/compact` 命令支持自定义指令(如 `/compact keep database discussions`),可指导压缩时重点保留的内容 * Web:新增 URL 操作参数(`?action=create` 打开创建会话对话框,`?action=create-in-dir&workDir=xxx` 直接创建会话)用于外部集成,支持 Cmd/Ctrl+点击新建会话按钮在新标签页中打开会话创建 * Web:在提示输入工具栏中添加待办列表显示——当 `SetTodoList` 工具激活时,显示任务进度并支持展开面板查看详情 * ACP:为会话操作添加认证检查,未认证时返回 `AUTH_REQUIRED` 错误响应,支持终端登录流程 ## 1.16.0 (2026-02-27) * Web:更新 ASCII Logo 横幅为新的样式设计 * Core:新增 `--add-dir` CLI 选项和 `/add-dir` 斜杠命令,支持将额外目录添加到工作区范围——添加的目录可被所有文件工具(读取、写入、glob、替换)访问,跨会话持久化保存,并在系统提示词中展示 * Shell:新增 `Ctrl-O` 快捷键,在外部编辑器中编辑当前输入内容(`$VISUAL`/`$EDITOR`),支持自动检测 VS Code、Vim、Vi 或 Nano * Shell:新增 `/editor` 斜杠命令,可交互式配置和切换默认外部编辑器,设置持久保存到配置文件 * Shell:新增 `/new` 斜杠命令,无需重启 Kimi Code CLI 即可创建并切换到新会话 * Wire:当客户端不支持 `supports_question` 能力时,自动隐藏 `AskUserQuestion` 工具,避免 LLM 调用不受支持的交互 * Core:在压缩后估算上下文 Token 数量,使上下文用量百分比不再显示为 0% * Web:上下文用量百分比显示精确到一位小数,提升精度 ## 1.15.0 (2026-02-27) * Shell:精简输入提示符,移除用户名前缀以获得更简洁的外观 * Shell:在工具栏中添加水平分隔线和更完整的键盘快捷键提示 * Shell:为问题面板和审批面板添加数字键(1–5)快速选择选项,并以带边框的面板和键盘提示重新设计交互界面 * Shell:为多问题面板添加标签式导航——使用左右方向键或 Tab 键在问题间切换,并以可视化指示器区分已答、当前和待答状态,重新访问已答问题时自动恢复选择状态 * Shell:在问题面板中支持使用空格键提交单选问题 * Web:为多问题对话框添加标签式导航,支持可点击标签栏、键盘导航,以及重新访问已答问题时恢复选择状态 * Core:将进程标题设置为 "Kimi Code"(在 `ps` / 活动监视器 / 终端标签页标题中可见),并将 Web Worker 子进程标记为 "kimi-code-worker" ## 1.14.0 (2026-02-26) * Shell:在终端中将 `FetchURL` 工具的 URL 参数显示为可点击的超链接 * Tool:新增 `AskUserQuestion` 工具,支持在执行过程中向用户展示结构化问题和预定义选项,支持单选、多选和自定义文本输入 * Wire:新增 `QuestionRequest` / `QuestionResponse` 消息类型和能力协商机制,用于结构化问答交互 * Shell:新增 `AskUserQuestion` 交互式问题面板,支持键盘驱动的选项选择 * Web:新增 `QuestionDialog` 组件,支持在界面内展示并回答结构化问题,问题待回答时替代提示输入框 * Core:支持会话状态跨会话持久化——审批决策(YOLO 模式、自动批准的操作)和动态子 Agent 现在会被保存,并在恢复会话时自动还原 * Core:对元数据和会话状态文件使用原子化 JSON 写入,防止崩溃时数据损坏 * Wire:新增 `steer` 请求,可在 Agent 轮次进行中注入用户消息(协议版本 1.4) * Web:支持在 `FetchURL` 工具的 URL 参数上使用 Cmd/Ctrl+点击在新标签页中打开链接,并显示适合当前平台的提示信息 ## 1.13.0 (2026-02-24) * Core:添加自动连接恢复机制,在连接错误和超时错误时重建 HTTP 客户端并重试,提升对瞬时网络故障的容错能力 ## 1.12.0 (2026-02-11) * Web:添加子 Agent 活动渲染,在 Task 工具消息中展示子 Agent 步骤(思考、工具调用、文本) * Web:添加 Think 工具渲染,以轻量级推理风格块展示 * Web:将 emoji 状态指示器替换为 Lucide 图标,并为工具名称添加分类图标 * Web:改进 Reasoning 组件,优化思考标签和状态图标 * Web:改进 Todo 组件,添加状态图标并优化样式 * Web:实现 WebSocket 断线重连,支持自动重发请求和连接超时监控 * Web:改进创建会话对话框的命令值处理 * Web:支持会话工作目录路径中的波浪号(`~`)展开 * Web:修复 Assistant 消息内容溢出被裁剪的问题 * Wire:修复多个子 Agent 并发运行时的死锁问题,不再在审批请求和工具调用请求上阻塞 UI 循环 * Wire:Agent 轮次结束后清理残留的待处理请求 * Web:在提示输入框中显示引导占位文本,提示可使用斜杠命令和 @ 引用文件 * Web:修复在 uvicorn Web 服务器中 Ctrl+C 无法使用的问题,在 Shell 模式退出后恢复默认的 SIGINT 信号处理程序和终端状态 * Web:改进会话停止处理,使用正确的异步清理和超时机制 * ACP:添加协议版本协商框架,用于客户端与服务端之间的兼容性校验 * ACP:添加会话恢复方法,用于恢复会话状态(实验性) ## 1.11.0 (2026-02-10) * Web:将上下文用量指示器从工作区标题栏移至提示工具栏,悬停时显示详细的 Token 用量明细 * Web:在文件变更面板底部添加文件夹指示器,显示工作目录路径 * Web:修复切换到 Web 模式时未恢复 stderr 的问题,该问题可能导致 Web 服务器的错误输出被抑制 * Web:修复端口可用性检查,在测试套接字上设置 SO\_REUSEADDR ## 1.10.0 (2026-02-09) * Web:为 Assistant 消息添加复制和分支(fork)操作按钮,支持快速复制内容和创建分支会话 * Web:为审批操作添加键盘快捷键——按 `1` 批准、`2` 本次会话批准、`3` 拒绝 * Web:添加消息队列功能——在 AI 处理过程中可排队发送后续消息,待当前回复完成后自动发送 * Web:将 Git diff 状态栏替换为统一的提示工具栏,以可折叠标签页展示活动状态、消息队列和文件变更 * Web:在 Web Worker 中加载全局 MCP 配置,使 Web 会话可以使用 MCP 工具 * Web:改进移动端提示输入框体验——缩小 textarea 最小高度、添加 `autoComplete="off"`、在小屏幕上禁用聚焦边框 * Web:处理部分模型先输出文本再输出思考过程的情况,确保思考消息始终显示在文本消息之前 * Web:在会话连接过程中显示更具体的状态信息("Loading history..."、"Starting environment..." 替代通用的 "Connecting...") * Web:会话环境初始化失败时发送错误状态,而非让 UI 一直处于等待状态 * Web:历史回放完成后 15 秒内未收到会话状态时自动重连 * Web:会话流中使用非阻塞文件 I/O,避免历史回放期间阻塞事件循环 ## 1.9.0 (2026-02-06) * Config:添加 `default_yolo` 配置项,支持默认开启 YOLO(自动审批)模式 * Config:支持 `max_steps_per_turn` 和 `max_steps_per_run` 作为循环控制设置的别名 * Wire:新增 `replay` 请求,用于回放已记录的 Wire 事件(协议版本 1.3) * Web:添加会话分支(fork)功能,可以从任意 Assistant 回复处创建新的分支会话 * Web:添加会话归档功能,自动归档超过 15 天的会话 * Web:添加多选模式,支持批量归档、取消归档和删除操作 * Web:添加工具结果的媒体预览(ReadMediaFile 的图片/视频),支持可点击缩略图 * Web:添加 Shell 命令和 Todo 列表的工具输出显示组件 * Web:添加活动状态指示器,显示 Agent 状态(处理中、等待审批等) * Web:添加图片加载失败时的错误回退 UI * Web:重新设计工具输入 UI,支持可展开参数和长值的语法高亮 * Web:上下文压缩时显示压缩指示器 * Web:改进聊天中的自动滚动行为,更流畅地跟随新内容 * Web:会话流开始时更新工作目录的最近会话 ID(`last_session_id`) * Shell:移除 `Ctrl-/` 快捷键(此前用于触发 `/help` 命令) * Rust:Rust 版实现迁移到 `MoonshotAI/kimi-agent-rs` 并独立发版;二进制更名为 `kimi-agent` * Core:重新加载配置时保留会话 ID,确保会话正确恢复 * Shell:修复会话回放时显示已被 `/clear` 或 `/reset` 清除的消息的问题 * Web:修复会话中断或取消时审批请求状态未更新的问题 * Web:修复选择斜杠命令时的输入法组合问题 * Web:修复执行 `/clear`、`/reset` 或 `/compact` 命令后 UI 未清空消息的问题 ## 1.8.0 (2026-02-05) * CLI:修复启动错误(如无效的配置文件)被静默吞掉而不显示的问题 ## 1.7.0 (2026-02-05) * Rust:添加 `kagent`,Kimi Agent 内核的 Rust 实现,支持 Wire 模式(实验性) * Auth:修复多个会话同时运行时的 OAuth 令牌刷新冲突 * Web:添加文件提及菜单(`@`),支持引用已上传附件和工作区文件,带自动补全功能 * Web:添加斜杠命令菜单,支持自动补全、键盘导航和别名匹配 * Web:修复认证令牌持久化问题,从 sessionStorage 切换到 localStorage 并设置 24 小时过期 * Web:创建会话时,若指定的路径不存在则提示创建目录 * Web:为会话列表添加服务端分页和虚拟滚动,提升性能 * Web:改进会话和工作目录加载,采用更智能的缓存和失效策略 * Web:修复历史记录回放时的 WebSocket 错误,发送前检查连接状态 * Web:Git diff 状态栏现在显示未跟踪文件(尚未添加到 git 的新文件) * Web:仅在 public 模式下限制敏感 API;更新 origin 执行逻辑 ## 1.6 (2026-02-03) * Web:为网络模式添加基于 Token 的认证和访问控制(`--network`、`--lan-only`、`--public`) * Web:添加安全选项:`--auth-token`、`--allowed-origins`、`--restrict-sensitive-apis`、`--dangerously-omit-auth` * Web:变更 `--host` 选项,用于绑定到指定 IP 地址;添加自动网络地址检测 * Web:修复创建新会话时 WebSocket 断开连接的问题 * Web:将最大图片尺寸从 1024 提升至 4096 像素 * Web:通过增强的悬停效果和更好的布局处理改进 UI 响应性 * Wire:添加 `TurnEnd` 事件,用于标识 Agent 轮次的完成(协议版本 1.2) * Core:修复包含 `$` 的自定义 Agent 提示词文件导致静默启动失败的问题 ## 1.5 (2026-01-30) * Web:添加 Git diff 状态栏,显示会话工作目录中的未提交更改 * Web:添加 "Open in" 菜单,用于在终端、VS Code、Cursor 或其他本地应用中打开文件/目录 * Web:添加会话搜索功能,支持按标题或工作目录过滤会话 * Web:改进会话标题显示,优化溢出处理 ## 1.4 (2026-01-30) * Shell:合并 `/login` 和 `/setup` 命令,`/setup` 现为 `/login` 的别名 * Shell:`/usage` 命令现在显示剩余配额百分比;添加 `/status` 别名 * Config:添加 `KIMI_SHARE_DIR` 环境变量,用于自定义共享目录路径(默认 `~/.kimi`) * Web:新增 Web UI,支持基于浏览器的交互 * CLI:添加 `kimi web` 子命令以启动 Web UI 服务器 * Auth:修复设备名称或操作系统版本包含非 ASCII 字符时的编码错误 * Auth:OAuth 凭据现在存储在文件中而非 keyring;启动时自动迁移现有令牌 * Auth:修复系统休眠或睡眠后的授权失败问题 ## 1.3 (2026-01-28) * Auth:修复 Agent 轮次期间的认证问题 * Tool:为 `ReadMediaFile` 中的媒体内容添加描述性标签,提高路径可追溯性 ## 1.2 (2026-01-27) * UI:显示 `kimi-for-coding` 模型的说明 ## 1.1 (2026-01-27) * LLM:修复 `kimi-for-coding` 模型的能力 ## 1.0 (2026-01-27) * Shell:添加 `/login` 和 `/logout` 斜杠命令,用于登录和登出 * CLI:添加 `kimi login` 和 `kimi logout` 子命令 * Core:修复子 Agent 审批请求处理问题 ## 0.88 (2026-01-26) * MCP:移除连接 MCP 服务器时的 `Mcp-Session-Id` header 以修复兼容性问题 ## 0.87 (2026-01-25) * Shell:修复 HTML 块出现在元素外时的 Markdown 渲染错误 * Skills:添加更多用户级和项目级 Skills 目录候选 * Core:改进系统提示词中的媒体文件生成和处理任务指引 * Shell:修复 macOS 上从剪贴板粘贴图片的问题 ## 0.86 (2026-01-24) * Build:修复二进制构建问题 ## 0.85 (2026-01-24) * Shell:粘贴的图片缓存到磁盘,支持跨会话持久化 * Shell:基于内容哈希去重缓存的附件 * Shell:修复消息历史中图片/音频/视频附件的显示 * Tool:使用文件路径作为 `ReadMediaFile` 中的媒体标识符,提高可追溯性 * Tool:修复部分 MP4 文件无法识别为视频的问题 * Shell:执行斜杠命令时支持 Ctrl-C 中断 * Shell:修复 Shell 模式下输入不符合 Shell 语法的内容时的解析错误 * Shell:修复 MCP 服务器和第三方库的 stderr 输出污染 Shell UI 的问题 * Wire:优雅关闭,当连接关闭或收到 Ctrl-C 时正确清理待处理请求 ## 0.84 (2026-01-22) * Build:添加跨平台独立二进制构建,支持 Windows、macOS(含代码签名和公证)和 Linux(x86\_64 和 ARM64) * Shell:修复斜杠命令自动补全在输入完整命令/别名时仍显示建议的问题 * Tool:将 SVG 文件作为文本而非图片处理 * Flow:支持 D2 markdown 块字符串(`|md` 语法),用于 Flow Skill 中的多行节点标签 * Core:修复运行 `/reload`、`/setup` 或 `/clear` 后可能出现的 "event loop is closed" 错误 * Core:修复在续接会话中使用 `/clear` 时的崩溃问题 ## 0.83 (2026-01-21) * Tool:添加 `ReadMediaFile` 工具用于读取图片/视频文件;`ReadFile` 现在仅用于读取文本文件 * Skills:Flow Skills 现在也注册为 `/skill:` 命令(除了 `/flow:`) ## 0.82 (2026-01-21) * Tool:`WriteFile` 和 `StrReplaceFile` 工具支持使用绝对路径编辑/写入工作目录外的文件 * Tool:使用 Kimi 供应商时,视频文件上传到 Kimi Files API,使用 `ms://` 引用替代 inline data URL * Config:添加 `reserved_context_size` 配置项,自定义自动压缩触发阈值(默认 50000 tokens) ## 0.81 (2026-01-21) * Skills:添加 Flow Skill 类型,在 SKILL.md 中内嵌 Agent Flow(Mermaid/D2),通过 `/flow:` 命令调用 * CLI:移除 `--prompt-flow` 选项,改用 Flow Skills * Core:用 `/flow:` 命令替代原来的 `/begin` 命令 ## 0.80 (2026-01-20) * Wire:添加 `initialize` 方法,用于交换客户端/服务端信息、注册外部工具和公布斜杠命令 * Wire:支持通过 Wire 协议调用外部工具 * Wire:将 `ApprovalRequestResolved` 重命名为 `ApprovalResponse`(向后兼容) ## 0.79 (2026-01-19) * Skills:添加项目级 Skills 支持,从 `.agents/skills/`(或 `.kimi/skills/`、`.claude/skills/`)发现 * Skills:统一 Skills 发现机制,采用分层加载(内置 → 用户 → 项目);用户级 Skills 现在优先使用 `~/.config/agents/skills/` * Shell:斜杠命令自动补全支持模糊匹配 * Shell:增强审批请求预览,显示 Shell 命令和 Diff 内容,使用 `Ctrl-E` 展开完整内容 * Wire:添加 `ShellDisplayBlock` 类型,用于在审批请求中显示 Shell 命令 * Shell:调整 `/help` 显示顺序,将键盘快捷键移至斜杠命令之前 * Wire:对无效请求返回符合 JSON-RPC 2.0 规范的错误响应 ## 0.78 (2026-01-16) * CLI:为 Prompt Flow 添加 D2 流程图格式支持(`.d2` 扩展名) ## 0.77 (2026-01-15) * Shell:修复 `/help` 和 `/changelog` 全屏分页显示中的换行问题 * Shell:使用 `/model` 命令切换 Thinking 模式,取代 Tab 键 * Config:添加 `default_thinking` 配置项(升级后需运行 `/model` 选择 Thinking 模式) * LLM:为始终使用 Thinking 模式的模型添加 `always_thinking` 能力 * CLI:将 `--command`/`-c` 重命名为 `--prompt`/`-p`,保留 `--command`/`-c` 作为别名,移除 `--query`/`-q` * Wire:修复 Wire 模式下审批请求无法正常响应的问题 * CLI:添加 `--prompt-flow` 选项,加载 Mermaid 流程图文件作为 Prompt Flow * Core:加载 Prompt Flow 后添加 `/begin` 斜杠命令以启动流程 * Core:使用基于 Prompt Flow 的实现替换旧的 Ralph 循环 ## 0.76 (2026-01-12) * Tool:让 `ReadFile` 工具描述根据模型能力动态反映图片/视频支持情况 * Tool:修复 TypeScript 文件(`.ts`、`.tsx`、`.mts`、`.cts`)被误识别为视频文件的问题 * Shell:允许在 Shell 模式下使用部分斜杠命令(`/help`、`/exit`、`/version`、`/changelog`、`/feedback`) * Shell:改进 `/help` 显示,使用全屏分页器,展示斜杠命令、Skills 和键盘快捷键 * Shell:改进 `/changelog` 和 `/mcp` 显示,采用一致的项目符号格式 * Shell:在底部状态栏显示当前模型名称 * Shell:添加 `Ctrl-/` 快捷键显示帮助 ## 0.75 (2026-01-09) * Tool:改进 `ReadFile` 工具描述 * Skills:添加内置 `kimi-cli-help` Skill,解答 Kimi Code CLI 使用和配置问题 ## 0.74 (2026-01-09) * ACP:允许 ACP 客户端选择和切换模型(包含 Thinking 变体) * ACP:添加 `terminal-auth` 认证方式,用于配置流程 * CLI:弃用 `--acp` 选项,请使用 `kimi acp` 子命令 * Tool:`ReadFile` 工具现支持读取图片和视频文件 ## 0.73 (2026-01-09) * Skills:添加随软件包发布的内置 skill-creator Skill * Tool:在 `ReadFile` 路径中将 `~` 展开为用户主目录 * MCP:确保 MCP 工具加载完成后再开始 Agent 循环 * Wire:修复 Wire 模式无法接受有效 `cancel` 请求的问题 * Setup:`/model` 命令现在可以切换所选供应商的所有可用模型 * Lib:从 `kimi_cli.wire.types` 重新导出所有 Wire 消息类型,作为 `kimi_cli.wire.message` 的替代 * Loop:添加 `max_ralph_iterations` 循环控制配置,限制额外的 Ralph 迭代次数 * Config:将循环控制配置中的 `max_steps_per_run` 重命名为 `max_steps_per_turn`(向后兼容) * CLI:添加 `--max-steps-per-turn`、`--max-retries-per-step` 和 `--max-ralph-iterations` 选项,覆盖循环控制配置 * SlashCmd:`/yolo` 命令现在切换 YOLO 模式 * UI:在 Shell 模式的提示符中显示 YOLO 标识 ## 0.72 (2026-01-04) * Python:修复在 Python 3.14 上的安装问题 ## 0.71 (2026-01-04) * ACP:通过 ACP 客户端路由文件读写和 Shell 命令,实现同步编辑/输出 * Shell:添加 `/model` 斜杠命令,在使用默认配置时切换默认模型并重新加载 * Skills:添加 `/skill:` 斜杠命令,按需加载 `SKILL.md` 指引 * CLI:添加 `kimi info` 子命令,显示版本和协议信息(支持 `--json`) * CLI:添加 `kimi term` 命令,启动 Toad 终端 UI * Python:将默认工具/CI 版本升级到 3.14 ## 0.70 (2025-12-31) * CLI:添加 `--final-message-only`(及 `--quiet` 别名),在 Print 模式下仅输出最终的 assistant 消息 * LLM:添加 `video_in` 模型能力,支持视频输入 ## 0.69 (2025-12-29) * Core:支持在 `~/.kimi/skills` 或 `~/.claude/skills` 中发现 Skills * Python:降低最低 Python 版本要求至 3.12 * Nix:添加 flake 打包支持;可通过 `nix profile install .#kimi-cli` 安装或 `nix run .#kimi-cli` 运行 * CLI:添加 `kimi-cli` 脚本别名;可通过 `uvx kimi-cli` 运行 * Lib:将 LLM 配置验证移入 `create_llm`,配置缺失时返回 `None` ## 0.68 (2025-12-24) * CLI:添加 `--config` 和 `--config-file` 选项,支持传入 JSON/TOML 配置 * Core:`KimiCLI.create` 的 `config` 参数现在除了 `Path` 也支持 `Config` 类型 * Tool:在 `WriteFile` 和 `StrReplaceFile` 的审批/结果中包含 diff 显示块 * Wire:在审批请求中添加显示块(包括 diff),保持向后兼容 * ACP:在工具结果和审批提示中显示文件 diff 预览 * ACP:连接 ACP 客户端管理的 MCP 服务器 * ACP:如果支持,在 ACP 客户端终端中运行 Shell 命令 * Lib:添加 `KimiToolset.find` 方法,按类或名称查找工具 * Lib:添加 `ToolResultBuilder.display` 方法,向工具结果追加显示块 * MCP:添加 `kimi mcp auth` 及相关子命令,管理 MCP 授权 ## 0.67 (2025-12-22) * ACP:在单会话 ACP 模式(`kimi --acp`)中广播斜杠命令 * MCP:添加 `mcp.client` 配置节,用于配置 MCP 工具调用超时等选项 * Core:改进默认系统提示词和 `ReadFile` 工具 * UI:修复某些罕见情况下 Ctrl-C 不工作的问题 ## 0.66 (2025-12-19) * Lib:在 `StatusUpdate` Wire 消息中提供 `token_usage` 和 `message_id` * Lib:添加 `KimiToolset.load_tools` 方法,支持依赖注入加载工具 * Lib:添加 `KimiToolset.load_mcp_tools` 方法,加载 MCP 工具 * Lib:将 `MCPTool` 从 `kimi_cli.tools.mcp` 移至 `kimi_cli.soul.toolset` * Lib:添加 `InvalidToolError`、`MCPConfigError` 和 `MCPRuntimeError` 异常类 * Lib:使 Kimi Code CLI 详细异常类扩展 `ValueError` 或 `RuntimeError` * Lib:`KimiCLI.create` 和 `load_agent` 的 `mcp_configs` 参数支持传入验证后的 `list[fastmcp.mcp_config.MCPConfig]` * Lib:修复 `KimiCLI.create`、`load_agent`、`KimiToolset.load_tools` 和 `KimiToolset.load_mcp_tools` 的异常抛出 * LLM:添加 `vertexai` 供应商类型,支持 Vertex AI * LLM:将 Gemini Developer API 的供应商类型从 `google_genai` 重命名为 `gemini` * Config:配置文件从 JSON 迁移至 TOML * MCP:后台并行连接 MCP 服务器,减少启动时间 * MCP:连接 MCP 服务器时添加 `mcp-session-id` HTTP 头 * Lib:将斜杠命令(原"元命令")拆分为两组:Shell 级和 KimiSoul 级 * Lib:在 `Soul` 协议中添加 `available_slash_commands` 属性 * ACP:向 ACP 客户端广播 `/init`、`/compact` 和 `/yolo` 斜杠命令 * SlashCmd:添加 `/mcp` 斜杠命令,显示 MCP 服务器和工具状态 ## 0.65 (2025-12-16) * Lib:支持通过 `Session.create(work_dir, session_id)` 创建命名会话 * CLI:指定的会话 ID 不存在时自动创建新会话 * CLI:退出时删除空会话,列表中忽略上下文文件为空的会话 * UI:改进会话回放 * Lib:在 `LLM` 类中添加 `model_config: LLMModel | None` 和 `provider_config: LLMProvider | None` 属性 * MetaCmd:添加 `/usage` 元命令,为 Kimi Code 用户显示 API 使用情况 ## 0.64 (2025-12-15) * UI:修复 Windows 上 UTF-16 代理字符输入问题 * Core:添加 `/sessions` 元命令,列出现有会话并切换到选中的会话 * CLI:添加 `--session/-S` 选项,指定要恢复的会话 ID * MCP:添加 `kimi mcp` 子命令组,管理全局 MCP 配置文件 `~/.kimi/mcp.json` ## 0.63 (2025-12-12) * Tool:修复 `FetchURL` 工具通过服务获取失败时输出不正确的问题 * Tool:在 `Shell` 工具中使用 `bash` 而非 `sh`,提高兼容性 * Tool:修复 Windows 上 `Grep` 工具的 Unicode 解码错误 * ACP:通过 `kimi acp` 子命令支持 ACP 会话续接(列出/加载会话) * Lib:添加 `Session.find` 和 `Session.list` 静态方法,查找和列出会话 * ACP:调用 `SetTodoList` 工具时在客户端更新 Agent 计划 * UI:防止以 `/` 开头的普通消息被误当作元命令处理 ## 0.62 (2025-12-08) * ACP:修复工具结果(包括 Shell 工具输出)在 Zed 等 ACP 客户端中不显示的问题 * ACP:修复与最新版 Zed IDE (0.215.3) 的兼容性 * Tool:Windows 上使用 PowerShell 替代 CMD,提升可用性 * Core:修复工作目录中存在损坏符号链接时的启动崩溃 * Core:添加内置 `okabe` Agent 文件,启用 `SendDMail` 工具 * CLI:添加 `--agent` 选项,指定内置 Agent(如 `default`、`okabe`) * Core:改进压缩逻辑,更好地保留相关信息 ## 0.61 (2025-12-04) * Lib:修复作为库使用时的日志问题 * Tool:加强文件路径检查,防止共享前缀逃逸 * LLM:改进与部分第三方 OpenAI Responses 和 Anthropic API 供应商的兼容性 ## 0.60 (2025-12-01) * LLM:修复 Kimi 和 OpenAI 兼容供应商的交错思考问题 ## 0.59 (2025-11-28) * Core:将上下文文件位置移至 `.kimi/sessions/{workdir_md5}/{session_id}/context.jsonl` * Lib:将 `WireMessage` 类型别名移至 `kimi_cli.wire.message` * Lib:添加 `kimi_cli.wire.message.Request` 类型别名,用于请求消息(目前仅包含 `ApprovalRequest`) * Lib:添加 `kimi_cli.wire.message.is_event`、`is_request` 和 `is_wire_message` 工具函数,检查 Wire 消息类型 * Lib:添加 `kimi_cli.wire.serde` 模块,用于 Wire 消息的序列化和反序列化 * Lib:修改 `StatusUpdate` Wire 消息,不再使用 `kimi_cli.soul.StatusSnapshot` * Core:在会话目录中记录 Wire 消息到 JSONL 文件 * Core:引入 `TurnBegin` Wire 消息,标记每个 Agent 轮次的开始 * UI:Shell 模式下用面板重新打印用户输入 * Lib:添加 `Session.dir` 属性,获取会话目录路径 * UI:改进多个并行子代理时的"本会话批准"体验 * Wire:重新实现 Wire 服务器模式(通过 `--wire` 选项启用) * Lib:重命名类以保持一致性:`ShellApp` → `Shell`,`PrintApp` → `Print`,`ACPServer` → `ACP`,`WireServer` → `WireOverStdio` * Lib:重命名方法以保持一致性:`KimiCLI.run_shell_mode` → `run_shell`,`run_print_mode` → `run_print`,`run_acp_server` → `run_acp`,`run_wire_server` → `run_wire_stdio` * Lib:添加 `KimiCLI.run` 方法,使用给定用户输入运行一轮并产生 Wire 消息 * Print:修复 stream-json 打印模式输出刷新不正确的问题 * LLM:改进与部分 OpenAI 和 Anthropic API 供应商的兼容性 * Core:修复使用 Anthropic API 时压缩后的聊天供应商错误 ## 0.58 (2025-11-21) * Core:修复使用 `extend` 时 Agent 规格文件的字段继承问题 * Core:支持在子代理中使用 MCP 工具 * Tool:添加 `CreateSubagent` 工具,动态创建子代理(默认 Agent 中未启用) * Tool:Kimi Code 方案在 `FetchURL` 工具中使用 MoonshotFetch 服务 * Tool:截断 Grep 工具输出,避免超出 token 限制 ## 0.57 (2025-11-20) * LLM:修复思考开关未开启时的 Google GenAI 供应商问题 * UI:改进审批请求措辞 * Tool:移除 `PatchFile` 工具 * Tool:将 `Bash`/`CMD` 工具重命名为 `Shell` 工具 * Tool:将 `Task` 工具移至 `kimi_cli.tools.multiagent` 模块 ## 0.56 (2025-11-19) * LLM:添加 Google GenAI 供应商支持 ## 0.55 (2025-11-18) * Lib:添加 `kimi_cli.app.enable_logging` 函数,直接使用 `KimiCLI` 类时启用日志 * Core:修复 Agent 规格文件中的相对路径解析 * Core:防止 LLM API 连接失败时 panic * Tool:优化 `FetchURL` 工具,改进内容提取 * Tool:将 MCP 工具调用超时增加到 60 秒 * Tool:在 `Glob` 工具中提供更好的错误消息(当模式为 `**` 时) * ACP:修复思考内容显示不正确的问题 * UI:Shell 模式的小幅 UI 改进 ## 0.54 (2025-11-13) * Lib:将 `WireMessage` 从 `kimi_cli.wire.message` 移至 `kimi_cli.wire` * Print:修复 `stream-json` 输出格式缺少最后一条助手消息的问题 * UI:当 API 密钥被 `KIMI_API_KEY` 环境变量覆盖时添加警告 * UI:审批请求时发出提示音 * Core:修复 Windows 上的上下文压缩和清除问题 ## 0.53 (2025-11-12) * UI:移除控制台输出中不必要的尾部空格 * Core:存在不支持的消息部分时抛出错误 * MetaCmd:添加 `/yolo` 元命令,启动后启用 YOLO 模式 * Tool:为 MCP 工具添加审批请求 * Tool:在默认 Agent 中禁用 `Think` 工具 * CLI:未指定 `--thinking` 时恢复上次的思考模式 * CLI:修复 PyInstaller 打包的二进制文件中 `/reload` 不工作的问题 ## 0.52 (2025-11-10) * CLI:移除 `--ui` 选项,改用 `--print`、`--acp` 和 `--wire` 标志(Shell 仍为默认) * CLI:更直观的会话续接行为 * Core:为 LLM 空响应添加重试 * Tool:Windows 上将 `Bash` 工具改为 `CMD` 工具 * UI:修复退格后的补全问题 * UI:修复浅色背景下代码块的渲染问题 ## 0.51 (2025-11-08) * Lib:将 `Soul.model` 重命名为 `Soul.model_name` * Lib:将 `LLMModelCapability` 重命名为 `ModelCapability` 并移至 `kimi_cli.llm` * Lib:在 `ModelCapability` 中添加 `"thinking"` * Lib:移除 `LLM.supports_image_in` 属性 * Lib:添加必需的 `Soul.model_capabilities` 属性 * Lib:将 `KimiSoul.set_thinking_mode` 重命名为 `KimiSoul.set_thinking` * Lib:添加 `KimiSoul.thinking` 属性 * UI:改进 LLM 模型能力检查和提示 * UI:`/clear` 元命令时清屏 * Tool:支持 Windows 上自动下载 ripgrep * CLI:添加 `--thinking` 选项,以思考模式启动 * ACP:ACP 模式支持思考内容 ## 0.50 (2025-11-07) * 改进 UI 外观和体验 * 改进 Task 工具可观测性 ## 0.49 (2025-11-06) * 小幅用户体验改进 ## 0.48 (2025-11-06) * 支持 Kimi K2 思考模式 ## 0.47 (2025-11-05) * 修复某些环境下 Ctrl-W 不工作的问题 * 搜索服务未配置时不加载 SearchWeb 工具 ## 0.46 (2025-11-03) * 引入 Wire over stdio 用于本地 IPC(实验性,可能变更) * 支持 Anthropic 供应商类型 * 修复 PyInstaller 打包的二进制文件因入口点错误而无法工作的问题 ## 0.45 (2025-10-31) * 允许 `KIMI_MODEL_CAPABILITIES` 环境变量覆盖模型能力 * 添加 `--no-markdown` 选项禁用 Markdown 渲染 * 支持 `openai_responses` LLM 供应商类型 * 修复续接会话时的崩溃问题 ## 0.44 (2025-10-30) * 改进启动时间 * 修复用户输入中可能出现的无效字节 ## 0.43 (2025-10-30) * 基础 Windows 支持(实验性) * 环境变量覆盖 base URL 或 API 密钥时显示警告 * 如果 LLM 模型支持,则支持图片输入 * 续接会话时回放近期上下文历史 * 确保执行 Shell 命令后换行 ## 0.42 (2025-10-28) * 支持 Ctrl-J 或 Alt-Enter 插入换行 * 模式切换快捷键从 Ctrl-K 改为 Ctrl-X * 改进整体健壮性 * 修复 ACP 服务器 `no attribute` 错误 ## 0.41 (2025-10-26) * 修复 Glob 工具未找到匹配文件时的 bug * 确保使用 UTF-8 编码读取文件 * Shell 模式下禁用从 stdin 读取命令/查询 * 澄清 `/setup` 元命令中的 API 平台选择 ## 0.40 (2025-10-24) * 支持 `ESC` 键中断 Agent 循环 * 修复某些罕见情况下的 SSL 证书验证错误 * 修复 Bash 工具中可能的解码错误 ## 0.39 (2025-10-24) * 修复上下文压缩阈值检查 * 修复 Shell 会话中设置 SOCKS 代理时的 panic ## 0.38 (2025-10-24) * 小幅用户体验改进 ## 0.37 (2025-10-24) * 修复更新检查 ## 0.36 (2025-10-24) * 添加 `/debug` 元命令用于调试上下文 * 添加自动上下文压缩 * 添加审批请求机制 * 添加 `--yolo` 选项自动批准所有操作 * 渲染 Markdown 内容以提高可读性 * 修复中断元命令时的"未知错误"消息 ## 0.35 (2025-10-22) * 小幅 UI 改进 * 系统中未找到 ripgrep 时自动下载 * `--print` 模式下始终批准工具调用 * 添加 `/feedback` 元命令 ## 0.34 (2025-10-21) * 添加 `/update` 元命令检查更新,并在后台自动更新 * 支持在原始 Shell 模式下运行交互式 Shell 命令 * 添加 `/setup` 元命令设置 LLM 供应商和模型 * 添加 `/reload` 元命令重新加载配置 ## 0.33 (2025-10-18) * 添加 `/version` 元命令 * 添加原始 Shell 模式,可通过 Ctrl-K 切换 * 在底部状态栏显示快捷键 * 修复日志重定向 * 合并重复的输入历史 ## 0.32 (2025-10-16) * 添加底部状态栏 * 支持文件路径自动补全(`@filepath`) * 不在用户输入中间自动补全元命令 ## 0.31 (2025-10-14) * 真正修复 Ctrl-C 中断步骤的问题 ## 0.30 (2025-10-14) * 添加 `/compact` 元命令,允许手动压缩上下文 * 修复上下文为空时的 `/clear` 元命令 ## 0.29 (2025-10-14) * Shell 模式下支持 Enter 键接受补全 * Shell 模式下跨会话记住用户输入历史 * 添加 `/reset` 元命令作为 `/clear` 的别名 * 修复 Ctrl-C 中断步骤的问题 * 在 Kimi Koder Agent 中禁用 `SendDMail` 工具 ## 0.28 (2025-10-13) * 添加 `/init` 元命令分析代码库并生成 `AGENTS.md` 文件 * 添加 `/clear` 元命令清除上下文 * 修复 `ReadFile` 输出 ## 0.27 (2025-10-11) * 添加 `--mcp-config-file` 和 `--mcp-config` 选项加载 MCP 配置 * 将 `--agent` 选项重命名为 `--agent-file` ## 0.26 (2025-10-11) * 修复 `--output-format stream-json` 模式下可能的编码错误 ## 0.25 (2025-10-11) * 将包名从 `ensoul` 重命名为 `kimi-cli` * 将 `ENSOUL_*` 内置系统提示词参数重命名为 `KIMI_*` * 进一步解耦 `App` 与 `Soul` * 拆分 `Soul` 协议和 `KimiSoul` 实现以提高模块化 ## 0.24 (2025-10-10) * 修复 ACP `cancel` 方法 ## 0.23 (2025-10-09) * 在 Agent 文件中添加 `extend` 字段支持 Agent 文件扩展 * 在 Agent 文件中添加 `exclude_tools` 字段支持排除工具 * 在 Agent 文件中添加 `subagents` 字段支持定义子代理 ## 0.22 (2025-10-09) * 改进 `SearchWeb` 和 `FetchURL` 工具调用可视化 * 改进搜索结果输出格式 ## 0.21 (2025-10-09) * 添加 `--print` 选项作为 `--ui print` 的快捷方式,`--acp` 选项作为 `--ui acp` 的快捷方式 * 支持 `--output-format stream-json` 以 JSON 格式输出 * 添加 `SearchWeb` 工具,使用 `services.moonshot_search` 配置。需要在配置文件中配置 `"services": {"moonshot_search": {"api_key": "your-search-api-key"}}` * 添加 `FetchURL` 工具 * 添加 `Think` 工具 * 添加 `PatchFile` 工具,Kimi Koder Agent 中未启用 * 在 Kimi Koder Agent 中启用 `SendDMail` 和 `Task` 工具,改进工具提示词 * 添加 `ENSOUL_NOW` 内置系统提示词参数 * 改进 `/release-notes` 外观 * 改进工具描述 * 改进工具输出截断 ## 0.20 (2025-09-30) * 添加 `--ui acp` 选项启动 Agent Client Protocol (ACP) 服务器 ## 0.19 (2025-09-29) * print UI 支持管道输入的 stdin * 支持 `--input-format=stream-json` 用于管道输入的 JSON * 未启用 `SendDMail` 时不在上下文中包含 `CHECKPOINT` 消息 ## 0.18 (2025-09-29) * 支持 LLM 模型配置中的 `max_context_size`,配置最大上下文大小(token 数) * 改进 `ReadFile` 工具描述 ## 0.17 (2025-09-29) * 修复超过最大步数时错误消息中的步数 * 修复 `kimi_run` 中的历史文件断言错误 * 修复 print 模式和单命令 Shell 模式中的错误处理 * 为 LLM API 连接错误和超时错误添加重试 * 将默认 max-steps-per-run 增加到 100 ## 0.16.0 (2025-09-26) * 添加 `SendDMail` 工具(Kimi Koder 中禁用,可在自定义 Agent 中启用) * 可通过 `_history_file` 参数在创建新会话时指定会话历史文件 ## 0.15.0 (2025-09-26) * 改进工具健壮性 ## 0.14.0 (2025-09-25) * 添加 `StrReplaceFile` 工具 * 强调使用与用户相同的语言 ## 0.13.0 (2025-09-25) * 添加 `SetTodoList` 工具 * 在 LLM API 调用中添加 `User-Agent` * 改进系统提示词和工具描述 * 改进 LLM 错误消息 ## 0.12.0 (2025-09-24) * 添加 `print` UI 模式,可通过 `--ui print` 选项使用 * 添加日志和 `--debug` 选项 * 捕获 EOF 错误以改善体验 ## 0.11.1 (2025-09-22) * 将 `max_retry_per_step` 重命名为 `max_retries_per_step` ## 0.11.0 (2025-09-22) * 添加 `/release-notes` 命令 * 为 LLM API 错误添加重试 * 添加循环控制配置,如 `{"loop_control": {"max_steps_per_run": 50, "max_retry_per_step": 3}}` * 改进 `read_file` 工具的极端情况处理 * 禁止 Ctrl-C 退出 CLI,强制使用 Ctrl-D 或 `exit` 退出 ## 0.10.1 (2025-09-18) * 小幅改进斜杠命令外观 * 改进 `glob` 工具 ## 0.10.0 (2025-09-17) * 添加 `read_file` 工具 * 添加 `write_file` 工具 * 添加 `glob` 工具 * 添加 `task` 工具 * 改进工具调用可视化 * 改进会话管理 * `--continue` 会话时恢复上下文使用量 ## 0.9.0 (2025-09-15) * 移除 `--session` 和 `--continue` 选项 ## 0.8.1 (2025-09-14) * 修复配置模型转储 ## 0.8.0 (2025-09-14) * 添加 `shell` 工具和基础系统提示词 * 添加工具调用可视化 * 添加上下文使用量计数 * 支持中断 Agent 循环 * 支持项目级 `AGENTS.md` * 支持 YAML 定义的自定义 Agent * 支持通过 `kimi -c` 执行一次性任务 --- --- url: /zh/guides/ides.md --- # 在 IDE 中使用 Kimi Code CLI 支持通过 [Agent Client Protocol (ACP)](https://agentclientprotocol.com/) 集成到 IDE 中,让你在编辑器内直接使用 AI 辅助编程。 ## 前置准备 在配置 IDE 之前,请确保已安装 Kimi Code CLI 并完成 `/login` 配置。 ## 在 Zed 中使用 [Zed](https://zed.dev/) 是一个支持 ACP 的现代 IDE。 在 Zed 的配置文件 `~/.config/zed/settings.json` 中添加: ```json { "agent_servers": { "Kimi Code CLI": { "type": "custom", "command": "kimi", "args": ["acp"], "env": {} } } } ``` 配置说明: * `type`:固定值 `"custom"` * `command`:Kimi Code CLI 的命令路径,如果 `kimi` 不在 PATH 中,需要使用完整路径 * `args`:启动参数,`acp` 启用 ACP 模式 * `env`:环境变量,通常留空即可 保存配置后,在 Zed 的 Agent 面板中就可以创建 Kimi Code CLI 会话了。 ## 在 JetBrains IDE 中使用 JetBrains 系列 IDE(IntelliJ IDEA、PyCharm、WebStorm 等)通过 AI 聊天插件支持 ACP。 如果你没有 JetBrains AI 订阅,可以在注册表中启用 `llm.enable.mock.response` 来使用 AI 聊天功能。连按两次 Shift 搜索 "注册表" 即可打开。 在 AI 聊天面板的菜单中点击 "Configure ACP agents",添加以下配置: ```json { "agent_servers": { "Kimi Code CLI": { "command": "~/.local/bin/kimi", "args": ["acp"], "env": {} } } } ``` `command` 需要使用完整路径,可以在终端中运行 `which kimi` 获取。保存后,在 AI 聊天的 Agent 选择器中就可以选择 Kimi Code CLI 了。 --- --- url: /zh/guides/use-cases.md --- # 常见使用案例 Kimi Code CLI 可以帮助你完成多种软件开发和通用任务,以下是一些典型场景。 ## 实现新功能 当你需要为项目添加新功能时,直接用自然语言描述需求即可。Kimi Code CLI 会自动阅读相关代码、理解项目结构,然后进行修改。 ``` 给用户列表页面添加分页功能,每页显示 20 条记录 ``` Kimi Code CLI 通常会按照「读 → 改 → 验证」的流程工作: 1. **阅读**:搜索和阅读相关代码,理解现有实现 2. **修改**:编写或修改代码,遵循项目的代码风格 3. **验证**:运行测试或构建,确保修改没有引入问题 如果你对修改不满意,可以直接告诉 Kimi Code CLI 调整方向: ``` 分页组件的样式和项目其他地方不一致,参考 Button 组件的样式 ``` ## 修复 bug 描述你遇到的问题,Kimi Code CLI 会帮你定位原因并修复: ``` 用户登录后跳转到首页时,偶尔会显示未登录状态,帮我排查一下 ``` 对于有明确错误信息的问题,可以直接贴上错误日志: ``` 运行 npm test 时出现这个错误: TypeError: Cannot read property 'map' of undefined at UserList.render (src/components/UserList.jsx:15:23) 帮我修复 ``` 你也可以让 Kimi Code CLI 运行命令来复现和验证问题: ``` 运行测试,如果有失败的用例就修复它们 ``` ## 理解项目 Kimi Code CLI 可以帮你探索和理解不熟悉的代码库: ``` 这个项目的整体架构是怎样的?入口文件在哪里? ``` ``` 用户认证的流程是怎么实现的?涉及哪些文件? ``` ``` 解释一下 src/core/scheduler.py 这个文件的作用 ``` 如果你在阅读代码时遇到不理解的部分,可以随时提问: ``` useCallback 和 useMemo 有什么区别?这里为什么要用 useCallback? ``` ## 自动化小任务 Kimi Code CLI 可以执行各种重复性的小任务: ``` 把 src 目录下所有 .js 文件的 var 声明改成 const 或 let ``` ``` 给所有没有 docstring 的公开函数添加文档注释 ``` ``` 生成这个 API 模块的单元测试 ``` ``` 更新 package.json 中所有依赖到最新版本,然后运行测试确保没有问题 ``` ## 自动化通用任务 除了代码相关的任务,Kimi Code CLI 也可以处理一些通用场景。 **调研任务** ``` 帮我调研一下 Python 的异步 Web 框架,比较 FastAPI、Starlette 和 Sanic 的优缺点 ``` **数据分析** ``` 分析 logs 目录下的访问日志,统计每个接口的调用次数和平均响应时间 ``` **批量文件处理** ``` 把 images 目录下的所有 PNG 图片转换为 JPEG 格式,保存到 output 目录 ``` --- --- url: /zh/faq.md --- # 常见问题 ## 安装与鉴权 ### `/login` 时模型列表为空 如果在运行 `/login`(或 `/setup`)命令时看到 "No models available for the selected platform" 错误,可能是以下原因: * **API 密钥无效或过期**:检查你输入的 API 密钥是否正确,以及是否仍有效。 * **网络连接问题**:确认能正常访问 API 服务地址(如 `api.kimi.com` 或 `api.moonshot.cn`)。 ### API 密钥无效 API 密钥无效可能的原因: * **密钥输入错误**:检查是否有多余的空格或遗漏的字符。 * **密钥已过期或被撤销**:在平台控制台确认密钥状态。 * **环境变量覆盖**:检查是否有 `KIMI_API_KEY` 或 `OPENAI_API_KEY` 环境变量覆盖了配置文件中的密钥。可以运行 `echo $KIMI_API_KEY` 检查。 ### 会员过期或配额用尽 如果你使用 Kimi Code 平台,可以通过 `/usage` 命令查看当前的配额和会员状态。如果配额用尽或会员过期,需要在 [Kimi Code](https://kimi.com/coding) 续费或升级。 ## 交互问题 ### Shell 模式中 `cd` 命令无效 在 Shell 模式中执行 `cd` 命令不会改变 Kimi Code CLI 的工作目录。这是因为每次 Shell 命令在独立的子进程中执行,目录切换只在该进程内生效。 如果需要切换工作目录: * **退出并重新启动**:在目标目录中重新运行 `kimi` 命令。 * **使用 `--work-dir` 参数**:启动时指定工作目录,如 `kimi --work-dir /path/to/project`。 * **在命令中使用绝对路径**:直接使用绝对路径执行命令,如 `ls /path/to/dir`。 ### 粘贴图片失败 使用 `Ctrl-V` 粘贴图片时,如果提示 "Current model does not support image input",说明当前模型不支持图片输入。 解决方法: * **切换到支持图片的模型**:使用支持 `image_in` 能力的模型。 * **检查剪贴板内容**:确保剪贴板中确实有图片数据,而非图片文件的路径。 ### 工作目录被删除或移除 如果在会话期间工作目录变得不可访问(外置硬盘拔出、目录被删除或文件系统卸载),Kimi Code CLI 会检测到这一情况并显示崩溃报告,包含会话 ID 和工作目录路径,之后干净退出。你可以通过 `kimi -r ` 在正确的目录中恢复会话。 ## ACP 问题 ### IDE 无法连接到 Kimi Code CLI 如果 IDE(如 Zed 或 JetBrains IDE)无法连接到 Kimi Code CLI,请检查以下几点: * **确认 Kimi Code CLI 已安装**:运行 `kimi --version` 确认安装成功。 * **检查配置路径**:确保 IDE 配置中的 Kimi Code CLI 路径正确。通常可以使用 `kimi acp` 作为命令。 * **检查 uv 路径**:如果使用 uv 安装,确保 `~/.local/bin` 在 PATH 中。可以使用绝对路径,如 `/Users/yourname/.local/bin/kimi acp`。 * **查看日志**:检查 `~/.kimi/logs/kimi.log` 中的错误信息。 ## MCP 问题 ### MCP 服务启动失败 添加 MCP 服务器后,如果工具未加载或报错,可能是以下原因: * **命令不存在**:对于 stdio 类型的服务器,确保命令(如 `npx`)在 PATH 中。可以使用绝对路径配置。 * **配置格式错误**:检查 `~/.kimi/mcp.json` 是否为有效的 JSON 格式。运行 `kimi mcp list` 查看当前配置。 调试步骤: ```sh # 查看已配置的服务器 kimi mcp list # 测试服务器是否正常 kimi mcp test ``` ### OAuth 授权失败 对于需要 OAuth 授权的 MCP 服务器(如 Linear),如果授权失败: * **检查网络连接**:确保能访问授权服务器。 * **重新授权**:运行 `kimi mcp auth ` 重新进行授权。 * **重置授权**:如果授权信息损坏,可以运行 `kimi mcp reset-auth ` 清除后重试。 ### Header 格式错误 添加 HTTP 类型的 MCP 服务器时,Header 格式应为 `KEY: VALUE`(冒号后有空格)。例如: ```sh # 正确 kimi mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY: your-key" # 错误(缺少空格或使用等号) kimi mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY=your-key" ``` ## Print/Wire 模式问题 ### JSONL 输入格式无效 使用 `--input-format stream-json` 时,输入必须是有效的 JSONL(每行一个 JSON 对象)。常见问题: * **JSON 格式错误**:确保每行是完整的 JSON 对象,没有语法错误。 * **编码问题**:确保输入使用 UTF-8 编码。 * **换行符问题**:Windows 用户注意检查换行符是否为 `\n` 而非 `\r\n`。 正确的输入格式示例: ```json {"role": "user", "content": "你好"} ``` ### Print 模式无输出 如果 `--print` 模式下没有输出,可能是: * **未提供输入**:需要通过 `--prompt`(或 `--command`)或 stdin 提供输入。例如:`kimi --print --prompt "你好"`。 * **输出被缓冲**:尝试使用 `--output-format stream-json` 获取流式输出。 * **配置未完成**:确保已通过 `/login` 配置 API 密钥和模型。 ## 更新与升级 ### macOS 首次运行缓慢 macOS 的 Gatekeeper 安全机制会在首次运行新程序时进行检查,导致启动变慢。解决方法: * **等待检查完成**:首次运行时耐心等待,后续启动会恢复正常。 * **添加到开发者工具**:在「系统设置 → 隐私与安全性 → 开发者工具」中添加你的终端应用。 ### 如何升级 Kimi Code CLI 使用 uv 升级到最新版本: ```sh uv tool upgrade kimi-cli --no-cache ``` 添加 `--no-cache` 参数可以确保获取最新版本。 ### 启动时弹出更新提醒 当后台检查发现新版本时,Kimi Code CLI 会在 Shell 启动前显示一个阻断式更新提醒,列出当前版本和最新版本信息。你可以通过以下按键选择操作: * `Enter`:立即升级到最新版本 * `q`:暂时跳过,下次启动时继续提醒 * `s`:跳过该版本,不再提醒(直到有更新的版本发布) ### 如何禁用更新提醒 如果不希望 Kimi Code CLI 检查更新或在启动时显示更新提醒,可以设置环境变量: ```sh export KIMI_CLI_NO_AUTO_UPDATE=1 ``` 这会同时禁用后台更新检查、启动时的阻断式更新提醒和欢迎面板中的版本提示。可以将此行添加到你的 shell 配置文件(如 `~/.zshrc` 或 `~/.bashrc`)中。 --- --- url: /zh/configuration/providers.md --- # 平台与模型 Kimi Code CLI 支持多种 LLM 平台,可以通过配置文件或 `/login` 命令进行配置。 ## 平台选择 最简单的配置方式是在 Shell 模式下运行 `/login` 命令(别名 `/setup`),按照向导完成平台和模型的选择: 1. 选择 API 平台 2. 输入 API 密钥 3. 从可用模型列表中选择模型 配置完成后,Kimi Code CLI 会自动保存设置到 `~/.kimi/config.toml` 并重新加载。 `/login` 目前支持以下平台: | 平台 | 说明 | | --- | --- | | Kimi Code | Kimi Code 平台,支持搜索和抓取服务 | | Moonshot AI 开放平台 (moonshot.cn) | 中国区 API 端点 | | Moonshot AI Open Platform (moonshot.ai) | 全球区 API 端点 | 如需使用其他平台,请手动编辑配置文件。 ## 供应商类型 `providers` 配置中的 `type` 字段指定 API 供应商类型。不同类型使用不同的 API 协议和客户端实现。 | 类型 | 说明 | | --- | --- | | `kimi` | Kimi API | | `openai_legacy` | OpenAI Chat Completions API | | `openai_responses` | OpenAI Responses API | | `anthropic` | Anthropic Claude API | | `gemini` | Google Gemini API | | `vertexai` | Google Vertex AI | 所有供应商类型都支持通过 `custom_headers` 字段添加自定义 HTTP 请求头。详见 [配置文件](./config-files.md)。 ### `kimi` 用于连接 Kimi API,包括 Kimi Code 和 Moonshot AI 开放平台。 ```toml [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-xxx" ``` ### `openai_legacy` 兼容 OpenAI Chat Completions API 的平台,包括 OpenAI 官方 API 和各种兼容服务。 ```toml [providers.openai] type = "openai_legacy" base_url = "https://api.openai.com/v1" api_key = "sk-xxx" ``` ### `openai_responses` 用于 OpenAI Responses API(较新的 API 格式)。 ```toml [providers.openai-responses] type = "openai_responses" base_url = "https://api.openai.com/v1" api_key = "sk-xxx" ``` ### `anthropic` 用于连接 Anthropic Claude API。 ```toml [providers.anthropic] type = "anthropic" base_url = "https://api.anthropic.com" api_key = "sk-ant-xxx" ``` ### `gemini` 用于连接 Google Gemini API。 ```toml [providers.gemini] type = "gemini" base_url = "https://generativelanguage.googleapis.com" api_key = "xxx" ``` ### `vertexai` 用于连接 Google Vertex AI。需要通过 `env` 字段设置必要的环境变量。 ```toml [providers.vertexai] type = "vertexai" base_url = "https://xxx-aiplatform.googleapis.com" api_key = "" env = { GOOGLE_CLOUD_PROJECT = "your-project-id" } ``` ## 模型能力 模型配置中的 `capabilities` 字段声明模型支持的能力。这会影响 Kimi Code CLI 的功能可用性。 | 能力 | 说明 | | --- | --- | | `thinking` | 支持 Thinking 模式(深度思考),可开关 | | `always_thinking` | 始终使用 Thinking 模式(不可关闭) | | `image_in` | 支持图片输入 | | `video_in` | 支持视频输入 | ```toml [models.gemini-3-pro-preview] provider = "gemini" model = "gemini-3-pro-preview" max_context_size = 262144 capabilities = ["thinking", "image_in"] ``` ### `thinking` 声明模型支持 Thinking 模式。启用后,模型会在回答前进行更深入的推理,适合复杂问题。在 Shell 模式下,可以通过 `/model` 命令切换模型和 Thinking 模式,或在启动时通过 `--thinking` / `--no-thinking` 参数控制。 ### `always_thinking` 表示模型始终使用 Thinking 模式,无法关闭。例如 `kimi-k2-thinking-turbo` 等名称中包含 "thinking" 的模型通常具有此能力。使用这类模型时,`/model` 命令不会提示选择 Thinking 模式的开关。 ### `image_in` 启用图片输入能力后,可以在对话中粘贴图片(`Ctrl-V`)。 ### `video_in` 启用视频输入能力后,可以在对话中发送视频内容。 ## 搜索和抓取服务 `SearchWeb` 和 `FetchURL` 工具依赖外部服务,目前仅 Kimi Code 平台提供这些服务。 使用 `/login` 选择 Kimi Code 平台时,搜索和抓取服务会自动配置。 | 服务 | 对应工具 | 未配置时的行为 | | --- | --- | --- | | `moonshot_search` | `SearchWeb` | 工具不可用 | | `moonshot_fetch` | `FetchURL` | 回退到本地抓取 | 使用其他平台时,`FetchURL` 工具仍可使用,但会回退到本地抓取。 --- --- url: /zh/guides/getting-started.md --- # 开始使用 ::: danger 警告 **本项目已归档**。Kimi CLI 已停止维护,不再提供任何更新和安全修复,旧版将无法继续使用。请改为安装 [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code),详见 [迁移指南](https://moonshotai.github.io/kimi-code/zh/guides/migration)。 ::: ## Kimi Code CLI 是什么 Kimi Code CLI 是一个运行在终端中的 AI Agent,帮助你完成软件开发任务和终端操作。它可以阅读和编辑代码、执行 Shell 命令、搜索和抓取网页,并在执行过程中自主规划和调整行动。 Kimi Code CLI 适合以下场景: * **编写和修改代码**:实现新功能、修复 bug、重构代码 * **理解项目**:探索陌生的代码库,解答架构和实现问题 * **自动化任务**:批量处理文件、执行构建和测试、运行脚本 Kimi Code CLI 支持以下几种使用方式: * **[交互式命令行(`kimi`)](../reference/kimi-command.md)**:在终端中以 Shell 方式与 AI 对话,支持自然语言描述任务或直接执行 Shell 命令 * **[浏览器界面(`kimi web`)](../reference/kimi-web.md)**:在本地浏览器中打开图形界面,支持会话管理、文件引用、代码高亮等 * **[Agent 集成(`kimi acp`)](../reference/kimi-acp.md)**:以服务方式运行,通过 [Agent Client Protocol] 集成到 [IDE](./ides.md) 和其他本地 Agent 客户端中 ::: info 提示 如果你遇到问题或有建议,欢迎在 [GitHub Issues](https://github.com/MoonshotAI/kimi-cli/issues) 反馈。 ::: [Agent Client Protocol]: https://agentclientprotocol.com/ ## 安装 Kimi CLI 已归档,不应再安装。请改为安装 [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code): ```sh # Linux / macOS curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash ``` ```powershell # Windows (PowerShell) irm https://code.kimi.com/kimi-code/install.ps1 | iex ``` 如果你之前使用过 Kimi CLI,Kimi Code CLI 首次启动时会提示迁移配置、MCP 服务与会话,你也可以随时运行 `kimi migrate`。详见 [迁移指南](https://moonshotai.github.io/kimi-code/zh/guides/migration)。 ## 卸载 迁移到 Kimi Code CLI 后,卸载 Kimi CLI: ```sh uv tool uninstall kimi-cli ``` ## 第一次运行 在你想要工作的项目目录中运行 `kimi` 命令启动 Kimi Code CLI: ```sh cd your-project kimi ``` 首次启动时,你需要配置 API 来源。输入 `/login` 命令开始配置: ``` /login ``` 执行后首先选择平台。推荐选择 **Kimi Code**,会自动打开浏览器进行 OAuth 授权;选择其他平台则需要输入 API 密钥。配置完成后 Kimi Code CLI 会自动保存设置并重新加载。详见 [平台与模型](../configuration/providers.md)。 现在你可以直接用自然语言和 Kimi Code CLI 对话了。试着描述你想完成的任务,比如: ``` 帮我看一下这个项目的目录结构 ``` ::: tip 提示 如果项目中没有 `AGENTS.md` 文件,可以运行 `/init` 命令让 Kimi Code CLI 分析项目并生成该文件,帮助 AI 更好地理解项目结构和规范。 ::: 输入 `/help` 可以查看所有可用的 [斜杠命令](../reference/slash-commands.md) 和使用提示。 --- --- url: /zh/customization/plugins.md --- # 插件 (Beta) ::: warning Beta 功能 插件系统目前处于 Beta 阶段,具体的实现细节和配置定义可能会在未来版本中调整。请谨慎在生产环境中使用,并关注后续更新。 ::: 插件系统让你可以为 Kimi Code CLI 添加自定义工具,扩展 AI 的能力。与 MCP 服务器不同,插件是轻量级的本地工具包,适合封装项目特定的脚本和实用程序。 ## 插件是什么 一个插件就是一个包含 `plugin.json` 文件的目录。插件可以声明多个「工具」,每个工具是一个可执行命令(Python、TypeScript、Shell 脚本等),AI 可以调用这些工具来完成特定任务。 例如,你可以创建一个插件来: * 封装内部 API 的调用脚本 * 提供项目特定的代码生成工具 * 集成专有服务或数据库查询 插件与 Agent Skills 的区别: * **Skills**:通过 `SKILL.md` 提供知识性指导,AI 读取后遵循其中的规范 * **Plugins**:通过 `plugin.json` 声明可执行工具,AI 可以直接调用工具获取结果 ## 安装插件 使用 `kimi plugin` 命令管理插件。 **从本地目录安装** ```sh kimi plugin install /path/to/my-plugin ``` **从 ZIP 文件安装** ```sh # 本地 ZIP 文件 kimi plugin install my-plugin.zip # 远程 ZIP 链接(含 GitHub/GitLab 归档下载链接) kimi plugin install https://example.com/my-plugin.zip kimi plugin install https://github.com/user/repo/archive/refs/heads/main.zip ``` **从 Git 仓库安装** ```sh # 安装根目录的插件 kimi plugin install https://github.com/user/repo.git # 安装子目录中的插件(多插件仓库) kimi plugin install https://github.com/user/repo.git/plugins/my-plugin # 指定分支(使用浏览器 URL 格式) kimi plugin install https://github.com/user/repo/tree/develop/plugins/my-plugin ``` 当 Git 仓库根目录没有 `plugin.json` 时,Kimi Code CLI 会检查根目录及其直接子目录,并列出可用的插件供你选择。 **列出已安装插件** ```sh kimi plugin list ``` **查看插件详情** ```sh kimi plugin info my-plugin ``` **移除插件** ```sh kimi plugin remove my-plugin ``` ## 创建插件 创建插件只需要三步: 1. 创建一个目录 2. 编写 `plugin.json` 文件 3. 实现工具脚本 **目录结构** ``` my-plugin/ ├── plugin.json # 插件配置(必需) ├── config.json # 插件配置(可选,用于凭证注入) └── scripts/ # 工具脚本 ├── greet.py └── calc.ts ``` **`plugin.json` 格式** ```json { "name": "my-plugin", "version": "1.0.0", "description": "My custom plugin for project X", "config_file": "config.json", "inject": { "api_key": "api_key", "endpoint": "base_url" }, "tools": [ { "name": "greet", "description": "Generate a greeting message", "command": ["python3", "scripts/greet.py"], "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "Name to greet" } }, "required": ["name"] } } ] } ``` **字段说明** | 字段 | 说明 | 是否必填 | |------|------|----------| | `name` | 插件名称,只能使用小写字母、数字和连字符 | 是 | | `version` | 插件版本,语义化版本格式 | 是 | | `description` | 插件描述 | 否 | | `config_file` | 配置文件路径,用于凭证注入 | 否 | | `inject` | 凭证注入映射,键为目标路径,值为源变量名 | 否 | | `tools` | 工具列表 | 否 | **工具字段说明** | 字段 | 说明 | 是否必填 | |------|------|----------| | `name` | 工具名称 | 是 | | `description` | 工具描述 | 是 | | `command` | 执行命令,字符串数组 | 是 | | `parameters` | JSON Schema 格式的参数定义 | 否 | ## 凭证注入 如果你的插件需要调用 LLM API,可以通过 `inject` 配置自动获取 Kimi Code CLI 的凭证配置。 **`inject` 配置示例** ```json { "config_file": "config.json", "inject": { "llm.api_key": "api_key", "llm.endpoint": "base_url" } } ``` **支持的注入变量** | 变量名 | 说明 | |--------|------| | `api_key` | LLM 提供商的 API 密钥,支持 OAuth token 和静态 API key | | `base_url` | LLM API 的基础 URL | **`config.json` 模板** ```json { "llm": { "api_key": "", "endpoint": "" } } ``` 安装时,Kimi Code CLI 会将当前配置的 API 密钥和 base URL 注入到指定的配置文件中。如果配置了 OAuth,会自动获取并注入有效的 token。之后在应用启动时,Kimi Code CLI 也会尝试将最新的凭证(如刷新后的 OAuth token)写入已安装插件的配置文件中。 ::: tip 提示 一般情况下,不需要为了更新凭证而重新安装插件:切换 LLM 提供商或重新授权后,重启 Kimi Code CLI 即可自动刷新配置文件中的凭证,插件工具在实际运行时也会通过环境变量获得当前有效的凭证。只有在修改了插件本身的配置结构(例如 `config_file` 或 `inject` 映射)时,才需要重新安装插件。 ::: ::: info 关于 inject 键名 `inject` 中的键名(如 `llm.api_key`)也会被用作环境变量名传递给插件工具子进程。由于这些名称包含点号,在某些运行环境中访问可能不便(例如 POSIX shell 中 `$llm.api_key` 是无效的)。你可以通过字典/映射方式访问: * **Node.js**: `process.env["llm.api_key"]` * **Python**: `os.environ["llm.api_key"]` 如果希望使用更友好的环境变量名,建议在插件中使用大写下划线格式(如 `LLM_API_KEY`),并相应调整配置文件结构。 ::: ## 工具脚本规范 工具脚本通过标准输入接收参数,通过标准输出返回结果。 **输入格式** 脚本从 `stdin` 接收 JSON 对象: ```json { "name": "World" } ``` **输出格式** 脚本向 `stdout` 输出的内容会作为字符串返回给 Agent。如果需要结构化输出,建议输出 JSON 文本: ```json { "content": "Hello, World!" } ``` **Python 示例** ```python #!/usr/bin/env python3 import json import sys params = json.load(sys.stdin) name = params.get("name", "Guest") result = {"content": f"Hello, {name}!"} print(json.dumps(result)) ``` **TypeScript 示例** ```typescript #!/usr/bin/env tsx import * as readline from "readline"; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, }); let input = ""; rl.on("line", (line) => { input += line; }); rl.on("close", () => { const params = JSON.parse(input); const name = params.name || "Guest"; console.log(JSON.stringify({ content: `Hello, ${name}!` })); }); ``` ## 完整示例 ```json { "name": "sample-plugin", "version": "1.0.0", "description": "Sample plugin demonstrating Skills + Tools", "tools": [ { "name": "py_greet", "description": "Generate a greeting message (Python tool)", "command": ["python3", "scripts/greet.py"], "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "Name to greet" }, "lang": { "type": "string", "enum": ["en", "zh", "ja"], "description": "Language" } }, "required": ["name"] } }, { "name": "ts_calc", "description": "Evaluate a math expression (TypeScript tool)", "command": ["npx", "tsx", "scripts/calc.ts"], "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "Math expression to evaluate" } }, "required": ["expression"] } } ] } ``` ## 插件安装位置 插件安装在 `~/.kimi/plugins/` 目录下。每个插件是一个独立的子目录,包含完整的 `plugin.json` 和脚本文件。 ::: info 说明 插件与 MCP 服务器是互补的扩展机制: * **MCP**:适合需要持续运行的服务、复杂的工具编排、跨进程通信 * **插件**:适合简单的脚本封装、项目特定的工具、快速原型开发 ::: --- --- url: /zh/configuration/data-locations.md --- # 数据路径 Kimi Code CLI 将所有数据存储在用户主目录下的 `~/.kimi/` 目录中。本页介绍各类数据文件的位置和用途。 ::: tip 提示 可以通过设置 `KIMI_SHARE_DIR` 环境变量来自定义共享目录路径。详见 [环境变量](./env-vars.md#kimi-share-dir)。 注意:`KIMI_SHARE_DIR` 仅影响上述运行时数据的存储位置,不影响 [Agent Skills](../customization/skills.md) 的搜索路径。Skills 作为跨工具共享的能力扩展,与运行时数据是不同类型的数据。 ::: ## 目录结构 ``` ~/.kimi/ ├── config.toml # 主配置文件 ├── kimi.json # 元数据 ├── mcp.json # MCP 服务器配置 ├── credentials/ # OAuth 凭据 │ └── .json ├── mcp-oauth/ # MCP OAuth token ├── sessions/ # 会话数据 │ └── / │ └── / │ ├── context.jsonl │ ├── wire.jsonl │ └── state.json ├── imported_sessions/ # 导入的会话数据(通过 kimi vis 导入) │ └── / │ ├── context.jsonl │ ├── wire.jsonl │ └── state.json ├── plans/ # Plan 模式方案文件 │ └── .md ├── user-history/ # 输入历史 │ └── .jsonl └── logs/ # 日志 └── kimi.log ``` ## 配置与元数据 ### `config.toml` 主配置文件,存储供应商、模型、服务和运行参数。详见 [配置文件](./config-files.md)。 可以通过 `--config-file` 参数指定其他位置的配置文件。 ### `kimi.json` 元数据文件,存储 Kimi Code CLI 的运行状态,包括: * `work_dirs`: 工作目录列表及其最后使用的会话 ID * `thinking`: 上次会话是否启用 thinking 模式 此文件由 Kimi Code CLI 自动管理,通常不需要手动编辑。 ### `mcp.json` MCP 服务器配置文件,存储通过 `kimi mcp add` 命令添加的 MCP 服务器。详见 [MCP](../customization/mcp.md)。 示例结构: ```json { "mcpServers": { "context7": { "url": "https://mcp.context7.com/mcp", "transport": "http", "headers": { "CONTEXT7_API_KEY": "ctx7sk-xxx" } } } } ``` ## 凭据 OAuth 凭据存储在 `~/.kimi/credentials/` 目录下。通过 `/login` 登录 Kimi 账号后,OAuth token 会保存在此目录中。 MCP 服务器的 OAuth token 单独存储在 `~/.kimi/mcp-oauth/`。通过 `kimi mcp auth ` 授权使用 `--auth oauth` 添加的 MCP 服务器后,后续会话会复用该目录中的 token。可以用 `kimi mcp reset-auth ` 清除某个服务器的 MCP OAuth token。 `credentials/` 目录中的文件权限设置为仅当前用户可读写(600),以保护敏感信息。 ## 会话数据 会话数据按工作目录分组存储在 `~/.kimi/sessions/` 下。每个工作目录对应一个以路径 MD5 哈希命名的子目录,每个会话对应一个以会话 ID 命名的子目录。 ### `context.jsonl` 上下文历史文件,以 JSONL 格式存储会话的完整上下文。文件第一行是系统提示词记录(`_system_prompt`),后续每行是一条消息(用户输入、模型回复、工具调用等)或内部记录(检查点、token 用量等)。 系统提示词在会话创建时生成并冻结,会话恢复时直接复用而不重新生成。 Kimi Code CLI 使用此文件在 `--continue` 或 `--session` 时恢复会话上下文。 ### `wire.jsonl` Wire 消息记录文件,以 JSONL 格式存储会话中的 Wire 事件。用于会话回放和提取会话标题。 ### `state.json` 会话状态文件,存储会话的运行状态,包括: * `title`:用户手动设置的会话标题 * `approval`:审批决策状态(YOLO 和 AFK 模式开关、已自动批准的操作类型) * `plan_mode`:Plan 模式的开关状态 * `plan_session_id`:当前 Plan 会话的唯一标识符,用于关联 plan 文件 * `plan_slug`:Plan 文件的路径标识(即 `~/.kimi/plans/.md` 中的 slug),会话重启后可恢复到同一文件 * `subagent_instances`:子 Agent 实例的状态和元数据 * `additional_dirs`:通过 `--add-dir` 或 `/add-dir` 添加的额外工作区目录 恢复会话时,Kimi Code CLI 会读取此文件还原会话状态。此文件使用原子写入,防止崩溃时数据损坏。 ### `subagents//` 每个通过 `Agent` 工具创建的子 Agent 实例在会话目录下有独立的存储目录,包含: * `context.jsonl`:子 Agent 的对话历史 * `wire.jsonl`:子 Agent 的 Wire 事件记录 * `meta.json`:实例元数据(状态、类型、创建时间等) * `prompt.txt`:最后执行的 prompt * `output`:执行输出 恢复会话时,子 Agent 实例的上下文和状态会自动还原,允许通过 `resume` 参数继续使用。 ## Plan 方案文件 Plan 模式的方案文件存储在 `~/.kimi/plans/` 目录下。每个 Plan 会话对应一个随机命名的 Markdown 文件(即 `.md`)。 `plan_slug` 保存在 `state.json` 中,会话重启后仍能恢复到同一方案文件。使用 `/plan clear` 命令可以清除当前 Plan 会话的方案文件。 ## 输入历史 用户输入历史存储在 `~/.kimi/user-history/` 目录下。每个工作目录对应一个以路径 MD5 哈希命名的 `.jsonl` 文件。 输入历史用于 Shell 模式下的历史浏览(上下方向键)和搜索(Ctrl-R)。 ## 日志 运行日志存储在 `~/.kimi/logs/kimi.log`。默认日志级别为 INFO,使用 `--debug` 参数可启用 TRACE 级别。 日志文件用于排查问题。如需报告 bug,请附上相关日志内容。 ## 清理数据 删除共享目录(默认 `~/.kimi/`,或 `KIMI_SHARE_DIR` 指定的路径)可以完全清理 Kimi Code CLI 的所有数据,包括配置、会话和历史。 如只需清理部分数据: | 需求 | 操作 | | --- | --- | | 重置配置 | 删除 `~/.kimi/config.toml` | | 清理所有会话 | 删除 `~/.kimi/sessions/` 目录 | | 清理特定工作目录的会话 | 在 Shell 模式下使用 `/sessions` 查看并删除 | | 清理 Plan 方案文件 | 删除 `~/.kimi/plans/` 目录,或在 Plan 模式下使用 `/plan clear` | | 清理输入历史 | 删除 `~/.kimi/user-history/` 目录 | | 清理日志 | 删除 `~/.kimi/logs/` 目录 | | 清理 MCP 配置 | 删除 `~/.kimi/mcp.json` 或使用 `kimi mcp remove` | | 清理登录凭据 | 删除 `~/.kimi/credentials/` 目录或使用 `/logout` | --- --- url: /zh/reference/slash-commands.md --- # 斜杠命令 斜杠命令是 Kimi Code CLI 的内置命令,用于控制会话、配置和调试。在输入框中输入 `/` 开头的命令即可触发。 ::: tip Shell 模式 部分斜杠命令在 Shell 模式下也可以使用,包括 `/help`、`/exit`、`/version`、`/editor`、`/theme`、`/changelog`、`/feedback`、`/export`、`/import` 和 `/task`。 ::: ## 帮助与信息 ### `/help` 显示帮助信息。在全屏分页器中列出键盘快捷键、所有可用的斜杠命令以及已加载的 Skills。按 `q` 退出。 别名:`/h`、`/?` ### `/version` 显示 Kimi Code CLI 版本号。 ### `/changelog` 显示最近版本的变更记录。 别名:`/release-notes` ### `/feedback` 提交反馈以改进 Kimi Code CLI。执行后会提示输入反馈内容并提交。如果网络请求失败或超时,会自动回退到打开 GitHub Issues 页面。 ## 账号与配置 ### `/login` 登录或配置 API 平台。执行后首先选择平台: * **Kimi Code**:自动打开浏览器进行 OAuth 授权登录 * **其他平台**:输入 API 密钥,然后选择可用模型 配置完成后自动保存到 `~/.kimi/config.toml` 并重新加载。详见 [平台与模型](../configuration/providers.md)。 别名:`/setup` ::: tip 提示 此命令仅在使用默认配置文件时可用。如果通过 `--config` 或 `--config-file` 指定了配置,则无法使用此命令。 ::: ### `/logout` 登出当前平台。会清理存储的凭据并移除配置文件中的相关配置。登出后 Kimi Code CLI 会自动重新加载配置。 ### `/model` 切换模型和 Thinking 模式。 此命令会先从 API 平台刷新可用模型列表。不带参数调用时,显示交互式选择界面,首先选择模型,然后选择是否开启 Thinking 模式(如果模型支持)。 选择完成后,Kimi Code CLI 会自动更新配置文件并重新加载。 ::: tip 提示 此命令仅在使用默认配置文件时可用。如果通过 `--config` 或 `--config-file` 指定了配置,则无法使用此命令。 ::: ### `/editor` 设置外部编辑器。不带参数调用时,显示交互式选择界面;也可以直接指定编辑器命令,如 `/editor vim`。配置后按 `Ctrl-O` 会使用此编辑器打开当前输入内容。详见 [键盘快捷键](./keyboard.md#外部编辑器)。 ### `/theme` 切换终端配色主题。Kimi Code CLI 提供深色(`dark`)和浅色(`light`)两套配色方案,默认使用深色主题。 用法: * `/theme`:显示当前主题 * `/theme dark`:切换到深色主题 * `/theme light`:切换到浅色主题 切换后配置会保存到 `config.toml` 并自动重新加载。浅色主题会调整 Diff 高亮、任务浏览器、提示符补全菜单、底部工具栏和 MCP 状态等所有 UI 组件的颜色,以适配浅色终端背景。也可以直接在配置文件中设置 `theme = "light"`,详见 [配置文件](../configuration/config-files.md)。 ### `/reload` 重新加载配置文件,无需退出 Kimi Code CLI。 ### `/debug` 显示当前上下文的调试信息,包括: * 消息数量和 token 数 * 检查点数量 * 完整的消息历史 调试信息会在分页器中显示,按 `q` 退出。 ### `/usage` 显示 API 用量和配额信息,以进度条和剩余百分比的形式展示各类配额的使用情况。 别名:`/status` ::: tip 提示 此命令仅适用于 Kimi Code 平台。 ::: ### `/mcp` 显示当前连接的 MCP 服务器和加载的工具。详见 [Model Context Protocol](../customization/mcp.md)。 输出包括: * 服务器连接状态(绿色表示已连接) * 每个服务器提供的工具列表 ### `/hooks` 显示当前配置的 hooks。详见 [Hooks](../customization/hooks.md)。 输出包括: * 已配置 hook 的事件类型和数量 * 提示信息(如果未配置任何 hook) ## 会话管理 ### `/new` 创建一个新会话并立即切换过去,无需退出 Kimi Code CLI。如果当前会话没有任何内容,会自动清理空会话目录。 ### `/sessions` 列出当前工作目录下的所有会话,可切换到其他会话。 别名:`/resume` 使用方向键选择会话,按 `Enter` 确认切换,按 `Ctrl-C` 取消。按 `Ctrl-A` 可在 「仅当前目录」 和 「所有目录」 之间切换会话范围。 ### `/title` 查看或设置当前会话的标题。设置的标题会显示在 `/sessions` 列表中,方便识别和查找会话。 别名:`/rename` 用法: * `/title`:显示当前会话标题 * `/title `:设置会话标题(最长 200 字符) 标题在首次对话后会自动从用户消息中生成;使用此命令手动设置后,自动生成将不再覆盖。 ### `/undo` 回退到之前的某个轮次并重试。执行后会弹出交互式选择器,展示所有历史轮次的用户消息(截断到 80 字符)。选中某个轮次后,Kimi Code CLI 会 fork 出一个新会话,包含该轮次**之前**的所有对话历史,并将被选中轮次的用户消息预填到输入框,方便编辑后重新发送。原会话始终保留不丢失。 使用方向键选择轮次,按 `Enter` 确认,按 `Ctrl-C` 取消。 ::: tip 使用场景 当 API 返回截断或异常的回复导致会话无法继续时,使用 `/undo` 可以回退到出问题之前的轮次重新开始,无需放弃整个会话。 ::: ### `/fork` 从当前会话 fork 出一个新会话,复制完整的对话历史。原会话保留不变,新会话成为当前活动会话。适用于需要从当前状态分支出不同方向尝试的场景。 ### `/export` 将当前会话的上下文导出为 Markdown 文件,方便归档或分享。 用法: * `/export`:导出到当前工作目录,文件名自动生成(格式为 `kimi-export-<会话ID前8位>-<时间戳>.md`) * `/export `:导出到指定路径。如果路径是目录,文件名会自动生成;如果是文件路径,则直接写入该文件 导出文件包含: * 会话元数据(会话 ID、导出时间、工作目录、消息数、token 数) * 对话概览(主题、轮次数、工具调用次数) * 完整的对话历史,按轮次组织,包括用户消息、AI 回复、工具调用和工具结果 ### `/import` 从文件或其他会话导入上下文到当前会话。导入的内容会作为参考上下文附加到当前对话中,AI 可以利用这些信息来辅助后续的交互。 用法: * `/import `:从文件导入。支持 Markdown、文本、代码、配置文件等常见文本格式;不支持二进制文件(如图片、PDF、压缩包) * `/import `:从指定会话 ID 导入。不能导入当前会话自身 ### `/clear` 清空当前会话的上下文,开始新的对话。 别名:`/reset` ### `/compact` 手动压缩上下文,减少 token 使用。可以在命令后附带自定义指引,告诉 AI 在压缩时优先保留哪些信息,例如 `/compact 保留数据库相关的讨论`。 当上下文过长时,Kimi Code CLI 会自动触发压缩。此命令可手动触发压缩过程。 ## Skills ### `/skill:` 加载指定的 Skill,将 `SKILL.md` 内容作为提示词发送给 Agent。此命令适用于普通 Skill 和 Flow Skill。 例如: * `/skill:code-style`:加载代码风格规范 * `/skill:pptx`:加载 PPT 制作流程 * `/skill:git-commits 修复用户登录问题`:加载 Skill 并附带额外的任务描述 命令后面可以附带额外的文本,这些内容会追加到 Skill 提示词之后。详见 [Agent Skills](../customization/skills.md)。 ::: tip 提示 Flow Skill 也可以通过 `/skill:` 调用,此时作为普通 Skill 加载内容,不会自动执行流程。如需执行流程,请使用 `/flow:`。 ::: ### `/flow:` 执行指定的 Flow Skill。Flow Skill 在 `SKILL.md` 中内嵌 Agent Flow 流程图,执行后 Agent 会从 `BEGIN` 节点开始,按照流程图定义依次处理每个节点,直到到达 `END` 节点。 例如: * `/flow:pull-request`:执行创建 Pull Request 的工作流 * `/flow:code-review`:执行代码审查工作流 ::: tip 提示 Flow Skill 也可以通过 `/skill:` 调用,此时作为普通 Skill 加载内容,不会自动执行流程。 ::: 详见 [Agent Skills](../customization/skills.md#flow-skills)。 ## 工作区 ### `/add-dir` 将额外目录添加到工作区范围。添加后,该目录对所有文件工具(`ReadFile`、`WriteFile`、`Glob`、`Grep`、`StrReplaceFile` 等)可用,并会在系统提示词中展示目录结构。添加的目录会随会话状态持久化,恢复会话时自动还原。 用法: * `/add-dir `:添加指定目录到工作区 * `/add-dir`:不带参数时列出已添加的额外目录 ::: tip 提示 已在工作目录内的目录无需添加,因为它们已经可访问。也可以在启动时通过 `--add-dir` 参数添加,详见 [`kimi` 命令](./kimi-command.md#工作目录)。 ::: ## 其他 ### `/btw` 在不打断主对话的情况下提出快速侧问。在空闲和 streaming 期间均可使用。 用法:`/btw <问题>` 侧问在隔离的上下文中运行:能看到对话历史但不会修改它。工具调用被禁用——响应仅基于模型对当前对话的已有了解,以纯文本形式回答。 在 streaming 期间,响应会显示在一个可滚动的模态面板中,覆盖在提示区域上方。使用 `↑`/`↓` 滚动,`Escape` 关闭。 ::: tip 此命令仅在交互式 Shell 模式下可用。Wire 和 ACP 客户端可使用 `BtwBegin`/`BtwEnd` Wire 事件配合 `run_side_question()` API。 ::: ### `/init` 分析当前项目并生成 `AGENTS.md` 文件。 此命令会启动一个临时子会话分析代码库结构,生成项目说明文档,帮助 Agent 更好地理解项目。 ### `/plan` 切换 Plan 模式。Plan 模式下 AI 只能使用只读工具探索代码库,将实施方案写入 plan 文件后提交给你审批。详见 [Plan 模式](../guides/interaction.md#plan-模式)。 用法: * `/plan`:切换 Plan 模式开关 * `/plan on`:开启 Plan 模式 * `/plan off`:关闭 Plan 模式 * `/plan view`:查看当前方案内容 * `/plan clear`:清除当前方案文件 开启 Plan 模式后,提示符变为 `📋`,底部状态栏显示蓝色的 `plan` 标识。 ### `/task` 打开交互式任务浏览器,查看、监控和管理后台任务。 任务浏览器为三列 TUI 界面: * **左列**:任务列表,显示任务 ID、状态和描述 * **中列**:选中任务的详细信息,包括 ID、状态、描述、时间、exit code 等 * **右列**:最后几行输出预览 支持以下键盘操作: | 快捷键 | 功能 | |--------|------| | `Enter` / `O` | 在分页器中查看选中任务的完整输出 | | `S` | 请求停止选中任务(需确认) | | `Tab` | 切换过滤模式(全部 / 仅活跃任务) | | `R` | 刷新任务列表 | | `Q` / `Esc` | 退出浏览器 | 任务浏览器每秒自动刷新,实时显示任务状态变化。 ::: tip 提示 后台任务通过 AI 使用 `Shell` 工具的 `run_in_background=true` 参数启动。当后台任务完成时,系统会自动通知 AI。 ::: ### `/yolo` 切换 YOLO 模式。开启后自动批准所有工具调用,底部状态栏会显示黄色的 YOLO 标识;再次输入可关闭。YOLO 只解除审批摩擦——Agent 仍可通过 `AskUserQuestion` 向你提问。`/yolo` 与 `/afk` 相互独立。 ::: warning 注意 YOLO 模式会跳过所有审批确认,请确保你了解可能的风险。 ::: ### `/afk` 切换 AFK(away-from-keyboard)模式。开启后会自动批准所有工具调用,并进一步自动 dismiss Agent 发出的任何 `AskUserQuestion`——让 Agent 自己做判断,不再等待一个永远不会到来的回答。状态栏会显示独立的橙色 AFK 标识,与 YOLO 标识互不相干;再次输入可关闭。 ::: warning 注意 AFK 会跳过所有审批确认,并且去掉提问澄清的安全网。仅在你确实无法守在终端前时使用。 ::: ### `/web` 切换到 Web UI。执行后 Kimi Code CLI 会启动 Web UI 服务器并在浏览器中打开当前会话,你可以在 Web UI 中继续对话。详见 [Web UI](./kimi-web.md)。 ### `/vis` 切换到 Agent Tracing Visualizer。执行后 Kimi Code CLI 会启动可视化面板服务器并在浏览器中打开当前会话的追踪视图,你可以在其中检查 Wire 事件时间线、上下文消息和用量统计。详见 [Agent Tracing Visualizer](./kimi-vis.md)。 ### `/upgrade` 安装新版 Kimi Code——更快、更强大的继任版本。执行后会显示安装命令并询问是否立即安装: * 选择立即安装:Kimi Code CLI 会运行安装脚本,你现有的配置和会话会自动迁移 * 选择稍后安装:仅显示安装命令,方便你手动执行 安装完成后,在新终端中运行 `kimi` 即可启动新版 Kimi Code。 ::: tip 提示 此命令仅在交互式 Shell 模式下可用。 ::: ## 命令补全 在输入框中输入 `/` 后,会自动显示可用命令列表。继续输入可过滤命令,支持模糊匹配,按 Enter 选择。 例如,输入 `/ses` 会匹配到 `/sessions`,输入 `/clog` 会匹配到 `/changelog`。命令的别名也支持匹配,例如输入 `/h` 会匹配到 `/help`。 --- --- url: /zh/configuration/env-vars.md --- # 环境变量 Kimi Code CLI 支持通过环境变量覆盖配置或控制运行行为。本页列出所有支持的环境变量。 关于环境变量如何覆盖配置文件的详细说明,请参阅 [配置覆盖](./overrides.md)。 ## Kimi 环境变量 以下环境变量在使用 `kimi` 类型的供应商时生效,用于覆盖供应商和模型配置。 | 环境变量 | 说明 | | --- | --- | | `KIMI_BASE_URL` | API 基础 URL | | `KIMI_API_KEY` | API 密钥 | | `KIMI_MODEL_NAME` | 模型标识符 | | `KIMI_MODEL_MAX_CONTEXT_SIZE` | 最大上下文长度(token 数) | | `KIMI_MODEL_CAPABILITIES` | 模型能力,逗号分隔(如 `thinking,image_in`) | | `KIMI_MODEL_TEMPERATURE` | 生成参数 `temperature` | | `KIMI_MODEL_TOP_P` | 生成参数 `top_p` | | `KIMI_MODEL_MAX_COMPLETION_TOKENS` | `max_completion_tokens` 的显式硬上限 | | `KIMI_MODEL_MAX_TOKENS` | `KIMI_MODEL_MAX_COMPLETION_TOKENS` 的兼容别名 | | `KIMI_MODEL_THINKING_KEEP` | Moonshot `thinking.keep` 开关(Preserved Thinking),仅在 Thinking 模式下生效 | ### `KIMI_BASE_URL` 覆盖配置文件中供应商的 `base_url` 字段。 ```sh export KIMI_BASE_URL="https://api.moonshot.cn/v1" ``` ### `KIMI_API_KEY` 覆盖配置文件中供应商的 `api_key` 字段。用于在不修改配置文件的情况下注入 API 密钥,适合 CI/CD 环境。 ```sh export KIMI_API_KEY="sk-xxx" ``` ### `KIMI_MODEL_NAME` 覆盖配置文件中模型的 `model` 字段(API 调用时使用的模型标识符)。 ```sh export KIMI_MODEL_NAME="kimi-k2-thinking-turbo" ``` ### `KIMI_MODEL_MAX_CONTEXT_SIZE` 覆盖配置文件中模型的 `max_context_size` 字段。必须是正整数。 ```sh export KIMI_MODEL_MAX_CONTEXT_SIZE="262144" ``` ### `KIMI_MODEL_CAPABILITIES` 覆盖配置文件中模型的 `capabilities` 字段。多个能力用逗号分隔,支持的值为 `thinking`、`always_thinking`、`image_in` 和 `video_in`。 ```sh export KIMI_MODEL_CAPABILITIES="thinking,image_in" ``` ### `KIMI_MODEL_TEMPERATURE` 设置生成参数 `temperature`,控制输出的随机性。值越高输出越随机,值越低输出越确定。 ```sh export KIMI_MODEL_TEMPERATURE="0.7" ``` ### `KIMI_MODEL_TOP_P` 设置生成参数 `top_p`(nucleus sampling),控制输出的多样性。 ```sh export KIMI_MODEL_TOP_P="0.9" ``` ### `KIMI_MODEL_MAX_COMPLETION_TOKENS` 设置生成参数 `max_completion_tokens` 的显式硬上限。未设置时,Kimi Code CLI 使用模型的 剩余上下文窗口;每次请求都会将实际值动态限制为 `max_context_size - input_tokens`。 ```sh export KIMI_MODEL_MAX_COMPLETION_TOKENS="4096" ``` `KIMI_MODEL_MAX_TOKENS` 仍可使用;如果两个环境变量都设置,优先使用 `KIMI_MODEL_MAX_COMPLETION_TOKENS`。将任一变量设为 `0` 或负整数可禁用 completion token 限制。 ### `KIMI_MODEL_THINKING_KEEP` 将 env 值原样作为 `thinking.keep` 字段发送给 Moonshot API,用于开启 Preserved Thinking(参考 [Moonshot 官方文档](https://platform.kimi.com/docs/guide/use-kimi-k2-thinking-model#preserved-thinking))。设为 `all` 可让模型在多轮之间保留历史 reasoning\_content。值不做任何校验、不做大小写归一化,透传给 API 自己判断。 ```sh export KIMI_MODEL_THINKING_KEEP="all" ``` 未设置或设为空字符串时,请求体不携带此字段(等同当前默认行为)。该覆盖仅在当前模型真正处于 Thinking 模式时生效;对非 Thinking 模式的调用会被忽略,以避免发出只有 `thinking.keep` 而缺少 `thinking.type` 的无效请求体。 此参数仅在支持 Preserved Thinking 的 Moonshot 模型(例如 `kimi-k2.6` / `kimi-k2-thinking`)上生效。传给其它模型时,Moonshot API 会忽略或拒绝该字段,CLI 本身不做校验。 ::: warning 注意成本 `thinking.keep=all` 会让 API 在多轮之间保留历史 reasoning\_content,input tokens 与 API 费用都会显著增加。请在确实需要 Preserved Thinking 时再开启。 ::: ## OpenAI 兼容环境变量 以下环境变量在使用 `openai_legacy` 或 `openai_responses` 类型的供应商时生效。 | 环境变量 | 说明 | | --- | --- | | `OPENAI_BASE_URL` | API 基础 URL | | `OPENAI_API_KEY` | API 密钥 | ### `OPENAI_BASE_URL` 覆盖配置文件中供应商的 `base_url` 字段。 ```sh export OPENAI_BASE_URL="https://api.openai.com/v1" ``` ### `OPENAI_API_KEY` 覆盖配置文件中供应商的 `api_key` 字段。 ```sh export OPENAI_API_KEY="sk-xxx" ``` ## 其他环境变量 | 环境变量 | 说明 | | --- | --- | | `KIMI_SHARE_DIR` | 自定义共享目录路径(默认 `~/.kimi`) | | `KIMI_CLI_NO_AUTO_UPDATE` | 禁用所有更新相关功能 | | `KIMI_CLI_PASTE_CHAR_THRESHOLD` | 粘贴文本折叠的字符数阈值(默认 `1000`) | | `KIMI_CLI_PASTE_LINE_THRESHOLD` | 粘贴文本折叠的行数阈值(默认 `15`) | ### `KIMI_SHARE_DIR` 自定义 Kimi Code CLI 的共享目录路径。默认路径为 `~/.kimi`,配置、会话、日志等运行时数据存储在此目录下。 ```sh export KIMI_SHARE_DIR="/path/to/custom/kimi" ``` 详见 [数据路径](./data-locations.md)。 ::: warning 注意 `KIMI_SHARE_DIR` 不影响 [Agent Skills](../customization/skills.md) 的搜索路径。Skills 是跨工具共享的能力扩展(与 Claude、Codex 等兼容),与应用运行时数据是不同类型的数据。如需覆盖 Skills 路径,请使用 `--skills-dir` 参数。 ::: ### `KIMI_CLI_NO_AUTO_UPDATE` 设置为 `1`、`true`、`t`、`yes` 或 `y`(不区分大小写)时,禁用所有更新相关功能,包括后台自动更新检查、启动时的阻断式更新提醒和欢迎面板中的版本提示。 ```sh export KIMI_CLI_NO_AUTO_UPDATE="1" ``` ::: tip 提示 如果你通过 Nix 或其他包管理器安装 Kimi Code CLI,通常会自动设置此环境变量,因为更新由包管理器处理。 ::: ### `KIMI_CLI_PASTE_CHAR_THRESHOLD` 在 Agent 模式下,当粘贴文本的字符数达到此阈值时,文本会被折叠为占位符(如 `[Pasted text #1 +10 lines]`)显示,提交时自动展开为完整内容。默认值为 `1000`。 ```sh export KIMI_CLI_PASTE_CHAR_THRESHOLD="1000" ``` ### `KIMI_CLI_PASTE_LINE_THRESHOLD` 在 Agent 模式下,当粘贴文本的行数达到此阈值时,文本会被折叠为占位符显示。默认值为 `15`。 ```sh export KIMI_CLI_PASTE_LINE_THRESHOLD="15" ``` ::: tip 提示 部分终端(如通过 SSH 连接的 XShell)在粘贴多行文本后,可能出现中文/日文/韩文等 CJK 输入法无法正常工作的问题,表现为 IME 候选窗口不弹出或输入无响应,需要按 Ctrl+C 后才能恢复。 这是因为多行文本在输入缓冲区中会导致终端光标定位信息错乱,影响 IME 的组合窗口定位。你可以通过降低行数阈值来规避此问题——将包含换行的粘贴内容折叠为单行占位符: ```sh export KIMI_CLI_PASTE_LINE_THRESHOLD="2" ``` 设置后,任何包含换行的粘贴内容都会被自动折叠,避免多行文本进入输入缓冲区。单行粘贴(如 URL、短命令)不受影响。 注意:两个阈值的判断逻辑是"满足任一即折叠"(字符数 **或** 行数),因此只需调低行数阈值即可。不建议将字符数阈值设为很小的值(如 `1`),否则所有非空粘贴(包括单行短文本)都会被折叠。 ::: --- --- url: /zh/release-notes/breaking-changes.md --- # 破坏性变更与迁移说明 本页面记录 Kimi Code CLI 各版本中的破坏性变更及对应的迁移指引。 ## 未发布 ## 1.51.0 ### PyPI 上的 `kimi-code` 包不再安装 Kimi CLI PyPI 上的 `kimi-code` 包原本是 Kimi CLI 的别名,现在改为一个占位包:运行时只打印新版 Kimi Code CLI 的安装说明,并以状态码 1 退出。Kimi CLI 本身已归档,不再维护。 * **受影响**:通过 PyPI 上的 `kimi-code` 包安装 Kimi CLI 的用户(例如 `uv tool install kimi-code`) * **迁移**:使用 `curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash`(Windows:`irm https://code.kimi.com/kimi-code/install.ps1 | iex`)安装 Kimi Code CLI,然后运行 `kimi migrate` 迁移配置和会话。详见 [迁移指南](https://moonshotai.github.io/kimi-code/zh/guides/migration) ## 1.49.0 ### Kimi 不再自动发送旧版 `reasoning_effort` Kimi 的 Thinking 配置现在仅使用 `thinking.type`。`Kimi.with_thinking(...)` 不再自动把旧版 `reasoning_effort` 参数加入请求。 * **受影响**:通过 Kosong 的 Kimi 供应商连接仍要求 `reasoning_effort` 的旧版 Kimi 兼容端点的应用 * **迁移**:将端点升级为支持 `thinking.type`。如果旧版端点仍要求该参数,请通过 `with_generation_kwargs(reasoning_effort="...")` 显式传入 ## 1.43.0 ### MCP OAuth token 缓存迁移到 `~/.kimi/mcp-oauth/` Kimi Code CLI 现在为 MCP 服务器使用 FastMCP 3 的持久化 OAuth 存储 API,并将 MCP OAuth token 存储在 `~/.kimi/mcp-oauth/`。旧 FastMCP 2.x 缓存位置中的 token 不会自动迁移。 * **受影响**:升级前已经授权过 OAuth MCP 服务器的用户 * **迁移**:如果 `kimi mcp list` 显示某个 OAuth 服务器需要授权,请运行一次 `kimi mcp auth `,在 `~/.kimi/mcp-oauth/` 中创建新的 token。如果已存储的 token 失效或损坏,可先运行 `kimi mcp reset-auth ` 再重新授权 ## 1.42.0 ### Windows Shell 后端从 PowerShell 切换为 Git Bash Windows 上的 Shell 工具现在通过 `bash.exe`(POSIX 语义)执行命令,不再使用 `powershell.exe`。Windows 用户获得与 Linux/macOS 一致的 Unix 风格命令语法,但需要先安装 Git for Windows。 * **受影响**:所有 Windows 用户;依赖 PowerShell 专属语法(`Get-ChildItem`、`Where-Object`、`cmdlet -Foo Bar` 参数风格、仅 `;` 链式命令、`NUL` 重定向等)经由 Shell 工具执行的集成、agent 规格或保存的代码片段 * **迁移**: 1. 如果尚未安装,先安装 [Git for Windows](https://git-scm.com/downloads/win);其自带的 `bash.exe`(通常位于 `C:\Program Files\Git\bin\bash.exe`)会通过 `where.exe git` 或标准安装位置自动发现 2. 如果 `bash.exe` 在非标准位置,启动 kimi-cli 前把 `KIMI_CLI_GIT_BASH_PATH` 环境变量设为它的绝对路径 3. 把任何硬编码 PowerShell 语法的自定义提示词、agent 规格或代码片段改为 Unix shell 语法(Shell 命令内用正斜杠路径,`/dev/null` 代替 `NUL`,控制流用 `&&` 和 `||`,文本工具用 `grep`/`sed`/`awk` 而非 PowerShell cmdlet) 4. 注意:从 bash 中调用 `python.exe`、`node.exe` 等原生 Windows 程序时仍需要传入原生 Windows 路径(例如 `python C:\path\to\script.py`);只有 POSIX-aware 工具(cat、ls、grep 等)才能识别 `/c/path/...` 形式 5. 如果 kimi-cli 找不到 `bash.exe`,现在会在启动时打印安装提示并退出,而不是回退到 PowerShell ## 1.40.0 ### `--print` 现在使用 runtime AFK 语义而不是 YOLO 语义 Print 模式仍然是非交互运行,并且会自动处理审批,但现在设置的是仅本次调用生效的 AFK 覆盖,而不是启用 YOLO。也就是说,`--print` 会把用户视为不在场并自动 dismiss `AskUserQuestion`,但之后以交互方式恢复同一会话时,不会仅仅因为之前运行过 Print 模式而继承 AFK。 * **受影响**:通过显式 YOLO 标志推断 Print 模式行为的脚本、包装器或自定义集成 * **迁移**:把 `--print` / `--quiet` 视为非交互 AFK 运行。只有在用户仍可回应、但希望绕过权限审批时才使用 `--yolo` ### `skip_yolo_prompt_injection` 替换为 `skip_afk_prompt_injection` YOLO 不再注入模型指导,因此旧的 `skip_yolo_prompt_injection` 配置键会被忽略。剩余的非交互提示属于 AFK 模式,可以通过 `skip_afk_prompt_injection` 关闭。 * **受影响**:设置了 `skip_yolo_prompt_injection` 的配置文件或嵌入式应用 * **迁移**:如果需要抑制 AFK 模式提示,请把 `skip_yolo_prompt_injection = true` 替换为 `skip_afk_prompt_injection = true` ## 1.39.0 ### `merge_all_available_skills` 默认值翻转为 `true` `merge_all_available_skills` 配置项的默认值从 `false` 改为 `true`。kimi-cli 现在默认会合并用户级和项目级所有已存在的品牌 Skills 目录(`.kimi/skills`、`.claude/skills`、`.codex/skills`),而不是仅使用找到的第一个。升级后,同时维护多个品牌目录(例如同时保留 `~/.kimi/skills` 和 `~/.claude/skills`)的用户会开箱即看到全部 Skills。 * **受影响**:同时维护多个品牌 Skills 目录,并依赖旧的"仅取第一个"行为来隐藏重复项的用户 * **迁移**:在配置中显式设置 `merge_all_available_skills = false` 可恢复旧的仅匹配第一个目录的行为 ## 1.25.0 ### Wire 协议 1.6——子 Agent 与审批字段变更 `SubagentEvent` 的 `task_tool_call_id` 字段重命名为 `parent_tool_call_id`,新增可选字段 `agent_id`、`subagent_type`。`ApprovalRequest` 新增 `source_kind`、`source_id`、`agent_id`、`subagent_type`、`source_description` 字段。`ApprovalResponse` 新增 `feedback` 字段。 * **受影响**:解析 `SubagentEvent` 或 `ApprovalRequest`/`ApprovalResponse` 载荷的 Wire 模式客户端 * **迁移**:在事件处理器中将 `task_tool_call_id` 重命名为 `parent_tool_call_id`;根据需要处理新增的可选字段 ### `CreateSubagent` 和 `Task`(multiagent)工具移除 `kimi_cli.tools.multiagent` 下的 `CreateSubagent` 和 `Task` 工具已移除,由新的 `Agent` 工具替代。 * **受影响**:在 Agent YAML 中引用 `kimi_cli.tools.multiagent:Task` 或 `kimi_cli.tools.multiagent:CreateSubagent` 的自定义 Agent 配置 * **迁移**:在 Agent YAML 的 `allowed_tools` 中替换为 `kimi_cli.tools.agent:Agent` ### `TaskOutput` `block` 参数默认值变更 `TaskOutput` 工具的 `block` 参数默认值从 `true` 改为 `false`。`TaskOutput` 现在默认返回非阻塞的状态/输出快照。 * **受影响**:依赖 `TaskOutput` 默认阻塞行为的自定义 Agent 或 Wire 模式客户端 * **迁移**:如需等待任务完成,显式传入 `block=true` ## 0.81 - Prompt Flow 被 Flow Skills 取代 ### `--prompt-flow` 选项移除 `--prompt-flow` CLI 选项已移除,请改用 flow skills。 * **受影响**:使用 `--prompt-flow` 加载 Mermaid/D2 流程图的脚本和自动化 * **迁移**:创建包含嵌入式 Agent Flow 的 flow skill(在 `SKILL.md` 中),并通过 `/flow:` 调用 ### `/begin` 命令被替换 `/begin` 斜杠命令已被 `/flow:` 命令替换。 * **受影响**:使用 `/begin` 启动已加载 Prompt Flow 的用户 * **迁移**:使用 `/flow:` 直接调用 flow skills ## 0.77 - Thinking 模式与 CLI 选项变更 ### Thinking 模式设置迁移调整 从 `0.76` 升级后,Thinking 模式设置不再自动保留。此前保存在 `~/.kimi/kimi.json` 中的 `thinking` 状态不再使用,改为通过 `~/.kimi/config.toml` 中的 `default_thinking` 配置项管理,但不会自动从旧版 `metadata` 迁移。 * **受影响**:此前启用 Thinking 模式的用户 * **迁移**:升级后需重新设置 Thinking 模式: * 使用 `/model` 命令选择模型时设置 Thinking 模式(交互式) * 或手动在 `~/.kimi/config.toml` 中添加: ```toml default_thinking = true # 如需默认启用 Thinking 模式 ``` ### `--query` 选项移除 `--query`(`-q`)已移除,改用 `--prompt` 作为主推参数,`--command` 作为别名。 * **受影响**:使用 `--query` 或 `-q` 的脚本与自动化 * **迁移**: * `--query` / `-q` → `--prompt` / `-p` * 或继续使用 `--command` / `-c` ## 0.74 - ACP 命令变更 ### `--acp` 选项弃用 `--acp` 选项已弃用,请使用 `kimi acp` 子命令。 * **受影响**:使用 `kimi --acp` 的脚本和 IDE 配置 * **迁移**:`kimi --acp` → `kimi acp` ## 0.66 - 配置文件与供应商类型 ### 配置文件格式迁移 配置文件格式从 JSON 迁移至 TOML。 * **受影响**:使用 `~/.kimi/config.json` 的用户 * **迁移**:Kimi Code CLI 会自动读取旧的 JSON 配置,但建议手动迁移到 TOML 格式 * **新位置**:`~/.kimi/config.toml` JSON 配置示例: ```json { "default_model": "kimi-k2-0711", "providers": { "kimi": { "type": "kimi", "base_url": "https://api.kimi.com/coding/v1", "api_key": "your-key" } } } ``` 对应的 TOML 配置: ```toml default_model = "kimi-k2-0711" [providers.kimi] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "your-key" ``` ### `google_genai` 供应商类型重命名 Gemini Developer API 的供应商类型从 `google_genai` 重命名为 `gemini`。 * **受影响**:配置中使用 `type = "google_genai"` 的用户 * **迁移**:将配置中的 `type` 值改为 `"gemini"` * **兼容性**:`google_genai` 仍可使用,但建议更新 ## 0.57 - 工具变更 ### `Shell` 工具 `Bash` 工具(Windows 上为 `CMD`)统一重命名为 `Shell`。 * **受影响**:Agent 文件中引用 `Bash` 或 `CMD` 工具的配置 * **迁移**:将工具引用改为 `Shell` ### `Task` 工具移至 `multiagent` 模块 `Task` 工具从 `kimi_cli.tools.task` 移至 `kimi_cli.tools.multiagent` 模块。 * **受影响**:自定义工具中导入 `Task` 工具的代码 * **迁移**:将导入路径改为 `from kimi_cli.tools.multiagent import Task` ### `PatchFile` 工具移除 `PatchFile` 工具已移除。 * **受影响**:使用 `PatchFile` 工具的 Agent 配置 * **替代**:使用 `StrReplaceFile` 工具进行文件修改 ## 0.52 - CLI 选项变更 ### `--ui` 选项移除 `--ui` 选项已移除,改用独立的标志位。 * **受影响**:使用 `--ui print`、`--ui acp`、`--ui wire` 的脚本 * **迁移**: * `--ui print` → `--print` * `--ui acp` → `kimi acp` * `--ui wire` → `--wire` ## 0.42 - 快捷键变更 ### 模式切换快捷键 Agent/Shell 模式切换快捷键从 `Ctrl-K` 改为 `Ctrl-X`。 * **受影响**:习惯使用 `Ctrl-K` 切换模式的用户 * **迁移**:使用 `Ctrl-X` 切换模式 ## 0.27 - CLI 选项重命名 ### `--agent` 选项重命名 `--agent` 选项重命名为 `--agent-file`。 * **受影响**:使用 `--agent` 指定自定义 Agent 文件的脚本 * **迁移**:将 `--agent` 改为 `--agent-file` * **注意**:`--agent` 现在用于指定内置 Agent(如 `default`、`okabe`) ## 0.25 - 包名变更 ### 包名从 `ensoul` 改为 `kimi-cli` * **受影响**:使用 `ensoul` 包名的代码或脚本 * **迁移**: * 安装:`pip install ensoul` → `pip install kimi-cli` 或 `uv tool install kimi-cli` * 命令:`ensoul` → `kimi` ### `ENSOUL_*` 参数前缀变更 系统提示词内置参数前缀从 `ENSOUL_*` 改为 `KIMI_*`。 * **受影响**:自定义 Agent 文件中使用 `ENSOUL_*` 参数的配置 * **迁移**:将参数前缀改为 `KIMI_*`(如 `ENSOUL_NOW` → `KIMI_NOW`) --- --- url: /zh/configuration/config-files.md --- # 配置文件 Kimi Code CLI 使用配置文件管理 API 供应商、模型、服务和运行参数,支持 TOML 和 JSON 两种格式。 ## 配置文件位置 默认配置文件位于 `~/.kimi/config.toml`。首次运行时,如果配置文件不存在,Kimi Code CLI 会自动创建一个默认的配置文件。 你可以通过 `--config-file` 参数指定其他配置文件(TOML 或 JSON 格式均可): ```sh kimi --config-file /path/to/config.toml ``` 在程序化调用 Kimi Code CLI 时,也可以通过 `--config` 参数直接传入完整的配置内容: ```sh kimi --config '{"default_model": "kimi-for-coding", "providers": {...}, "models": {...}}' ``` ## 配置项 配置文件包含以下顶层配置项: | 配置项 | 类型 | 说明 | | --- | --- | --- | | `default_model` | `string` | 默认使用的模型名称,必须是 `models` 中定义的模型 | | `default_thinking` | `boolean` | 默认是否开启 Thinking 模式(默认为 `false`) | | `default_yolo` | `boolean` | 默认是否开启 YOLO(自动审批)模式(默认为 `false`) | | `skip_afk_prompt_injection` | `boolean` | 是否抑制 AFK 模式的系统提示词注入(默认为 `false`) | | `default_plan_mode` | `boolean` | 默认是否以计划模式启动新会话(默认为 `false`);恢复的会话保留其原有状态 | | `default_editor` | `string` | 默认外部编辑器命令(如 `"vim"`、`"code --wait"`),为空时自动检测 | | `theme` | `string` | 终端配色主题,可选 `"dark"` 或 `"light"`(默认为 `"dark"`) | | `show_thinking_stream` | `boolean` | 是否在 Live 区域以 6 行滚动预览方式实时展示模型的原始思考文本,并在 thinking 块结束时把完整思考内容(Markdown)写入历史记录(默认为 `true`;设为 `false` 则仅显示紧凑的 `Thinking ...` 指示器和一行 trace 总结) | | `merge_all_available_skills` | `boolean` | 是否合并所有品牌目录中的 Skills(默认为 `true`);详见 [Skills 配置](../customization/skills.md) | | `telemetry` | `boolean` | 是否启用匿名遥测以帮助改进 kimi-cli(默认为 `true`;设为 `false` 可关闭) | | `providers` | `table` | API 供应商配置 | | `models` | `table` | 模型配置 | | `loop_control` | `table` | Agent 循环控制参数 | | `background` | `table` | 后台任务运行参数 | | `services` | `table` | 外部服务配置(搜索、抓取) | | `mcp` | `table` | MCP 客户端配置 | ### 完整配置示例 ```toml default_model = "kimi-for-coding" default_thinking = false default_yolo = false skip_afk_prompt_injection = false default_plan_mode = false default_editor = "" theme = "dark" show_thinking_stream = true merge_all_available_skills = true telemetry = true [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-xxx" [models.kimi-for-coding] provider = "kimi-for-coding" model = "kimi-for-coding" max_context_size = 262144 [loop_control] max_steps_per_turn = 1000 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 agent_task_timeout_s = 900 [services.moonshot_search] base_url = "https://api.kimi.com/coding/v1/search" api_key = "sk-xxx" [services.moonshot_fetch] base_url = "https://api.kimi.com/coding/v1/fetch" api_key = "sk-xxx" [mcp.client] tool_call_timeout_ms = 60000 ``` ### `providers` `providers` 定义 API 供应商连接信息。每个供应商使用一个唯一的名称作为 key。 | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `type` | `string` | 是 | 供应商类型,详见 [平台与模型](./providers.md) | | `base_url` | `string` | 是 | API 基础 URL | | `api_key` | `string` | 是 | API 密钥 | | `env` | `table` | 否 | 创建供应商实例前设置的环境变量 | | `custom_headers` | `table` | 否 | 请求时附加的自定义 HTTP 头 | 示例: ```toml [providers.moonshot-cn] type = "kimi" base_url = "https://api.moonshot.cn/v1" api_key = "sk-xxx" custom_headers = { "X-Custom-Header" = "value" } ``` ### `models` `models` 定义可用的模型。每个模型使用一个唯一的名称作为 key。 ::: warning 注意 如果 `providers` 或 `models` 的 key 中包含 `.`,必须使用带引号的 TOML key。否则 TOML 会把 `.` 当作路径分隔符,将 key 解析为嵌套表。 ::: | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `provider` | `string` | 是 | 使用的供应商名称,必须在 `providers` 中定义 | | `model` | `string` | 是 | 模型标识符(API 中使用的模型名称) | | `max_context_size` | `integer` | 是 | 最大上下文长度(token 数) | | `capabilities` | `array` | 否 | 模型能力列表,详见 [平台与模型](./providers.md#模型能力) | | `display_name` | `string` | 否 | 模型展示名。在欢迎界面、提示框状态栏、`/model` 选单和切换确认消息中显示;未设置时回落到 `model`。对于 OAuth 登录的托管模型,启动时会从供应商的 `/models` 接口自动刷新此字段 | 示例: ```toml [models.kimi-k2-thinking-turbo] provider = "moonshot-cn" model = "kimi-k2-thinking-turbo" max_context_size = 262144 capabilities = ["thinking", "image_in"] ``` 如果模型名包含 `.`,需要使用带引号的 key: ```toml [models."gpt-4.1"] provider = "openai" model = "gpt-4.1" max_context_size = 1047576 capabilities = ["thinking"] ``` ### `loop_control` `loop_control` 控制 Agent 执行循环的行为。 | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `max_steps_per_turn` | `integer` | `1000` | 单轮最大步数(别名:`max_steps_per_run`) | | `max_retries_per_step` | `integer` | `3` | 单步最大重试次数 | | `max_ralph_iterations` | `integer` | `0` | 每个 User 消息后额外自动迭代次数;`0` 表示关闭;`-1` 表示无限 | | `reserved_context_size` | `integer` | `50000` | 预留给 LLM 响应生成的 token 数量;当 `context_tokens + reserved_context_size >= max_context_size` 时自动触发压缩 | | `compaction_trigger_ratio` | `float` | `0.85` | 触发自动压缩的上下文使用率阈值(0.5–0.99);当 `context_tokens >= max_context_size * compaction_trigger_ratio` 时自动触发压缩,与 `reserved_context_size` 条件取先触发者 | ### `background` `background` 控制后台任务的运行行为。后台任务通过 `Shell` 工具的 `run_in_background=true` 或 `Agent` 工具的 `run_in_background=true` 参数启动。 | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `max_running_tasks` | `integer` | `4` | 同时运行的最大后台任务数 | | `keep_alive_on_exit` | `boolean` | `false` | CLI 退出时是否保留后台任务运行;默认退出时终止所有后台任务 | | `kill_grace_period_ms` | `integer` | `2000` | CLI 退出发送 SIGTERM 后等待 shell worker 写入终态的宽限期(毫秒),超过后仍未退出的 worker 会被报告为残留。Agent 任务在 kill 时直接同步转为终态,不使用这个 grace period | | `agent_task_timeout_s` | `integer` | `900` | 后台 Agent 任务的最大运行时间(秒);超时后任务标记为失败并通知主 Agent | | `print_wait_ceiling_s` | `integer` | `3600` | 一次性 `--print` 模式等待后台任务完成的硬上限(秒),超时则 kill 并退出。实际等待时间为"当前活跃任务中剩余预算最长的那个",被此上限封顶 | ### `services` `services` 配置 Kimi Code CLI 使用的外部服务。 #### `moonshot_search` 配置网页搜索服务,启用后 `SearchWeb` 工具可用。 | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `base_url` | `string` | 是 | 搜索服务 API URL | | `api_key` | `string` | 是 | API 密钥 | | `custom_headers` | `table` | 否 | 请求时附加的自定义 HTTP 头 | #### `moonshot_fetch` 配置网页抓取服务,启用后 `FetchURL` 工具优先使用此服务抓取网页内容。 | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `base_url` | `string` | 是 | 抓取服务 API URL | | `api_key` | `string` | 是 | API 密钥 | | `custom_headers` | `table` | 否 | 请求时附加的自定义 HTTP 头 | ::: tip 提示 使用 `/login` 命令配置 Kimi Code 平台时,搜索和抓取服务会自动配置。 ::: ### `mcp` `mcp` 配置 MCP 客户端行为。 | 字段 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `client.tool_call_timeout_ms` | `integer` | `60000` | MCP 工具调用超时时间(毫秒) | ### `hooks` `hooks` 配置生命周期 hook(Beta 功能)。详见 [Hooks](../customization/hooks.md)。 使用 `[[hooks]]` 数组语法定义多个 hook: ```toml [[hooks]] event = "PreToolUse" matcher = "Shell" command = ".kimi/hooks/safety-check.sh" timeout = 10 [[hooks]] event = "PostToolUse" matcher = "WriteFile" command = "prettier --write" ``` | 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `event` | `string` | 是 | 事件类型,如 `PreToolUse`、`Stop` 等 | | `command` | `string` | 是 | 要执行的 shell 命令 | | `matcher` | `string` | 否 | 正则表达式过滤条件 | | `timeout` | `integer` | 否 | 超时时间(秒),默认 30 | ## JSON 配置迁移 如果 `~/.kimi/config.toml` 不存在但 `~/.kimi/config.json` 存在,Kimi Code CLI 会自动将 JSON 配置迁移到 TOML 格式,并将原文件备份为 `config.json.bak`。 `--config-file` 指定的配置文件根据扩展名自动选择解析方式。`--config` 传入的配置内容会先尝试按 JSON 解析,失败后再尝试 TOML。 --- --- url: /zh/configuration/overrides.md --- # 配置覆盖 Kimi Code CLI 的配置可以通过多种方式设置,不同来源的配置按优先级覆盖。 ## 优先级 配置的优先级从高到低为: 1. **环境变量** - 最高优先级,用于临时覆盖或 CI/CD 环境 2. **CLI 参数** - 启动时指定的参数 3. **配置文件** - `~/.kimi/config.toml` 或通过 `--config-file` 指定的文件 ## CLI 参数 ### 配置文件相关 | 参数 | 说明 | | --- | --- | | `--config ` | 直接传入配置内容,覆盖默认配置文件 | | `--config-file ` | 指定配置文件路径,替代默认的 `~/.kimi/config.toml` | `--config` 和 `--config-file` 不能同时使用。 ### 模型相关 | 参数 | 说明 | | --- | --- | | `--model, -m ` | 指定使用的模型名称 | `--model` 指定的模型必须在配置文件的 `models` 中定义。如果未指定,使用配置文件中的 `default_model`。 ### 行为相关 | 参数 | 说明 | | --- | --- | | `--thinking` | 启用 thinking 模式 | | `--no-thinking` | 禁用 thinking 模式 | | `--yolo, --yes, -y` | 自动批准所有工具调用(用户仍可回应 `AskUserQuestion`) | | `--afk` | Away-from-keyboard:自动批准所有工具调用,并自动 dismiss `AskUserQuestion` | | `--plan` | 以计划模式启动 | `--thinking` / `--no-thinking` 会覆盖上次会话保存的 thinking 状态。如果不指定,使用上次会话的状态。 `--plan` 对新会话启用计划模式;恢复已有会话时强制开启计划模式。也可以在配置文件中设置 `default_plan_mode = true` 让新会话默认进入计划模式。 ## 环境变量覆盖 环境变量可以在不修改配置文件的情况下覆盖供应商和模型设置。这在以下场景特别有用: * CI/CD 环境中注入密钥 * 临时测试不同的 API 端点 * 在多个环境间切换 环境变量根据当前使用的供应商类型来决定是否生效: * `kimi` 类型的供应商:使用 `KIMI_*` 环境变量 * `openai_legacy` 或 `openai_responses` 类型的供应商:使用 `OPENAI_*` 环境变量 * 其他类型的供应商:不支持环境变量覆盖 完整的环境变量列表请参阅 [环境变量](./env-vars.md)。 示例: ```sh KIMI_API_KEY="sk-xxx" KIMI_MODEL_NAME="kimi-k2-thinking-turbo" kimi ``` ## 配置优先级示例 假设配置文件 `~/.kimi/config.toml` 内容如下: ```toml default_model = "kimi-for-coding" [providers.kimi-for-coding] type = "kimi" base_url = "https://api.kimi.com/coding/v1" api_key = "sk-config" [models.kimi-for-coding] provider = "kimi-for-coding" model = "kimi-for-coding" max_context_size = 262144 ``` 以下是不同场景的配置来源: | 场景 | `base_url` | `api_key` | `model` | | --- | --- | --- | --- | | `kimi` | 配置文件 | 配置文件 | 配置文件 | | `KIMI_API_KEY=sk-env kimi` | 配置文件 | 环境变量 | 配置文件 | | `kimi --model other` | 配置文件 | 配置文件 | CLI 参数 | | `KIMI_MODEL_NAME=k2 kimi` | 配置文件 | 配置文件 | 环境变量 | --- --- url: /zh/reference/keyboard.md --- # 键盘快捷键 Kimi Code CLI Shell 模式支持以下键盘快捷键。 ## 快捷键列表 | 快捷键 | 功能 | |--------|------| | `Ctrl-X` | 切换 Agent/Shell 模式 | | `Shift-Tab` | 切换 Plan 模式(只读研究与规划) | | `Ctrl-O` | 在外部编辑器中编辑(`$VISUAL`/`$EDITOR`) | | `Ctrl-J` | 插入换行 | | `Alt-Enter` | 插入换行(同 `Ctrl-J`) | | `Ctrl-S` | Steer:在 streaming 期间将输入立即注入到正在运行的轮次 | | `Ctrl-V` | 粘贴(支持图片和视频文件) | | `Ctrl-E` | 展开审批请求完整内容 | | `1`–`4` | 审批面板快速选择(`4` 为附带反馈拒绝) | | `1`–`5` | 问题面板按编号选择选项 | | `Ctrl-D` | 退出 Kimi Code CLI | | `Ctrl-C` | 中断当前操作 | ## 模式切换 ### `Ctrl-X`:切换 Agent/Shell 模式 在输入框中按 `Ctrl-X` 可在两种模式间切换: * **Agent 模式**:输入发送给 AI Agent 处理 * **Shell 模式**:输入作为本地 Shell 命令执行 提示符会根据当前模式变化: * Agent 模式:`✨`(普通)或 `💫`(Thinking 模式) * Plan 模式:`📋` * Shell 模式:`$` ## Plan 模式 ### `Shift-Tab`:切换 Plan 模式 按 `Shift-Tab` 可以开启或关闭 Plan 模式。Plan 模式下 AI 只能使用只读工具探索代码库,将实施方案写入 plan 文件后提交给你审批。 开启时提示符变为 `📋`,状态栏显示蓝色的 `plan` 标识。也可以使用 `/plan` 斜杠命令管理 Plan 模式。详见 [Plan 模式](../guides/interaction.md#plan-模式)。 ## 外部编辑器 ### `Ctrl-O`:在外部编辑器中编辑 按 `Ctrl-O` 会打开外部编辑器(如 VS Code、Vim)编辑当前输入内容。编辑器按以下优先级选择: 1. `/editor` 命令配置的编辑器 2. `$VISUAL` 环境变量 3. `$EDITOR` 环境变量 4. 自动检测:`code --wait`(VS Code)→ `vim` → `vi` → `nano` 使用 `/editor` 命令可交互式切换编辑器,也可直接指定,如 `/editor vim`。 在编辑器中保存退出后,编辑后的内容会替换当前输入框内容。如果不保存退出(如 Vim 中 `:q!`),输入框内容保持不变。如果输入中包含粘贴文本占位符,编辑器会自动展开为原始文本供你编辑,保存后未修改的部分会重新折叠为占位符。 适用于编写多行 prompt、复杂代码片段等场景。 ## 多行输入 ### `Ctrl-J` / `Alt-Enter`:插入换行 默认情况下,按 `Enter` 会提交输入。如需输入多行内容,可使用: * `Ctrl-J`:在任意位置插入换行 * `Alt-Enter`:在任意位置插入换行 适用于输入多行代码片段或格式化文本。 ## 剪贴板操作 ### `Ctrl-V`:粘贴 粘贴剪贴板内容到输入框。支持: * **文本**:在 Agent 模式下,超过 1000 字符或 15 行的文本会自动折叠为 `[Pasted text #n]` 占位符,保持输入框整洁;完整内容在发送时展开传递给模型。使用 `Ctrl-O` 打开外部编辑器时,占位符会自动展开为原始文本,保存后重新折叠 * **图片**:缓存到磁盘并显示为 `[image:xxx.png,WxH]` 占位符,实际图片数据在发送时一并传递给模型(需模型支持图片输入) * **视频文件**:文件路径以文本形式插入输入框(需模型支持视频输入) ::: tip 提示 图片粘贴需要模型支持 `image_in` 能力,视频粘贴需要模型支持 `video_in` 能力。 ::: ## Streaming 期间输入 ### `Ctrl-S`:Steer(立即注入) 在 streaming 期间,按 `Ctrl-S` 提交当前输入(或弹出最早的排队消息)并立即注入到正在运行的轮次上下文中。模型会立即看到你的消息,无需等待当前轮次结束。 如果输入框为空且有排队消息,`Ctrl-S` 会弹出最早的排队消息并注入。 ### `Enter`:排队 在 streaming 期间,按 `Enter` 将消息排入队列,等当前轮次完成后再发送。排队消息数量显示在输入区标题中(如 `── input · 2 queued ──`)。在空输入框中按 `↑` 可召回最后一条排队消息进行编辑。 ## 审批请求操作 ### `Ctrl-E`:展开完整内容 当审批请求的预览内容被截断时,按 `Ctrl-E` 可以在全屏分页器中查看完整内容。预览被截断时会显示 "... (truncated, ctrl-e to expand)" 提示。 适用于查看较长的 Shell 命令或文件 Diff 内容。 ### 数字键快速选择 在审批面板中,按 `1`–`3` 可以直接选中并提交对应的审批选项,无需先用方向键选择再按 `Enter`。按 `4` 进入反馈模式,输入拒绝原因后按 Enter 提交,反馈文本会传递给 Agent 以指导下一次尝试。 ## 结构化问答操作 当 AI 使用 `AskUserQuestion` 工具向你提问时,问题面板支持以下键盘操作: | 快捷键 | 功能 | |--------|------| | `↑` / `↓` | 浏览选项 | | `←` / `→` / `Tab` | 切换问题(多问题模式) | | `1`–`5` | 按编号选择选项(单选时自动提交,多选时切换选中状态) | | `Space` | 单选模式下提交选择,多选模式下切换选中状态 | | `Enter` | 确认选择 | | `Esc` | 跳过问题 | 当 AI 一次提出多个问题时,问题面板会以标签页形式展示,使用 `←` / `→` 或 `Tab` 可在问题间切换,已回答的问题会标记为已完成状态,切换回已回答的问题时会恢复之前的选择。 ## 退出与中断 ### `Ctrl-D`:退出 在输入框为空时按 `Ctrl-D` 退出 Kimi Code CLI。 ### `Ctrl-C`:中断 * 在输入框中:清空当前输入 * Agent 运行时:中断当前操作 * 斜杠命令执行时:中断命令 ## 补全操作 在 Agent 模式下,输入时会自动显示补全菜单: | 触发 | 补全内容 | |------|---------| | `/` | 斜杠命令 | | `@` | 工作目录文件路径 | 补全操作: * 方向键选择 * `Enter` 确认选择 * `Esc` 关闭菜单 * 继续输入过滤选项 ## 状态栏 底部状态栏显示: * 当前时间 * 当前模式(agent/shell)和模型名称(Agent 模式下显示) * YOLO 标识(开启时显示黄色标识) * AFK 标识(开启时显示橙色标识) * Plan 标识(开启时显示蓝色标识) * 快捷键提示 * 上下文使用率 状态栏会自动刷新更新信息。 --- --- url: /zh/guides/integrations.md --- # 集成到工具 除了在终端和 IDE 中使用,Kimi Code CLI 还可以集成到其他工具中。 ## Zsh 插件 [zsh-kimi-cli](https://github.com/MoonshotAI/zsh-kimi-cli) 是一个 Zsh 插件,让你可以在 Zsh 中快速切换到 Kimi Code CLI。 **安装** 如果你使用 Oh My Zsh,可以这样安装: ```sh git clone https://github.com/MoonshotAI/zsh-kimi-cli.git \ ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/kimi-cli ``` 然后在 `~/.zshrc` 中添加插件: ```sh plugins=(... kimi-cli) ``` 重新加载 Zsh 配置: ```sh source ~/.zshrc ``` **使用** 安装后,在 Zsh 中按 `Ctrl-X` 可以快速切换到 Kimi Code CLI,无需手动输入 `kimi` 命令。 ::: tip 提示 如果你使用其他 Zsh 插件管理器(如 zinit、zplug 等),请参考 [zsh-kimi-cli 仓库](https://github.com/MoonshotAI/zsh-kimi-cli) 的 README 了解安装方法。 :::