Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

kimi: the base runs Kimi Code CLI itself (MoonshotAI/kimi-code 2.0.0) (#206)

github-actions[bot]236cd6721bd9
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index d4a63203..6872d52f 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -240,54 +240,56 @@ install_opencode() {
# download has to go unverified: the digests are pinned HERE instead, computed from the v1.50.0
# release assets (each archive holds exactly ./goose). That is strictly stronger than the tag
# alone, which can be moved and whose asset can be re-uploaded.
-# Kimi CLI, Apache-2.0 (MoonshotAI/kimi-cli), pinned to 1.50.0.
+# Kimi Code CLI, MIT (MoonshotAI/kimi-code), pinned to 2.0.0.
#
-# THE STANDALONE BINARY, NOT PyPI, and the reason is this image. `pip install kimi-cli` pins
-# pydantic==2.12.5, aiohttp==3.13.3, httpx==0.28.1, fastmcp==3.2.4, fastapi and uvicorn — the same
-# packages the runner itself is a FastAPI app on — so it would need its own venv (the dsh/hermes
-# precedent) at 314 MB and ~50 s. The release binary is ~93 MB, carries no Python-version
-# constraint at all, and cannot collide with the runner's interpreter.
+# THIS IS THE SUCCESSOR, NOT Kimi CLI. 0.18.0 shipped MoonshotAI/kimi-cli 1.50.0, the Python
+# predecessor whose own README says it "is evolving into Kimi Code CLI"; the product is the
+# TypeScript rewrite in MoonshotAI/kimi-code, a single binary that is also called `kimi`. The pin
+# below is compared against `kimi --version` on every start, so a volume that still holds the old
+# binary ("kimi, version 1.50.0") is upgraded in place rather than left running the wrong product.
#
-# Upstream DOES publish a per-asset .sha256 beside each archive, so unlike goose there is an
-# upstream checksum to cite. The digests are still pinned HERE rather than fetched: a checksum
-# served from the same origin as the artifact adds nothing against a compromised origin, while a
-# digest pinned in this file fails closed if the tag is moved or the asset re-uploaded. The values
-# below were read from the 1.50.0 assets and agree with upstream's own .sha256 files.
+# The release archive, not the install script and not npm: the script pipes a moving target into a
+# shell, while an asset under a tag can be pinned. Upstream publishes a per-asset .sha256 beside
+# each archive; the digests are still pinned HERE rather than fetched, because a checksum served
+# from the same origin as the artifact adds nothing against a compromised origin, while a digest
+# in this file fails closed if the tag is moved or the asset re-uploaded. The values below were
+# read from the 2.0.0 assets and agree with upstream's own .sha256 files. The release tag is
+# "@moonshot-ai/kimi-code@<version>", which has to be percent-encoded in the download URL.
#
-# Everything runner/server.py's kimi code was written against — the stream-json line shapes, the
-# openai_legacy env override, exclude_tools matching PATHS, the sessions/<md5(cwd)>/<id> layout,
-# and the 75/1 provider-failure exit codes — was read out of THIS version.
+# Everything runner/server.py's kimi code relies on (the stream-json line shapes, the model defined
+# from KIMI_MODEL_* alone, -r refusing an unknown session, agent files matching tool NAMES,
+# $KIMI_CODE_HOME/mcp.json, the exit-1 failure line) was measured on THIS version.
+KIMI_PIN="${HR_KIMI_VERSION:-2.0.0}"; KIMI_PIN="${KIMI_PIN#v}"
install_kimi() {
case "$(uname -m)" in
- x86_64) km_arch="x86_64"; km_sha="10ccaa26ee7f5bb43f7c05baf808c11cd0160710b07ac422382d1d1923f3dab6" ;;
- aarch64|arm64) km_arch="aarch64"; km_sha="de235322f48abe63e7a8d737f39f0c00fecf724f1dfaa1ae02491bb773ae8070" ;;
+ x86_64) km_arch="x64"; km_sha="ebc1ad504e458d66f0cc57d4e9d709a2060647f5b89d4e21026903b96204c3ed" ;;
+ aarch64|arm64) km_arch="arm64"; km_sha="870fdb2fc45622fed92753bc4995ff80ba02e15a6304b396b5a70df1c7a23174" ;;
*) echo "unsupported architecture $(uname -m) for kimi"; return 1 ;;
esac
- km_ver="${HR_KIMI_VERSION:-1.50.0}"; km_ver="${km_ver#v}"
- if [ "$km_ver" != "1.50.0" ]; then
+ if [ "$KIMI_PIN" != "2.0.0" ]; then
# Same contract as goose's: an operator who overrides the version supplies the digest for the
# version they chose, or is TOLD the archive is unverified. Read as ${VAR:-} because this
# script runs under `set -euo pipefail`.
if [ -n "${HR_KIMI_SHA256:-}" ]; then
km_sha="$HR_KIMI_SHA256"
else
- echo "[harnessrouter] WARN: HR_KIMI_VERSION=$km_ver overrides the pinned 1.50.0, and no"
+ echo "[harnessrouter] WARN: HR_KIMI_VERSION=$KIMI_PIN overrides the pinned 2.0.0, and no"
echo "[harnessrouter] HR_KIMI_SHA256 was given — this kimi archive is UNVERIFIED."
km_sha=""
fi
fi
- km_url="https://github.com/MoonshotAI/kimi-cli/releases/download/${km_ver}/kimi-${km_ver}-${km_arch}-unknown-linux-gnu.tar.gz"
+ km_url="https://github.com/MoonshotAI/kimi-code/releases/download/%40moonshot-ai%2Fkimi-code%40${KIMI_PIN}/kimi-code-linux-${km_arch}.tar.gz"
km_tmp="$(mktemp -d)"
curl -fsSL "$km_url" -o "$km_tmp/kimi.tar.gz" || { rm -rf "$km_tmp"; return 1; }
if [ -n "$km_sha" ]; then
km_have="$(sha256sum "$km_tmp/kimi.tar.gz" | awk '{print $1}')"
if [ "$km_sha" != "$km_have" ]; then
- echo "kimi $km_ver: archive digest mismatch for $km_arch (want $km_sha, have $km_have)"
+ echo "kimi $KIMI_PIN: archive digest mismatch for $km_arch (want $km_sha, have $km_have)"
rm -rf "$km_tmp"; return 1
fi
fi
- tar -xzf "$km_tmp/kimi.tar.gz" -C "$km_tmp" || { rm -rf "$km_tmp"; return 1; }
- km_bin="$(find "$km_tmp" -type f -name kimi -perm -u+x | head -n 1)"
+ mkdir "$km_tmp/x" && tar -xzf "$km_tmp/kimi.tar.gz" -C "$km_tmp/x" || { rm -rf "$km_tmp"; return 1; }
+ km_bin="$(find "$km_tmp/x" -type f -name kimi -perm -u+x | head -n 1)"
[ -n "$km_bin" ] || { echo "release archive contained no kimi binary"; rm -rf "$km_tmp"; return 1; }
mkdir -p "$TOOLS/bin" && install -m 755 "$km_bin" "$TOOLS/bin/kimi" \
|| { rm -rf "$km_tmp"; return 1; }
@@ -441,9 +443,12 @@ install_backends() {
try_install "goose" install_goose || true
fi
- if wanted kimi && [ ! -x "$(backend_bin kimi)" ]; then
- echo "[harnessrouter] installing Kimi CLI (Apache-2.0)…"
- try_install "Kimi CLI" install_kimi || true
+ # `kimi --version` prints the bare version on Kimi Code CLI ("2.0.0") and "kimi, version 1.50.0" on
+ # its predecessor, so comparing it to the pin both installs a missing binary and replaces the old
+ # product on a volume that was first started by 0.18.0.
+ if wanted kimi && [ "$("$(backend_bin kimi)" --version 2>/dev/null | head -n 1)" != "$KIMI_PIN" ]; then
+ echo "[harnessrouter] installing Kimi Code CLI $KIMI_PIN (MIT, version-pinned)…"
+ try_install "Kimi Code CLI" install_kimi || true
fi
# The dsh venv lives on the data volume, so a pin bump in the image must reach a volume that
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index af9e3f04..cae24a3a 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -333,16 +333,16 @@ problem, because it only offers you providers that work.
| Connection `provider` | Backends that can use it |
|---|---|
-| `anthropic` | Claude Code, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi CLI |
+| `anthropic` | Claude Code, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, Kimi Code CLI |
| `bedrock` | Claude Code, Hermes |
-| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi CLI |
-| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
-| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi CLI |
+| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
+| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose, Kimi Code CLI |
</details>
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index 9da882ee..c6ad256b 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -313,7 +313,84 @@ re-run once.
on opencode because the same pair passes on Vercel; the miss is recorded. OpenRouter's no-channel set
is empty.
-## The kimi backend (Kimi CLI 1.50.0) — behaviour measured, columns NOT yet run
+## The kimi backend: Kimi Code CLI 2.0.0 (2026-09-17)
+
+0.18.0 wired this base to MoonshotAI/kimi-cli 1.50.0. That is the predecessor: its own README opens
+with "Kimi CLI is evolving into Kimi Code CLI", and the product, the one kimi.ai/code points at, is
+the TypeScript rewrite in MoonshotAI/kimi-code. The base now runs the product itself. Everything
+below was measured on the 2.0.0 binary, first on the test VM host and then through the product on a
+candidate image; the section after this one is the predecessor's record and no longer describes what
+the base runs.
+
+**The surface, as measured.**
+
+- Headless is `kimi -p <prompt> --output-format stream-json`, one JSON message per line: a version
+ line, assistant text (`content` a string), assistant tool calls (no `content` key, `arguments` a JSON
+ string), tool results, and LAST a `session.resume_hint` line, the only place the session id appears.
+ No usage and no result event: usage is the relay's, the process exiting ends the turn.
+- The model is defined from the environment alone (`KIMI_MODEL_NAME` and its family): a provider
+ synthesised in memory, no config file, no key at rest. After a full session the data home
+ (`KIMI_CODE_HOME`, under the workspace so a resume survives a recycle) held no trace of the key.
+ Telemetry and the self-update preflight are switched off by environment.
+- Resume is `-r <id>`. An id the store does not hold is a hard failure, exit 1 with `Session "<id>"
+ not found`, where the predecessor silently started over; the builder asks the store first and a lost
+ conversation is reported through the resume-lost note instead of failing the turn.
+- Failures are exit 1 and one stderr line, `error: failed to run prompt: <class>: <reason>`
+ (`provider.auth_error: 401 …`, `loop.max_steps_exceeded: …`), followed by a `See log: <path>` note
+ that is trimmed from the reason. The step budget is `KIMI_LOOP_MAX_STEPS_PER_TURN`; unset is unlimited.
+- Tool policy is an agent file (Markdown) whose `disallowedTools` match by exact NAME and are enforced
+ again before execution. The 26 names are the `tools` array of a live request captured at a stub.
+ The agent is bound when the session is created, so a policy change reaches the next conversation,
+ not the open one.
+- MCP is `$KIMI_CODE_HOME/mcp.json`: a `command` entry is stdio (args, env, cwd honoured), a `url` is
+ streamable HTTP, and a legacy server says `transport: "sse"` explicitly. Tools are named
+ `mcp__<server>__<tool>`. Skills come from `--skills-dir`; AGENTS.md is honoured.
+
+**Two things the product run found, both fixed before merge.**
+
+- With only Bash disallowed, kimi-k3 said it had no shell of its own "but I can dispatch a subagent
+ that does", and did: a built-in subagent carries its own tool list. The agent file now empties the
+ subagent allowlist whenever a tool is withheld; the same prompt then calls nothing and says it has
+ no shell.
+- An MCP server that cannot be reached is skipped in SILENCE: no stream line, nothing on stderr,
+ exit 0, where the predecessor failed the turn. The only trace is one line in the CLI's log. The
+ runner reads this turn's lines and the reply now ends with a note naming the server.
+
+**Measured through the product** on the candidate image (hr-test, 2026-09-17): a volume first started
+by 0.18.0 was upgraded from the old binary in place (`kimi, version 1.50.0` to `2.0.0`, digest
+checked); first turn, a follow-up that remembered, an artifact; a person's own skill with its script
+plus an MCP tool in ONE round, twice in one session (`Skill`, `Bash`, `mcp__probe__probe_http`), the
+script's value one that can only come from running it; the four plugin columns (skill, stdio, SSE,
+streamable HTTP).
+
+**Every id on the five console scenarios, through a real browser** (first turn, follow-up, switch to
+another model and back, an artifact checked on the file cards, a recycle that must recall the first
+message after the sandbox is let go): 50 ids across six connections (TokenRouter 38, Vercel 6,
+Anthropic 2, a custom OpenAI endpoint 2, Azure OpenAI 1, OpenRouter 1), **248 of 250**, taking the
+latest run of each id. The first full pass was 217 of 250, and all but two of its misses were one
+cause with two faces:
+
+- **The CLI sends request fields nobody configured**, captured at a stub across ten model families:
+ `max_tokens: 131072` on every request (as `max_completion_tokens` for a gpt or o name), an output
+ budget sized for a Kimi window, and `reasoning_effort: "high"` whenever the model NAME looks like a
+ reasoning model. OpenAI, Anthropic and Google refuse the first outright, each naming its limit
+ ("supports at most 128000 completion tokens", "131072 > 128000", "range is from 1 to 65537
+ (exclusive)"); on llama-3.3-70b the budget alone overflows the 131k window ("requested about
+ 154972 tokens ... 131072 in the output"); TokenRouter turns the second into `thinking.type.enabled`,
+ which claude-fable-5-1, claude-fable-5, claude-opus-4.8, claude-opus-4.7 and claude-sonnet-5 refuse
+ ("Use thinking.type.adaptive"). The relay route this base registers is born dropping all three, so
+ the provider's defaults apply as on every other base. `prompt_cache_key`, the one other extra,
+ is harmless and stays. The CLI also retries a failing step ten times, a flat 400 included (143 to
+ 178 s to surface a refusal); the base sets three attempts.
+- **claude-opus-5, artifact and recycle, three runs of three:** "Provider safety policy blocked the
+ response". Isolated through the API: the scenario's own words trip it. After the switch turn has
+ gpt-5.6-sol answer `M3-gpt-5.6-sol`, the next claude-opus-5 turn is blocked; the same shape with
+ neutral words (a text turn, a switch turn answering `SW-1`, then the file) passes every time, as
+ does the artifact prompt on a fresh session. It is the provider's policy meeting the test's
+ vocabulary, not the wiring, and the id stays listed.
+
+
+## The kimi backend's first wiring: Kimi CLI 1.50.0, the predecessor (superseded, kept as the record) — behaviour measured, columns NOT yet run
No column has run for this harness. Everything below was measured against the pinned 1.50.0
artifact — its source, its bytes on the wire, and two live turns through Vercel — and none of it is
diff --git a/gateway/app.py b/gateway/app.py
index e5edbaa2..3544c0e0 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -5097,6 +5097,16 @@ def _blocks_from_canonical(ev: dict) -> list[tuple[str, object]]:
# learn the context was dropped, so it is a short, honest note at the top of the reply.
out.append(("text", "_Note: the earlier conversation could not be restored. This reply "
"continues as a new session, without that context._\n\n"))
+ elif t == "system" and ev.get("subtype") == "mcp_unavailable":
+ # A CLI that runs the turn without an MCP server it could not reach, and says nothing (Kimi
+ # Code CLI does exactly that), leaves a person wondering why the agent never used their
+ # tool. The runner reads the CLI's own record of it; this is the sentence that tells them.
+ names = [str(s.get("name") or "") for s in ev.get("servers") or [] if isinstance(s, dict) and s.get("name")]
+ if names:
+ quoted = ", ".join(f'"{n}"' for n in names)
+ word = "server" if len(names) == 1 else "servers"
+ out.append(("text", f"\n\n_Note: the MCP {word} {quoted} could not be reached, so this "
+ "reply ran without those tools._\n"))
return out
@@ -6015,28 +6025,18 @@ _MODEL_CATALOG: dict[str, dict] = {
# its text turns answer but its first tool turn is refused on every channel (TokenRouter
# "404 This model is not supported in the v1/chat/completions endpoint", Azure "400 The
# requested operation is unsupported"). Same rule cline earned for it on 2026-08-30.
- # kimi: the same relay reach as qwen and cline (OpenAI chat/completions through the loopback
- # relay), so the list is qwen's, reordered to put the kimi family first as its home family.
+ # kimi (Kimi Code CLI): the same relay reach as qwen and cline (OpenAI chat/completions through the
+ # loopback relay), so the list is qwen's, reordered to put the kimi family first as its home family.
#
- # MEASURED, two columns, 2026-09-16, against a candidate built from this branch:
- # Vercel 46 ids x 5 scenarios -> 229/230 passed, no foreign connection
- # Google 11 ids x 5 scenarios -> 53/55 passed, no foreign connection
- # Google serves only its own family, which is why its column is eleven ids and not forty-six.
+ # MEASURED on Kimi Code CLI 2.0.0, 2026-09-17, against a candidate built from the rewiring branch:
+ # every id below on the five console scenarios through a real browser, across six connections
+ # (TokenRouter 38, Vercel 6, Anthropic 2, a custom OpenAI endpoint 2, Azure OpenAI 1, OpenRouter 1):
+ # 248 of 250. The two misses are claude-opus-5's artifact and recycle turns, the provider's safety
+ # policy meeting the scenario's own words (neutral words pass); see docs/support-matrix-notes.md,
+ # which also records the three request fields this CLI invents and the route drops.
#
- # THE SEVEN IDS NEITHER COLUMN RAN, and why: Vercel does not serve claude-fable-5-1,
- # gemini-3-flash-preview, grok-4.20, hunyuan-4-preview or nemotron-3-super, and this
- # deployment's model map had no entry for gemini-3.6-flash or llama-3.3-70b. They stay listed
- # because other providers serve them; they are unmeasured HERE, which is not the same as refused.
- #
- # THE ONE FINDING, and it needed both columns to read correctly: a gemini-2.5-class model
- # returns "The API returned an empty response" on the artifact turn — the one that follows a
- # model switch and asks for a file. On Vercel that is gemini-2.5-flash-lite (three runs, two
- # builds) while gemini-2.5-flash passes; on Google it is exactly the other way round. So it
- # belongs to neither the channel nor one id. See docs/support-matrix-notes.md.
- #
- # kimi does not rewrite the id it is given: the value reaches the provider verbatim (captured at
- # a stub and against both live gateways), and its only alias machinery raises KeyError on a miss
- # rather than substituting — the gemini resolveModel class of silent substitution is absent.
+ # The id reaches the provider verbatim: KIMI_MODEL_NAME is sent as `model` unchanged (captured at
+ # a stub), so the gemini resolveModel class of silent substitution is absent.
"kimi": {"default": "kimi-k3",
"models": [
"gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-5.4",
@@ -6182,9 +6182,9 @@ for _b, _e in _MODEL_CATALOG.items():
# an omission: the support matrix lists these pairs as not run for that reason, and the chat-only
# test forbids listing such an id for such a harness.
RESPONSES_ONLY_MODELS = frozenset({"gpt-5.3-codex", "gpt-6-astra"})
-# kimi speaks chat/completions only: its provider type is openai_legacy (openai_responses
-# exists in the CLI but is not the type the runner writes), so a Responses-API-only id would be
-# a picker row that fails on send.
+# kimi speaks chat/completions only: the runner defines its model with provider type `openai`
+# through the relay (Kimi Code CLI has an openai_responses type too, but it is not the one the runner
+# sets), so a Responses-API-only id would be a picker row that fails on send.
CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose", "kimi")
_BARE_MODELS = {"", "claude", "codex", "anthropic", "bedrock", "openai", "hermes", "pi", "dsh", "deepseek", "omp"}
# Models whose serving CHANNEL refuses image input outright. Measured, not assumed — probed
@@ -13294,29 +13294,32 @@ _BASE_CATALOG: dict[str, dict] = {
"tool_enforcement": "hard",
},
"kimi": {
- "label": "Kimi CLI", "backend": "kimi", "status": "ready",
- "system_prompt": ("You are Kimi CLI, an autonomous coding agent. You work on a real git "
+ "label": "Kimi Code CLI", "backend": "kimi", "status": "ready",
+ "system_prompt": ("You are Kimi Code CLI, an autonomous coding agent. You work on a real git "
"workspace with shell and file access, reading and editing files and "
"running commands to complete the task end to end."),
- # Measured from the `tools` array a live run SENT ITS PROVIDER, captured at a local stub —
- # these are the names the model actually sees, not doc-sourced ones.
- #
- # SearchWeb and ReadMediaFile are in the shipped default agent and are deliberately NOT
- # listed: each raises SkipThisTool unless a Moonshot search key / a vision-capable model is
- # configured, so neither is ever constructed here, and listing one would be the "tool id
- # that matches nothing" this catalog's own rules forbid.
- "tools": [("Shell", "Shell"), ("ReadFile", "File Read"), ("WriteFile", "File Write"),
- ("StrReplaceFile", "Edit"), ("Grep", "Search"), ("Glob", "Glob"),
- ("FetchURL", "Web Fetch"), ("SetTodoList", "Todo"), ("Agent", "Subagent"),
+ # Measured from the `tools` array a live Kimi Code CLI 2.0.0 run SENT ITS PROVIDER, captured at
+ # a local stub: these are the names the model actually sees, not doc-sourced ones. WebSearch
+ # is absent on purpose: it is declared only with a Moonshot search service configured, and
+ # listing it would be the "tool id that matches nothing" this catalog's own rules forbid.
+ "tools": [("Bash", "Shell"), ("Read", "File Read"), ("Write", "File Write"), ("Edit", "Edit"),
+ ("Grep", "Search"), ("Glob", "Glob"), ("FetchURL", "Web Fetch"),
+ ("ReadMediaFile", "Media Read"), ("TodoList", "Todo"), ("Skill", "Skill"),
+ ("Agent", "Subagent"), ("AgentSwarm", "Subagent Swarm"),
("AskUserQuestion", "Question"), ("TaskList", "Background Tasks"),
- ("TaskOutput", "Task Output"), ("TaskStop", "Task Stop"),
- ("EnterPlanMode", "Enter Plan"), ("ExitPlanMode", "Exit Plan")],
- # "hard", and earned: a --agent-file with `extend: default` + `exclude_tools` means the tool
- # is never constructed and never declared to the model. Verified live — an excluded tool was
- # absent from the captured tools array. The enforcement depends entirely on
- # runner/server.py's _KIMI_TOOL_PATHS, because kimi matches tool PATHS and a bare NAME is a
- # silent no-op; test_catalog_kimi_tool_paths.py pins these ids equal to that table's keys so
- # this claim cannot drift into an overstatement.
+ ("TaskOutput", "Task Output"), ("TaskStop", "Task Stop"), ("WaitFor", "Wait"),
+ ("EnterPlanMode", "Enter Plan"), ("ExitPlanMode", "Exit Plan"),
+ ("CreateGoal", "Create Goal"), ("GetGoal", "Get Goal"), ("UpdateGoal", "Update Goal"),
+ ("SetGoalBudget", "Goal Budget"), ("CronCreate", "Schedule Create"),
+ ("CronList", "Schedule List"), ("CronDelete", "Schedule Delete")],
+ # "hard", and earned: an agent file's `disallowedTools` shapes the tools shown to the model
+ # AND is enforced again before execution (the CLI's agents reference). Verified live on
+ # 2.0.0: with Bash disallowed and asked for the machine's boot id, the agent called no tool
+ # and said it had no shell. The file also empties the subagent allowlist, because a built-in
+ # subagent carries its own tools and handed the withheld one back by delegation (measured
+ # through the product). It matches by exact tool NAME and a name it does not know
+ # matches nothing, so test_catalog_kimi_tool_paths.py pins these ids equal to the runner's
+ # _KIMI_TOOLS tuple and the claim cannot drift into an overstatement.
"tool_enforcement": "hard",
},
"qwen": {
diff --git a/gateway/tests/test_catalog_kimi_tool_paths.py b/gateway/tests/test_catalog_kimi_tool_paths.py
index 9b016679..bf17dde7 100644
--- a/gateway/tests/test_catalog_kimi_tool_paths.py
+++ b/gateway/tests/test_catalog_kimi_tool_paths.py
@@ -1,14 +1,13 @@
-"""kimi's "hard" tool enforcement is only real while the catalog and the path table agree.
-
-kimi matches `exclude_tools` on tool PATHS (`kimi_cli.tools.shell:Shell`), not on the tool NAMES the
-model sees. Measured on 1.50.0: excluding the bare name "Shell" is a SILENT no-op — the tool stays
-in the array sent to the provider — while excluding the path removes it. So a catalog id with no
-row in runner/server.py's _KIMI_TOOL_PATHS would be offered as a toggle in the console, reported as
-off, and change nothing: the exact overstatement UHP §4.3 forbids and the reason this backend is
-allowed to claim `tool_enforcement: "hard"` at all.
-
-This test is named in both comments that make the claim (the catalog entry and the path table), so
-that a drift on either side fails here rather than on a live turn.
+"""The console must never offer a Kimi Code CLI tool toggle the runner cannot enforce.
+
+Kimi Code CLI's agent files match `disallowedTools` by exact, case-sensitive tool NAME, and a name
+the CLI does not know "never matches anything" (its agents reference): a catalog id outside the
+runner's _KIMI_TOOLS would be offered as a toggle in the console, reported as off, and change
+nothing, the exact overstatement UHP section 4.3 forbids and the reason this backend is allowed to
+claim `tool_enforcement: "hard"` at all. _KIMI_TOOLS is the `tools` array of a live 2.0.0 request
+captured at a stub; this test holds the catalog to it, so a drift on either side fails here rather
+than on a live turn. (The file keeps its first name: under the CLI's predecessor the table mapped
+names to module paths.)
"""
import os
import pathlib
@@ -18,31 +17,42 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "runner"))
os.environ.setdefault("HR_BACKING", "local")
import app as A # noqa: E402
-from server import _KIMI_TOOL_PATHS # noqa: E402
+from server import _KIMI_TOOLS # noqa: E402
def test_every_advertised_kimi_tool_can_actually_be_withheld():
advertised = {tid for tid, _label in A._BASE_CATALOG["kimi"]["tools"]}
- assert advertised == set(_KIMI_TOOL_PATHS), (
- "catalog ids and _KIMI_TOOL_PATHS keys must match exactly; "
- f"only in catalog: {advertised - set(_KIMI_TOOL_PATHS)}, "
- f"only in table: {set(_KIMI_TOOL_PATHS) - advertised}")
+ assert advertised == set(_KIMI_TOOLS), (
+ "catalog ids and _KIMI_TOOLS must match exactly; "
+ f"only in catalog: {advertised - set(_KIMI_TOOLS)}, only in the runner: {set(_KIMI_TOOLS) - advertised}")
def test_kimi_claims_hard_enforcement_and_earns_it():
assert A._BASE_CATALOG["kimi"]["tool_enforcement"] == "hard"
assert A._BASE_CATALOG["kimi"]["backend"] == "kimi"
+ assert A._BASE_CATALOG["kimi"]["label"] == "Kimi Code CLI"
-def test_tools_gated_behind_a_key_or_a_vision_model_are_not_offered():
- """SearchWeb and ReadMediaFile are in kimi's shipped default agent but raise SkipThisTool
- unless a Moonshot search key / a vision-capable model is configured, so neither is ever
- constructed here. Listing one would be a picker row for a tool that does not exist."""
- advertised = {tid for tid, _ in A._BASE_CATALOG["kimi"]["tools"]}
- assert "SearchWeb" not in advertised
- assert "ReadMediaFile" not in advertised
+def test_a_tool_that_needs_a_moonshot_service_is_not_offered():
+ """WebSearch is declared only with a Moonshot search service configured, which this product
+ never sets, so it is not in the captured array and must not be a picker row."""
+ assert "WebSearch" not in {tid for tid, _ in A._BASE_CATALOG["kimi"]["tools"]}
def test_kimi_is_chat_completions_only():
- """Its provider type is openai_legacy, so a Responses-API-only id would fail on send."""
+ """The runner defines its model as provider type `openai` through the relay, so a
+ Responses-API-only id would fail on send."""
assert "kimi" in A.CHAT_ONLY_BACKENDS
+
+
+def test_a_server_the_cli_ran_without_becomes_a_note_in_the_reply():
+ """Kimi Code CLI runs a turn without an MCP server it could not reach and says nothing; the
+ runner reads the CLI's own record of it and this is the sentence a person gets."""
+ one = A._blocks_from_canonical({"type": "system", "subtype": "mcp_unavailable",
+ "servers": [{"name": "dead", "reason": "fetch failed"}]})
+ assert one == [("text", '\n\n_Note: the MCP server "dead" could not be reached, so this reply ran '
+ 'without those tools._\n')]
+ two = A._blocks_from_canonical({"type": "system", "subtype": "mcp_unavailable",
+ "servers": [{"name": "a"}, {"name": "b"}]})
+ assert 'servers "a", "b"' in two[0][1]
+ assert A._blocks_from_canonical({"type": "system", "subtype": "mcp_unavailable", "servers": []}) == []
diff --git a/runner/server.py b/runner/server.py
index cd5af720..315bffdf 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -45,6 +45,7 @@ from __future__ import annotations
import base64
import hashlib
import http.server
+import datetime
import json
import mimetypes
import os
@@ -239,24 +240,9 @@ def _own_tree(root: str, uid: int, from_uids: set[int]) -> None:
continue
-def _kimi_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:
- """Ask kimi's store whether this session exists, with kimi's own predicate.
-
- `Session.find` treats a session as existing iff sessions/<md5(work_dir)>/<id>/context.jsonl is
- on disk, so this makes the identical check. It CANNOT be inferred from argv: --session is on the
- command line whether or not the session exists, because kimi mints a session with whatever id it
- is handed (cli/__init__.py:558-565, find -> None -> "not found, creating new session" ->
- Session.create). Measured on 1.50.0: resuming an id that never existed printed nothing, changed
- no exit code, and left a brand-new session directory behind — with a working provider it would
- have answered from an empty history as a completed turn, which is the exact failure this whole
- mechanism exists to stop."""
- share = pathlib.Path(cwd) / ".harness" / "home" / ".kimi"
- return (_kimi_session_dir(share, cwd, session_id) / "context.jsonl").exists()
-
-
def _argv_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:
- """The builder looked the session up and said so in argv: claude's --resume and opencode's
- --session carry the id only when it was found in this workspace."""
+ """The builder looked the session up and said so in argv: claude's --resume, opencode's
+ --session and kimi's -r carry the id only when it was found in this workspace."""
return session_id in cmd
@@ -284,7 +270,7 @@ _SESSION_PRESENT = {
"claude": _argv_session_present,
"opencode": _argv_session_present,
"goose": _goose_session_present,
- "kimi": _kimi_session_present,
+ "kimi": _argv_session_present,
}
@@ -427,7 +413,14 @@ CHECKPOINT_EXCLUDE = ["./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.jso
# dominate checkpoint size — a node project checkpointed 200MB+ and paid
# that again on every hydrate. The agent reinstalls when it needs them.
"node_modules", ".venv", "venv", "__pycache__", ".pnpm-store",
- ".cache/pip", ".npm/_cacache"]
+ ".cache/pip", ".npm/_cacache",
+ # Kimi Code CLI: sessions/ is what a resume reads and it travels; its logs,
+ # response cache and update-check state do not need to, and a log is the one
+ # place a CLI may print what it was handed. The key itself is never at rest:
+ # the model is defined from the environment (see _build_kimi).
+ "./.harness/home/.kimi-code/logs",
+ "./.harness/home/.kimi-code/cache",
+ "./.harness/home/.kimi-code/updates"]
_GIT_ENV = {"GIT_AUTHOR_NAME": "harness", "GIT_AUTHOR_EMAIL": "[email protected]",
"GIT_COMMITTER_NAME": "harness", "GIT_COMMITTER_EMAIL": "[email protected]"}
CLAUDE_DEFAULT_MODEL = os.environ.get("CLAUDE_DEFAULT_MODEL", "claude-sonnet-4.6")
@@ -448,13 +441,12 @@ CODEX_REASONING_EFFORT = os.environ.get("CODEX_REASONING_EFFORT", "medium")
# The window Codex plans compaction against. Its own catalog says 272k for every gpt-5.x; a larger
# number here made it compact late and let a long thread overflow the real window first.
CODEX_CONTEXT_WINDOW = os.environ.get("CODEX_CONTEXT_WINDOW", "272000")
-# kimi REQUIRES a per-model max_context_size in its config (no default), and plans compaction
-# against it: loop_control.compaction_trigger_ratio 0.85 over reserved_context_size 50000. The
-# same problem codex has above, solved the same way and for the same reason — a number that is
-# too LARGE compacts late and lets the thread overflow the real window (the provider then 400s);
-# too small compacts early and wastes tokens on a turn that would have fit. One value across the
-# catalog is a known approximation: it is honest only because being wrong changes WHEN the agent
-# compacts, never whether it answers. A per-id window belongs in the catalog, not here.
+# Kimi Code CLI takes the model's window as KIMI_MODEL_MAX_CONTEXT_SIZE (its own default is 256k) and
+# plans compaction against it. The same problem codex has above, solved the same way and for the
+# same reason: a number that is too LARGE compacts late and lets the thread overflow the real window
+# (the provider then 400s); too small compacts early and wastes tokens on a turn that would have
+# fit. One value across the catalog is a known approximation: it is honest only because being wrong
+# changes WHEN the agent compacts, never whether it answers. A per-id window belongs in the catalog.
KIMI_CONTEXT_WINDOW = os.environ.get("KIMI_CONTEXT_WINDOW", "272000")
# Provider defaults (overridable per-turn via auth.base_url). Wired from pool env.
OPENAI_BASE_URL = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1")
@@ -3564,8 +3556,12 @@ def _gemini_relay_route(host_root: str, api_key: str, model: str = "", native_mo
return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok
-def _hermes_relay_route(base_url: str, api_key: str) -> tuple[str, str]:
- """Register one turn's upstream; → (relay base_url, placeholder bearer for the CLI)."""
+def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ...] = ()) -> tuple[str, str]:
+ """Register one turn's upstream; → (relay base_url, placeholder bearer for the CLI).
+
+ `drop_fields` names top-level request fields this route's client sends on its own initiative and
+ the harness never asked for; they are removed before the provider sees them (the same list the
+ relay grows by itself when a provider names an unknown field)."""
with _HERMES_RELAY["lock"]:
if _HERMES_RELAY["server"] is None:
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _HermesRelayHandler)
@@ -3578,7 +3574,8 @@ def _hermes_relay_route(base_url: str, api_key: str) -> tuple[str, str]:
# https://api.anthropic.com/chat/completions, a 404 with no body (2026-09-06 support
# matrix; Anthropic's OpenAI-compatible surface lives under /v1). Bedrock keeps its host
# (its own path is built in _bedrock_anthropic).
- _HERMES_RELAY["routes"][tok] = (_relay_base_with_version(base_url), api_key, {"rename_max_tokens": False})
+ _HERMES_RELAY["routes"][tok] = (_relay_base_with_version(base_url), api_key,
+ {"rename_max_tokens": False, "drop_fields": tuple(drop_fields)})
return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok
@@ -3766,113 +3763,93 @@ def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
KIMI_PROVIDERS = {"anthropic", "openai", "azure", "openai-api", "tokenrouter"}
-# Every kimi tool, mapped from the name the model sees to the MODULE PATH its agent spec needs.
+# Every built-in tool Kimi Code CLI declares to the model, by the exact name its agent files match.
#
-# THE TRAP THIS TABLE EXISTS FOR, measured on 1.50.0: `exclude_tools` matches tool PATHS, not tool
-# names. In one probe both "Shell" (bare name) and "kimi_cli.tools.web:FetchURL" (path) were
-# excluded — FetchURL disappeared from the tools array the model received and Shell did NOT. A bare
-# name is a SILENT no-op: the console would report the tool as off while the model still has it,
-# which is exactly the failure registration point 9 warns about, and it is why this backend can
-# claim tool_enforcement "hard" only through this table. _BASE_CATALOG["kimi"]'s tool ids are
-# pinned equal to these keys by test_catalog_kimi_tool_paths.py, so the console can never offer a
-# name that has no path here.
-#
-# SearchWeb and ReadMediaFile are deliberately absent: both are in the shipped default agent but
-# raise SkipThisTool unless a Moonshot search key / a vision-capable model is configured
-# (kimi_cli/tools/web/search.py:47, kimi_cli/tools/file/read_media.py:54), so neither is ever
-# constructed here and listing either would be offering a tool that does not exist.
-_KIMI_TOOL_PATHS = {
- "Agent": "kimi_cli.tools.agent:Agent",
- "AskUserQuestion": "kimi_cli.tools.ask_user:AskUserQuestion",
- "SetTodoList": "kimi_cli.tools.todo:SetTodoList",
- "Shell": "kimi_cli.tools.shell:Shell",
- "TaskList": "kimi_cli.tools.background:TaskList",
- "TaskOutput": "kimi_cli.tools.background:TaskOutput",
- "TaskStop": "kimi_cli.tools.background:TaskStop",
- "ReadFile": "kimi_cli.tools.file:ReadFile",
- "Glob": "kimi_cli.tools.file:Glob",
- "Grep": "kimi_cli.tools.file:Grep",
- "WriteFile": "kimi_cli.tools.file:WriteFile",
- "StrReplaceFile": "kimi_cli.tools.file:StrReplaceFile",
- "FetchURL": "kimi_cli.tools.web:FetchURL",
- "EnterPlanMode": "kimi_cli.tools.plan.enter:EnterPlanMode",
- "ExitPlanMode": "kimi_cli.tools.plan:ExitPlanMode",
-}
-
-
-def _kimi_session_dir(share: pathlib.Path, cwd: str, session_id: str) -> pathlib.Path:
- """Where kimi keeps one session, asked the way kimi itself asks it.
-
- `Session.find` (kimi_cli/session.py) treats a session as existing iff
- sessions/<md5(work_dir)>/<id>/context.jsonl is on disk, and metadata.py:36 hashes the work dir
- with plain md5. Reproducing that predicate is the whole of _resume_lost's kimi arm — the goose
- lesson (a byte search for the session NAME matched the workspace path and reported a session
- that was not there) is why this asks the store instead of searching it."""
- key = hashlib.md5(cwd.encode("utf-8")).hexdigest() # noqa: S324 - kimi's own key, not a digest
- return share / "sessions" / key / session_id
-
-
-def _kimi_config(ws: pathlib.Path, model: str) -> pathlib.Path:
- """kimi's config file. Required, not optional, for three separate reasons measured on 1.50.0:
-
- 1. OPENAI_BASE_URL / OPENAI_API_KEY only OVERRIDE an existing provider entry (llm.py:305-311,
- `case "openai_legacy" | "openai_responses":`), so a provider block must exist to be
- overridden. Env alone configures nothing.
- 2. `-m` names an ALIAS in config.models, not a model id; the id that reaches the provider is
- models.<alias>.model. So the real id is written HERE and `-m hr` is a constant.
- 3. telemetry defaults to TRUE and posts to telemetry-logs.kimi.com (telemetry/transport.py:22).
- There is no env kill switch — it is a config key only.
-
- No credential is written: the placeholders below exist so the provider block parses, and the
- environment wins over both. --config (the inline-string form) is deliberately not used: it
- would put the provider block on argv, where /proc exposes it."""
- path = ws / ".harness" / "kimi-config.toml"
- path.parent.mkdir(parents=True, exist_ok=True)
- esc = model.replace("\\", "\\\\").replace('"', '\\"')
- path.write_text(
- "default_model = \"hr\"\n"
- "telemetry = false\n"
- "\n"
- "[providers.hr]\n"
- "type = \"openai_legacy\"\n"
- "base_url = \"http://127.0.0.1:1/v1\"\n"
- "api_key = \"set-from-environment\"\n"
- "\n"
- "[models.hr]\n"
- "provider = \"hr\"\n"
- f"model = \"{esc}\"\n"
- f"max_context_size = {KIMI_CONTEXT_WINDOW}\n")
- return path
+# MEASURED, not read off the docs: the `tools` array of a live 2.0.0 request, captured at a local
+# stub with no provider involved. The console offers exactly these as toggles, and
+# test_catalog_kimi_tool_paths.py pins _BASE_CATALOG["kimi"]'s tool ids equal to this tuple so the
+# catalog can never offer a name the CLI would not recognise (an unknown name in disallowedTools
+# "never matches anything", per the agents reference, which would be a toggle that does nothing).
+# WebSearch is absent on purpose: it is declared only with a Moonshot search service configured.
+_KIMI_TOOLS = ("Agent", "AgentSwarm", "AskUserQuestion", "Bash", "CreateGoal", "CronCreate",
+ "CronDelete", "CronList", "Edit", "EnterPlanMode", "ExitPlanMode", "FetchURL",
+ "GetGoal", "Glob", "Grep", "Read", "ReadMediaFile", "SetGoalBudget", "Skill",
+ "TaskList", "TaskOutput", "TaskStop", "TodoList", "UpdateGoal", "WaitFor", "Write")
+
+
+# Two request fields Kimi Code CLI sends on its own initiative, captured at a stub on 2.0.0, that no
+# person configured and that break models which are fine without them:
+# max_tokens: 131072 on EVERY request, an output budget derived from a Kimi-sized window. OpenAI,
+# Anthropic and Google each refuse the whole request (limits 128000, 128000, 65536), and on a
+# 131k-window model the budget alone overflows the context (llama-3.3-70b: "requested about
+# 154972 tokens ... 131072 in the output"). There is no knob for it on the openai provider type.
+# reasoning_effort: "high" whenever the MODEL NAME looks like a reasoning model (claude-*), whatever
+# capabilities are declared. TokenRouter turns that into thinking.type.enabled, which the newer
+# Claude models refuse outright ("not supported for this model. Use thinking.type.adaptive"): five
+# ids failed their first turn on it.
+# The budget travels under a second name for an OpenAI-named model (gpt-*, o*): the CLI sends
+# max_completion_tokens: 131072 there instead, captured at the same stub across ten model families,
+# and gpt-5.4-mini refused it exactly as the others refused max_tokens. prompt_cache_key, the one
+# other extra it sends, is a caching hint no endpoint here objects to and stays.
+# Every other base here sends none of these and the provider's defaults apply; this base now does too.
+_KIMI_DROP_FIELDS = ("max_tokens", "max_completion_tokens", "reasoning_effort")
+
+
+def _kimi_home(ws: pathlib.Path) -> pathlib.Path:
+ """KIMI_CODE_HOME for this workspace: config, sessions, logs and mcp.json all land under it
+ (env-vars reference). It sits under .harness/home so the sessions travel with the checkpoint
+ and a resume survives a recycled sandbox, and so nothing of it shows up as a produced file."""
+ return ws / ".harness" / "home" / ".kimi-code"
+
+
+def _kimi_has_session(home: pathlib.Path, session_id: str) -> bool:
+ """Is this conversation in the store? Sessions live at sessions/<workdir key>/<session id>/
+ (measured on 2.0.0; the key is `wd_<dirname>_<hash>`), so the id is looked up under any key
+ rather than recomputing a hash this code does not own. It matters because `kimi -r <unknown id>`
+ is a hard failure on this CLI, exit 1 with `Session "<id>" not found`, where its predecessor
+ silently started a new conversation: the runner must not pass an id the store does not hold."""
+ sid = (session_id or "").strip()
+ if not sid or "/" in sid or sid.startswith("."):
+ return False
+ return any((home / "sessions").glob(f"*/{sid}"))
def _kimi_agent_file(ws: pathlib.Path, tools_disabled: list[str] | None) -> pathlib.Path | None:
- """A per-turn agent spec that withholds tools, or None when nothing is disabled.
-
- `extend: default` resolves to the shipped agent.yaml, and an excluded tool is never constructed
- and never declared to the model (kimi_cli/soul/agent.py:447-450) — this is what makes kimi's
- tool_enforcement "hard" rather than "instruction". Names are translated through
- _KIMI_TOOL_PATHS because kimi matches paths, not names; see that table's comment."""
- paths = [_KIMI_TOOL_PATHS[t] for t in (tools_disabled or []) if t in _KIMI_TOOL_PATHS]
- if not paths:
+ """A per-session agent file that withholds tools, or None when nothing is disabled.
+
+ An agent file is Markdown with a frontmatter block; `disallowedTools` matches built-in tools by
+ exact, case-sensitive name, shapes the tools shown to the model AND is enforced again before
+ execution (agents reference), which is what makes tool_enforcement "hard" here. Measured on
+ 2.0.0: with Bash disallowed and asked for the machine's boot id, the agent called no tool and
+ answered that it had no shell. The body is ${base_prompt} so the workspace instructions, skills
+ and plugin injections of the default prompt stay in effect."""
+ names = [t for t in (tools_disabled or []) if t in _KIMI_TOOLS]
+ if not names:
return None
- path = ws / ".harness" / "kimi-agent.yaml"
+ path = ws / ".harness" / "kimi-agent.md"
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps( # YAML is a superset of JSON, and json.dumps quotes safely
- {"version": 1, "agent": {"extend": "default", "name": "harness", "exclude_tools": paths}},
- indent=2))
+ # `subagents: []` is part of the policy, not decoration. Measured through the product on 2.0.0:
+ # with only Bash disallowed, kimi-k3 answered "I don't have a direct shell tool, but I can
+ # dispatch a subagent that does" and called Agent; the built-in coder subagent carries its own
+ # tool list, so a withheld tool came back by delegation. With the allowlist empty the Agent tools
+ # have nobody to dispatch to and the same prompt answers that it has no shell.
+ path.write_text("---\nname: harness\n"
+ "description: The harness agent with its tool policy applied.\n"
+ "disallowedTools:\n" + "".join(f" - {n}\n" for n in names) +
+ "subagents: []\n"
+ "---\n${base_prompt}\n")
return path
-def _kimi_mcp_config(ws: pathlib.Path, mcp_servers: list[dict] | None) -> pathlib.Path | None:
- """The standard `mcpServers` object, parsed by fastmcp's MCPConfig (kimi_cli/soul/toolset.py).
- The same shape _qwen_settings writes, with ONE field difference: streamable HTTP is `url` here,
- where gemini-cli's schema (which qwen inherited) calls it `httpUrl`.
+def _kimi_mcp_config(home: pathlib.Path, mcp_servers: list[dict] | None) -> pathlib.Path:
+ """$KIMI_CODE_HOME/mcp.json, the user-level file (the project-level one raises a trust prompt
+ for an untrusted folder). Written on EVERY turn, empty included, so a server removed from the
+ harness is gone from the next turn instead of lingering in the file.
- A server that cannot start is FATAL on this CLI — `Unknown error: Failed to connect MCP
- servers: {…}` on stdout and exit 1, verified live — rather than a degraded turn. That is the
- opposite of hermes (which disables HTTP MCP with only a log line) and of goose (which warns on
- stderr and continues); it satisfies UHP's visibility SHOULD loudly, at the cost of a flaky
- third-party server taking the whole turn with it. Recorded in docs/support-matrix-notes.md."""
+ Shapes per the MCP reference, each measured on 2.0.0: a `command` entry is stdio (args, env and
+ cwd honoured, which is what a plugin launcher needs); a `url` entry with no transport is
+ streamable HTTP; a legacy SSE server says `transport: "sse"` explicitly. The harness's declared
+ transport decides, never the url's spelling."""
servers: dict = {}
for i, sv in enumerate(mcp_servers or []):
if not isinstance(sv, dict):
@@ -3880,15 +3857,9 @@ def _kimi_mcp_config(ws: pathlib.Path, mcp_servers: list[dict] | None) -> pathli
name = _skill_dir_name(sv.get("name") or sv.get("id") or f"server{i}")
url = (sv.get("url") or "").strip()
if url:
- # The transport the harness DECLARED, written out: fastmcp's RemoteMCPServer takes an
- # optional `transport` and, when it is absent, guesses from the url's path
- # (mcp_config.py infer_transport_type_from_url: SSE iff the path matches
- # /sse(/|?|&|$), streamable HTTP otherwise). An SSE server at any other path would be
- # dialed as streamable HTTP, and on this CLI a server that fails to connect takes the
- # whole turn with it. _qwen_settings makes the same choice through gemini-cli's
- # url/httpUrl keys; this is the same choice in fastmcp's spelling.
- entry: dict = {"url": url,
- "transport": "sse" if str(sv.get("transport") or "").lower() == "sse" else "http"}
+ entry: dict = {"url": url}
+ if str(sv.get("transport") or "").lower() == "sse":
+ entry["transport"] = "sse"
hdrs = sv.get("headers")
if isinstance(hdrs, dict) and hdrs:
entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}
@@ -3900,13 +3871,13 @@ def _kimi_mcp_config(ws: pathlib.Path, mcp_servers: list[dict] | None) -> pathli
envv = sv.get("env")
if isinstance(envv, dict) and envv:
entry["env"] = {str(k): str(v) for k, v in envv.items()}
+ if sv.get("cwd"):
+ entry["cwd"] = str(sv["cwd"])
else:
continue
servers[name] = entry
- if not servers:
- return None
- path = ws / ".harness" / "kimi-mcp.json"
- path.parent.mkdir(parents=True, exist_ok=True)
+ home.mkdir(parents=True, exist_ok=True)
+ path = home / "mcp.json"
path.write_text(json.dumps({"mcpServers": servers}, indent=2))
return path
@@ -3915,77 +3886,58 @@ def _build_kimi(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
resume_session_id: str | None = None, mcp_servers: list[dict] | None = None,
skills_dir: str | None = None, tools_disabled: list[str] | None = None,
max_turns: int | None = None) -> list[str]:
+ """Kimi Code CLI (MoonshotAI/kimi-code, 2.0.0), the successor its vendor moved Kimi CLI to.
+
+ The model is defined from the ENVIRONMENT alone: with KIMI_MODEL_NAME set the CLI synthesises a
+ provider in memory and persists nothing (env-vars reference), so no config file is written and
+ no credential exists at rest. Measured: after a full session the data home held no trace of the
+ key. Every turn rides the loopback relay, the qwen rationale unchanged: the real key never
+ enters the CLI's environment, request shapes strict endpoints refuse are repaired in flight,
+ and the provider's own "model" passes through for the served-model check."""
pr = provider or "openai-api"
if pr not in KIMI_PROVIDERS:
raise HTTPException(400, f"unknown kimi provider '{pr}' (one of {sorted(KIMI_PROVIDERS)})")
if not auth.base_url:
raise HTTPException(400, "kimi needs a base_url (none configured)")
if auth.api_key:
- # EVERY kimi turn rides the loopback relay, the qwen rationale unchanged: the real key never
- # enters the CLI's environment, and request shapes strict endpoints refuse are repaired in
- # flight. kimi needs one repair of its own — it sends `reasoning_effort: null`, which
- # Vercel's AI Gateway answers with HTTP 400 ("Invalid option: expected one of
- # \"none\"|\"minimal\"|…", measured twice in one live turn) — handled for every backend in
- # _set_reasoning_effort_none rather than here.
- #
- # Riding the relay is also what makes matrix rule 2 enforceable on this backend: kimi itself
- # reports no served model anywhere in its stream, but the provider's own "model" passes the
- # relay in the bytes and _relay_served_model stamps it onto the synthesised result.
- relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key)
+ relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key, drop_fields=_KIMI_DROP_FIELDS)
auth = auth.model_copy(update={"base_url": relay_base, "api_key": relay_tok})
ws = pathlib.Path(cwd)
- share = ws / ".harness" / "home" / ".kimi"
- share.mkdir(parents=True, exist_ok=True)
- # KIMI_SHARE_DIR is a DEDICATED variable for config + sessions + logs, so unlike qwen (and every
- # other backend that redirects HOME) this one never touches HOME at all. Verified after a full
- # two-turn session: a fresh HOME stayed empty. It sits under .harness/ so sessions/ is
- # checkpointed — resume has to survive a sandbox recycle (matrix scenario 5) — and is excluded
- # from produced files.
- env["KIMI_SHARE_DIR"] = str(share)
- env["OPENAI_API_KEY"] = auth.api_key or ""
- env["OPENAI_BASE_URL"] = auth.base_url
- # kimi prints its error lines through `rich.print` (ui/print/__init__.py:27), which hard-wraps at
- # the terminal width — 80 in a non-tty — and a wrapped `Error code: 400 - {…}` reaches errbuf as
- # three unrelated-looking fragments. Measured: the same probe at COLUMNS=400 came back as one
- # unbroken line, which is what _failure_reason needs to match a provider refusal in it.
- env["COLUMNS"] = "400"
- cfg = _kimi_config(ws, model)
- cmd = ["kimi", "--config-file", str(cfg), "-w", cwd,
- "--print", "--output-format", "stream-json",
- # -m names the alias written into the config above, never a model id: kimi resolves it
- # against config.models and raises KeyError on a miss rather than substituting, which is
- # why checklist 2 is clean on this backend (no gemini-style resolveModel rewrite).
- "-m", "hr",
- # --print already implies auto-approval (cli/__init__.py:626 runtime_afk = ui == "print");
- # --yolo is passed anyway for one deterministic path, qwen's rationale unchanged.
- "--yolo"]
+ home = _kimi_home(ws)
+ home.mkdir(parents=True, exist_ok=True)
+ env["KIMI_CODE_HOME"] = str(home)
+ env["KIMI_DISABLE_TELEMETRY"] = "1"
+ # An agent that replaces its own binary mid-turn is not a pinned backend: the update preflight
+ # (check, background install, prompt) is switched off; the image decides the version.
+ env["KIMI_CODE_NO_AUTO_UPDATE"] = "1"
+ env["KIMI_MODEL_NAME"] = model
+ env["KIMI_MODEL_PROVIDER_TYPE"] = "openai"
+ env["KIMI_MODEL_BASE_URL"] = auth.base_url
+ env["KIMI_MODEL_API_KEY"] = auth.api_key or ""
+ env["KIMI_MODEL_MAX_CONTEXT_SIZE"] = str(KIMI_CONTEXT_WINDOW)
+ env["NO_COLOR"] = "1"
+ # The CLI retries a failing step up to ten times, a provider's flat 400 included: measured, a
+ # request a model refuses outright took 143 to 178 s to fail. Three total attempts still rides
+ # out a transient error and lets a real refusal reach the person in seconds.
+ env["KIMI_LOOP_MAX_ATTEMPTS_PER_STEP"] = "3"
if max_turns:
- # THE BUDGET, and without it a turn is bounded only by kimi's own default of 1000 steps
- # (config.py max_steps_per_turn, raised 500 -> 1000 upstream). On a fast model that is
- # invisible; on a slow reasoning one it is hours. Measured in the vercel column before this
- # was wired: gpt-5.6-luna's switch ran 8,754s, gpt-5.5's artifact 7,418s and its switch
- # 2,200s, while the same scenarios on other ids took 7-30s. The operator's step budget
- # reaches every other backend (claude and goose take it as --max-turns); it was dropped here.
- #
- # Reaching the cap is VISIBLE on this CLI rather than silent: it raises MaxStepsReached,
- # which arrives as its own stdout line and a non-zero exit, so a truncated turn reads as
- # truncated. goose, by contrast, reports nothing at its cap.
- cmd += ["--max-steps-per-turn", str(int(max_turns))]
- # ALWAYS named, on every turn, first or not: kimi mints a session with whatever id it is given
- # (cli/__init__.py:558-565 — find -> None -> create), so naming it on the first turn is what
- # makes the SECOND turn able to continue it. Passing it only on a resume is what broke the
- # recycle scenario on every row — the first turn wrote its history under a random id nobody
- # could name again. _resume_lost reports a genuinely lost conversation by asking the store.
- cmd += ["--session", resume_session_id or _KIMI_SESSION_NAME]
+ # THE BUDGET. Unset means unlimited on this CLI, and on a slow reasoning model that was
+ # hours on its predecessor. Reaching it is loud: exit 1 with loop.max_steps_exceeded.
+ env["KIMI_LOOP_MAX_STEPS_PER_TURN"] = str(int(max_turns))
+ _kimi_mcp_config(home, mcp_servers)
+ # -p runs one prompt without the TUI, with automatic permission (it refuses --yolo/--auto
+ # beside it); stream-json is one message per line. The process's cwd is the workspace.
+ cmd = ["kimi", "-p", prompt, "--output-format", "stream-json"]
+ if resume_session_id and _kimi_has_session(home, resume_session_id):
+ cmd += ["-r", resume_session_id]
+ else:
+ # The agent is bound when a session is created and restored on resume, and the CLI refuses
+ # --agent-file beside -r: the tool policy is set on the first turn of a conversation.
+ agent_file = _kimi_agent_file(ws, tools_disabled)
+ if agent_file is not None:
+ cmd += ["--agent-file", str(agent_file)]
if skills_dir:
cmd += ["--skills-dir", skills_dir]
- agent_file = _kimi_agent_file(ws, tools_disabled)
- if agent_file is not None:
- cmd += ["--agent-file", str(agent_file)]
- mcp_cfg = _kimi_mcp_config(ws, mcp_servers)
- if mcp_cfg is not None:
- cmd += ["--mcp-config-file", str(mcp_cfg)]
- cmd += ["-p", prompt]
return cmd
@@ -5194,57 +5146,32 @@ def _goose_eof(state: dict, rc: int) -> list[dict]:
_goose_to_claude.eof = _goose_eof # type: ignore[attr-defined]
-# The conversation id the runner MINTS for kimi. kimi emits no session id of its own — nothing in
-# its stream carries one — so without minting one here every follow-up would silently start a new
-# conversation, which is exactly what the first version of this backend did: the support matrix's
-# recycle scenario failed on every kimi row while first/follow-up/switch passed, because those three
-# never ask the agent to remember anything.
-#
-# A constant name rather than a uuid, for goose's reason: it has to be reproducible from the
-# workspace alone after a sandbox recycle, and kimi accepts any id — `Session.find` misses and
-# `Session.create(work_dir, session_id)` makes it (cli/__init__.py:558-565).
-_KIMI_SESSION_NAME = "harness"
-
-
# ── kimi ─────────────────────────────────────────────────────────────────────────
def _kimi_to_claude(obj: dict, state: dict) -> list[dict]:
- """Map ONE `kimi --print --output-format stream-json` line to zero+ canonical claude events.
+ """Map ONE `kimi -p … --output-format stream-json` line to zero+ canonical claude events.
- Shapes verified against the pinned 1.50.0 by reading its ONLY emitter,
- kimi_cli/ui/print/visualize.py::JsonPrinter.feed, which matches StatusUpdate / StepBegin /
- StepRetry / TurnBegin / TurnEnd and then falls through to `case _: # ignore other messages`.
- The flag name is claude's; the schema is not — it is one kosong `Message` per line:
+ Shapes captured live from Kimi Code CLI 2.0.0, one JSON object per line:
+ version {"role":"meta","type":"system.version","version":"2.0.0"}
assistant text {"role":"assistant","content":"…"}
- assistant call {"role":"assistant","content":[…parts…],
- "tool_calls":[{"id",…,"function":{"name","arguments"}}]}
+ assistant call {"role":"assistant","tool_calls":[{"id",…,"function":{"name","arguments"}}]}
tool result {"role":"tool","content":"…","tool_call_id":"…"}
- notification the Notification model — background-task notices
- plan display {"content":…,"file_path":…} — plan mode only
-
- `content` is a PLAIN STRING on a text-only message and a LIST OF PARTS when the message carries
- tool calls; both were captured live and both are handled.
+ resume hint {"role":"meta","type":"session.resume_hint","session_id":"session_<uuid>",…}
- THREE ABSENCES drive every design choice here, each verified in the emitter AND in a live
- capture rather than inferred:
- - no usage of any kind -> the result event's usage is {} (see _kimi_eof)
- - no session id -> the runner MINTS one and announces it (_KIMI_SESSION_NAME)
- - no terminal / result event -> this normaliser carries an `eof`, the opencode precedent
- """
+ The resume hint is the LAST line of a turn and the only place the session id appears, so the
+ conversation id is announced from it; the run loop records an init event whenever it arrives.
+ The stream carries no usage and no result event: usage is the relay's to stamp, and the process
+ exiting is the end of the turn (see _kimi_eof)."""
role = obj.get("role")
- pre: list[dict] = []
- if not state.get("_kimi_init"):
- # The turn's FIRST event carries the conversation id. _run_turn_bg records it only from a
- # system/init event, and that recorded id is what the next turn resumes with — without it
- # every follow-up starts a new conversation in the same workspace, and only a scenario that
- # asks the agent to remember something notices.
- state["_kimi_init"] = True
- pre = [{"type": "system", "subtype": "init", "session_id": _KIMI_SESSION_NAME,
- "model": state.get("model")}]
+ if role == "meta":
+ if obj.get("type") == "session.resume_hint" and obj.get("session_id"):
+ return [{"type": "system", "subtype": "init", "session_id": str(obj["session_id"]),
+ "model": state.get("model")}]
+ return []
if role == "assistant":
- out: list[dict] = list(pre)
+ out: list[dict] = []
content = obj.get("content")
if isinstance(content, str):
txt = content
@@ -5254,9 +5181,8 @@ def _kimi_to_claude(obj: dict, state: dict) -> list[dict]:
else:
txt = ""
if txt.strip():
- # The LAST assistant text is the turn's answer: kimi emits no terminal event, so there
- # is nothing else to take it from, and a tool-carrying message has content [] (captured)
- # and therefore never overwrites a real answer here.
+ # The LAST assistant text is the turn's answer: there is no result event to take it
+ # from, and a tool-carrying message has no content, so it never overwrites an answer.
state["final"] = txt
out.append({"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}})
for call in obj.get("tool_calls") or []:
@@ -5266,9 +5192,8 @@ def _kimi_to_claude(obj: dict, state: dict) -> list[dict]:
tuid = str(call.get("id") or "tool")
args = fn.get("arguments")
if isinstance(args, str):
- # kimi sends arguments as a JSON STRING (OpenAI's shape), not an object. A model can
- # emit one that does not parse; keep the raw text rather than dropping the call, so
- # the trace still shows what was attempted.
+ # arguments arrive as a JSON STRING (OpenAI's shape). A model can emit one that
+ # does not parse; keep the raw text rather than dropping the call.
try:
args = json.loads(args)
except Exception: # noqa: BLE001
@@ -5280,49 +5205,68 @@ def _kimi_to_claude(obj: dict, state: dict) -> list[dict]:
return out
if role == "tool":
body = obj.get("content")
- _ = pre
text = body if isinstance(body, str) else json.dumps(body, default=str)
- # is_error is NOT knowable from this line. kimi wraps both outcomes in <system>…</system>
- # ("File successfully overwritten", and errors alike); the boolean lives on
- # ToolResult.return_value.is_error in wire.jsonl, which this stream does not carry. Marking
- # every result a success would be a lie only when it failed, and inventing a heuristic over
- # the <system> prose is the guesswork this repo refuses — so the flag stays False and the
- # text itself carries the outcome to the reader.
- return pre + [{"type": "user", "message": {"content": [
+ # is_error is not on this line: the text itself carries the outcome to the reader.
+ return [{"type": "user", "message": {"content": [
{"type": "tool_result", "tool_use_id": str(obj.get("tool_call_id") or "tool"),
"is_error": False, "content": text}]}}]
- return pre
+ return []
def _kimi_eof(state: dict, rc: int) -> list[dict]:
- """Synthesize the turn's result at end of stream: kimi emits no terminal event, so the process
- exiting IS the end of the turn.
-
- THE EXIT CODE IS THE STATUS, and on this CLI that is stronger than any prose test. 1.50.0
- classifies provider failures itself (`Print._classify_provider_error`,
- kimi_cli/ui/print/__init__.py): 75 (EX_TEMPFAIL) for APIConnectionError / APITimeoutError /
- APIEmptyResponseError and for status 429/500/502/503/504; 1 for every other APIStatusError and
- for the catch-all. So unlike claude (`API Error: …`) and goose (`Ran into this error: …`) there
- is no failure NARRATED AS ASSISTANT TEXT to recognise, and this backend needs no error regex —
- registration point 6 is satisfied by the exit code instead. Pinned by
- test_kimi_backend.py::test_failure_exit_codes_are_the_signal.
-
- The failure SENTENCE is a bare non-JSON line on stdout (`Error code: 401 - {…}`,
- `Connection error.`, `Unknown error: Failed to connect MCP servers: {…}`), which _run_turn_bg
- has already collected into errbuf. Returning an EMPTY result here is deliberate and load-bearing:
- _run_turn_bg fills an empty result event from that tail, and _failure_reason then prefers the
- provider refusal it matches inside it. Putting a placeholder sentence here instead would shadow
- the real reason, and putting the partial assistant text here would report a 401 as if the model
- had answered. rec["result"] keeps that partial text either way, from state["final"].
-
- usage is {} deliberately, not as an oversight: kimi's stream carries no token counts at all, and
- per the 2026-09-13 decision no harness PR builds its own usage pipeline — `_relay_usage` stamps
- these rows when it lands. goose's eof already emits {} for the same reason."""
+ """Synthesize the turn's result at end of stream: there is no terminal event, so the process
+ exiting IS the end of the turn, and THE EXIT CODE IS THE STATUS. Measured on 2.0.0: a provider
+ refusal, an unknown session, a spent step budget and an MCP failure all exit 1 with one line on
+ stderr, `error: failed to run prompt: <class>: <reason>` (provider.auth_error: 401 …,
+ loop.max_steps_exceeded: …), which the run loop has already collected. Returning an EMPTY
+ result on failure is deliberate: the run loop fills it from that line and _failure_reason
+ prefers a provider refusal it matches inside it; a placeholder here would shadow the real
+ reason. usage is {} because the stream carries none; the relay stamps it."""
final = state.get("final", "")
+ pre: list[dict] = []
+ down = _kimi_mcp_unavailable(state)
+ if down:
+ pre = [{"type": "system", "subtype": "mcp_unavailable", "servers": down}]
if rc == 0:
- return [{"type": "result", "subtype": "success", "is_error": False,
- "result": final, "usage": {}}]
- return [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": {}}]
+ return pre + [{"type": "result", "subtype": "success", "is_error": False,
+ "result": final, "usage": {}}]
+ return pre + [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": {}}]
+
+
+_KIMI_MCP_DOWN = re.compile(
+ r'^(\S+) ERROR mcp server unavailable\s+server=(\S+)\s+transport=\S+\s+status=\S+(?:\s+reason="([^"]*)")?')
+
+
+def _kimi_mcp_unavailable(state: dict) -> list[dict]:
+ """The MCP servers this turn could not reach, read from the CLI's own log.
+
+ Kimi Code CLI runs the turn WITHOUT an unreachable server and says nothing about it: no stream
+ line, nothing on stderr, exit 0 (measured on 2.0.0 against a dead endpoint; its predecessor
+ failed the turn instead). The only trace is one line in $KIMI_CODE_HOME/logs/kimi-code.log,
+ `<iso time> ERROR mcp server unavailable server=<name> transport=<t> status=failed reason="…"`.
+ A person whose tool silently was not there has no way to know why the agent never used it, so
+ the lines written since this turn began become a system event the gateway renders as a note."""
+ cwd = state.get("cwd")
+ if not cwd:
+ return []
+ log = _kimi_home(pathlib.Path(cwd)) / "logs" / "kimi-code.log"
+ try:
+ lines = log.read_text(errors="replace").splitlines()[-400:]
+ except OSError:
+ return []
+ since = float(state.get("started") or 0) - 2.0
+ out: dict[str, dict] = {}
+ for ln in lines:
+ m = _KIMI_MCP_DOWN.match(ln)
+ if not m:
+ continue
+ try:
+ ts = datetime.datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ continue
+ if ts >= since:
+ out[m.group(2)] = {"name": m.group(2), "reason": (m.group(3) or "")[:200]}
+ return list(out.values())
_kimi_to_claude.eof = _kimi_eof # type: ignore[attr-defined]
@@ -5364,9 +5308,9 @@ BACKENDS = {
# carries its own normaliser rather than sharing one — see _goose_to_claude's docstring.
"goose": {"providers": sorted(GOOSE_PROVIDERS), "default_model": GOOSE_DEFAULT_MODEL,
"normalize": _goose_to_claude},
- # kimi's stream-json shares claude's FLAG NAME and nothing else: one kosong Message per line,
- # no usage, no session id and no terminal event — so it carries its own normaliser and an eof,
- # rather than the passthrough qwen's genuinely-claude-shaped stream can use.
+ # Kimi Code CLI's stream-json shares claude's FLAG NAME and nothing else: one message per line,
+ # no usage and no result event, the session id on the last line, so it carries its own
+ # normaliser and an eof rather than the passthrough qwen's claude-shaped stream can use.
"kimi": {"providers": sorted(KIMI_PROVIDERS), "default_model": KIMI_DEFAULT_MODEL,
"normalize": _kimi_to_claude},
}
@@ -5443,7 +5387,7 @@ def _kill_capped(proc: subprocess.Popen, rec: dict) -> None:
def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, model: str,
timeout_seconds: int | None = None, partial: bool = False) -> None:
rec = _turns[turn_id]
- state = {"model": model, "final": "", "partial": partial}
+ state = {"model": model, "final": "", "partial": partial, "cwd": cwd, "started": time.time()}
result_ev = None
try:
# start_new_session: own process group so cancel/timeout can killpg the CLI AND its
@@ -5549,7 +5493,7 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
_NO_DIAGNOSTIC_RE = re.compile(r"\w[\w-]* exited -?\d+ without reporting an error")
-_CLI_RESUME_HINT = re.compile(r"^To resume this session:")
+_CLI_RESUME_HINT = re.compile(r"^(To resume this session:|See log: )")
def _failure_reason(refusal: str, ev_err: str, tail: str, rc: int) -> str:
@@ -5559,10 +5503,11 @@ def _failure_reason(refusal: str, ev_err: str, tail: str, rc: int) -> str:
lines win over it: goose's tokio panic ("Permission denied (os error 13) at path /tmp/...")
sat in the stderr behind that sentence and the record never showed it (2026-09-13)."""
ev_err = ev_err.strip()
- # A CLI's advice on how to resume ITSELF is not part of the reason. kimi follows every failure
- # sentence with "To resume this session: kimi -r <id>" (measured on a dead MCP server, 1.50.0);
- # the person reading the record has no kimi to type that into, and the line names an internal
- # the product does not show. The sentence before it is the reason and stays.
+ # A CLI's notes to a person at its own terminal are not part of the reason: a "To resume this
+ # session: <cli> -r <id>" hint (Kimi CLI printed one after every failure) and Kimi Code CLI's
+ # "See log: <a path inside the sandbox>". The person reading the record has neither that CLI
+ # nor that path, and both name internals the product does not show. The sentence before them
+ # is the reason and stays.
tail = "\n".join(ln for ln in tail.splitlines() if not _CLI_RESUME_HINT.match(ln.strip())).strip()
if tail and _NO_DIAGNOSTIC_RE.fullmatch(ev_err):
ev_err = ""
diff --git a/runner/tests/test_kimi_backend.py b/runner/tests/test_kimi_backend.py
index 1cf39d55..f46b4d5b 100644
--- a/runner/tests/test_kimi_backend.py
+++ b/runner/tests/test_kimi_backend.py
@@ -1,18 +1,23 @@
-"""The kimi backend (MoonshotAI/kimi-cli, Apache-2.0, pinned to 1.50.0).
-
-Every shape asserted here was read off the 1.50.0 artifact the installer pins, or captured from a
-live turn — not from the docs. Each test pins one thing that would otherwise fail SILENTLY: the
-tool call that never renders, the disabled tool that disables nothing, the lost session that
-answers from an empty history as a completed turn, the provider 400 that kills every turn on one
-gateway.
-
-Source anchors (all 1.50.0):
- JsonPrinter.feed (the only emitter) kimi_cli/ui/print/visualize.py
- _classify_provider_error kimi_cli/ui/print/__init__.py
- openai_legacy env override kimi_cli/llm.py:305-311
- exclude_tools (paths, not names) kimi_cli/soul/agent.py:447-450
- Session.find / md5(work_dir) kimi_cli/session.py, kimi_cli/metadata.py:36
- telemetry default + endpoint kimi_cli/telemetry/transport.py:22
+"""The kimi backend: Kimi Code CLI (MoonshotAI/kimi-code, MIT, pinned to 2.0.0).
+
+0.18.0 wired this base to MoonshotAI/kimi-cli 1.50.0, the Python predecessor whose own README says
+it "is evolving into Kimi Code CLI". The product is the TypeScript rewrite, a different integration
+surface, and everything asserted here was measured on the 2.0.0 binary the installer pins (the VM
+host, 2026-09-17), not read off the docs. Each test pins one thing that would otherwise fail
+SILENTLY or loudly in production: the session id that only appears on the last line, the resume of
+an id the store does not hold (a hard exit 1 on this CLI), the disabled tool that disables
+nothing, the SSE server dialed as HTTP, the key written to disk.
+
+Measured facts the code rests on:
+ stream-json lines meta system.version / assistant text / assistant tool_calls / tool / meta
+ session.resume_hint (LAST line, the only place the session id appears)
+ model from env alone KIMI_MODEL_NAME (+ _PROVIDER_TYPE, _BASE_URL, _API_KEY, _MAX_CONTEXT_SIZE):
+ a provider synthesised in memory, nothing persisted, no key at rest
+ failures exit 1 and one stderr line `error: failed to run prompt: <class>: <reason>`
+ (provider.auth_error, loop.max_steps_exceeded, Session "<id>" not found)
+ tool policy agent file (Markdown) `disallowedTools` by exact NAME, bound at session
+ creation; --agent-file is refused beside -r
+ MCP $KIMI_CODE_HOME/mcp.json; url = streamable HTTP, transport "sse" explicit
"""
import json
import pathlib
@@ -20,14 +25,16 @@ import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
-from server import (Auth, BACKENDS, _KIMI_SESSION_NAME, _KIMI_TOOL_PATHS, # noqa: E402
- _agent_doc_path,
- _build_kimi, _kimi_eof, _kimi_to_claude, _normalize_openai_chat_body,
- _resume_lost)
+from server import (Auth, BACKENDS, CHECKPOINT_EXCLUDE, _KIMI_TOOLS, # noqa: E402
+ _kimi_mcp_unavailable, _HERMES_RELAY, _drop_top_level_field,
+ _agent_doc_path, _build_kimi, _failure_reason, _kimi_eof, _kimi_has_session,
+ _kimi_home, _kimi_to_claude, _normalize_openai_chat_body, _resume_lost)
+SID = "session_ce4ef4a0-1606-430e-89fd-f228abfda9e7"
-def _argv(**kw):
- d = tempfile.mkdtemp()
+
+def _argv(d=None, **kw):
+ d = d or tempfile.mkdtemp()
env: dict = {}
cmd = _build_kimi("openai-api", Auth(api_key="sk-t", base_url="https://up.example/v1"),
"kimi-k3", "do it", d, env, **kw)
@@ -35,318 +42,257 @@ def _argv(**kw):
def _norm(lines):
- state: dict = {}
+ state: dict = {"model": "kimi-k3"}
out = []
for line in lines:
out += _kimi_to_claude(line, state)
return out, state
-def _body(lines):
- """The turn's events with the system/init one dropped — it is asserted on its own below."""
- out, state = _norm(lines)
- return [e for e in out if e.get("subtype") != "init"], state
-
-
-# ── the stream's four line shapes ────────────────────────────────────────────────
-def test_assistant_text_is_a_plain_string_not_a_part_list():
- """Captured live: a text-only message carries `content` as a STRING. A normalizer that assumes
- claude's list-of-blocks (the flag name is the same, `stream-json`) renders nothing at all."""
- out, state = _body([{"role": "assistant", "content": "Created hello.txt. DONE"}])
- assert out == [{"type": "assistant",
- "message": {"content": [{"type": "text", "text": "Created hello.txt. DONE"}]}}]
- assert state["final"] == "Created hello.txt. DONE"
-
-
-def test_tool_call_message_carries_a_list_content_and_does_not_overwrite_the_answer():
- """Captured live: the tool-carrying message has `content: []` and the answer arrives after it.
- Taking `final` from the last assistant LINE rather than the last assistant TEXT would leave the
- turn's result empty."""
- out, state = _body([
- {"role": "assistant", "content": [],
- "tool_calls": [{"type": "function", "id": "call_1",
- "function": {"name": "WriteFile",
- "arguments": '{"path": "hello.txt", "content": "hi"}'}}]},
- {"role": "tool", "content": "<system>File successfully overwritten.</system>",
- "tool_call_id": "call_1"},
- {"role": "assistant", "content": "done. DONE"},
+def _store(d, sid=SID):
+ """A session as 2.0.0 lays it down: sessions/<workdir key>/<session id>/…"""
+ p = _kimi_home(pathlib.Path(d)) / "sessions" / "wd_ws_86f57a64234a" / sid
+ (p / "agents" / "main").mkdir(parents=True)
+ (p / "state.json").write_text("{}")
+ return p
+
+
+# ── the stream ───────────────────────────────────────────────────────────────────
+def test_assistant_text_is_a_plain_string():
+ out, state = _norm([{"role": "meta", "type": "system.version", "version": "2.0.0"},
+ {"role": "assistant", "content": "KC-ONE-5e1"}])
+ assert out == [{"type": "assistant", "message": {"content": [{"type": "text", "text": "KC-ONE-5e1"}]}}]
+ assert state["final"] == "KC-ONE-5e1"
+
+
+def test_a_tool_call_has_no_content_key_and_does_not_overwrite_the_answer():
+ """Captured live: the tool-carrying message has NO `content` key at all and the answer arrives
+ after the tool result."""
+ out, state = _norm([
+ {"role": "assistant", "tool_calls": [{"type": "function", "id": "call_1", "function": {
+ "name": "Write", "arguments": '{"path":"kc.txt","content":"HELLO\\n"}'}}]},
+ {"role": "tool", "tool_call_id": "call_1", "content": "Wrote 6 bytes to kc.txt"},
+ {"role": "assistant", "content": "DONE"},
])
- assert state["final"] == "done. DONE"
+ assert state["final"] == "DONE"
call = out[0]["message"]["content"][0]
- assert call["type"] == "tool_use" and call["name"] == "WriteFile" and call["id"] == "call_1"
- # arguments arrive as a JSON STRING (OpenAI's shape) and must reach the trace as an object
- assert call["input"] == {"path": "hello.txt", "content": "hi"}
+ assert call == {"type": "tool_use", "id": "call_1", "name": "Write",
+ "input": {"path": "kc.txt", "content": "HELLO\n"}}
res = out[1]["message"]["content"][0]
assert res["type"] == "tool_result" and res["tool_use_id"] == "call_1"
- assert "File successfully overwritten" in res["content"]
+ assert res["content"] == "Wrote 6 bytes to kc.txt"
def test_unparseable_tool_arguments_keep_the_raw_text_instead_of_dropping_the_call():
- out, _ = _body([{"role": "assistant", "content": [],
- "tool_calls": [{"id": "c9", "function": {"name": "Shell",
- "arguments": "{not json"}}]}])
+ out, _ = _norm([{"role": "assistant", "tool_calls": [{"id": "c", "function": {
+ "name": "Bash", "arguments": "{not json"}}]}])
assert out[0]["message"]["content"][0]["input"] == {"arguments": "{not json"}
-def test_unknown_line_shapes_are_dropped_not_crashed():
- """Notifications and plan displays share the stream and carry no role we render."""
- seen = {"_kimi_init": True} # the init event is emitted once, before these
- assert _kimi_to_claude({"id": "n1", "category": "task", "title": "done"}, seen) == []
- assert _kimi_to_claude({"content": "a plan", "file_path": "/tmp/p.md"}, seen) == []
-
-
-# ── the turn's end: exit code is the status, and the reason comes from stdout ─────
-def test_failure_exit_codes_are_the_signal():
- """kimi classifies provider failures ITSELF (Print._classify_provider_error): 75 EX_TEMPFAIL for
- connection/timeout/empty-response and 429/500/502/503/504, 1 for every other APIStatusError.
- So this backend needs no error-prose regex — unlike claude's `API Error:` and goose's `Ran into
- this error:`, a failed turn here never reads as a completed one. Registration point 6 is
- satisfied by the exit code, and this test is what pins that claim."""
- assert _kimi_eof({"final": "hi"}, 0) == [
- {"type": "result", "subtype": "success", "is_error": False, "result": "hi", "usage": {}}]
- for rc in (75, 1):
- ev = _kimi_eof({"final": "partial text"}, rc)[0]
- assert ev["is_error"] is True and ev["subtype"] == "error"
- # EMPTY on purpose: _run_turn_bg fills an empty result from the errbuf tail, where kimi's
- # bare stdout line ("Error code: 401 - {…}") is. A placeholder sentence would shadow the
- # real reason; the partial assistant text would report a 401 as if the model had answered.
- assert ev["result"] == ""
-
-
-def test_usage_is_empty_because_the_stream_carries_none():
- """kimi's stream-json has no token counts at all (JsonPrinter drops StatusUpdate). Per the
- 2026-09-13 decision no harness PR builds its own usage pipeline: `_relay_usage` stamps these
- rows from the provider's own bytes. goose's eof emits {} for the same reason."""
- assert _kimi_eof({"final": "x"}, 0)[0]["usage"] == {}
- assert BACKENDS["kimi"]["normalize"] is _kimi_to_claude
- assert getattr(BACKENDS["kimi"]["normalize"], "eof", None) is _kimi_eof
-
-
-# ── a lost session must not answer from an empty history ─────────────────────────
-def test_resume_lost_asks_the_store_because_argv_cannot_tell():
- """kimi MINTS a session with whatever id it is handed (find -> None -> create), so --session is
- on the command line whether or not the conversation exists. The argv heuristic every other
- backend uses would report "present" for a session that is gone — and the turn would answer from
- an empty history as a completed turn."""
- cmd, d, _ = _argv(resume_session_id="11111111-2222-3333-4444-555555555555")
- assert "--session" in cmd and "11111111-2222-3333-4444-555555555555" in cmd
- # the id IS in argv, and the session is still absent: the store is what decides
- assert _resume_lost("kimi", cmd, "11111111-2222-3333-4444-555555555555", d) == \
- "11111111-2222-3333-4444-555555555555"
-
- import hashlib
- share = pathlib.Path(d) / ".harness" / "home" / ".kimi"
- sdir = share / "sessions" / hashlib.md5(d.encode()).hexdigest() / \
- "11111111-2222-3333-4444-555555555555"
- sdir.mkdir(parents=True)
- (sdir / "context.jsonl").write_text("{}\n")
- assert _resume_lost("kimi", cmd, "11111111-2222-3333-4444-555555555555", d) is None
+def test_the_session_id_arrives_on_the_last_line_and_is_announced_from_it():
+ """The resume hint is the only line that names the session. Without an init event carrying it
+ the run loop records no conversation id and every follow-up starts a new conversation."""
+ out, _ = _norm([{"role": "assistant", "content": "hi"},
+ {"role": "meta", "type": "session.resume_hint", "session_id": SID,
+ "command": f"kimi -r {SID}", "content": f"To resume this session: kimi -r {SID}"}])
+ assert out[-1] == {"type": "system", "subtype": "init", "session_id": SID, "model": "kimi-k3"}
+ assert sum(1 for e in out if e.get("subtype") == "init") == 1
-def test_resume_lost_keeps_the_other_backends_unchanged():
- """The generalisation must not move claude/opencode/goose off their builders' own conclusion."""
- assert _resume_lost("opencode", ["opencode", "run", "hi"], "ses_a") == "ses_a"
- assert _resume_lost("opencode", ["opencode", "--session", "ses_a", "hi"], "ses_a") is None
- assert _resume_lost("goose", ["goose", "-n", "harness"], "harness") == "harness"
- assert _resume_lost("goose", ["goose", "-n", "harness", "-r"], "harness") is None
- assert _resume_lost("hermes", ["hermes"], "s1") is None # says so itself, not in the table
-
-
-# ── argv, config and environment ─────────────────────────────────────────────────
-def test_model_reaches_the_provider_through_the_config_not_the_m_flag():
- """-m names an ALIAS in config.models; the id that goes upstream is models.<alias>.model. A
- builder that put the model id on -m would be resolving it against a table that does not contain
- it, and kimi raises KeyError on that rather than substituting."""
- cmd, d, _ = _argv()
- assert cmd[cmd.index("-m") + 1] == "hr"
- cfg = (pathlib.Path(d) / ".harness" / "kimi-config.toml").read_text()
- assert 'model = "kimi-k3"' in cfg
- assert 'type = "openai_legacy"' in cfg
- assert "max_context_size = " in cfg
- # telemetry is ON by default and posts to telemetry-logs.kimi.com; there is no env kill switch,
- # which is why the config file is mandatory rather than a convenience.
- assert "telemetry = false" in cfg
- # no credential on disk: the placeholders exist only so the provider block parses
- assert "sk-t" not in cfg
-
-
-def test_the_real_key_never_reaches_the_cli_and_home_is_not_touched():
+def test_version_and_unknown_lines_are_dropped_not_crashed():
+ out, _ = _norm([{"role": "meta", "type": "system.version", "version": "2.0.0"},
+ {"role": "meta", "type": "something.new"}, {"role": "system"}, {}])
+ assert out == []
+
+
+def test_the_exit_code_is_the_status_and_a_failure_leaves_the_reason_to_the_cli_s_own_line():
+ ok = _kimi_eof({"final": "answer"}, 0)[0]
+ assert ok["is_error"] is False and ok["result"] == "answer" and ok["usage"] == {}
+ bad = _kimi_eof({"final": "half an answer"}, 1)[0]
+ assert bad["is_error"] is True and bad["result"] == "" # never report a failure as an answer
+
+
+def test_the_failure_reason_drops_the_cli_s_notes_to_a_person_at_its_terminal():
+ tail = ("error: failed to run prompt: provider.auth_error: 401 Invalid API-key provided.\n"
+ "See log: /data/workspaces/hsess1/.harness/home/.kimi-code/logs/kimi-code.log")
+ assert _failure_reason("", "", tail, 1) == \
+ "error: failed to run prompt: provider.auth_error: 401 Invalid API-key provided."
+ assert _failure_reason("", "", "To resume this session: kimi -r session_x", 1) == \
+ "exit_code=1, no diagnostic output"
+
+
+# ── the command and its environment ──────────────────────────────────────────────
+def test_the_model_is_defined_from_the_environment_and_nothing_is_written_with_a_key():
cmd, d, env = _argv()
- assert env["OPENAI_API_KEY"].startswith("hr-relay-") # the relay bearer, not sk-t
- assert env["OPENAI_BASE_URL"] != "https://up.example/v1"
- assert env["KIMI_SHARE_DIR"] == str(pathlib.Path(d) / ".harness" / "home" / ".kimi")
- assert "HOME" not in env # a dedicated share dir, so unlike qwen this never redirects HOME
- # rich.print hard-wraps at 80 in a non-tty, and a wrapped "Error code: 400 - {…}" reaches
- # errbuf as three fragments _failure_reason cannot match a refusal in.
- assert env["COLUMNS"] == "400"
- assert "--print" in cmd and cmd[cmd.index("--output-format") + 1] == "stream-json"
- assert cmd[-2] == "-p" and cmd[-1] == "do it"
+ assert cmd[:5] == ["kimi", "-p", "do it", "--output-format", "stream-json"]
+ assert env["KIMI_MODEL_NAME"] == "kimi-k3" and env["KIMI_MODEL_PROVIDER_TYPE"] == "openai"
+ assert env["KIMI_CODE_HOME"] == str(_kimi_home(pathlib.Path(d)))
+ assert env["KIMI_DISABLE_TELEMETRY"] == "1" and env["KIMI_CODE_NO_AUTO_UPDATE"] == "1"
+ assert int(env["KIMI_MODEL_MAX_CONTEXT_SIZE"]) > 0
+ # the relay stands between the CLI and the provider: neither the real key nor the real base
+ assert env["KIMI_MODEL_API_KEY"] != "sk-t" and "up.example" not in env["KIMI_MODEL_BASE_URL"]
+ for f in pathlib.Path(d).rglob("*"):
+ if f.is_file():
+ assert "sk-t" not in f.read_text(errors="replace"), f"the key was written to {f}"
+ assert not list(pathlib.Path(d).rglob("config.toml")) # no config file at all
+ # -p refuses --yolo/--auto beside it, and there is no work-dir flag: the process cwd is the workspace
+ assert not {"--yolo", "--auto", "-y", "-w"} & set(cmd)
+
+
+def test_the_operators_step_budget_reaches_the_cli_and_none_means_no_variable():
+ assert _argv(max_turns=40)[2]["KIMI_LOOP_MAX_STEPS_PER_TURN"] == "40"
+ assert "KIMI_LOOP_MAX_STEPS_PER_TURN" not in _argv()[2]
+
+
+def test_a_session_the_store_holds_is_resumed_and_one_it_does_not_hold_is_never_passed():
+ """`kimi -r <unknown id>` is exit 1 on this CLI (`Session "<id>" not found`), so passing an id
+ the store lost would fail the whole turn. The builder asks the store; the lost conversation is
+ reported through _resume_lost instead, and the turn runs fresh."""
+ d = tempfile.mkdtemp(); _store(d)
+ cmd, _, _ = _argv(d, resume_session_id=SID)
+ assert cmd[cmd.index("-r") + 1] == SID
+ assert _resume_lost("kimi", cmd, SID, d) is None
+ lost, d2, _ = _argv(resume_session_id=SID)
+ assert "-r" not in lost
+ assert _resume_lost("kimi", lost, SID, d2) == SID
+ assert _resume_lost("kimi", lost, None, d2) is None
+
+
+def test_the_store_lookup_refuses_an_id_that_is_a_path():
+ d = tempfile.mkdtemp(); _store(d)
+ home = _kimi_home(pathlib.Path(d))
+ assert _kimi_has_session(home, SID)
+ for bad in ("", "../..", "a/b", ".hidden", "session_nope"):
+ assert not _kimi_has_session(home, bad)
-def test_agent_doc_is_agents_md():
- assert _agent_doc_path("/ws", "kimi").name == "AGENTS.md"
+def test_resume_lost_keeps_the_other_backends_unchanged():
+ assert _resume_lost("claude", ["claude", "--resume", "abc"], "abc", "/x") is None
+ assert _resume_lost("claude", ["claude"], "abc", "/x") == "abc"
+ assert _resume_lost("goose", ["goose", "-n", "harness", "-r"], "harness", "/x") is None
+ assert _resume_lost("goose", ["goose", "-n", "harness"], "harness", "/x") == "harness"
+ assert _resume_lost("codex", ["codex"], "abc", "/x") is None # carries its own note
+
+
+# ── tool policy ──────────────────────────────────────────────────────────────────
+def test_disabled_tools_become_an_agent_file_by_name_on_a_new_session():
+ cmd, d, _ = _argv(tools_disabled=["Bash", "NotATool"])
+ path = pathlib.Path(cmd[cmd.index("--agent-file") + 1])
+ text = path.read_text()
+ assert text.startswith("---\n") and "disallowedTools:\n - Bash\nsubagents: []\n---" in text
+ # a withheld tool must not come back by delegation: a built-in subagent carries its own tools
+ assert "NotATool" not in text # an unknown name "never matches anything": not written
+ assert text.rstrip().endswith("${base_prompt}") # the default prompt's injections stay
+
+def test_no_agent_file_when_nothing_is_disabled_or_when_resuming():
+ assert "--agent-file" not in _argv()[0]
+ assert "--agent-file" not in _argv(tools_disabled=["NotATool"])[0]
+ d = tempfile.mkdtemp(); _store(d)
+ cmd, _, _ = _argv(d, resume_session_id=SID, tools_disabled=["Bash"])
+ assert "-r" in cmd and "--agent-file" not in cmd # the CLI refuses the two together
-# ── tool policy: the trap that makes "hard" enforcement real or a lie ────────────
-def test_excluded_tools_are_written_as_paths_never_bare_names():
- """MEASURED on 1.50.0: exclude_tools matches tool PATHS. In one probe both "Shell" (bare name)
- and "kimi_cli.tools.web:FetchURL" (path) were excluded — FetchURL disappeared from the tools
- array the model received and Shell did NOT. A bare name is a silent no-op, and the console
- would report the tool as off while the model still had it."""
- cmd, d, _ = _argv(tools_disabled=["Shell", "FetchURL"])
- spec = json.loads((pathlib.Path(d) / ".harness" / "kimi-agent.yaml").read_text())
- assert spec["agent"]["extend"] == "default"
- assert spec["agent"]["exclude_tools"] == ["kimi_cli.tools.shell:Shell",
- "kimi_cli.tools.web:FetchURL"]
- assert "Shell" not in spec["agent"]["exclude_tools"]
- assert "--agent-file" in cmd
-
-
-def test_no_agent_file_when_nothing_is_disabled():
- cmd, d, _ = _argv()
- assert "--agent-file" not in cmd
- assert not (pathlib.Path(d) / ".harness" / "kimi-agent.yaml").exists()
-
-
-def test_every_tool_path_is_a_module_path():
- for name, path in _KIMI_TOOL_PATHS.items():
- assert path.startswith("kimi_cli.tools.") and ":" in path, (name, path)
-
-
-# ── MCP ──────────────────────────────────────────────────────────────────────────
-def test_mcp_streamable_http_uses_url_not_httpurl():
- """The one field that differs from _qwen_settings, which inherited gemini-cli's `httpUrl`.
- kimi parses the config with fastmcp's MCPConfig, where streamable HTTP is `url`."""
- cmd, d, _ = _argv(mcp_servers=[{"name": "deepwiki", "url": "https://mcp.deepwiki.com/mcp",
- "headers": {"X-K": "v"}}])
- cfg = json.loads((pathlib.Path(d) / ".harness" / "kimi-mcp.json").read_text())
- assert cfg == {"mcpServers": {"deepwiki": {"url": "https://mcp.deepwiki.com/mcp",
- "transport": "http", "headers": {"X-K": "v"}}}}
- assert "--mcp-config-file" in cmd
-
-
-
-def test_a_url_server_carries_the_transport_the_harness_declared(tmp_path):
- """kimi's client (fastmcp) guesses a url server's transport from the PATH when the config does
- not say: SSE iff the path matches /sse(/|?|&|$), streamable HTTP otherwise. A harness that
- declared `transport: sse` for a server at any other path would be dialed as streamable HTTP,
- and on this CLI a server that cannot be reached is fatal to the turn. So the declared transport
- is written, and the url's spelling decides nothing."""
- from server import _kimi_mcp_config
- cfg = _kimi_mcp_config(tmp_path, [
+
+def test_the_tool_names_are_the_captured_array():
+ assert {"Bash", "Read", "Write", "Edit", "Grep", "Glob", "FetchURL", "Skill", "Agent"} <= set(_KIMI_TOOLS)
+ assert "WebSearch" not in _KIMI_TOOLS and len(set(_KIMI_TOOLS)) == len(_KIMI_TOOLS)
+
+
+# ── MCP, skills, instructions ────────────────────────────────────────────────────
+def _mcp(d):
+ return json.loads((_kimi_home(pathlib.Path(d)) / "mcp.json").read_text())["mcpServers"]
+
+
+def test_mcp_servers_carry_the_transport_the_harness_declared():
+ _, d, _ = _argv(mcp_servers=[
{"name": "events", "transport": "sse", "url": "https://example.test/events"},
- {"name": "api", "transport": "http", "url": "https://example.test/mcp"},
- ])
- servers = json.loads(cfg.read_text())["mcpServers"]
- assert servers["events"] == {"url": "https://example.test/events", "transport": "sse"}
- assert servers["api"] == {"url": "https://example.test/mcp", "transport": "http"}
-
-def test_no_mcp_flag_when_no_servers():
- cmd, _, _ = _argv()
- assert "--mcp-config-file" not in cmd
-
-
-# ── the relay repair kimi needs ──────────────────────────────────────────────────
-def test_null_reasoning_effort_is_dropped_before_the_provider_sees_it():
- """kimi sends `reasoning_effort: null` on every request and Vercel's AI Gateway answers HTTP
- 400 ("Invalid option: expected one of …"), measured twice in one live turn — so without this
- every kimi turn on that gateway fails before it begins. Null means "unset"; deleting the key
- says the same thing in a shape every endpoint accepts."""
- body = json.dumps({"model": "m", "reasoning_effort": None,
- "messages": [{"role": "user", "content": "hi"}]}).encode()
- out = json.loads(_normalize_openai_chat_body(body))
- assert "reasoning_effort" not in out
- assert out["messages"] == [{"role": "user", "content": "hi"}]
-
-
-def test_a_real_reasoning_effort_is_left_alone():
- """Only null is touched: a chosen effort is the caller's, and _set_reasoning_effort_none sets
- "none" deliberately elsewhere."""
- for value in ("none", "minimal", "high"):
- body = json.dumps({"reasoning_effort": value,
- "messages": [{"role": "user", "content": "hi"}]}).encode()
- assert json.loads(_normalize_openai_chat_body(body))["reasoning_effort"] == value
-
-
-# ── conversation continuity: the bug the support matrix found ────────────────────
-def test_the_first_turn_names_the_session_so_the_second_can_continue_it():
- """MEASURED FAILURE this pins: with --session added only on a resume, the first turn wrote its
- history under an id nobody could name again, so every follow-up silently started a new
- conversation in the same workspace. The support matrix's recycle scenario failed on every kimi
- row while first/follow-up/switch passed — those three never ask the agent to remember
- anything, so nothing else noticed."""
- cmd, _, _ = _argv() # a FIRST turn: no resume id
- assert "--session" in cmd
- assert cmd[cmd.index("--session") + 1] == _KIMI_SESSION_NAME
-
-
-def test_the_normalizer_reports_the_session_id_or_nothing_can_resume():
- """_run_turn_bg records the conversation id ONLY from a system/init event, and that recorded id
- is what the next turn resumes with. kimi's own stream carries no session id anywhere, so the
- runner mints one and announces it here."""
- out, _ = _norm([{"role": "assistant", "content": "hi"}])
- init = out[0]
- assert init["type"] == "system" and init["subtype"] == "init"
- assert init["session_id"] == _KIMI_SESSION_NAME
-
-
-def test_the_init_event_is_emitted_once_per_turn():
- out, _ = _norm([{"role": "assistant", "content": "one"},
- {"role": "assistant", "content": "two"}])
- assert len([e for e in out if e.get("subtype") == "init"]) == 1
-
-
-# ── the Plugins sub-protocol (UHP 2026-09-12) ────────────────────────────────────
+ {"name": "api", "transport": "http", "url": "https://example.test/mcp", "headers": {"X-K": "v"}},
+ {"name": "local", "command": "/ws/launch.sh", "args": ["--root", "/p"], "env": {"A": "1"}, "cwd": "/p"}])
+ got = _mcp(d)
+ assert got["events"] == {"url": "https://example.test/events", "transport": "sse"}
+ assert got["api"] == {"url": "https://example.test/mcp", "headers": {"X-K": "v"}} # no transport = HTTP
+ assert got["local"] == {"command": "/ws/launch.sh", "args": ["--root", "/p"], "env": {"A": "1"}, "cwd": "/p"}
+
+
+def test_the_mcp_file_is_rewritten_every_turn_so_a_removed_server_is_gone():
+ d = tempfile.mkdtemp()
+ _argv(d, mcp_servers=[{"name": "api", "url": "https://example.test/mcp"}])
+ assert "api" in _mcp(d)
+ _argv(d)
+ assert _mcp(d) == {}
+
+
def test_a_plugins_stdio_server_reaches_kimi_as_command_and_args():
- """_plugin_launchers bakes env, cwd and the ${PLUGIN_ROOT}/${PLUGIN_DATA} placeholders into one
- launcher script so every backend writer sees the same {name, command, args} — "none of the nine
- has to learn env or cwd". kimi parses its file with fastmcp's MCPConfig, whose stdio entry is
- exactly that shape, so the branch _kimi_mcp_config already had is all a plugin needs."""
- cmd, d, _ = _argv(mcp_servers=[
- {"name": "probe", "command": "/ws/.harness/plugin-data/demo/.launch-probe.sh",
- "args": ["--x", "1"]},
- {"name": "vault", "url": "https://mcp.example.invalid/mcp"}])
- cfg = json.loads((pathlib.Path(d) / ".harness" / "kimi-mcp.json").read_text())["mcpServers"]
- assert cfg["probe"] == {"command": "/ws/.harness/plugin-data/demo/.launch-probe.sh",
- "args": ["--x", "1"]}
- assert cfg["vault"]["url"].startswith("https://")
- assert "--mcp-config-file" in cmd
-
-
-# The companion test that asserted membership of _STDIO_MCP_BACKENDS is gone with the set itself:
-# upstream (#185) stopped declaring any transport missing, because the runner now hands every client
-# one launcher shape and bridges SSE and streamable HTTP over stdio for the ones that cannot speak
-# them. Nothing about kimi changed — its writer already emitted {command, args} — so what is left to
-# pin is the writer's output above, and that is where the value was.
-
-
-def test_the_operators_step_budget_reaches_the_cli():
- """MEASURED FAILURE this pins: the gateway's step budget reaches the runner as max_turns and
- every other backend passes it on (claude and goose as --max-turns), but this builder dropped it.
- A turn was then bounded only by kimi's own default of 1000 steps per turn (config.py
- max_steps_per_turn, raised 500 -> 1000 upstream), which on a slow reasoning model is HOURS: in
- the vercel column gpt-5.6-luna's switch ran 8,754s and gpt-5.5's artifact 7,418s, against 7-30s
- for the same scenarios on other ids."""
- cmd, _, _ = _argv(max_turns=12)
- assert "--max-steps-per-turn" in cmd
- assert cmd[cmd.index("--max-steps-per-turn") + 1] == "12"
-
-
-def test_no_budget_means_no_flag_rather_than_a_number_of_our_own():
- """An operator who set none gets kimi's own default, not one invented here."""
- cmd, _, _ = _argv()
- assert "--max-steps-per-turn" not in cmd
-
-
-
-def test_the_failure_reason_keeps_the_sentence_and_drops_the_cli_resume_hint():
- """kimi follows a failure with "To resume this session: kimi -r <id>", advice for a person at
- a terminal the product does not have. The sentence that says what failed is the reason; the
- hint is not, and it names a command the product never shows."""
- from server import _failure_reason
- tail = ("Unknown error: Failed to connect MCP servers: {'dead': McpError('Timed out')}\n"
- "To resume this session: kimi -r harness")
- reason = _failure_reason("", "", tail, 1)
- assert reason == "Unknown error: Failed to connect MCP servers: {'dead': McpError('Timed out')}"
- assert _failure_reason("", "", "To resume this session: kimi -r harness", 1) == "exit_code=1, no diagnostic output"
+ """_plugin_launchers hands every writer {name, command, args}; that is mcp.json's stdio entry."""
+ _, d, _ = _argv(mcp_servers=[{"name": "probe", "command": "/ws/.harness/plugins/x/launch-probe.sh", "args": []}])
+ assert _mcp(d)["probe"] == {"command": "/ws/.harness/plugins/x/launch-probe.sh", "args": []}
+
+
+def test_skills_dir_is_named_only_when_there_are_skills():
+ assert "--skills-dir" not in _argv()[0]
+ cmd, _, _ = _argv(skills_dir="/ws/.harness/skills")
+ assert cmd[cmd.index("--skills-dir") + 1] == "/ws/.harness/skills"
+
+
+def test_agent_doc_is_agents_md():
+ assert _agent_doc_path("/ws", "kimi").name == "AGENTS.md"
+
+
+# ── the rest of the wiring ───────────────────────────────────────────────────────
+def test_registry_and_checkpoint():
+ assert BACKENDS["kimi"]["normalize"] is _kimi_to_claude and hasattr(_kimi_to_claude, "eof")
+ assert "./.harness/home/.kimi-code/logs" in CHECKPOINT_EXCLUDE
+ assert not any(e.rstrip("/").endswith(".kimi-code/sessions") or e.rstrip("/").endswith(".kimi-code")
+ for e in CHECKPOINT_EXCLUDE), "sessions must travel or a resume dies with the sandbox"
+
+
+def test_null_reasoning_effort_is_still_dropped_in_the_relay():
+ """Kimi Code CLI 2.0.0 sends no reasoning_effort at all (captured at a stub); the repair stays
+ for any client that sends the null, and a real value is the caller's choice."""
+ assert "reasoning_effort" not in json.loads(_normalize_openai_chat_body(
+ json.dumps({"model": "m", "reasoning_effort": None, "messages": []}).encode()))
+ assert json.loads(_normalize_openai_chat_body(
+ json.dumps({"model": "m", "reasoning_effort": "high", "messages": []}).encode()))["reasoning_effort"] == "high"
+
+
+def test_an_mcp_server_the_cli_silently_ran_without_is_said_out_loud():
+ """2.0.0 runs the turn without an unreachable server and prints nothing anywhere but its log.
+ Only this turn's lines count: an older failure is not this reply's news."""
+ import datetime, time
+ d = tempfile.mkdtemp(); logs = _kimi_home(pathlib.Path(d)) / "logs"; logs.mkdir(parents=True)
+ now = time.time()
+ iso = lambda ts: datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ (logs / "kimi-code.log").write_text(
+ f'{iso(now - 3600)} ERROR mcp server unavailable server=old transport=http status=failed reason="fetch failed"\n'
+ f'{iso(now + 1)} INFO something else entirely\n'
+ f'{iso(now + 1)} ERROR mcp server unavailable server=dead transport=http status=failed reason="fetch failed"\n')
+ state = {"cwd": d, "started": now, "final": "HELLO"}
+ assert _kimi_mcp_unavailable(state) == [{"name": "dead", "reason": "fetch failed"}]
+ evs = _kimi_eof(state, 0)
+ assert evs[0] == {"type": "system", "subtype": "mcp_unavailable", "servers": [{"name": "dead", "reason": "fetch failed"}]}
+ assert evs[-1]["type"] == "result" and evs[-1]["result"] == "HELLO" and evs[-1]["is_error"] is False
+ assert _kimi_eof({"final": "x"}, 0)[0]["type"] == "result" # no cwd, no log: just the result
+
+
+def test_the_two_fields_the_cli_invents_never_reach_the_provider():
+ """Captured at a stub on 2.0.0: max_tokens 131072 on every request and reasoning_effort "high"
+ for a claude-named model. Through the product they failed gpt, claude and gemini ids on the
+ output limit, five newer Claude ids on thinking.type.enabled, and llama-3.3-70b on its window.
+ The route is born dropping both, so the provider's defaults apply as on every other base."""
+ _, _, env = _argv()
+ tok = env["KIMI_MODEL_API_KEY"]
+ flags = _HERMES_RELAY["routes"][tok][2]
+ assert set(flags["drop_fields"]) == {"max_tokens", "max_completion_tokens", "reasoning_effort"}
+ # the same budget under its other name for a gpt-named model, and the caching hint that stays
+ body = json.dumps({"model": "claude-sonnet-5", "max_tokens": 131072, "max_completion_tokens": 131072,
+ "reasoning_effort": "high", "prompt_cache_key": "session_x",
+ "messages": [], "stream": True}).encode()
+ for f in flags["drop_fields"]:
+ body = _drop_top_level_field(body, f)
+ assert json.loads(body) == {"model": "claude-sonnet-5", "prompt_cache_key": "session_x",
+ "messages": [], "stream": True}
+
+
+def test_a_hard_refusal_does_not_burn_ten_attempts():
+ assert _argv()[2]["KIMI_LOOP_MAX_ATTEMPTS_PER_STEP"] == "3"
diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.ts
index bbdeabd7..06fff959 100644
--- a/ui/src/lib/harness.ts
+++ b/ui/src/lib/harness.ts
@@ -132,13 +132,12 @@ export const OOB: OobHarness[] = [
models: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-4-maverick', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'qwen3.7-flash', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'hunyuan-3', 'minimax-m3', 'nemotron-3.5-lightning', 'nemotron-3-ultra', 'nemotron-3-super', 'ling-3.0-flash'], defaultModel: 'gpt-5.4', moreModels: 0,
systemPrompt: 'You are goose, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',
tools: [], skills: [] },
- { id: 'kimi', name: 'Kimi CLI', version: 'v1.50.0', backend: 'kimi', status: 'ready',
- // Placeholder only, like every list above: the gateway's catalog wins once fetched. Measured on
- // Vercel (46 ids, 229/230 scenarios) and Google (11 ids, 53/55); the gateway's
- // _MODEL_CATALOG["kimi"] says which ids neither column ran and why. kimi family first, since it
- // is the backend's home family.
+ { id: 'kimi', name: 'Kimi Code CLI', version: 'v2.0.0', backend: 'kimi', status: 'ready',
+ // Placeholder only, like every list above: the gateway's catalog wins once fetched. Every id was
+ // measured on Kimi Code CLI 2.0.0 (five console scenarios, 248 of 250); the gateway's
+ // _MODEL_CATALOG["kimi"] and docs/support-matrix-notes.md carry the record.
models: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.2', 'claude-fable-5-1', 'claude-fable-5', 'claude-opus-5', 'claude-sonnet-5', 'claude-opus-4.8', 'claude-opus-4.7', 'claude-sonnet-4.6', 'claude-haiku-4.5', 'gemini-3.8-flash', 'gemini-3.7-flash', 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview', 'grok-4.6', 'grok-4.5', 'grok-4.3', 'grok-4.20', 'grok-build-0.1', 'muse-spark-1.3', 'muse-spark-1.2', 'muse-spark-1.1', 'muse-glimmer-30b', 'llama-3.3-70b', 'deepseek-v4.1-flash', 'deepseek-v4-pro', 'deepseek-v4-flash', 'kimi-k3', 'kimi-k2.7-code', 'qwen3.8-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.7-max', 'qwen3.7-plus', 'glm-5.3', 'glm-5.3-flash', 'mistral-medium-3.5', 'step-3.7-flash', 'hunyuan-4-preview', 'nemotron-3.5-lightning', 'nemotron-3-super'], defaultModel: 'kimi-k3', moreModels: 0,
- systemPrompt: 'You are Kimi CLI, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',
+ systemPrompt: 'You are Kimi Code CLI, an autonomous coding agent. You work on a real git workspace with shell and file access, reading and editing files and running commands to complete the task end to end.',
tools: [], skills: [] },
];