Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy
Rust
bootstrap rust foundation
Raine Virta2d70d3175a8d
diff --git a/.gitignore b/.gitignoreindex b947077..97f7d4a 100644--- a/.gitignore+++ b/.gitignore@@ -1,2 +1,3 @@node_modules/dist/+target/diff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..d4d8205--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,1167 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys",+]++[[package]]+name = "anyhow"+version = "1.0.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"++[[package]]+name = "assert_cmd"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6"+dependencies = [+ "anstyle",+ "bstr",+ "libc",+ "predicates",+ "predicates-core",+ "predicates-tree",+ "wait-timeout",+]++[[package]]+name = "async-trait"+version = "0.1.89"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "axum"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"+dependencies = [+ "axum-core",+ "axum-macros",+ "bytes",+ "form_urlencoded",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "serde_core",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-core"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-macros"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"++[[package]]+name = "bstr"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"+dependencies = [+ "memchr",+ "regex-automata",+ "serde_core",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytes"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "clap"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "clap_lex"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"++[[package]]+name = "claude-code-proxy"+version = "0.0.22"+dependencies = [+ "anyhow",+ "assert_cmd",+ "async-trait",+ "axum",+ "bytes",+ "clap",+ "futures-core",+ "futures-util",+ "http",+ "http-body-util",+ "predicates",+ "serde",+ "serde_json",+ "tempfile",+ "thiserror",+ "time",+ "tokio",+ "tower",+ "tracing",+ "tracing-subscriber",+ "uuid",+]++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"++[[package]]+name = "difflib"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "float-cmp"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8"+dependencies = [+ "num-traits",+]++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-channel"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+dependencies = [+ "futures-core",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-core",+ "futures-macro",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "http"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "httpdate",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "bytes",+ "http",+ "http-body",+ "hyper",+ "pin-project-lite",+ "tokio",+ "tower-service",+]++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "matchers"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"+dependencies = [+ "regex-automata",+]++[[package]]+name = "matchit"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"++[[package]]+name = "memchr"+version = "2.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "mio"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"+dependencies = [+ "libc",+ "wasi",+ "windows-sys",+]++[[package]]+name = "normalize-line-endings"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys",+]++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "predicates"+version = "3.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe"+dependencies = [+ "anstyle",+ "difflib",+ "float-cmp",+ "normalize-line-endings",+ "predicates-core",+ "regex",+]++[[package]]+name = "predicates-core"+version = "1.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144"++[[package]]+name = "predicates-tree"+version = "1.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2"+dependencies = [+ "predicates-core",+ "termtree",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "regex"+version = "1.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[package]]+name = "rustversion"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.150"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "socket2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "termtree"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thread_local"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"+dependencies = [+ "cfg-if",+]++[[package]]+name = "time"+version = "0.3.51"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dcef1a61bdb119096e153208ec5cbec23944ce8bca13be5c7f60c634f7403935"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tokio"+version = "1.52.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+dependencies = [+ "libc",+ "mio",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys",+]++[[package]]+name = "tokio-macros"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "log",+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+ "valuable",+]++[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core",+]++[[package]]+name = "tracing-serde"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"+dependencies = [+ "serde",+ "tracing-core",+]++[[package]]+name = "tracing-subscriber"+version = "0.3.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "serde",+ "serde_json",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",+ "tracing-serde",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "uuid"+version = "1.23.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"+dependencies = [+ "getrandom",+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "wait-timeout"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"+dependencies = [+ "libc",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[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.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "zmij"+version = "1.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..b56e0f5--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,32 @@+[package]+name = "claude-code-proxy"+version = "0.0.22"+description = "Anthropic-compatible proxy for Claude Code provider backends"+edition = "2024"+authors = ["Claude Code Proxy contributors"]+license = "MIT"++[dependencies]+clap = { version = "4.5", features = ["derive", "env"] }+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"+anyhow = "1.0"+thiserror = "2.0"+axum = { version = "0.8", features = ["macros"] }+tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "time", "fs"] }+tower = { version = "0.5", features = ["util"] }+http = "1"+http-body-util = "0.1"+bytes = "1"+futures-core = "0.3"+futures-util = "0.3"+async-trait = "0.1"+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"] }++[dev-dependencies]+tempfile = "3.14"+assert_cmd = "2"+predicates = "3"diff --git a/checkle.toml b/checkle.tomlnew file mode 100644index 0000000..6c621bb--- /dev/null+++ b/checkle.toml@@ -0,0 +1,23 @@+[[check]]+name = "format-check"+mode = "rustfmt"+command = ["cargo", "fmt", "--all", "--", "--check"]++[[check]]+name = "clippy"+mode = "cargo"+command = ["cargo", "clippy", "--all-targets", "--message-format=json"]++[[check]]+name = "build"+mode = "cargo"+command = ["cargo", "build", "--all", "--message-format=json"]++[[check]]+name = "test"+mode = "cargo"+command = ["cargo", "test", "--all", "--message-format=json"]++[[group]]+name = "all"+checks = ["format-check", "clippy", "build", "test"]diff --git a/hooks/pre-commit b/hooks/pre-commitnew file mode 100755index 0000000..bbcbdcf--- /dev/null+++ b/hooks/pre-commit@@ -0,0 +1,2 @@+#!/usr/bin/env bash+exec checkle pre-commitdiff --git a/justfile b/justfileindex 5a92a0a..5b65f3f 100644--- a/justfile+++ b/justfile@@ -1,89 +1,63 @@-# Glob list shared by check-format and fix-format. Each pattern stays-# single-quoted so the shell hands oxfmt the literal pattern.-oxfmt_globs := "'**/*.ts' '**/*.tsx' '**/*.js' '**/*.jsx' '**/*.mjs' '**/*.cjs' '**/*.mts' '**/*.cts' '**/*.json' '**/*.jsonc'"+# Rust project checks-# Point git at .githooks/ so the tracked hooks run. Idempotent.+set positional-arguments+set shell := ["bash", "-euo", "pipefail", "-c"]++# List available commands+default:+ @just --list++# Run project checks through checkle+check:+ checkle run all++# Run check and fail if there are uncommitted changes for CI+check-ci: check+ #!/usr/bin/env bash+ set -euo pipefail+ if ! git diff --quiet || ! git diff --cached --quiet; then+ echo "Error: check caused uncommitted changes"+ echo "Run 'just check' locally and commit the results"+ git diff --stat+ exit 1+ fi++# Install shims into the Git hooks directoryinstall-hooks:- git config core.hooksPath .githooks- @echo "git hooks installed (core.hooksPath=.githooks)"+ scripts/install-git-hook-shims++# Check Rust formatting through checkle+format:+ checkle run format-check-types:- bun run typecheck+# Check clippy through checkle+clippy:+ checkle run clippy-lint:- bunx oxlint --type-aware+# Check the build through checkle+build:+ checkle run build+# Run tests through checkletest:- bun test+ checkle run test-# Format check across JS/TS/JSON. Intentionally not part of `just check`.-check-format:- bunx oxfmt --check {{oxfmt_globs}}+# Install release binary globally+install:+ cargo install --offline --path . --locked-# Auto-fix formatting across JS/TS/JSON.-fix-format:- bunx oxfmt --write {{oxfmt_globs}}+# Install debug binary globally via symlink+install-dev:+ cargo build && ln -sf $(pwd)/target/debug/claude-code-proxy ~/.cargo/bin/claude-code-proxy-# Pre-push gate: format-check + the full check in parallel.-[parallel]-check-push: check-format check+# Run the application+run *ARGS:+ cargo run -- "$@"-# Runs types, lint, and tests in parallel.-# just check # quiet: one PASS/FAIL line per job-# just check --verbose # stream all output prefixed with [job]-check mode="":- #!/usr/bin/env bash- set -uo pipefail- case "{{mode}}" in- ""|--quiet) verbose=0 ;;- -v|--verbose) verbose=1 ;;- *) echo "usage: just check [--verbose|--quiet]" >&2; exit 2 ;;- esac- tmp=$(mktemp -d)- trap 'rm -rf "$tmp"' EXIT- if [ -t 1 ]; then export FORCE_COLOR=1; fi- if [ -t 1 ]; then- reset=$'\033[0m'- bold=$'\033[1m'- dim=$'\033[2m'- green=$'\033[32m'- red=$'\033[31m'- else- reset='' bold='' dim='' green='' red=''- fi- run() {- local label=$1 color=$2; shift 2- [ -z "$reset" ] && color=''- local prefix="${color}${bold}${label}${reset}${dim} |${reset} "- (- if [ "$verbose" = 1 ]; then- if "$@" 2>&1 | awk -v p="$prefix" '{print p $0}'; then- echo "${green}${bold}✔ PASS${reset} $label"- else- rc=${PIPESTATUS[0]}- echo "${red}${bold}✘ FAIL${reset} $label ${dim}(exit $rc)${reset}"- exit "$rc"- fi- else- if "$@" >"$tmp/$label.out" 2>&1; then- echo "${green}${bold}✔ PASS${reset} $label"- else- rc=$?- echo "${red}${bold}✘ FAIL${reset} $label ${dim}(exit $rc)${reset}"- grep -v $'\xe2\x9c\x93' "$tmp/$label.out" \- | awk -v p="$prefix" '{print p $0}'- exit "$rc"- fi- fi- ) &- pids+=("$!")- }- pids=()- run types $'\033[38;5;75m' bun run typecheck- run lint $'\033[38;5;213m' bunx oxlint --type-aware- run test $'\033[38;5;120m' bun test- fail=0- for pid in "${pids[@]}"; do- wait "$pid" || fail=1- done- exit "$fail"+# Internal release helper+_release bump *ARGS:+ @cargo-release {{bump}} {{ARGS}}++# Release a new patch version+release *ARGS:+ @just _release patch {{ARGS}}diff --git a/bun.lock b/reference/typescript/bun.locksimilarity index 100%rename from bun.lockrename to reference/typescript/bun.lockdiff --git a/package.json b/reference/typescript/package.jsonsimilarity index 100%rename from package.jsonrename to reference/typescript/package.jsondiff --git a/scripts/publish b/reference/typescript/scripts/publishsimilarity index 100%rename from scripts/publishrename to reference/typescript/scripts/publishdiff --git a/src/anthropic/response.test.ts b/reference/typescript/src/anthropic/response.test.tssimilarity index 100%rename from src/anthropic/response.test.tsrename to reference/typescript/src/anthropic/response.test.tsdiff --git a/src/anthropic/response.ts b/reference/typescript/src/anthropic/response.tssimilarity index 100%rename from src/anthropic/response.tsrename to reference/typescript/src/anthropic/response.tsdiff --git a/src/anthropic/schema.ts b/reference/typescript/src/anthropic/schema.tssimilarity index 100%rename from src/anthropic/schema.tsrename to reference/typescript/src/anthropic/schema.tsdiff --git a/src/anthropic/stream.test.ts b/reference/typescript/src/anthropic/stream.test.tssimilarity index 100%rename from src/anthropic/stream.test.tsrename to reference/typescript/src/anthropic/stream.test.tsdiff --git a/src/anthropic/stream.ts b/reference/typescript/src/anthropic/stream.tssimilarity index 100%rename from src/anthropic/stream.tsrename to reference/typescript/src/anthropic/stream.tsdiff --git a/src/cli.ts b/reference/typescript/src/cli.tssimilarity index 100%rename from src/cli.tsrename to reference/typescript/src/cli.tsdiff --git a/src/config.test.ts b/reference/typescript/src/config.test.tssimilarity index 100%rename from src/config.test.tsrename to reference/typescript/src/config.test.tsdiff --git a/src/config.ts b/reference/typescript/src/config.tssimilarity index 100%rename from src/config.tsrename to reference/typescript/src/config.tsdiff --git a/src/keychain.ts b/reference/typescript/src/keychain.tssimilarity index 100%rename from src/keychain.tsrename to reference/typescript/src/keychain.tsdiff --git a/src/log.ts b/reference/typescript/src/log.tssimilarity index 100%rename from src/log.tsrename to reference/typescript/src/log.tsdiff --git a/src/paths.test.ts b/reference/typescript/src/paths.test.tssimilarity index 100%rename from src/paths.test.tsrename to reference/typescript/src/paths.test.tsdiff --git a/src/paths.ts b/reference/typescript/src/paths.tssimilarity index 100%rename from src/paths.tsrename to reference/typescript/src/paths.tsdiff --git a/src/providers/codex/auth/constants.ts b/reference/typescript/src/providers/codex/auth/constants.tssimilarity index 100%rename from src/providers/codex/auth/constants.tsrename to reference/typescript/src/providers/codex/auth/constants.tsdiff --git a/src/providers/codex/auth/device.ts b/reference/typescript/src/providers/codex/auth/device.tssimilarity index 100%rename from src/providers/codex/auth/device.tsrename to reference/typescript/src/providers/codex/auth/device.tsdiff --git a/src/providers/codex/auth/jwt.ts b/reference/typescript/src/providers/codex/auth/jwt.tssimilarity index 100%rename from src/providers/codex/auth/jwt.tsrename to reference/typescript/src/providers/codex/auth/jwt.tsdiff --git a/src/providers/codex/auth/manager.ts b/reference/typescript/src/providers/codex/auth/manager.tssimilarity index 100%rename from src/providers/codex/auth/manager.tsrename to reference/typescript/src/providers/codex/auth/manager.tsdiff --git a/src/providers/codex/auth/pkce.ts b/reference/typescript/src/providers/codex/auth/pkce.tssimilarity index 100%rename from src/providers/codex/auth/pkce.tsrename to reference/typescript/src/providers/codex/auth/pkce.tsdiff --git a/src/providers/codex/auth/token-store.ts b/reference/typescript/src/providers/codex/auth/token-store.tssimilarity index 100%rename from src/providers/codex/auth/token-store.tsrename to reference/typescript/src/providers/codex/auth/token-store.tsdiff --git a/src/providers/codex/cli.ts b/reference/typescript/src/providers/codex/cli.tssimilarity index 100%rename from src/providers/codex/cli.tsrename to reference/typescript/src/providers/codex/cli.tsdiff --git a/src/providers/codex/client.test.ts b/reference/typescript/src/providers/codex/client.test.tssimilarity index 100%rename from src/providers/codex/client.test.tsrename to reference/typescript/src/providers/codex/client.test.tsdiff --git a/src/providers/codex/client.ts b/reference/typescript/src/providers/codex/client.tssimilarity index 100%rename from src/providers/codex/client.tsrename to reference/typescript/src/providers/codex/client.tsdiff --git a/src/providers/codex/continuation.test.ts b/reference/typescript/src/providers/codex/continuation.test.tssimilarity index 100%rename from src/providers/codex/continuation.test.tsrename to reference/typescript/src/providers/codex/continuation.test.tsdiff --git a/src/providers/codex/continuation.ts b/reference/typescript/src/providers/codex/continuation.tssimilarity index 100%rename from src/providers/codex/continuation.tsrename to reference/typescript/src/providers/codex/continuation.tsdiff --git a/src/providers/codex/count-tokens.ts b/reference/typescript/src/providers/codex/count-tokens.tssimilarity index 100%rename from src/providers/codex/count-tokens.tsrename to reference/typescript/src/providers/codex/count-tokens.tsdiff --git a/src/providers/codex/index.test.ts b/reference/typescript/src/providers/codex/index.test.tssimilarity index 100%rename from src/providers/codex/index.test.tsrename to reference/typescript/src/providers/codex/index.test.tsdiff --git a/src/providers/codex/index.ts b/reference/typescript/src/providers/codex/index.tssimilarity index 100%rename from src/providers/codex/index.tsrename to reference/typescript/src/providers/codex/index.tsdiff --git a/src/providers/codex/request-summary.test.ts b/reference/typescript/src/providers/codex/request-summary.test.tssimilarity index 100%rename from src/providers/codex/request-summary.test.tsrename to reference/typescript/src/providers/codex/request-summary.test.tsdiff --git a/src/providers/codex/request-summary.ts b/reference/typescript/src/providers/codex/request-summary.tssimilarity index 100%rename from src/providers/codex/request-summary.tsrename to reference/typescript/src/providers/codex/request-summary.tsdiff --git a/src/providers/codex/translate/accumulate.test.ts b/reference/typescript/src/providers/codex/translate/accumulate.test.tssimilarity index 100%rename from src/providers/codex/translate/accumulate.test.tsrename to reference/typescript/src/providers/codex/translate/accumulate.test.tsdiff --git a/src/providers/codex/translate/accumulate.ts b/reference/typescript/src/providers/codex/translate/accumulate.tssimilarity index 100%rename from src/providers/codex/translate/accumulate.tsrename to reference/typescript/src/providers/codex/translate/accumulate.tsdiff --git a/src/providers/codex/translate/model-allowlist.test.ts b/reference/typescript/src/providers/codex/translate/model-allowlist.test.tssimilarity index 100%rename from src/providers/codex/translate/model-allowlist.test.tsrename to reference/typescript/src/providers/codex/translate/model-allowlist.test.tsdiff --git a/src/providers/codex/translate/model-allowlist.ts b/reference/typescript/src/providers/codex/translate/model-allowlist.tssimilarity index 100%rename from src/providers/codex/translate/model-allowlist.tsrename to reference/typescript/src/providers/codex/translate/model-allowlist.tsdiff --git a/src/providers/codex/translate/reducer.test.ts b/reference/typescript/src/providers/codex/translate/reducer.test.tssimilarity index 100%rename from src/providers/codex/translate/reducer.test.tsrename to reference/typescript/src/providers/codex/translate/reducer.test.tsdiff --git a/src/providers/codex/translate/reducer.ts b/reference/typescript/src/providers/codex/translate/reducer.tssimilarity index 100%rename from src/providers/codex/translate/reducer.tsrename to reference/typescript/src/providers/codex/translate/reducer.tsdiff --git a/src/providers/codex/translate/request.test.ts b/reference/typescript/src/providers/codex/translate/request.test.tssimilarity index 100%rename from src/providers/codex/translate/request.test.tsrename to reference/typescript/src/providers/codex/translate/request.test.tsdiff --git a/src/providers/codex/translate/request.ts b/reference/typescript/src/providers/codex/translate/request.tssimilarity index 100%rename from src/providers/codex/translate/request.tsrename to reference/typescript/src/providers/codex/translate/request.tsdiff --git a/src/providers/codex/translate/stream.test.ts b/reference/typescript/src/providers/codex/translate/stream.test.tssimilarity index 100%rename from src/providers/codex/translate/stream.test.tsrename to reference/typescript/src/providers/codex/translate/stream.test.tsdiff --git a/src/providers/codex/translate/stream.ts b/reference/typescript/src/providers/codex/translate/stream.tssimilarity index 100%rename from src/providers/codex/translate/stream.tsrename to reference/typescript/src/providers/codex/translate/stream.tsdiff --git a/src/providers/codex/translate/test-helpers.ts b/reference/typescript/src/providers/codex/translate/test-helpers.tssimilarity index 100%rename from src/providers/codex/translate/test-helpers.tsrename to reference/typescript/src/providers/codex/translate/test-helpers.tsdiff --git a/src/providers/codex/translate/web-search-compat.ts b/reference/typescript/src/providers/codex/translate/web-search-compat.tssimilarity index 100%rename from src/providers/codex/translate/web-search-compat.tsrename to reference/typescript/src/providers/codex/translate/web-search-compat.tsdiff --git a/src/providers/codex/websocket.test.ts b/reference/typescript/src/providers/codex/websocket.test.tssimilarity index 100%rename from src/providers/codex/websocket.test.tsrename to reference/typescript/src/providers/codex/websocket.test.tsdiff --git a/src/providers/codex/websocket.ts b/reference/typescript/src/providers/codex/websocket.tssimilarity index 100%rename from src/providers/codex/websocket.tsrename to reference/typescript/src/providers/codex/websocket.tsdiff --git a/src/providers/cursor/auth/jwt.ts b/reference/typescript/src/providers/cursor/auth/jwt.tssimilarity index 100%rename from src/providers/cursor/auth/jwt.tsrename to reference/typescript/src/providers/cursor/auth/jwt.tsdiff --git a/src/providers/cursor/auth/login.ts b/reference/typescript/src/providers/cursor/auth/login.tssimilarity index 100%rename from src/providers/cursor/auth/login.tsrename to reference/typescript/src/providers/cursor/auth/login.tsdiff --git a/src/providers/cursor/auth/token-parser.ts b/reference/typescript/src/providers/cursor/auth/token-parser.tssimilarity index 100%rename from src/providers/cursor/auth/token-parser.tsrename to reference/typescript/src/providers/cursor/auth/token-parser.tsdiff --git a/src/providers/cursor/auth/token-store.test.ts b/reference/typescript/src/providers/cursor/auth/token-store.test.tssimilarity index 100%rename from src/providers/cursor/auth/token-store.test.tsrename to reference/typescript/src/providers/cursor/auth/token-store.test.tsdiff --git a/src/providers/cursor/auth/token-store.ts b/reference/typescript/src/providers/cursor/auth/token-store.tssimilarity index 100%rename from src/providers/cursor/auth/token-store.tsrename to reference/typescript/src/providers/cursor/auth/token-store.tsdiff --git a/src/providers/cursor/cli.ts b/reference/typescript/src/providers/cursor/cli.tssimilarity index 100%rename from src/providers/cursor/cli.tsrename to reference/typescript/src/providers/cursor/cli.tsdiff --git a/src/providers/cursor/client.test.ts b/reference/typescript/src/providers/cursor/client.test.tssimilarity index 100%rename from src/providers/cursor/client.test.tsrename to reference/typescript/src/providers/cursor/client.test.tsdiff --git a/src/providers/cursor/client.ts b/reference/typescript/src/providers/cursor/client.tssimilarity index 100%rename from src/providers/cursor/client.tsrename to reference/typescript/src/providers/cursor/client.tsdiff --git a/src/providers/cursor/count-tokens.ts b/reference/typescript/src/providers/cursor/count-tokens.tssimilarity index 100%rename from src/providers/cursor/count-tokens.tsrename to reference/typescript/src/providers/cursor/count-tokens.tsdiff --git a/src/providers/cursor/cursor-test-helpers.ts b/reference/typescript/src/providers/cursor/cursor-test-helpers.tssimilarity index 100%rename from src/providers/cursor/cursor-test-helpers.tsrename to reference/typescript/src/providers/cursor/cursor-test-helpers.tsdiff --git a/src/providers/cursor/index.test.ts b/reference/typescript/src/providers/cursor/index.test.tssimilarity index 100%rename from src/providers/cursor/index.test.tsrename to reference/typescript/src/providers/cursor/index.test.tsdiff --git a/src/providers/cursor/index.ts b/reference/typescript/src/providers/cursor/index.tssimilarity index 100%rename from src/providers/cursor/index.tsrename to reference/typescript/src/providers/cursor/index.tsdiff --git a/src/providers/cursor/proto-loader.ts b/reference/typescript/src/providers/cursor/proto-loader.tssimilarity index 100%rename from src/providers/cursor/proto-loader.tsrename to reference/typescript/src/providers/cursor/proto-loader.tsdiff --git a/src/providers/cursor/session.test.ts b/reference/typescript/src/providers/cursor/session.test.tssimilarity index 100%rename from src/providers/cursor/session.test.tsrename to reference/typescript/src/providers/cursor/session.test.tsdiff --git a/src/providers/cursor/session.ts b/reference/typescript/src/providers/cursor/session.tssimilarity index 100%rename from src/providers/cursor/session.tsrename to reference/typescript/src/providers/cursor/session.tsdiff --git a/src/providers/cursor/sse-framing.ts b/reference/typescript/src/providers/cursor/sse-framing.tssimilarity index 100%rename from src/providers/cursor/sse-framing.tsrename to reference/typescript/src/providers/cursor/sse-framing.tsdiff --git a/src/providers/cursor/tool-bridge.ts b/reference/typescript/src/providers/cursor/tool-bridge.tssimilarity index 100%rename from src/providers/cursor/tool-bridge.tsrename to reference/typescript/src/providers/cursor/tool-bridge.tsdiff --git a/src/providers/cursor/tool-use-xml.ts b/reference/typescript/src/providers/cursor/tool-use-xml.tssimilarity index 100%rename from src/providers/cursor/tool-use-xml.tsrename to reference/typescript/src/providers/cursor/tool-use-xml.tsdiff --git a/src/providers/cursor/translate/catalog.ts b/reference/typescript/src/providers/cursor/translate/catalog.tssimilarity index 100%rename from src/providers/cursor/translate/catalog.tsrename to reference/typescript/src/providers/cursor/translate/catalog.tsdiff --git a/src/providers/cursor/translate/model.test.ts b/reference/typescript/src/providers/cursor/translate/model.test.tssimilarity index 100%rename from src/providers/cursor/translate/model.test.tsrename to reference/typescript/src/providers/cursor/translate/model.test.tsdiff --git a/src/providers/cursor/translate/model.ts b/reference/typescript/src/providers/cursor/translate/model.tssimilarity index 100%rename from src/providers/cursor/translate/model.tsrename to reference/typescript/src/providers/cursor/translate/model.tsdiff --git a/src/providers/cursor/translate/request.test.ts b/reference/typescript/src/providers/cursor/translate/request.test.tssimilarity index 100%rename from src/providers/cursor/translate/request.test.tsrename to reference/typescript/src/providers/cursor/translate/request.test.tsdiff --git a/src/providers/cursor/translate/request.ts b/reference/typescript/src/providers/cursor/translate/request.tssimilarity index 100%rename from src/providers/cursor/translate/request.tsrename to reference/typescript/src/providers/cursor/translate/request.tsdiff --git a/src/providers/cursor/translate/response.test.ts b/reference/typescript/src/providers/cursor/translate/response.test.tssimilarity index 100%rename from src/providers/cursor/translate/response.test.tsrename to reference/typescript/src/providers/cursor/translate/response.test.tsdiff --git a/src/providers/cursor/translate/response.ts b/reference/typescript/src/providers/cursor/translate/response.tssimilarity index 100%rename from src/providers/cursor/translate/response.tsrename to reference/typescript/src/providers/cursor/translate/response.tsdiff --git a/src/providers/kimi/auth/constants.ts b/reference/typescript/src/providers/kimi/auth/constants.tssimilarity index 100%rename from src/providers/kimi/auth/constants.tsrename to reference/typescript/src/providers/kimi/auth/constants.tsdiff --git a/src/providers/kimi/auth/device-id.ts b/reference/typescript/src/providers/kimi/auth/device-id.tssimilarity index 100%rename from src/providers/kimi/auth/device-id.tsrename to reference/typescript/src/providers/kimi/auth/device-id.tsdiff --git a/src/providers/kimi/auth/headers.ts b/reference/typescript/src/providers/kimi/auth/headers.tssimilarity index 100%rename from src/providers/kimi/auth/headers.tsrename to reference/typescript/src/providers/kimi/auth/headers.tsdiff --git a/src/providers/kimi/auth/jwt.ts b/reference/typescript/src/providers/kimi/auth/jwt.tssimilarity index 100%rename from src/providers/kimi/auth/jwt.tsrename to reference/typescript/src/providers/kimi/auth/jwt.tsdiff --git a/src/providers/kimi/auth/login.ts b/reference/typescript/src/providers/kimi/auth/login.tssimilarity index 100%rename from src/providers/kimi/auth/login.tsrename to reference/typescript/src/providers/kimi/auth/login.tsdiff --git a/src/providers/kimi/auth/manager.ts b/reference/typescript/src/providers/kimi/auth/manager.tssimilarity index 100%rename from src/providers/kimi/auth/manager.tsrename to reference/typescript/src/providers/kimi/auth/manager.tsdiff --git a/src/providers/kimi/auth/token-store.ts b/reference/typescript/src/providers/kimi/auth/token-store.tssimilarity index 100%rename from src/providers/kimi/auth/token-store.tsrename to reference/typescript/src/providers/kimi/auth/token-store.tsdiff --git a/src/providers/kimi/cli.ts b/reference/typescript/src/providers/kimi/cli.tssimilarity index 100%rename from src/providers/kimi/cli.tsrename to reference/typescript/src/providers/kimi/cli.tsdiff --git a/src/providers/kimi/client.ts b/reference/typescript/src/providers/kimi/client.tssimilarity index 100%rename from src/providers/kimi/client.tsrename to reference/typescript/src/providers/kimi/client.tsdiff --git a/src/providers/kimi/count-tokens.ts b/reference/typescript/src/providers/kimi/count-tokens.tssimilarity index 100%rename from src/providers/kimi/count-tokens.tsrename to reference/typescript/src/providers/kimi/count-tokens.tsdiff --git a/src/providers/kimi/index.test.ts b/reference/typescript/src/providers/kimi/index.test.tssimilarity index 100%rename from src/providers/kimi/index.test.tsrename to reference/typescript/src/providers/kimi/index.test.tsdiff --git a/src/providers/kimi/index.ts b/reference/typescript/src/providers/kimi/index.tssimilarity index 100%rename from src/providers/kimi/index.tsrename to reference/typescript/src/providers/kimi/index.tsdiff --git a/src/providers/kimi/translate/accumulate.ts b/reference/typescript/src/providers/kimi/translate/accumulate.tssimilarity index 100%rename from src/providers/kimi/translate/accumulate.tsrename to reference/typescript/src/providers/kimi/translate/accumulate.tsdiff --git a/src/providers/kimi/translate/model-allowlist.ts b/reference/typescript/src/providers/kimi/translate/model-allowlist.tssimilarity index 100%rename from src/providers/kimi/translate/model-allowlist.tsrename to reference/typescript/src/providers/kimi/translate/model-allowlist.tsdiff --git a/src/providers/kimi/translate/reducer.ts b/reference/typescript/src/providers/kimi/translate/reducer.tssimilarity index 100%rename from src/providers/kimi/translate/reducer.tsrename to reference/typescript/src/providers/kimi/translate/reducer.tsdiff --git a/src/providers/kimi/translate/request.test.ts b/reference/typescript/src/providers/kimi/translate/request.test.tssimilarity index 100%rename from src/providers/kimi/translate/request.test.tsrename to reference/typescript/src/providers/kimi/translate/request.test.tsdiff --git a/src/providers/kimi/translate/request.ts b/reference/typescript/src/providers/kimi/translate/request.tssimilarity index 100%rename from src/providers/kimi/translate/request.tsrename to reference/typescript/src/providers/kimi/translate/request.tsdiff --git a/src/providers/kimi/translate/signature.ts b/reference/typescript/src/providers/kimi/translate/signature.tssimilarity index 100%rename from src/providers/kimi/translate/signature.tsrename to reference/typescript/src/providers/kimi/translate/signature.tsdiff --git a/src/providers/kimi/translate/stream.ts b/reference/typescript/src/providers/kimi/translate/stream.tssimilarity index 100%rename from src/providers/kimi/translate/stream.tsrename to reference/typescript/src/providers/kimi/translate/stream.tsdiff --git a/src/providers/registry.test.ts b/reference/typescript/src/providers/registry.test.tssimilarity index 100%rename from src/providers/registry.test.tsrename to reference/typescript/src/providers/registry.test.tsdiff --git a/src/providers/registry.ts b/reference/typescript/src/providers/registry.tssimilarity index 100%rename from src/providers/registry.tsrename to reference/typescript/src/providers/registry.tsdiff --git a/src/providers/retry.test.ts b/reference/typescript/src/providers/retry.test.tssimilarity index 100%rename from src/providers/retry.test.tsrename to reference/typescript/src/providers/retry.test.tsdiff --git a/src/providers/retry.ts b/reference/typescript/src/providers/retry.tssimilarity index 100%rename from src/providers/retry.tsrename to reference/typescript/src/providers/retry.tsdiff --git a/src/providers/shared/anthropic-sse.ts b/reference/typescript/src/providers/shared/anthropic-sse.tssimilarity index 100%rename from src/providers/shared/anthropic-sse.tsrename to reference/typescript/src/providers/shared/anthropic-sse.tsdiff --git a/src/providers/shared/auth/atomic-write.ts b/reference/typescript/src/providers/shared/auth/atomic-write.tssimilarity index 100%rename from src/providers/shared/auth/atomic-write.tsrename to reference/typescript/src/providers/shared/auth/atomic-write.tsdiff --git a/src/providers/shared/auth/manager.ts b/reference/typescript/src/providers/shared/auth/manager.tssimilarity index 100%rename from src/providers/shared/auth/manager.tsrename to reference/typescript/src/providers/shared/auth/manager.tsdiff --git a/src/providers/shared/auth/token-store.ts b/reference/typescript/src/providers/shared/auth/token-store.tssimilarity index 100%rename from src/providers/shared/auth/token-store.tsrename to reference/typescript/src/providers/shared/auth/token-store.tsdiff --git a/src/providers/shared/cli-status.ts b/reference/typescript/src/providers/shared/cli-status.tssimilarity index 100%rename from src/providers/shared/cli-status.tsrename to reference/typescript/src/providers/shared/cli-status.tsdiff --git a/src/providers/shared/count-tokens.ts b/reference/typescript/src/providers/shared/count-tokens.tssimilarity index 100%rename from src/providers/shared/count-tokens.tsrename to reference/typescript/src/providers/shared/count-tokens.tsdiff --git a/src/providers/shared/tool-schema.ts b/reference/typescript/src/providers/shared/tool-schema.tssimilarity index 100%rename from src/providers/shared/tool-schema.tsrename to reference/typescript/src/providers/shared/tool-schema.tsdiff --git a/src/providers/shared/upstream-errors.ts b/reference/typescript/src/providers/shared/upstream-errors.tssimilarity index 100%rename from src/providers/shared/upstream-errors.tsrename to reference/typescript/src/providers/shared/upstream-errors.tsdiff --git a/src/providers/translate/accumulate.ts b/reference/typescript/src/providers/translate/accumulate.tssimilarity index 100%rename from src/providers/translate/accumulate.tsrename to reference/typescript/src/providers/translate/accumulate.tsdiff --git a/src/providers/translate/anthropic-content.ts b/reference/typescript/src/providers/translate/anthropic-content.tssimilarity index 100%rename from src/providers/translate/anthropic-content.tsrename to reference/typescript/src/providers/translate/anthropic-content.tsdiff --git a/src/providers/types.ts b/reference/typescript/src/providers/types.tssimilarity index 100%rename from src/providers/types.tsrename to reference/typescript/src/providers/types.tsdiff --git a/src/server.test.ts b/reference/typescript/src/server.test.tssimilarity index 100%rename from src/server.test.tsrename to reference/typescript/src/server.test.tsdiff --git a/src/server.ts b/reference/typescript/src/server.tssimilarity index 100%rename from src/server.tsrename to reference/typescript/src/server.tsdiff --git a/src/server/session-affinity.test.ts b/reference/typescript/src/server/session-affinity.test.tssimilarity index 100%rename from src/server/session-affinity.test.tsrename to reference/typescript/src/server/session-affinity.test.tsdiff --git a/src/server/session-affinity.ts b/reference/typescript/src/server/session-affinity.tssimilarity index 100%rename from src/server/session-affinity.tsrename to reference/typescript/src/server/session-affinity.tsdiff --git a/src/sse.ts b/reference/typescript/src/sse.tssimilarity index 100%rename from src/sse.tsrename to reference/typescript/src/sse.tsdiff --git a/src/test/server.test.ts b/reference/typescript/src/test/server.test.tssimilarity index 100%rename from src/test/server.test.tsrename to reference/typescript/src/test/server.test.tsdiff --git a/src/test/server.ts b/reference/typescript/src/test/server.tssimilarity index 100%rename from src/test/server.tsrename to reference/typescript/src/test/server.tsdiff --git a/src/traffic.ts b/reference/typescript/src/traffic.tssimilarity index 100%rename from src/traffic.tsrename to reference/typescript/src/traffic.tsdiff --git a/tsconfig.json b/reference/typescript/tsconfig.jsonsimilarity index 100%rename from tsconfig.jsonrename to reference/typescript/tsconfig.jsondiff --git a/scripts/install-git-hook-shims b/scripts/install-git-hook-shimsnew file mode 100755index 0000000..3c91cc1--- /dev/null+++ b/scripts/install-git-hook-shims@@ -0,0 +1,38 @@+#!/usr/bin/env bash+set -euo pipefail++repo_root="$(git rev-parse --show-toplevel)"+git_common_dir="$(git rev-parse --git-common-dir)"+hooks_dir="$git_common_dir/hooks"++if (($# == 0)); then+ set -- pre-commit+fi++mkdir -p "$hooks_dir"++for hook_name in "$@"; do+ tracked_hook="$repo_root/hooks/$hook_name"+ hook_path="$hooks_dir/$hook_name"++ if [[ ! -x "$tracked_hook" ]]; then+ echo "error: tracked hook is missing or not executable: $tracked_hook" >&2+ exit 1+ fi++ cat > "$hook_path" <<HOOK+#!/usr/bin/env bash+set -euo pipefail++worktree_root="\$(git rev-parse --show-toplevel)"+tracked_hook="\$worktree_root/hooks/$hook_name"++if [[ ! -x "\$tracked_hook" ]]; then+ echo "error: tracked $hook_name hook is missing or not executable: \$tracked_hook" >&2+ exit 1+fi++exec "\$tracked_hook" "\$@"+HOOK+ chmod +x "$hook_path"+donediff --git a/src/anthropic/error.rs b/src/anthropic/error.rsnew file mode 100644index 0000000..e3cd505--- /dev/null+++ b/src/anthropic/error.rs@@ -0,0 +1,38 @@+use axum::{+ Json,+ http::StatusCode,+ response::{IntoResponse, Response},+};+use serde::Serialize;++#[derive(Debug, Clone, Serialize)]+pub struct ErrorEnvelope {+ #[serde(rename = "type")]+ pub kind: &'static str,+ pub error: ErrorDetail,+}++#[derive(Debug, Clone, Serialize)]+pub struct ErrorDetail {+ #[serde(rename = "type")]+ pub kind: String,+ pub message: String,+}++pub fn json_error(+ status: StatusCode,+ kind: impl Into<String>,+ message: impl Into<String>,+) -> Response {+ (+ status,+ Json(ErrorEnvelope {+ kind: "error",+ error: ErrorDetail {+ kind: kind.into(),+ message: message.into(),+ },+ }),+ )+ .into_response()+}diff --git a/src/anthropic/mod.rs b/src/anthropic/mod.rsnew file mode 100644index 0000000..781d9a8--- /dev/null+++ b/src/anthropic/mod.rs@@ -0,0 +1,9 @@+pub mod error;+pub mod schema;+pub mod sse;++pub use self::error::{ErrorDetail, ErrorEnvelope, json_error};+pub use self::schema::{CountTokensResponse, Message, MessagesRequest};+pub use self::sse::{+ SseEvent, SseParseStats, encode_sse_event, parse_sse_events, parse_sse_events_with_stats,+};diff --git a/src/anthropic/schema.rs b/src/anthropic/schema.rsnew file mode 100644index 0000000..cbd57e5--- /dev/null+++ b/src/anthropic/schema.rs@@ -0,0 +1,25 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MessagesRequest {+ pub model: Option<String>,+ #[serde(default)]+ pub max_tokens: Option<u32>,+ #[serde(default)]+ pub messages: Vec<Message>,+ #[serde(default)]+ pub stream: bool,+ #[serde(flatten)]+ pub extra: serde_json::Map<String, serde_json::Value>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Message {+ pub role: String,+ pub content: serde_json::Value,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CountTokensResponse {+ pub input_tokens: u64,+}diff --git a/src/anthropic/sse.rs b/src/anthropic/sse.rsnew file mode 100644index 0000000..8b9c7d3--- /dev/null+++ b/src/anthropic/sse.rs@@ -0,0 +1,155 @@+use serde::{Deserialize, Serialize};+use serde_json;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct SseEvent {+ pub event: Option<String>,+ pub data: String,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SseParseStats {+ pub bytes_read: usize,+ pub chunk_count: usize,+ pub event_count: usize,+}++pub fn parse_sse_events(input: &[u8]) -> Vec<SseEvent> {+ parse_sse_events_with_stats(input).0+}++pub fn parse_sse_events_with_stats(input: &[u8]) -> (Vec<SseEvent>, SseParseStats) {+ let text = String::from_utf8_lossy(input);+ let normalized = normalize_lines(&text);+ let mut events = Vec::new();+ let mut block = String::new();+ let mut bytes_read = 0usize;+ let mut chunk_count = 0usize;++ for segment in normalized.split('\n') {+ chunk_count += 1;+ bytes_read += segment.len() + 1;+ if segment.is_empty() {+ if let Some(event) = parse_block(&block) {+ events.push(event);+ }+ block.clear();+ continue;+ }+ if !block.is_empty() {+ block.push('\n');+ }+ block.push_str(segment);+ }++ if !block.is_empty()+ && let Some(event) = parse_block(&block)+ {+ events.push(event);+ }++ let event_count = events.len();+ let payload = SseParseStats {+ bytes_read,+ chunk_count,+ event_count,+ };++ (events, payload)+}++pub fn encode_sse_event(event: Option<&str>, data: &str) -> Vec<u8> {+ let mut out = String::new();+ if let Some(event) = event {+ out.push_str("event: ");+ out.push_str(event);+ out.push('\n');+ }+ for line in data.split('\n') {+ out.push_str("data: ");+ let escaped = serde_json::to_string(line)+ .ok()+ .map(|encoded| encoded.trim_matches('"').to_string())+ .unwrap_or_else(|| line.to_string());+ out.push_str(&escaped);+ out.push('\n');+ }+ out.push('\n');+ out.into_bytes()+}++fn normalize_lines(input: &str) -> String {+ let mut normalized = String::new();+ let mut chars = input.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '\r' {+ if chars.peek() == Some(&'\n') {+ chars.next();+ }+ normalized.push('\n');+ continue;+ }+ normalized.push(ch);+ }+ normalized+}++fn parse_block(block: &str) -> Option<SseEvent> {+ let mut event: Option<String> = None;+ let mut data_lines = Vec::new();+ let mut events = Vec::new();+ let mut push_if_relevant = |event: Option<String>, data_lines: &mut Vec<String>| {+ if data_lines.is_empty() {+ return;+ }+ if event.as_deref().is_none_or(|current| current == "final") {+ events.push(SseEvent {+ event,+ data: data_lines.join("\n"),+ });+ }+ data_lines.clear();+ };++ for raw in block.lines() {+ if raw.is_empty() || raw.starts_with(':') {+ continue;+ }++ let mut split = raw.splitn(2, ':');+ let key = split.next().unwrap_or_default();+ let value = split+ .next()+ .unwrap_or_default()+ .trim_start_matches(' ')+ .to_string();++ match key {+ "event" => {+ push_if_relevant(event.take(), &mut data_lines);+ event = Some(value);+ continue;+ }+ "data" => data_lines.push(value),+ _ => {}+ }+ }++ push_if_relevant(event.take(), &mut data_lines);++ if events.is_empty() {+ None+ } else if events.len() == 1 {+ events.pop()+ } else {+ // Keep behavior aligned with the expected upstream parser: when multiple+ // events are present in a block, keep only the last event when it is+ // final and otherwise surface nothing.+ events.into_iter().last().filter(|event| {+ event+ .event+ .as_deref()+ .is_none_or(|current| current == "final")+ })+ }+}diff --git a/src/auth.rs b/src/auth.rsnew file mode 100644index 0000000..4975e54--- /dev/null+++ b/src/auth.rs@@ -0,0 +1,253 @@+use anyhow::Result;+use serde::{Serialize, de::DeserializeOwned};+use serde_json::to_string_pretty;+use std::fs::{self, File};+use std::io::{self, Read, Write};+#[cfg(unix)]+use std::os::unix::fs::PermissionsExt;++pub trait AuthStorage<T>: Send + Sync+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ fn load(&self) -> Result<Option<T>>;+ fn save(&self, value: T) -> Result<()>;+ fn clear(&self) -> Result<()>;+ fn path(&self) -> String;+}++pub trait Keychain: Send + Sync {+ fn read(&self, _service: &str, _account: &str) -> Option<String>;+ fn write(&self, _service: &str, _account: &str, _value: &str) -> bool;+ fn delete(&self, _service: &str, _account: &str) -> bool;+}++#[derive(Default)]+pub struct StubKeychain;++impl Keychain for StubKeychain {+ fn read(&self, _service: &str, _account: &str) -> Option<String> {+ None+ }++ fn write(&self, _service: &str, _account: &str, _value: &str) -> bool {+ true+ }++ fn delete(&self, _service: &str, _account: &str) -> bool {+ true+ }+}++pub struct FileAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ file: String,+ legacy_file: String,+ _marker: std::marker::PhantomData<T>,+}++impl<T> FileAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ pub fn new(file: String, legacy_file: String) -> Self {+ Self {+ file,+ legacy_file,+ _marker: Default::default(),+ }+ }+}++impl<T> AuthStorage<T> for FileAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ fn load(&self) -> Result<Option<T>> {+ let parsed = load_auth_file::<T>(&self.file);+ if parsed.is_some() {+ return Ok(parsed);+ }+ if self.file == self.legacy_file {+ return Ok(None);+ }+ Ok(load_auth_file::<T>(&self.legacy_file))+ }++ fn save(&self, value: T) -> Result<()> {+ let path = std::path::Path::new(&self.file);+ if let Some(dir) = path.parent() {+ fs::create_dir_all(dir)?;+ set_mode(dir, 0o700);+ }+ write_atomically(&self.file, &value)+ }++ fn clear(&self) -> Result<()> {+ for path in [&self.file, &self.legacy_file] {+ if let Err(err) = fs::remove_file(path)+ && err.kind() != io::ErrorKind::NotFound+ {+ return Err(anyhow::Error::from(err));+ }+ }+ Ok(())+ }++ fn path(&self) -> String {+ self.file.clone()+ }+}++pub fn load_auth_file<T: DeserializeOwned>(path: &str) -> Option<T> {+ let mut file = File::open(path).ok()?;+ let mut raw = String::new();+ file.read_to_string(&mut raw).ok()?;+ serde_json::from_str::<T>(&raw).ok()+}++pub fn load_auth_file_value(path: &std::path::Path) -> Option<serde_json::Value> {+ let mut file = File::open(path).ok()?;+ let mut raw = String::new();+ file.read_to_string(&mut raw).ok()?;+ serde_json::from_str::<serde_json::Value>(&raw).ok()+}++pub fn load_auth_file_with_legacy<T: DeserializeOwned>(+ primary: &std::path::Path,+ legacy: &std::path::Path,+) -> Option<T> {+ if let Some(value) = load_auth_file_value(primary) {+ return serde_json::from_value(value).ok();+ }+ if primary == legacy {+ None+ } else {+ load_auth_file_value(legacy).and_then(|value| serde_json::from_value(value).ok())+ }+}++pub fn delete_auth_file(primary: &std::path::Path, legacy: &std::path::Path) -> io::Result<()> {+ if let Err(err) = fs::remove_file(primary)+ && err.kind() != io::ErrorKind::NotFound+ {+ return Err(err);+ }+ if primary != legacy+ && let Err(err) = fs::remove_file(legacy)+ && err.kind() != io::ErrorKind::NotFound+ {+ return Err(err);+ }+ Ok(())+}++pub fn write_atomically<T: Serialize>(path: &str, value: &T) -> Result<()> {+ let dir = std::path::Path::new(path)+ .parent()+ .ok_or_else(|| anyhow::anyhow!("invalid auth path"))?;+ fs::create_dir_all(dir)?;+ set_mode(dir, 0o700);++ let tmp = format!("{path}.tmp-{}", std::process::id());+ let mut out = File::create(&tmp)?;+ out.write_all(to_string_pretty(value)?.as_bytes())?;+ out.sync_all()?;+ fs::rename(&tmp, path)?;+ set_mode(std::path::Path::new(path), 0o600);+ Ok(())+}++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);+ }+ }+}++pub struct InMemoryAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ inner: std::sync::Arc<std::sync::Mutex<Option<T>>>,+}++impl<T> Default for InMemoryAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ fn default() -> Self {+ Self::new()+ }+}++impl<T> InMemoryAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ pub fn new() -> Self {+ Self {+ inner: std::sync::Arc::new(std::sync::Mutex::new(None)),+ }+ }+}++impl<T> Clone for InMemoryAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ fn clone(&self) -> Self {+ Self {+ inner: self.inner.clone(),+ }+ }+}++impl<T> AuthStorage<T> for InMemoryAuthStore<T>+where+ T: Serialize + DeserializeOwned + Send + Sync + Clone,+{+ fn load(&self) -> Result<Option<T>> {+ let inner = self+ .inner+ .lock()+ .map_err(|err| anyhow::anyhow!(err.to_string()))?;+ Ok(inner.clone())+ }++ fn save(&self, value: T) -> Result<()> {+ let mut inner = self+ .inner+ .lock()+ .map_err(|err| anyhow::anyhow!(err.to_string()))?;+ *inner = Some(value);+ Ok(())+ }++ fn clear(&self) -> Result<()> {+ let mut inner = self+ .inner+ .lock()+ .map_err(|err| anyhow::anyhow!(err.to_string()))?;+ *inner = None;+ Ok(())+ }++ fn path(&self) -> String {+ "memory".to_string()+ }+}++#[cfg(test)]+pub fn fixture_store<T>() -> InMemoryAuthStore<T>+where+ T: Serialize + serde::de::DeserializeOwned + Send + Sync + Clone,+{+ InMemoryAuthStore::new()+}diff --git a/src/config.rs b/src/config.rsnew file mode 100644index 0000000..4e7ee65--- /dev/null+++ b/src/config.rs@@ -0,0 +1,183 @@+use serde::Deserialize;+use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};++use crate::paths;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AliasProvider {+ Codex,+ Kimi,+}++impl AliasProvider {+ pub fn as_str(&self) -> &str {+ match self {+ AliasProvider::Codex => "codex",+ AliasProvider::Kimi => "kimi",+ }+ }+}++#[derive(Debug, Clone)]+pub struct LoadedConfig {+ pub port: u16,+ pub alias_provider: AliasProvider,+ pub log_verbose: bool,+ pub log_stderr: bool,+ pub config_dir: PathBuf,+}++#[derive(Deserialize)]+struct FileConfig {+ pub port: Option<u16>,+ #[serde(rename = "aliasProvider")]+ pub alias_provider: Option<String>,+ pub log: Option<FileLog>,+}++#[derive(Deserialize)]+struct FileLog {+ pub verbose: Option<bool>,+ pub stderr: Option<bool>,+}++fn parse_alias(raw: &str) -> Option<AliasProvider> {+ match raw {+ "codex" => Some(AliasProvider::Codex),+ "kimi" => Some(AliasProvider::Kimi),+ _ => None,+ }+}++fn parse_bool_raw(raw: &str) -> Option<bool> {+ match raw.to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" => Some(true),+ "0" | "false" | "no" => Some(false),+ _ => None,+ }+}++fn read_file_config(config_dir: &Path) -> Option<FileConfig> {+ let path = config_dir.join("config.json");+ let raw = fs::read_to_string(path).ok()?;+ serde_json::from_str(&raw).ok()+}++pub fn load_config() -> LoadedConfig {+ let config_dir = paths::config_dir();+ let file = read_file_config(&config_dir);+ let env: HashMap<_, _> = std::env::vars().collect();++ let mut out = LoadedConfig {+ port: 18765,+ alias_provider: AliasProvider::Codex,+ log_verbose: false,+ log_stderr: false,+ config_dir: config_dir.clone(),+ };++ if let Some(raw) = env.get("CCP_ALIAS_PROVIDER") {+ if let Some(alias) = parse_alias(raw) {+ out.alias_provider = alias;+ }+ } else if let Some(alias_provider) = file+ .as_ref()+ .and_then(|f| f.alias_provider.as_deref())+ .and_then(parse_alias)+ {+ out.alias_provider = alias_provider;+ }++ if let Some(raw) = env.get("PORT") {+ if let Ok(port) = raw.parse::<u16>() {+ out.port = port;+ }+ } else if let Some(port) = file.as_ref().and_then(|f| f.port) {+ out.port = port;+ }++ if let Some(raw) = env.get("CCP_LOG_VERBOSE") {+ if let Some(value) = parse_bool_raw(raw) {+ out.log_verbose = value;+ }+ } else if let Some(value) = file+ .as_ref()+ .and_then(|f| f.log.as_ref().and_then(|v| v.verbose))+ {+ out.log_verbose = value;+ }++ if let Some(raw) = env.get("CCP_LOG_STDERR") {+ if let Some(value) = parse_bool_raw(raw) {+ out.log_stderr = value;+ }+ } else if let Some(value) = file+ .as_ref()+ .and_then(|f| f.log.as_ref().and_then(|v| v.stderr))+ {+ out.log_stderr = value;+ }++ out+}++pub fn config_path() -> PathBuf {+ paths::config_dir().join("config.json")+}++pub fn port() -> u16 {+ load_config().port+}++pub fn alias_provider() -> AliasProvider {+ load_config().alias_provider+}++pub fn log_verbose() -> bool {+ load_config().log_verbose+}++pub fn log_stderr() -> bool {+ load_config().log_stderr+}++pub fn config_override_summary_lines(cfg: &LoadedConfig) -> Vec<String> {+ let file = read_file_config(&cfg.config_dir);+ let env: HashMap<_, _> = std::env::vars().collect();+ let mut out = Vec::new();+ if env.contains_key("PORT") {+ out.push("port (env)".to_string());+ }+ if env.contains_key("CCP_ALIAS_PROVIDER") {+ out.push("aliasProvider (env)".to_string());+ }+ if env.contains_key("CCP_LOG_VERBOSE") {+ out.push("log.verbose (env)".to_string());+ }+ if env.contains_key("CCP_LOG_STDERR") {+ out.push("log.stderr (env)".to_string());+ }+ if let Some(file_cfg) = file {+ if let Some(p) = file_cfg.port {+ out.push(format!("port: {p}"));+ }+ if let Some(alias) = file_cfg.alias_provider {+ out.push(format!("aliasProvider: {alias}"));+ }+ if let Some(log) = file_cfg.log {+ if let Some(v) = log.verbose {+ out.push(format!("log.verbose: {v}"));+ }+ if let Some(v) = log.stderr {+ out.push(format!("log.stderr: {v}"));+ }+ }+ }+ out+}++pub fn is_verbose() -> bool {+ log_verbose()+}diff --git a/src/lib.rs b/src/lib.rsnew file mode 100644index 0000000..12ce863--- /dev/null+++ b/src/lib.rs@@ -0,0 +1,16 @@+pub mod anthropic;+pub mod auth;+pub mod config;+pub mod logging;+pub mod paths;+pub mod provider;+pub mod registry;+pub mod retry;+pub mod server;+pub mod session;+pub mod traffic;++pub use crate::anthropic::error::{ErrorDetail, ErrorEnvelope, json_error};+pub use crate::anthropic::schema::MessagesRequest;+pub use crate::provider::{AuthCommand, CliHandlers, Provider, RequestContext};+pub use crate::registry::Registry;diff --git a/src/logging.rs b/src/logging.rsnew file mode 100644index 0000000..fa69891--- /dev/null+++ b/src/logging.rs@@ -0,0 +1,201 @@+use crate::{config, paths};+use serde_json::Value;+use std::collections::HashSet;+use std::fs::{self, OpenOptions};+use std::io::{self, Write};+use std::path::Path;+use std::time::{SystemTime, UNIX_EPOCH};++pub const MAX_LOG_BYTES: u64 = 20 * 1024 * 1024;++pub const REDACT_KEYS: [&str; 14] = [+ "authorization",+ "access",+ "access_token",+ "refresh",+ "refresh_token",+ "id_token",+ "code",+ "code_verifier",+ "chatgpt-account-id",+ "cookie",+ "set-cookie",+ "x-api-key",+ "apikey",+ "api_key",+];++pub fn log_file() -> std::path::PathBuf {+ paths::log_file()+}++#[derive(Clone)]+pub struct Logger {+ service: String,+ base: serde_json::Map<String, Value>,+}++impl Logger {+ pub fn child(&self, bindings: serde_json::Map<String, Value>) -> Logger {+ let mut merged = self.base.clone();+ merged.extend(bindings);+ Logger {+ service: self.service.clone(),+ base: merged,+ }+ }++ pub fn debug(&self, msg: &str, fields: Option<serde_json::Map<String, Value>>) {+ self.emit("debug", msg, fields)+ }++ pub fn info(&self, msg: &str, fields: Option<serde_json::Map<String, Value>>) {+ self.emit("info", msg, fields)+ }++ pub fn warn(&self, msg: &str, fields: Option<serde_json::Map<String, Value>>) {+ self.emit("warn", msg, fields)+ }++ pub fn error(&self, msg: &str, fields: Option<serde_json::Map<String, Value>>) {+ self.emit("error", msg, fields)+ }++ fn emit(&self, level: &str, msg: &str, fields: Option<serde_json::Map<String, Value>>) {+ let mut body = serde_json::Map::new();+ body.insert("t".into(), Value::String(now_iso8601()));+ body.insert("level".into(), Value::String(level.to_string()));+ body.insert("service".into(), Value::String(self.service.clone()));+ body.insert("msg".into(), Value::String(msg.to_string()));++ let mut merged = self.base.clone();+ if let Some(fields) = fields {+ merged.extend(fields);+ }+ if !merged.is_empty() {+ body.insert("fields".into(), redact_value(Value::Object(merged)));+ }++ let line = Value::Object(body).to_string();++ let mirror_to_stderr = matches!(level, "warn" | "error") || config::log_stderr();+ if mirror_to_stderr {+ let _ = writeln!(io::stderr(), "{line}");+ }++ if write_log_line(&line).is_err() && mirror_to_stderr {+ // swallow logging errors intentionally+ }+ }+}++pub fn create_logger(service: &str) -> Logger {+ Logger {+ service: service.to_string(),+ base: serde_json::Map::new(),+ }+}++fn write_log_line(line: &str) -> io::Result<()> {+ let file = log_file();+ if let Some(dir) = file.parent() {+ create_dir(dir, 0o700)?;+ }++ if fs::metadata(&file).is_ok_and(|meta| meta.len() > MAX_LOG_BYTES) {+ rotate_file(&file)?;+ }++ let mut out = OpenOptions::new().create(true).append(true).open(&file)?;+ out.write_all(line.as_bytes())?;+ out.write_all(b"\n")?;+ Ok(())+}++fn rotate_file(path: &Path) -> io::Result<()> {+ let ts = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis();+ let rotated = path.with_extension(format!("{ts}"));+ fs::rename(path, rotated)?;+ Ok(())+}++fn create_dir(path: &Path, mode: u32) -> io::Result<()> {+ fs::create_dir_all(path)?;+ set_mode(path, mode);+ Ok(())+}++fn set_mode(path: &Path, mode: u32) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(meta) = fs::metadata(path) {+ let mut perm = meta.permissions();+ perm.set_mode(mode);+ let _ = fs::set_permissions(path, perm);+ }+ }+}++fn now_iso8601() -> String {+ let now = time::OffsetDateTime::now_utc();+ let format = time::format_description::parse_borrowed::<3>(+ "[year]-[month]-[day]T[hour]:[minute]:[second]Z",+ )+ .unwrap();+ now.format(&format).unwrap_or_else(|_| String::new())+}++pub fn redact_value(value: Value) -> Value {+ redact_with_depth(value, 0)+}++fn redact_with_depth(value: Value, depth: u8) -> Value {+ if depth > 6 {+ return Value::String("[depth-limit]".into());+ }++ match value {+ Value::String(s) => {+ if config::log_verbose() {+ Value::String(s)+ } else if s.len() > 1000 {+ Value::String(format!("{}…[{} more]", &s[..1000], s.len() - 1000))+ } else {+ Value::String(s)+ }+ }+ Value::Array(values) => Value::Array(+ values+ .into_iter()+ .map(|v| redact_with_depth(v, depth + 1))+ .collect(),+ ),+ Value::Object(fields) => {+ let mut out = serde_json::Map::new();+ for (key, value) in fields {+ if REDACT_KEYS.contains(&key.to_lowercase().as_str()) {+ out.insert(key, redact_key_redaction(value));+ } else {+ out.insert(key, redact_with_depth(value, depth + 1));+ }+ }+ Value::Object(out)+ }+ value => value,+ }+}++fn redact_key_redaction(value: Value) -> Value {+ match value {+ Value::String(s) => Value::String(format!("[redacted len={}]", s.len())),+ _ => Value::String("[redacted]".to_string()),+ }+}++pub fn redacted_keys() -> HashSet<&'static str> {+ REDACT_KEYS.iter().copied().collect()+}diff --git a/src/main.rs b/src/main.rsnew file mode 100644index 0000000..ad7a51c--- /dev/null+++ b/src/main.rs@@ -0,0 +1,193 @@+use anyhow::Result;+use clap::{ArgAction, Parser, Subcommand};+use claude_code_proxy::{+ config, paths,+ registry::{ANTHROPIC_STYLE_ALIASES, Registry},+ server::{self, ServerConfig},+};++const VERSION: &str = env!("CARGO_PKG_VERSION");++#[derive(Debug, Parser)]+#[command(+ name = "claude-code-proxy",+ version = VERSION,+ about = "Anthropic-compatible proxy for Claude Code provider backends",+ disable_version_flag = true+)]+struct Cli {+ #[arg(long = "version", short = 'v', action = ArgAction::SetTrue)]+ version_flag: bool,++ #[command(subcommand)]+ command: Option<Commands>,+}++#[derive(Debug, Subcommand)]+enum Commands {+ Version,+ Serve {+ #[arg(long)]+ port: Option<u16>,+ },+ Models {+ #[arg(long)]+ full: bool,+ },+ Codex {+ #[command(subcommand)]+ command: ProviderGroup,+ },+ Kimi {+ #[command(subcommand)]+ command: ProviderGroup,+ },+ Cursor {+ #[command(subcommand)]+ command: ProviderGroup,+ },+}++#[derive(Debug, Subcommand)]+enum ProviderGroup {+ Auth {+ #[command(subcommand)]+ command: claude_code_proxy::provider::AuthCommand,+ },+}++fn main() -> Result<()> {+ let cli = Cli::parse();++ if cli.version_flag {+ println!("claude-code-proxy {}", VERSION);+ return Ok(());+ }++ let commands = cli.command.unwrap_or(Commands::Serve { port: None });++ match commands {+ Commands::Version => {+ println!("claude-code-proxy {}", VERSION);+ return Ok(());+ }+ Commands::Serve { port } => {+ let effective_port = port.unwrap_or_else(config::port);+ let registry = Registry::with_default_alias();+ print_server_banner(effective_port, ®istry);+ tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .build()?+ .block_on(server::serve(ServerConfig {+ port: effective_port,+ }))+ .map_err(|err| anyhow::anyhow!(err))+ }+ Commands::Models { full } => {+ print_models(&Registry::with_default_alias(), full);+ Ok(())+ }+ Commands::Codex { command } => run_provider_cli("codex", command),+ Commands::Kimi { command } => run_provider_cli("kimi", command),+ Commands::Cursor { command } => run_provider_cli("cursor", command),+ }+}++fn run_provider_cli(name: &str, command: ProviderGroup) -> Result<()> {+ let registry = Registry::with_default_alias();+ let provider = registry+ .provider(name)+ .ok_or_else(|| anyhow::anyhow!("unknown provider: {name}"))?;+ let handlers = provider.cli();+ match command {+ ProviderGroup::Auth { command } => match command {+ claude_code_proxy::provider::AuthCommand::Login => {+ if let Err(err) = handlers.login() {+ eprintln!("{err}");+ std::process::exit(2);+ }+ Ok(())+ }+ claude_code_proxy::provider::AuthCommand::Device => {+ if let Err(err) = handlers.device() {+ eprintln!("{err}");+ std::process::exit(2);+ }+ Ok(())+ }+ claude_code_proxy::provider::AuthCommand::Status => {+ if let Err(err) = handlers.status() {+ println!("{err}");+ if err.to_string() == "Not authenticated" {+ std::process::exit(1);+ }+ std::process::exit(2);+ }+ Ok(())+ }+ claude_code_proxy::provider::AuthCommand::Logout => {+ handlers.logout()?;+ Ok(())+ }+ },+ }+}++fn print_models(registry: &Registry, full: bool) {+ let grouped = registry.grouped_models();+ for provider in ["codex", "kimi", "cursor"] {+ let Some(models) = grouped.get(provider) else {+ continue;+ };+ if full || provider != "cursor" {+ println!("{provider}: {}", models.join(", "));+ } else {+ println!("{provider}: {}", compact_cursor_list(models));+ }+ }+}++fn compact_cursor_list(models: &[String]) -> String {+ let mut legacy = Vec::new();+ let mut dynamic = Vec::new();+ for model in models {+ if !model.contains(':') {+ legacy.push(model.clone());+ } else {+ dynamic.push(model.clone());+ }+ }+ let mut out = String::new();+ if !legacy.is_empty() {+ out.push_str(&legacy.join(", "));+ out.push_str("; ");+ }+ out.push_str(&format!("{} cursor model aliases", dynamic.len()));+ if !dynamic.is_empty() {+ out.push_str(", example: cursor:gpt-5.5");+ }+ out.push_str(" run `claude-code-proxy models --full` for all aliases");+ out+}++fn print_server_banner(port: u16, registry: &Registry) {+ println!("Proxy listening on http://127.0.0.1:{port}");+ println!("Logs: {}", paths::log_file().display());+ let cfg = paths::config_dir();+ if cfg.exists() {+ println!("Config: {}", cfg.display());+ }+ print_models(registry, false);+ println!();+ println!("Configure Claude Code (pick a model from above):");+ println!(" export ANTHROPIC_BASE_URL=\"http://localhost:{port}\"");+ println!(" export ANTHROPIC_AUTH_TOKEN=\"anything\"");+ println!(" export ANTHROPIC_MODEL=\"gpt-5.5\"");+ println!(" export ANTHROPIC_SMALL_FAST_MODEL=\"gpt-5.4-mini\"");+ println!(" export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1");+}++#[allow(dead_code)]+fn alias_names() -> usize {+ ANTHROPIC_STYLE_ALIASES.len()+}diff --git a/src/paths.rs b/src/paths.rsnew file mode 100644index 0000000..ed0219b--- /dev/null+++ b/src/paths.rs@@ -0,0 +1,143 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};++#[derive(Debug, Clone)]+pub struct DirResolverEnv {+ pub platform: String,+ pub env: HashMap<String, String>,+ pub home: String,+}++impl Default for DirResolverEnv {+ fn default() -> Self {+ Self {+ platform: std::env::consts::OS.into(),+ env: std::env::vars().collect(),+ home: std::env::var("HOME")+ .or_else(|_| std::env::var("USERPROFILE"))+ .unwrap_or_else(|_| "/".to_string()),+ }+ }+}++pub fn resolve_config_dir(deps: &DirResolverEnv) -> PathBuf {+ if let Some(override_dir) = deps.env.get("CCP_CONFIG_DIR") {+ return Path::new(override_dir).to_path_buf();+ }++ if deps.platform == "win32" {+ let appdata = deps+ .env+ .get("APPDATA")+ .cloned()+ .unwrap_or_else(|| format!("{}\\AppData\\Roaming", deps.home));+ return join_with_sep(&appdata, &["claude-code-proxy"], true);+ }++ if deps.platform == "darwin" {+ return join_with_sep(&deps.home, &[".config", "claude-code-proxy"], false);+ }++ let base = deps.env.get("XDG_CONFIG_HOME").cloned().unwrap_or_else(|| {+ join_with_sep(&deps.home, &[".config"], false)+ .to_string_lossy()+ .into_owned()+ });+ join_with_sep(&base, &["claude-code-proxy"], false)+}++pub fn resolve_state_dir(deps: &DirResolverEnv) -> PathBuf {+ if deps.platform == "win32" {+ let local = deps+ .env+ .get("LOCALAPPDATA")+ .cloned()+ .unwrap_or_else(|| format!("{}\\AppData\\Local", deps.home));+ return join_with_sep(&local, &["claude-code-proxy"], true);+ }++ let base = deps.env.get("XDG_STATE_HOME").cloned().unwrap_or_else(|| {+ join_with_sep(&deps.home, &[".local", "state"], false)+ .to_string_lossy()+ .into_owned()+ });+ join_with_sep(&base, &["claude-code-proxy"], false)+}++pub fn legacy_config_dir(deps: &DirResolverEnv) -> PathBuf {+ join_with_sep(&deps.home, &[".config", "claude-code-proxy"], false)+}++pub fn config_dir() -> PathBuf {+ resolve_config_dir(&DirResolverEnv::default())+}++pub fn state_dir() -> PathBuf {+ resolve_state_dir(&DirResolverEnv::default())+}++pub fn codex_auth_file(deps: &DirResolverEnv) -> PathBuf {+ resolve_config_dir(deps).join("codex").join("auth.json")+}++pub fn kimi_auth_file(deps: &DirResolverEnv) -> PathBuf {+ resolve_config_dir(deps).join("kimi").join("auth.json")+}++pub fn cursor_auth_file(deps: &DirResolverEnv) -> PathBuf {+ resolve_config_dir(deps).join("cursor").join("auth.json")+}++pub fn kimi_device_id_file(deps: &DirResolverEnv) -> PathBuf {+ resolve_config_dir(deps).join("kimi").join("device_id")+}++pub fn log_file() -> PathBuf {+ resolve_state_dir(&DirResolverEnv::default()).join("proxy.log")+}++pub fn provider_auth_file(provider: &str) -> PathBuf {+ let deps = DirResolverEnv::default();+ resolve_config_dir(&deps).join(provider).join("auth.json")+}++pub fn provider_legacy_auth_file(provider: &str) -> PathBuf {+ let deps = DirResolverEnv::default();+ legacy_config_dir(&deps).join(provider).join("auth.json")+}++fn join_with_sep(base: &str, parts: &[&str], win32: bool) -> PathBuf {+ let sep = if win32 { '/' } else { '/' };+ let mut out = String::new();+ for part in std::iter::once(base).chain(parts.iter().copied()) {+ if !out.is_empty() && !out.ends_with(sep) {+ out.push(sep);+ }+ out.push_str(part);+ }+ Path::new(&out).to_path_buf()+}++pub fn resolve_config_dir_for_env(+ platform: &str,+ home: &str,+ env: &HashMap<String, String>,+) -> PathBuf {+ resolve_config_dir(&DirResolverEnv {+ platform: platform.to_string(),+ env: env.clone(),+ home: home.to_string(),+ })+}++pub fn resolve_state_dir_for_env(+ platform: &str,+ home: &str,+ env: &HashMap<String, String>,+) -> PathBuf {+ resolve_state_dir(&DirResolverEnv {+ platform: platform.to_string(),+ env: env.clone(),+ home: home.to_string(),+ })+}diff --git a/src/provider.rs b/src/provider.rsnew file mode 100644index 0000000..3a92882--- /dev/null+++ b/src/provider.rs@@ -0,0 +1,37 @@+use crate::anthropic::schema::MessagesRequest;+use anyhow::Result;+use async_trait::async_trait;+use axum::response::Response;+use clap::Subcommand;++#[derive(Debug, Clone, Subcommand)]+pub enum AuthCommand {+ Login,+ Device,+ Status,+ Logout,+}++#[async_trait]+pub trait Provider: Send + Sync {+ fn name(&self) -> &'static str;+ fn supported_models(&self) -> Vec<String>;+ fn cli(&self) -> &'static dyn CliHandlers;+ async fn handle_messages(&self, body: MessagesRequest, ctx: RequestContext) -> Response;+ async fn handle_count_tokens(&self, body: MessagesRequest, ctx: RequestContext) -> Response;+}++pub trait CliHandlers: Send + Sync {+ fn login(&self) -> Result<()>;+ fn device(&self) -> Result<()>;+ fn status(&self) -> Result<()>;+ fn logout(&self) -> Result<()>;+}++#[derive(Debug, Clone)]+pub struct RequestContext {+ pub req_id: String,+ pub session_id: Option<String>,+ pub session_seq: Option<u64>,+ pub provider: String,+}diff --git a/src/registry.rs b/src/registry.rsnew file mode 100644index 0000000..449e221--- /dev/null+++ b/src/registry.rs@@ -0,0 +1,337 @@+use crate::{+ anthropic::{json_error, schema::MessagesRequest},+ config::AliasProvider,+ provider::{CliHandlers, Provider, RequestContext},+};+use anyhow::{Result, anyhow};+use async_trait::async_trait;+use axum::{http::StatusCode, response::Response};+use std::collections::{BTreeMap, HashSet};+use std::sync::Arc;++pub const ANTHROPIC_STYLE_ALIASES: &[&str] = &[+ "haiku",+ "claude-haiku-4-5",+ "claude-haiku-4-5-20251001",+ "sonnet",+ "claude-sonnet-4-6",+ "opus",+ "claude-opus-4-7",+];++pub const CURSOR_PREFIXES: &[&str] = &["cursor:", "cursor-plan:", "cursor-ask:"];++const CURSOR_LEGACY_MODELS: &[&str] = &[+ "cursor",+ "cursor-agent",+ "cursor-composer",+ "cursor-composer-fast",+ "cursor-plan",+ "cursor-ask",+ "composer-2.5",+ "composer-2.5-fast",+];++const CODEX_MODELS: &[&str] = &[+ "gpt-5.2",+ "gpt-5.3-codex",+ "gpt-5.3-codex-spark",+ "gpt-5.4",+ "gpt-5.4-mini",+ "gpt-5.5",+];++const KIMI_MODELS: &[&str] = &["kimi-for-coding", "kimi-k2.6", "k2.6"];++pub struct Registry {+ alias_provider: AliasProvider,+ models: BTreeMap<String, Vec<String>>,+ handlers: BTreeMap<String, Arc<dyn Provider>>,+}++impl Registry {+ pub fn new(alias_provider: AliasProvider) -> Self {+ let mut models: BTreeMap<String, Vec<String>> = BTreeMap::new();+ models.insert("codex".into(), expand_codex_models());+ models.insert(+ "kimi".into(),+ KIMI_MODELS.iter().map(|m| (*m).to_string()).collect(),+ );+ models.insert("cursor".into(), build_cursor_models());++ 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>,+ );+ }++ Self {+ alias_provider,+ models,+ handlers,+ }+ }++ pub fn with_default_alias() -> Self {+ Self::new(crate::config::alias_provider())+ }++ pub fn list_provider_names(&self) -> Vec<String> {+ let mut names: Vec<String> = self.handlers.keys().cloned().collect();+ names.sort_unstable();+ names+ }++ pub fn provider(&self, name: &str) -> Option<Arc<dyn Provider>> {+ self.handlers.get(name).cloned()+ }++ pub fn supported_models_for(&self, provider: &str) -> Vec<String> {+ let mut models = self.models.get(provider).cloned().unwrap_or_default();+ if provider == self.alias_provider.as_str() {+ for alias in ANTHROPIC_STYLE_ALIASES {+ if !models.iter().any(|value| value == alias) {+ models.push((*alias).to_string());+ }+ }+ }+ models.sort_unstable();+ models+ }++ pub fn all_supported_models(&self) -> Vec<(String, String)> {+ let mut out = Vec::new();+ for provider in self.handlers.keys() {+ for model in self.supported_models_for(provider) {+ out.push((model, provider.clone()));+ }+ }+ out+ }++ pub fn grouped_models(&self) -> BTreeMap<String, Vec<String>> {+ let mut out = BTreeMap::new();+ for provider in self.handlers.keys() {+ out.insert(provider.clone(), self.supported_models_for(provider));+ }+ out+ }++ pub fn provider_for_model(+ &self,+ raw_model: &str,+ session_affinity: Option<&AliasProvider>,+ ) -> Option<Arc<dyn Provider>> {+ let normalized = normalize_incoming_model(raw_model);+ if is_anthropic_alias(&normalized) {+ let target = session_affinity.unwrap_or(&self.alias_provider);+ return self.handlers.get(target.as_str()).cloned();+ }+ if is_cursor_model(&normalized) {+ return self.handlers.get("cursor").cloned();+ }++ for (name, models) in &self.models {+ if models.iter().any(|candidate| candidate == &normalized) {+ return self.handlers.get(name).cloned();+ }+ }++ None+ }++ pub fn unknown_model_message(&self) -> String {+ let mut parts = Vec::new();+ for (provider, models) in self.grouped_models() {+ let mut models = models;+ models.sort_unstable();+ parts.push(format!("{}: {}", provider, models.join(", ")));+ }+ format!("Supported: {}.", parts.join("; "))+ }+}++pub fn normalize_incoming_model(model: &str) -> String {+ let suffix = "[1m]";+ if model.len() >= suffix.len() && model.to_ascii_lowercase().ends_with(suffix) {+ return model[..model.len() - suffix.len()].to_string();+ }+ model.to_string()+}++pub fn is_anthropic_alias(model: &str) -> bool {+ ANTHROPIC_STYLE_ALIASES.contains(&model)+}++pub fn is_cursor_model(model: &str) -> bool {+ if CURSOR_LEGACY_MODELS.contains(&model) {+ return true;+ }++ CURSOR_PREFIXES+ .iter()+ .any(|prefix| model.starts_with(prefix))+}++struct PlaceholderProvider {+ name: &'static str,+ models: Vec<String>,+}++impl PlaceholderProvider {+ fn new(name: &str, models: Vec<String>) -> Self {+ let name = match name {+ "codex" => "codex",+ "kimi" => "kimi",+ "cursor" => "cursor",+ _ => "codex",+ };+ Self { name, models }+ }+}++#[async_trait]+impl Provider for PlaceholderProvider {+ fn name(&self) -> &'static str {+ self.name+ }++ fn supported_models(&self) -> Vec<String> {+ self.models.clone()+ }++ fn cli(&self) -> &'static dyn CliHandlers {+ match self.name {+ "codex" => &CODEX_CLI,+ "kimi" => &KIMI_CLI,+ "cursor" => &CURSOR_CLI,+ _ => &CODEX_CLI,+ }+ }++ async fn handle_messages(&self, _body: MessagesRequest, ctx: RequestContext) -> Response {+ placeholder_provider_response("messages", &ctx.provider)+ }++ async fn handle_count_tokens(&self, _body: MessagesRequest, ctx: RequestContext) -> Response {+ placeholder_provider_response("count_tokens", &ctx.provider)+ }+}++fn placeholder_provider_response(route: &str, provider: &str) -> Response {+ let _ = route;+ json_error(+ StatusCode::NOT_IMPLEMENTED,+ "unsupported_provider_error",+ format!("provider '{}' is not yet implemented", provider),+ )+}++#[derive(Clone, Copy)]+struct PlaceholderCli {+ provider: &'static str,+}++impl CliHandlers for PlaceholderCli {+ fn login(&self) -> Result<()> {+ Err(anyhow!("{}: browser login not supported", self.provider))+ }++ fn device(&self) -> Result<()> {+ Err(anyhow!("{}: device login not supported", self.provider))+ }++ fn status(&self) -> Result<()> {+ use serde_json::Value;+ let path = crate::paths::provider_auth_file(self.provider);+ let legacy = crate::paths::provider_legacy_auth_file(self.provider);+ if crate::auth::load_auth_file_with_legacy::<Value>(&path, &legacy).is_some() {+ Ok(())+ } else {+ Err(anyhow!("Not authenticated"))+ }+ }++ fn logout(&self) -> Result<()> {+ let path = crate::paths::provider_auth_file(self.provider);+ let legacy = crate::paths::provider_legacy_auth_file(self.provider);+ let _ = crate::auth::delete_auth_file(&path, &legacy);+ Ok(())+ }+}++const CODEX_CLI: PlaceholderCli = PlaceholderCli { provider: "codex" };+const KIMI_CLI: PlaceholderCli = PlaceholderCli { provider: "kimi" };+const CURSOR_CLI: PlaceholderCli = PlaceholderCli { provider: "cursor" };++fn expand_codex_models() -> Vec<String> {+ let mut set = HashSet::new();+ let mut out = Vec::new();+ for model in CODEX_MODELS {+ if set.insert((*model).to_string()) {+ out.push((*model).to_string());+ }+ let fast = format!("{model}-fast");+ if set.insert(fast.clone()) {+ out.push(fast);+ }+ }+ out.sort_unstable();+ out+}++fn build_cursor_models() -> Vec<String> {+ let mut out: Vec<String> = CURSOR_LEGACY_MODELS+ .iter()+ .map(|s| (*s).to_string())+ .collect();+ out.sort_unstable();+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn normalize_model_trims_hint() {+ assert_eq!(normalize_incoming_model("gpt-5.4-fast[1m]"), "gpt-5.4-fast");+ assert_eq!(normalize_incoming_model("gpt-5.4-fast"), "gpt-5.4-fast");+ }++ #[test]+ fn alias_routes_to_configured_provider() {+ let registry = Registry::new(AliasProvider::Kimi);+ let p = registry.provider_for_model("haiku", None);+ assert!(p.is_some());+ assert_eq!(p.expect("provider").name(), "kimi");+ }++ #[test]+ fn cursor_prefix_routes() {+ let registry = Registry::new(AliasProvider::Codex);+ assert_eq!(+ registry+ .provider_for_model("cursor:gpt-5.5", None)+ .unwrap()+ .name(),+ "cursor"+ );+ assert_eq!(+ registry+ .provider_for_model("cursor-plan:gpt-5.5", None)+ .unwrap()+ .name(),+ "cursor"+ );+ assert_eq!(+ registry+ .provider_for_model("cursor-ask:gpt-5.5", None)+ .unwrap()+ .name(),+ "cursor"+ );+ }+}diff --git a/src/retry.rs b/src/retry.rsnew file mode 100644index 0000000..48b6196--- /dev/null+++ b/src/retry.rs@@ -0,0 +1,70 @@+use std::time::Duration;++pub const RETRY_INITIAL_DELAY_MS: u64 = 2000;+pub const RETRY_MAX_DELAY_MS: u64 = 30_000;+pub const RETRY_BACKOFF_FACTOR: u64 = 2;+pub const MAX_RATE_LIMIT_RETRIES: u32 = 3;++#[derive(Debug, Clone, Copy)]+pub struct BackoffOutcome {+ pub wait_ms: u64,+ pub exceeds_budget: bool,+}++pub fn should_retry_status(status: u16) -> bool {+ matches!(status, 429 | 500 | 502 | 503 | 504)+}++pub fn compute_backoff_delay(attempt: u32, retry_after: Option<&str>) -> BackoffOutcome {+ if let Some(raw) = retry_after+ && let Ok(raw_secs) = raw.parse::<f64>()+ {+ let target_ms = (raw_secs * 1000.0).ceil() as u64;+ return BackoffOutcome {+ wait_ms: target_ms.min(RETRY_MAX_DELAY_MS),+ exceeds_budget: target_ms > RETRY_MAX_DELAY_MS,+ };+ }++ let mut exp =+ RETRY_INITIAL_DELAY_MS.saturating_mul(RETRY_BACKOFF_FACTOR.saturating_pow(attempt));+ if exp > RETRY_MAX_DELAY_MS {+ exp = RETRY_MAX_DELAY_MS;+ }+ let jitter = exp / 2;+ let wait_ms = (exp / 2) + (jitter / 2);+ BackoffOutcome {+ wait_ms,+ exceeds_budget: false,+ }+}++pub async fn sleep(ms: u64) {+ tokio::time::sleep(Duration::from_millis(ms)).await;+}++#[cfg(test)]+pub async fn retry_on_statuses<T, E, F>(mut next: F) -> Result<T, E>+where+ E: std::fmt::Debug,+ F: FnMut(u32) -> Result<T, E>,+{+ let mut attempt = 0;+ loop {+ attempt += 1;+ if attempt > MAX_RATE_LIMIT_RETRIES + 1 {+ break;+ }+ match next(attempt) {+ Ok(value) => return Ok(value),+ Err(err) if attempt <= MAX_RATE_LIMIT_RETRIES + 1 => {+ if attempt > MAX_RATE_LIMIT_RETRIES {+ return Err(err);+ }+ sleep(compute_backoff_delay(attempt, None).wait_ms).await;+ }+ Err(err) => return Err(err),+ }+ }+ unreachable!()+}diff --git a/src/server.rs b/src/server.rsnew file mode 100644index 0000000..9b5f537--- /dev/null+++ b/src/server.rs@@ -0,0 +1,212 @@+use crate::{+ anthropic::json_error,+ provider::RequestContext,+ registry::{Registry, normalize_incoming_model},+ session::{self, SessionState},+ traffic::{TrafficCaptureOptions, create_traffic_capture},+};+use axum::{+ Json, Router,+ body::Body,+ extract::State,+ http::{Request, StatusCode},+ response::Response,+ routing::{get, post},+};+use serde::de::DeserializeOwned;+use serde_json::json;+use std::sync::Arc;+use tokio::net::TcpListener;+use uuid::Uuid;++pub struct ServerConfig {+ pub port: u16,+}++pub async fn serve(config: ServerConfig) -> anyhow::Result<()> {+ let listener = TcpListener::bind(("127.0.0.1", config.port)).await?;+ let app = app(Arc::new(Registry::with_default_alias()));+ axum::serve(listener, app).await?;+ Ok(())+}++pub fn app(registry: Arc<Registry>) -> Router {+ Router::new()+ .route("/healthz", get(healthz))+ .route("/v1/messages", post(handler_messages))+ .route("/v1/messages/count_tokens", post(handler_count_tokens))+ .fallback(fallback_handler)+ .with_state(registry)+}++async fn healthz() -> Json<serde_json::Value> {+ Json(json!({ "ok": true }))+}++async fn handler_messages(State(registry): State<Arc<Registry>>, req: Request<Body>) -> Response {+ dispatch_request(registry, req, false).await+}++async fn handler_count_tokens(+ State(registry): State<Arc<Registry>>,+ req: Request<Body>,+) -> Response {+ dispatch_request(registry, req, true).await+}++async fn dispatch_request(+ registry: Arc<Registry>,+ req: Request<Body>,+ count_tokens: bool,+) -> Response {+ let session_id = req+ .headers()+ .get("x-claude-code-session-id")+ .and_then(|value| value.to_str().ok())+ .map(std::string::ToString::to_string);+ let req_id = Uuid::new_v4().to_string();+ let now = current_millis();+ let body_bytes = match axum::body::to_bytes(req.into_body(), usize::MAX).await {+ Ok(bytes) => bytes,+ Err(err) => {+ return json_error(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ format!("Invalid JSON: {err}"),+ );+ }+ };++ let body: crate::anthropic::schema::MessagesRequest = match parse_json_body(&body_bytes) {+ Ok(body) => body,+ Err(response) => return *response,+ };++ let model = match body.model.as_deref() {+ Some(model) => model,+ None => {+ return json_error(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ format!(+ "Missing \"model\" in request body. {}",+ registry.unknown_model_message()+ ),+ );+ }+ };++ let normalized_model = normalize_incoming_model(model);+ let session_state = if let Some(session_id) = session_id.as_deref() {+ session::existing_session(Some(session_id), now)+ } else {+ None+ };++ let provider = registry.provider_for_model(+ &normalized_model,+ session_state+ .as_ref()+ .and_then(|state| state.affinity_provider.as_ref()),+ );++ let provider = match provider {+ Some(provider) => provider,+ None => {+ return json_error(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ format!(+ "Unknown model \"{normalized_model}\". {}",+ registry.unknown_model_message()+ ),+ );+ }+ };++ let current = session::record_session_request(+ session_id.as_deref(),+ session_state.as_ref(),+ provider.name(),+ &normalized_model,+ now,+ );++ if let Some(capture) = create_traffic_capture(TrafficCaptureOptions {+ req_id: req_id.clone(),+ session_id: session_id.clone(),+ session_seq: current.as_ref().map(|s| s.seq),+ provider: Some(provider.name().to_string()),+ state_dir_override: None,+ }) {+ capture.write_json(+ "000-metadata",+ &json!({+ "reqId": req_id,+ "sessionId": session_id,+ "sessionSeq": current.as_ref().map(|s| s.seq),+ "provider": provider.name(),+ "model": normalized_model,+ }),+ );+ capture.write_json(+ "010-anthropic-request",+ &serde_json::to_value(&body).unwrap_or_else(|_| json!({})),+ );+ }++ let context = RequestContext {+ req_id,+ session_id,+ session_seq: current.map(|s| s.seq),+ provider: provider.name().to_string(),+ };++ if count_tokens {+ provider.handle_count_tokens(body, context).await+ } else {+ provider.handle_messages(body, context).await+ }+}++fn parse_json_body<T>(body: &[u8]) -> Result<T, Box<Response>>+where+ T: DeserializeOwned,+{+ if body.is_empty() {+ return Err(Box::new(json_error(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ "Invalid JSON: empty body",+ )));+ }++ serde_json::from_slice::<T>(body).map_err(|err| {+ Box::new(json_error(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ format!("Invalid JSON: {err}"),+ ))+ })+}++async fn fallback_handler(method: axum::http::Method, uri: axum::http::Uri) -> Response {+ json_error(+ StatusCode::NOT_FOUND,+ "not_found",+ format!("No route for {method} {}", uri.path()),+ )+}++fn current_millis() -> u64 {+ use std::time::{SystemTime, UNIX_EPOCH};+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}++#[allow(dead_code)]+fn _unused(session_state: Option<&SessionState>) {+ let _ = session_state;+}diff --git a/src/session.rs b/src/session.rsnew file mode 100644index 0000000..d5559b5--- /dev/null+++ b/src/session.rs@@ -0,0 +1,104 @@+use crate::config::AliasProvider;+use crate::registry::normalize_incoming_model;+use std::collections::{HashMap, VecDeque};+use std::sync::{LazyLock, Mutex};++const SESSION_IDLE_TTL_MS: u64 = 30 * 60 * 1000;+pub const MAX_SESSIONS: usize = 10_000;++#[derive(Debug, Clone)]+pub struct SessionState {+ pub seq: u64,+ pub affinity_provider: Option<AliasProvider>,+ pub last_seen: u64,+}++#[derive(Default)]+struct SessionStore {+ map: HashMap<String, SessionState>,+ order: VecDeque<String>,+}++static SESSIONS: LazyLock<Mutex<SessionStore>> =+ LazyLock::new(|| Mutex::new(SessionStore::default()));++fn now_millis() -> u64 {+ use std::time::{SystemTime, UNIX_EPOCH};+ let dur = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default();+ dur.as_millis() as u64+}++pub fn existing_session(session_id: Option<&str>, now: u64) -> Option<SessionState> {+ let id = session_id?;+ let mut store = SESSIONS.lock().expect("session lock");+ let state = store.map.get(id).cloned()?;+ if now.saturating_sub(state.last_seen) > SESSION_IDLE_TTL_MS {+ store.map.remove(id);+ store.order.retain(|item| item != id);+ return None;+ }+ Some(state)+}++pub fn existing_session_now(session_id: Option<&str>) -> Option<SessionState> {+ existing_session(session_id, now_millis())+}++pub fn record_session_request(+ session_id: Option<&str>,+ prior: Option<&SessionState>,+ provider_name: &str,+ model: &str,+ now: u64,+) -> Option<SessionState> {+ let id = session_id?;+ let mut store = SESSIONS.lock().expect("session lock");+ let mut next = prior.cloned().unwrap_or(SessionState {+ seq: 0,+ affinity_provider: None,+ last_seen: now,+ });+ next.seq += 1;+ next.last_seen = now;+ if is_alias_routable_provider(provider_name)+ && !crate::registry::is_anthropic_alias(normalize_incoming_model(model).as_str())+ {+ next.affinity_provider = Some(match provider_name {+ "codex" => AliasProvider::Codex,+ "kimi" => AliasProvider::Kimi,+ _ => next.affinity_provider.unwrap_or(AliasProvider::Codex),+ });+ }++ if !store.map.contains_key(id) {+ store.order.push_back(id.to_string());+ }+ store.map.insert(id.to_string(), next.clone());++ while store.order.len() > MAX_SESSIONS {+ if let Some(evict) = store.order.pop_front() {+ store.map.remove(&evict);+ } else {+ break;+ }+ }++ Some(next)+}++fn is_alias_routable_provider(name: &str) -> bool {+ matches!(name, "codex" | "kimi")+}++#[cfg(test)]+pub fn reset_sessions_for_test() {+ let mut store = SESSIONS.lock().expect("session lock");+ store.map.clear();+ store.order.clear();+}++pub fn affinity_provider_from_session(session: &SessionState) -> Option<AliasProvider> {+ session.affinity_provider+}diff --git a/src/traffic.rs b/src/traffic.rsnew file mode 100644index 0000000..dd9fdb6--- /dev/null+++ b/src/traffic.rs@@ -0,0 +1,231 @@+use serde_json::{Map, Value};+use std::fs::{self, File, create_dir_all};+use std::io::{self, Write};+use std::path::{Path, PathBuf};+use std::sync::{Mutex, MutexGuard};++use crate::config::AliasProvider;+use crate::logging::REDACT_KEYS;+use crate::paths;++#[derive(Debug)]+pub struct TrafficCapture {+ root: PathBuf,+ artifact_counter: Mutex<usize>,+ event_counter: Mutex<usize>,+}++#[derive(Debug)]+pub struct TrafficCaptureOptions {+ pub req_id: String,+ pub session_id: Option<String>,+ pub session_seq: Option<u64>,+ pub provider: Option<String>,+ pub state_dir_override: Option<PathBuf>,+}++pub fn traffic_capture_enabled() -> bool {+ traffic_capture_enabled_for_env(&std::env::vars().collect())+}++pub fn traffic_capture_enabled_for_env(env: &std::collections::HashMap<String, String>) -> bool {+ match env.get("CCP_TRAFFIC_LOG").map(String::as_str) {+ Some(v) => matches!(v, "1" | "true" | "yes"),+ None => false,+ }+}++pub fn create_traffic_capture(opts: TrafficCaptureOptions) -> Option<TrafficCapture> {+ if !traffic_capture_enabled() {+ return None;+ }+ let state_root = opts+ .state_dir_override+ .unwrap_or_else(paths::state_dir)+ .join("traffic")+ .join(sanitize_path_part(+ opts.session_id.as_deref().unwrap_or("no-session"),+ ))+ .join(format!(+ "{:06}-{}-{}",+ opts.session_seq.unwrap_or(0),+ sanitize_path_part(opts.provider.as_deref().unwrap_or("unknown-provider")),+ sanitize_path_part(&opts.req_id),+ ));++ Some(TrafficCapture {+ root: state_root,+ artifact_counter: Mutex::new(0),+ event_counter: Mutex::new(0),+ })+}++impl TrafficCapture {+ pub fn write_json(&self, name: &str, value: &Value) {+ let value = redact_traffic(value);+ let payload = serde_json::to_string_pretty(&value)+ .unwrap_or_else(|_| "{}".to_string())+ .into_bytes();+ let path = self.next_artifact_path(name, true);+ let _ = write_bytes(path, &payload);+ }++ pub fn write_text(&self, name: &str, text: &str) {+ let path = self.next_artifact_path(name, false);+ let _ = write_bytes(path, text.as_bytes());+ }++ pub fn write_bytes(&self, name: &str, value: &[u8]) {+ let path = self.next_artifact_path(name, true);+ let _ = write_bytes(path, value);+ }++ pub fn write_json_event(&self, name: &str, value: &Value) {+ let value = redact_traffic(value);+ let payload = serde_json::to_string_pretty(&value)+ .unwrap_or_else(|_| "{}".to_string())+ .into_bytes();+ let path = self.next_event_path(name, true);+ let _ = write_bytes(path, &payload);+ }++ fn next_artifact_path(&self, name: &str, ensure_ext_json: bool) -> PathBuf {+ let mut counter: MutexGuard<'_, usize> = self+ .artifact_counter+ .lock()+ .unwrap_or_else(|_| self.artifact_counter.lock().unwrap());+ *counter += 1;+ let file = if ensure_ext_json && !name.ends_with(".json") {+ format!("{name}.json")+ } else {+ name.to_string()+ };+ self.root+ .join(format!("{:03}-{}", *counter, sanitize_path_part(&file)))+ }++ fn next_event_path(&self, name: &str, ensure_ext_json: bool) -> PathBuf {+ let mut counter: MutexGuard<'_, usize> = self+ .event_counter+ .lock()+ .unwrap_or_else(|_| self.event_counter.lock().unwrap());+ *counter += 1;+ let file = if ensure_ext_json && !name.ends_with(".json") {+ format!("{name}.json")+ } else {+ name.to_string()+ };+ self.root+ .join("events")+ .join(format!("{:06}-{}", *counter, sanitize_path_part(&file)))+ }+}++fn write_bytes(path: PathBuf, value: &[u8]) -> io::Result<()> {+ if let Some(parent) = path.parent() {+ create_dir_all(parent)?;+ if let Ok(meta) = fs::metadata(parent) {+ set_mode(parent, 0o700);+ if meta.is_dir() {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perm = meta.permissions();+ perm.set_mode(0o700);+ let _ = fs::set_permissions(parent, perm);+ }+ }+ }+ }+ let mut out = File::create(&path)?;+ out.write_all(value)?;+ out.sync_all()?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perm = out.metadata()?.permissions();+ perm.set_mode(0o600);+ let _ = fs::set_permissions(&path, perm);+ }+ Ok(())+}++pub fn sanitize_path_part(input: &str) -> String {+ let cleaned: String = input+ .chars()+ .map(|ch| {+ if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' {+ ch+ } else {+ '_'+ }+ })+ .collect();++ let truncated = if cleaned.len() > 160 {+ &cleaned[..160]+ } else {+ &cleaned+ };+ if truncated.is_empty() {+ "unknown".to_string()+ } else {+ truncated.to_string()+ }+}++pub fn redact_traffic(value: &Value) -> Value {+ redact_traffic_with_depth(value, 0)+}++fn redact_traffic_with_depth(value: &Value, depth: u16) -> Value {+ if depth > 100 {+ return Value::String("[depth-limit]".to_string());+ }++ match value {+ Value::Object(map) => {+ let mut out = Map::new();+ for (key, value) in map {+ if REDACT_KEYS.contains(&key.to_lowercase().as_str()) {+ out.insert(key.clone(), redact_traffic_value(value));+ } else {+ out.insert(key.clone(), redact_traffic_with_depth(value, depth + 1));+ }+ }+ Value::Object(out)+ }+ Value::Array(values) => Value::Array(+ values+ .iter()+ .map(|value| redact_traffic_with_depth(value, depth + 1))+ .collect(),+ ),+ _ => value.clone(),+ }+}++fn redact_traffic_value(value: &Value) -> Value {+ match value {+ Value::String(s) => Value::String(format!("[redacted len={}]", s.len())),+ Value::Object(_) | Value::Array(_) => Value::String("[redacted]".to_string()),+ _ => Value::String("[redacted]".to_string()),+ }+}++fn set_mode(path: &Path, mode: u32) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(meta) = fs::metadata(path) {+ let mut perm = meta.permissions();+ perm.set_mode(mode);+ let _ = fs::set_permissions(path, perm);+ }+ }+}++#[allow(dead_code)]+fn _provider_alias(_provider: &str) -> Option<AliasProvider> {+ None+}diff --git a/tests/cli.rs b/tests/cli.rsnew file mode 100644index 0000000..bbfed31--- /dev/null+++ b/tests/cli.rs@@ -0,0 +1,96 @@+use assert_cmd::Command;+use predicates::str::contains;+use std::env;+use tempfile::TempDir;++#[test]+fn version_aliases_print_expected_version() -> Result<(), Box<dyn std::error::Error>> {+ let expected = format!("claude-code-proxy {}", env!("CARGO_PKG_VERSION"));++ for arg in ["--version", "-v", "version"] {+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.arg(arg)+ .assert()+ .success()+ .stdout(contains(expected.clone()));+ }+ Ok(())+}++#[test]+fn models_prints_all_providers() -> Result<(), Box<dyn std::error::Error>> {+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.arg("models");+ let out = String::from_utf8(cmd.output()?.stdout)?;+ assert!(out.contains("codex:"));+ assert!(out.contains("kimi:"));+ assert!(out.contains("cursor:"));++ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["models", "--full"]);+ cmd.output()?;+ Ok(())+}++#[test]+fn invalid_command_exits_two() -> Result<(), Box<dyn std::error::Error>> {+ Command::cargo_bin("claude-code-proxy")?+ .arg("definitely-not-a-command")+ .assert()+ .failure()+ .code(2);+ Ok(())+}++#[test]+fn provider_auth_status_unauthenticated_and_logout() -> Result<(), Box<dyn std::error::Error>> {+ let temp = TempDir::new()?;+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["codex", "auth", "status"]);+ cmd.env("CCP_CONFIG_DIR", temp.path());+ let output = cmd.output()?;+ assert_eq!(output.status.code(), Some(1));+ assert!(String::from_utf8(output.stdout)?.contains("Not authenticated"));++ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["codex", "auth", "logout"]);+ cmd.env("CCP_CONFIG_DIR", temp.path());+ let output = cmd.output()?;+ assert!(output.status.success());+ Ok(())+}++#[test]+fn invalid_provider_login_is_unsupported_exit_two() -> Result<(), Box<dyn std::error::Error>> {+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["cursor", "auth", "login"]);+ let output = cmd.output()?;+ assert_eq!(output.status.code(), Some(2));+ let out = String::from_utf8(output.stderr)?;+ assert!(out.contains("not supported") || out.contains("unsupported"));+ Ok(())+}++#[test]+fn provider_logout_without_auth_is_success() -> Result<(), Box<dyn std::error::Error>> {+ let temp = TempDir::new()?;+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["kimi", "auth", "logout"]);+ cmd.env("CCP_CONFIG_DIR", temp.path());+ cmd.assert().success();+ Ok(())+}++#[test]+fn models_output_is_stable_order() -> Result<(), Box<dyn std::error::Error>> {+ let mut cmd = Command::cargo_bin("claude-code-proxy")?;+ cmd.args(["models", "--full"]);+ let output = cmd.output()?;+ let out = String::from_utf8(output.stdout)?;+ let codex_pos = out.find("codex:").unwrap_or(0);+ let kimi_pos = out.find("kimi:").unwrap_or(0);+ let cursor_pos = out.find("cursor:").unwrap_or(0);+ assert!(codex_pos < kimi_pos);+ assert!(kimi_pos < cursor_pos);+ Ok(())+}diff --git a/tests/fixtures/anthropic-message.json b/tests/fixtures/anthropic-message.jsonnew file mode 100644index 0000000..c7c5b71--- /dev/null+++ b/tests/fixtures/anthropic-message.json@@ -0,0 +1,12 @@+{+ "model": "gpt-5.4[1m]",+ "max_tokens": 64,+ "messages": [+ {+ "role": "user",+ "content": "hello"+ }+ ],+ "stream": true,+ "extra_field": "extra"+}diff --git a/tests/fixtures/sse-basic.txt b/tests/fixtures/sse-basic.txtnew file mode 100644index 0000000..4370ac0--- /dev/null+++ b/tests/fixtures/sse-basic.txt@@ -0,0 +1,11 @@+: ping+:event+: keep alive++data: {"chunk":1}+event: update+data: {"text":"line1"}+data: {"text":"line2"}++event: final+data: {"done":true}diff --git a/tests/foundation.rs b/tests/foundation.rsnew file mode 100644index 0000000..5f0df71--- /dev/null+++ b/tests/foundation.rs@@ -0,0 +1,224 @@+use claude_code_proxy::anthropic::{+ encode_sse_event, parse_sse_events, parse_sse_events_with_stats, schema::MessagesRequest,+};+use claude_code_proxy::auth::{AuthStorage, InMemoryAuthStore};+use claude_code_proxy::config::{AliasProvider, load_config};+use claude_code_proxy::logging::{create_logger, redact_value};+use claude_code_proxy::paths::{self, DirResolverEnv};+use claude_code_proxy::retry::{RETRY_INITIAL_DELAY_MS, RETRY_MAX_DELAY_MS, compute_backoff_delay};+use claude_code_proxy::traffic::{+ TrafficCaptureOptions, create_traffic_capture, redact_traffic, sanitize_path_part,+ traffic_capture_enabled_for_env,+};+use serde_json::Map;+use serde_json::json;+use std::collections::HashMap;+use std::env;+use tempfile::TempDir;++#[test]+fn messages_fixture_and_sse_parsing() {+ let raw = std::fs::read_to_string("tests/fixtures/anthropic-message.json").unwrap();+ let req: MessagesRequest = serde_json::from_str(&raw).unwrap();+ assert_eq!(req.model.as_deref(), Some("gpt-5.4[1m]"));+ assert!(req.extra.contains_key("extra_field"));++ let raw_sse = std::fs::read_to_string("tests/fixtures/sse-basic.txt").unwrap();+ let events = parse_sse_events(raw_sse.as_bytes());+ assert_eq!(events.len(), 2);+ assert_eq!(events[0].event, None);+ assert_eq!(events[0].data, "{\"chunk\":1}");+ assert_eq!(events[1].event.as_deref(), Some("final"));+ assert_eq!(events[1].data, "{\"done\":true}");++ let (events_with_stats, stats) = parse_sse_events_with_stats(raw_sse.as_bytes());+ assert_eq!(events_with_stats.len(), events.len());+ assert!(stats.event_count >= 2);++ let encoded = encode_sse_event(Some("message"), "{\"a\":1}\n{\"b\":2}");+ assert_eq!(+ encoded,+ b"event: message\ndata: {\\\"a\\\":1}\ndata: {\\\"b\\\":2}\n\n".to_vec()+ );+}++#[test]+fn path_resolvers_cover_platform_rules() {+ let mut env = HashMap::new();+ env.insert("CCP_CONFIG_DIR".to_string(), "/tmp/ccp-config".to_string());+ let deps = DirResolverEnv {+ platform: "darwin".to_string(),+ home: "/home/u".into(),+ env: env.clone(),+ };+ assert_eq!(+ paths::resolve_config_dir(&deps).to_string_lossy(),+ "/tmp/ccp-config"+ );++ let deps = DirResolverEnv {+ platform: "darwin".to_string(),+ home: "/home/u".into(),+ env: HashMap::from([("XDG_CONFIG_HOME".into(), "/x".into())]),+ };+ assert_eq!(+ paths::resolve_config_dir(&deps).to_string_lossy(),+ "/home/u/.config/claude-code-proxy"+ );++ let deps = DirResolverEnv {+ platform: "linux".to_string(),+ home: "/home/u".into(),+ env: HashMap::from([("XDG_CONFIG_HOME".into(), "/x".into())]),+ };+ assert_eq!(+ paths::resolve_config_dir(&deps).to_string_lossy(),+ "/x/claude-code-proxy"+ );++ let deps = DirResolverEnv {+ platform: "win32".to_string(),+ home: "C:/Users/u".into(),+ env: HashMap::from([("APPDATA".into(), "C:/Users/u/AppData/Roaming".into())]),+ };+ assert_eq!(+ paths::resolve_config_dir(&deps).to_string_lossy(),+ "C:/Users/u/AppData/Roaming/claude-code-proxy"+ );+}++#[test]+fn logging_redaction_and_truncation() {+ let short =+ json!({"authorization": "abc", "visible": "x", "nested": {"set-cookie": "c", "v": "y"}});+ let redacted = redact_value(short);+ assert_eq!(redacted["visible"], json!("x"));+ assert!(+ redacted["authorization"]+ .as_str()+ .unwrap()+ .contains("redacted")+ );++ let long = "a".repeat(5000);+ let long_payload = redact_value(json!({"text": long}));+ let text = long_payload["text"].as_str().unwrap();+ assert!(text.contains("[4000 more]"));+}++#[test]+fn traffic_capture_helpers() {+ let mut env = HashMap::new();+ env.insert("CCP_TRAFFIC_LOG".into(), "1".into());+ assert!(traffic_capture_enabled_for_env(&env));+ assert!(!traffic_capture_enabled_for_env(&HashMap::new()));++ assert_eq!(sanitize_path_part("a*b@c/def"), "a_b_c_def");+ let path = sanitize_path_part(+ &"/a\+/path"+ .to_string(),+ );+ assert_eq!(path.chars().all(|ch| ch != '/'), true);++ let sample = json!({"access_token":"abc","nested":{"chatgpt-account-id":"x","value":1}});+ let redacted = redact_traffic(&sample);+ assert!(+ redacted["access_token"]+ .as_str()+ .unwrap()+ .contains("redacted")+ );++ unsafe {+ env::set_var("CCP_TRAFFIC_LOG", "1");+ }+ let temp = TempDir::new().unwrap();+ let capture = create_traffic_capture(TrafficCaptureOptions {+ req_id: "req-1".into(),+ session_id: None,+ session_seq: Some(12),+ provider: Some("codex".into()),+ state_dir_override: Some(temp.path().to_path_buf()),+ })+ .expect("capture");++ capture.write_text("020-note", "hello");+ capture.write_json("030-req", &json!({"token":"abc"}));+ unsafe {+ env::remove_var("CCP_TRAFFIC_LOG");+ }+}++#[test]+fn retry_backoff_decisions() {+ let outcome = compute_backoff_delay(0, None);+ assert!(outcome.wait_ms >= RETRY_INITIAL_DELAY_MS / 2);+ assert!(outcome.wait_ms <= RETRY_MAX_DELAY_MS);++ let outcome_num = compute_backoff_delay(0, Some("5"));+ assert_eq!(outcome_num.wait_ms, 5000);++ let too_long = compute_backoff_delay(0, Some("120"));+ assert!(too_long.exceeds_budget);+}++#[tokio::test]+async fn auth_store_read_write_and_logout() {+ let store: InMemoryAuthStore<serde_json::Value> = InMemoryAuthStore::new();+ assert!(store.load().unwrap().is_none());+ store.save(json!({"token": "abc"})).unwrap();+ let loaded = store.load().unwrap().expect("value");+ assert_eq!(loaded["token"], json!("abc"));+ store.clear().unwrap();+ assert!(store.load().unwrap().is_none());++ let path = tempfile::tempdir().unwrap().path().join("auth.json");+ assert!(!path.exists());+}++#[test]+fn config_env_precedence_and_defaults() {+ let original = env::var("PORT").ok();+ unsafe {+ env::remove_var("PORT");+ }+ let cfg = load_config();+ assert_eq!(cfg.port, 18765);++ unsafe {+ env::set_var("PORT", "19999");+ }+ let cfg = load_config();+ assert_eq!(cfg.port, 19999);++ if let Some(v) = original {+ unsafe {+ env::set_var("PORT", v);+ }+ } else {+ unsafe {+ env::remove_var("PORT");+ }+ }++ unsafe {+ env::set_var("CCP_ALIAS_PROVIDER", "kimi");+ }+ assert!(matches!(load_config().alias_provider, AliasProvider::Kimi));+ unsafe {+ env::remove_var("CCP_ALIAS_PROVIDER");+ }+}++#[test]+fn alias_provider_has_expected_default() {+ assert!(matches!(load_config().alias_provider, AliasProvider::Codex));+}++#[test]+fn logger_factory_builds() {+ let logger = create_logger("server");+ let fields = Map::new();+ logger.debug("ready", Some(fields));+}diff --git a/tests/server.rs b/tests/server.rsnew file mode 100644index 0000000..fe4c2e2--- /dev/null+++ b/tests/server.rs@@ -0,0 +1,199 @@+use axum::body::Body;+use axum::http::{Method, Request, StatusCode};+use claude_code_proxy::{registry::Registry, server::app};+use serde_json::{Value, json};+use std::sync::Arc;+use tower::util::ServiceExt;++fn body_string(json: &str) -> Body {+ Body::from(json.to_string())+}++#[tokio::test]+async fn healthz_returns_ok() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::GET)+ .uri("/healthz")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ assert_eq!(body, json!({"ok": true}));+}++#[tokio::test]+async fn invalid_json_request_is_json_error() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .body(body_string("{"))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let value: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ let error_type = value["error"]["type"].as_str().unwrap_or("");+ assert_eq!(error_type, "invalid_request_error");+}++#[tokio::test]+async fn empty_body_is_invalid_json() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn unknown_model_returns_400_with_summary() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .header("content-type", "application/json")+ .body(body_string(+ r#"{"messages":[{"role":"user","content":"hello"}],"model":"not-a-model"}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let body: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ let message = body["error"]["message"].as_str().unwrap_or("");+ assert!(message.contains("Unknown model \"not-a-model\""));+ assert!(message.contains("Supported:"));+}++#[tokio::test]+async fn missing_model_returns_400() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages/count_tokens")+ .header("content-type", "application/json")+ .body(body_string(+ r#"{"messages":[{"role":"user","content":"hello"}]}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let body: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ let error_type = body["error"]["type"].as_str().unwrap_or("");+ assert_eq!(error_type, "invalid_request_error");+}++#[tokio::test]+async fn known_model_reaches_placeholder_provider() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .header("content-type", "application/json")+ .body(body_string(+ r#"{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}]}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);+ let body: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ assert_eq!(+ body["error"]["type"].as_str().unwrap_or(""),+ "unsupported_provider_error"+ );+}++#[tokio::test]+async fn count_tokens_routes_to_provider() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages/count_tokens")+ .header("content-type", "application/json")+ .body(body_string(+ r#"{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}]}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);+}++#[tokio::test]+async fn unknown_routes_use_anthropic_not_found_error() {+ let app = app(Arc::new(Registry::with_default_alias()));+ let response = app+ .oneshot(+ Request::builder()+ .method(Method::GET)+ .uri("/nope")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::NOT_FOUND);+ let body: Value = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .ok()+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())+ .unwrap();+ assert_eq!(body["type"].as_str().unwrap_or(""), "error");+}