- 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 <claude|codex>, hx -p Closes #3, closes #4, closes #5
This commit is contained in:
1 parent
e16e33ed2d
commit
da9d5d1ae0
9 files changed
+3101
-6
No files matched your search
Generated
+1684
-4
File diff suppressed because it is too large.
Load diff
@@ -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.
|
||||
@@ -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"] }
|
||||
@@ -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<Self> {
|
||||
Ok(Self::new(Auth::load(Kind::Claude)?))
|
||||
}
|
||||
pub fn with_base_url(mut self, u: impl Into<String>) -> 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<Value> = req
|
||||
.messages
|
||||
.iter()
|
||||
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
|
||||
.collect();
|
||||
let tools: Vec<Value> = 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<ContentBlock>,
|
||||
/// partial JSON for tool_use input, per block index
|
||||
partial: Vec<String>,
|
||||
usage: Usage,
|
||||
stop: Option<StopReason>,
|
||||
}
|
||||
|
||||
impl Assembler {
|
||||
pub fn feed(&mut self, event: &str, data: &str, req: &Request) -> Result<Vec<StreamEvent>> {
|
||||
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<BoxStream<'static, Result<StreamEvent>>> {
|
||||
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 { .. })));
|
||||
}
|
||||
}
|
||||
@@ -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<Self, String> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<Kind, Credential>;
|
||||
|
||||
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<Credential> {
|
||||
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<Value> {
|
||||
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<String> {
|
||||
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<String>,
|
||||
expires_in: u64,
|
||||
}
|
||||
|
||||
async fn token_req(k: Kind, form: &[(&str, &str)]) -> Result<Credential> {
|
||||
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::<BTreeMap<_, _>>()),
|
||||
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<Credential> {
|
||||
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<String>, Option<String>) {
|
||||
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<String> {
|
||||
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::<String>()
|
||||
};
|
||||
let qs: Vec<String> = 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<Credential> {
|
||||
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<Credential>,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// From `~/.hx/auth.json`, else imported from Claude Code / Codex CLI.
|
||||
pub fn load(kind: Kind) -> Result<Self> {
|
||||
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<String>)> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<Self> {
|
||||
Ok(Self::new(Auth::load(Kind::Codex)?))
|
||||
}
|
||||
pub fn with_base_url(mut self, u: impl Into<String>) -> 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::<Value>(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<Value> = 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<Vec<StreamEvent>> {
|
||||
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::<Vec<_>>().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<ContentBlock> = 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<BoxStream<'static, Result<StreamEvent>>> {
|
||||
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<StreamEvent> = 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")));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -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<Cmd>,
|
||||
/// Print mode: send one prompt, stream the reply to stdout, exit.
|
||||
#[arg(short, long)]
|
||||
print: Option<String>,
|
||||
/// claude | codex
|
||||
#[arg(long, env = "HX_PROVIDER", default_value = "claude")]
|
||||
provider: Kind,
|
||||
#[arg(short, long, env = "HX_MODEL")]
|
||||
model: Option<String>,
|
||||
}
|
||||
|
||||
#[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<Box<dyn Provider>> {
|
||||
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(())
|
||||
}
|
||||
Reference in new issue
Block a user