From da9d5d1ae070aebe03c320588cefeb74c314711b Mon Sep 17 00:00:00 2001 From: hermes Date: Wed, 30 Sep 2026 09:30:58 +0000 Subject: [PATCH] Subscription OAuth providers (Claude, Codex) + hx -p - auth: PKCE login, localhost callback or pasted redirect, refresh, ~/.hx/auth.json 0600, import Claude Code / Codex CLI logins - anthropic: Messages SSE with Claude Code identity, beta headers, tool-name mapping - codex: Responses SSE on chatgpt.com/backend-api/codex, store=false, encrypted reasoning replay - cli: hx login|logout , hx -p Closes #3, closes #4, closes #5 --- Cargo.lock | 1688 ++++++++++++++++++++++++++++++++- README.md | 14 + crates/hx-ai/Cargo.toml | 9 + crates/hx-ai/src/anthropic.rs | 384 ++++++++ crates/hx-ai/src/auth.rs | 499 ++++++++++ crates/hx-ai/src/codex.rs | 413 ++++++++ crates/hx-ai/src/lib.rs | 4 + crates/hx-cli/Cargo.toml | 5 + crates/hx-cli/src/main.rs | 91 +- 9 files changed, 3101 insertions(+), 6 deletions(-) create mode 100644 crates/hx-ai/src/anthropic.rs create mode 100644 crates/hx-ai/src/auth.rs create mode 100644 crates/hx-ai/src/codex.rs diff --git a/Cargo.lock b/Cargo.lock index 74015f0..387af53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,62 @@ # It is not intended for manual editing. version = 4 +[[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 0.61.2", +] + +[[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 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "async-trait" version = "0.1.92" @@ -10,9 +66,283 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "eventsource-stream" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" +dependencies = [ + "futures-core", + "nom", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[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 = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures" version = "0.3.34" @@ -69,7 +399,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -101,20 +431,130 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +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 = "hx-ai" version = "0.1.0" dependencies = [ "async-trait", + "base64", + "eventsource-stream", "futures", + "getrandom 0.4.3", + "reqwest", "serde", "serde_json", + "sha2", "thiserror", + "tokio", ] [[package]] name = "hx-cli" version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "futures", + "hx-ai", + "tokio", +] [[package]] name = "hx-core" @@ -136,24 +576,379 @@ version = "0.1.0" name = "hx-tui" version = "0.1.0" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[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 = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[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 = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[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 = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -163,6 +958,63 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -172,6 +1024,243 @@ 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 = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -199,7 +1288,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -215,12 +1304,102 @@ dependencies = [ "zmij", ] +[[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 = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.6" @@ -232,6 +1411,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -249,15 +1448,496 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[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", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +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 = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[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 = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/README.md b/README.md index 5c1001a..d364cde 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,16 @@ # hx +Minimal Rust coding agent. Uses your existing subscriptions, no API keys. + +```sh +cargo build --release +hx login claude # Claude Pro/Max +hx login codex # ChatGPT Plus/Pro +hx -p "hello" # Claude +hx --provider codex -p "hello" # Codex +``` + +Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically. +Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically. + +On a headless box, open the printed URL elsewhere and paste the final redirect URL back into the terminal. diff --git a/crates/hx-ai/Cargo.toml b/crates/hx-ai/Cargo.toml index 954f91c..2da20c2 100644 --- a/crates/hx-ai/Cargo.toml +++ b/crates/hx-ai/Cargo.toml @@ -6,10 +6,19 @@ license.workspace = true [dependencies] async-trait = "0.1.92" +base64 = "0.23.1" +eventsource-stream = "0.2.3" futures = "0.3.34" +getrandom = "0.4.3" +reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "rustls", "http2", "form"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" +sha2 = "0.11.0" thiserror = "2.0.21" +tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros", "time", "net", "io-util", "sync"] } [lints] workspace = true + +[dev-dependencies] +tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] } diff --git a/crates/hx-ai/src/anthropic.rs b/crates/hx-ai/src/anthropic.rs new file mode 100644 index 0000000..b459912 --- /dev/null +++ b/crates/hx-ai/src/anthropic.rs @@ -0,0 +1,384 @@ +//! Anthropic Messages API over Claude subscription OAuth. + +use crate::auth::{Auth, Kind}; +use crate::{ + ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage, +}; +use eventsource_stream::Eventsource; +use futures::{StreamExt, stream::BoxStream}; +use serde_json::{Value, json}; + +const CC_VERSION: &str = "2.1.280"; +const CC_IDENTITY: &str = "You are Claude Code, Anthropic's official CLI for Claude."; +/// OAuth tokens are only accepted with Claude Code tool-name casing. +const CC_TOOLS: &[&str] = &[ + "Read", + "Write", + "Edit", + "Bash", + "Grep", + "Glob", + "WebFetch", + "WebSearch", + "Task", + "TodoWrite", +]; + +fn to_cc(name: &str) -> String { + CC_TOOLS + .iter() + .find(|t| t.eq_ignore_ascii_case(name)) + .map_or_else(|| name.to_string(), |t| t.to_string()) +} + +fn from_cc(name: &str, req: &Request) -> String { + req.tools + .iter() + .find(|t| t.name.eq_ignore_ascii_case(name)) + .map_or_else(|| name.to_string(), |t| t.name.clone()) +} + +pub struct Anthropic { + auth: Auth, + base_url: String, + http: reqwest::Client, +} + +impl Anthropic { + pub fn new(auth: Auth) -> Self { + Self { + auth, + base_url: "https://api.anthropic.com".into(), + http: reqwest::Client::new(), + } + } + pub fn login_default() -> Result { + Ok(Self::new(Auth::load(Kind::Claude)?)) + } + pub fn with_base_url(mut self, u: impl Into) -> Self { + self.base_url = u.into(); + self + } +} + +fn block_json(b: &ContentBlock) -> Value { + match b { + ContentBlock::Image { media_type, data } => json!({ + "type": "image", + "source": {"type": "base64", "media_type": media_type, "data": data} + }), + ContentBlock::ToolUse { id, name, input } => { + json!({"type": "tool_use", "id": id, "name": to_cc(name), "input": input}) + } + other => serde_json::to_value(other).unwrap_or(Value::Null), + } +} + +pub fn body(req: &Request) -> Value { + let mut system = vec![json!({"type": "text", "text": CC_IDENTITY})]; + if !req.system.is_empty() { + system.push(json!({"type": "text", "text": req.system})); + } + // cache the stable prefix + if let Some(last) = system.last_mut() { + last["cache_control"] = json!({"type": "ephemeral"}); + } + let messages: Vec = req + .messages + .iter() + .map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::>()})) + .collect(); + let tools: Vec = req + .tools + .iter() + .map(|t| json!({"name": to_cc(&t.name), "description": t.description, "input_schema": t.input_schema})) + .collect(); + let mut b = json!({ + "model": req.model, + "max_tokens": req.max_tokens, + "stream": true, + "system": system, + "messages": messages, + }); + if !tools.is_empty() { + b["tools"] = tools.into(); + } + b +} + +/// Folds Anthropic SSE events into `StreamEvent`s. +#[derive(Default)] +pub struct Assembler { + blocks: Vec, + /// partial JSON for tool_use input, per block index + partial: Vec, + usage: Usage, + stop: Option, +} + +impl Assembler { + pub fn feed(&mut self, event: &str, data: &str, req: &Request) -> Result> { + let d: Value = match event { + "ping" | "" => return Ok(vec![]), + _ => serde_json::from_str(data).map_err(|e| Error::Decode(format!("{e}: {data}")))?, + }; + let u = |v: &Value| v.as_u64().unwrap_or(0); + let mut out = vec![]; + match event { + "message_start" => { + let us = &d["message"]["usage"]; + self.usage.input_tokens = u(&us["input_tokens"]); + self.usage.cache_read_tokens = u(&us["cache_read_input_tokens"]); + self.usage.cache_write_tokens = u(&us["cache_creation_input_tokens"]); + self.usage.output_tokens = u(&us["output_tokens"]); + } + "content_block_start" => { + let cb = &d["content_block"]; + let s = |k: &str| cb[k].as_str().unwrap_or_default().to_string(); + let b = match cb["type"].as_str() { + Some("text") => ContentBlock::Text { text: s("text") }, + Some("thinking") => ContentBlock::Thinking { + thinking: s("thinking"), + signature: None, + }, + Some("tool_use") => { + let name = from_cc(&s("name"), req); + out.push(StreamEvent::ToolUseStart { + id: s("id"), + name: name.clone(), + }); + ContentBlock::ToolUse { + id: s("id"), + name, + input: json!({}), + } + } + // redacted_thinking etc: keep as empty text so indices stay aligned + _ => ContentBlock::Text { + text: String::new(), + }, + }; + self.blocks.push(b); + self.partial.push(String::new()); + } + "content_block_delta" => { + let i = u(&d["index"]) as usize; + let dl = &d["delta"]; + let s = |k: &str| dl[k].as_str().unwrap_or_default(); + let (Some(b), Some(p)) = (self.blocks.get_mut(i), self.partial.get_mut(i)) else { + return Err(Error::Decode(format!("delta for unknown block {i}"))); + }; + match (dl["type"].as_str(), b) { + (Some("text_delta"), ContentBlock::Text { text }) => { + text.push_str(s("text")); + out.push(StreamEvent::TextDelta { + text: s("text").into(), + }); + } + (Some("thinking_delta"), ContentBlock::Thinking { thinking, .. }) => { + thinking.push_str(s("thinking")); + out.push(StreamEvent::ThinkingDelta { + text: s("thinking").into(), + }); + } + (Some("signature_delta"), ContentBlock::Thinking { signature, .. }) => { + *signature = Some(s("signature").into()); + } + (Some("input_json_delta"), ContentBlock::ToolUse { .. }) => { + p.push_str(s("partial_json")) + } + _ => {} + } + } + "content_block_stop" => { + let i = u(&d["index"]) as usize; + if let (Some(ContentBlock::ToolUse { input, .. }), Some(p)) = + (self.blocks.get_mut(i), self.partial.get(i)) + && !p.is_empty() + { + *input = serde_json::from_str(p) + .map_err(|e| Error::Decode(format!("tool input: {e}: {p}")))?; + } + } + "message_delta" => { + self.usage.output_tokens = + u(&d["usage"]["output_tokens"]).max(self.usage.output_tokens); + self.stop = Some(match d["delta"]["stop_reason"].as_str() { + Some("end_turn" | "stop_sequence") => StopReason::EndTurn, + Some("tool_use") => StopReason::ToolUse, + Some("max_tokens") => StopReason::MaxTokens, + _ => StopReason::Other, + }); + } + "message_stop" => { + let content = std::mem::take(&mut self.blocks) + .into_iter() + .filter(|b| !matches!(b, ContentBlock::Text { text } if text.is_empty())) + .collect(); + out.push(StreamEvent::Done { + message: Message { + role: Role::Assistant, + content, + }, + stop: self.stop.unwrap_or(StopReason::EndTurn), + usage: std::mem::take(&mut self.usage), + }); + } + "error" => { + return Err(Error::Api { + status: 0, + body: d["error"].to_string(), + }); + } + _ => {} + } + Ok(out) + } +} + +#[async_trait::async_trait] +impl Provider for Anthropic { + async fn stream(&self, req: Request) -> Result>> { + let (token, _) = self.auth.token().await?; + let r = self + .http + .post(format!("{}/v1/messages", self.base_url)) + .bearer_auth(token) + .header("anthropic-version", "2023-06-01") + .header( + "anthropic-beta", + "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14", + ) + .header("user-agent", format!("claude-cli/{CC_VERSION}")) + .header("x-app", "cli") + .json(&body(&req)) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))?; + let status = r.status().as_u16(); + if !(200..300).contains(&status) { + let body = r.text().await.unwrap_or_default(); + return Err(Error::Api { status, body }); + } + let s = r + .bytes_stream() + .eventsource() + .scan(Assembler::default(), move |a, ev| { + let out = match ev { + Ok(ev) => match a.feed(&ev.event, &ev.data, &req) { + Ok(v) => v.into_iter().map(Ok).collect(), + Err(e) => vec![Err(e)], + }, + Err(e) => vec![Err(Error::Http(e.to_string()))], + }; + futures::future::ready(Some(futures::stream::iter(out))) + }) + .flatten(); + Ok(s.boxed()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ToolSpec; + + fn req() -> Request { + Request { + model: "claude-sonnet-4-5".into(), + system: "be terse".into(), + messages: vec![Message::user("read a")], + tools: vec![ToolSpec { + name: "read".into(), + description: "read file".into(), + input_schema: json!({"type": "object"}), + }], + max_tokens: 1024, + } + } + + #[test] + fn request_body() { + let b = body(&req()); + assert_eq!(b["system"][0]["text"], CC_IDENTITY); + assert_eq!(b["system"][1]["text"], "be terse"); + assert_eq!(b["tools"][0]["name"], "Read"); + assert_eq!(b["messages"][0]["content"][0]["type"], "text"); + assert_eq!(b["stream"], true); + } + + #[test] + fn assemble_tool_use() { + let fixture = r#"message_start|{"type":"message_start","message":{"usage":{"input_tokens":10,"cache_read_input_tokens":3,"output_tokens":1}}} +ping|{} +content_block_start|{"index":0,"content_block":{"type":"thinking","thinking":""}} +content_block_delta|{"index":0,"delta":{"type":"thinking_delta","thinking":"hmm"}} +content_block_delta|{"index":0,"delta":{"type":"signature_delta","signature":"sig"}} +content_block_stop|{"index":0} +content_block_start|{"index":1,"content_block":{"type":"text","text":""}} +content_block_delta|{"index":1,"delta":{"type":"text_delta","text":"Read"}} +content_block_delta|{"index":1,"delta":{"type":"text_delta","text":"ing."}} +content_block_stop|{"index":1} +content_block_start|{"index":2,"content_block":{"type":"tool_use","id":"tu_1","name":"Read","input":{}}} +content_block_delta|{"index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\":"}} +content_block_delta|{"index":2,"delta":{"type":"input_json_delta","partial_json":"\"a\"}"}} +content_block_stop|{"index":2} +message_delta|{"delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":42}} +message_stop|{}"#; + let r = req(); + let mut a = Assembler::default(); + let mut evs = vec![]; + for l in fixture.lines() { + let (e, d) = l.split_once('|').unwrap(); + evs.extend(a.feed(e, d, &r).unwrap()); + } + assert_eq!(evs[0], StreamEvent::ThinkingDelta { text: "hmm".into() }); + assert_eq!( + evs[3], + StreamEvent::ToolUseStart { + id: "tu_1".into(), + name: "read".into() + } + ); + let StreamEvent::Done { + message, + stop, + usage, + } = evs.last().unwrap() + else { + panic!() + }; + assert_eq!(*stop, StopReason::ToolUse); + assert_eq!( + ( + usage.input_tokens, + usage.output_tokens, + usage.cache_read_tokens + ), + (10, 42, 3) + ); + assert_eq!(message.text(), "Reading."); + assert_eq!( + message.content[0], + ContentBlock::Thinking { + thinking: "hmm".into(), + signature: Some("sig".into()) + } + ); + assert_eq!( + message.content[2], + ContentBlock::ToolUse { + id: "tu_1".into(), + name: "read".into(), + input: json!({"path": "a"}) + } + ); + } + + #[test] + fn error_event() { + let e = + Assembler::default().feed("error", r#"{"error":{"type":"overloaded_error"}}"#, &req()); + assert!(matches!(e, Err(Error::Api { .. }))); + } +} diff --git a/crates/hx-ai/src/auth.rs b/crates/hx-ai/src/auth.rs new file mode 100644 index 0000000..5f9d955 --- /dev/null +++ b/crates/hx-ai/src/auth.rs @@ -0,0 +1,499 @@ +//! Subscription OAuth (Claude Pro/Max, ChatGPT Plus/Pro). No API keys. +//! +//! Credentials live in `~/.hx/auth.json` (0600). Existing Claude Code / Codex CLI logins are imported. + +use crate::{Error, Result}; +use base64::Engine; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::Mutex; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + Claude, + Codex, +} + +impl std::str::FromStr for Kind { + type Err = String; + fn from_str(s: &str) -> std::result::Result { + match s { + "claude" | "anthropic" => Ok(Kind::Claude), + "codex" | "openai" | "chatgpt" => Ok(Kind::Codex), + _ => Err(format!("unknown provider {s:?} (claude|codex)")), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Credential { + pub access: String, + pub refresh: String, + /// unix ms + pub expires: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account_id: Option, +} + +struct Oauth { + client_id: &'static str, + authorize: &'static str, + token: &'static str, + redirect: &'static str, + port: u16, + path: &'static str, + scope: &'static str, +} + +const CLAUDE: Oauth = Oauth { + client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", + authorize: "https://claude.ai/oauth/authorize", + token: "https://platform.claude.com/v1/oauth/token", + redirect: "http://localhost:53692/callback", + port: 53692, + path: "/callback", + scope: "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload", +}; + +const CODEX: Oauth = Oauth { + client_id: "app_EMoamEEZ73f0CkXaXp7hrann", + authorize: "https://auth.openai.com/oauth/authorize", + token: "https://auth.openai.com/oauth/token", + redirect: "http://localhost:1455/auth/callback", + port: 1455, + path: "/auth/callback", + scope: "openid profile email offline_access", +}; + +fn cfg(k: Kind) -> &'static Oauth { + match k { + Kind::Claude => &CLAUDE, + Kind::Codex => &CODEX, + } +} + +pub fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +fn home() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default() +} + +pub fn store_path() -> PathBuf { + std::env::var_os("HX_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home().join(".hx")) + .join("auth.json") +} + +type Store = BTreeMap; + +fn load_store() -> Store { + load_at(&store_path()) +} + +fn load_at(p: &std::path::Path) -> Store { + std::fs::read(p) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +fn save(k: Kind, c: &Credential) -> Result<()> { + save_at(&store_path(), k, Some(c)) +} + +fn save_at(p: &std::path::Path, k: Kind, c: Option<&Credential>) -> Result<()> { + let mut s = load_at(p); + match c { + Some(c) => s.insert(k, c.clone()), + None => s.remove(&k), + }; + let io = |e: std::io::Error| Error::Http(format!("{}: {e}", p.display())); + std::fs::create_dir_all(p.parent().unwrap_or(p)).map_err(io)?; + let tmp = p.with_extension("tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(&s).unwrap_or_default()).map_err(io)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)).map_err(io)?; + } + std::fs::rename(&tmp, p).map_err(io) +} + +/// Pull an existing login from Claude Code / Codex CLI. +fn import(k: Kind) -> Option { + match k { + Kind::Claude => { + let v: Value = serde_json::from_slice( + &std::fs::read(home().join(".claude/.credentials.json")).ok()?, + ) + .ok()?; + let o = &v["claudeAiOauth"]; + Some(Credential { + access: o["accessToken"].as_str()?.into(), + refresh: o["refreshToken"].as_str()?.into(), + expires: o["expiresAt"].as_u64().unwrap_or(0), + account_id: None, + }) + } + Kind::Codex => { + let codex = std::env::var_os("CODEX_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home().join(".codex")); + let v: Value = + serde_json::from_slice(&std::fs::read(codex.join("auth.json")).ok()?).ok()?; + let t = &v["tokens"]; + let access = t["access_token"].as_str()?; + Some(Credential { + access: access.into(), + refresh: t["refresh_token"].as_str()?.into(), + // unknown: force refresh on first use if the JWT says expired + expires: jwt_claims(access) + .and_then(|c| c["exp"].as_u64()) + .map(|s| s * 1000) + .unwrap_or(0), + account_id: t["account_id"] + .as_str() + .map(Into::into) + .or_else(|| account_id(access)), + }) + } + } +} + +pub fn jwt_claims(tok: &str) -> Option { + let p = tok.split('.').nth(1)?; + let b = URL_SAFE_NO_PAD + .decode(p.trim_end_matches('=')) + .or_else(|_| STANDARD.decode(p)) + .ok()?; + serde_json::from_slice(&b).ok() +} + +pub fn account_id(tok: &str) -> Option { + jwt_claims(tok)?["https://api.openai.com/auth"]["chatgpt_account_id"] + .as_str() + .map(Into::into) +} + +pub fn pkce() -> (String, String) { + let mut b = [0u8; 32]; + getrandom::fill(&mut b).expect("os rng"); + let verifier = URL_SAFE_NO_PAD.encode(b); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + (verifier, challenge) +} + +#[derive(Deserialize)] +struct TokenResp { + access_token: String, + refresh_token: Option, + expires_in: u64, +} + +async fn token_req(k: Kind, form: &[(&str, &str)]) -> Result { + let c = cfg(k); + let rb = reqwest::Client::new().post(c.token); + // Anthropic wants JSON, OpenAI wants form encoding. + let rb = match k { + Kind::Claude => rb.json(&form.iter().cloned().collect::>()), + Kind::Codex => rb.form(form), + }; + let r = rb.send().await.map_err(|e| Error::Http(e.to_string()))?; + let status = r.status().as_u16(); + let body = r.text().await.map_err(|e| Error::Http(e.to_string()))?; + if !(200..300).contains(&status) { + return Err(Error::Api { status, body }); + } + let t: TokenResp = serde_json::from_str(&body).map_err(|e| Error::Decode(e.to_string()))?; + let refresh = t + .refresh_token + .or_else(|| { + form.iter() + .find(|(k, _)| *k == "refresh_token") + .map(|(_, v)| v.to_string()) + }) + .ok_or_else(|| Error::Decode("no refresh_token".into()))?; + Ok(Credential { + account_id: account_id(&t.access_token), + access: t.access_token, + refresh, + // refresh 5 min early + expires: now_ms() + t.expires_in.saturating_mul(1000).saturating_sub(300_000), + }) +} + +pub async fn refresh(k: Kind, cred: &Credential) -> Result { + let mut c = token_req( + k, + &[ + ("grant_type", "refresh_token"), + ("client_id", cfg(k).client_id), + ("refresh_token", &cred.refresh), + ], + ) + .await?; + if c.account_id.is_none() { + c.account_id = cred.account_id.clone(); + } + Ok(c) +} + +/// Accepts a full redirect URL, `code#state`, a query string, or a bare code. +pub fn parse_code(input: &str) -> (Option, Option) { + let v = input.trim(); + let q = v.split_once('?').map(|(_, q)| q).unwrap_or(v); + if q.contains("code=") { + let get = |key: &str| { + q.split(['&', '#']) + .find_map(|kv| kv.strip_prefix(&format!("{key}="))) + .map(|s| { + s.replace("%2B", "+") + .replace("%2F", "/") + .replace("%3D", "=") + }) + }; + return (get("code"), get("state")); + } + match v.split_once('#') { + Some((c, s)) => (Some(c.into()), Some(s.into())), + None if v.is_empty() => (None, None), + None => (Some(v.into()), None), + } +} + +/// Wait for the browser redirect on localhost, or for the user to paste the redirect URL on stdin. +async fn await_code(c: &Oauth) -> Result { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", c.port)) + .await + .ok(); + // Detached std thread: tokio's stdin would block runtime shutdown until a line arrives. + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + std::thread::spawn(move || { + for l in std::io::stdin().lines() { + if tx.send(l).is_err() { + break; + } + } + }); + loop { + tokio::select! { + acc = async { listener.as_ref().unwrap().accept().await }, if listener.is_some() => { + let Ok((mut s, _)) = acc else { continue }; + let mut buf = vec![0u8; 8192]; + let n = s.read(&mut buf).await.unwrap_or(0); + let req = String::from_utf8_lossy(&buf[..n]); + let target = req.split_whitespace().nth(1).unwrap_or(""); + if !target.starts_with(c.path) { let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n").await; continue; } + let _ = s.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\nconnection: close\r\n\r\nhx: login complete, you can close this tab.").await; + return Ok(target.to_string()); + } + line = rx.recv() => match line { + Some(Ok(l)) if !l.trim().is_empty() => return Ok(l), + Some(Ok(_)) => continue, + _ => return Err(Error::Http("login cancelled".into())), + } + } + } +} + +pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String { + let c = cfg(k); + let mut p = vec![ + ("response_type", "code"), + ("client_id", c.client_id), + ("redirect_uri", c.redirect), + ("scope", c.scope), + ("code_challenge", challenge), + ("code_challenge_method", "S256"), + ("state", state), + ]; + match k { + Kind::Claude => p.insert(0, ("code", "true")), + Kind::Codex => p.extend([ + ("id_token_add_organizations", "true"), + ("codex_cli_simplified_flow", "true"), + ("originator", "hx"), + ]), + } + let enc = |s: &str| { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect::() + }; + let qs: Vec = p.iter().map(|(k, v)| format!("{k}={}", enc(v))).collect(); + format!("{}?{}", c.authorize, qs.join("&")) +} + +/// Interactive browser login. Prints the URL to stderr. +pub async fn login(k: Kind) -> Result { + let c = cfg(k); + let (verifier, challenge) = pkce(); + // Claude uses the verifier as state (matches Claude Code); Codex uses a random state. + let state = match k { + Kind::Claude => verifier.clone(), + Kind::Codex => pkce().0, + }; + eprintln!( + "Open this URL to log in:\n\n{}\n\nWaiting for redirect on {} (or paste the final redirect URL / code here):", + authorize_url(k, &challenge, &state), + c.redirect + ); + let (code, got_state) = parse_code(&await_code(c).await?); + if got_state.as_deref().is_some_and(|s| s != state) { + return Err(Error::Http("OAuth state mismatch".into())); + } + let code = code.ok_or_else(|| Error::Http("missing authorization code".into()))?; + let mut form = vec![ + ("grant_type", "authorization_code"), + ("client_id", c.client_id), + ("code", code.as_str()), + ("redirect_uri", c.redirect), + ("code_verifier", verifier.as_str()), + ]; + if k == Kind::Claude { + form.push(("state", state.as_str())); + } + let cred = token_req(k, &form).await?; + if k == Kind::Codex && cred.account_id.is_none() { + return Err(Error::Decode("no chatgpt_account_id in token".into())); + } + save(k, &cred)?; + Ok(cred) +} + +pub fn logout(k: Kind) -> Result<()> { + save_at(&store_path(), k, None) +} + +/// Holds one credential, refreshing it when near expiry. +pub struct Auth { + kind: Kind, + cred: Mutex, +} + +impl Auth { + /// From `~/.hx/auth.json`, else imported from Claude Code / Codex CLI. + pub fn load(kind: Kind) -> Result { + let cred = load_store() + .remove(&kind) + .or_else(|| import(kind)) + .ok_or_else(|| { + Error::Http(format!( + "not logged in to {kind:?}; run `hx login {}`", + format!("{kind:?}").to_lowercase() + )) + })?; + Ok(Self::new(kind, cred)) + } + + pub fn new(kind: Kind, cred: Credential) -> Self { + Self { + kind, + cred: Mutex::new(cred), + } + } + + /// Fresh access token (+ account id for Codex). + pub async fn token(&self) -> Result<(String, Option)> { + let mut c = self.cred.lock().await; + if c.expires <= now_ms() + 60_000 { + *c = refresh(self.kind, &c).await?; + save(self.kind, &c)?; + } + Ok((c.access.clone(), c.account_id.clone())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pkce_shape() { + let (v, c) = pkce(); + assert_eq!(v.len(), 43); + assert_eq!(c.len(), 43); + assert_ne!(v, pkce().0); + } + + #[test] + fn parse_inputs() { + assert_eq!( + parse_code("http://localhost:1455/auth/callback?code=abc&state=xyz"), + (Some("abc".into()), Some("xyz".into())) + ); + assert_eq!( + parse_code("/callback?code=a&state=b"), + (Some("a".into()), Some("b".into())) + ); + assert_eq!( + parse_code("abc#xyz"), + (Some("abc".into()), Some("xyz".into())) + ); + assert_eq!(parse_code(" abc "), (Some("abc".into()), None)); + assert_eq!(parse_code(""), (None, None)); + } + + #[test] + fn jwt_account() { + let p = URL_SAFE_NO_PAD + .encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"acc_1"},"exp":10}"#); + let t = format!("h.{p}.s"); + assert_eq!(account_id(&t).as_deref(), Some("acc_1")); + assert_eq!(jwt_claims(&t).unwrap()["exp"], 10); + assert_eq!(account_id("nope"), None); + } + + #[test] + fn url_has_params() { + let u = authorize_url(Kind::Codex, "CH", "ST"); + assert!(u.starts_with("https://auth.openai.com/oauth/authorize?")); + assert!(u.contains("code_challenge=CH") && u.contains("state=ST")); + assert!(u.contains("redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback")); + let u = authorize_url(Kind::Claude, "CH", "ST"); + assert!(u.contains("code=true") && u.contains("user%3Ainference")); + } + + #[test] + fn store_roundtrip() { + let p = std::env::temp_dir().join(format!("hx-auth-{}/auth.json", now_ms())); + let c = Credential { + access: "a".into(), + refresh: "r".into(), + expires: 1, + account_id: None, + }; + save_at(&p, Kind::Claude, Some(&c)).unwrap(); + assert_eq!(load_at(&p).get(&Kind::Claude), Some(&c)); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + save_at(&p, Kind::Claude, None).unwrap(); + assert!(load_at(&p).is_empty()); + } +} diff --git a/crates/hx-ai/src/codex.rs b/crates/hx-ai/src/codex.rs new file mode 100644 index 0000000..d4b2eed --- /dev/null +++ b/crates/hx-ai/src/codex.rs @@ -0,0 +1,413 @@ +//! OpenAI Responses API via ChatGPT subscription OAuth (Codex backend). + +use crate::auth::{Auth, Kind}; +use crate::{ + ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage, +}; +use eventsource_stream::Eventsource; +use futures::{StreamExt, stream::BoxStream}; +use serde_json::{Value, json}; + +pub struct Codex { + auth: Auth, + base_url: String, + http: reqwest::Client, + /// "none" | "minimal" | "low" | "medium" | "high" + pub reasoning_effort: Option, +} + +impl Codex { + pub fn new(auth: Auth) -> Self { + Self { + auth, + base_url: "https://chatgpt.com/backend-api/codex".into(), + http: reqwest::Client::new(), + reasoning_effort: Some("medium".into()), + } + } + pub fn login_default() -> Result { + Ok(Self::new(Auth::load(Kind::Codex)?)) + } + pub fn with_base_url(mut self, u: impl Into) -> Self { + self.base_url = u.into(); + self + } +} + +/// Tool-call ids are stored as `call_id|item_id` so both survive a round trip. +fn split_id(id: &str) -> (&str, Option<&str>) { + match id.split_once('|') { + Some((c, i)) => (c, Some(i)), + None => (id, None), + } +} + +pub fn body(req: &Request, effort: Option<&str>) -> Value { + let mut input = vec![]; + for m in &req.messages { + for b in &m.content { + let item = match (m.role, b) { + (Role::User, ContentBlock::Text { text }) => { + json!({"role": "user", "content": [{"type": "input_text", "text": text}]}) + } + (Role::User, ContentBlock::Image { media_type, data }) => json!({ + "role": "user", + "content": [{"type": "input_image", "detail": "auto", "image_url": format!("data:{media_type};base64,{data}")}] + }), + ( + _, + ContentBlock::ToolResult { + tool_use_id, + content, + .. + }, + ) => { + json!({"type": "function_call_output", "call_id": split_id(tool_use_id).0, "output": content}) + } + (Role::Assistant, ContentBlock::Text { text }) => json!({ + "type": "message", "role": "assistant", "status": "completed", + "content": [{"type": "output_text", "text": text, "annotations": []}] + }), + // encrypted reasoning item is replayed verbatim (store=false) + ( + Role::Assistant, + ContentBlock::Thinking { + signature: Some(sig), + .. + }, + ) => match serde_json::from_str::(sig) { + Ok(v) if v["type"] == "reasoning" => v, + _ => continue, + }, + (Role::Assistant, ContentBlock::ToolUse { id, name, input }) => { + let (call, item) = split_id(id); + let mut v = json!({"type": "function_call", "call_id": call, "name": name, "arguments": input.to_string()}); + if let Some(i) = item { + v["id"] = i.into(); + } + v + } + _ => continue, + }; + input.push(item); + } + } + let tools: Vec = req + .tools + .iter() + .map(|t| json!({"type": "function", "name": t.name, "description": t.description, "parameters": t.input_schema, "strict": null})) + .collect(); + let mut b = json!({ + "model": req.model, + "store": false, + "stream": true, + "instructions": if req.system.is_empty() { "You are a helpful assistant." } else { &req.system }, + "input": input, + "tools": tools, + "tool_choice": "auto", + "parallel_tool_calls": true, + "text": {"verbosity": "low"}, + "include": ["reasoning.encrypted_content"], + }); + if let Some(e) = effort { + b["reasoning"] = json!({"effort": e, "summary": "auto"}); + } + b +} + +#[derive(Default)] +pub struct Assembler { + /// (output_index, block) — finalized from `output_item.done` + blocks: Vec<(u64, ContentBlock)>, +} + +impl Assembler { + pub fn feed(&mut self, data: &str) -> Result> { + if data.trim() == "[DONE]" { + return Ok(vec![]); + } + let d: Value = + serde_json::from_str(data).map_err(|e| Error::Decode(format!("{e}: {data}")))?; + let s = |v: &Value| v.as_str().unwrap_or_default().to_string(); + let mut out = vec![]; + match d["type"].as_str().unwrap_or_default() { + "response.output_text.delta" | "response.refusal.delta" => { + out.push(StreamEvent::TextDelta { + text: s(&d["delta"]), + }) + } + "response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => { + out.push(StreamEvent::ThinkingDelta { + text: s(&d["delta"]), + }) + } + "response.output_item.added" if d["item"]["type"] == "function_call" => { + out.push(StreamEvent::ToolUseStart { + id: format!("{}|{}", s(&d["item"]["call_id"]), s(&d["item"]["id"])), + name: s(&d["item"]["name"]), + }) + } + "response.output_item.done" => { + let it = &d["item"]; + let idx = d["output_index"] + .as_u64() + .unwrap_or(self.blocks.len() as u64); + let join = |k: &str, f: &str| { + it[k] + .as_array() + .map(|a| a.iter().map(|x| s(&x[f])).collect::>().join("\n\n")) + .unwrap_or_default() + }; + let b = match it["type"].as_str() { + Some("message") => ContentBlock::Text { + text: it["content"] + .as_array() + .map(|a| { + a.iter() + .map(|c| { + s(if c["type"] == "refusal" { + &c["refusal"] + } else { + &c["text"] + }) + }) + .collect() + }) + .unwrap_or_default(), + }, + Some("reasoning") => ContentBlock::Thinking { + thinking: Some(join("summary", "text")) + .filter(|t| !t.is_empty()) + .unwrap_or_else(|| join("content", "text")), + signature: Some(it.to_string()), + }, + Some("function_call") => { + let args = s(&it["arguments"]); + ContentBlock::ToolUse { + id: format!("{}|{}", s(&it["call_id"]), s(&it["id"])), + name: s(&it["name"]), + input: if args.is_empty() { + json!({}) + } else { + serde_json::from_str(&args) + .map_err(|e| Error::Decode(format!("tool args: {e}: {args}")))? + }, + } + } + _ => return Ok(out), + }; + self.blocks.push((idx, b)); + } + t @ ("response.completed" | "response.incomplete" | "response.done") => { + let r = &d["response"]; + let us = &r["usage"]; + let u = |v: &Value| v.as_u64().unwrap_or(0); + let cached = u(&us["input_tokens_details"]["cached_tokens"]); + let usage = Usage { + input_tokens: u(&us["input_tokens"]).saturating_sub(cached), + output_tokens: u(&us["output_tokens"]), + cache_read_tokens: cached, + cache_write_tokens: 0, + }; + self.blocks.sort_by_key(|(i, _)| *i); + let content: Vec = std::mem::take(&mut self.blocks) + .into_iter() + .map(|(_, b)| b) + .collect(); + let stop = if content + .iter() + .any(|b| matches!(b, ContentBlock::ToolUse { .. })) + { + StopReason::ToolUse + } else if t == "response.incomplete" { + match r["incomplete_details"]["reason"].as_str() { + Some("max_output_tokens") => StopReason::MaxTokens, + _ => StopReason::Other, + } + } else { + StopReason::EndTurn + }; + out.push(StreamEvent::Done { + message: Message { + role: Role::Assistant, + content, + }, + stop, + usage, + }); + } + "response.failed" | "error" => { + let e = if d["response"]["error"].is_null() { + &d + } else { + &d["response"]["error"] + }; + return Err(Error::Api { + status: 0, + body: e.to_string(), + }); + } + _ => {} + } + Ok(out) + } +} + +#[async_trait::async_trait] +impl Provider for Codex { + async fn stream(&self, req: Request) -> Result>> { + let (token, account) = self.auth.token().await?; + let account = account.ok_or_else(|| { + Error::Http("codex credential has no account id; run `hx login codex`".into()) + })?; + let r = self + .http + .post(format!("{}/responses", self.base_url)) + .bearer_auth(token) + .header("chatgpt-account-id", account) + .header("originator", "hx") + .header("OpenAI-Beta", "responses=experimental") + .header("accept", "text/event-stream") + .header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION"))) + .json(&body(&req, self.reasoning_effort.as_deref())) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))?; + let status = r.status().as_u16(); + if !(200..300).contains(&status) { + let body = r.text().await.unwrap_or_default(); + return Err(Error::Api { status, body }); + } + let s = r + .bytes_stream() + .eventsource() + .scan(Assembler::default(), |a, ev| { + let out = match ev { + Ok(ev) => match a.feed(&ev.data) { + Ok(v) => v.into_iter().map(Ok).collect(), + Err(e) => vec![Err(e)], + }, + Err(e) => vec![Err(Error::Http(e.to_string()))], + }; + futures::future::ready(Some(futures::stream::iter(out))) + }) + .flatten(); + Ok(s.boxed()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ToolSpec; + + #[test] + fn assemble_and_replay() { + let fixture = [ + r#"{"type":"response.created","response":{"id":"r1"}}"#, + r#"{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}"#, + r#"{"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"think"}"#, + r#"{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"think"}],"encrypted_content":"ENC"}}"#, + r#"{"type":"response.output_item.added","output_index":1,"item":{"type":"message","id":"msg_1"}}"#, + r#"{"type":"response.output_text.delta","output_index":1,"delta":"Hi"}"#, + r#"{"type":"response.output_item.done","output_index":1,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"Hi"}]}}"#, + r#"{"type":"response.output_item.added","output_index":2,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}"#, + r#"{"type":"response.function_call_arguments.delta","output_index":2,"delta":"{\"path\":\"a\"}"}"#, + r#"{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\"path\":\"a\"}"}}"#, + r#"{"type":"response.completed","response":{"usage":{"input_tokens":100,"input_tokens_details":{"cached_tokens":40},"output_tokens":7}}}"#, + ]; + let mut a = Assembler::default(); + let evs: Vec = fixture.iter().flat_map(|l| a.feed(l).unwrap()).collect(); + assert_eq!( + evs[0], + StreamEvent::ThinkingDelta { + text: "think".into() + } + ); + assert_eq!(evs[1], StreamEvent::TextDelta { text: "Hi".into() }); + assert_eq!( + evs[2], + StreamEvent::ToolUseStart { + id: "call_1|fc_1".into(), + name: "read".into() + } + ); + let StreamEvent::Done { + message, + stop, + usage, + } = evs.last().unwrap().clone() + else { + panic!() + }; + assert_eq!(stop, StopReason::ToolUse); + assert_eq!( + ( + usage.input_tokens, + usage.cache_read_tokens, + usage.output_tokens + ), + (60, 40, 7) + ); + assert_eq!(message.text(), "Hi"); + assert_eq!( + message.content[2], + ContentBlock::ToolUse { + id: "call_1|fc_1".into(), + name: "read".into(), + input: json!({"path": "a"}) + } + ); + + // replay the turn plus a tool result + let req = Request { + model: "gpt-5-codex".into(), + system: "sys".into(), + messages: vec![ + Message::user("go"), + message, + Message { + role: Role::User, + content: vec![ContentBlock::ToolResult { + tool_use_id: "call_1|fc_1".into(), + content: "data".into(), + is_error: false, + }], + }, + ], + tools: vec![ToolSpec { + name: "read".into(), + description: "r".into(), + input_schema: json!({"type":"object"}), + }], + max_tokens: 100, + }; + let b = body(&req, Some("low")); + let inp = b["input"].as_array().unwrap(); + assert_eq!(inp[0]["content"][0]["type"], "input_text"); + assert_eq!(inp[1]["type"], "reasoning"); + assert_eq!(inp[1]["encrypted_content"], "ENC"); + assert_eq!(inp[2]["content"][0]["text"], "Hi"); + assert_eq!(inp[3]["type"], "function_call"); + assert_eq!( + (inp[3]["call_id"].as_str(), inp[3]["id"].as_str()), + (Some("call_1"), Some("fc_1")) + ); + assert_eq!(inp[3]["arguments"], r#"{"path":"a"}"#); + assert_eq!( + inp[4], + json!({"type":"function_call_output","call_id":"call_1","output":"data"}) + ); + assert_eq!(b["store"], false); + assert_eq!(b["instructions"], "sys"); + assert_eq!(b["reasoning"]["effort"], "low"); + assert_eq!(b["tools"][0]["name"], "read"); + } + + #[test] + fn failed() { + let e = Assembler::default() + .feed(r#"{"type":"response.failed","response":{"error":{"code":"rate_limit"}}}"#); + assert!(matches!(e, Err(Error::Api { body, .. }) if body.contains("rate_limit"))); + } +} diff --git a/crates/hx-ai/src/lib.rs b/crates/hx-ai/src/lib.rs index 6095f34..1335dfa 100644 --- a/crates/hx-ai/src/lib.rs +++ b/crates/hx-ai/src/lib.rs @@ -1,5 +1,9 @@ //! Provider-agnostic LLM types and the `Provider` trait. +pub mod anthropic; +pub mod auth; +pub mod codex; + use futures::stream::BoxStream; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 8d68191..cba1a03 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -9,6 +9,11 @@ name = "hx" path = "src/main.rs" [dependencies] +anyhow = "1.0.104" +clap = { version = "4.6.7", features = ["derive", "env"] } +futures = "0.3.34" +hx-ai = { version = "0.1.0", path = "../hx-ai" } +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] } [lints] workspace = true diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index e7a11a9..67dac4e 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -1,3 +1,90 @@ -fn main() { - println!("Hello, world!"); +use anyhow::Result; +use clap::{Parser, Subcommand}; +use futures::StreamExt; +use hx_ai::auth::{self, Kind}; +use hx_ai::{Message, Provider, Request, StreamEvent, anthropic::Anthropic, codex::Codex}; +use std::io::Write; + +#[derive(Parser)] +#[command(name = "hx", version, about = "Minimal coding agent")] +struct Cli { + #[command(subcommand)] + cmd: Option, + /// Print mode: send one prompt, stream the reply to stdout, exit. + #[arg(short, long)] + print: Option, + /// claude | codex + #[arg(long, env = "HX_PROVIDER", default_value = "claude")] + provider: Kind, + #[arg(short, long, env = "HX_MODEL")] + model: Option, +} + +#[derive(Subcommand)] +enum Cmd { + /// Log in with a Claude Pro/Max or ChatGPT Plus/Pro subscription. + Login { provider: Kind }, + /// Remove stored credentials for a provider. + Logout { provider: Kind }, +} + +fn default_model(k: Kind) -> &'static str { + match k { + Kind::Claude => "claude-sonnet-4-5", + Kind::Codex => "gpt-5-codex", + } +} + +fn provider(k: Kind) -> hx_ai::Result> { + Ok(match k { + Kind::Claude => Box::new(Anthropic::login_default()?), + Kind::Codex => Box::new(Codex::login_default()?), + }) +} + +#[tokio::main] +async fn main() -> Result<()> { + let cli = Cli::parse(); + match cli.cmd { + Some(Cmd::Login { provider }) => { + auth::login(provider).await?; + eprintln!("logged in; credentials in {}", auth::store_path().display()); + return Ok(()); + } + Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?), + None => {} + } + let Some(prompt) = cli.print else { + anyhow::bail!("interactive mode not implemented yet; use -p \"prompt\""); + }; + let p = provider(cli.provider)?; + let req = Request { + model: cli + .model + .unwrap_or_else(|| default_model(cli.provider).into()), + system: String::new(), + messages: vec![Message::user(prompt)], + tools: vec![], + max_tokens: 8192, + }; + let mut s = p.stream(req).await?; + let mut out = std::io::stdout().lock(); + while let Some(ev) = s.next().await { + match ev? { + StreamEvent::TextDelta { text } => { + out.write_all(text.as_bytes())?; + out.flush()?; + } + StreamEvent::Done { usage, .. } => { + writeln!(out)?; + eprintln!( + "[{} in / {} out tokens]", + usage.input_tokens + usage.cache_read_tokens, + usage.output_tokens + ); + } + _ => {} + } + } + Ok(()) }