diff --git a/agentcore/src/cli.rs b/agentcore/src/cli.rs new file mode 100644 index 0000000..8cfd5dc --- /dev/null +++ b/agentcore/src/cli.rs @@ -0,0 +1,1051 @@ +//! `agentcore cli [program] [-- extra_args...]`: an engine that drives an installed +//! coding CLI directly (`claude`, `codex`, `pi`, `omp`, `opencode`) over headless JSON-lines +//! without needing an npm ACP adapter. Speaks the exact same Bate engine protocol (`PROTOCOL.md`) +//! on stdin/stdout as `agentcore` and `agentcore acp`. + +use crate::tools::OUTPUT_CAP; +use proto::connectors::{Connector, Transport}; +use proto::{Event, MAX_EVENT_FRAME, MAX_OP_FRAME, Op, PROTOCOL, Request, Tokens, TurnEnd}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::io::{self, BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use std::sync::mpsc::{self, Sender}; +use std::thread; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Claude, + Codex, + Pi, + Omp, + OpenCode, +} + +impl Kind { + fn parse(s: &str) -> Option { + match s.to_ascii_lowercase().as_str() { + "claude" | "claude-code" => Some(Kind::Claude), + "codex" => Some(Kind::Codex), + "pi" => Some(Kind::Pi), + "omp" | "oh-my-pi" => Some(Kind::Omp), + "opencode" => Some(Kind::OpenCode), + _ => None, + } + } + + fn default_bin(self) -> &'static str { + match self { + Kind::Claude => "claude", + Kind::Codex => "codex", + Kind::Pi => "pi", + Kind::Omp => "omp", + Kind::OpenCode => "opencode", + } + } +} + +struct Spec { + kind: Kind, + program: String, + extra_args: Vec, +} + +fn parse_args(args: &[String]) -> Result { + let Some(first) = args.first() else { + return Err( + "usage: agentcore cli [program] [-- extra_args...]" + .into(), + ); + }; + let kind = Kind::parse(first).ok_or_else(|| { + format!("unknown cli kind `{first}` (expected claude, codex, pi, omp, or opencode)") + })?; + let rest = &args[1..]; + let (program, extra_args) = match rest.first().map(String::as_str) { + None => (kind.default_bin().to_owned(), Vec::new()), + Some("--") => (kind.default_bin().to_owned(), rest[1..].to_vec()), + Some(prog) if prog.starts_with('-') => (kind.default_bin().to_owned(), rest.to_vec()), + Some(prog) => { + let tail = if rest.get(1).map(String::as_str) == Some("--") { + rest[2..].to_vec() + } else { + rest[1..].to_vec() + }; + (prog.to_owned(), tail) + } + }; + Ok(Spec { + kind, + program, + extra_args, + }) +} + +enum Input { + Op(Request), + TurnDone(TurnOutcome), + Closed, +} + +struct TurnOutcome { + session_id: Option, + end: Event, +} + +static CHILD_PID: AtomicI32 = AtomicI32::new(0); + +fn out(event: &Event) { + let mut stdout = io::stdout().lock(); + if let Err(e) = proto::write_frame(&mut stdout, event, MAX_EVENT_FRAME) { + eprintln!("cannot send an event: {e}"); + kill_child(); + #[allow(clippy::disallowed_methods)] + std::process::exit(1); + } +} + +fn kill_child() { + let pid = CHILD_PID.swap(0, Ordering::SeqCst); + if pid > 0 { + // SAFETY: SIGKILL to our own spawned CLI child process. + unsafe { libc::kill(pid, libc::SIGKILL) }; + } +} + +fn ok(id: String) { + out(&Event::Response { id, error: None }); +} + +fn err(id: String, msg: impl Into) { + out(&Event::Response { + id, + error: Some(msg.into()), + }); +} + +fn work_dir() -> PathBuf { + match std::env::var_os("BATE_WORK_DIR").filter(|d| !d.is_empty()) { + Some(dir) => { + let p = PathBuf::from(dir); + p.canonicalize().unwrap_or(p) + } + None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + } +} + +fn cap_text(s: &str) -> String { + if s.len() <= OUTPUT_CAP { + return s.to_owned(); + } + let mut end = OUTPUT_CAP; + while !s.is_char_boundary(end) { + end -= 1; + } + format!("{}…[truncated]", &s[..end]) +} + +/// Write Bate's enabled connectors to a temporary Claude-compatible `mcpServers` JSON file. +fn write_claude_mcp_config(bot_dir: &Path, connectors: &[Connector]) -> Option { + let mut servers = serde_json::Map::new(); + for c in connectors { + if !c.enabled { + continue; + } + let entry = match &c.transport { + Transport::Stdio { command, args, env } => { + let mut m = serde_json::Map::new(); + m.insert("command".into(), json!(command)); + m.insert("args".into(), json!(args)); + if !env.is_empty() { + m.insert("env".into(), json!(env)); + } + Value::Object(m) + } + Transport::Http { url, headers } => { + let mut m = serde_json::Map::new(); + m.insert("type".into(), json!("http")); + m.insert("url".into(), json!(url)); + if !headers.is_empty() { + m.insert("headers".into(), json!(headers)); + } + Value::Object(m) + } + }; + servers.insert(c.name.clone(), entry); + } + if servers.is_empty() { + return None; + } + let path = bot_dir.join(".bate-cli-mcp.json"); + let body = json!({"mcpServers": servers}); + if std::fs::write(&path, serde_json::to_vec_pretty(&body).ok()?).is_ok() { + Some(path) + } else { + None + } +} + +#[derive(Default)] +struct ParseState { + session_id: Option, + saw_partial_text: bool, + started_tools: HashSet, + ended_tools: HashSet, + usage: Option, + error: Option, + next_call_seq: u64, +} + +impl ParseState { + fn next_id(&mut self, prefix: &str) -> String { + self.next_call_seq += 1; + format!("{prefix}_{}", self.next_call_seq) + } + + fn emit_tool_start(&mut self, call: String, tool: String, args: Value) { + if self.started_tools.insert(call.clone()) { + let map = match args { + Value::Object(m) => m, + Value::Null => serde_json::Map::new(), + other => { + let mut m = serde_json::Map::new(); + m.insert("input".into(), other); + m + } + }; + out(&Event::ToolStart { + call, + tool, + args: map, + }); + } + } + + fn emit_tool_end(&mut self, call: String, output: String, is_error: bool) { + if self.ended_tools.insert(call.clone()) { + out(&Event::ToolEnd { + call, + output: cap_text(&output), + is_error, + undo: None, + }); + } + } +} + +/// Parse one NDJSON event line from a headless CLI into Bate `Event`s. +fn handle_line(kind: Kind, line: &str, st: &mut ParseState) { + let trimmed = line.trim(); + if trimmed.is_empty() { + return; + } + let Ok(v) = serde_json::from_str::(trimmed) else { + // Non-JSON plain output (fallback if CLI printed plain text). + return; + }; + match kind { + Kind::Claude => handle_claude(&v, st), + Kind::Codex => handle_codex(&v, st), + Kind::Pi | Kind::Omp => handle_pi(&v, st), + Kind::OpenCode => handle_opencode(&v, st), + } +} + +fn handle_claude(v: &Value, st: &mut ParseState) { + if let Some(sid) = v["session_id"].as_str().filter(|s| !s.is_empty()) { + st.session_id = Some(sid.to_owned()); + } + match v["type"].as_str().unwrap_or("") { + "stream_event" => { + let ev = &v["event"]; + if ev["type"] == "content_block_delta" { + let d = &ev["delta"]; + match d["type"].as_str().unwrap_or("") { + "text_delta" => { + if let Some(t) = d["text"].as_str().filter(|s| !s.is_empty()) { + st.saw_partial_text = true; + out(&Event::Text { + delta: t.to_owned(), + }); + } + } + "thinking_delta" => { + if let Some(t) = d["thinking"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Thinking { + delta: t.to_owned(), + }); + } + } + _ => {} + } + } + } + "assistant" => { + for block in v["message"]["content"].as_array().into_iter().flatten() { + match block["type"].as_str().unwrap_or("") { + "text" if !st.saw_partial_text => { + if let Some(t) = block["text"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Text { + delta: t.to_owned(), + }); + } + } + "tool_use" => { + let call = block["id"] + .as_str() + .filter(|s| !s.is_empty()) + .map_or_else(|| st.next_id("claude"), str::to_owned); + let tool = block["name"].as_str().unwrap_or("tool").to_owned(); + let args = block["input"].clone(); + st.emit_tool_start(call, tool, args); + } + _ => {} + } + } + // Reset partial flag for the next assistant message round. + st.saw_partial_text = false; + } + "user" => { + for block in v["message"]["content"].as_array().into_iter().flatten() { + if block["type"] == "tool_result" { + let call = block["tool_use_id"].as_str().unwrap_or("").to_owned(); + let is_err = block["is_error"].as_bool().unwrap_or(false); + let output = match &block["content"] { + Value::String(s) => s.clone(), + Value::Array(arr) => arr + .iter() + .filter_map(|x| x["text"].as_str()) + .collect::>() + .join("\n"), + other => other.to_string(), + }; + if !call.is_empty() { + st.emit_tool_end(call, output, is_err); + } + } + } + } + "result" => { + let u = &v["usage"]; + if u.is_object() { + let base_in = u["input_tokens"].as_u64().unwrap_or(0); + let cache_create = u["cache_creation_input_tokens"].as_u64().unwrap_or(0); + let cache_read = u["cache_read_input_tokens"].as_u64().unwrap_or(0); + let out_tok = u["output_tokens"].as_u64().unwrap_or(0); + st.usage = Some(Tokens { + input: base_in + cache_create + cache_read, + cached: cache_read, + output: out_tok, + }); + } + if v["is_error"].as_bool().unwrap_or(false) { + let msg = v["result"] + .as_str() + .or_else(|| v["error"].as_str()) + .unwrap_or("claude CLI turn failed"); + st.error = Some(msg.to_owned()); + } + } + _ => {} + } +} + +fn handle_codex(v: &Value, st: &mut ParseState) { + match v["type"].as_str().unwrap_or("") { + "thread.started" => { + if let Some(tid) = v["thread_id"].as_str().filter(|s| !s.is_empty()) { + st.session_id = Some(tid.to_owned()); + } + } + "item.started" => { + let item = &v["item"]; + let id = item["id"] + .as_str() + .filter(|s| !s.is_empty()) + .map_or_else(|| st.next_id("codex"), str::to_owned); + match item["type"].as_str().unwrap_or("") { + "command_execution" => { + let cmd = item["command"].as_str().unwrap_or(""); + st.emit_tool_start(id, "run".into(), json!({"command": cmd})); + } + "mcp_tool_call" => { + let tool = item["tool"] + .as_str() + .or_else(|| item["name"].as_str()) + .unwrap_or("mcp") + .to_owned(); + let args = item["arguments"].clone(); + st.emit_tool_start(id, tool, args); + } + "file_change" => { + st.emit_tool_start(id, "edit".into(), json!({"changes": item["changes"]})); + } + _ => {} + } + } + "item.completed" => { + let item = &v["item"]; + let id = item["id"].as_str().unwrap_or("").to_owned(); + match item["type"].as_str().unwrap_or("") { + "agent_message" => { + if let Some(t) = item["text"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Text { + delta: t.to_owned(), + }); + } + } + "reasoning" => { + if let Some(t) = item["text"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Thinking { + delta: t.to_owned(), + }); + } + } + "command_execution" => { + let call = if id.is_empty() { + st.next_id("codex") + } else { + id + }; + if !st.started_tools.contains(&call) { + let cmd = item["command"].as_str().unwrap_or(""); + st.emit_tool_start(call.clone(), "run".into(), json!({"command": cmd})); + } + let output = item["aggregated_output"].as_str().unwrap_or("").to_owned(); + let exit = item["exit_code"].as_i64().unwrap_or(0); + st.emit_tool_end(call, output, exit != 0); + } + "mcp_tool_call" => { + let call = if id.is_empty() { + st.next_id("codex") + } else { + id + }; + let output = item["result"].to_string(); + let is_err = item["error"].is_string() || item["status"] == "failed"; + st.emit_tool_end(call, output, is_err); + } + "file_change" => { + let call = if id.is_empty() { + st.next_id("codex") + } else { + id + }; + if !st.started_tools.contains(&call) { + st.emit_tool_start( + call.clone(), + "edit".into(), + json!({"changes": item["changes"]}), + ); + } + let is_err = item["status"] == "failed"; + st.emit_tool_end(call, item["changes"].to_string(), is_err); + } + _ => {} + } + } + "turn.completed" => { + let u = &v["usage"]; + if u.is_object() { + st.usage = Some(Tokens { + input: u["input_tokens"].as_u64().unwrap_or(0), + cached: u["cached_input_tokens"].as_u64().unwrap_or(0), + output: u["output_tokens"].as_u64().unwrap_or(0), + }); + } + } + "turn.failed" | "error" => { + let msg = v["error"]["message"] + .as_str() + .or_else(|| v["message"].as_str()) + .unwrap_or("codex turn failed"); + st.error = Some(msg.to_owned()); + } + _ => {} + } +} + +fn handle_pi(v: &Value, st: &mut ParseState) { + match v["type"].as_str().unwrap_or("") { + "session" => { + if let Some(sid) = v["id"].as_str().filter(|s| !s.is_empty()) { + st.session_id = Some(sid.to_owned()); + } + } + "message_update" => { + let ev = &v["assistantMessageEvent"]; + match ev["type"].as_str().unwrap_or("") { + "text_delta" => { + if let Some(t) = ev["delta"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Text { + delta: t.to_owned(), + }); + } + } + "thinking_delta" => { + if let Some(t) = ev["delta"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Thinking { + delta: t.to_owned(), + }); + } + } + _ => {} + } + } + "tool_execution_start" => { + let call = v["toolCallId"] + .as_str() + .filter(|s| !s.is_empty()) + .map_or_else(|| st.next_id("pi"), str::to_owned); + let tool = v["toolName"].as_str().unwrap_or("tool").to_owned(); + let args = v["args"].clone(); + st.emit_tool_start(call, tool, args); + } + "tool_execution_end" => { + let call = v["toolCallId"].as_str().unwrap_or("").to_owned(); + let is_err = v["isError"].as_bool().unwrap_or(false); + let output = match &v["result"] { + Value::String(s) => s.clone(), + Value::Object(obj) => obj + .get("content") + .and_then(|c| c.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|x| x["text"].as_str()) + .collect::>() + .join("\n") + }) + .unwrap_or_else(|| v["result"].to_string()), + other => other.to_string(), + }; + if !call.is_empty() { + st.emit_tool_end(call, output, is_err); + } + } + "message_end" => { + let msg = &v["message"]; + if msg["role"] == "assistant" { + let u = &msg["usage"]; + if u.is_object() { + let prev = st.usage.unwrap_or(Tokens { + input: 0, + cached: 0, + output: 0, + }); + st.usage = Some(Tokens { + input: prev.input + u["input"].as_u64().unwrap_or(0), + cached: prev.cached + u["cacheRead"].as_u64().unwrap_or(0), + output: prev.output + u["output"].as_u64().unwrap_or(0), + }); + } + if msg["stopReason"] == "error" + && let Some(e) = msg["errorMessage"].as_str() + { + st.error = Some(e.to_owned()); + } + } + } + _ => {} + } +} + +fn handle_opencode(v: &Value, st: &mut ParseState) { + if let Some(sid) = v["sessionID"].as_str().filter(|s| !s.is_empty()) { + st.session_id = Some(sid.to_owned()); + } + match v["type"].as_str().unwrap_or("") { + "text" => { + if let Some(t) = v["part"]["text"].as_str().filter(|s| !s.is_empty()) { + out(&Event::Text { + delta: t.to_owned(), + }); + } + } + "tool_use" => { + let part = &v["part"]; + let call = part["callID"] + .as_str() + .filter(|s| !s.is_empty()) + .map_or_else(|| st.next_id("oc"), str::to_owned); + let tool = part["tool"].as_str().unwrap_or("tool").to_owned(); + let args = part["state"]["input"].clone(); + st.emit_tool_start(call.clone(), tool, args); + let status = part["state"]["status"].as_str().unwrap_or(""); + if status == "completed" || status == "error" { + let output = part["state"]["output"] + .as_str() + .or_else(|| part["state"]["error"].as_str()) + .unwrap_or("") + .to_owned(); + st.emit_tool_end(call, output, status == "error"); + } + } + "step_finish" => { + let u = &v["part"]["tokens"]; + if u.is_object() { + let prev = st.usage.unwrap_or(Tokens { + input: 0, + cached: 0, + output: 0, + }); + st.usage = Some(Tokens { + input: prev.input + u["input"].as_u64().unwrap_or(0), + cached: prev.cached + u["cache"]["read"].as_u64().unwrap_or(0), + output: prev.output + u["output"].as_u64().unwrap_or(0), + }); + } + } + "error" => { + let msg = v["error"]["data"]["message"] + .as_str() + .or_else(|| v["error"]["name"].as_str()) + .unwrap_or("opencode error"); + st.error = Some(msg.to_owned()); + } + _ => {} + } +} + +struct TurnParams { + kind: Kind, + program: String, + extra_args: Vec, + work: PathBuf, + bot_dir: PathBuf, + prompt: String, + instructions: String, + model: Option, + session_id: Option, + pi_session_file: Option, + connectors: Vec, + aborted: Arc, +} + +fn spawn_cli_turn(p: &TurnParams) -> io::Result { + let mut cmd = Command::new(&p.program); + cmd.current_dir(&p.work) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + match p.kind { + Kind::Claude => { + cmd.args([ + "-p", + &p.prompt, + "--output-format", + "stream-json", + "--verbose", + "--include-partial-messages", + "--permission-mode", + "bypassPermissions", + ]); + if let Some(m) = &p.model { + cmd.args(["--model", m]); + } + if !p.instructions.is_empty() { + cmd.args(["--append-system-prompt", &p.instructions]); + } + if let Some(sid) = &p.session_id { + cmd.args(["--resume", sid]); + } + if let Some(cfg) = write_claude_mcp_config(&p.bot_dir, &p.connectors) { + cmd.arg("--mcp-config").arg(cfg); + } + } + Kind::Codex => { + cmd.arg("exec"); + if let Some(sid) = &p.session_id { + cmd.args(["resume", sid]); + } + cmd.args(["--json", "--skip-git-repo-check"]); + if p.session_id.is_none() { + cmd.args(["--sandbox", "workspace-write"]); + } + if let Some(m) = &p.model { + cmd.args(["--model", m]); + } + cmd.arg(&p.prompt); + } + Kind::Pi | Kind::Omp => { + cmd.args(["-p", "--mode", "json"]); + if let Some(m) = &p.model { + cmd.args(["--model", m]); + } + if !p.instructions.is_empty() { + cmd.args(["--append-system-prompt", &p.instructions]); + } + if let Some(sf) = &p.pi_session_file { + cmd.arg("--session").arg(sf); + } + cmd.arg(&p.prompt); + } + Kind::OpenCode => { + cmd.args(["run", "--format", "json"]); + if let Some(m) = &p.model { + cmd.args(["--model", m]); + } + if let Some(sid) = &p.session_id { + cmd.args(["--session", sid]); + } + cmd.arg(&p.prompt); + } + } + cmd.args(&p.extra_args); + cmd.spawn() +} + +fn run_turn_thread(p: TurnParams, tx: Sender) { + let mut child = match spawn_cli_turn(&p) { + Ok(c) => c, + Err(e) => { + let _ = tx.send(Input::TurnDone(TurnOutcome { + session_id: p.session_id, + end: Event::TurnEnd { + reason: TurnEnd::Error, + error: Some(format!("cannot start `{}`: {e}", p.program)), + }, + })); + return; + } + }; + CHILD_PID.store(child.id() as i32, Ordering::SeqCst); + + let Some(stdout) = child.stdout.take() else { + kill_child(); + let _ = tx.send(Input::TurnDone(TurnOutcome { + session_id: p.session_id, + end: Event::TurnEnd { + reason: TurnEnd::Error, + error: Some("CLI stdout pipe unavailable".into()), + }, + })); + return; + }; + let stderr = child.stderr.take(); + let stderr_handle = thread::spawn(move || { + let mut buf = String::new(); + if let Some(mut s) = stderr { + let _ = io::Read::read_to_string(&mut s, &mut buf); + } + buf + }); + + let mut st = ParseState { + session_id: p.session_id.clone(), + ..ParseState::default() + }; + let mut reader = BufReader::new(stdout); + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + handle_line(p.kind, &line, &mut st); + line.clear(); + } + + let status = child.wait(); + CHILD_PID.store(0, Ordering::SeqCst); + let stderr_text = stderr_handle.join().unwrap_or_default(); + + // Close any tools whose end event was omitted by the CLI. + let unclosed: Vec = st + .started_tools + .difference(&st.ended_tools) + .cloned() + .collect(); + for call in unclosed { + out(&Event::ToolEnd { + call, + output: String::new(), + is_error: false, + undo: None, + }); + } + + if let Some(tokens) = st.usage { + out(&Event::Usage { + reported: true, + tokens, + }); + } + + let end = if p.aborted.load(Ordering::SeqCst) { + Event::TurnEnd { + reason: TurnEnd::Aborted, + error: None, + } + } else if let Some(msg) = st.error { + Event::TurnEnd { + reason: TurnEnd::Error, + error: Some(msg), + } + } else if let Ok(s) = status + && !s.success() + { + let detail = stderr_text.trim(); + let msg = if detail.is_empty() { + format!("{} exited with {s}", p.program) + } else { + format!("{} exited with {s}: {}", p.program, cap_text(detail)) + }; + Event::TurnEnd { + reason: TurnEnd::Error, + error: Some(msg), + } + } else { + Event::TurnEnd { + reason: TurnEnd::Done, + error: None, + } + }; + + let _ = tx.send(Input::TurnDone(TurnOutcome { + session_id: st.session_id, + end, + })); +} + +pub fn run(args: &[String]) -> i32 { + let spec = match parse_args(args) { + Ok(s) => s, + Err(e) => { + eprintln!("{e}"); + return 2; + } + }; + + out(&Event::Ready { protocol: PROTOCOL }); + + let (tx, rx) = mpsc::channel(); + let reader_tx = tx.clone(); + thread::spawn(move || { + let mut stdin = BufReader::new(io::stdin()); + let mut buf = Vec::new(); + loop { + match proto::read_frame::(&mut stdin, MAX_OP_FRAME, &mut buf) { + Ok(Some(req)) => { + if reader_tx.send(Input::Op(req)).is_err() { + return; + } + } + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + eprintln!("unreadable operation: {e}"); + } + _ => { + let _ = reader_tx.send(Input::Closed); + return; + } + } + } + }); + + let bot_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let work = work_dir(); + let mut session_id: Option = None; + let mut session_counter: u64 = 0; + let mut pi_session_file: Option = None; + let mut model: Option = None; + let mut instructions = String::new(); + let mut connectors: Vec = Vec::new(); + let mut running_abort: Option> = None; + + for input in rx { + match input { + Input::Closed => { + kill_child(); + break; + } + Input::TurnDone(outcome) => { + running_abort = None; + session_id = outcome.session_id; + out(&outcome.end); + } + Input::Op(Request { id, op }) => match op { + Op::Start { .. } => { + if running_abort.is_some() { + err(id, "a turn is running"); + continue; + } + session_counter += 1; + session_id = None; + let local_id = format!("cli-{}-{session_counter}", spec.kind.default_bin()); + pi_session_file = Some(bot_dir.join(format!("{local_id}.jsonl"))); + ok(id); + out(&Event::Session { session: local_id }); + } + Op::Open { session, .. } => { + if running_abort.is_some() { + err(id, "a turn is running"); + continue; + } + session_id = Some(session.clone()); + pi_session_file = Some(bot_dir.join(format!("{session}.jsonl"))); + ok(id); + out(&Event::Session { session }); + } + Op::Connectors { connectors: list } => { + connectors = list; + ok(id); + } + Op::SetModel { model: m, .. } => { + model = (!m.is_empty()).then_some(m); + ok(id); + } + Op::Instructions { text } => { + instructions = text; + ok(id); + } + Op::Prompt { text, nonce, .. } => { + if running_abort.is_some() { + err(id, "a turn is already running"); + continue; + } + ok(id); + out(&Event::TurnStart { nonce }); + let aborted = Arc::new(AtomicBool::new(false)); + running_abort = Some(aborted.clone()); + let params = TurnParams { + kind: spec.kind, + program: spec.program.clone(), + extra_args: spec.extra_args.clone(), + work: work.clone(), + bot_dir: bot_dir.clone(), + prompt: text, + instructions: instructions.clone(), + model: model.clone(), + session_id: session_id.clone(), + pi_session_file: pi_session_file.clone(), + connectors: connectors.clone(), + aborted, + }; + let done_tx = tx.clone(); + thread::spawn(move || run_turn_thread(params, done_tx)); + } + Op::Abort => { + if let Some(flag) = &running_abort { + flag.store(true, Ordering::SeqCst); + kill_child(); + } + ok(id); + } + // Operations handled by Bate's own engine that are no-ops for external CLIs. + Op::StepLimit { .. } + | Op::FallbackModel { .. } + | Op::WebSearch { .. } + | Op::SkillFolders { .. } + | Op::SkillsOff { .. } + | Op::BlockedTools { .. } + | Op::Peers { .. } + | Op::Answer { .. } + | Op::Token { .. } + | Op::Steer { .. } => ok(id), + _ => err(id, "not supported by the cli engine"), + }, + } + } + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_cli_kinds_and_custom_binary_args() { + let s = parse_args(&["claude".into()]).unwrap(); + assert_eq!((s.kind, s.program.as_str()), (Kind::Claude, "claude")); + assert!(s.extra_args.is_empty()); + + let s = parse_args(&[ + "codex".into(), + "/tmp/fake-codex".into(), + "--".into(), + "--profile".into(), + "fast".into(), + ]) + .unwrap(); + assert_eq!(s.kind, Kind::Codex); + assert_eq!(s.program, "/tmp/fake-codex"); + assert_eq!(s.extra_args, vec!["--profile", "fast"]); + + assert!(parse_args(&[]).is_err()); + assert!(parse_args(&["unknown".into()]).is_err()); + } + + #[test] + fn claude_stream_json_captures_session_tools_and_usage() { + let mut st = ParseState::default(); + handle_line( + Kind::Claude, + r#"{"type":"system","subtype":"init","session_id":"sess-42"}"#, + &mut st, + ); + handle_line( + Kind::Claude, + r#"{"type":"result","is_error":false,"session_id":"sess-42","usage":{"input_tokens":120,"cache_read_input_tokens":30,"cache_creation_input_tokens":10,"output_tokens":45}}"#, + &mut st, + ); + assert_eq!(st.session_id.as_deref(), Some("sess-42")); + assert_eq!( + st.usage, + Some(Tokens { + input: 160, + cached: 30, + output: 45 + }) + ); + assert!(st.error.is_none()); + } + + #[test] + fn codex_jsonl_captures_thread_and_usage() { + let mut st = ParseState::default(); + handle_line( + Kind::Codex, + r#"{"type":"thread.started","thread_id":"th-9"}"#, + &mut st, + ); + handle_line( + Kind::Codex, + r#"{"type":"turn.completed","usage":{"input_tokens":500,"cached_input_tokens":200,"output_tokens":80}}"#, + &mut st, + ); + assert_eq!(st.session_id.as_deref(), Some("th-9")); + assert_eq!( + st.usage, + Some(Tokens { + input: 500, + cached: 200, + output: 80 + }) + ); + } + + #[test] + fn pi_json_accumulates_usage_across_rounds() { + let mut st = ParseState::default(); + handle_line(Kind::Pi, r#"{"type":"session","id":"pi-1"}"#, &mut st); + handle_line( + Kind::Pi, + r#"{"type":"message_end","message":{"role":"assistant","usage":{"input":100,"cacheRead":20,"output":15}}}"#, + &mut st, + ); + handle_line( + Kind::Pi, + r#"{"type":"message_end","message":{"role":"assistant","usage":{"input":150,"cacheRead":50,"output":25}}}"#, + &mut st, + ); + assert_eq!(st.session_id.as_deref(), Some("pi-1")); + assert_eq!( + st.usage, + Some(Tokens { + input: 250, + cached: 70, + output: 40 + }) + ); + } +} diff --git a/agentcore/src/main.rs b/agentcore/src/main.rs index 13bc740..4802250 100644 --- a/agentcore/src/main.rs +++ b/agentcore/src/main.rs @@ -2,6 +2,7 @@ //! stdin/stdout in the bot's folder; one turn at a time runs on its own thread. mod acp; +mod cli; mod mcp; mod memory; mod model; @@ -134,6 +135,11 @@ fn main() { #[allow(clippy::disallowed_methods)] std::process::exit(acp::run(&args[1..])); } + if args.first().is_some_and(|arg| arg == "cli") { + // Top-level dispatch to the direct headless CLI engine mode. + #[allow(clippy::disallowed_methods)] + std::process::exit(cli::run(&args[1..])); + } let out = Out(Arc::new(Mutex::new(io::stdout()))); out.send(&Event::Ready { protocol: proto::PROTOCOL, diff --git a/agentcore/src/model.rs b/agentcore/src/model.rs index b457f45..c0d6963 100644 --- a/agentcore/src/model.rs +++ b/agentcore/src/model.rs @@ -38,6 +38,20 @@ const NAMESPACE: &str = "bate"; pub enum Api { Chat, Responses, + Anthropic, +} + +/// Infer API style from a server URL when no explicit `api` tag was provided. +pub fn detect_api(url: &str) -> Api { + let lower = url.trim_end_matches('/').to_ascii_lowercase(); + if lower.contains("://api.anthropic.com") + || lower.ends_with("/anthropic") + || lower.ends_with("/anthropic/v1") + { + Api::Anthropic + } else { + Api::Chat + } } /// Why a model call failed. @@ -152,6 +166,131 @@ fn responses_done(line: &str) -> bool { }) } +/// Whether a line of an Anthropic Messages stream ends the reply. +fn anthropic_done(line: &str) -> bool { + #[derive(Deserialize)] + struct Kind<'a> { + #[serde(borrow, rename = "type")] + kind: std::borrow::Cow<'a, str>, + } + let kind = data(line).and_then(|d| serde_json::from_str::(d).ok()); + kind.is_some_and(|k| matches!(&*k.kind, "message_stop" | "error")) +} + +/// Convert chat-shaped messages into Anthropic Messages format (strictly alternating user/assistant, +/// consecutive tool outputs grouped into a single user message with `tool_result` blocks). +fn anthropic_messages<'a>(messages: impl Iterator) -> Vec { + let mut out: Vec = Vec::new(); + let push_blocks = |out: &mut Vec, role: &str, mut blocks: Vec| { + if blocks.is_empty() { + return; + } + if let Some(last) = out.last_mut() + && last["role"].as_str() == Some(role) + && let Some(arr) = last["content"].as_array_mut() + { + arr.append(&mut blocks); + return; + } + out.push(json!({"role": role, "content": blocks})); + }; + + for m in messages { + let text = |v: &Value| v.as_str().map_or_else(|| v.to_string(), str::to_owned); + match m["role"].as_str().unwrap_or("") { + "tool" => { + let block = json!({ + "type": "tool_result", + "tool_use_id": m["tool_call_id"].as_str().unwrap_or(""), + "content": text(&m["content"]), + }); + push_blocks(&mut out, "user", vec![block]); + } + "assistant" => { + let mut blocks = Vec::new(); + if let Some(t) = m["content"].as_str().filter(|t| !t.is_empty()) { + blocks.push(json!({"type": "text", "text": t})); + } + for c in m["tool_calls"].as_array().into_iter().flatten() { + let raw_args = c["function"]["arguments"].as_str().unwrap_or("{}"); + let parsed = serde_json::from_str::(raw_args) + .ok() + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + blocks.push(json!({ + "type": "tool_use", + "id": c["id"].as_str().unwrap_or(""), + "name": c["function"]["name"].as_str().unwrap_or(""), + "input": parsed, + })); + } + push_blocks(&mut out, "assistant", blocks); + } + // Mid-turn system nudges (steer / doom-loop / check) become user text blocks. + _ => { + let t = text(&m["content"]); + if !t.is_empty() { + push_blocks(&mut out, "user", vec![json!({"type": "text", "text": t})]); + } + } + } + } + out +} + +/// Build an Anthropic `/v1/messages` streaming request body for `ask`. +fn anthropic_body(ask: &Ask) -> Value { + let budget: Option = match ask.effort { + Some("low") => Some(2048), + Some("medium") => Some(4096), + Some("high") => Some(8192), + _ => None, + }; + let max_tokens = budget.map_or(8192, |b| b + 8192); + let mut body = json!({ + "model": ask.model, + "max_tokens": max_tokens, + "stream": true, + "messages": anthropic_messages(ask.messages.iter().chain(ask.last)), + }); + if !ask.system.is_empty() { + body["system"] = json!([{ + "type": "text", + "text": ask.system, + "cache_control": {"type": "ephemeral"}, + }]); + } + let mut tools: Vec = ask + .tools + .as_array() + .into_iter() + .flatten() + .map(|t| { + let f = &t["function"]; + let schema = if f["parameters"].is_object() { + f["parameters"].clone() + } else { + json!({"type": "object", "properties": {}}) + }; + json!({ + "name": f["name"], + "description": f["description"].as_str().unwrap_or(""), + "input_schema": schema, + }) + }) + .collect(); + if let Some(last) = tools.last_mut() { + last["cache_control"] = json!({"type": "ephemeral"}); + } + if !tools.is_empty() { + body["tools"] = json!(tools); + } + if let Some(b) = budget { + body["thinking"] = json!({"type": "enabled", "budget_tokens": b}); + } + body +} + /// The chat-shaped conversation as Responses input items. // shortcut: the model's reasoning items and its hosted searches are not kept between calls of // a turn (`store` is false, so the server has none either; the reply's text has what the @@ -483,13 +622,18 @@ impl Provider { }; let body = serde_json::to_vec(&body).map_err(|e| e.to_string())?; let url = format!("{base}/chat/completions"); - chat(&self.lines(url, key, body, chat_done), abort, self.idle, on) + chat( + &self.lines(url, key, api, body, chat_done), + abort, + self.idle, + on, + ) } Api::Responses => { let body = serde_json::to_vec(&responses_body(ask, search)).map_err(|e| e.to_string())?; let url = format!("{base}/responses"); - let lines = self.lines(url, key, body, responses_done); + let lines = self.lines(url, key, api, body, responses_done); responses(&lines, abort, self.idle, on).map_err(|mut fail| { let e = &fail.why; // Comes as a 429 or as `response.failed` mid-stream; it may be the plan's limit @@ -511,6 +655,18 @@ impl Provider { fail }) } + Api::Anthropic => { + let body = serde_json::to_vec(&anthropic_body(ask)).map_err(|e| e.to_string())?; + let url = if base.ends_with("/messages") { + base.to_owned() + } else if base.ends_with("/v1") { + format!("{base}/messages") + } else { + format!("{base}/v1/messages") + }; + let lines = self.lines(url, key, api, body, anthropic_done); + anthropic_stream(&lines, abort, self.idle, on) + } } } @@ -520,6 +676,7 @@ impl Provider { &self, url: String, key: Option<&str>, + api: Api, body: Vec, done: fn(&str) -> bool, ) -> Lines { @@ -531,7 +688,12 @@ impl Provider { std::thread::spawn(move || { let read = || -> Result<(), Fail> { let mut request = agent.post(&url).header("Content-Type", "application/json"); - if let Some(key) = &key { + if api == Api::Anthropic { + request = request.header("anthropic-version", "2023-06-01"); + if let Some(key) = &key { + request = request.header("x-api-key", key); + } + } else if let Some(key) = &key { request = request.header("Authorization", format!("Bearer {key}")); } let response = request.send(&body[..]).map_err(|e| { @@ -810,6 +972,129 @@ fn chat( Ok(reply) } +/// Reads an Anthropic `/v1/messages` SSE stream to its `message_stop`. +fn anthropic_stream( + lines: &Lines, + abort: &AtomicBool, + idle: Duration, + mut on: impl FnMut(Delta), +) -> Result { + let mut reply = Reply::default(); + let mut call_at = HashMap::::new(); + let mut in_tokens: u64 = 0; + let mut cached_tokens: u64 = 0; + let mut out_tokens: u64 = 0; + let mut saw_usage = false; + let mut max_tokens_hit = false; + let mut first = true; + loop { + let line = match next(lines, abort, idle, first)? { + Next::Line(line) => { + first = false; + line + } + Next::Aborted => { + reply.calls.clear(); + reply.aborted = true; + return Ok(reply); + } + Next::End => return Err(cut_off()), + }; + let Some(event) = data(&line).and_then(|d| serde_json::from_str::(d).ok()) else { + continue; + }; + match event["type"].as_str().unwrap_or("") { + "message_start" => { + let u = &event["message"]["usage"]; + if u.is_object() { + let base_in = u["input_tokens"].as_u64().unwrap_or(0); + let cache_create = u["cache_creation_input_tokens"].as_u64().unwrap_or(0); + let cache_read = u["cache_read_input_tokens"].as_u64().unwrap_or(0); + in_tokens = base_in + cache_create + cache_read; + cached_tokens = cache_read; + out_tokens = u["output_tokens"].as_u64().unwrap_or(0); + saw_usage = true; + } + } + "content_block_start" => { + let index = event["index"].as_u64().unwrap_or(0); + let block = &event["content_block"]; + if block["type"] == "tool_use" { + let id = block["id"].as_str().unwrap_or("").to_owned(); + let name = block["name"].as_str().unwrap_or("").to_owned(); + reply.calls.push(Call { + id, + name, + arguments: String::new(), + }); + call_at.insert(index, reply.calls.len() - 1); + } + } + "content_block_delta" => { + let index = event["index"].as_u64().unwrap_or(0); + let delta = &event["delta"]; + match delta["type"].as_str().unwrap_or("") { + "text_delta" => { + if let Some(t) = delta["text"].as_str().filter(|t| !t.is_empty()) { + reply.text.push_str(t); + on(Delta::Text(t)); + } + } + "thinking_delta" => { + if let Some(t) = delta["thinking"].as_str().filter(|t| !t.is_empty()) { + on(Delta::Thinking(t)); + } + } + "input_json_delta" => { + if let Some(&i) = call_at.get(&index) { + reply.calls[i] + .arguments + .push_str(delta["partial_json"].as_str().unwrap_or("")); + } + } + _ => {} + } + } + "message_delta" => { + if event["delta"]["stop_reason"] == "max_tokens" { + max_tokens_hit = true; + } + if let Some(o) = event["usage"]["output_tokens"].as_u64() { + out_tokens = o; + saw_usage = true; + } + } + "message_stop" => { + // Ensure any tool_use block with zero partial_json gets valid `{}` JSON. + for call in &mut reply.calls { + if call.arguments.is_empty() { + call.arguments.push_str("{}"); + } + } + if saw_usage { + reply.usage = Some(Tokens { + input: in_tokens, + cached: cached_tokens, + output: out_tokens, + }); + } + if max_tokens_hit && reply.calls.is_empty() { + return Err(cut_off()); + } + return Ok(reply); + } + "error" => { + let msg = event["error"]["message"] + .as_str() + .unwrap_or("unknown error"); + let kind = event["error"]["type"].as_str().unwrap_or("error"); + return Err(format!("the model server failed: {kind}: {msg}").into()); + } + _ => {} + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -890,6 +1175,75 @@ mod tests { assert_eq!(reply.usage, None); } + #[test] + fn an_anthropic_stream_parses_thinking_text_tool_calls_and_cache_usage() { + let mut thinking = String::new(); + let mut text = String::new(); + let lines = stream(&[ + r#"data: {"type":"message_start","message":{"usage":{"input_tokens":100,"cache_creation_input_tokens":20,"cache_read_input_tokens":80,"output_tokens":1}}}"#, + r#"data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#, + r#"data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"plan"}}"#, + r#"data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}"#, + r#"data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"checking"}}"#, + r#"data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_1","name":"read","input":{}}}"#, + r#"data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\":"}}"#, + r#"data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"a.txt\"}"}}"#, + r#"data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":35}}"#, + r#"data: {"type":"message_stop"}"#, + ]); + let reply = anthropic_stream( + &lines, + &AtomicBool::new(false), + Duration::from_secs(5), + |d| match d { + Delta::Thinking(t) => thinking.push_str(t), + Delta::Text(t) => text.push_str(t), + _ => {} + }, + ) + .unwrap_or_else(|e| panic!("{}", e.why)); + assert_eq!(thinking, "plan"); + assert_eq!(text, "checking"); + assert_eq!(reply.text, "checking"); + assert_eq!(reply.calls.len(), 1); + assert_eq!(reply.calls[0].id, "toolu_1"); + assert_eq!(reply.calls[0].name, "read"); + assert_eq!(reply.calls[0].arguments, r#"{"path":"a.txt"}"#); + assert_eq!( + reply.usage, + Some(Tokens { + input: 200, + cached: 80, + output: 35, + }) + ); + } + + #[test] + fn anthropic_messages_groups_consecutive_tool_results_and_auto_detects_url() { + let msgs = [ + json!({"role": "user", "content": "check two files"}), + json!({ + "role": "assistant", + "content": "", + "tool_calls": [ + {"id": "c1", "type": "function", "function": {"name": "read", "arguments": "{\"path\":\"a\"}"}}, + {"id": "c2", "type": "function", "function": {"name": "read", "arguments": "{\"path\":\"b\"}"}} + ] + }), + json!({"role": "tool", "tool_call_id": "c1", "content": "alpha"}), + json!({"role": "tool", "tool_call_id": "c2", "content": "beta"}), + ]; + let out = anthropic_messages(msgs.iter()); + assert_eq!(out.len(), 3); + assert_eq!(out[2]["role"], "user"); + assert_eq!(out[2]["content"].as_array().unwrap().len(), 2); + assert_eq!(out[2]["content"][0]["tool_use_id"], "c1"); + assert_eq!(out[2]["content"][1]["tool_use_id"], "c2"); + assert_eq!(detect_api("https://api.anthropic.com/v1"), Api::Anthropic); + assert_eq!(detect_api("http://127.0.0.1:4100/v1"), Api::Chat); + } + #[test] fn the_first_line_may_take_four_times_as_long_as_a_later_silence() { let idle = Duration::from_millis(400); diff --git a/agentcore/src/turn.rs b/agentcore/src/turn.rs index d3ca52b..bc6ca95 100644 --- a/agentcore/src/turn.rs +++ b/agentcore/src/turn.rs @@ -433,6 +433,8 @@ fn parse_token(token: &str) -> (&str, Option, Api, &str, Option) let (url, key, api, named, context) = (part(), part(), part(), part(), part()); let api = match api { "responses" => Api::Responses, + "anthropic" => Api::Anthropic, + "" => crate::model::detect_api(url), _ => Api::Chat, }; let key = (!key.is_empty()).then(|| key.to_owned()); diff --git a/agentcore/tests/backends.rs b/agentcore/tests/backends.rs new file mode 100644 index 0000000..30befe0 --- /dev/null +++ b/agentcore/tests/backends.rs @@ -0,0 +1,439 @@ +//! Offline integration tests for `agentcore`'s native Anthropic Messages API +//! and direct headless CLI engine (`agentcore cli `). + +use proto::connectors::{Connector, Transport}; +use proto::permissions::APPROVE; +use proto::{Event, MAX_EVENT_FRAME, MAX_OP_FRAME, Op, Request, TurnEnd}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +const WAIT: Duration = Duration::from_secs(15); + +fn temp_dir(label: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = + std::env::temp_dir().join(format!("bate-backends-{}-{label}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +struct EngineProc { + child: Child, + stdin: ChildStdin, + events: Receiver, + seq: u64, +} + +impl EngineProc { + fn start(bot_dir: &Path, work_dir: &Path, extra_args: &[&str]) -> Self { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_agentcore")); + cmd.args(extra_args) + .current_dir(bot_dir) + .env("BATE_WORK_DIR", work_dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + let mut child = cmd.spawn().unwrap(); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, rx) = mpsc::channel(); + thread::spawn(move || { + let mut r = BufReader::new(stdout); + let mut buf = Vec::new(); + while let Ok(Some(ev)) = proto::read_frame::(&mut r, MAX_EVENT_FRAME, &mut buf) { + if tx.send(ev).is_err() { + break; + } + } + }); + let mut eng = EngineProc { + child, + stdin, + events: rx, + seq: 0, + }; + assert!(matches!(eng.next_event(), Event::Ready { .. })); + eng + } + + fn send(&mut self, op: Op) { + self.seq += 1; + let req = Request { + id: format!("r{}", self.seq), + op, + }; + proto::write_frame(&mut self.stdin, &req, MAX_OP_FRAME).unwrap(); + } + + fn next_event(&mut self) -> Event { + self.events + .recv_timeout(WAIT) + .expect("timed out waiting for event") + } +} + +impl Drop for EngineProc { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn anthropic_sse(events: Vec) -> Vec { + let mut body = String::new(); + for ev in events { + let kind = ev["type"].as_str().unwrap_or("message"); + body.push_str(&format!("event: {kind}\ndata: {ev}\n\n")); + } + body.into_bytes() +} + +#[test] +fn anthropic_native_tool_loop_and_headers() { + let bot_dir = temp_dir("anthropic-bot"); + let work_dir = temp_dir("anthropic-work"); + fs::write(work_dir.join("note.txt"), "secret-code=4242\n").unwrap(); + + let replies = vec![ + anthropic_sse(vec![ + json!({"type": "message_start", "message": {"usage": {"input_tokens": 100, "cache_creation_input_tokens": 20, "cache_read_input_tokens": 50, "output_tokens": 1}}}), + json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "toolu_01", "name": "read", "input": {}}}), + json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"path\":\"note.txt\"}"}}), + json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 18}}), + json!({"type": "message_stop"}), + ]), + anthropic_sse(vec![ + json!({"type": "message_start", "message": {"usage": {"input_tokens": 140, "cache_read_input_tokens": 100, "output_tokens": 1}}}), + json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}), + json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "The code is 4242."}}), + json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 10}}), + json!({"type": "message_stop"}), + ]), + ]; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/v1", listener.local_addr().unwrap()); + type CapturedReq = (String, BTreeMap, Value); + let captured: Arc>> = Arc::new(Mutex::new(Vec::new())); + let cap_clone = captured.clone(); + thread::spawn(move || { + for (stream, reply) in listener.incoming().zip(replies) { + let Ok(mut stream) = stream else { break }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut req_line = String::new(); + let _ = reader.read_line(&mut req_line); + let mut headers = BTreeMap::new(); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some((k, v)) = line.split_once(':') { + let kl = k.trim().to_ascii_lowercase(); + let vl = v.trim().to_owned(); + if kl == "content-length" { + length = vl.parse().unwrap_or(0); + } + headers.insert(kl, vl); + } + } + let mut raw = vec![0u8; length]; + let _ = reader.read_exact(&mut raw); + let body: Value = serde_json::from_slice(&raw).unwrap_or(Value::Null); + cap_clone + .lock() + .unwrap() + .push((req_line.trim().to_owned(), headers, body)); + let resp = format!( + "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + reply.len() + ); + let _ = stream.write_all(resp.as_bytes()); + let _ = stream.write_all(&reply); + } + }); + + let mut eng = EngineProc::start(&bot_dir, &work_dir, &[]); + eng.send(Op::Start { + bot: "test-anthropic".into(), + }); + eng.send(Op::SetModel { + model: "claude-sonnet-4-5".into(), + effort: None, + }); + eng.send(Op::Prompt { + text: "Read note.txt and tell me the code.".into(), + nonce: "n1".into(), + check: false, + check_back: false, + }); + + let mut final_text = String::new(); + let mut saw_tool_end = false; + let mut saw_cached = false; + loop { + match eng.next_event() { + Event::Token { request, .. } => eng.send(Op::Token { + request, + url: Some(url.clone()), + key: Some("sk-ant-test-key".into()), + api: Some("anthropic".into()), + model: Some("claude-sonnet-4-5".into()), + context: Some(200_000), + checker: None, + error: None, + }), + Event::Question { question, .. } => eng.send(Op::Answer { + question, + choice: APPROVE.into(), + }), + Event::Text { delta } => final_text.push_str(&delta), + Event::ToolEnd { + is_error, output, .. + } => { + assert!(!is_error); + assert!(output.contains("4242")); + saw_tool_end = true; + } + Event::Usage { tokens, .. } => { + if tokens.cached > 0 { + saw_cached = true; + } + } + Event::TurnEnd { reason, error } => { + assert_eq!(reason, TurnEnd::Done, "unexpected error: {error:?}"); + break; + } + _ => {} + } + } + + assert!(saw_tool_end); + assert!(saw_cached); + assert!(final_text.contains("4242")); + + let reqs = captured.lock().unwrap(); + assert_eq!(reqs.len(), 2); + assert!(reqs[0].0.starts_with("POST /v1/messages ")); + assert_eq!( + reqs[0].1.get("x-api-key").map(String::as_str), + Some("sk-ant-test-key") + ); + assert_eq!( + reqs[0].1.get("anthropic-version").map(String::as_str), + Some("2023-06-01") + ); + assert!(reqs[0].2["system"].is_array()); + // Second request must contain the tool_result block in a user message. + let msgs = reqs[1].2["messages"].as_array().unwrap(); + let last_msg = msgs.last().unwrap(); + assert_eq!(last_msg["role"], "user"); + assert_eq!(last_msg["content"][0]["type"], "tool_result"); + assert_eq!(last_msg["content"][0]["tool_use_id"], "toolu_01"); +} + +fn write_exec_script(path: &Path, content: &str) { + fs::write(path, content).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn cli_engine_claude_stream_and_multi_turn_resume() { + let bot_dir = temp_dir("cli-claude-bot"); + let work_dir = temp_dir("cli-claude-work"); + let fake = work_dir.join("fake-claude.sh"); + let args_log = work_dir.join("claude-args.log"); + + write_exec_script( + &fake, + &format!( + r#"#!/bin/sh +printf '%s\n' "$*" >> "{}" +echo '{{"type":"system","subtype":"init","session_id":"sess-test-1"}}' +echo '{{"type":"stream_event","event":{{"type":"content_block_delta","delta":{{"type":"text_delta","text":"Working..."}}}}}}' +echo '{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"tu1","name":"Bash","input":{{"command":"echo ok"}}}}]}}}}' +echo '{{"type":"user","message":{{"content":[{{"type":"tool_result","tool_use_id":"tu1","content":"ok","is_error":false}}]}}}}' +echo '{{"type":"result","is_error":false,"session_id":"sess-test-1","usage":{{"input_tokens":100,"cache_read_input_tokens":25,"output_tokens":30}}}}' +"#, + args_log.display() + ), + ); + + let fake_str = fake.to_string_lossy().into_owned(); + let mut eng = EngineProc::start(&bot_dir, &work_dir, &["cli", "claude", &fake_str]); + eng.send(Op::Connectors { + connectors: vec![Connector { + name: "demo".into(), + enabled: true, + oauth: false, + client_id: None, + signed_in: None, + transport: Transport::Stdio { + command: "echo".into(), + args: vec!["hi".into()], + env: BTreeMap::new(), + }, + }], + }); + eng.send(Op::Start { + bot: "claude-bot".into(), + }); + eng.send(Op::SetModel { + model: "claude-sonnet-4-5".into(), + effort: None, + }); + + // Turn 1 + eng.send(Op::Prompt { + text: "first prompt".into(), + nonce: "n1".into(), + check: false, + check_back: false, + }); + let mut got_text = String::new(); + let mut got_tool = false; + let mut got_usage = false; + loop { + match eng.next_event() { + Event::Text { delta } => got_text.push_str(&delta), + Event::ToolEnd { call, is_error, .. } => { + assert_eq!(call, "tu1"); + assert!(!is_error); + got_tool = true; + } + Event::Usage { tokens, .. } => { + assert_eq!(tokens.input, 125); + assert_eq!(tokens.cached, 25); + assert_eq!(tokens.output, 30); + got_usage = true; + } + Event::TurnEnd { reason, error } => { + assert_eq!(reason, TurnEnd::Done, "error: {error:?}"); + break; + } + _ => {} + } + } + assert_eq!(got_text, "Working..."); + assert!(got_tool && got_usage); + + // Turn 2: should pass --resume sess-test-1 + eng.send(Op::Prompt { + text: "second prompt".into(), + nonce: "n2".into(), + check: false, + check_back: false, + }); + loop { + if let Event::TurnEnd { reason, error } = eng.next_event() { + assert_eq!(reason, TurnEnd::Done, "error: {error:?}"); + break; + } + } + + let log = fs::read_to_string(&args_log).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 2); + assert!( + lines[0].contains("--mcp-config"), + "missing --mcp-config: {}", + lines[0] + ); + assert!(lines[0].contains("--model claude-sonnet-4-5")); + assert!( + lines[1].contains("--resume sess-test-1"), + "missing --resume: {}", + lines[1] + ); +} + +#[test] +fn cli_engine_codex_jsonl_and_multi_turn_resume() { + let bot_dir = temp_dir("cli-codex-bot"); + let work_dir = temp_dir("cli-codex-work"); + let fake = work_dir.join("fake-codex.sh"); + let args_log = work_dir.join("codex-args.log"); + + write_exec_script( + &fake, + &format!( + r#"#!/bin/sh +printf '%s\n' "$*" >> "{}" +echo '{{"type":"thread.started","thread_id":"thread-77"}}' +echo '{{"type":"item.started","item":{{"id":"cmd_1","type":"command_execution","command":"ls"}}}}' +echo '{{"type":"item.completed","item":{{"id":"cmd_1","type":"command_execution","command":"ls","aggregated_output":"a.txt\n","exit_code":0}}}}' +echo '{{"type":"item.completed","item":{{"id":"msg_1","type":"agent_message","text":"Done checking."}}}}' +echo '{{"type":"turn.completed","usage":{{"input_tokens":300,"cached_input_tokens":50,"output_tokens":20}}}}' +"#, + args_log.display() + ), + ); + + let fake_str = fake.to_string_lossy().into_owned(); + let mut eng = EngineProc::start(&bot_dir, &work_dir, &["cli", "codex", &fake_str]); + eng.send(Op::Start { + bot: "codex-bot".into(), + }); + eng.send(Op::Prompt { + text: "list files".into(), + nonce: "n1".into(), + check: false, + check_back: false, + }); + let mut text = String::new(); + let mut tool_ok = false; + loop { + match eng.next_event() { + Event::Text { delta } => text.push_str(&delta), + Event::ToolEnd { call, is_error, .. } => { + assert_eq!(call, "cmd_1"); + assert!(!is_error); + tool_ok = true; + } + Event::TurnEnd { reason, error } => { + assert_eq!(reason, TurnEnd::Done, "error: {error:?}"); + break; + } + _ => {} + } + } + assert_eq!(text, "Done checking."); + assert!(tool_ok); + + eng.send(Op::Prompt { + text: "follow up".into(), + nonce: "n2".into(), + check: false, + check_back: false, + }); + loop { + if let Event::TurnEnd { reason, error } = eng.next_event() { + assert_eq!(reason, TurnEnd::Done, "error: {error:?}"); + break; + } + } + + let log = fs::read_to_string(&args_log).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 2); + assert!(lines[0].starts_with("exec --json")); + assert!( + lines[1].starts_with("exec resume thread-77 --json"), + "expected resume, got: {}", + lines[1] + ); +} diff --git a/evals/README.md b/evals/README.md index f39a3f8..5274536 100644 --- a/evals/README.md +++ b/evals/README.md @@ -40,24 +40,52 @@ python3 evals/run.py --mock --engine target/debug/agentcore --out /tmp/bate-eval python3 -m unittest discover -s evals -v ``` -### 3. Live run against any OpenAI-compatible model endpoint (e.g. `omp` gateway, OpenAI, OpenRouter, Ollama) +### 3. Discover available local CLIs, gateways & API keys ```bash -python3 evals/run.py \ - --url http://127.0.0.1:4100/v1 \ - --model claude-sonnet-5 \ - --k 3 \ - --out /tmp/bate-eval-main +python3 evals/run.py discover ``` -### 4. Compare Bate `agentcore` vs another commit OR vs an installed ACP agent (`claude-agent-acp` / `codex-acp`) +### 4. Live run against any API endpoint (OpenAI, OpenRouter, `omp auth-gateway`, or native Anthropic) ```bash -# Run an installed ACP agent on the exact same 16 tasks: -python3 evals/run.py --acp "claude-agent-acp" --out /tmp/bate-eval-claude +# OpenAI-compatible (e.g. omp auth-gateway / OpenRouter / Ollama) +python3 evals/run.py --url http://127.0.0.1:4100/v1 --model claude-sonnet-5 --k 3 --out /tmp/bate-eval-main -# Paired McNemar exact test + token/tool deltas: -python3 evals/run.py compare /tmp/bate-eval-base /tmp/bate-eval-main +# Native Anthropic `/v1/messages` (direct from agentcore, with prompt caching) +python3 evals/run.py --url https://api.anthropic.com/v1 --api anthropic --model claude-sonnet-4-5 --out /tmp/bate-eval-ant +``` + +### 5. Tern-style local model gateway daemon (`serve` + `ctl` Unix control socket) +Routes OpenAI-compatible requests to `openai`, `anthropic`, `gemini`, `omp` (`omp auth-gateway stdio`), `cli`, or `mock` with live request/token/latency tracing: +```bash +# Standalone daemon + live control commands +python3 evals/run.py gateway serve --bind 127.0.0.1:4100 --control /tmp/bate-gw.sock --backend omp +python3 evals/run.py gateway ctl --control /tmp/bate-gw.sock status +python3 evals/run.py gateway ctl --control /tmp/bate-gw.sock stats +python3 evals/run.py gateway ctl --control /tmp/bate-gw.sock route claude- anthropic +python3 evals/run.py gateway ctl --control /tmp/bate-gw.sock stop + +# Or auto-start an embedded gateway for a single eval run: +python3 evals/run.py --gateway gemini --model gemini-2.5-pro --out /tmp/bate-eval-gem +``` + +### 6. Direct headless CLI engines (`agentcore cli`) & ACP agents + multi-backend matrix +```bash +# Drive installed CLIs directly through `agentcore cli ` (no npm ACP adapter needed): +python3 evals/run.py --cli claude --out /tmp/bate-eval-claude +python3 evals/run.py --cli codex --out /tmp/bate-eval-codex +python3 evals/run.py --cli pi --out /tmp/bate-eval-pi +python3 evals/run.py --acp "opencode acp" --out /tmp/bate-eval-opencode -# Or feed exported results.jsonl straight into d41sys/evalkit: +# Run a multi-backend matrix and produce a ranked leaderboard + pairwise McNemar table: +python3 evals/run.py matrix \ + --spec bate=url:http://127.0.0.1:4100/v1@claude-sonnet-5 \ + --spec claude=cli:claude \ + --spec codex=cli:codex \ + --spec opencode=acp:"opencode acp" \ + --k 3 --out /tmp/bate-eval-matrix + +# Or compare any two runs / export into d41sys/evalkit: +python3 evals/run.py compare /tmp/bate-eval-base /tmp/bate-eval-main # evalkit compare /tmp/bate-eval-main/results.jsonl --all-pairs ``` diff --git a/evals/analyze.py b/evals/analyze.py index f54bd8d..4b02600 100644 --- a/evals/analyze.py +++ b/evals/analyze.py @@ -315,3 +315,36 @@ def load(d: Path) -> dict[str, list[dict[str, Any]]]: if diffs: lines += ["", "## Tasks That Differed", "", "| Task | A | B | Delta |", "|---|---:|---:|---:|", *diffs] return "\n".join(lines) + "\n" + + +def leaderboard(runs: list[tuple[str, Path]]) -> str: + """Render a multi-backend ranked leaderboard with pairwise McNemar tests vs the top run.""" + if not runs: + return "No runs provided.\n" + entries: list[tuple[str, Path, dict[str, Any]]] = [] + for label, d in runs: + rep = enrich_run(d) + entries.append((label, d, rep)) + entries.sort(key=lambda x: (-x[2]["pass_rate"], -x[2]["pass_hat_k"], x[2]["mean_wall_s"])) + + lines = [ + "# AgentCore Multi-Backend Leaderboard", + "", + "| Rank | Backend | Pass@1 | Pass^k | Avg Tools | Avg Tokens | Avg Wall (s) | Top Failure |", + "|---:|---|---:|---:|---:|---:|---:|---|", + ] + for rank, (label, _, rep) in enumerate(entries, start=1): + modes = {k: v for k, v in rep["failure_modes"].items() if k != "pass"} + top_fail = max(modes.items(), key=lambda kv: kv[1])[0] if modes else "none" + lines.append( + f"| {rank} | `{label}` | {rep['passed']}/{rep['total']} ({rep['pass_rate'] * 100:.1f}%) " + f"| {rep['pass_hat_k'] * 100:.1f}% | {rep['mean_tools']:.1f} | {rep['mean_tokens']:,.0f} " + f"| {rep['mean_wall_s']:.2f} | `{top_fail}` |" + ) + if len(entries) >= 2: + top_label, top_dir, _ = entries[0] + lines += ["", f"## Pairwise vs `{top_label}`", ""] + for label, d, _ in entries[1:]: + lines.append(compare_runs(d, top_dir).strip()) + lines.append("") + return "\n".join(lines) + "\n" diff --git a/evals/driver.py b/evals/driver.py index 9804618..081ba7a 100644 --- a/evals/driver.py +++ b/evals/driver.py @@ -117,6 +117,7 @@ def run_trial( context: int | None = None, mock: bool = False, acp_command: list[str] | None = None, + cli_command: list[str] | None = None, ) -> dict[str, Any]: """Run one isolated trial of `task` and return a structured result dict.""" work_dir = trial_dir / "work" @@ -132,7 +133,9 @@ def run_trial( effective_url = mock_server.url effective_model = "mock-oracle" else: - assert model_url or acp_command, "either --url or --mock or --acp is required" + assert model_url or acp_command or cli_command, ( + "either --url, --gateway, --mock, --acp, or --cli is required" + ) effective_url = model_url or "" effective_model = model_name @@ -143,6 +146,8 @@ def run_trial( cmd = [str(engine_bin)] if acp_command: cmd.extend(["acp", *acp_command]) + elif cli_command: + cmd.extend(["cli", *cli_command]) env = os.environ.copy() env["BATE_WORK_DIR"] = str(work_dir) @@ -219,11 +224,13 @@ def start_session_and_prompt(idx: int) -> None: } ) send({"type": "start", "bot": f"eval-{task.id}"}) - if not acp_command: + if not acp_command and not cli_command: send({"type": "set_model", "model": effective_model}) if fallback_model: send({"type": "fallback_model", "model": fallback_model}) send({"type": "step_limit", "steps": steps}) + elif cli_command and effective_model and effective_model != "default": + send({"type": "set_model", "model": effective_model}) prompt_op: dict[str, Any] = { "type": "prompt", "nonce": f"n{idx + 1}", diff --git a/evals/gateway.py b/evals/gateway.py new file mode 100644 index 0000000..cf18659 --- /dev/null +++ b/evals/gateway.py @@ -0,0 +1,801 @@ +"""Tern-style local model gateway daemon (`serve` + `ctl` Unix control socket). + +Exposes an OpenAI-compatible HTTP endpoint (`/v1/chat/completions`, `/v1/responses`, +`/v1/models`, `/health`) on loopback so Bate's `agentcore` can call ANY backend through +one uniform wire protocol while recording exact latency, token, and error telemetry: + + - `openai` : pass-through to any OpenAI-compatible server (OpenAI, OpenRouter, + Ollama, LM Studio, remote `kiri`, or `omp auth-gateway serve`) + - `anthropic` : translates OpenAI Chat Completions <-> Anthropic `/v1/messages` SSE + (including tool_calls <-> tool_use/tool_result & cache usage) + - `gemini` : translates OpenAI Chat Completions <-> Google Gemini REST API + (including functionCall/functionResponse & usageMetadata) + - `omp` : bridges directly to `omp auth-gateway stdio` (JSON lines over stdio) + - `cli` : raw single-shot CLI completion bridge (`claude -p --tools ""`, etc.) + - `mock` : deterministic local responder for zero-cost testing + +Control socket (`--control /tmp/bate-gw.sock`): + - `status`, `stats`, `route`, `dump`, `stop` +""" + +from __future__ import annotations + +import json +import os +import shutil +import socket +import subprocess +import threading +import time +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + + +@dataclass +class RouteTarget: + backend: str # openai | anthropic | gemini | omp | cli | mock + upstream: str = "" + api_key: str = "" + model_override: str = "" + cli_kind: str = "claude" + cli_bin: str = "" + + +def _default_target(backend: str, upstream: str = "", api_key: str = "") -> RouteTarget: + b = backend.lower() + if b == "anthropic": + return RouteTarget( + backend="anthropic", + upstream=upstream or os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"), + api_key=api_key or os.environ.get("ANTHROPIC_API_KEY", ""), + ) + if b == "gemini": + return RouteTarget( + backend="gemini", + upstream=upstream + or os.environ.get("GEMINI_BASE_URL", "https://generativelanguage.googleapis.com/v1beta"), + api_key=api_key or os.environ.get("GEMINI_API_KEY", ""), + ) + if b == "omp": + return RouteTarget(backend="omp", upstream="stdio://omp-auth-gateway") + if b.startswith("cli:"): + kind = b.split(":", 1)[1] or "claude" + return RouteTarget(backend="cli", cli_kind=kind, cli_bin=upstream or kind) + if b == "cli": + return RouteTarget(backend="cli", cli_kind="claude", cli_bin=upstream or "claude") + if b == "mock": + return RouteTarget(backend="mock", upstream="mock://local") + return RouteTarget( + backend="openai", + upstream=upstream or os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1"), + api_key=api_key or os.environ.get("OPENAI_API_KEY", ""), + ) + + +def openai_to_anthropic(req: dict[str, Any]) -> dict[str, Any]: + """Translate an OpenAI `/v1/chat/completions` body into Anthropic `/v1/messages`.""" + system_parts: list[str] = [] + messages: list[dict[str, Any]] = [] + + def push_blocks(role: str, blocks: list[dict[str, Any]]) -> None: + if not blocks: + return + if messages and messages[-1]["role"] == role: + messages[-1]["content"].extend(blocks) + else: + messages.append({"role": role, "content": blocks}) + + for m in req.get("messages") or []: + role = m.get("role", "user") + content = m.get("content") + text = content if isinstance(content, str) else json.dumps(content) if content is not None else "" + if role == "system": + if text: + system_parts.append(text) + elif role == "tool": + push_blocks( + "user", + [ + { + "type": "tool_result", + "tool_use_id": m.get("tool_call_id", ""), + "content": text, + } + ], + ) + elif role == "assistant": + blocks: list[dict[str, Any]] = [] + if text: + blocks.append({"type": "text", "text": text}) + for tc in m.get("tool_calls") or []: + fn = tc.get("function") or {} + raw_args = fn.get("arguments", "{}") + try: + parsed = json.loads(raw_args) if isinstance(raw_args, str) else raw_args + except json.JSONDecodeError: + parsed = {} + if not isinstance(parsed, dict): + parsed = {} + blocks.append( + { + "type": "tool_use", + "id": tc.get("id") or "toolu_0", + "name": fn.get("name", ""), + "input": parsed, + } + ) + push_blocks("assistant", blocks) + else: + if text: + push_blocks("user", [{"type": "text", "text": text}]) + + body: dict[str, Any] = { + "model": req.get("model", "claude-sonnet-4-5"), + "max_tokens": int(req.get("max_tokens") or 8192), + "messages": messages or [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}], + "stream": bool(req.get("stream", False)), + } + if system_parts: + body["system"] = [ + {"type": "text", "text": "\n\n".join(system_parts), "cache_control": {"type": "ephemeral"}} + ] + tools: list[dict[str, Any]] = [] + for t in req.get("tools") or []: + fn = t.get("function") or {} + tools.append( + { + "name": fn.get("name", ""), + "description": fn.get("description", ""), + "input_schema": fn.get("parameters") or {"type": "object", "properties": {}}, + } + ) + if tools: + tools[-1]["cache_control"] = {"type": "ephemeral"} + body["tools"] = tools + return body + + +def openai_to_gemini(req: dict[str, Any]) -> dict[str, Any]: + """Translate an OpenAI `/v1/chat/completions` body into Google Gemini `generateContent`.""" + system_parts: list[str] = [] + contents: list[dict[str, Any]] = [] + id_to_name: dict[str, str] = {} + + for m in req.get("messages") or []: + role = m.get("role", "user") + content = m.get("content") + text = content if isinstance(content, str) else json.dumps(content) if content is not None else "" + if role == "system": + if text: + system_parts.append(text) + elif role == "assistant": + parts: list[dict[str, Any]] = [] + if text: + parts.append({"text": text}) + for tc in m.get("tool_calls") or []: + fn = tc.get("function") or {} + cid = tc.get("id", "") + name = fn.get("name", "") + if cid: + id_to_name[cid] = name + raw_args = fn.get("arguments", "{}") + try: + parsed = json.loads(raw_args) if isinstance(raw_args, str) else raw_args + except json.JSONDecodeError: + parsed = {} + parts.append({"functionCall": {"name": name, "args": parsed if isinstance(parsed, dict) else {}}}) + if parts: + contents.append({"role": "model", "parts": parts}) + elif role == "tool": + name = id_to_name.get(m.get("tool_call_id", ""), "tool") + contents.append( + { + "role": "user", + "parts": [{"functionResponse": {"name": name, "response": {"output": text}}}], + } + ) + else: + if text: + contents.append({"role": "user", "parts": [{"text": text}]}) + + body: dict[str, Any] = {"contents": contents or [{"role": "user", "parts": [{"text": "Hello"}]}]} + if system_parts: + body["systemInstruction"] = {"parts": [{"text": "\n\n".join(system_parts)}]} + decls = [] + for t in req.get("tools") or []: + fn = t.get("function") or {} + decls.append( + { + "name": fn.get("name", ""), + "description": fn.get("description", ""), + "parameters": fn.get("parameters") or {"type": "object", "properties": {}}, + } + ) + if decls: + body["tools"] = [{"functionDeclarations": decls}] + return body + + +def _openai_sse_from_result( + model: str, + text: str, + tool_calls: list[dict[str, Any]], + tokens_in: int, + tokens_out: int, +) -> bytes: + """Pack a completed text/tool_calls response into OpenAI SSE chunks.""" + chunks: list[bytes] = [] + if text: + chunk = { + "id": "gw-1", + "object": "chat.completion.chunk", + "model": model, + "choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": None}], + } + chunks.append(f"data: {json.dumps(chunk)}\n\n".encode("utf-8")) + if tool_calls: + delta_calls = [] + for idx, tc in enumerate(tool_calls): + delta_calls.append( + { + "index": idx, + "id": tc.get("id", f"call_{idx}"), + "type": "function", + "function": { + "name": tc["name"], + "arguments": json.dumps(tc.get("args", {})), + }, + } + ) + chunk = { + "id": "gw-1", + "object": "chat.completion.chunk", + "model": model, + "choices": [{"index": 0, "delta": {"tool_calls": delta_calls}, "finish_reason": None}], + } + chunks.append(f"data: {json.dumps(chunk)}\n\n".encode("utf-8")) + finish = "tool_calls" if tool_calls else "stop" + end_chunk = { + "id": "gw-1", + "object": "chat.completion.chunk", + "model": model, + "choices": [{"index": 0, "delta": {}, "finish_reason": finish}], + "usage": {"prompt_tokens": tokens_in, "completion_tokens": tokens_out}, + } + chunks.append(f"data: {json.dumps(end_chunk)}\n\n".encode("utf-8")) + chunks.append(b"data: [DONE]\n\n") + return b"".join(chunks) + + +def _openai_json_from_result( + model: str, + text: str, + tool_calls: list[dict[str, Any]], + tokens_in: int, + tokens_out: int, +) -> dict[str, Any]: + msg: dict[str, Any] = {"role": "assistant", "content": text or None} + if tool_calls: + msg["tool_calls"] = [ + { + "id": tc.get("id", f"call_{idx}"), + "type": "function", + "function": {"name": tc["name"], "arguments": json.dumps(tc.get("args", {}))}, + } + for idx, tc in enumerate(tool_calls) + ] + return { + "id": "gw-1", + "object": "chat.completion", + "model": model, + "choices": [{"index": 0, "message": msg, "finish_reason": "tool_calls" if tool_calls else "stop"}], + "usage": {"prompt_tokens": tokens_in, "completion_tokens": tokens_out}, + } + + +def _percentile(values: list[int], pct: float) -> int: + if not values: + return 0 + s = sorted(values) + idx = min(len(s) - 1, max(0, int(round((len(s) - 1) * pct)))) + return s[idx] + + +class GatewayServer: + """Loopback OpenAI-compatible model gateway with Tern-style Unix control socket.""" + + def __init__( + self, + host: str = "127.0.0.1", + port: int = 0, + default_target: RouteTarget | None = None, + routes: dict[str, RouteTarget] | None = None, + control_path: Path | None = None, + trace_path: Path | None = None, + ) -> None: + self.host = host + self.port = port + self.default_target = default_target or _default_target("openai") + self.routes: dict[str, RouteTarget] = dict(routes or {}) + self.control_path = control_path + self.trace_path = trace_path + self._lock = threading.Lock() + self._started = time.monotonic() + self._traces: list[dict[str, Any]] = [] + self._stop_event = threading.Event() + self._httpd: ThreadingHTTPServer | None = None + self._ctl_sock: socket.socket | None = None + self._threads: list[threading.Thread] = [] + self._omp_proc: subprocess.Popen[str] | None = None + self._omp_lock = threading.Lock() + self._omp_req_id = 0 + + def resolve_route(self, model: str) -> RouteTarget: + with self._lock: + # Longest prefix match wins. + for prefix in sorted(self.routes, key=len, reverse=True): + if model.startswith(prefix): + return self.routes[prefix] + return self.default_target + + def record(self, entry: dict[str, Any]) -> None: + with self._lock: + self._traces.append(entry) + if len(self._traces) > 500: + self._traces = self._traces[-500:] + if self.trace_path: + self.trace_path.parent.mkdir(parents=True, exist_ok=True) + with self.trace_path.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry) + "\n") + + def status_snapshot(self) -> dict[str, Any]: + with self._lock: + latencies = [int(t.get("latency_ms", 0)) for t in self._traces] + return { + "ok": True, + "url": self.base_url, + "uptime_s": round(time.monotonic() - self._started, 2), + "default_backend": self.default_target.backend, + "default_upstream": self.default_target.upstream, + "routes": { + k: {"backend": v.backend, "upstream": v.upstream, "model_override": v.model_override} + for k, v in self.routes.items() + }, + "requests": len(self._traces), + "errors": sum(1 for t in self._traces if int(t.get("status", 200)) >= 400), + "tokens_in": sum(int(t.get("tokens_in", 0)) for t in self._traces), + "tokens_out": sum(int(t.get("tokens_out", 0)) for t in self._traces), + "p50_ms": _percentile(latencies, 0.50), + "p95_ms": _percentile(latencies, 0.95), + } + + def stats_by_model(self) -> dict[str, Any]: + with self._lock: + grouped: dict[str, dict[str, Any]] = {} + for t in self._traces: + m = str(t.get("model", "unknown")) + g = grouped.setdefault( + m, + {"requests": 0, "errors": 0, "tokens_in": 0, "tokens_out": 0, "latencies": []}, + ) + g["requests"] += 1 + if int(t.get("status", 200)) >= 400: + g["errors"] += 1 + g["tokens_in"] += int(t.get("tokens_in", 0)) + g["tokens_out"] += int(t.get("tokens_out", 0)) + g["latencies"].append(int(t.get("latency_ms", 0))) + out = {} + for m, g in grouped.items(): + lats = g.pop("latencies") + g["avg_ms"] = round(sum(lats) / len(lats), 1) if lats else 0.0 + g["p95_ms"] = _percentile(lats, 0.95) + out[m] = g + return {"ok": True, "models": out} + + def handle_ctl(self, cmd: dict[str, Any]) -> dict[str, Any]: + op = cmd.get("cmd", "") + if op == "status": + return self.status_snapshot() + if op == "stats": + return self.stats_by_model() + if op == "dump": + n = int(cmd.get("limit") or 20) + with self._lock: + return {"ok": True, "traces": self._traces[-n:]} + if op == "route": + prefix = str(cmd.get("prefix", "")) + backend = str(cmd.get("backend", "openai")) + target = _default_target( + backend, + upstream=str(cmd.get("upstream", "")), + api_key=str(cmd.get("api_key", "")), + ) + target.model_override = str(cmd.get("model", "")) + with self._lock: + if prefix: + self.routes[prefix] = target + else: + self.default_target = target + return {"ok": True, "prefix": prefix or "*", "backend": target.backend} + if op == "stop": + threading.Thread(target=self.stop, daemon=True).start() + return {"ok": True, "stopping": True} + return {"ok": False, "error": f"unknown ctl command `{op}`"} + + @property + def base_url(self) -> str: + return f"http://{self.host}:{self.port}/v1" + + def _call_omp_stdio(self, path: str, body: dict[str, Any]) -> tuple[int, dict[str, Any]]: + with self._omp_lock: + if self._omp_proc is None or self._omp_proc.poll() is not None: + omp_bin = shutil.which("omp") or "omp" + self._omp_proc = subprocess.Popen( + [omp_bin, "auth-gateway", "stdio"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + bufsize=1, + ) + assert self._omp_proc.stdin is not None and self._omp_proc.stdout is not None + self._omp_req_id += 1 + req_frame = {"id": self._omp_req_id, "path": path, "body": {**body, "stream": False}} + self._omp_proc.stdin.write(json.dumps(req_frame) + "\n") + self._omp_proc.stdin.flush() + line = self._omp_proc.stdout.readline() + if not line: + return 502, {"error": {"message": "omp auth-gateway stdio closed unexpectedly"}} + resp = json.loads(line) + status = int(resp.get("status", 200)) + payload = resp.get("body", resp) + if isinstance(payload, str): + try: + payload = json.loads(payload) + except json.JSONDecodeError: + payload = {"error": {"message": payload}} + return status, payload if isinstance(payload, dict) else {"data": payload} + + def _dispatch_chat( + self, req_body: dict[str, Any], target: RouteTarget + ) -> tuple[int, str, bytes, int, int]: + """Return (status_code, content_type, body_bytes, tokens_in, tokens_out).""" + model = target.model_override or str(req_body.get("model", "default")) + stream = bool(req_body.get("stream", False)) + forwarded = {**req_body, "model": model} + + if target.backend == "mock": + msgs = req_body.get("messages") or [] + last_user = next((m.get("content", "") for m in reversed(msgs) if m.get("role") == "user"), "") + reply_text = f"mock-gateway({model}): {str(last_user)[:80]}" + if stream: + return 200, "text/event-stream", _openai_sse_from_result(model, reply_text, [], 64, 16), 64, 16 + payload = _openai_json_from_result(model, reply_text, [], 64, 16) + return 200, "application/json", json.dumps(payload).encode("utf-8"), 64, 16 + + if target.backend == "openai": + url = f"{target.upstream.rstrip('/')}/chat/completions" + headers = {"Content-Type": "application/json"} + if target.api_key: + headers["Authorization"] = f"Bearer {target.api_key}" + http_req = urllib.request.Request( + url, data=json.dumps(forwarded).encode("utf-8"), headers=headers, method="POST" + ) + try: + with urllib.request.urlopen(http_req, timeout=180) as resp: + raw = resp.read() + ct = resp.headers.get("Content-Type", "application/json") + tin, tout = _extract_usage_from_openai_bytes(raw) + return resp.status, ct, raw, tin, tout + except urllib.error.HTTPError as e: + raw = e.read() + return e.code, "application/json", raw, 0, 0 + + if target.backend == "anthropic": + ant_body = openai_to_anthropic({**forwarded, "stream": False}) + base = target.upstream.rstrip("/") + url = base if base.endswith("/messages") else (f"{base}/messages" if base.endswith("/v1") else f"{base}/v1/messages") + headers = { + "Content-Type": "application/json", + "anthropic-version": "2023-06-01", + } + if target.api_key: + headers["x-api-key"] = target.api_key + http_req = urllib.request.Request( + url, data=json.dumps(ant_body).encode("utf-8"), headers=headers, method="POST" + ) + try: + with urllib.request.urlopen(http_req, timeout=180) as resp: + data = json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + return e.code, "application/json", e.read(), 0, 0 + text_parts: list[str] = [] + tool_calls: list[dict[str, Any]] = [] + for blk in data.get("content") or []: + if blk.get("type") == "text": + text_parts.append(blk.get("text", "")) + elif blk.get("type") == "tool_use": + tool_calls.append( + {"id": blk.get("id", ""), "name": blk.get("name", ""), "args": blk.get("input", {})} + ) + usage = data.get("usage") or {} + tin = int(usage.get("input_tokens", 0)) + int(usage.get("cache_read_input_tokens", 0)) + int(usage.get("cache_creation_input_tokens", 0)) + tout = int(usage.get("output_tokens", 0)) + text = "".join(text_parts) + if stream: + return 200, "text/event-stream", _openai_sse_from_result(model, text, tool_calls, tin, tout), tin, tout + payload = _openai_json_from_result(model, text, tool_calls, tin, tout) + return 200, "application/json", json.dumps(payload).encode("utf-8"), tin, tout + + if target.backend == "gemini": + gem_body = openai_to_gemini(forwarded) + base = target.upstream.rstrip("/") + url = f"{base}/models/{model}:generateContent" + if target.api_key: + url = f"{url}?key={target.api_key}" + http_req = urllib.request.Request( + url, + data=json.dumps(gem_body).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(http_req, timeout=180) as resp: + data = json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + return e.code, "application/json", e.read(), 0, 0 + text_parts = [] + tool_calls = [] + cands = data.get("candidates") or [] + if cands: + for idx, part in enumerate((cands[0].get("content") or {}).get("parts") or []): + if "text" in part: + text_parts.append(part["text"]) + elif "functionCall" in part: + fc = part["functionCall"] + tool_calls.append( + {"id": f"gem_{idx}", "name": fc.get("name", ""), "args": fc.get("args", {})} + ) + um = data.get("usageMetadata") or {} + tin = int(um.get("promptTokenCount", 0)) + tout = int(um.get("candidatesTokenCount", 0)) + text = "".join(text_parts) + if stream: + return 200, "text/event-stream", _openai_sse_from_result(model, text, tool_calls, tin, tout), tin, tout + payload = _openai_json_from_result(model, text, tool_calls, tin, tout) + return 200, "application/json", json.dumps(payload).encode("utf-8"), tin, tout + + if target.backend == "omp": + status, payload = self._call_omp_stdio("/v1/chat/completions", forwarded) + if status >= 400: + return status, "application/json", json.dumps(payload).encode("utf-8"), 0, 0 + u = payload.get("usage") or {} + tin = int(u.get("prompt_tokens", 0)) + tout = int(u.get("completion_tokens", 0)) + if stream: + choice = (payload.get("choices") or [{}])[0] + msg = choice.get("message") or {} + tcs = [] + for tc in msg.get("tool_calls") or []: + fn = tc.get("function") or {} + try: + parsed = json.loads(fn.get("arguments", "{}")) + except json.JSONDecodeError: + parsed = {} + tcs.append({"id": tc.get("id", ""), "name": fn.get("name", ""), "args": parsed}) + raw = _openai_sse_from_result(model, msg.get("content") or "", tcs, tin, tout) + return 200, "text/event-stream", raw, tin, tout + return 200, "application/json", json.dumps(payload).encode("utf-8"), tin, tout + + if target.backend == "cli": + # Raw single-shot text completion via installed CLI (tools disabled). + transcript = "\n".join( + f"[{m.get('role', 'user')}]: {m.get('content', '')}" for m in (req_body.get("messages") or []) + ) + bin_path = target.cli_bin or target.cli_kind + if target.cli_kind == "claude": + cmd = [bin_path, "-p", transcript, "--tools", "", "--output-format", "json"] + if model and model != "default": + cmd.extend(["--model", model]) + else: + cmd = [bin_path, "-p", "--no-tools", "--mode", "json", transcript] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + if proc.returncode != 0: + err_payload = {"error": {"message": (proc.stderr or proc.stdout).strip()[:500]}} + return 502, "application/json", json.dumps(err_payload).encode("utf-8"), 0, 0 + text = proc.stdout.strip() + tin = tout = 0 + try: + parsed = json.loads(text) + if isinstance(parsed, dict) and "result" in parsed: + text = str(parsed["result"]) + u = parsed.get("usage") or {} + tin = int(u.get("input_tokens", 0)) + tout = int(u.get("output_tokens", 0)) + except json.JSONDecodeError: + pass + if stream: + return 200, "text/event-stream", _openai_sse_from_result(model, text, [], tin, tout), tin, tout + payload = _openai_json_from_result(model, text, [], tin, tout) + return 200, "application/json", json.dumps(payload).encode("utf-8"), tin, tout + + return 400, "application/json", json.dumps({"error": {"message": f"unknown backend {target.backend}"}}).encode(), 0, 0 + + def start(self) -> None: + gw = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, fmt: str, *args: Any) -> None: + return + + def _send(self, code: int, content_type: str, body: bytes) -> None: + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(body) + + def do_GET(self) -> None: + if self.path == "/health": + self._send(200, "application/json", json.dumps(gw.status_snapshot()).encode("utf-8")) + return + if self.path.rstrip("/") in ("/v1/models", "/models"): + models = [{"id": k, "object": "model"} for k in gw.routes] or [ + {"id": gw.default_target.model_override or "default", "object": "model"} + ] + self._send(200, "application/json", json.dumps({"object": "list", "data": models}).encode("utf-8")) + return + self._send(404, "application/json", b'{"error":"not found"}') + + def do_POST(self) -> None: + n = int(self.headers.get("Content-Length", "0")) + raw = self.rfile.read(n) + try: + body = json.loads(raw.decode("utf-8")) + except Exception as e: + self._send(400, "application/json", json.dumps({"error": {"message": str(e)}}).encode("utf-8")) + return + model = str(body.get("model", "default")) + target = gw.resolve_route(model) + t0 = time.monotonic() + + if self.path.rstrip("/").endswith("/responses") and target.backend == "openai": + url = f"{target.upstream.rstrip('/')}/responses" + headers = {"Content-Type": "application/json"} + if target.api_key: + headers["Authorization"] = f"Bearer {target.api_key}" + req = urllib.request.Request(url, data=raw, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=180) as resp: + out_raw = resp.read() + code = resp.status + ct = resp.headers.get("Content-Type", "application/json") + except urllib.error.HTTPError as e: + out_raw = e.read() + code = e.code + ct = "application/json" + tin, tout = _extract_usage_from_openai_bytes(out_raw) + else: + code, ct, out_raw, tin, tout = gw._dispatch_chat(body, target) + + lat_ms = int((time.monotonic() - t0) * 1000) + gw.record( + { + "ts": round(time.time(), 3), + "path": self.path, + "model": model, + "backend": target.backend, + "status": code, + "latency_ms": lat_ms, + "tokens_in": tin, + "tokens_out": tout, + } + ) + self._send(code, ct, out_raw) + + self._httpd = ThreadingHTTPServer((self.host, self.port), Handler) + self.port = int(self._httpd.server_address[1]) + t_http = threading.Thread(target=self._httpd.serve_forever, daemon=True) + t_http.start() + self._threads.append(t_http) + + if self.control_path: + if self.control_path.exists(): + self.control_path.unlink() + self.control_path.parent.mkdir(parents=True, exist_ok=True) + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.bind(str(self.control_path)) + sock.listen(16) + sock.settimeout(0.25) + self._ctl_sock = sock + t_ctl = threading.Thread(target=self._serve_ctl, daemon=True) + t_ctl.start() + self._threads.append(t_ctl) + + def _serve_ctl(self) -> None: + assert self._ctl_sock is not None + while not self._stop_event.is_set(): + try: + conn, _ = self._ctl_sock.accept() + except TimeoutError: + continue + except OSError: + break + with conn: + try: + data = conn.recv(65536).decode("utf-8").strip() + req = json.loads(data) if data else {} + resp = self.handle_ctl(req) + except Exception as e: + resp = {"ok": False, "error": str(e)} + conn.sendall((json.dumps(resp) + "\n").encode("utf-8")) + + def wait_forever(self) -> None: + try: + while not self._stop_event.is_set(): + time.sleep(0.2) + except KeyboardInterrupt: + self.stop() + + def stop(self) -> None: + self._stop_event.set() + if self._httpd: + self._httpd.shutdown() + self._httpd.server_close() + self._httpd = None + if self._ctl_sock: + try: + self._ctl_sock.close() + except OSError: + pass + self._ctl_sock = None + if self.control_path and self.control_path.exists(): + try: + self.control_path.unlink() + except OSError: + pass + if self._omp_proc and self._omp_proc.poll() is None: + self._omp_proc.terminate() + self._omp_proc = None + + +def send_ctl(control_path: Path, payload: dict[str, Any], timeout: float = 5.0) -> dict[str, Any]: + """Send one JSON command to a running GatewayServer over its Unix control socket.""" + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: + s.settimeout(timeout) + s.connect(str(control_path)) + s.sendall((json.dumps(payload) + "\n").encode("utf-8")) + chunks: list[bytes] = [] + while True: + part = s.recv(65536) + if not part: + break + chunks.append(part) + if b"\n" in part: + break + return json.loads(b"".join(chunks).decode("utf-8").strip()) + + +def _extract_usage_from_openai_bytes(raw: bytes) -> tuple[int, int]: + tin = tout = 0 + text = raw.decode("utf-8", errors="ignore") + for line in text.splitlines(): + s = line.strip() + if s.startswith("data:"): + s = s[5:].strip() + if not s or s == "[DONE]" or not s.startswith("{"): + continue + try: + obj = json.loads(s) + except json.JSONDecodeError: + continue + u = obj.get("usage") or (obj.get("response") or {}).get("usage") + if isinstance(u, dict): + tin = int(u.get("prompt_tokens") or u.get("input_tokens") or tin) + tout = int(u.get("completion_tokens") or u.get("output_tokens") or tout) + return tin, tout diff --git a/evals/run.py b/evals/run.py index a09d774..111a63a 100644 --- a/evals/run.py +++ b/evals/run.py @@ -1,30 +1,50 @@ #!/usr/bin/env python3 -"""Bate AgentCore Local Eval Suite CLI. +"""Bate AgentCore Local Eval Suite & Tern-Style Model Gateway CLI. Examples: - # Self-test all 16 tasks against real compiled agentcore using the built-in mock LLM (0 API cost): + # Discover all installed CLIs, gateways, and API keys on this machine: + python3 evals/run.py discover + + # Self-test all 16 tasks against real compiled agentcore using built-in mock LLM (0 API cost): python3 evals/run.py --mock --engine target/debug/agentcore --out /tmp/bate-eval-mock - # Run live against any OpenAI-compatible model endpoint: - python3 evals/run.py --url http://127.0.0.1:4100/v1 --model gpt-5.4 --k 1 --out evals/runs/main + # Run live against OpenAI / OpenRouter / omp auth-gateway / native Anthropic: + python3 evals/run.py --url https://api.anthropic.com/v1 --api anthropic --model claude-sonnet-4-5 --out /tmp/eval-ant + + # Run via embedded Tern-style gateway (translates Anthropic / Gemini / omp stdio / CLI): + python3 evals/run.py --gateway anthropic --model claude-sonnet-4-5 --out /tmp/eval-gw + + # Run installed CLIs directly through `agentcore cli ` or `agentcore acp `: + python3 evals/run.py --cli claude --out /tmp/eval-claude + python3 evals/run.py --cli codex --out /tmp/eval-codex + python3 evals/run.py --acp "opencode acp" --out /tmp/eval-opencode - # Compare two runs (paired McNemar exact test + token/tool deltas): - python3 evals/run.py compare evals/runs/base evals/runs/main + # Start / control the standalone Tern-style model gateway daemon: + python3 evals/run.py gateway serve --bind 127.0.0.1:4100 --control /tmp/bate-gw.sock --backend omp + python3 evals/run.py gateway ctl --control /tmp/bate-gw.sock status + + # Multi-backend matrix + ranked leaderboard + McNemar comparisons: + python3 evals/run.py matrix --spec mock=mock --spec claude=cli:claude --spec codex=cli:codex --out /tmp/eval-matrix + python3 evals/run.py compare /tmp/eval-a /tmp/eval-b """ from __future__ import annotations import argparse +import json import os import shlex import shutil +import socket import sys from pathlib import Path +from typing import Any sys.path.insert(0, str(Path(__file__).resolve().parent)) -from analyze import compare_runs, enrich_run +from analyze import compare_runs, enrich_run, leaderboard from driver import run_trial +from gateway import GatewayServer, _default_target, send_ctl from tasks import all_tasks @@ -42,39 +62,313 @@ def _default_engine() -> Path: return repo / "target" / "debug" / "agentcore" -def main() -> int: - if len(sys.argv) >= 2 and sys.argv[1] == "analyze": - if len(sys.argv) < 3: - print("Usage: run.py analyze ", file=sys.stderr) - return 2 - rep = enrich_run(Path(sys.argv[2])) - print(rep["summary_md"]) +def _tcp_open(host: str, port: int, timeout: float = 0.4) -> bool: + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +def _cmd_discover() -> int: + engine = _default_engine() + clis = ["claude", "codex", "opencode", "pi", "omp", "tern", "ollama", "claude-agent-acp", "codex-acp"] + endpoints = [ + ("omp auth-gateway (127.0.0.1:4100)", "127.0.0.1", 4100), + ("LM Studio (127.0.0.1:1234)", "127.0.0.1", 1234), + ("Ollama (127.0.0.1:11434)", "127.0.0.1", 11434), + ] + env_keys = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY", "BATE_EVAL_API_KEY"] + + print("# Bate AgentCore Benchmark Backend Discovery\n") + print(f"- **agentcore binary**: `{engine}` ({'found' if engine.exists() else 'not built yet — run `cargo build -p agentcore`'})") + print("\n## Installed CLIs") + for name in clis: + path = shutil.which(name) + status = f"`{path}`" if path else "not installed" + print(f"- `{name}`: {status}") + print("\n## Local Model Endpoints") + for label, host, port in endpoints: + print(f"- {label}: {'UP' if _tcp_open(host, port) else 'down'}") + print("\n## API Key Environment Variables (presence only)") + for k in env_keys: + print(f"- `{k}`: {'set' if os.environ.get(k) else 'unset'}") + return 0 + + +def _cmd_gateway(argv: list[str]) -> int: + gp = argparse.ArgumentParser(prog="run.py gateway", description="Tern-style local model gateway daemon.") + sub = gp.add_subparsers(dest="action", required=True) + + sp = sub.add_parser("serve", help="Start the loopback model gateway HTTP + Unix control server.") + sp.add_argument("--bind", default="127.0.0.1:4100", help="Listen host:port (default 127.0.0.1:4100).") + sp.add_argument("--control", type=Path, default=Path("/tmp/bate-gw.sock"), help="Unix control socket path.") + sp.add_argument( + "--backend", + default="openai", + help="Default backend: openai | anthropic | gemini | omp | cli | cli: | mock.", + ) + sp.add_argument("--upstream", default="", help="Upstream base URL or CLI binary path.") + sp.add_argument("--api-key", default="", help="Upstream API key (optional; defaults to env).") + sp.add_argument("--trace", type=Path, default=None, help="Optional JSONL trace output path.") + + cp = sub.add_parser("ctl", help="Send a control command to a running gateway.") + cp.add_argument("--control", type=Path, default=Path("/tmp/bate-gw.sock"), help="Unix control socket path.") + cp.add_argument("cmd", choices=["status", "stats", "dump", "route", "stop"], help="Control command.") + cp.add_argument("rest", nargs="*", help="Arguments for `route [upstream]` or `dump [limit]`.") + + args = gp.parse_args(argv) + if args.action == "serve": + host, _, port_s = args.bind.rpartition(":") + host = host or "127.0.0.1" + port = int(port_s) if port_s else 4100 + target = _default_target(args.backend, upstream=args.upstream, api_key=args.api_key) + gw = GatewayServer( + host=host, + port=port, + default_target=target, + control_path=args.control, + trace_path=args.trace, + ) + gw.start() + print( + json.dumps({"listening": gw.base_url, "control": str(args.control), "backend": target.backend}), + flush=True, + ) + gw.wait_forever() return 0 - if len(sys.argv) >= 2 and sys.argv[1] == "compare": - if len(sys.argv) < 4: - print("Usage: run.py compare ", file=sys.stderr) + payload: dict[str, Any] = {"cmd": args.cmd} + if args.cmd == "dump" and args.rest: + payload["limit"] = int(args.rest[0]) + elif args.cmd == "route": + if len(args.rest) < 2: + print("Usage: gateway ctl route [upstream] [model_override]", file=sys.stderr) return 2 - print(compare_runs(Path(sys.argv[2]), Path(sys.argv[3]))) - return 0 + payload["prefix"] = "" if args.rest[0] == "*" else args.rest[0] + payload["backend"] = args.rest[1] + if len(args.rest) >= 3: + payload["upstream"] = args.rest[2] + if len(args.rest) >= 4: + payload["model"] = args.rest[3] + resp = send_ctl(args.control, payload) + print(json.dumps(resp, indent=2)) + return 0 if resp.get("ok") else 1 + + +def _run_suite( + tasks: list[Any], + out_dir: Path, + *, + engine: Path, + url: str | None, + model: str, + api_key: str | None, + api_style: str | None, + fallback_model: str | None, + k: int, + steps: int, + timeout: int, + context: int | None, + check: bool, + mock: bool, + acp_cmd: list[str] | None, + cli_cmd: list[str] | None, + gateway_backend: str | None = None, + gateway_upstream: str = "", +) -> dict[str, Any]: + out_dir.mkdir(parents=True, exist_ok=True) + gw: GatewayServer | None = None + effective_url = url + if gateway_backend: + target = _default_target(gateway_backend, upstream=gateway_upstream, api_key=api_key or "") + gw = GatewayServer( + host="127.0.0.1", + port=0, + default_target=target, + trace_path=out_dir / "gateway_trace.jsonl", + ) + gw.start() + effective_url = gw.base_url + + try: + for task in tasks: + for trial_idx in range(1, k + 1): + trial_dir = out_dir / task.id / f"t{trial_idx}" + if trial_dir.exists(): + shutil.rmtree(trial_dir) + res = run_trial( + task, + trial_dir, + engine_bin=engine.resolve(), + model_url=effective_url, + model_name=model, + api_key=None if gw else api_key, + api_style=None if gw else api_style, + fallback_model=fallback_model, + steps=steps, + timeout_s=timeout, + check=check, + context=context, + mock=mock, + acp_command=acp_cmd, + cli_command=cli_cmd, + ) + status = "PASS" if res["passed"] else "FAIL" + print( + f"[{status}] {task.id} (t{trial_idx}) {res['wall_ms']}ms — {res['verify_detail'][:90]}", + flush=True, + ) + finally: + if gw: + gw.stop() + + return enrich_run(out_dir) + + +def _cmd_matrix(argv: list[str]) -> int: + mp = argparse.ArgumentParser(prog="run.py matrix", description="Run multi-backend matrix and emit leaderboard.") + mp.add_argument( + "--spec", + action="append", + required=True, + help="Backend spec `