ai: claude_cli provider (official claude binary, subscription billing)

This commit is contained in:
hermes committed 2026-10-16 20:09:32 +00:00
1 parent bd9671804b
commit 769effc8b0
7 files changed
+293 -1

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ 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"] }
tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros", "time", "net", "io-util", "sync", "process"] }
[lints]
workspace = true
+244
View File
@@ -0,0 +1,244 @@
//! Claude via the real `claude` CLI (`claude -p --output-format stream-json`).
//!
//! Anthropic bills OAuth traffic from third-party apps as "extra usage"; the official binary keeps
//! using the subscription. `claude` runs its own agent loop (tools included), hx only displays the
//! stream. ponytail: one `claude` process per hx turn, continued with `--resume`; add a long-lived
//! `--input-format stream-json` process if startup latency hurts.
use crate::{
ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage,
};
use futures::StreamExt;
use futures::stream::BoxStream;
use serde_json::{Value, json};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufReadExt, BufReader};
pub struct ClaudeCli {
bin: String,
/// extra args, e.g. `["--permission-mode", "acceptEdits"]`
args: Vec<String>,
/// `hx mcp-serve` entry (command, args) offered to claude as MCP server "hx"
mcp: Option<(String, Vec<String>)>,
session: Arc<Mutex<Option<String>>>,
}
impl ClaudeCli {
pub fn new(args: Vec<String>) -> Self {
Self {
bin: std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()),
args,
mcp: None,
session: Default::default(),
}
}
pub fn with_mcp(mut self, command: String, args: Vec<String>) -> Self {
self.mcp = Some((command, args));
self
}
/// Whether the binary can be started at all.
pub fn available() -> bool {
let bin = std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into());
std::process::Command::new(bin)
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
}
/// Prompt for this turn. Fresh `claude` session: replay earlier text so a resumed hx session keeps context.
fn prompt(msgs: &[Message], resumed: bool) -> String {
let last = msgs
.iter()
.rposition(|m| m.role == Role::User && !m.text().is_empty());
let Some(last) = last else {
return String::new();
};
if resumed || last == 0 {
return msgs[last].text();
}
let mut s = String::from("Conversation so far:\n");
for m in &msgs[..last] {
let t = m.text();
if !t.is_empty() {
let who = if m.role == Role::User {
"User"
} else {
"Assistant"
};
s += &format!("{who}: {t}\n");
}
}
s + "\nCurrent request:\n" + &msgs[last].text()
}
fn usage(u: &Value) -> Usage {
let n = |k: &str| u[k].as_u64().unwrap_or(0);
Usage {
input_tokens: n("input_tokens"),
output_tokens: n("output_tokens"),
cache_read_tokens: n("cache_read_input_tokens"),
cache_write_tokens: n("cache_creation_input_tokens"),
}
}
#[async_trait::async_trait]
impl Provider for ClaudeCli {
async fn models(&self) -> Result<Vec<crate::models::ModelInfo>> {
Ok(crate::models::fallback(crate::auth::Kind::Claude))
}
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>> {
let sid = self.session.lock().ok().and_then(|s| s.clone());
let mut cmd = tokio::process::Command::new(&self.bin);
cmd.args([
"-p",
"--output-format",
"stream-json",
"--verbose",
"--include-partial-messages",
"--model",
&req.model,
]);
if let Some(s) = &sid {
cmd.args(["--resume", s]);
}
if !req.system.is_empty() {
cmd.args(["--append-system-prompt", &req.system]);
}
if let Some((c, a)) = &self.mcp {
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a}}});
cmd.args(["--mcp-config", &cfg.to_string()]);
}
cmd.args(&self.args)
.arg("--")
.arg(prompt(&req.messages, sid.is_some()))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| {
Error::Http(format!(
"cannot start {:?}: {e} (is claude installed?)",
self.bin
))
})?;
let out = child.stdout.take().expect("piped");
let mut err = child.stderr.take().expect("piped");
let session = self.session.clone();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<StreamEvent>>();
tokio::spawn(async move {
let _child = child; // dropped (killed) when the consumer goes away
let mut lines = BufReader::new(out).lines();
let (mut text, mut think) = (String::new(), String::new());
let mut done = false;
while let Ok(Some(l)) = lines.next_line().await {
let Ok(v) = serde_json::from_str::<Value>(&l) else {
continue;
};
if let (Some(s), Ok(mut g)) = (v["session_id"].as_str(), session.lock()) {
*g = Some(s.into());
}
match v["type"].as_str() {
Some("stream_event") => {
let e = &v["event"];
match e["type"].as_str() {
Some("content_block_delta") => match e["delta"]["type"].as_str() {
Some("text_delta") => {
let t = e["delta"]["text"].as_str().unwrap_or_default();
text += t;
let _ = tx.send(Ok(StreamEvent::TextDelta { text: t.into() }));
}
Some("thinking_delta") => {
let t = e["delta"]["thinking"].as_str().unwrap_or_default();
think += t;
let _ =
tx.send(Ok(StreamEvent::ThinkingDelta { text: t.into() }));
}
_ => {}
},
// claude runs its tools itself; show them, don't hand them to hx
Some("content_block_start")
if e["content_block"]["type"] == "tool_use" =>
{
let n = e["content_block"]["name"].as_str().unwrap_or("tool");
let _ = tx.send(Ok(StreamEvent::TextDelta {
text: format!("\n[claude tool: {n}]\n"),
}));
}
_ => {}
}
}
Some("result") => {
done = true;
if v["is_error"].as_bool().unwrap_or(false) {
let body = v["result"].as_str().unwrap_or("claude failed").to_string();
let _ = tx.send(Err(Error::Api { status: 0, body }));
break;
}
if text.is_empty() && think.is_empty() {
text = v["result"].as_str().unwrap_or_default().into();
}
let mut content = vec![];
if !think.is_empty() {
content.push(ContentBlock::Thinking {
thinking: std::mem::take(&mut think),
signature: None,
});
}
content.push(ContentBlock::Text {
text: std::mem::take(&mut text),
});
let _ = tx.send(Ok(StreamEvent::Done {
message: Message {
role: Role::Assistant,
content,
},
stop: StopReason::EndTurn,
usage: usage(&v["usage"]),
}));
break;
}
_ => {}
}
}
if !done {
let mut e = String::new();
let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await;
let _ = tx.send(Err(Error::Http(format!(
"claude exited without result: {}",
e.trim()
))));
}
});
Ok(
futures::stream::unfold(rx, |mut rx| async move { rx.recv().await.map(|x| (x, rx)) })
.boxed(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prompt_replays_history_only_on_fresh_session() {
let m = vec![
Message::user("a"),
Message {
role: Role::Assistant,
content: vec![ContentBlock::Text { text: "b".into() }],
},
Message::user("c"),
];
assert_eq!(prompt(&m, true), "c");
let p = prompt(&m, false);
assert!(p.contains("User: a") && p.contains("Assistant: b") && p.ends_with("c"));
assert_eq!(prompt(&m[..1], false), "a");
}
}
+1
View File
@@ -2,6 +2,7 @@
pub mod anthropic;
pub mod auth;
pub mod claude_cli;
pub mod codex;
pub mod models;
pub mod openai_compat;
+17
View File
@@ -117,6 +117,8 @@ struct Config {
provider: Option<Kind>,
model: Option<String>,
claude_model: Option<String>,
/// Run Claude through the official `claude` CLI (subscription billing). Value = extra `claude` args, `[]` for none.
claude_cli: Option<Vec<String>>,
/// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom".
openai_compat: Option<hx_ai::openai_compat::Config>,
codex_model: Option<String>,
@@ -193,6 +195,7 @@ impl Config {
provider: o.provider.or(c.provider),
model: o.model.or(c.model),
claude_model: o.claude_model.or(c.claude_model),
claude_cli: o.claude_cli.or(c.claude_cli),
openai_compat: o.openai_compat.or(c.openai_compat),
codex_model: o.codex_model.or(c.codex_model),
compact_at: o.compact_at.or(c.compact_at),
@@ -258,6 +261,7 @@ fn logged_in() -> Vec<Kind> {
.into_iter()
.filter(|k| match k {
Kind::Custom => COMPAT.get().is_some(),
Kind::Claude if CLAUDE_CLI.get().is_some() => true,
k => hx_ai::auth::Auth::load(*k).is_ok(),
})
.collect()
@@ -346,9 +350,19 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
/// `[openai_compat]` from config, set once at startup.
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
/// `claude_cli` from config: extra args for the `claude` binary.
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
Ok(match k {
Kind::Claude if CLAUDE_CLI.get().is_some() => {
let c =
hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default());
Arc::new(match std::env::current_exe() {
Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()]),
Err(_) => c,
})
}
Kind::Claude => {
let a = Anthropic::login_default()?;
Arc::new(match std::env::var("HX_BASE_URL") {
@@ -615,6 +629,9 @@ async fn main() -> Result<()> {
if let Some(oc) = cfg.openai_compat.clone() {
let _ = COMPAT.set(oc);
}
if let Some(a) = cfg.claude_cli.clone() {
let _ = CLAUDE_CLI.set(a);
}
// MCP servers connect while the model catalog loads
let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
let mcp = hx_mcp::Hub::spawn(mcp_cfg);