Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

kimi: implement provider with auth, translation, client, and streaming

Raine Virta5f9839e309cd
diff --git a/Cargo.lock b/Cargo.lock
index d4d8205..7c875ed 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -47,7 +47,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -58,7 +58,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -169,6 +169,12 @@ dependencies = [
"syn",
]
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
[[package]]
name = "bitflags"
version = "2.13.0"
@@ -198,12 +204,28 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
+[[package]]
+name = "cc"
+version = "1.2.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
[[package]]
name = "clap"
version = "4.6.1"
@@ -252,13 +274,17 @@ dependencies = [
"assert_cmd",
"async-trait",
"axum",
+ "base64",
"bytes",
"clap",
"futures-core",
"futures-util",
+ "hostname",
"http",
"http-body-util",
+ "once_cell",
"predicates",
+ "reqwest",
"serde",
"serde_json",
"tempfile",
@@ -289,6 +315,17 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
+[[package]]
+name = "displaydoc"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -296,7 +333,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -305,6 +342,12 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+
[[package]]
name = "float-cmp"
version = "0.10.0"
@@ -330,6 +373,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
+ "futures-sink",
]
[[package]]
@@ -338,6 +382,12 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+[[package]]
+name = "futures-io"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
+
[[package]]
name = "futures-macro"
version = "0.3.32"
@@ -349,6 +399,12 @@ dependencies = [
"syn",
]
+[[package]]
+name = "futures-sink"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
+
[[package]]
name = "futures-task"
version = "0.3.32"
@@ -362,12 +418,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
+ "futures-io",
"futures-macro",
+ "futures-sink",
"futures-task",
+ "memchr",
"pin-project-lite",
"slab",
]
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+ "wasm-bindgen",
+]
+
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -376,7 +462,7 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
- "r-efi",
+ "r-efi 6.0.0",
]
[[package]]
@@ -385,6 +471,17 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hostname"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "windows-link",
+]
+
[[package]]
name = "http"
version = "1.4.2"
@@ -448,6 +545,23 @@ dependencies = [
"pin-project-lite",
"smallvec",
"tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+ "webpki-roots",
]
[[package]]
@@ -456,15 +570,132 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
+ "base64",
"bytes",
+ "futures-channel",
+ "futures-util",
"http",
"http-body",
"hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
"pin-project-lite",
+ "socket2",
"tokio",
"tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
]
+[[package]]
+name = "icu_normalizer_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
+
+[[package]]
+name = "icu_properties"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
+
+[[package]]
+name = "icu_provider"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
+
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -506,12 +737,24 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+[[package]]
+name = "litemap"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
+
[[package]]
name = "log"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
[[package]]
name = "matchers"
version = "0.2.0"
@@ -547,7 +790,7 @@ checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
dependencies = [
"libc",
"wasi",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -562,7 +805,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -604,12 +847,30 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+[[package]]
+name = "potential_utf"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
+dependencies = [
+ "zerovec",
+]
+
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
[[package]]
name = "predicates"
version = "3.1.4"
@@ -649,6 +910,61 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "quinn"
+version = "0.11.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.60.2",
+]
+
[[package]]
name = "quote"
version = "1.0.46"
@@ -658,12 +974,47 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "rand"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
[[package]]
name = "regex"
version = "1.12.4"
@@ -693,6 +1044,68 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tokio-util",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams",
+ "web-sys",
+ "webpki-roots",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -703,7 +1116,42 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
]
[[package]]
@@ -793,6 +1241,12 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -822,15 +1276,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
dependencies = [
"libc",
- "windows-sys",
+ "windows-sys 0.61.2",
]
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "syn"
version = "2.0.118"
@@ -847,6 +1313,20 @@ name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
[[package]]
name = "tempfile"
@@ -855,10 +1335,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom",
+ "getrandom 0.4.3",
"once_cell",
"rustix",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -926,19 +1406,45 @@ dependencies = [
"time-core",
]
+[[package]]
+name = "tinystr"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
[[package]]
name = "tokio"
version = "1.52.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
dependencies = [
+ "bytes",
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -952,6 +1458,29 @@ dependencies = [
"syn",
]
+[[package]]
+name = "tokio-rustls"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
[[package]]
name = "tower"
version = "0.5.3"
@@ -968,6 +1497,24 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
[[package]]
name = "tower-layer"
version = "0.3.3"
@@ -1055,12 +1602,42 @@ dependencies = [
"tracing-serde",
]
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -1073,7 +1650,7 @@ version = "1.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"
dependencies = [
- "getrandom",
+ "getrandom 0.4.3",
"js-sys",
"serde_core",
"wasm-bindgen",
@@ -1094,12 +1671,30 @@ dependencies = [
"libc",
]
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.126"
@@ -1113,6 +1708,16 @@ dependencies = [
"wasm-bindgen-shared",
]
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.76"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.126"
@@ -1145,12 +1750,72 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-streams"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -1160,6 +1825,250 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "writeable"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "zmij"
version = "1.0.21"
diff --git a/Cargo.toml b/Cargo.toml
index b56e0f5..c0b0cfb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,6 +25,10 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "json"] }
uuid = { version = "1", features = ["v4", "serde"] }
time = { version = "0.3", features = ["formatting"] }
+reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "blocking"] }
+base64 = "0.22"
+hostname = "0.4"
+once_cell = "1.20"
[dev-dependencies]
tempfile = "3.14"
diff --git a/src/config.rs b/src/config.rs
index 4e7ee65..29df6bc 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -35,6 +35,17 @@ struct FileConfig {
#[serde(rename = "aliasProvider")]
pub alias_provider: Option<String>,
pub log: Option<FileLog>,
+ pub kimi: Option<KimiConfig>,
+}
+
+#[derive(Deserialize, Clone)]
+struct KimiConfig {
+ #[serde(rename = "userAgent")]
+ pub user_agent: Option<String>,
+ #[serde(rename = "oauthHost")]
+ pub oauth_host: Option<String>,
+ #[serde(rename = "baseUrl")]
+ pub base_url: Option<String>,
}
#[derive(Deserialize)]
@@ -159,6 +170,15 @@ pub fn config_override_summary_lines(cfg: &LoadedConfig) -> Vec<String> {
if env.contains_key("CCP_LOG_STDERR") {
out.push("log.stderr (env)".to_string());
}
+ if env.contains_key("CCP_KIMI_OAUTH_HOST") {
+ out.push("kimi.oauthHost (env)".to_string());
+ }
+ if env.contains_key("CCP_KIMI_BASE_URL") {
+ out.push("kimi.baseUrl (env)".to_string());
+ }
+ if env.contains_key("CCP_KIMI_USER_AGENT") {
+ out.push("kimi.userAgent (env)".to_string());
+ }
if let Some(file_cfg) = file {
if let Some(p) = file_cfg.port {
out.push(format!("port: {p}"));
@@ -181,3 +201,54 @@ pub fn config_override_summary_lines(cfg: &LoadedConfig) -> Vec<String> {
pub fn is_verbose() -> bool {
log_verbose()
}
+
+pub fn kimi_oauth_host() -> String {
+ let env: HashMap<_, _> = std::env::vars().collect();
+ if let Some(raw) = env.get("CCP_KIMI_OAUTH_HOST") {
+ return raw.clone();
+ }
+ let config_dir = paths::config_dir();
+ if let Some(file) = read_file_config(&config_dir) {
+ if let Some(kimi) = file.kimi {
+ if let Some(host) = kimi.oauth_host {
+ return host;
+ }
+ }
+ }
+ "https://auth.kimi.com".to_string()
+}
+
+pub fn kimi_base_url() -> String {
+ let env: HashMap<_, _> = std::env::vars().collect();
+ if let Some(raw) = env.get("CCP_KIMI_BASE_URL") {
+ return raw.clone();
+ }
+ let config_dir = paths::config_dir();
+ if let Some(file) = read_file_config(&config_dir) {
+ if let Some(kimi) = file.kimi {
+ if let Some(url) = kimi.base_url {
+ return url;
+ }
+ }
+ }
+ "https://api.kimi.com/coding/v1".to_string()
+}
+
+pub fn kimi_user_agent(default: &str) -> String {
+ let env: HashMap<_, _> = std::env::vars().collect();
+ if let Some(raw) = env.get("CCP_KIMI_USER_AGENT") {
+ return raw.clone();
+ }
+ if let Some(raw) = env.get("CCP_USER_AGENT") {
+ return raw.clone();
+ }
+ let config_dir = paths::config_dir();
+ if let Some(file) = read_file_config(&config_dir) {
+ if let Some(kimi) = file.kimi {
+ if let Some(ua) = kimi.user_agent {
+ return ua;
+ }
+ }
+ }
+ default.to_string()
+}
diff --git a/src/lib.rs b/src/lib.rs
index 12ce863..84f3e2f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -4,6 +4,7 @@ pub mod config;
pub mod logging;
pub mod paths;
pub mod provider;
+pub mod providers;
pub mod registry;
pub mod retry;
pub mod server;
diff --git a/src/providers/kimi/auth/constants.rs b/src/providers/kimi/auth/constants.rs
new file mode 100644
index 0000000..aa6569e
--- /dev/null
+++ b/src/providers/kimi/auth/constants.rs
@@ -0,0 +1,13 @@
+use crate::config;
+
+pub const CLIENT_ID: &str = "17e5f671-d194-4dfb-9706-5516cb48c098";
+pub const KIMI_CLI_VERSION: &str = "1.37.0";
+pub const REFRESH_MARGIN_MS: u64 = 5 * 60 * 1000;
+
+pub fn oauth_host() -> String {
+ config::kimi_oauth_host()
+}
+
+pub fn api_base_url() -> String {
+ config::kimi_base_url()
+}
diff --git a/src/providers/kimi/auth/device_id.rs b/src/providers/kimi/auth/device_id.rs
new file mode 100644
index 0000000..6b28c3b
--- /dev/null
+++ b/src/providers/kimi/auth/device_id.rs
@@ -0,0 +1,54 @@
+use std::fs;
+#[cfg(unix)]
+use std::os::unix::fs::PermissionsExt;
+use std::path::PathBuf;
+
+use crate::paths;
+
+fn device_id_path() -> PathBuf {
+ let deps = paths::DirResolverEnv::default();
+ paths::kimi_device_id_file(&deps)
+}
+
+fn legacy_device_id_path() -> PathBuf {
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .unwrap_or_else(|_| "/".to_string());
+ std::path::Path::new(&home)
+ .join(".config")
+ .join("claude-code-proxy")
+ .join("kimi")
+ .join("device_id")
+}
+
+pub fn get_device_id() -> Result<String, anyhow::Error> {
+ for candidate in [device_id_path(), legacy_device_id_path()] {
+ if let Ok(raw) = fs::read_to_string(&candidate) {
+ let trimmed = raw.trim().to_string();
+ if !trimmed.is_empty() {
+ return Ok(trimmed);
+ }
+ }
+ }
+
+ let id = uuid::Uuid::new_v4().to_string().replace('-', "");
+ let target = device_id_path();
+ if let Some(dir) = target.parent() {
+ fs::create_dir_all(dir)?;
+ set_mode(dir, 0o700);
+ }
+ fs::write(&target, &id)?;
+ set_mode(&target, 0o600);
+ Ok(id)
+}
+
+fn set_mode(path: &std::path::Path, mode: u32) {
+ #[cfg(unix)]
+ {
+ if let Ok(meta) = fs::metadata(path) {
+ let mut permissions = meta.permissions();
+ permissions.set_mode(mode);
+ let _ = fs::set_permissions(path, permissions);
+ }
+ }
+}
diff --git a/src/providers/kimi/auth/headers.rs b/src/providers/kimi/auth/headers.rs
new file mode 100644
index 0000000..1e0e60c
--- /dev/null
+++ b/src/providers/kimi/auth/headers.rs
@@ -0,0 +1,53 @@
+use std::collections::HashMap;
+
+use super::constants::KIMI_CLI_VERSION;
+use super::device_id::get_device_id;
+use crate::config;
+
+fn device_model() -> String {
+ let arch = std::env::consts::ARCH;
+ let os = std::env::consts::OS;
+ format!("{} {}", os, arch)
+}
+
+fn ascii_only(value: &str, fallback: &str) -> String {
+ let cleaned: String = value
+ .chars()
+ .filter(|&c| c.is_ascii() && !c.is_control())
+ .collect();
+ let trimmed = cleaned.trim().to_string();
+ if trimmed.is_empty() {
+ fallback.to_string()
+ } else {
+ trimmed
+ }
+}
+
+pub fn common_headers() -> Result<HashMap<String, String>, anyhow::Error> {
+ let device_id = get_device_id()?;
+ let hostname_str = hostname::get()
+ .map(|h| h.to_string_lossy().to_string())
+ .unwrap_or_else(|_| "unknown".to_string());
+
+ let mut headers = HashMap::new();
+ headers.insert("X-Msh-Platform".to_string(), "kimi_cli".to_string());
+ headers.insert("X-Msh-Version".to_string(), KIMI_CLI_VERSION.to_string());
+ headers.insert(
+ "X-Msh-Device-Name".to_string(),
+ ascii_only(&hostname_str, "unknown"),
+ );
+ headers.insert(
+ "X-Msh-Device-Model".to_string(),
+ ascii_only(&device_model(), "unknown"),
+ );
+ headers.insert(
+ "X-Msh-Os-Version".to_string(),
+ ascii_only(std::env::consts::ARCH, "unknown"),
+ );
+ headers.insert("X-Msh-Device-Id".to_string(), device_id);
+ headers.insert(
+ "User-Agent".to_string(),
+ config::kimi_user_agent(&format!("KimiCLI/{KIMI_CLI_VERSION}")),
+ );
+ Ok(headers)
+}
diff --git a/src/providers/kimi/auth/jwt.rs b/src/providers/kimi/auth/jwt.rs
new file mode 100644
index 0000000..833f5eb
--- /dev/null
+++ b/src/providers/kimi/auth/jwt.rs
@@ -0,0 +1,53 @@
+use serde::Deserialize;
+
+#[derive(Debug, Deserialize)]
+struct KimiClaims {
+ #[serde(alias = "user_id")]
+ user_id: Option<String>,
+}
+
+pub fn extract_user_id(access_token: &str) -> Option<String> {
+ let parts: Vec<&str> = access_token.split('.').collect();
+ if parts.len() < 2 {
+ return None;
+ }
+
+ let payload_b64 = parts[1].replace('-', "+").replace('_', "/");
+
+ let padded = match payload_b64.len() % 4 {
+ 2 => format!("{}==", payload_b64),
+ 3 => format!("{}=", payload_b64),
+ _ => payload_b64,
+ };
+
+ use base64::Engine;
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(&padded)
+ .ok()?;
+
+ let claims: KimiClaims = serde_json::from_slice(&decoded).ok()?;
+ claims.user_id
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn extract_user_id_from_jwt() {
+ // JWT with header {"alg":"HS256"}, payload {"user_id":"test_user","exp":9999999999}
+ let token =
+ "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidGVzdF91c2VyIiwiZXhwIjo5OTk5OTk5OTk5fQ.signature";
+ assert_eq!(extract_user_id(token), Some("test_user".to_string()));
+ }
+
+ #[test]
+ fn extract_user_id_invalid_token() {
+ assert_eq!(extract_user_id("invalid"), None);
+ }
+
+ #[test]
+ fn extract_user_id_from_empty_parts() {
+ assert_eq!(extract_user_id(""), None);
+ }
+}
diff --git a/src/providers/kimi/auth/login.rs b/src/providers/kimi/auth/login.rs
new file mode 100644
index 0000000..eb4077b
--- /dev/null
+++ b/src/providers/kimi/auth/login.rs
@@ -0,0 +1,125 @@
+use serde::Deserialize;
+
+use super::constants::{CLIENT_ID, oauth_host};
+use super::headers::common_headers;
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct TokenResponse {
+ pub access_token: String,
+ #[serde(default)]
+ pub refresh_token: Option<String>,
+ #[serde(default)]
+ pub expires_in: Option<u64>,
+ #[serde(default)]
+ pub scope: Option<String>,
+ #[serde(default)]
+ pub token_type: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[allow(dead_code)]
+struct DeviceAuthResponse {
+ user_code: String,
+ device_code: String,
+ #[serde(default)]
+ verification_uri: Option<String>,
+ verification_uri_complete: String,
+ #[serde(default)]
+ expires_in: Option<u64>,
+ #[serde(default)]
+ interval: Option<u64>,
+}
+
+const GRANT_DEVICE_CODE: &str = "urn:ietf:params:oauth:grant-type:device_code";
+const POLL_SAFETY_MARGIN_MS: u64 = 500;
+
+pub fn run_device_login() -> Result<TokenResponse, anyhow::Error> {
+ let headers = common_headers()?;
+ let client = reqwest::blocking::Client::new();
+
+ let init_resp = client
+ .post(format!("{}/api/oauth/device_authorization", oauth_host()))
+ .headers(build_header_map(&headers))
+ .form(&[("client_id", CLIENT_ID)])
+ .send()?;
+
+ if !init_resp.status().is_success() {
+ let status = init_resp.status();
+ let text = init_resp.text().unwrap_or_default();
+ anyhow::bail!("Device authorization failed: {status} {text}");
+ }
+
+ let auth: DeviceAuthResponse = init_resp.json()?;
+ let interval_ms = (auth.interval.unwrap_or(5).max(1)) * 1000;
+
+ eprintln!();
+ eprintln!("Visit: {}", auth.verification_uri_complete);
+ eprintln!("Code: {}", auth.user_code);
+ eprintln!();
+
+ loop {
+ let resp = client
+ .post(format!("{}/api/oauth/token", oauth_host()))
+ .headers(build_header_map(&headers))
+ .form(&[
+ ("client_id", CLIENT_ID),
+ ("device_code", &auth.device_code),
+ ("grant_type", GRANT_DEVICE_CODE),
+ ])
+ .send()?;
+
+ let status = resp.status();
+ if status.as_u16() == 200 {
+ return Ok(resp.json::<TokenResponse>()?);
+ }
+
+ let body: serde_json::Value = resp.json().unwrap_or(serde_json::json!({}));
+ let error = body
+ .get("error")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+
+ match error {
+ "expired_token" => {
+ anyhow::bail!("Device code expired. Run login again.");
+ }
+ "authorization_pending" | "slow_down" => {
+ std::thread::sleep(std::time::Duration::from_millis(
+ interval_ms + POLL_SAFETY_MARGIN_MS,
+ ));
+ continue;
+ }
+ _ => {
+ let desc = body
+ .get("error_description")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ anyhow::bail!(
+ "Device token poll failed ({}): {}{}",
+ status,
+ error,
+ if desc.is_empty() {
+ "".to_string()
+ } else {
+ format!(" - {desc}")
+ }
+ );
+ }
+ }
+ }
+}
+
+fn build_header_map(
+ headers: &std::collections::HashMap<String, String>,
+) -> reqwest::header::HeaderMap {
+ use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
+ let mut map = HeaderMap::new();
+ for (k, v) in headers {
+ if let Ok(name) = HeaderName::from_bytes(k.as_bytes()) {
+ if let Ok(value) = HeaderValue::from_str(v) {
+ map.insert(name, value);
+ }
+ }
+ }
+ map
+}
diff --git a/src/providers/kimi/auth/manager.rs b/src/providers/kimi/auth/manager.rs
new file mode 100644
index 0000000..95b252d
--- /dev/null
+++ b/src/providers/kimi/auth/manager.rs
@@ -0,0 +1,230 @@
+use std::sync::{Arc, Mutex};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use super::constants::{CLIENT_ID, REFRESH_MARGIN_MS, oauth_host};
+use super::headers::common_headers;
+use super::jwt::extract_user_id;
+use super::login::TokenResponse;
+use super::token_store::{KimiTokenStore, StoredAuth};
+use crate::auth::AuthStorage;
+
+const MAX_REFRESH_ATTEMPTS: u32 = 3;
+const RETRYABLE_STATUSES: &[u16] = &[429, 500, 502, 503, 504];
+
+pub struct KimiAuthManager<S: AuthStorage<StoredAuth>> {
+ pub store: KimiTokenStore<S>,
+ cached: Arc<Mutex<Option<StoredAuth>>>,
+}
+
+impl<S: AuthStorage<StoredAuth>> KimiAuthManager<S> {
+ pub fn new(store: KimiTokenStore<S>) -> Self {
+ Self {
+ store,
+ cached: Arc::new(Mutex::new(None)),
+ }
+ }
+
+ fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64
+ }
+
+ pub fn get_auth(&self) -> Result<StoredAuth, anyhow::Error> {
+ let cached = {
+ let guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ guard.clone()
+ };
+ let stored = match cached {
+ Some(ref auth) => auth.clone(),
+ None => {
+ let loaded = self.store.load_auth()?;
+ match loaded {
+ Some(auth) => {
+ let mut guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ *guard = Some(auth.clone());
+ auth
+ }
+ None => {
+ anyhow::bail!("Not authenticated. Run: claude-code-proxy kimi auth login");
+ }
+ }
+ }
+ };
+
+ if stored.expires > Self::now_ms() + REFRESH_MARGIN_MS {
+ return Ok(stored);
+ }
+
+ self.refresh_now(&stored)
+ }
+
+ pub fn force_refresh(&self) -> Result<StoredAuth, anyhow::Error> {
+ let stored = {
+ let guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ guard.clone()
+ };
+ let stored = match stored {
+ Some(auth) => auth,
+ None => {
+ let loaded = self.store.load_auth()?;
+ loaded.ok_or_else(|| anyhow::anyhow!("Not authenticated"))?
+ }
+ };
+ self.refresh_now(&stored)
+ }
+
+ fn refresh_now(&self, current: &StoredAuth) -> Result<StoredAuth, anyhow::Error> {
+ if current.refresh.is_empty() {
+ anyhow::bail!("No refresh token stored; re-authenticate");
+ }
+
+ let headers = common_headers()?;
+ let client = reqwest::blocking::Client::new();
+
+ for attempt in 0..MAX_REFRESH_ATTEMPTS {
+ let form = [
+ ("client_id", CLIENT_ID.to_string()),
+ ("grant_type", "refresh_token".to_string()),
+ ("refresh_token", current.refresh.clone()),
+ ];
+
+ let resp = match client
+ .post(format!("{}/api/oauth/token", oauth_host()))
+ .headers(build_headers_map(&headers))
+ .form(&form)
+ .send()
+ {
+ Ok(r) => r,
+ Err(err) => {
+ if attempt < MAX_REFRESH_ATTEMPTS - 1 {
+ let ms = 2u64.pow(attempt) * 1000;
+ std::thread::sleep(std::time::Duration::from_millis(ms));
+ continue;
+ }
+ anyhow::bail!("refresh network error: {err}");
+ }
+ };
+
+ if resp.status().as_u16() == 200 {
+ let tokens: TokenResponse = resp.json()?;
+ let expires = Self::now_ms() + (tokens.expires_in.unwrap_or(900) as u64 * 1000);
+ let next = StoredAuth {
+ access: tokens.access_token.clone(),
+ refresh: tokens
+ .refresh_token
+ .unwrap_or_else(|| current.refresh.clone()),
+ expires,
+ scope: tokens.scope.clone(),
+ user_id: extract_user_id(&tokens.access_token)
+ .or_else(|| current.user_id.clone()),
+ };
+ self.store.save_auth(next.clone())?;
+ {
+ let mut guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ *guard = Some(next.clone());
+ }
+ return Ok(next);
+ }
+
+ let status = resp.status().as_u16();
+ if status == 401 || status == 403 {
+ {
+ let mut guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ *guard = None;
+ }
+ let _ = self.store.clear_auth();
+ let err_msg = resp
+ .text()
+ .unwrap_or_else(|_| "Token refresh unauthorized".to_string());
+ anyhow::bail!("{err_msg}");
+ }
+
+ if !RETRYABLE_STATUSES.contains(&status) {
+ anyhow::bail!("Token refresh failed: {status}");
+ }
+
+ if attempt < MAX_REFRESH_ATTEMPTS - 1 {
+ let ms = 2u64.pow(attempt) * 1000;
+ std::thread::sleep(std::time::Duration::from_millis(ms));
+ }
+ }
+
+ anyhow::bail!("Token refresh failed after {MAX_REFRESH_ATTEMPTS} attempts");
+ }
+
+ pub fn persist_initial_tokens(
+ &self,
+ tokens: &TokenResponse,
+ ) -> Result<StoredAuth, anyhow::Error> {
+ let expires = Self::now_ms() + (tokens.expires_in.unwrap_or(900) as u64 * 1000);
+ let auth = StoredAuth {
+ access: tokens.access_token.clone(),
+ refresh: tokens.refresh_token.clone().unwrap_or_default(),
+ expires,
+ scope: tokens.scope.clone(),
+ user_id: extract_user_id(&tokens.access_token),
+ };
+ self.store.save_auth(auth.clone())?;
+ {
+ let mut guard = self.cached.lock().map_err(|e| anyhow::anyhow!("{e}"))?;
+ *guard = Some(auth.clone());
+ }
+ Ok(auth)
+ }
+
+ pub fn reset_cache(&self) {
+ if let Ok(mut guard) = self.cached.lock() {
+ *guard = None;
+ }
+ }
+}
+
+fn build_headers_map(
+ headers: &std::collections::HashMap<String, String>,
+) -> reqwest::header::HeaderMap {
+ let mut map = reqwest::header::HeaderMap::new();
+ for (k, v) in headers {
+ if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes()) {
+ if let Ok(value) = reqwest::header::HeaderValue::from_str(v) {
+ map.insert(name, value);
+ }
+ }
+ }
+ map
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::auth::InMemoryAuthStore;
+
+ fn test_store() -> KimiTokenStore<InMemoryAuthStore<StoredAuth>> {
+ KimiTokenStore::new(InMemoryAuthStore::new())
+ }
+
+ #[test]
+ fn get_auth_returns_stored() {
+ let store = test_store();
+ let auth = StoredAuth {
+ access: "test_access".into(),
+ refresh: "test_refresh".into(),
+ expires: 9999999999999,
+ scope: Some("openid".into()),
+ user_id: Some("user1".into()),
+ };
+ store.save_auth(auth.clone()).unwrap();
+ let manager = KimiAuthManager::new(store);
+ let result = manager.get_auth().unwrap();
+ assert_eq!(result.access, "test_access");
+ assert_eq!(result.user_id.as_deref(), Some("user1"));
+ }
+
+ #[test]
+ fn get_auth_fails_when_no_auth() {
+ let store = test_store();
+ let manager = KimiAuthManager::new(store);
+ assert!(manager.get_auth().is_err());
+ }
+}
diff --git a/src/providers/kimi/auth/mod.rs b/src/providers/kimi/auth/mod.rs
new file mode 100644
index 0000000..3dc0266
--- /dev/null
+++ b/src/providers/kimi/auth/mod.rs
@@ -0,0 +1,7 @@
+pub mod constants;
+pub mod device_id;
+pub mod headers;
+pub mod jwt;
+pub mod login;
+pub mod manager;
+pub mod token_store;
diff --git a/src/providers/kimi/auth/token_store.rs b/src/providers/kimi/auth/token_store.rs
new file mode 100644
index 0000000..f335cbf
--- /dev/null
+++ b/src/providers/kimi/auth/token_store.rs
@@ -0,0 +1,61 @@
+use serde::{Deserialize, Serialize};
+
+use crate::auth::{AuthStorage, FileAuthStore};
+use crate::paths;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct StoredAuth {
+ pub access: String,
+ pub refresh: String,
+ pub expires: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub scope: Option<String>,
+ #[serde(rename = "userId", default, skip_serializing_if = "Option::is_none")]
+ pub user_id: Option<String>,
+}
+
+pub struct KimiTokenStore<S: AuthStorage<StoredAuth>> {
+ store: S,
+}
+
+impl<S: AuthStorage<StoredAuth>> KimiTokenStore<S> {
+ pub fn new(store: S) -> Self {
+ Self { store }
+ }
+
+ pub fn load_auth(&self) -> Result<Option<StoredAuth>, anyhow::Error> {
+ self.store.load()
+ }
+
+ pub fn save_auth(&self, value: StoredAuth) -> Result<(), anyhow::Error> {
+ self.store.save(value)
+ }
+
+ pub fn clear_auth(&self) -> Result<(), anyhow::Error> {
+ self.store.clear()
+ }
+
+ pub fn auth_path(&self) -> String {
+ self.store.path()
+ }
+}
+
+pub fn file_store() -> KimiTokenStore<FileAuthStore<StoredAuth>> {
+ let deps = paths::DirResolverEnv::default();
+ let primary = paths::kimi_auth_file(&deps);
+ let legacy = {
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .unwrap_or_else(|_| "/".to_string());
+ std::path::Path::new(&home)
+ .join(".config")
+ .join("claude-code-proxy")
+ .join("kimi")
+ .join("auth.json")
+ };
+ let store = FileAuthStore::new(
+ primary.to_string_lossy().to_string(),
+ legacy.to_string_lossy().to_string(),
+ );
+ KimiTokenStore::new(store)
+}
diff --git a/src/providers/kimi/client.rs b/src/providers/kimi/client.rs
new file mode 100644
index 0000000..089a5ae
--- /dev/null
+++ b/src/providers/kimi/client.rs
@@ -0,0 +1,197 @@
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use crate::providers::kimi::auth::constants::api_base_url;
+use crate::providers::kimi::auth::headers::common_headers;
+use crate::providers::kimi::auth::manager::KimiAuthManager;
+use crate::providers::kimi::auth::token_store::{StoredAuth, file_store};
+use crate::providers::kimi::translate::request::KimiChatRequest;
+use crate::retry::{MAX_RATE_LIMIT_RETRIES, compute_backoff_delay};
+
+#[derive(Debug)]
+pub struct KimiError {
+ pub status: u16,
+ pub message: String,
+ pub detail: Option<String>,
+ pub retry_after: Option<String>,
+}
+
+pub struct KimiResponse {
+ pub body: Vec<u8>,
+ pub status: u16,
+ pub request_start_time: u64,
+}
+
+pub struct KimiHttpClient {
+ client: reqwest::blocking::Client,
+ auth_manager: KimiAuthManager<crate::auth::FileAuthStore<StoredAuth>>,
+}
+
+impl KimiHttpClient {
+ pub fn new() -> Self {
+ Self {
+ client: reqwest::blocking::Client::builder()
+ .timeout(std::time::Duration::from_secs(120))
+ .build()
+ .expect("failed to create HTTP client"),
+ auth_manager: KimiAuthManager::new(file_store()),
+ }
+ }
+
+ pub fn auth_manager(&self) -> &KimiAuthManager<crate::auth::FileAuthStore<StoredAuth>> {
+ &self.auth_manager
+ }
+
+ pub fn post_kimi(&self, body: &KimiChatRequest) -> Result<KimiResponse, KimiError> {
+ let mut auth = self.auth_manager.get_auth().map_err(|e| KimiError {
+ status: 401,
+ message: "Auth error".to_string(),
+ detail: Some(e.to_string()),
+ retry_after: None,
+ })?;
+
+ let mut attempt = 0u32;
+ loop {
+ let result = self.attempt_post(&auth.access, body);
+
+ match result {
+ Ok(response) if response.status == 401 && attempt == 0 => {
+ // First 401: try refresh
+ match self.auth_manager.force_refresh() {
+ Ok(new_auth) => {
+ auth = new_auth;
+ attempt += 1;
+ continue;
+ }
+ Err(e) => {
+ return Err(KimiError {
+ status: 401,
+ message: "Unauthorized".to_string(),
+ detail: Some(e.to_string()),
+ retry_after: None,
+ });
+ }
+ }
+ }
+ Ok(response) => return Ok(response),
+ Err(err @ KimiError { status: 429, .. }) => {
+ if attempt < MAX_RATE_LIMIT_RETRIES {
+ let delay = compute_backoff_delay(attempt, err.retry_after.as_deref());
+ std::thread::sleep(std::time::Duration::from_millis(delay.wait_ms));
+ attempt += 1;
+ continue;
+ }
+ return Err(err);
+ }
+ Err(err) => return Err(err),
+ }
+ }
+ }
+
+ fn attempt_post(
+ &self,
+ access_token: &str,
+ body: &KimiChatRequest,
+ ) -> Result<KimiResponse, KimiError> {
+ let headers = common_headers().map_err(|e| KimiError {
+ status: 500,
+ message: "Failed to build headers".to_string(),
+ detail: Some(e.to_string()),
+ retry_after: None,
+ })?;
+
+ let url = format!("{}/chat/completions", api_base_url());
+ let body_json = serde_json::to_string(body).map_err(|e| KimiError {
+ status: 500,
+ message: "Failed to serialize request".to_string(),
+ detail: Some(e.to_string()),
+ retry_after: None,
+ })?;
+
+ let request_start_time = now_ms();
+
+ let mut req_builder = self
+ .client
+ .post(&url)
+ .header("Content-Type", "application/json")
+ .header("Accept", "application/json")
+ .header("Authorization", format!("Bearer {access_token}"));
+
+ // Add common headers
+ for (k, v) in &headers {
+ if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes()) {
+ if let Ok(value) = reqwest::header::HeaderValue::from_str(v) {
+ req_builder = req_builder.header(name, value);
+ }
+ }
+ }
+
+ let resp = match req_builder.body(body_json).send() {
+ Ok(r) => r,
+ Err(e) => {
+ return Err(KimiError {
+ status: 0,
+ message: "Network error".to_string(),
+ detail: Some(e.to_string()),
+ retry_after: None,
+ });
+ }
+ };
+
+ let status = resp.status().as_u16();
+
+ if status == 429 {
+ let retry_after = resp
+ .headers()
+ .get("retry-after")
+ .and_then(|v| v.to_str().ok())
+ .map(|s| s.to_string());
+ let text = resp.text().unwrap_or_default();
+ return Err(KimiError {
+ status: 429,
+ message: "Rate limited".to_string(),
+ detail: if text.is_empty() { None } else { Some(text) },
+ retry_after,
+ });
+ }
+
+ if status == 401 || status == 403 {
+ let text = resp.text().unwrap_or_default();
+ return Err(KimiError {
+ status,
+ message: if status == 401 {
+ "Unauthorized"
+ } else {
+ "Forbidden"
+ }
+ .to_string(),
+ detail: if text.is_empty() { None } else { Some(text) },
+ retry_after: None,
+ });
+ }
+
+ if !resp.status().is_success() {
+ let text = resp.text().unwrap_or_default();
+ return Err(KimiError {
+ status,
+ message: "Upstream error".to_string(),
+ detail: if text.is_empty() { None } else { Some(text) },
+ retry_after: None,
+ });
+ }
+
+ let body_bytes = resp.bytes().map(|b| b.to_vec()).unwrap_or_default();
+
+ Ok(KimiResponse {
+ body: body_bytes,
+ status,
+ request_start_time,
+ })
+ }
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64
+}
diff --git a/src/providers/kimi/count_tokens.rs b/src/providers/kimi/count_tokens.rs
new file mode 100644
index 0000000..92c684e
--- /dev/null
+++ b/src/providers/kimi/count_tokens.rs
@@ -0,0 +1,231 @@
+use crate::anthropic::schema::MessagesRequest;
+
+// Approximate token counter. Kimi's tokenizer isn't replicated here;
+// we use a simple monotonic estimator that satisfies Claude Code's
+// compaction logic (needs approximate, not exact counts).
+
+pub const IMAGE_TOKEN_ESTIMATE: u64 = 2000;
+pub const MESSAGE_OVERHEAD_TOKENS: u64 = 4;
+
+pub fn count_tokens(req: &MessagesRequest) -> u64 {
+ let mut total = 0u64;
+
+ // System text
+ if let Some(system) = req.extra.get("system") {
+ total += count_system_tokens(system);
+ }
+
+ // Messages
+ for msg in &req.messages {
+ total += count_message_tokens(&msg.role, &msg.content);
+ }
+
+ // Message overhead
+ total += req.messages.len() as u64 * MESSAGE_OVERHEAD_TOKENS;
+
+ // Tools
+ if let Some(tools) = req.extra.get("tools").and_then(|v| v.as_array()) {
+ total += count_tool_tokens(tools);
+ }
+
+ total
+}
+
+fn count_system_tokens(system: &serde_json::Value) -> u64 {
+ match system {
+ serde_json::Value::String(s) => approx_token_count(s),
+ serde_json::Value::Array(arr) => {
+ let mut total = 0u64;
+ for block in arr {
+ if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
+ if !text.starts_with("x-anthropic-billing-header:") {
+ total += approx_token_count(text);
+ }
+ }
+ }
+ total
+ }
+ _ => 0,
+ }
+}
+
+fn count_message_tokens(role: &str, content: &serde_json::Value) -> u64 {
+ match content {
+ serde_json::Value::String(s) => approx_token_count(s),
+ serde_json::Value::Array(arr) => {
+ let mut total = 0u64;
+ for block in arr {
+ total += count_content_block_tokens(role, block);
+ }
+ total
+ }
+ _ => 0,
+ }
+}
+
+fn count_content_block_tokens(_role: &str, block: &serde_json::Value) -> u64 {
+ match block.get("type").and_then(|v| v.as_str()) {
+ Some("text") => block
+ .get("text")
+ .and_then(|v| v.as_str())
+ .map(approx_token_count)
+ .unwrap_or(0),
+ Some("image") => IMAGE_TOKEN_ESTIMATE,
+ Some("thinking") => block
+ .get("thinking")
+ .and_then(|v| v.as_str())
+ .map(approx_token_count)
+ .unwrap_or(0),
+ Some("tool_use") => {
+ let mut total = 0u64;
+ if let Some(name) = block.get("name").and_then(|v| v.as_str()) {
+ total += approx_token_count(name);
+ }
+ if let Some(input) = block.get("input") {
+ total += approx_token_count(&serde_json::to_string(input).unwrap_or_default());
+ }
+ total
+ }
+ Some("tool_result") => {
+ let content = block.get("content");
+ let role = "tool";
+ count_message_tokens(role, &content.unwrap_or(&serde_json::Value::Null))
+ }
+ _ => 0,
+ }
+}
+
+fn count_tool_tokens(tools: &[serde_json::Value]) -> u64 {
+ let mut total = 0u64;
+ for tool in tools {
+ if let Some(name) = tool.get("name").and_then(|v| v.as_str()) {
+ total += approx_token_count(name);
+ }
+ if let Some(desc) = tool.get("description").and_then(|v| v.as_str()) {
+ total += approx_token_count(desc);
+ }
+ if let Some(schema) = tool.get("input_schema") {
+ total += approx_token_count(&serde_json::to_string(schema).unwrap_or_default());
+ }
+ }
+ total
+}
+
+fn approx_token_count(text: &str) -> u64 {
+ if text.is_empty() {
+ return 0;
+ }
+ // Simple heuristic: count whitespace-separated groups plus punctuation
+ // as approximate tokens. This gives a monotonic estimate that's roughly
+ // proportional to actual token counts.
+ let mut count = 0u64;
+ let mut in_word = false;
+
+ for ch in text.chars() {
+ if ch.is_alphanumeric() || ch == '-' || ch == '_' {
+ if !in_word {
+ count += 1;
+ in_word = true;
+ }
+ } else {
+ in_word = false;
+ // Count individual punctuation as tokens
+ if !ch.is_whitespace() {
+ count += 1;
+ }
+ }
+ }
+
+ count.max(1)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn token_count_is_positive() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hello world"}]
+ }))
+ .unwrap();
+ assert!(count_tokens(&req) > 0);
+ }
+
+ #[test]
+ fn token_count_is_monotonic() {
+ let short: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "short"}]
+ }))
+ .unwrap();
+ let long: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "this is a much longer message with many words in it"}]
+ }))
+ .unwrap();
+ assert!(
+ count_tokens(&long) >= count_tokens(&short),
+ "longer message should have >= tokens"
+ );
+ }
+
+ #[test]
+ fn token_count_includes_overhead() {
+ let single: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hi"}]
+ }))
+ .unwrap();
+ let double: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello"}
+ ]
+ }))
+ .unwrap();
+ // Two messages should have 4 more tokens for overhead
+ assert!(
+ count_tokens(&double) > count_tokens(&single),
+ "more messages should have more tokens"
+ );
+ }
+
+ #[test]
+ fn image_adds_token_estimate() {
+ let text_only: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": [{"type": "text", "text": "desc"}]}]
+ }))
+ .unwrap();
+ let with_image: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": [
+ {"type": "text", "text": "desc"},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "abc"}}
+ ]}]
+ }))
+ .unwrap();
+ assert!(
+ count_tokens(&with_image) >= count_tokens(&text_only) + IMAGE_TOKEN_ESTIMATE - 1,
+ "image should add ~2000 tokens"
+ );
+ }
+
+ #[test]
+ fn token_count_works_with_tools() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "use a tool"}],
+ "tools": [{"name": "search", "description": "Search tool", "input_schema": {"type": "object"}}]
+ }))
+ .unwrap();
+ assert!(
+ count_tokens(&req) > 0,
+ "request with tools should have positive count"
+ );
+ }
+}
diff --git a/src/providers/kimi/mod.rs b/src/providers/kimi/mod.rs
new file mode 100644
index 0000000..ca84fce
--- /dev/null
+++ b/src/providers/kimi/mod.rs
@@ -0,0 +1,217 @@
+pub mod auth;
+pub mod client;
+pub mod count_tokens;
+pub mod translate;
+
+use async_trait::async_trait;
+use axum::Json;
+use axum::response::{IntoResponse, Response};
+use http::StatusCode;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use crate::anthropic::error::json_error;
+use crate::anthropic::schema::{CountTokensResponse, MessagesRequest};
+use crate::provider::{CliHandlers, Provider, RequestContext};
+use crate::providers::kimi::auth::token_store::file_store;
+use crate::providers::kimi::translate::accumulate::accumulate_response;
+use crate::providers::kimi::translate::model_allowlist::{assert_allowed_model, resolve_model};
+use crate::providers::kimi::translate::request::{TranslateOptions, translate_request};
+use crate::providers::kimi::translate::stream::translate_stream_bytes;
+use crate::registry::KIMI_MODELS;
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64
+}
+
+pub struct KimiProvider;
+
+impl KimiProvider {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl Provider for KimiProvider {
+ fn name(&self) -> &'static str {
+ "kimi"
+ }
+
+ fn supported_models(&self) -> Vec<String> {
+ KIMI_MODELS.iter().map(|s| s.to_string()).collect()
+ }
+
+ fn cli(&self) -> &'static dyn CliHandlers {
+ &KIMI_CLI
+ }
+
+ async fn handle_messages(&self, body: MessagesRequest, ctx: RequestContext) -> Response {
+ let message_id = format!("msg_{}", uuid::Uuid::new_v4().to_string().replace('-', ""));
+ let want_stream = body.stream;
+ let model = body.model.as_deref().unwrap_or("kimi-for-coding");
+ let resolved = resolve_model(model);
+
+ if let Err(e) = assert_allowed_model(&resolved) {
+ return json_error(
+ StatusCode::BAD_REQUEST,
+ "invalid_request_error",
+ format!(
+ "Model \"{model}\" resolves to unsupported model \"{}\"",
+ e.model
+ ),
+ );
+ }
+
+ let translated = match translate_request(
+ &body,
+ TranslateOptions {
+ session_id: ctx.session_id.clone(),
+ },
+ ) {
+ Ok(t) => t,
+ Err(e) => {
+ return json_error(
+ StatusCode::BAD_REQUEST,
+ "invalid_request_error",
+ e.to_string(),
+ );
+ }
+ };
+
+ // For count_tokens endpoint, we use local token counting
+ // For messages endpoint, we send to upstream
+ let client = client::KimiHttpClient::new();
+ let upstream = match client.post_kimi(&translated) {
+ Ok(r) => r,
+ Err(e) => {
+ return map_kimi_error_to_response(&e);
+ }
+ };
+
+ if want_stream {
+ let sse_bytes = match translate_stream_bytes(&upstream.body, &message_id, model) {
+ Ok(b) => b,
+ Err(e) => {
+ return json_error(
+ StatusCode::BAD_GATEWAY,
+ "api_error",
+ format!("Stream translation error: {e}"),
+ );
+ }
+ };
+
+ let headers = [
+ (http::header::CONTENT_TYPE, "text/event-stream"),
+ (http::header::CACHE_CONTROL, "no-cache"),
+ (http::header::CONNECTION, "keep-alive"),
+ ];
+ (headers, sse_bytes).into_response()
+ } else {
+ match accumulate_response(&upstream.body, &message_id, model) {
+ Ok(json) => (StatusCode::OK, Json(json)).into_response(),
+ Err(e) => json_error(
+ StatusCode::BAD_GATEWAY,
+ "api_error",
+ format!("Accumulation error: {e}"),
+ ),
+ }
+ }
+ }
+
+ async fn handle_count_tokens(&self, body: MessagesRequest, _ctx: RequestContext) -> Response {
+ let tokens = count_tokens::count_tokens(&body);
+ (
+ StatusCode::OK,
+ Json(CountTokensResponse {
+ input_tokens: tokens,
+ }),
+ )
+ .into_response()
+ }
+}
+
+fn map_kimi_error_to_response(err: &client::KimiError) -> Response {
+ match err.status {
+ 401 | 403 => json_error(
+ StatusCode::UNAUTHORIZED,
+ "authentication_error",
+ err.detail.as_deref().unwrap_or("Authentication failed"),
+ ),
+ 429 => {
+ let retry_after = err.retry_after.as_deref().unwrap_or("5");
+ let resp = json_error(
+ StatusCode::TOO_MANY_REQUESTS,
+ "rate_limit_error",
+ &err.message,
+ );
+ // Forward retry-after header
+ let headers = [(http::header::RETRY_AFTER, retry_after)];
+ (headers, resp).into_response()
+ }
+ _ => json_error(
+ StatusCode::BAD_GATEWAY,
+ "api_error",
+ err.detail.as_deref().unwrap_or("Upstream error"),
+ ),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+// ---------------------------------------------------------------------------
+
+pub(crate) struct KimiCli;
+
+impl CliHandlers for KimiCli {
+ fn login(&self) -> Result<(), anyhow::Error> {
+ let tokens = auth::login::run_device_login()?;
+ let store = file_store();
+ let manager = auth::manager::KimiAuthManager::new(store);
+ let saved = manager.persist_initial_tokens(&tokens)?;
+ println!("Auth saved in {}", manager.store.auth_path());
+ if let Some(ref uid) = saved.user_id {
+ println!("User: {uid}");
+ }
+ println!("Authentication complete");
+ Ok(())
+ }
+
+ fn device(&self) -> Result<(), anyhow::Error> {
+ self.login()
+ }
+
+ fn status(&self) -> Result<(), anyhow::Error> {
+ let store = file_store();
+ let stored = store.load_auth()?;
+ match stored {
+ Some(auth) => {
+ println!("Auth path: {}", store.auth_path());
+ println!("Authenticated: true");
+ if let Some(ref uid) = auth.user_id {
+ println!("User: {uid}");
+ }
+ if let Some(ref scope) = auth.scope {
+ println!("Scope: {scope}");
+ }
+ let remaining = auth.expires.saturating_sub(now_ms()) / 1000;
+ println!("Expires in {remaining}s");
+ Ok(())
+ }
+ None => {
+ anyhow::bail!("Not authenticated");
+ }
+ }
+ }
+
+ fn logout(&self) -> Result<(), anyhow::Error> {
+ let store = file_store();
+ store.clear_auth()?;
+ println!("Logged out");
+ Ok(())
+ }
+}
+
+pub(crate) static KIMI_CLI: KimiCli = KimiCli;
diff --git a/src/providers/kimi/translate/accumulate.rs b/src/providers/kimi/translate/accumulate.rs
new file mode 100644
index 0000000..eaf26b6
--- /dev/null
+++ b/src/providers/kimi/translate/accumulate.rs
@@ -0,0 +1,211 @@
+use serde_json::Value;
+
+use super::reducer::{
+ AnthropicUsage, KimiUsage, ReducerEvent, StopReason, map_usage_to_anthropic,
+ reduce_upstream_bytes,
+};
+use super::signature::make_thinking_signature;
+
+pub fn accumulate_response(
+ input: &[u8],
+ message_id: &str,
+ model: &str,
+) -> Result<Value, anyhow::Error> {
+ let events = reduce_upstream_bytes(input)
+ .map_err(|e| anyhow::anyhow!("upstream error: {} ({:?})", e.message, e.kind))?;
+
+ let mut content: Vec<Value> = Vec::new();
+ let mut stop_reason: Option<StopReason> = None;
+ let mut usage: Option<AnthropicUsage> = None;
+ let mut _raw_usage: Option<KimiUsage> = None;
+
+ struct AccumulatedBlock {
+ index: usize,
+ kind: BlockKind,
+ }
+
+ enum BlockKind {
+ Thinking {
+ text: String,
+ },
+ Text {
+ text: String,
+ },
+ Tool {
+ id: String,
+ name: String,
+ args: String,
+ },
+ }
+
+ let mut blocks: Vec<AccumulatedBlock> = Vec::new();
+
+ for event in &events {
+ match event {
+ ReducerEvent::ThinkingStart { index } => {
+ blocks.push(AccumulatedBlock {
+ index: *index,
+ kind: BlockKind::Thinking {
+ text: String::new(),
+ },
+ });
+ }
+ ReducerEvent::ThinkingDelta { index, text } => {
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
+ if let BlockKind::Thinking { text: t } = &mut block.kind {
+ t.push_str(text);
+ }
+ }
+ }
+ ReducerEvent::TextStart { index } => {
+ blocks.push(AccumulatedBlock {
+ index: *index,
+ kind: BlockKind::Text {
+ text: String::new(),
+ },
+ });
+ }
+ ReducerEvent::TextDelta { index, text } => {
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
+ if let BlockKind::Text { text: t } = &mut block.kind {
+ t.push_str(text);
+ }
+ }
+ }
+ ReducerEvent::ToolStart { index, id, name } => {
+ blocks.push(AccumulatedBlock {
+ index: *index,
+ kind: BlockKind::Tool {
+ id: id.clone(),
+ name: name.clone(),
+ args: String::new(),
+ },
+ });
+ }
+ ReducerEvent::ToolDelta {
+ index,
+ partial_json,
+ } => {
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
+ if let BlockKind::Tool { args, .. } = &mut block.kind {
+ args.push_str(partial_json);
+ }
+ }
+ }
+ ReducerEvent::Finish {
+ stop_reason: sr,
+ usage: u,
+ } => {
+ stop_reason = Some(sr.clone());
+ _raw_usage = u.clone();
+ usage = Some(map_usage_to_anthropic(u));
+ }
+ _ => {}
+ }
+ }
+
+ // Build content array from blocks
+ for block in &blocks {
+ match &block.kind {
+ BlockKind::Thinking { text } => {
+ if !text.is_empty() {
+ content.push(serde_json::json!({
+ "type": "thinking",
+ "thinking": text,
+ "signature": make_thinking_signature(message_id, block.index),
+ }));
+ }
+ }
+ BlockKind::Text { text } => {
+ if !text.is_empty() {
+ content.push(serde_json::json!({
+ "type": "text",
+ "text": text,
+ }));
+ }
+ }
+ BlockKind::Tool { id, name, args } => {
+ let parsed = serde_json::from_str::<Value>(args)
+ .unwrap_or_else(|_| Value::String(args.clone()));
+ content.push(serde_json::json!({
+ "type": "tool_use",
+ "id": id,
+ "name": name,
+ "input": parsed,
+ }));
+ }
+ }
+ }
+
+ let response = serde_json::json!({
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": content,
+ "stop_reason": stop_reason.map(|s| match s {
+ StopReason::EndTurn => "end_turn",
+ StopReason::ToolUse => "tool_use",
+ StopReason::MaxTokens => "max_tokens",
+ }),
+ "stop_sequence": null,
+ "usage": usage.unwrap_or_default(),
+ });
+
+ Ok(response)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn simple_text_upstream() -> Vec<u8> {
+ concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"content\":\" world\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n",
+ "data: [DONE]\n\n"
+ )
+ .as_bytes()
+ .to_vec()
+ }
+
+ #[test]
+ fn accumulate_outputs_anthropic_message() {
+ let response =
+ accumulate_response(&simple_text_upstream(), "msg_test", "kimi-for-coding").unwrap();
+ assert_eq!(response["type"], "message");
+ assert_eq!(response["content"][0]["type"], "text");
+ assert_eq!(response["content"][0]["text"], "Hello world");
+ assert_eq!(response["stop_reason"], "end_turn");
+ }
+
+ #[test]
+ fn accumulate_with_reasoning_and_tools() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"content\":\"result\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"search\",\"arguments\":\"{\\\"q\\\":\\\"rust\\\"}\"}}]}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":5}}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let response =
+ accumulate_response(upstream.as_bytes(), "msg_1", "kimi-for-coding").unwrap();
+ assert_eq!(response["type"], "message");
+ let content = response["content"].as_array().unwrap();
+ assert!(content.len() >= 3);
+ // First block should be thinking
+ assert_eq!(content[0]["type"], "thinking");
+ // Second block should be text
+ assert_eq!(content[1]["type"], "text");
+ // Third block should be tool_use
+ assert_eq!(content[2]["type"], "tool_use");
+ }
+
+ #[test]
+ fn accumulate_handles_upstream_error() {
+ let upstream = concat!("data: {\"error\":{\"message\":\"upstream failure\"}}\n\n",);
+ let result = accumulate_response(upstream.as_bytes(), "msg_e", "model");
+ assert!(result.is_err());
+ }
+}
diff --git a/src/providers/kimi/translate/mod.rs b/src/providers/kimi/translate/mod.rs
new file mode 100644
index 0000000..10323a6
--- /dev/null
+++ b/src/providers/kimi/translate/mod.rs
@@ -0,0 +1,6 @@
+pub mod accumulate;
+pub mod model_allowlist;
+pub mod reducer;
+pub mod request;
+pub mod signature;
+pub mod stream;
diff --git a/src/providers/kimi/translate/model_allowlist.rs b/src/providers/kimi/translate/model_allowlist.rs
new file mode 100644
index 0000000..5ae2a5b
--- /dev/null
+++ b/src/providers/kimi/translate/model_allowlist.rs
@@ -0,0 +1,77 @@
+use std::collections::HashMap;
+
+pub const KIMI_DEFAULT_MODEL: &str = "kimi-for-coding";
+
+static ALIAS_TARGETS: once_cell::sync::Lazy<HashMap<&'static str, &'static str>> =
+ once_cell::sync::Lazy::new(|| {
+ let mut m = HashMap::new();
+ m.insert("haiku", KIMI_DEFAULT_MODEL);
+ m.insert("claude-haiku-4-5", KIMI_DEFAULT_MODEL);
+ m.insert("claude-haiku-4-5-20251001", KIMI_DEFAULT_MODEL);
+ m.insert("sonnet", KIMI_DEFAULT_MODEL);
+ m.insert("claude-sonnet-4-6", KIMI_DEFAULT_MODEL);
+ m.insert("opus", KIMI_DEFAULT_MODEL);
+ m.insert("claude-opus-4-7", KIMI_DEFAULT_MODEL);
+ m.insert("kimi-for-coding", KIMI_DEFAULT_MODEL);
+ m
+ });
+
+pub fn resolve_model(model: &str) -> String {
+ ALIAS_TARGETS
+ .get(model)
+ .copied()
+ .unwrap_or(KIMI_DEFAULT_MODEL)
+ .to_string()
+}
+
+pub fn assert_allowed_model(model: &str) -> Result<(), ModelNotAllowedError> {
+ if model != KIMI_DEFAULT_MODEL {
+ return Err(ModelNotAllowedError {
+ model: model.to_string(),
+ });
+ }
+ Ok(())
+}
+
+#[derive(Debug)]
+pub struct ModelNotAllowedError {
+ pub model: String,
+}
+
+impl std::fmt::Display for ModelNotAllowedError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Model not allowed: {}", self.model)
+ }
+}
+
+impl std::error::Error for ModelNotAllowedError {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolve_haiku_to_default() {
+ assert_eq!(resolve_model("haiku"), KIMI_DEFAULT_MODEL);
+ }
+
+ #[test]
+ fn resolve_unknown_to_default() {
+ assert_eq!(resolve_model("unknown-model"), KIMI_DEFAULT_MODEL);
+ }
+
+ #[test]
+ fn resolve_kimi_for_coding() {
+ assert_eq!(resolve_model("kimi-for-coding"), KIMI_DEFAULT_MODEL);
+ }
+
+ #[test]
+ fn assert_allowed_accepts_default() {
+ assert!(assert_allowed_model(KIMI_DEFAULT_MODEL).is_ok());
+ }
+
+ #[test]
+ fn assert_allowed_rejects_other() {
+ assert!(assert_allowed_model("kimi-k2.6").is_err());
+ }
+}
diff --git a/src/providers/kimi/translate/reducer.rs b/src/providers/kimi/translate/reducer.rs
new file mode 100644
index 0000000..9043533
--- /dev/null
+++ b/src/providers/kimi/translate/reducer.rs
@@ -0,0 +1,507 @@
+use crate::anthropic::sse::parse_sse_events;
+
+#[derive(Debug, Clone)]
+pub struct UpstreamStreamError {
+ pub kind: UpstreamErrorKind,
+ pub message: String,
+ pub retry_after_seconds: Option<u64>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UpstreamErrorKind {
+ RateLimit,
+ Failed,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct KimiUsage {
+ pub prompt_tokens: Option<u64>,
+ pub completion_tokens: Option<u64>,
+ pub total_tokens: Option<u64>,
+ pub cached_tokens: Option<u64>,
+ pub reasoning_tokens: Option<u64>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum StopReason {
+ EndTurn,
+ ToolUse,
+ MaxTokens,
+}
+
+#[derive(Debug, Clone)]
+pub enum ReducerEvent {
+ ThinkingStart {
+ index: usize,
+ },
+ ThinkingDelta {
+ index: usize,
+ text: String,
+ },
+ ThinkingStop {
+ index: usize,
+ },
+ TextStart {
+ index: usize,
+ },
+ TextDelta {
+ index: usize,
+ text: String,
+ },
+ TextStop {
+ index: usize,
+ },
+ ToolStart {
+ index: usize,
+ id: String,
+ name: String,
+ },
+ ToolDelta {
+ index: usize,
+ partial_json: String,
+ },
+ ToolStop {
+ index: usize,
+ },
+ Finish {
+ stop_reason: StopReason,
+ usage: Option<KimiUsage>,
+ },
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamChunk {
+ #[serde(default)]
+ choices: Option<Vec<StreamChoice>>,
+ #[serde(default)]
+ usage: Option<StreamUsage>,
+ #[serde(default)]
+ error: Option<StreamError>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamChoice {
+ #[serde(default)]
+ delta: Option<StreamDelta>,
+ #[serde(default)]
+ finish_reason: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamDelta {
+ #[serde(default)]
+ role: Option<String>,
+ #[serde(default)]
+ content: Option<String>,
+ #[serde(default)]
+ reasoning_content: Option<String>,
+ #[serde(default)]
+ tool_calls: Option<Vec<StreamToolCall>>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamToolCall {
+ index: usize,
+ #[serde(default)]
+ id: Option<String>,
+ #[serde(default)]
+ r#type: Option<String>,
+ #[serde(default)]
+ function: Option<StreamToolCallFunction>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamToolCallFunction {
+ #[serde(default)]
+ name: Option<String>,
+ #[serde(default)]
+ arguments: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamUsage {
+ #[serde(default)]
+ prompt_tokens: Option<u64>,
+ #[serde(default)]
+ completion_tokens: Option<u64>,
+ #[serde(default)]
+ total_tokens: Option<u64>,
+ #[serde(default)]
+ cached_tokens: Option<u64>,
+ #[serde(default)]
+ prompt_tokens_details: Option<PromptTokensDetails>,
+ #[serde(default)]
+ completion_tokens_details: Option<CompletionTokensDetails>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct PromptTokensDetails {
+ #[serde(default)]
+ cached_tokens: Option<u64>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct CompletionTokensDetails {
+ #[serde(default)]
+ reasoning_tokens: Option<u64>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+struct StreamError {
+ #[serde(default)]
+ message: Option<String>,
+ #[serde(default)]
+ r#type: Option<String>,
+}
+
+#[allow(dead_code)]
+struct ToolSlot {
+ block_index: usize,
+ id: String,
+ name: String,
+}
+
+pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, UpstreamStreamError> {
+ let sse_events = parse_sse_events(input);
+ let mut out = Vec::new();
+ let mut next_block_index = 0usize;
+ let mut thinking_index: Option<usize> = None;
+ let mut text_index: Option<usize> = None;
+ let mut tool_slots: Vec<ToolSlot> = Vec::new();
+ let mut saw_tool_calls = false;
+ let mut finish_reason: Option<String> = None;
+ let mut final_usage: Option<KimiUsage> = None;
+
+ for evt in &sse_events {
+ let data = evt.data.trim();
+ if data.is_empty() || data == "[DONE]" {
+ continue;
+ }
+
+ let chunk: StreamChunk = match serde_json::from_str(data) {
+ Ok(c) => c,
+ Err(_) => continue,
+ };
+
+ if let Some(ref err) = chunk.error {
+ return Err(UpstreamStreamError {
+ kind: UpstreamErrorKind::Failed,
+ message: err
+ .message
+ .clone()
+ .unwrap_or_else(|| "Upstream error".to_string()),
+ retry_after_seconds: None,
+ });
+ }
+
+ if chunk.usage.is_some() && chunk.choices.as_ref().map(|c| c.is_empty()).unwrap_or(true) {
+ final_usage = chunk.usage.map(|u| kimi_usage_from_stream(&u));
+ continue;
+ }
+
+ let choice = match chunk.choices.as_ref().and_then(|c| c.first()) {
+ Some(c) => c,
+ None => continue,
+ };
+ let delta = match choice.delta.as_ref() {
+ Some(d) => d,
+ None => {
+ if choice.finish_reason.is_some() {
+ finish_reason = choice.finish_reason.clone();
+ if chunk.usage.is_some() {
+ final_usage = chunk.usage.map(|u| kimi_usage_from_stream(&u));
+ }
+ }
+ continue;
+ }
+ };
+
+ // Reasoning content
+ if let Some(ref reasoning) = delta.reasoning_content {
+ if !reasoning.is_empty() {
+ if thinking_index.is_none() {
+ thinking_index = Some(next_block_index);
+ next_block_index += 1;
+ out.push(ReducerEvent::ThinkingStart {
+ index: thinking_index.unwrap(),
+ });
+ }
+ out.push(ReducerEvent::ThinkingDelta {
+ index: thinking_index.unwrap(),
+ text: reasoning.clone(),
+ });
+ }
+ }
+
+ // Content text
+ if let Some(ref content) = delta.content {
+ if !content.is_empty() {
+ // Close thinking before text
+ if let Some(ti) = thinking_index.take() {
+ out.push(ReducerEvent::ThinkingStop { index: ti });
+ }
+ if text_index.is_none() {
+ text_index = Some(next_block_index);
+ next_block_index += 1;
+ out.push(ReducerEvent::TextStart {
+ index: text_index.unwrap(),
+ });
+ }
+ out.push(ReducerEvent::TextDelta {
+ index: text_index.unwrap(),
+ text: content.clone(),
+ });
+ }
+ }
+
+ // Tool calls
+ if let Some(ref tool_calls) = delta.tool_calls {
+ if !tool_calls.is_empty() {
+ // Close thinking and text before tools
+ if let Some(ti) = thinking_index.take() {
+ out.push(ReducerEvent::ThinkingStop { index: ti });
+ }
+ if let Some(ti) = text_index.take() {
+ out.push(ReducerEvent::TextStop { index: ti });
+ }
+
+ for tc in tool_calls {
+ let existing_pos = tool_slots.iter().position(|s| s.block_index == tc.index);
+ let block_index = if let Some(pos) = existing_pos {
+ tool_slots[pos].block_index
+ } else {
+ let id = tc.id.clone().unwrap_or_default();
+ let name = tc
+ .function
+ .as_ref()
+ .and_then(|f| f.name.clone())
+ .unwrap_or_default();
+ if id.is_empty() || name.is_empty() {
+ // Defensive: skip out-of-order fragments
+ continue;
+ }
+ saw_tool_calls = true;
+ let bi = next_block_index;
+ next_block_index += 1;
+ tool_slots.push(ToolSlot {
+ block_index: bi,
+ id: id.clone(),
+ name: name.clone(),
+ });
+ out.push(ReducerEvent::ToolStart {
+ index: bi,
+ id,
+ name,
+ });
+ bi
+ };
+
+ if let Some(args) = tc.function.as_ref().and_then(|f| f.arguments.as_ref()) {
+ if !args.is_empty() {
+ out.push(ReducerEvent::ToolDelta {
+ index: block_index,
+ partial_json: args.to_string(),
+ });
+ }
+ }
+ }
+ }
+ }
+
+ // Finish reason on choice level
+ if let Some(ref reason) = choice.finish_reason {
+ finish_reason = Some(reason.clone());
+ if chunk.usage.is_some() {
+ final_usage = chunk.usage.map(|u| kimi_usage_from_stream(&u));
+ }
+ }
+ }
+
+ // Close any open blocks
+ if let Some(ti) = thinking_index.take() {
+ out.push(ReducerEvent::ThinkingStop { index: ti });
+ }
+ if let Some(ti) = text_index.take() {
+ out.push(ReducerEvent::TextStop { index: ti });
+ }
+ for slot in tool_slots.iter() {
+ out.push(ReducerEvent::ToolStop {
+ index: slot.block_index,
+ });
+ }
+
+ let stop_reason = match finish_reason.as_deref() {
+ Some("length") => StopReason::MaxTokens,
+ Some("tool_calls") => StopReason::ToolUse,
+ _ if saw_tool_calls => StopReason::ToolUse,
+ _ => StopReason::EndTurn,
+ };
+
+ out.push(ReducerEvent::Finish {
+ stop_reason,
+ usage: final_usage,
+ });
+
+ Ok(out)
+}
+
+fn kimi_usage_from_stream(u: &StreamUsage) -> KimiUsage {
+ KimiUsage {
+ prompt_tokens: u.prompt_tokens,
+ completion_tokens: u.completion_tokens,
+ total_tokens: u.total_tokens,
+ cached_tokens: u
+ .prompt_tokens_details
+ .as_ref()
+ .and_then(|d| d.cached_tokens)
+ .or(u.cached_tokens),
+ reasoning_tokens: u
+ .completion_tokens_details
+ .as_ref()
+ .and_then(|d| d.reasoning_tokens),
+ }
+}
+
+pub fn map_usage_to_anthropic(u: &Option<KimiUsage>) -> AnthropicUsage {
+ let usage = match u {
+ Some(u) => u,
+ None => return AnthropicUsage::default(),
+ };
+ let cached = usage.cached_tokens.unwrap_or(0);
+ let total_prompt = usage.prompt_tokens.unwrap_or(0);
+
+ // Subtract cached from input_tokens like reference does
+ let input_tokens = total_prompt.saturating_sub(cached);
+ AnthropicUsage {
+ input_tokens,
+ output_tokens: usage.completion_tokens.unwrap_or(0),
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: cached,
+ }
+}
+
+#[derive(Debug, Clone, Default, serde::Serialize)]
+pub struct AnthropicUsage {
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cache_creation_input_tokens: u64,
+ pub cache_read_input_tokens: u64,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reducer_maps_reasoning_text_tool_and_usage() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"think\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"search\",\"arguments\":\"{\\\"q\\\"\"}}]}}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\":\\\"rust\\\"}\"}}]}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":3,\"prompt_tokens_details\":{\"cached_tokens\":4}}}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let events = reduce_upstream_bytes(upstream.as_bytes()).unwrap();
+ assert!(
+ events
+ .iter()
+ .any(|e| matches!(e, ReducerEvent::ThinkingDelta { text, .. } if text == "think"))
+ );
+ assert!(events.iter().any(|e| matches!(
+ e,
+ ReducerEvent::Finish {
+ stop_reason: StopReason::ToolUse,
+ ..
+ }
+ )));
+ }
+
+ #[test]
+ fn reducer_handles_simple_text() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"hello\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"content\":\" world\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let events = reduce_upstream_bytes(upstream.as_bytes()).unwrap();
+ assert!(
+ events
+ .iter()
+ .any(|e| matches!(e, ReducerEvent::TextStart { .. }))
+ );
+ let texts: Vec<&str> = events
+ .iter()
+ .filter_map(|e| match e {
+ ReducerEvent::TextDelta { text, .. } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(texts, vec!["hello", " world"]);
+ assert!(events.iter().any(|e| matches!(
+ e,
+ ReducerEvent::Finish {
+ stop_reason: StopReason::EndTurn,
+ ..
+ }
+ )));
+ }
+
+ #[test]
+ fn reducer_handles_max_tokens() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"length\"}]}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let events = reduce_upstream_bytes(upstream.as_bytes()).unwrap();
+ assert!(events.iter().any(|e| matches!(
+ e,
+ ReducerEvent::Finish {
+ stop_reason: StopReason::MaxTokens,
+ ..
+ }
+ )));
+ }
+
+ #[test]
+ fn reducer_ignores_invalid_json() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"valid\"}}]}\n\n",
+ "data: not json\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}]}\n\n",
+ );
+ let events = reduce_upstream_bytes(upstream.as_bytes()).unwrap();
+ let texts: Vec<&str> = events
+ .iter()
+ .filter_map(|e| match e {
+ ReducerEvent::TextDelta { text, .. } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(texts, vec!["valid"]);
+ }
+
+ #[test]
+ fn reducer_returns_error_on_upstream_error() {
+ let upstream = concat!("data: {\"error\":{\"message\":\"rate limit exceeded\"}}\n\n",);
+ let result = reduce_upstream_bytes(upstream.as_bytes());
+ assert!(result.is_err());
+ assert_eq!(result.unwrap_err().kind, UpstreamErrorKind::Failed);
+ }
+
+ #[test]
+ fn map_usage_subtracts_cached() {
+ let usage = KimiUsage {
+ prompt_tokens: Some(100),
+ completion_tokens: Some(50),
+ cached_tokens: Some(20),
+ ..Default::default()
+ };
+ let mapped = map_usage_to_anthropic(&Some(usage));
+ assert_eq!(mapped.input_tokens, 80);
+ assert_eq!(mapped.output_tokens, 50);
+ assert_eq!(mapped.cache_read_input_tokens, 20);
+ }
+}
diff --git a/src/providers/kimi/translate/request.rs b/src/providers/kimi/translate/request.rs
new file mode 100644
index 0000000..6f117d2
--- /dev/null
+++ b/src/providers/kimi/translate/request.rs
@@ -0,0 +1,1022 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::model_allowlist::{KIMI_DEFAULT_MODEL, assert_allowed_model, resolve_model};
+use crate::anthropic::schema::MessagesRequest;
+
+// ---------------------------------------------------------------------------
+// Kimi OpenAI-compatible chat-completions types
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiChatRequest {
+ pub model: String,
+ pub messages: Vec<KimiMessage>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tools: Option<Vec<KimiTool>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tool_choice: Option<KimiToolChoice>,
+ pub stream: bool,
+ pub stream_options: KimiStreamOptions,
+ pub max_tokens: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reasoning_effort: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thinking: Option<KimiThinking>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prompt_cache_key: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiStreamOptions {
+ pub include_usage: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiThinking {
+ #[serde(rename = "type")]
+ pub kind: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum KimiToolChoice {
+ Auto,
+ None,
+ Required,
+ Function {
+ #[serde(rename = "type")]
+ kind: String,
+ function: KimiToolChoiceFunction,
+ },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiToolChoiceFunction {
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum KimiMessage {
+ System {
+ role: String,
+ content: String,
+ },
+ User {
+ role: String,
+ content: serde_json::Value,
+ },
+ Assistant {
+ role: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ content: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ reasoning_content: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ tool_calls: Option<Vec<KimiAssistantToolCall>>,
+ },
+ Tool {
+ role: String,
+ tool_call_id: String,
+ content: serde_json::Value,
+ },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiAssistantToolCall {
+ pub id: String,
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub function: KimiToolCallFunction,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiToolCallFunction {
+ pub name: String,
+ pub arguments: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiTool {
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub function: KimiToolFunction,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KimiToolFunction {
+ pub name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
+ pub parameters: serde_json::Value,
+}
+
+pub struct TranslateOptions {
+ pub session_id: Option<String>,
+}
+
+const DEFAULT_MAX_TOKENS: u32 = 32000;
+
+// ---------------------------------------------------------------------------
+// Content block types (parsed from serde_json::Value)
+// ---------------------------------------------------------------------------
+
+#[derive(Debug)]
+pub enum ContentBlock {
+ Text {
+ text: String,
+ },
+ Image {
+ source: ImageSource,
+ },
+ ToolUse {
+ id: String,
+ name: String,
+ input: Value,
+ },
+ ToolResult {
+ tool_use_id: String,
+ content: Value,
+ is_error: Option<bool>,
+ },
+ Thinking {
+ thinking: String,
+ },
+}
+
+#[derive(Debug)]
+pub struct ImageSource {
+ pub media_type: String,
+ pub data: String,
+ pub source_type: String,
+}
+
+// ---------------------------------------------------------------------------
+// Translation entry point
+// ---------------------------------------------------------------------------
+
+pub fn translate_request(
+ req: &MessagesRequest,
+ opts: TranslateOptions,
+) -> Result<KimiChatRequest, anyhow::Error> {
+ let model = req.model.as_deref().unwrap_or(KIMI_DEFAULT_MODEL);
+ let resolved = resolve_model(model);
+ assert_allowed_model(&resolved).map_err(|e| anyhow::anyhow!("{e}"))?;
+
+ let messages = build_messages(req)?;
+ let tools = read_tools(req)?;
+ let tool_choice = read_tool_choice(req)?;
+
+ let mut out = KimiChatRequest {
+ model: resolved,
+ messages,
+ stream: true,
+ stream_options: KimiStreamOptions {
+ include_usage: true,
+ },
+ max_tokens: clamp_max_tokens(req.max_tokens),
+ reasoning_effort: Some(map_reasoning_effort(read_effort(req)?)),
+ thinking: Some(KimiThinking {
+ kind: "enabled".to_string(),
+ }),
+ tools: if tools.is_empty() { None } else { Some(tools) },
+ tool_choice,
+ prompt_cache_key: opts.session_id,
+ };
+
+ // Collapse auto tool_choice to None (default behavior)
+ if matches!(out.tool_choice, Some(KimiToolChoice::Auto)) {
+ out.tool_choice = None;
+ }
+
+ Ok(out)
+}
+
+fn clamp_max_tokens(requested: Option<u32>) -> u32 {
+ match requested {
+ Some(v) if v > 0 => v.min(DEFAULT_MAX_TOKENS),
+ _ => DEFAULT_MAX_TOKENS,
+ }
+}
+
+fn map_reasoning_effort(effort: Option<&str>) -> String {
+ match effort {
+ Some("max") => "high".to_string(),
+ Some(v) => v.to_string(),
+ None => "medium".to_string(),
+ }
+}
+
+fn read_effort(req: &MessagesRequest) -> Result<Option<&str>, anyhow::Error> {
+ let output_config = match req.extra.get("output_config") {
+ Some(Value::Object(m)) => m,
+ _ => return Ok(None),
+ };
+ match output_config.get("effort") {
+ Some(Value::String(s)) => {
+ let valid = ["low", "medium", "high", "max"];
+ if valid.contains(&s.as_str()) {
+ Ok(Some(s.as_str()))
+ } else {
+ anyhow::bail!("Invalid output_config.effort: {s}")
+ }
+ }
+ _ => Ok(None),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tool & tool_choice reading
+// ---------------------------------------------------------------------------
+
+fn map_tool_choice(choice: &serde_json::Map<String, Value>) -> KimiToolChoice {
+ match choice.get("type").and_then(|v| v.as_str()) {
+ Some("auto") => KimiToolChoice::Auto,
+ Some("none") => KimiToolChoice::None,
+ Some("any") => KimiToolChoice::Required,
+ Some("tool") => {
+ if let Some(name) = choice.get("name").and_then(|v| v.as_str()) {
+ KimiToolChoice::Function {
+ kind: "function".to_string(),
+ function: KimiToolChoiceFunction {
+ name: name.to_string(),
+ },
+ }
+ } else {
+ KimiToolChoice::Required
+ }
+ }
+ _ => KimiToolChoice::Auto,
+ }
+}
+
+fn read_tool_choice(req: &MessagesRequest) -> Result<Option<KimiToolChoice>, anyhow::Error> {
+ match req.extra.get("tool_choice") {
+ Some(Value::Object(choice)) => Ok(Some(map_tool_choice(choice))),
+ Some(Value::String(s)) => Ok(Some(match s.as_str() {
+ "auto" => KimiToolChoice::Auto,
+ "none" => KimiToolChoice::None,
+ "any" | "required" => KimiToolChoice::Required,
+ _ => KimiToolChoice::Auto,
+ })),
+ _ => Ok(None),
+ }
+}
+
+fn read_tools(req: &MessagesRequest) -> Result<Vec<KimiTool>, anyhow::Error> {
+ let Some(tools) = req.extra.get("tools") else {
+ return Ok(Vec::new());
+ };
+ let tools_arr = match tools {
+ Value::Array(a) => a,
+ _ => return Ok(Vec::new()),
+ };
+ let mut out = Vec::new();
+ for tool in tools_arr {
+ let name = tool
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let description = tool
+ .get("description")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+ let parameters = tool
+ .get("input_schema")
+ .cloned()
+ .unwrap_or(serde_json::json!({}));
+ out.push(KimiTool {
+ kind: "function".to_string(),
+ function: KimiToolFunction {
+ name,
+ description,
+ parameters,
+ },
+ });
+ }
+ Ok(out)
+}
+
+// ---------------------------------------------------------------------------
+// System text extraction
+// ---------------------------------------------------------------------------
+
+fn flatten_system_text(system_val: Option<&Value>) -> Option<String> {
+ let system = system_val?;
+ let texts: Vec<String> = match system {
+ Value::String(s) => vec![s.clone()],
+ Value::Array(arr) => arr
+ .iter()
+ .filter_map(|b| {
+ let text = b.get("text").and_then(|v| v.as_str())?;
+ if text.starts_with("x-anthropic-billing-header:") {
+ None
+ } else {
+ Some(text.to_string())
+ }
+ })
+ .collect(),
+ _ => return None,
+ };
+ if texts.is_empty() {
+ None
+ } else {
+ Some(texts.join("\n\n"))
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Message building
+// ---------------------------------------------------------------------------
+
+fn build_messages(req: &MessagesRequest) -> Result<Vec<KimiMessage>, anyhow::Error> {
+ let mut out: Vec<KimiMessage> = Vec::new();
+
+ // System message
+ if let Some(system) = flatten_system_text(req.extra.get("system")) {
+ out.push(KimiMessage::System {
+ role: "system".to_string(),
+ content: system,
+ });
+ }
+
+ // Convert each message
+ for msg in &req.messages {
+ let blocks = normalize_content(&msg.content);
+ match msg.role.as_str() {
+ "user" => push_user_messages(&mut out, &blocks),
+ "assistant" => push_assistant_message(&mut out, &blocks),
+ other => {
+ anyhow::bail!("unexpected message role: {other}");
+ }
+ }
+ }
+
+ Ok(out)
+}
+
+fn push_user_messages(out: &mut Vec<KimiMessage>, blocks: &[ContentBlock]) {
+ let mut buffer: Vec<KimiUserContentPart> = Vec::new();
+
+ let flush_buffer = |out: &mut Vec<KimiMessage>, buffer: &mut Vec<KimiUserContentPart>| {
+ if buffer.is_empty() {
+ return;
+ }
+ let all_text = buffer
+ .iter()
+ .all(|p| matches!(p, KimiUserContentPart::Text { .. }));
+ if all_text {
+ let joined: String = buffer
+ .iter()
+ .map(|p| match p {
+ KimiUserContentPart::Text { text } => text.as_str(),
+ _ => "",
+ })
+ .collect();
+ out.push(KimiMessage::User {
+ role: "user".to_string(),
+ content: Value::String(joined),
+ });
+ } else {
+ let parts: Vec<KimiUserContentPart> = buffer.drain(..).collect();
+ out.push(KimiMessage::User {
+ role: "user".to_string(),
+ content: serde_json::to_value(parts).unwrap_or_default(),
+ });
+ return;
+ }
+ buffer.clear();
+ };
+
+ for block in blocks {
+ match block {
+ ContentBlock::Text { text } => {
+ buffer.push(KimiUserContentPart::Text { text: text.clone() });
+ }
+ ContentBlock::Image { source } => {
+ let url = if source.source_type == "url" {
+ source.data.clone()
+ } else {
+ format!("data:{};base64,{}", source.media_type, source.data)
+ };
+ buffer.push(KimiUserContentPart::ImageUrl {
+ image_url: KimiImageUrl { url },
+ });
+ }
+ ContentBlock::ToolResult {
+ tool_use_id,
+ content,
+ is_error,
+ } => {
+ // flush any buffered user content first
+ let mut temp = Vec::new();
+ std::mem::swap(&mut buffer, &mut temp);
+ flush_buffer(out, &mut temp);
+
+ out.push(KimiMessage::Tool {
+ role: "tool".to_string(),
+ tool_call_id: tool_use_id.clone(),
+ content: tool_result_content(content, *is_error),
+ });
+ }
+ _ => {}
+ }
+ }
+
+ // flush remaining buffer
+ flush_buffer(out, &mut buffer);
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(untagged)]
+enum KimiUserContentPart {
+ Text { text: String },
+ ImageUrl { image_url: KimiImageUrl },
+}
+
+#[derive(Debug, Clone, Serialize)]
+struct KimiImageUrl {
+ url: String,
+}
+
+fn tool_result_content(content: &Value, is_error: Option<bool>) -> Value {
+ let prefix = if is_error.unwrap_or(false) {
+ "[tool execution error]\n"
+ } else {
+ ""
+ };
+
+ match content {
+ Value::String(s) => Value::String(format!("{prefix}{s}")),
+ Value::Array(arr) => {
+ let mut parts: Vec<KimiToolResultPart> = Vec::new();
+ if !prefix.is_empty() {
+ parts.push(KimiToolResultPart::Text {
+ text: prefix.to_string(),
+ });
+ }
+ for b in arr {
+ match b.get("type").and_then(|v| v.as_str()) {
+ Some("text") => {
+ let text = b.get("text").and_then(|v| v.as_str()).unwrap_or("");
+ parts.push(KimiToolResultPart::Text {
+ text: text.to_string(),
+ });
+ }
+ Some("image") => {
+ let url = image_block_to_url(b);
+ parts.push(KimiToolResultPart::ImageUrl {
+ image_url: KimiImageUrl { url },
+ });
+ }
+ Some(other) => {
+ parts.push(KimiToolResultPart::Text {
+ text: format!("[unsupported content block omitted: {other}]"),
+ });
+ }
+ None => {}
+ }
+ }
+
+ // Collapse to string when only one text part
+ if parts.len() == 1 {
+ if let KimiToolResultPart::Text { text } = &parts[0] {
+ return Value::String(text.clone());
+ }
+ }
+
+ serde_json::to_value(parts).unwrap_or(Value::String(prefix.to_string()))
+ }
+ _ => Value::String(prefix.to_string()),
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(untagged)]
+enum KimiToolResultPart {
+ Text { text: String },
+ ImageUrl { image_url: KimiImageUrl },
+}
+
+fn image_block_to_url(block: &Value) -> String {
+ let source_type = block
+ .get("source")
+ .and_then(|s| s.get("type"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("base64");
+ if source_type == "url" {
+ block
+ .get("source")
+ .and_then(|s| s.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string()
+ } else {
+ let media_type = block
+ .get("source")
+ .and_then(|s| s.get("media_type"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("image/png");
+ let data = block
+ .get("source")
+ .and_then(|s| s.get("data"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ format!("data:{media_type};base64,{data}")
+ }
+}
+
+fn push_assistant_message(out: &mut Vec<KimiMessage>, blocks: &[ContentBlock]) {
+ let mut text_parts: Vec<String> = Vec::new();
+ let mut thinking_parts: Vec<String> = Vec::new();
+ let mut tool_calls: Vec<KimiAssistantToolCall> = Vec::new();
+
+ for block in blocks {
+ match block {
+ ContentBlock::Text { text } => {
+ if !text.is_empty() {
+ text_parts.push(text.clone());
+ }
+ }
+ ContentBlock::Thinking { thinking } => {
+ if !thinking.is_empty() {
+ thinking_parts.push(thinking.clone());
+ }
+ }
+ ContentBlock::ToolUse { id, name, input } => {
+ let args = serde_json::to_string(input).unwrap_or_else(|_| "{}".to_string());
+ tool_calls.push(KimiAssistantToolCall {
+ id: id.clone(),
+ kind: "function".to_string(),
+ function: KimiToolCallFunction {
+ name: name.clone(),
+ arguments: args,
+ },
+ });
+ }
+ // Image blocks from assistant are dropped
+ _ => {}
+ }
+ }
+
+ if text_parts.is_empty() && tool_calls.is_empty() && thinking_parts.is_empty() {
+ return;
+ }
+
+ let content = if text_parts.is_empty() {
+ Some(String::new())
+ } else {
+ Some(text_parts.join(""))
+ };
+
+ let reasoning_content = if thinking_parts.is_empty() {
+ None
+ } else {
+ Some(thinking_parts.join("\n\n"))
+ };
+
+ let tool_calls_val = if tool_calls.is_empty() {
+ None
+ } else {
+ Some(tool_calls)
+ };
+
+ out.push(KimiMessage::Assistant {
+ role: "assistant".to_string(),
+ content,
+ reasoning_content,
+ tool_calls: tool_calls_val,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Content normalization (parse serde_json::Value to typed ContentBlocks)
+// ---------------------------------------------------------------------------
+
+fn normalize_content(content: &Value) -> Vec<ContentBlock> {
+ match content {
+ Value::String(s) => {
+ vec![ContentBlock::Text { text: s.clone() }]
+ }
+ Value::Array(arr) => {
+ let mut blocks = Vec::new();
+ for item in arr {
+ if let Some(block) = parse_content_block(item) {
+ blocks.push(block);
+ }
+ }
+ blocks
+ }
+ _ => Vec::new(),
+ }
+}
+
+fn parse_content_block(value: &Value) -> Option<ContentBlock> {
+ let kind = value.get("type").and_then(|v| v.as_str())?;
+ match kind {
+ "text" => {
+ let text = value
+ .get("text")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Some(ContentBlock::Text { text })
+ }
+ "image" => {
+ let source = value.get("source")?;
+ let media_type = source
+ .get("media_type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("image/png")
+ .to_string();
+ let source_type = source
+ .get("type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("base64")
+ .to_string();
+ let data = if source_type == "url" {
+ source.get("url").and_then(|v| v.as_str()).unwrap_or("")
+ } else {
+ source.get("data").and_then(|v| v.as_str()).unwrap_or("")
+ }
+ .to_string();
+ Some(ContentBlock::Image {
+ source: ImageSource {
+ media_type,
+ data,
+ source_type,
+ },
+ })
+ }
+ "tool_use" => {
+ let id = value
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let name = value
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let input = value.get("input").cloned().unwrap_or(serde_json::json!({}));
+ Some(ContentBlock::ToolUse { id, name, input })
+ }
+ "tool_result" => {
+ let tool_use_id = value
+ .get("tool_use_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let content = value
+ .get("content")
+ .cloned()
+ .unwrap_or(Value::String(String::new()));
+ let is_error = value.get("is_error").and_then(|v| v.as_bool());
+ Some(ContentBlock::ToolResult {
+ tool_use_id,
+ content,
+ is_error,
+ })
+ }
+ "thinking" => {
+ let thinking = value
+ .get("thinking")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Some(ContentBlock::Thinking { thinking })
+ }
+ _ => None,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn translate_text_request_defaults_like_reference() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "haiku",
+ "max_tokens": 10,
+ "system": "sys",
+ "messages": [{"role": "user", "content": "hello"}],
+ "tools": [{"name":"search","description":"Search","input_schema":{"type":"object"}}],
+ "tool_choice": {"type":"tool", "name":"search"},
+ "output_config": {"effort":"max"}
+ }))
+ .unwrap();
+ let translated = translate_request(
+ &req,
+ TranslateOptions {
+ session_id: Some("sid".into()),
+ },
+ )
+ .unwrap();
+ assert_eq!(translated.model, "kimi-for-coding");
+ assert_eq!(translated.reasoning_effort.as_deref(), Some("high"));
+ assert_eq!(translated.prompt_cache_key.as_deref(), Some("sid"));
+ assert_eq!(translated.max_tokens, 10);
+ }
+
+ #[test]
+ fn translate_tool_result_with_unsupported_blocks() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-k2",
+ "messages": [{
+ "role": "user",
+ "content": [{
+ "type": "tool_result",
+ "tool_use_id": "toolu_1",
+ "content": [
+ {"type": "text", "text": "visible output"},
+ {"type": "thinking", "thinking": "hidden thought"}
+ ]
+ }]
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ // Should have one tool message
+ assert_eq!(translated.messages.len(), 1);
+ match &translated.messages[0] {
+ KimiMessage::Tool {
+ role,
+ tool_call_id,
+ content,
+ } => {
+ assert_eq!(role, "tool");
+ assert_eq!(tool_call_id, "toolu_1");
+ // content should be an array with text parts
+ let parts: Vec<&Value> = match content {
+ Value::Array(a) => a.iter().collect(),
+ _ => panic!("expected array content"),
+ };
+ assert_eq!(parts.len(), 2);
+ assert_eq!(
+ parts[0].get("text").and_then(|v| v.as_str()),
+ Some("visible output")
+ );
+ assert_eq!(
+ parts[1].get("text").and_then(|v| v.as_str()),
+ Some("[unsupported content block omitted: thinking]")
+ );
+ }
+ _ => panic!("expected Tool message"),
+ }
+ }
+
+ #[test]
+ fn translate_tool_result_with_image() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-k2",
+ "messages": [{
+ "role": "user",
+ "content": [{
+ "type": "tool_result",
+ "tool_use_id": "toolu_1",
+ "content": [
+ {"type": "text", "text": "caption"},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "abc"}}
+ ]
+ }]
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.messages.len(), 1);
+ match &translated.messages[0] {
+ KimiMessage::Tool {
+ role,
+ tool_call_id,
+ content,
+ } => {
+ assert_eq!(role, "tool");
+ assert_eq!(tool_call_id, "toolu_1");
+ let parts: Vec<&Value> = match content {
+ Value::Array(a) => a.iter().collect(),
+ _ => panic!("expected array"),
+ };
+ assert_eq!(parts.len(), 2);
+ assert_eq!(
+ parts[1]
+ .get("image_url")
+ .and_then(|u| u.get("url"))
+ .and_then(|v| v.as_str()),
+ Some("data:image/png;base64,abc")
+ );
+ }
+ _ => panic!("expected Tool message"),
+ }
+ }
+
+ #[test]
+ fn translate_assistant_with_thinking_tool_use_and_text() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "let me think..."},
+ {"type": "text", "text": "here's the answer"},
+ {"type": "tool_use", "id": "tu_1", "name": "search", "input": {"q": "rust"}}
+ ]
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.messages.len(), 1);
+ match &translated.messages[0] {
+ KimiMessage::Assistant {
+ role,
+ content,
+ reasoning_content,
+ tool_calls,
+ } => {
+ assert_eq!(role, "assistant");
+ assert_eq!(content.as_deref(), Some("here's the answer"));
+ assert_eq!(reasoning_content.as_deref(), Some("let me think..."));
+ assert!(tool_calls.is_some());
+ let tcs = tool_calls.as_ref().unwrap();
+ assert_eq!(tcs.len(), 1);
+ assert_eq!(tcs[0].function.name, "search");
+ }
+ _ => panic!("expected Assistant message"),
+ }
+ }
+
+ #[test]
+ fn translate_empty_assistant_content_emits_empty_string() {
+ // When there are no text blocks and no tool calls but there is thinking
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "thinking..."}
+ ]
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.messages.len(), 1);
+ match &translated.messages[0] {
+ KimiMessage::Assistant {
+ content,
+ reasoning_content,
+ ..
+ } => {
+ assert_eq!(content.as_deref(), Some(""));
+ assert_eq!(reasoning_content.as_deref(), Some("thinking..."));
+ }
+ _ => panic!("expected Assistant message"),
+ }
+ }
+
+ #[test]
+ fn translate_user_text_and_image_collapse_correctly() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "describe this"},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "xyz"}}
+ ]
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.messages.len(), 1);
+ match &translated.messages[0] {
+ KimiMessage::User { role, content } => {
+ assert_eq!(role, "user");
+ // Mixed text+image produces array, not string
+ assert!(content.is_array());
+ let parts = content.as_array().unwrap();
+ assert_eq!(parts.len(), 2);
+ assert_eq!(
+ parts[0].get("text").and_then(|v| v.as_str()),
+ Some("describe this")
+ );
+ assert!(parts[1].get("image_url").is_some());
+ }
+ _ => panic!("expected User message"),
+ }
+ }
+
+ #[test]
+ fn translate_text_only_user_collapses_to_string() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{
+ "role": "user",
+ "content": "hello"
+ }]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ match &translated.messages[0] {
+ KimiMessage::User { role, content } => {
+ assert_eq!(role, "user");
+ assert_eq!(content.as_str(), Some("hello"));
+ }
+ _ => panic!("expected User message"),
+ }
+ }
+
+ #[test]
+ fn max_tokens_defaults_to_32000() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hi"}]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.max_tokens, 32000);
+ }
+
+ #[test]
+ fn max_tokens_clamps_at_32000() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "max_tokens": 99999,
+ "messages": [{"role": "user", "content": "hi"}]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert_eq!(translated.max_tokens, 32000);
+ }
+
+ #[test]
+ fn invalid_effort_rejected() {
+ let req: Result<MessagesRequest, _> = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hi"}],
+ "output_config": {"effort": "extreme"}
+ }));
+ // The serde flatten extra captures it, so it parses. Error comes at translate time.
+ let req = req.unwrap();
+ let result = translate_request(&req, TranslateOptions { session_id: None });
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn auto_tool_choice_is_collapsed() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hi"}],
+ "tool_choice": {"type": "auto"}
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert!(translated.tool_choice.is_none());
+ }
+
+ #[test]
+ fn any_tool_choice_becomes_required() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "messages": [{"role": "user", "content": "hi"}],
+ "tools": [{"name":"search","input_schema":{"type":"object"}}],
+ "tool_choice": {"type": "any"}
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ assert!(matches!(
+ translated.tool_choice,
+ Some(KimiToolChoice::Required)
+ ));
+ }
+
+ #[test]
+ fn system_text_excludes_billing_headers() {
+ let req: MessagesRequest = serde_json::from_value(json!({
+ "model": "kimi-for-coding",
+ "system": [
+ {"type": "text", "text": "You are a helpful assistant."},
+ {"type": "text", "text": "x-anthropic-billing-header: secret"}
+ ],
+ "messages": [{"role": "user", "content": "hi"}]
+ }))
+ .unwrap();
+ let translated = translate_request(&req, TranslateOptions { session_id: None }).unwrap();
+ let system_msg = translated
+ .messages
+ .iter()
+ .find(|m| matches!(m, KimiMessage::System { .. }));
+ assert!(system_msg.is_some());
+ if let Some(KimiMessage::System { content, .. }) = system_msg {
+ assert!(!content.contains("x-anthropic-billing-header"));
+ assert!(content.contains("helpful"));
+ }
+ }
+}
diff --git a/src/providers/kimi/translate/signature.rs b/src/providers/kimi/translate/signature.rs
new file mode 100644
index 0000000..4d876b2
--- /dev/null
+++ b/src/providers/kimi/translate/signature.rs
@@ -0,0 +1,18 @@
+pub fn make_thinking_signature(message_id: &str, index: usize) -> String {
+ use base64::Engine;
+ let input = format!("ccp:kimi:v1:{message_id}:{index}");
+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(input.as_bytes())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn signature_is_reference_base64url() {
+ assert_eq!(
+ make_thinking_signature("msg_1", 2),
+ "Y2NwOmtpbWk6djE6bXNnXzE6Mg"
+ );
+ }
+}
diff --git a/src/providers/kimi/translate/stream.rs b/src/providers/kimi/translate/stream.rs
new file mode 100644
index 0000000..e055976
--- /dev/null
+++ b/src/providers/kimi/translate/stream.rs
@@ -0,0 +1,383 @@
+use super::reducer::{map_usage_to_anthropic, reduce_upstream_bytes};
+use super::signature::make_thinking_signature;
+use crate::anthropic::sse::encode_sse_event;
+
+pub fn translate_stream_bytes(
+ input: &[u8],
+ message_id: &str,
+ model: &str,
+) -> Result<Vec<u8>, anyhow::Error> {
+ let events = reduce_upstream_bytes(input)
+ .map_err(|e| anyhow::anyhow!("upstream stream error: {} ({:?})", e.message, e.kind))?;
+
+ let mut out = Vec::new();
+ let mut message_started = false;
+ let mut active_tools: Vec<(usize, String, String)> = Vec::new();
+
+ let mut emit = |event: Option<&str>, data: &str| {
+ out.extend_from_slice(&encode_sse_event(event, data));
+ };
+
+ for event in &events {
+ match event {
+ super::reducer::ReducerEvent::ThinkingStart { index } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let data = serde_json::json!({
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {
+ "type": "thinking",
+ "thinking": ""
+ }
+ });
+ emit(Some("content_block_start"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::ThinkingDelta { index, text } => {
+ // Ensure message start
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let data = serde_json::json!({
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {
+ "type": "thinking_delta",
+ "thinking": text
+ }
+ });
+ emit(Some("content_block_delta"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::ThinkingStop { index } => {
+ let data = serde_json::json!({
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {
+ "type": "signature_delta",
+ "signature": make_thinking_signature(message_id, *index)
+ }
+ });
+ emit(Some("content_block_delta"), &data.to_string());
+ let data = serde_json::json!({
+ "type": "content_block_stop",
+ "index": index,
+ });
+ emit(Some("content_block_stop"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::TextStart { index } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let data = serde_json::json!({
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {
+ "type": "text",
+ "text": ""
+ }
+ });
+ emit(Some("content_block_start"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::TextDelta { index, text } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let data = serde_json::json!({
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {
+ "type": "text_delta",
+ "text": text
+ }
+ });
+ emit(Some("content_block_delta"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::TextStop { index } => {
+ let data = serde_json::json!({
+ "type": "content_block_stop",
+ "index": index,
+ });
+ emit(Some("content_block_stop"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::ToolStart { index, id, name } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ active_tools.push((*index, id.clone(), name.clone()));
+ let data = serde_json::json!({
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {
+ "type": "tool_use",
+ "id": id,
+ "name": name,
+ "input": {}
+ }
+ });
+ emit(Some("content_block_start"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::ToolDelta {
+ index,
+ partial_json,
+ } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let data = serde_json::json!({
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": partial_json
+ }
+ });
+ emit(Some("content_block_delta"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::ToolStop { index } => {
+ active_tools.retain(|(i, _, _)| *i != *index);
+ let data = serde_json::json!({
+ "type": "content_block_stop",
+ "index": index,
+ });
+ emit(Some("content_block_stop"), &data.to_string());
+ }
+ super::reducer::ReducerEvent::Finish { stop_reason, usage } => {
+ if !message_started {
+ let data = serde_json::json!({
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [],
+ "stop_reason": null,
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ }
+ }
+ });
+ emit(Some("message_start"), &data.to_string());
+ message_started = true;
+ }
+ let sr = match stop_reason {
+ super::reducer::StopReason::EndTurn => "end_turn",
+ super::reducer::StopReason::ToolUse => "tool_use",
+ super::reducer::StopReason::MaxTokens => "max_tokens",
+ };
+ let mapped = map_usage_to_anthropic(usage);
+ let data = serde_json::json!({
+ "type": "message_delta",
+ "delta": {
+ "stop_reason": sr,
+ "stop_sequence": null
+ },
+ "usage": mapped
+ });
+ emit(Some("message_delta"), &data.to_string());
+ let data = serde_json::json!({
+ "type": "message_stop"
+ });
+ emit(Some("message_stop"), &data.to_string());
+ }
+ }
+ }
+
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn stream_translates_simple_text() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":1}}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let result =
+ translate_stream_bytes(upstream.as_bytes(), "msg_1", "kimi-for-coding").unwrap();
+ let output = String::from_utf8_lossy(&result);
+
+ // Should contain message_start, content_block_start, content_block_delta,
+ // content_block_stop, message_delta, message_stop
+ assert!(output.contains("message_start"), "missing message_start");
+ assert!(
+ output.contains("content_block_start"),
+ "missing content_block_start"
+ );
+ assert!(output.contains("text_delta"), "missing text_delta");
+ assert!(
+ output.contains("content_block_stop"),
+ "missing content_block_stop"
+ );
+ assert!(output.contains("message_delta"), "missing message_delta");
+ assert!(output.contains("message_stop"), "missing message_stop");
+ assert!(output.contains("end_turn"), "missing end_turn");
+ }
+
+ #[test]
+ fn stream_translates_reasoning_content() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n",
+ "data: {\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":5}}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let result = translate_stream_bytes(upstream.as_bytes(), "msg_2", "model").unwrap();
+ let output = String::from_utf8_lossy(&result);
+
+ assert!(output.contains("thinking_delta"), "missing thinking_delta");
+ assert!(
+ output.contains("signature_delta"),
+ "missing signature_delta"
+ );
+ assert!(output.contains("text_delta"), "missing text_delta");
+ }
+
+ #[test]
+ fn stream_translates_tool_calls() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"search\",\"arguments\":\"{\\\"q\\\":\\\"rust\\\"}\"}}]}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"tool_calls\"}]}\n\n",
+ "data: [DONE]\n\n"
+ );
+ let result = translate_stream_bytes(upstream.as_bytes(), "msg_3", "model").unwrap();
+ let output = String::from_utf8_lossy(&result);
+
+ assert!(output.contains("tool_use"), "missing tool_use");
+ assert!(
+ output.contains("input_json_delta"),
+ "missing input_json_delta"
+ );
+ assert!(
+ output.contains("tool_use"),
+ "missing tool_use in stop_reason"
+ );
+ }
+
+ #[test]
+ fn stream_emits_message_start_before_content_blocks() {
+ let upstream = concat!(
+ "data: {\"choices\":[{\"delta\":{\"content\":\"direct\"}}]}\n\n",
+ "data: {\"choices\":[{\"finish_reason\":\"stop\"}]}\n\n",
+ );
+ let result = translate_stream_bytes(upstream.as_bytes(), "msg_4", "model").unwrap();
+ let output = String::from_utf8_lossy(&result);
+
+ // message_start should come before content_block_start
+ let msg_start_pos = output.find("message_start").unwrap();
+ let cb_start_pos = output.find("content_block_start").unwrap();
+ assert!(
+ msg_start_pos < cb_start_pos,
+ "message_start should be before content_block_start"
+ );
+ }
+}
diff --git a/src/providers/mod.rs b/src/providers/mod.rs
new file mode 100644
index 0000000..fe085d1
--- /dev/null
+++ b/src/providers/mod.rs
@@ -0,0 +1 @@
+pub mod kimi;
diff --git a/src/registry.rs b/src/registry.rs
index 449e221..173c805 100644
--- a/src/registry.rs
+++ b/src/registry.rs
@@ -41,7 +41,7 @@ const CODEX_MODELS: &[&str] = &[
"gpt-5.5",
];
-const KIMI_MODELS: &[&str] = &["kimi-for-coding", "kimi-k2.6", "k2.6"];
+pub(crate) const KIMI_MODELS: &[&str] = &["kimi-for-coding", "kimi-k2.6", "k2.6"];
pub struct Registry {
alias_provider: AliasProvider,
@@ -61,10 +61,11 @@ impl Registry {
let mut handlers = BTreeMap::new();
for (name, entries) in &models {
- handlers.insert(
- name.clone(),
- Arc::new(PlaceholderProvider::new(name, entries.clone())) as Arc<dyn Provider>,
- );
+ let handler: Arc<dyn Provider> = match name.as_str() {
+ "kimi" => Arc::new(crate::providers::kimi::KimiProvider::new()),
+ _ => Arc::new(PlaceholderProvider::new(name, entries.clone())),
+ };
+ handlers.insert(name.clone(), handler);
}
Self {
diff --git a/tests/cli.rs b/tests/cli.rs
index bbfed31..ecb75ad 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -94,3 +94,19 @@ fn models_output_is_stable_order() -> Result<(), Box<dyn std::error::Error>> {
assert!(kimi_pos < cursor_pos);
Ok(())
}
+
+#[test]
+fn kimi_auth_status_reads_stored_auth() -> Result<(), Box<dyn std::error::Error>> {
+ let temp = TempDir::new()?;
+ let auth_dir = temp.path().join("kimi");
+ std::fs::create_dir_all(&auth_dir)?;
+ std::fs::write(
+ auth_dir.join("auth.json"),
+ r#"{"access":"a","refresh":"r","expires":4102444800000,"scope":"openid","userId":"u"}"#,
+ )?;
+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;
+ cmd.args(["kimi", "auth", "status"]);
+ cmd.env("CCP_CONFIG_DIR", temp.path());
+ cmd.assert().success().stdout(contains("User: u"));
+ Ok(())
+}