> ## Documentation Index
> Fetch the complete documentation index at: https://platform.kimi.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Manage Hosted Agents with kha CLI

> Create and configure agents, manage sessions, run tasks, and download artifacts in natural language from an AI coding assistant.

Alongside the Console and REST API, `kha` is the command-line interface for Kimi Hosted Agents, providing the same resource management and session operations. Once installed, you can use natural language in AI coding assistants such as [Kimi Code](https://platform.kimi.ai/docs/guide/kimi-code-cli.md), Claude Code, and Codex to create and configure agents and execution environments, and to create sessions. You can also submit and continue tasks, inspect run status, and download artifacts.

## Installation and authentication

Before you begin, prepare an API key with access to Hosted Agents.

### Install kha CLI

Run the one-line installer in your terminal:

> [tab] macOS / Linux
>
> ```bash theme={null}
> curl -fsSL https://ha-static.moonshot.cn/kha/install.sh | sh
> export PATH="$HOME/.local/bin:$PATH"
> ```
>
> The script detects your OS and CPU architecture automatically, verifies the SHA-256 checksum, and installs to `~/.local/bin` by default. Set `KHA_INSTALL_DIR` to customize the directory, or set `KHA_VERSION=0.X.Y` to install a specific version (defaults to the latest stable release).

> [tab] Windows (PowerShell)
>
> ```powershell theme={null}
> $installer = Join-Path ([IO.Path]::GetTempPath()) 'kha-install.ps1'
> Invoke-WebRequest https://ha-static.moonshot.cn/kha/install.ps1 -UseBasicParsing -OutFile $installer
> & $installer
> $env:Path = "$(Join-Path $env:LOCALAPPDATA 'kha\bin');$env:Path"
> ```
>
> Installs to `%LOCALAPPDATA%\kha\bin` by default. Pass `-InstallDir` to customize the directory, or `-Version 0.X.Y` to install a specific version (defaults to the latest stable release).

The installer downloads from `ha-static.moonshot.cn`, which serves all regions. To download from GitHub Releases instead, set `KHA_RELEASE_BASE_URL=https://github.com/MoonshotAI/kha/releases/download` and pass an explicit version (`KHA_VERSION=0.X.Y` on macOS/Linux, or `-Version 0.X.Y` on Windows).

Verify the installation:

```bash theme={null}
kha version
```

If you want your AI coding assistant to install the CLI for you, send it this prompt:

```text wrap theme={null}
Download and run the kha CLI installer from https://ha-static.moonshot.cn/kha/install.sh (on Windows, use install.ps1 in the same directory).
After verifying that kha version works, run kha install-skill -g to install the kha skill package into the user-level skills directory, then report the CLI version and skill installation path.
```

### Install the kha skill package

When using `kha` inside an AI coding assistant, install the companion kha skill package so the assistant invokes the CLI following built-in best practices. The skill package ships with the CLI binary—no network download is needed:

```bash theme={null}
kha install-skill      # Project-level: ./.agents/skills/kha/
kha install-skill -g   # User-level: ~/.agents/skills/kha/
```

Pass `--dir` to install into a custom directory. Once installed, reload skills or open a new session in your coding assistant to confirm the skill is active. If you prefer running CLI commands directly without an assistant, see [Check CLI command usage](#check-cli-command-usage).

### Upgrade kha CLI

The CLI checks for updates once per day and prints a notice to `stderr` when a newer version is available, without affecting command output on `stdout`. Set `KHA_NO_UPDATE_CHECK=1` to disable update checks (skipped automatically in CI environments). To upgrade manually:

```bash theme={null}
kha upgrade                  # Upgrade to the latest stable release
```

Upgrading downloads and verifies the new binary, replaces the executable in place, and refreshes any installed copies of the skill package automatically.

### Configure authentication

Create an API key on [Kimi API Platform](https://platform.kimi.ai/console/api-keys), then run the following command in your local terminal:

```bash theme={null}
kha login --base-url https://api.moonshot.ai
```

Pass `--base-url https://api.moonshot.ai` to connect to the Global API endpoint; without it (or `KHA_BASE_URL`), the CLI defaults to the CN endpoint. Paste your API key at the hidden prompt and press Enter. In scripts or non-interactive environments, run `kha login --base-url https://api.moonshot.ai --api-key-stdin` to read the key from standard input instead.

Always enter your API key directly in a local terminal—never pass it as a command-line argument or paste it into an AI coding assistant chat.

`login` only saves credentials locally; run `whoami` to call the API and verify your identity:

```bash theme={null}
kha whoami
```

If `KIMI_API_KEY` is already set in your terminal environment, the CLI can also use it directly—set `KHA_BASE_URL=https://api.moonshot.ai` alongside it so requests go to the Global endpoint. To manage multiple accounts or environments, store separate configurations in named profiles:

```bash theme={null}
kha login --base-url https://api.moonshot.ai --profile work
kha whoami --profile work
```

## Complete your first task in natural language

Send the following prompt in your AI coding assistant:

```text wrap theme={null}
Use the kha CLI to select or create a suitable agent and execution environment for the sales data below.
Once the execution environment is ready, create a session to calculate monthly sales by product category and save the report as an artifact named sales-report.md.
After the task finishes, download the report and share the key takeaways along with the session ID.

January 2026: Product A $12,000, Product B $8,000;
February 2026: Product A $15,000, Product B $10,000;
March 2026: Product A $18,000, Product B $12,000.
```

Your AI coding assistant uses the kha CLI to carry out these steps:

1. Inspect existing agents and execution environments, creating new ones only if none fit the task.
2. Wait until the execution environment status reaches `ready`.
3. Create a session and send the sales data and aggregation instructions.
4. Check the agent's response and artifacts to confirm the output is complete.
5. Download `sales-report.md` and return the key takeaways, session ID, and local file path.

## Common management workflows

You can use the example prompts below directly in your AI coding assistant—replace resource names, IDs, and file paths with your own values.

| Scenario | Example natural-language prompt | Related docs |
| - | - | - |
| Update an agent | "Read the current agent configuration, update the system prompt while keeping all other settings intact, and create a new session to verify it." | [Create and Manage Agents](https://platform.kimi.ai/docs/hosted-agents/agents.md) |
| Attach skills or plugins | "Upload this skill package and attach it to the specified agent while preserving its existing skills and plugins." | [Skills](https://platform.kimi.ai/docs/hosted-agents/skills.md), [Plugins](https://platform.kimi.ai/docs/hosted-agents/plugins.md) |
| Multi-agent collaboration | "Create a coordinator agent and three subagents so the coordinator can delegate subtasks to them in parallel and summarize the results." | [Multi-Agent Orchestration](https://platform.kimi.ai/docs/hosted-agents/multiagent-orchestration.md) |
| Connect external services | "Configure a vault for tasks that access GitHub and tell me where to complete authorization." | [Vaults](https://platform.kimi.ai/docs/hosted-agents/vaults.md), [Configure MCP Servers](https://platform.kimi.ai/docs/hosted-agents/mcp.md) |
| Use GitHub repositories | "Mount this GitHub repository when creating a session, read the code, and run tests; if it is a private repository, read the token from standard input." | [GitHub Repositories](https://platform.kimi.ai/docs/hosted-agents/github.md) |
| Cross-session memory | "Create a project memory store and mount it read-only in a new session." | [Memory](https://platform.kimi.ai/docs/hosted-agents/memory.md) |
| Scheduled runs | "Create a trigger that runs every weekday at 09:00, and trigger one manual run to verify the output." | [Run Agents with Triggers](https://platform.kimi.ai/docs/hosted-agents/triggers.md) |
| Files and artifacts | "Upload this file, attach it to the existing session, and download the generated artifact once the task completes." | [Files](https://platform.kimi.ai/docs/hosted-agents/files.md) |
| Debug a failed run | "Fetch the full event log for this session and analyze `agent.thinking`, `agent.tool_use`, and `agent.tool_result` to identify why it failed." | [Event Stream](https://platform.kimi.ai/docs/hosted-agents/event-stream.md) |

Vaults, memory stores, and GitHub repositories must be bound when creating a session. After updating an agent, create a new session to verify the change—existing sessions continue using the agent version pinned at creation. When a trigger reports that its initial event was accepted, inspect the corresponding session's responses and artifacts to verify completion.

## Work across the Console and API

Agents, sessions, and artifacts created with the kha CLI remain fully accessible in both the Console and the REST API. You can continue issuing natural-language instructions in your AI coding assistant, open the session in the [Console](https://platform.kimi.ai/docs/hosted-agents/console.md), or call the [API](https://platform.kimi.ai/docs/api-reference/sessions/send-events-to-a-session.md) to send follow-up messages, inspect events, or cancel the current turn.

The Console works well for visual configuration, OAuth authorization, run observability, and artifact inspection, while the API is well suited for integrating follow-up operations into your own applications. You can send the initial task message directly through the kha CLI without opening the Console.

## Troubleshooting

| Issue | What to check and do |
| - | - |
| AI coding assistant does not recognize the kha skill | Check the installation scope, the `kha/SKILL.md` path, and the full `references/` directory, then reload skills or start a new chat session in your client |
| `kha` command not found | Confirm the CLI is installed, verify the install directory is on your `PATH`, and test with `kha version` |
| Authentication fails or requests return `401` / `403` | Run `kha whoami` with the same profile and endpoint to check whether your API key is valid and has Hosted Agents access |
| Session creation reports environment not ready | Wait until the execution environment reaches `ready` status and retry with the same configuration instead of creating duplicate environments |
| Waiting locally times out with no result | Query the session's current status and recent events—a local CLI timeout does not stop cloud execution |
| Follow-up input does not run immediately | New inputs are queued while a session is `running`; check whether queued inputs are still pending |
| Agent behavior does not change after an update | Start a new session to test—existing sessions continue using the agent version pinned at creation |

## Check CLI command usage

You can also run the kha CLI directly without an AI coding assistant. View the full command reference matching your installed CLI version:

```bash theme={null}
kha docs
```

To inspect flags and usage for a specific subcommand, drill down with `kha docs <resource> <command>`.

## Request body input

When creating or updating resources directly with the CLI, you can pass request parameters in two ways:

* **Field flags**: Pass top-level scalar fields as command options, such as `kha sessions create --agent "$AGENT_ID" --environment "$ENVIRONMENT_ID" --title "Weekly report"`.
* **Full request body**: Pass nested structures (such as `resources`, `tools`, `mcp_servers`, or `metadata`) as a single payload via `--file` in **JSON or YAML** format; `--file -` reads from standard input.

The two modes cannot be combined—do not pass field flags alongside `--file`. Because request body fields match the REST API contract directly, you can pass any JSON body from cURL examples in these docs straight to `--file`, or write the equivalent payload in YAML:

```bash theme={null}
kha sessions create --file - <<'YAML'
agent_id: agent_...
environment_id: env_...
title: Weekly report
resources:
  - type: file
    file_id: file_...
YAML
```

For single-field text such as message content, use options like `--text-file`, `--payload-file`, and `--content-file` to read the text verbatim without structured parsing.

## Next steps

> [card] [Manage running sessions](https://platform.kimi.ai/docs/hosted-agents/session-operations.md)
>
> Inspect session status, check queued inputs, and cancel the current turn.

> [card] [Continue in the Console](https://platform.kimi.ai/docs/hosted-agents/console.md)
>
> Configure resources, observe runs, and inspect artifacts in your browser.
