562 lines
22 KiB
Rust
562 lines
22 KiB
Rust
//! 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,
|
|
}
|
|
|
|
impl Codex {
|
|
pub fn new(auth: Auth) -> Self {
|
|
Self {
|
|
auth,
|
|
base_url: "https://chatgpt.com/backend-api/codex".into(),
|
|
http: reqwest::Client::new(),
|
|
}
|
|
}
|
|
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) -> 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"],
|
|
});
|
|
// Off has no Codex equivalent (see Effort::levels); send the lowest level instead
|
|
let e = match req.effort {
|
|
crate::Effort::Off | crate::Effort::Low => "low",
|
|
e => e.name(),
|
|
};
|
|
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)
|
|
}
|
|
}
|
|
|
|
/// ChatGPT subscription limits from `x-codex-*` headers: primary/secondary windows (used %,
|
|
/// window length in minutes, reset as unix seconds) and the credit balance.
|
|
pub fn quota(h: &reqwest::header::HeaderMap) -> Option<crate::Quota> {
|
|
use crate::hdr;
|
|
let mut q = crate::Quota::default();
|
|
for w in ["primary", "secondary"] {
|
|
let Some(used) = hdr(h, &format!("x-codex-{w}-used-percent")).and_then(|v| v.parse().ok())
|
|
else {
|
|
continue;
|
|
};
|
|
let mins: Option<u64> =
|
|
hdr(h, &format!("x-codex-{w}-window-minutes")).and_then(|v| v.parse().ok());
|
|
q.windows.push(crate::QuotaWindow {
|
|
label: match mins {
|
|
Some(m) if m >= 10_080 => "week".into(),
|
|
Some(m) if m >= 1440 => format!("{}d", m / 1440),
|
|
Some(m) if m >= 60 => format!("{}h", m / 60),
|
|
Some(m) => format!("{m}m"),
|
|
None => w.into(),
|
|
},
|
|
used_pct: used,
|
|
resets_at: hdr(h, &format!("x-codex-{w}-reset-at")).and_then(|v| v.parse().ok()),
|
|
});
|
|
}
|
|
let yes = |k: &str| hdr(h, k).is_some_and(|v| v.eq_ignore_ascii_case("true"));
|
|
q.credits = if yes("x-codex-credits-unlimited") {
|
|
Some("credits: unlimited".into())
|
|
} else if hdr(h, "x-codex-credits-has-credits").is_some() {
|
|
Some(match hdr(h, "x-codex-credits-balance") {
|
|
Some(b) => format!("credits: {b}"),
|
|
None if yes("x-codex-credits-has-credits") => "credits: available".into(),
|
|
None => "credits: none".into(),
|
|
})
|
|
} else {
|
|
None
|
|
};
|
|
(!q.windows.is_empty() || q.credits.is_some()).then_some(q)
|
|
}
|
|
|
|
/// The server hides models whose `minimal_client_version` exceeds ours, so claim a high one
|
|
/// (override: `HX_CODEX_CLIENT_VERSION`). ponytail: we only list ids; the server still gates use.
|
|
fn client_version() -> String {
|
|
std::env::var("HX_CODEX_CLIENT_VERSION").unwrap_or_else(|_| "99.0.0".into())
|
|
}
|
|
|
|
/// `GET {base}/models` body (Codex backend) to catalog entries, by the server's priority.
|
|
pub fn parse_models(v: &Value) -> Vec<crate::models::ModelInfo> {
|
|
let mut v: Vec<(i64, crate::models::ModelInfo)> = v["models"]
|
|
.as_array()
|
|
.into_iter()
|
|
.flatten()
|
|
.filter(|m| {
|
|
m["visibility"].as_str() != Some("hide")
|
|
&& m["supported_in_api"].as_bool() != Some(false)
|
|
})
|
|
.filter_map(|m| {
|
|
let id = m["slug"].as_str()?;
|
|
Some((
|
|
m["priority"].as_i64().unwrap_or(i64::MAX),
|
|
crate::models::ModelInfo {
|
|
id: id.into(),
|
|
kind: Kind::Codex,
|
|
context_window: m["context_window"]
|
|
.as_u64()
|
|
.unwrap_or_else(|| crate::models::window(&[], id)),
|
|
},
|
|
))
|
|
})
|
|
.collect();
|
|
v.sort_by_key(|(p, _)| *p);
|
|
v.into_iter().map(|(_, m)| m).collect()
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl Provider for Codex {
|
|
async fn models(&self) -> Result<Vec<crate::models::ModelInfo>> {
|
|
let (token, account) = self.auth.token().await?;
|
|
let mut r = self
|
|
.http
|
|
.get(format!(
|
|
"{}/models?client_version={}",
|
|
self.base_url,
|
|
client_version()
|
|
))
|
|
.bearer_auth(token)
|
|
.header("originator", "hx");
|
|
if let Some(a) = account {
|
|
r = r.header("chatgpt-account-id", a);
|
|
}
|
|
let v: Value = r
|
|
.send()
|
|
.await
|
|
.map_err(|e| Error::Http(e.to_string()))?
|
|
.error_for_status()
|
|
.map_err(|e| Error::Http(e.to_string()))?
|
|
.json()
|
|
.await
|
|
.map_err(|e| Error::Decode(e.to_string()))?;
|
|
Ok(parse_models(&v))
|
|
}
|
|
|
|
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))
|
|
.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 q = quota(r.headers());
|
|
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(crate::with_quota(q, s.boxed()))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn quota_and_models() {
|
|
let mut h = reqwest::header::HeaderMap::new();
|
|
for (k, v) in [
|
|
("x-codex-primary-used-percent", "12.5"),
|
|
("x-codex-primary-window-minutes", "300"),
|
|
("x-codex-primary-reset-at", "1790850000"),
|
|
("x-codex-secondary-used-percent", "40"),
|
|
("x-codex-secondary-window-minutes", "10080"),
|
|
("x-codex-credits-has-credits", "true"),
|
|
("x-codex-credits-unlimited", "false"),
|
|
("x-codex-credits-balance", "37.5"),
|
|
] {
|
|
h.insert(k, v.parse().unwrap());
|
|
}
|
|
let q = quota(&h).unwrap();
|
|
let w: Vec<_> = q
|
|
.windows
|
|
.iter()
|
|
.map(|w| (w.label.as_str(), w.used_pct, w.resets_at))
|
|
.collect();
|
|
assert_eq!(w, [("5h", 12.5, Some(1_790_850_000)), ("week", 40.0, None)]);
|
|
assert_eq!(q.credits.as_deref(), Some("credits: 37.5"));
|
|
|
|
let m = parse_models(&json!({"models": [
|
|
{"slug": "gpt-5.6-terra", "priority": 2, "context_window": 272000},
|
|
{"slug": "gpt-6-astra", "priority": 1, "context_window": 272000},
|
|
{"slug": "hidden", "priority": 0, "visibility": "hide"},
|
|
{"slug": "gpt-6-nolist", "priority": 3, "visibility": "none", "context_window": 272000},
|
|
{"slug": "no-vis", "priority": 4, "context_window": 272000},
|
|
{"slug": "no-api", "priority": 5, "supported_in_api": false}
|
|
]}));
|
|
let ids: Vec<_> = m
|
|
.iter()
|
|
.map(|m| (m.id.as_str(), m.context_window))
|
|
.collect();
|
|
assert_eq!(
|
|
ids,
|
|
[
|
|
("gpt-6-astra", 272_000),
|
|
("gpt-5.6-terra", 272_000),
|
|
("gpt-6-nolist", 272_000),
|
|
("no-vis", 272_000)
|
|
]
|
|
);
|
|
}
|
|
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,
|
|
effort: crate::Effort::Low,
|
|
};
|
|
let b = body(&req);
|
|
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")));
|
|
}
|
|
}
|