Files
hx/crates/hx-ai/src/claude_cli.rs
T

451 lines
18 KiB
Rust

//! 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, Quota, QuotaWindow, 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};
/// Builds the `claude` command (lets the caller wrap it in a sandbox).
pub type Spawner = Arc<
dyn Fn(
String,
)
-> std::pin::Pin<Box<dyn std::future::Future<Output = tokio::process::Command> + Send>>
+ Send
+ Sync,
>;
/// hx plan mode is on: claude runs with `--permission-mode plan`, else its `ExitPlanMode` is rejected.
// ponytail: process-wide flag; make it per-provider if two claude providers ever run at once.
static PLAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn set_plan(on: bool) {
PLAN.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub struct ClaudeCli {
spawner: Option<Spawner>,
bin: String,
/// extra args, e.g. `["--permission-mode", "acceptEdits"]`
args: Vec<String>,
/// `hx mcp-serve` entry (command, args, env) offered to claude as MCP server "hx"
mcp: Option<(String, Vec<String>, Value)>,
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,
spawner: None,
session: Default::default(),
}
}
/// `env` also carries the permission socket: claude then asks hx (`mcp__hx__approve`) before tools run.
pub fn with_spawner(mut self, f: Spawner) -> Self {
self.spawner = Some(f);
self
}
pub fn with_mcp(mut self, command: String, args: Vec<String>, env: Value) -> Self {
self.mcp = Some((command, args, env));
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()
}
/// `Bash: cargo test`, `Edit: src/a.rs`; other tools show their input, shortened.
fn tool_line(b: &Value) -> String {
let name = b["name"].as_str().unwrap_or("tool");
let i = &b["input"];
let d = [
"command",
"file_path",
"notebook_path",
"pattern",
"url",
"query",
"description",
]
.iter()
.find_map(|k| i[*k].as_str().map(String::from))
.unwrap_or_else(|| i.to_string());
let d: String = d.chars().take(300).collect();
format!("{name}: {d}")
}
/// Tool result content: a string or a list of `{type: "text", text}` blocks.
fn result_text(c: &Value) -> String {
match c.as_array() {
Some(a) => a
.iter()
.filter_map(|b| b["text"].as_str())
.collect::<Vec<_>>()
.join("\n"),
None => c.as_str().unwrap_or_default().to_string(),
}
}
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"),
}
}
/// `rate_limit_event` -> window. claude reports `utilization` (0..1) when known, else only a
/// status; `surpassedThreshold` is the best percent then. ponytail: no percent -> no window.
fn window(v: &Value) -> Option<QuotaWindow> {
let i = &v["rate_limit_info"];
let label = match i["rateLimitType"].as_str()? {
"five_hour" => "5h".to_string(),
"seven_day" => "7d".into(),
"seven_day_opus" => "7d opus".into(),
"seven_day_sonnet" => "7d sonnet".into(),
o => o.replace('_', " "),
};
let used_pct = match (i["utilization"].as_f64(), i["surpassedThreshold"].as_f64()) {
(Some(u), _) => u * 100.0,
_ if i["status"] == "rejected" => 100.0,
(_, Some(t)) => t * 100.0,
_ => return None,
};
Some(QuotaWindow {
label,
used_pct,
resets_at: i["resetsAt"].as_u64(),
})
}
#[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 = match &self.spawner {
Some(f) => f(self.bin.clone()).await,
None => tokio::process::Command::new(&self.bin),
};
cmd.args([
"-p",
"--output-format",
"stream-json",
"--verbose",
"--include-partial-messages",
// print mode defaults to display "omitted" (empty thinking text) on new models
// ponytail: hidden flag; an older claude that rejects it needs a version probe
"--thinking-display",
"summarized",
"--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, env)) = &self.mcp {
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
cmd.args(["--mcp-config", &cfg.to_string()]);
if !env.is_null() {
// reads in the project run without a prompt by default; "ask" sends them to hx too
// ponytail: unverified against a real claude (not installed on the dev box)
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
cmd.args([
"--settings",
r#"{"permissions":{"ask":["Bash","Read","Grep","Glob","LS"]}}"#,
]);
}
}
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
cmd.args(["--permission-mode", "plan"]);
}
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;
// usage of the last API request: the real context size (`result` sums all requests)
let mut last: Option<Value> = None;
let mut quota = Quota::default();
// tool_use blocks by id, completed by the `user` message carrying the result
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
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"];
if e["type"] == "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();
// omitted thinking: claude sends empty deltas (signature only)
if t.trim().is_empty() {
continue;
}
think += t;
let _ =
tx.send(Ok(StreamEvent::ThinkingDelta { text: t.into() }));
}
_ => {}
}
}
}
// complete tool calls (the stream events only carry partial JSON)
Some("assistant") => {
if v["message"]["usage"].is_object() {
last = Some(v["message"]["usage"].clone());
}
for b in v["message"]["content"].as_array().into_iter().flatten() {
if b["type"] == "tool_use" {
uses.insert(
b["id"].as_str().unwrap_or_default().into(),
(
b["name"].as_str().unwrap_or("tool").into(),
b["input"].clone(),
),
);
let _ = tx.send(Ok(StreamEvent::TextDelta {
text: format!("\n[claude {}]\n", tool_line(b)),
}));
}
}
}
Some("user") => {
for b in v["message"]["content"].as_array().into_iter().flatten() {
let id = b["tool_use_id"].as_str().unwrap_or_default();
if b["type"] != "tool_result" {
continue;
}
let Some((name, input)) = uses.remove(id) else {
continue;
};
let _ = tx.send(Ok(StreamEvent::ToolRun {
id: id.into(),
name,
input,
content: result_text(&b["content"]),
is_error: b["is_error"].as_bool().unwrap_or(false),
}));
}
}
Some("rate_limit_event") => {
if let Some(w) = window(&v) {
quota.windows.retain(|x| x.label != w.label);
quota.windows.push(w);
let _ = tx.send(Ok(StreamEvent::Quota(quota.clone())));
}
}
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,
// ponytail: billing/stats see the last request only; split Done if exact sums matter
usage: usage(last.as_ref().unwrap_or(&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 tool_line_shows_what_runs() {
let b = json!({"name": "Bash", "input": {"command": "cargo test", "description": "run"}});
assert_eq!(tool_line(&b), "Bash: cargo test");
let b = json!({"name": "Edit", "input": {"file_path": "a.rs", "old_string": "x"}});
assert_eq!(tool_line(&b), "Edit: a.rs");
let b = json!({"name": "X", "input": {"a": 1}});
assert_eq!(tool_line(&b), "X: {\"a\":1}");
}
#[test]
fn rate_limit_event_maps_to_window() {
let w = |i: Value| window(&json!({"rate_limit_info": i}));
let a =
w(json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 99})).unwrap();
assert_eq!(
(a.label.as_str(), a.used_pct.round(), a.resets_at),
("5h", 42.0, Some(99))
);
let b = w(json!({"rateLimitType": "seven_day", "status": "rejected"})).unwrap();
assert_eq!(b.used_pct, 100.0);
let c = w(json!({"rateLimitType": "seven_day", "status": "allowed_warning", "surpassedThreshold": 0.75})).unwrap();
assert_eq!(c.used_pct, 75.0);
assert!(w(json!({"rateLimitType": "five_hour", "status": "allowed"})).is_none());
}
#[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");
}
#[tokio::test]
async fn done_usage_is_last_request_not_the_sum() {
use futures::StreamExt;
let out = [
r#"{"type":"assistant","message":{"content":[],"usage":{"input_tokens":1,"cache_read_input_tokens":90000,"output_tokens":5}}}"#,
r#"{"type":"assistant","message":{"content":[],"usage":{"input_tokens":1,"cache_read_input_tokens":91000,"output_tokens":7}}}"#,
r#"{"type":"result","result":"ok","usage":{"input_tokens":2,"cache_read_input_tokens":181000,"output_tokens":12}}"#,
]
.join("\n");
let p = ClaudeCli::new(vec![]).with_spawner(Arc::new(move |_| {
let o = out.clone();
Box::pin(async move {
let mut c = tokio::process::Command::new("sh");
c.args(["-c", &format!("printf '%s\\n' '{o}'"), "sh"]);
c
})
}));
let req = Request {
model: "m".into(),
system: String::new(),
messages: vec![Message::user("hi")],
tools: vec![],
max_tokens: 100,
effort: crate::Effort::levels(crate::auth::Kind::Claude)[0],
};
let evs: Vec<_> = p.stream(req).await.unwrap().collect().await;
let Some(Ok(StreamEvent::Done { usage, .. })) = evs.last() else {
panic!("{evs:?}")
};
assert_eq!(usage.cache_read_tokens, 91_000);
assert_eq!(usage.output_tokens, 7);
}
}