- 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
@@ -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")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user