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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
kimi: a new backend (Kimi CLI 1.50.0) (#191)
ZixiaoLd593bbe18f27
diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex d7043ae2..d4a63203 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -177,7 +177,7 @@ export HOSTNAME=0.0.0.0TOOLS="$DATA_DIR/agent-tools"export PATH="$TOOLS/bin:$PATH"export NODE_PATH="$TOOLS/lib/node_modules"-export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose}"+export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi}"wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }# The executable IS the definition of "installed" — an installer that exits 0 without producing@@ -196,6 +196,7 @@ backend_bin() {cline) echo "$TOOLS/bin/cline" ;;omp) echo "$TOOLS/bin/omp" ;;goose) echo "$TOOLS/bin/goose" ;;+ kimi) echo "$TOOLS/bin/kimi" ;;esac}@@ -239,6 +240,61 @@ 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.+#+# 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.+#+# 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.+#+# 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.+install_kimi() {+ case "$(uname -m)" in+ x86_64) km_arch="x86_64"; km_sha="10ccaa26ee7f5bb43f7c05baf808c11cd0160710b07ac422382d1d1923f3dab6" ;;+ aarch64|arm64) km_arch="aarch64"; km_sha="de235322f48abe63e7a8d737f39f0c00fecf724f1dfaa1ae02491bb773ae8070" ;;+ *) 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+ # 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] 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_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)"+ 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)"+ [ -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; }+ rm -rf "$km_tmp"+}++install_goose() {case "$(uname -m)" inx86_64) gs_arch="x86_64"; gs_sha="6389eea4440178de006fa148d466ac411021315ff7f72b1014beae2d445851e2" ;;@@ -385,6 +441,11 @@ install_backends() {try_install "goose" install_goose || truefi+ if wanted kimi && [ ! -x "$(backend_bin kimi)" ]; then+ echo "[harnessrouter] installing Kimi CLI (Apache-2.0)…"+ try_install "Kimi 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# already has a venv: dsh-ready names the version it was built for, and a mismatch rebuilds# the venv (sessions live under ~/.dsh, not in it). The 0.1.0rc7 -> 0.1.2rc1 move is wherediff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex e669f119..af9e3f04 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -159,7 +159,7 @@ Wait for `ready on :3000`, then open the browser:[harnessrouter] installing goose (Apache-2.0)…[harnessrouter] installing DeepSeek Harness (MIT, developer preview — version-pinned)…[harnessrouter] installing Hermes (check its upstream license before use)…-[harnessrouter] data=/data backends available: claude codex hermes pi dsh opencode qwen gemini cline omp goose+[harnessrouter] data=/data backends available: claude codex hermes pi dsh opencode qwen gemini cline omp goose kimi[harnessrouter] ready on :3000```@@ -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 |-| `openai` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |-| `openrouter` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |-| `azure-foundry` | Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |-| `google` | Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi |+| `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 || `bedrock` | Claude Code, Hermes |-| `tokenrouter` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Gemini CLI, Cline, Oh My Pi, goose |-| `vercel` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |-| `llmtr` | Claude Code, Codex, Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |-| `custom` | Claude Code, Codex (Responses format), Hermes, Pi, DeepSeek Harness, OpenCode, Qwen Code, Cline, Oh My Pi, goose |+| `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 |</details>@@ -650,7 +650,7 @@ Backends are installed into your data volume rather than baked into the image, swant is a run-time setting:```bash-docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose ... # the default+docker run -e HR_BACKENDS=claude,codex,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi ... # the defaultdocker run -e HR_BACKENDS=opencode ... # lean```diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.mdindex fd498b92..9da882ee 100644--- a/docs/support-matrix-notes.md+++ b/docs/support-matrix-notes.md@@ -312,3 +312,194 @@ re-run once.recall misses on muse-spark-1.1; hermes passed its re-run, opencode missed twice. muse-spark-1.1 stayson opencode because the same pair passes on Vercel; the miss is recorded. OpenRouter's no-channel setis empty.++## The kimi backend (Kimi CLI 1.50.0) — 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+a substitute for a column. `docs/support-matrix.md` is rendered from+`docs/support-matrix-results.json` and is deliberately untouched by this change.++**Verified by running the real image, not only by reading the CLI.** `docker build` of this tree,+then a container with `HR_BACKENDS=kimi`: `install_kimi` downloaded the pinned archive, the digest+check passed, and the container reported `backends available: kimi` with+`/data/agent-tools/bin/kimi --version` answering `kimi, version 1.50.0`. The two pinned digests were+also compared against upstream's own published `.sha256` files and match character for character.++**One real turn was run end to end in that image**, against Vercel, with the argv and the+`config.toml` the runner generates — not a hand-written approximation. It is an A/B that settles the+`reasoning_effort` question: the same command sent straight to Vercel answers+`Error code: 400 - {… 'param': 'reasoning_effort' …}`, on ONE stdout line (so the `COLUMNS=400`+mitigation for rich's 80-column wrapping works); sent through `_normalize_openai_chat_body`, the turn+completes and prints `{"role":"assistant","content":"PROBE-OK"}` with exit 0. That line is also the+shape `_kimi_to_claude` expects — `content` a plain STRING, not a list of blocks.++Two more things that turn settled, from the state it left behind rather than from the notes:++- `Connection error.` really does exit **75**, observed when the relay was not yet listening.+- The `_resume_lost` probe matches kimi's own store: `md5("/tmp/ws")` is `59fa73ff…`, which is+ exactly the directory kimi created, and `context.jsonl` is in it — so the probe reports the+ session PRESENT for the id that ran and LOST for one that never existed.++**A failed turn reads as failed, by exit code rather than by prose.** kimi classifies provider+failures itself (`Print._classify_provider_error`): 75 (EX_TEMPFAIL) for connection, timeout and+empty-response errors and for HTTP 429/500/502/503/504; 1 for every other status error and for the+catch-all. The reason arrives as a bare non-JSON line on stdout (`Error code: 401 - {…}`,+`Connection error.`), which the runner already collects and `_failure_reason` already prefers. This+is the first backend here that needs no error-prose regex at all — contrast claude's `API Error: …`+and goose's `Ran into this error: …`, both of which are narrated as assistant text.++**The CLI reports no served model anywhere**, so every kimi row is substitution-checked from the+relay (`_relay_served_model`), the same path goose, cline and qwen use. Measured: a live turn's+upstream SSE carried `"model":"openai/gpt-5.4-nano"`, which `_served_model_in` matches. Separately,+kimi does not rewrite the id it is given — the value reaches the provider verbatim, and its only+alias machinery raises `KeyError` on a miss rather than substituting, so the gemini `resolveModel`+class of silent substitution is absent.++**`reasoning_effort: null` is on every kimi request and Vercel's AI Gateway answers it with HTTP+400** ("Invalid option: expected one of \"none\"|\"minimal\"|…", reproduced twice in one live turn).+Without the relay dropping that key, every kimi turn on Vercel fails before it begins. The drop is+in `_normalize_openai_chat_body`, so it applies to any backend that sends the same shape.++**An unreachable MCP server KILLS the turn on this backend** — `Unknown error: Failed to connect+MCP servers: {…}` and exit 1, verified live against a dead server — it does not degrade. That is+the opposite of goose (warns on stderr, continues) and of hermes (disables HTTP MCP with a log+line), and it means the visibility UHP §4.1 asks for is satisfied loudly here, at the cost of a+flaky third-party server taking every turn with it. The matrix probes the server once before a run+and skips the MCP half when it is unreachable, so the custom-harness dimension is unaffected; a+user-configured server that dies mid-session is the real exposure.++**A resumed session that is gone is silent.** `--session <unknown-id>` does not error: kimi mints a+session with that id and answers from an empty history, with no stdout line and no change of exit+code. `_resume_lost`'s kimi arm therefore asks the store — `sessions/<md5(work_dir)>/<id>/context.jsonl`,+kimi's own predicate — rather than reading argv, where the id is present either way.++**Tool policy is real but path-keyed.** `exclude_tools` matches tool PATHS+(`kimi_cli.tools.shell:Shell`), not the names the model sees; a bare name is a silent no-op.+Measured in one probe: excluding `kimi_cli.tools.web:FetchURL` removed it from the tools array,+while excluding `Shell` did not. `tool_enforcement: "hard"` is honest only because+`runner/server.py`'s `_KIMI_TOOL_PATHS` translates, and a gateway test pins the catalog's ids equal+to that table's keys.++**`SearchWeb` and `ReadMediaFile` are not offered.** Both ship in kimi's default agent and both+raise `SkipThisTool` unless a Moonshot search key / a vision-capable model is configured, so+neither is ever constructed on this deployment.++**Token usage is absent from the stream**, not merely named differently: `JsonPrinter` drops every+`StatusUpdate`. kimi's result events carry `usage: {}` until `_relay_usage` lands, which is the+agreed division of work — no harness PR builds its own usage pipeline.++**The Vercel column, measured 2026-09-16 (candidate built from this branch, kimi 1.50.0).**+46 ids, five scenarios each: **229 of 230 scenarios passed**, every turn served by the connection+under test — no foreign connection on any pair.++The single failure is `gemini-2.5-flash-lite`'s artifact turn, with the provider's own words: "The+API returned an empty response". It is **deterministic through this product** (three independent+runs on two different builds, same id, same scenario, same sentence) and takes ~175s, which is kimi+retrying the empty response until `max_retries_per_step` is exhausted rather than one slow call.++What it is NOT, each eliminated by measurement rather than reasoning:+- not the request shape — the same conversation replayed by hand against the same provider answers+ correctly, non-streaming and streaming, with one tool and with the full fifteen, and with a+ system prompt padded to the size kimi sends;+- not the `reasoning_effort` repair, which is applied identically on every other id here;+- not a transient — `qwen3.7-max` failed the same scenario in the previous run with "Upstream stream+ ended before terminal chunk" and PASSED here, so that one was the flake this is not.++What could not be reproduced outside the product: replaying the exact four-step sequence+(first, follow-up, switch to the partner model, artifact) through the real kimi binary against the+same provider, with the workspace contract in AGENTS.md, completes all four turns and writes the+file. So the remaining variable is something the gateway path adds that a CLI replay does not.++**The Google column then said what one column could not.** Same harness, same scenarios, 11 ids,+**53 of 55 scenarios passed**, no foreign connection. The two failures are+`gemini-2.5-flash`'s artifact turn — *the same sentence*, "The API returned an empty response" — and+the recycle that followed it with nothing to recall. And `gemini-2.5-flash-lite`, which fails+deterministically on Vercel, **passes all five here**:++| id | Vercel | Google |+|---|---|---|+| `gemini-2.5-flash-lite` | artifact fails, empty response | 5/5 |+| `gemini-2.5-flash` | 5/5 | artifact fails, empty response |++So it is NOT the channel — both show it — and NOT one id, since each channel's healthy member is the+other's casualty. What survives is the shape: **a gemini-2.5-class model returns an empty response on+the artifact turn**, the one that follows a model switch and asks for a file, and which member of the+family trips differs by provider (most likely the actual build behind the same name on each). One+column alone would have supported the wrong conclusion — the Vercel notes above nearly recorded it as+a property of that id on that channel.++Recorded as rows that fail with the provider's reproduced text, which is what the rules ask for.++Vercel's answers carry the aggregator's vendor prefix (`openai/gpt-5.4`, `anthropic/claude-opus-5`,+`alibaba/qwen3.7-max`), which rule 2 counts as the same model.++**Five ids Vercel does not serve at all**, so this column never ran them: `claude-fable-5-1`,+`gemini-3-flash-preview`, `grok-4.20`, `hunyuan-4-preview`, `nemotron-3-super`. They remain in the+catalog because other providers serve them; they are unmeasured HERE, not rejected.++**The four slow ids: the cause was found, and it was ours.** kimi's own default is **1000 steps per+turn** (`config.py` `max_steps_per_turn`, raised from 500 upstream), and `_build_kimi` never passed+the operator's step budget — the gateway's `max_step` reaches the runner as `max_turns` and every+other backend forwards it (claude and goose as `--max-turns`), but this builder dropped it. On a+fast model the default is invisible; on a slow reasoning one, 1000 steps at 10-30s each is three to+eight hours, which is exactly the range that was measured. Now forwarded as+`--max-steps-per-turn`. Reaching the cap is visible on this CLI rather than silent — it raises+`MaxStepsReached`, which arrives as its own stdout line with a non-zero exit — so a truncated turn+reads as truncated, unlike goose, which reports nothing at its cap.++Two hypotheses were tested and rejected before that one: the relay's repair loop is bounded+(`attempt < 2`), and the `reasoning_effort` shape is not the trigger — measured directly against+Vercel with function tools on `gpt-5.6-sol`, `reasoning_effort: null` is a 400 in 0s while both the+key deleted (what the relay does for kimi) and `reasoning_effort: "none"` answer 200 in 1-2s.++**What was measured of those four before the fix**, with the budget still unbounded: What was measured of them, before the exclusion:+`gpt-5.6-sol` and `gpt-5.6-terra` passed all five scenarios but took HOURS each; `gpt-5.6-luna`'s+switch hung 8,754s and then failed; `gpt-5.5`'s switch hung 2,200s and its artifact 7,418s. The+mechanism is not established. The cline and qwen catalog entries already record that the gpt-5.6+line answers 400 through aggregator chat/completions when the request carries function tools, which+`_set_reasoning_effort_none` repairs per (route, model) — but on those backends that is a FAST+error, and here it is an hours-long wait, which is not the same shape. Whether this is kimi's or the+channel's is an open question: aider and openhands have no data on those four ids at all.++**The custom-harness dimension passes, and deepwiki works here.** All claims on the kimi row:+the skill and the tool policy were stored and came back on a read, the bundle reached the agent (the+answer carried the token that exists only inside the script), the script ran (`stamp.txt` among the+turn's produced files), and the declared MCP server was stored and called — `read_wiki_structure`,+against `https://mcp.deepwiki.com/mcp`, which needed no override. Worth recording because goose+cannot handshake with deepwiki and its row needs `MCP_URL=https://mcp.context7.com/mcp`; kimi's does+not.++**But `disabled_tool_unused` passes VACUOUSLY on this row, as it does on aider, qwen, gemini and+cline.** The dimension switches off the fixed id `WebSearch`, and kimi's catalog does not list it —+deliberately, because it is never constructed without a Moonshot search key. Nothing named the tool+because nothing could, so that claim proves the policy was STORED and nothing about whether it TOOK+EFFECT.++**Measured separately, so the `hard` claim is not left resting on that.** A one-off experiment — the+dimension run once with the disabled tool changed to `Shell`, a tool kimi has and this task needs;+the shared script was NOT changed, and this is a recommendation rather than a diff:++| | tools the turn used |+|---|---|+| Shell allowed | `ReadFile`, `Shell` |+| Shell disabled | `ReadFile`, `ReadFile`, `WriteFile` |++Shell is absent, and the agent reached the same result another way. The policy really withholds, so+`tool_enforcement: "hard"` on this base is measured rather than asserted.++**That experiment also exposed something about claim 4 that is the dimension's, not kimi's.** With+Shell disabled the agent could execute nothing, yet `script_ran` still passed and `stamp.txt` still+appeared: the agent read SKILL.md, read the script, and wrote the file itself. "The script actually+ran" is judged by the file being among the produced files, and an agent that can read the script can+produce that file without running it. Same shape as the vacuous pass above — a gap between the+judge and the thing it means to prove — and harder to notice, since nothing about the row looks+wrong. Two suggestions, both the maintainer's call: let the dimension name the tool it disables+(a base that has no `WebSearch` could disable one it has), and make the script write something the+agent cannot predict from reading it.++**Known open question: `max_context_size`.** kimi requires one per model and plans compaction+against it; the catalog carries no per-id window, so `KIMI_CONTEXT_WINDOW` holds one value for all+ids, exactly as `CODEX_CONTEXT_WINDOW` does for codex. Being wrong changes WHEN the agent compacts,+never whether it answers: too large lets a thread overflow the real window (the provider then+errors), too small compacts early and wastes tokens.diff --git a/gateway/app.py b/gateway/app.pyindex 316f98a0..e5edbaa2 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -1061,6 +1061,15 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("openrouter", "opencode"): "openai-api",("tokenrouter", "opencode"): "tokenrouter", ("vercel", "opencode"): "tokenrouter",("llmtr", "opencode"): "tokenrouter",+ # kimi reaches every provider the same way qwen does — one OpenAI-compatible surface through+ # the loopback relay — so these rows are qwen's, verbatim, with the backend renamed.+ ("anthropic", "kimi"): "anthropic", ("openai", "kimi"): "openai",+ ("azure-foundry", "kimi"): "azure",+ ("openrouter", "kimi"): "openai-api",+ ("tokenrouter", "kimi"): "tokenrouter", ("vercel", "kimi"): "tokenrouter",+ ("llmtr", "kimi"): "tokenrouter",+ ("custom", "kimi"): "openai-api",+ ("google", "kimi"): "openai-api",("anthropic", "qwen"): "anthropic", ("openai", "qwen"): "openai",("azure-foundry", "qwen"): "azure",("openrouter", "qwen"): "openai-api",@@ -1123,6 +1132,7 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("harnessrouter", "hermes"): "openai-api", ("harnessrouter", "pi"): "tokenrouter",("harnessrouter", "omp"): "tokenrouter", ("harnessrouter", "dsh"): "tokenrouter",("harnessrouter", "opencode"): "tokenrouter", ("harnessrouter", "qwen"): "tokenrouter",+ ("harnessrouter", "kimi"): "tokenrouter",("harnessrouter", "cline"): "tokenrouter", ("harnessrouter", "gemini"): "google",("harnessrouter", "goose"): "tokenrouter",}@@ -4588,7 +4598,7 @@ _CUSTOM_FORMAT_BACKENDS = {# OPENAI_BASE_PATH through the relay). Its own anthropic provider takes ANTHROPIC_HOST with no# base-path counterpart and is unprobed, so a custom ANTHROPIC endpoint stays off this set# until it is — the picker greys out what the router cannot actually run.- "openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose"},+ "openai": {"hermes", "opencode", "pi", "dsh", "qwen", "cline", "omp", "goose", "kimi"},"anthropic": {"claude", "opencode", "pi", "dsh", "omp"},# The OpenAI Responses API: what codex speaks, and only codex among the agent CLIs here."responses": {"codex"},@@ -6005,6 +6015,42 @@ _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.+ #+ # 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.+ #+ # 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.+ "kimi": {"default": "kimi-k3",+ "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"]},"qwen": {"default": "qwen3.7-max","models": ["qwen3.7-max", "qwen3.8-max","gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5",@@ -6136,7 +6182,10 @@ 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"})-CHAT_ONLY_BACKENDS = ("qwen", "cline", "goose")+# 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.+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# 2026-08-19 on the TokenRouter connection with a data-URI image in a user message:@@ -13244,6 +13293,32 @@ _BASE_CATALOG: dict[str, dict] = {# as claude's permissions.deny and pi's -xt, not the instruction-only tier."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 "+ "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"),+ ("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.+ "tool_enforcement": "hard",+ },"qwen": {"label": "Qwen Code", "backend": "qwen", "status": "ready","system_prompt": ("You are Qwen Code, an autonomous coding agent. You work on a real git "diff --git a/gateway/tests/test_catalog_kimi_tool_paths.py b/gateway/tests/test_catalog_kimi_tool_paths.pynew file mode 100644index 00000000..9b016679--- /dev/null+++ b/gateway/tests/test_catalog_kimi_tool_paths.py@@ -0,0 +1,48 @@+"""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.+"""+import os+import pathlib+import sys++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+++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}")+++def test_kimi_claims_hard_enforcement_and_earns_it():+ assert A._BASE_CATALOG["kimi"]["tool_enforcement"] == "hard"+ assert A._BASE_CATALOG["kimi"]["backend"] == "kimi"+++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_kimi_is_chat_completions_only():+ """Its provider type is openai_legacy, so a Responses-API-only id would fail on send."""+ assert "kimi" in A.CHAT_ONLY_BACKENDSdiff --git a/runner/server.py b/runner/server.pyindex fe8332f0..cd5af720 100644--- a/runner/server.py+++ b/runner/server.py@@ -239,22 +239,69 @@ def _own_tree(root: str, uid: int, from_uids: set[int]) -> None:continue-def _resume_lost(backend: str, cmd: list[str], resume_session_id: str | None) -> str | None:- """The session id the caller asked to continue when the built command does not carry it: the- builder looked for the session in the workspace, did not find it, and started fresh (claude's- --resume, opencode's --session). hermes says so itself; codex carries its own note. Four- hosted opencode sessions answered three recalls each with "there is no earlier message" as+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."""+ return session_id in cmd+++def _goose_session_present(cwd: str, cmd: list[str], session_id: str) -> bool:+ """goose carries the id as `-n <name>` on EVERY turn — it names a fresh session as well as+ selecting an existing one — so the id being present in cmd says nothing. `-r` is the flag that+ means "continue", and _build_goose adds it only once the session was found in this workspace's+ database."""+ return "-r" in cmd+++# How each backend answers "is the conversation the caller asked to continue actually there?".+#+# ASK THE STORE, DO NOT SEARCH IT. goose's first version searched the sessions database for the+# session NAME; the name was `harness`, which also occurs in the workspace path that tool output+# carries, so a database holding one message and no session matched — a false positive that added+# -r and failed the turn with "No session found", the very failure the check existed to prevent.+# A backend whose builder already performs the lookup can answer from argv (that IS the builder's+# conclusion, not a guess about it); a backend that cannot must query its store the way the CLI+# queries it.+#+# A backend absent from this table cannot lose a session, or has not been measured — either way it+# never reports one lost. Adding a backend here is registration point 5.+_SESSION_PRESENT = {+ "claude": _argv_session_present,+ "opencode": _argv_session_present,+ "goose": _goose_session_present,+ "kimi": _kimi_session_present,+}+++def _resume_lost(backend: str, cmd: list[str], resume_session_id: str | None,+ cwd: str = "") -> str | None:+ """The session id the caller asked to continue when that conversation is not there: the turn+ will run, and it will answer from an empty history unless someone says so.++ Four hosted opencode sessions answered three recalls each with "there is no earlier message" ascompleted turns (2026-09-08): the history was lost to the 2026-09-06 restore burst, and nothing- told the person. The gateway renders the event as a note at the top of the reply."""- if backend not in ("opencode", "claude", "goose") or not resume_session_id:+ told the person. The gateway renders the event this produces as a note at the top of the reply.++ hermes says so itself and codex carries its own note, so neither is in the table."""+ probe = _SESSION_PRESENT.get(backend)+ if probe is None or not resume_session_id:return None- if backend == "goose":- # goose carries the id as `-n <name>` on EVERY turn — it names a fresh session as well as- # selecting an existing one — so the id being present in cmd says nothing. `-r` is the- # flag that means "continue", and _build_goose adds it only once the session was found in- # this workspace's database.- return None if "-r" in cmd else resume_session_id- return None if resume_session_id in cmd else resume_session_id+ return None if probe(cwd, cmd, resume_session_id) else resume_session_iddef _isolate_session(ws: str) -> None:@@ -396,10 +443,19 @@ CLINE_DEFAULT_MODEL = os.environ.get("CLINE_DEFAULT_MODEL", "gpt-5.4")DSH_DEFAULT_MODEL = os.environ.get("DSH_DEFAULT_MODEL", "deepseek-v4-pro")OMP_DEFAULT_MODEL = os.environ.get("OMP_DEFAULT_MODEL", "gpt-5.4")GOOSE_DEFAULT_MODEL = os.environ.get("GOOSE_DEFAULT_MODEL", "gpt-5.4")+KIMI_DEFAULT_MODEL = os.environ.get("KIMI_DEFAULT_MODEL", "kimi-k3")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_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")AZURE_OPENAI_BASE_URL = os.environ.get("AZURE_OPENAI_BASE_URL", "")@@ -793,6 +849,15 @@ def _write_skills(cwd: str, skills: list[dict], backend: str = "claude") -> list# frontmatter does not match its directory name.rootrels = [".harness/goose/config/skills"]entryroot = ".harness/goose/config/skills"+ elif backend == "kimi":+ # --skills-dir "Overrides default discovery" (repeatable), so like opencode the loader+ # adapts to us and there is no per-CLI home directory to guess. Verified on 1.50.0: a skill+ # written here appeared in the system prompt under an "### Extra" scope heading with its+ # path and its frontmatter description. Default discovery would otherwise sweep+ # .kimi/skills, .claude/skills, .codex/skills and .agents/skills — including trees another+ # backend wrote — which is a second reason to name the directory explicitly.+ rootrels = [".harness/skills"]+ entryroot = ".harness/skills"elif backend == "opencode":# opencode's `skills` config key takes ARBITRARY paths ("Additional paths or URLs to# discover skills from"), so there is no per-CLI home directory to guess here — we write@@ -1124,8 +1189,12 @@ def _agent_doc_path(cwd: str, backend: str) -> pathlib.Path:return pathlib.Path(cwd) / (# goose reads AGENTS.md natively and first: its default context-file list is# ["AGENTS.md", ".goosehints"], overridable only via CONTEXT_FILE_NAMES.+ # kimi reads AGENTS.md and nothing else (no KIMI.md, no CLAUDE.md - grepped the whole+ # 1.50.0 package), merging from the project root down to the work dir, and injects the+ # content VERBATIM into the system prompt: verified live, inside a+ # "<!-- From: .../AGENTS.md -->" fence, with a behavioural instruction in it obeyed."AGENTS.md" if backend in ("codex", "hermes", "pi", "dsh", "opencode", "cline", "omp",- "goose")+ "goose", "kimi")else "CLAUDE.md")@@ -2654,13 +2723,26 @@ def _normalize_openai_chat_body(body: bytes) -> bytes:verbatim, and LLMTR's validator requires it non-empty when present ('String must contain atleast 1 character(s)', measured live on deepseek-v4-pro 2026-08-27 — the turn died rightafter its tool call). A non-empty one is meaningful interleaved thinking and passes through.+ A top-level `reasoning_effort: null` is deleted: kimi sends the key with a null value on every+ request, and Vercel's AI Gateway answers that with HTTP 400 ("Invalid option: expected one of+ \"none\"|\"minimal\"|…", measured twice in one live turn on 1.50.0), so on that gateway every+ kimi turn would fail before it began. Null is not one of the enum's options, and a client that+ sends it means "unset" — deleting it says the same thing in a shape every endpoint accepts.+ Only null is touched; a real effort value is the caller's choice and passes through, as does+ the `reasoning_effort: "none"` that _set_reasoning_effort_none sets deliberately.+Anything else — other roles, non-empty text, unparseable bodies — passes throughbyte-identical."""try:obj = json.loads(body)- if not isinstance(obj, dict) or not isinstance(obj.get("messages"), list):+ if not isinstance(obj, dict):return bodychanged = False+ if "reasoning_effort" in obj and obj["reasoning_effort"] is None:+ del obj["reasoning_effort"]+ changed = True+ if not isinstance(obj.get("messages"), list):+ return json.dumps(obj, separators=(",", ":")).encode() if changed else bodyfor m in obj["messages"]:if not isinstance(m, dict):continue@@ -3682,6 +3764,231 @@ def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, enreturn cmd+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.+#+# 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+++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:+ return None+ path = ws / ".harness" / "kimi-agent.yaml"+ 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))+ 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`.++ 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."""+ servers: dict = {}+ for i, sv in enumerate(mcp_servers or []):+ if not isinstance(sv, dict):+ continue+ 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"}+ hdrs = sv.get("headers")+ if isinstance(hdrs, dict) and hdrs:+ entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ elif sv.get("command"):+ cmd = sv["command"]+ argv = cmd if isinstance(cmd, list) else [str(cmd)]+ entry = {"command": argv[0],+ "args": [str(x) for x in argv[1:]] + [str(x) for x in (sv.get("args") or [])]}+ envv = sv.get("env")+ if isinstance(envv, dict) and envv:+ entry["env"] = {str(k): str(v) for k, v in envv.items()}+ else:+ continue+ servers[name] = entry+ if not servers:+ return None+ path = ws / ".harness" / "kimi-mcp.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps({"mcpServers": servers}, indent=2))+ return path+++def _build_kimi(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env: dict,+ 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]:+ 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)+ 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"]+ 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]+ 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++# Path A only (Gemini API Key / Google AI Studio). Unlike qwen, upstream gemini-cli speaks NO# OpenAI-compatible mode at all (that is a qwen-fork-only addition — see QWEN_PROVIDERS above),# so there is no loopback-relay trick that lets any generic OpenAI/Anthropic-shaped integration@@ -4887,6 +5194,140 @@ 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.++ 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:++ assistant text {"role":"assistant","content":"…"}+ assistant call {"role":"assistant","content":[…parts…],+ "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.++ 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+ """+ 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 == "assistant":+ out: list[dict] = list(pre)+ content = obj.get("content")+ if isinstance(content, str):+ txt = content+ elif isinstance(content, list):+ txt = "".join(str(part.get("text") or "") for part in content+ if isinstance(part, dict) and part.get("type") == "text")+ 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.+ state["final"] = txt+ out.append({"type": "assistant", "message": {"content": [{"type": "text", "text": txt}]}})+ for call in obj.get("tool_calls") or []:+ if not isinstance(call, dict):+ continue+ fn = call.get("function") if isinstance(call.get("function"), dict) else {}+ 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.+ try:+ args = json.loads(args)+ except Exception: # noqa: BLE001+ args = {"arguments": args}+ if not isinstance(args, dict):+ args = {}+ out.append({"type": "assistant", "message": {"content": [+ {"type": "tool_use", "id": tuid, "name": str(fn.get("name") or "tool"), "input": args}]}})+ 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": [+ {"type": "tool_result", "tool_use_id": str(obj.get("tool_call_id") or "tool"),+ "is_error": False, "content": text}]}}]+ return pre+++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."""+ final = state.get("final", "")+ if rc == 0:+ return [{"type": "result", "subtype": "success", "is_error": False,+ "result": final, "usage": {}}]+ return [{"type": "result", "subtype": "error", "is_error": True, "result": "", "usage": {}}]+++_kimi_to_claude.eof = _kimi_eof # type: ignore[attr-defined]++# Registry — providers/default_model/normalize per backend. The cmd build + run loop is dispatched# in turn(): claude/codex run through _run_turn_bg over stdout JSONL; hermes has its own driver# (_run_hermes_bg — DB-polling, no stdout events), so it carries no normalizer.@@ -4923,6 +5364,11 @@ 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": {"providers": sorted(KIMI_PROVIDERS), "default_model": KIMI_DEFAULT_MODEL,+ "normalize": _kimi_to_claude},}@@ -5103,6 +5549,9 @@ 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:")++def _failure_reason(refusal: str, ev_err: str, tail: str, rc: int) -> str:"""The one line that explains a failed turn, in order of how much it says: the provider'srefusal, the result event's own message, the CLI's last lines, the exit code. A normaliser's@@ -5110,6 +5559,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.+ 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 = ""return (refusal or ev_err or tail or f"exit_code={rc}, no diagnostic output")[:2000]@@ -6109,6 +6563,16 @@ def turn(req: TurnReq, identifier: str = "") -> dict:model = model or QWEN_DEFAULT_MODELcmd = _build_qwen(req.provider, auth, model, req.prompt, cwd, env,resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers)+ elif backend == "kimi":+ model = model or KIMI_DEFAULT_MODEL+ # _write_skills has already run, so the directory is on disk and can simply be named:+ # --skills-dir "Overrides default discovery", the opencode shape, so there is no per-CLI+ # home directory to guess here.+ kimi_skills = os.path.join(cwd, ".harness", "skills") if installed_skills else None+ cmd = _build_kimi(req.provider, auth, model, req.prompt, cwd, env,+ resume_session_id=req.resume_session_id, mcp_servers=req.mcp_servers,+ skills_dir=kimi_skills, tools_disabled=req.tools_disabled,+ max_turns=req.max_turns)elif backend == "gemini":model = model or GEMINI_DEFAULT_MODELcmd = _build_gemini(req.provider, auth, model, req.prompt, cwd, env,@@ -6141,7 +6605,7 @@ def turn(req: TurnReq, identifier: str = "") -> dict:resume_session_id=req.resume_session_id, mcp_config=mcp_config,disallowed_tools=req.tools_disabled, partial=bool(req.partial_messages),plugin_dirs=plugin_dirs)- resume_lost = _resume_lost(backend, cmd, req.resume_session_id)+ resume_lost = _resume_lost(backend, cmd, req.resume_session_id, cwd)_isolate_session(cwd) # everything the runner just wrote into the session is the session's nowturn_id = "turn" + uuid.uuid4().hex_evict_turns()diff --git a/runner/tests/test_kimi_backend.py b/runner/tests/test_kimi_backend.pynew file mode 100644index 00000000..1cf39d55--- /dev/null+++ b/runner/tests/test_kimi_backend.py@@ -0,0 +1,352 @@+"""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+"""+import json+import pathlib+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)+++def _argv(**kw):+ d = 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)+ return cmd, d, env+++def _norm(lines):+ state: dict = {}+ 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"},+ ])+ assert state["final"] == "done. 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"}+ 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"]+++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"}}]}])+ 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_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():+ 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"+++def test_agent_doc_is_agents_md():+ assert _agent_doc_path("/ws", "kimi").name == "AGENTS.md"+++# ── 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, [+ {"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) ────────────────────────────────────+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"+diff --git a/scripts/support-matrix/custom-harness.mjs b/scripts/support-matrix/custom-harness.mjsindex f8e921c1..44017efb 100644--- a/scripts/support-matrix/custom-harness.mjs+++ b/scripts/support-matrix/custom-harness.mjs@@ -14,7 +14,7 @@ import { chromium } from 'playwright';import crypto from 'node:crypto';const BASE = process.env.BASE;-const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose').split(','); // every built-in harness, all eleven+const BASES = (process.env.BASES || 'codex,claude-code,hermes,pi,dsh,opencode,qwen,gemini,cline,omp,goose,kimi').split(','); // every built-in harness, all twelveconst RESULTS = process.env.RESULTS || 'results-custom.json';// A harness's other kind of tool is an MCP server. A self-contained instance hosts only the// database and media servers, one needing a database and the other costing real money per call, sodiff --git a/ui/public/logos/kimi.png b/ui/public/logos/kimi.pngnew file mode 100644index 00000000..5b41bb60Binary files /dev/null and b/ui/public/logos/kimi.png differdiff --git a/ui/src/components/HarnessLogo.tsx b/ui/src/components/HarnessLogo.tsxindex c0c59284..abbfa57d 100644--- a/ui/src/components/HarnessLogo.tsx+++ b/ui/src/components/HarnessLogo.tsx@@ -16,6 +16,7 @@ const LOGO: Record<string, string> = {gemini: '/logos/gemini.png',omp: '/logos/omp.png',goose: '/logos/goose.png', // the flying goose from goose-docs.ai (logo_light.png, cropped to the mark)+ kimi: '/logos/kimi.png', // the official Kimi mark (the K app icon from kimi.ai/code), supplied by Richard 2026-09-17};export function HarnessLogo({ id, size = 26 }: { id: string; size?: number }) {diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsxindex 060585ae..d8ba24ee 100644--- a/ui/src/components/HarnessSettings.tsx+++ b/ui/src/components/HarnessSettings.tsx@@ -269,7 +269,7 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {<section className="form-section"><div><h3>Agent instructions</h3><p>Persistent role, conventions, constraints, and output contract loaded on every Task.</p></div><div className="field-stack">- <div className="field"><label htmlFor="hsInstructions">{['codex', 'hermes', 'omp', 'pi', 'opencode', 'dsh', 'qwen', 'cline', 'goose'].includes(base?.id || draft?.base || '') ? 'AGENTS.md' : 'CLAUDE.md'}</label>+ <div className="field"><label htmlFor="hsInstructions">{['codex', 'hermes', 'omp', 'pi', 'opencode', 'dsh', 'qwen', 'cline', 'goose', 'kimi'].includes(base?.id || draft?.base || '') ? 'AGENTS.md' : 'CLAUDE.md'}</label><textarea id="hsInstructions" rows={7} disabled={readOnly}value={oob ? oob.systemPrompt : (draft?.systemPrompt || '')}onChange={(e) => upd({ systemPrompt: e.target.value })} />diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex df2bf192..bbdeabd7 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -20,7 +20,7 @@ export interface OobHarness {defaultModel?: string; // the backend default, NOT necessarily models[0]moreModels?: number; // "+N" pillstatus: 'ready' | 'soon';- backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | null; // gateway backend; null = coming soon+ backend: 'claude' | 'codex' | 'hermes' | 'pi' | 'dsh' | 'opencode' | 'qwen' | 'gemini' | 'cline' | 'omp' | 'goose' | 'kimi' | null; // gateway backend; null = coming soonsystemPrompt: string; // the harness's built-in system prompt (shown read-only)tools: string[]; // built-in tools (read-only)skills: string[]; // built-in skills (read-only)@@ -132,6 +132,14 @@ 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.+ 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.',+ tools: [], skills: [] },];export const oobById = (id: string) => OOB.find((o) => o.id === id) || null;