// Claude Code as a model: the person's own `claude` command, signed in with their Claude // subscription (no API key), run once per model step. AnyBot keeps its tool loop. The CLI gets // no tools of its own (`--tools ""`), so the model asks for AnyBot's tools in its answer, and // AnyBot runs them through its usual gate (rules, approvals, the 安全規則) like any other // provider's tool calls. Nothing about approvals changes here. // // The answer is forced into `{text, tool_calls}` (`--json-schema`) and read from the CLI's // `structured_output`. The CLI doesn't stream here: the words arrive when the step is done. use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; use serde_json::{json, Value}; use crate::model::{Message, Role, ToolCall, ToolStatus}; use crate::providers::{self, ChatRequest, Failure, StepOutput, StreamEvent, Usage}; /// A step that runs longer than this is stopped. const STEP_TIMEOUT: Duration = Duration::from_secs(15 * 60); /// How often a waiting step tells the agent it is alive (the stall watchdog waits 35 s). const ALIVE_EVERY: Duration = Duration::from_secs(1); /// The model when a bot names none: the CLI's own alias for the newest Sonnet. const DEFAULT_MODEL: &str = "sonnet"; /// The aliases the CLI takes; each follows the newest model of its family. pub const MODELS: [&str; 3] = ["opus", "sonnet", "haiku"]; const CLI_NAME: &str = if cfg!(windows) { "claude.exe" } else { "claude" }; /// The answer shape: the words, and the tools the model asks AnyBot to run. `arguments` is JSON /// text, the way AnyBot keeps a call's arguments. const ANSWER_SCHEMA: &str = r#"{"type":"object","properties":{"text":{"type":"string"},"tool_calls":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"arguments":{"type":"string"}},"required":["name","arguments"]}}},"required":["text","tool_calls"]}"#; static CALL_SEQ: AtomicU64 = AtomicU64::new(0); #[cfg(test)] static CLI_FOR_TESTS: Mutex> = Mutex::new(None); #[cfg(test)] fn test_cli() -> Option { CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()).clone() } #[cfg(not(test))] fn test_cli() -> Option { None } /// The `claude` command the app can run: searched in the same places a shell would find it (a /// Mac app started from Finder has no shell PATH; `cloudbox::tool_path` adds the usual places). pub fn cli_path() -> Option { if let Some(p) = test_cli() { return Some(p); } // For the verify harness only: a path given here is the command, and a path that is not a file // means "not installed", whatever this machine has (scratch's login shell finds the real one). if let Some(v) = std::env::var_os("ANYBOT_CLAUDE_CLI") { let p = PathBuf::from(v); return p.is_file().then_some(p); } std::env::split_paths(&crate::cloudbox::tool_path()).map(|d| d.join(CLI_NAME)).find(|p| p.is_file()) } /// Whether the command is installed. (Being signed in is only known when a step runs.) pub fn installed() -> bool { cli_path().is_some() } /// Looks for the command once on a background thread at start, so the first frame of the settings /// page doesn't wait on the login shell. pub fn warm() { std::thread::spawn(|| { let _ = cli_path(); }); } /// The system prompt for the step: the bot's own words, the earlier summaries, then the tools the /// model may ask for and the answer's shape. The tools' own definitions go in as they are. fn system_prompt(req: &ChatRequest) -> String { let mut s = providers::system_with_summaries(req); if !req.tools.is_empty() { s.push_str("\n\n# 工具\n\n你不能自己執行工具。要用的時候,在回覆的 tool_calls 列出工具名稱和參數(arguments 是 JSON 文字);AnyBot 會執行,再把結果放進下一輪的對話給你。"); for t in &req.tools { s.push_str(&format!( "\n\n## {}\n{}\n參數(JSON Schema):{}", t["name"].as_str().unwrap_or(""), t["description"].as_str().unwrap_or(""), t["parameters"] )); } } s.push_str("\n\n# 回覆格式\n\n每次都只回一個 JSON 物件:text 是要給使用者看的話(沒有就空字串),tool_calls 是要執行的工具(沒有就空陣列)。"); s } /// The conversation as one user message: each earlier message labelled, pictures after the text /// (the person's own, and the kept screenshots of tool results). The last line asks for the next /// reply, so the answer is a reply, not a continuation of the transcript. fn input_line(req: &ChatRequest) -> String { let mut text = String::new(); let mut images: Vec = vec![]; let kept = providers::kept_images(&req.history); let picture = |images: &mut Vec, b: &String| { images.push(b.clone()); format!("(附圖 {})", images.len()) }; for (i, m) in req.history.iter().enumerate().filter(|(_, m)| !m.summary) { match m.role { Role::User => { let mut line = if m.context.is_empty() { m.text.clone() } else { format!("{}\n\n{}", m.text, m.context) }; for b in &m.images { line.push_str(&picture(&mut images, b)); } text.push_str(&format!("【使用者】\n{line}\n\n")); } Role::Assistant => { if m.error && m.tool_calls.is_empty() { continue; } if !m.text.is_empty() { text.push_str(&format!("【你】\n{}\n\n", m.text)); } for c in &m.tool_calls { text.push_str(&format!("【你呼叫了工具 {}(id {})】參數:{}\n\n", c.name, c.id, c.args.trim())); } } Role::Tool => { let mut line = m.text.clone(); if !m.images.is_empty() && kept.contains(&i) { for b in &m.images { line.push_str(&picture(&mut images, b)); } } text.push_str(&format!("【工具結果(id {})】\n{line}\n\n", m.tool_call_id)); } } } text.push_str("請依上面的對話,回覆你的下一則(JSON 格式)。"); let mut content = vec![json!({"type": "text", "text": text})]; content.extend(images.iter().map(|b| json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": b}}))); json!({"type": "user", "message": {"role": "user", "content": content}}).to_string() } /// The command-line flags for one step. The CLI runs with no tools, no MCP servers, no settings /// from the person's user folder and no session saved: the only thing it does is answer. fn args(req: &ChatRequest, system_file: &Path) -> Vec { let model = if req.model.trim().is_empty() { DEFAULT_MODEL } else { req.model.trim() }; let mut a: Vec = [ "-p", "--input-format", "stream-json", // Stream-json in and out go together; the answer is the last `result` line. "--output-format", "stream-json", "--verbose", "--tools", "", "--strict-mcp-config", "--setting-sources", "project", "--no-session-persistence", ] .map(String::from) .to_vec(); a.extend(["--system-prompt-file".into(), system_file.display().to_string()]); a.extend(["--json-schema".into(), ANSWER_SCHEMA.into()]); a.extend(["--model".into(), model.into()]); if matches!(req.effort.as_str(), "low" | "medium" | "high") { a.extend(["--effort".into(), req.effort.clone()]); } a } /// What a failed step says, in words the person can act on. "已達用量上限" at the start is what /// AnyBot's 備用模型 switch looks for. fn failure_of(detail: &str) -> Failure { let d = detail.trim(); let low = d.to_lowercase(); if low.contains("not logged in") || low.contains("/login") || (low.contains("please run") && low.contains("login")) { return Failure::fatal("Claude Code 還沒有登入。請在這台電腦執行 claude auth login,用你的 Claude 帳號登入。".into()); } if low.contains("usage limit") || low.contains("rate limit") || low.contains("limit reached") { return Failure::fatal(format!("已達用量上限(Claude Code):{d}")); } Failure::fatal(format!("Claude Code 出錯:{}", if d.is_empty() { "沒有說明" } else { d })) } /// The tool calls and words in the CLI's answer. `structured_output` is the schema's object; a /// result that is only text (no structured answer) is taken as the words. fn parse_answer(v: &Value) -> Result<(String, Vec), Failure> { let structured = v.get("structured_output").filter(|s| s.is_object()).cloned().or_else(|| v["result"].as_str().and_then(|r| serde_json::from_str::(r).ok()).filter(Value::is_object)); let Some(s) = structured else { return Ok((v["result"].as_str().unwrap_or("").to_string(), vec![])); }; let text = s["text"].as_str().unwrap_or("").to_string(); let mut calls = vec![]; for c in s["tool_calls"].as_array().map(Vec::as_slice).unwrap_or(&[]) { let name = c["name"].as_str().unwrap_or("").trim().to_string(); if name.is_empty() { continue; } let args = match &c["arguments"] { Value::String(a) if !a.trim().is_empty() => a.trim().to_string(), Value::Object(_) => c["arguments"].to_string(), _ => "{}".into(), }; let n = CALL_SEQ.fetch_add(1, Ordering::Relaxed); calls.push(ToolCall { id: format!("cc{n}"), name, args, status: ToolStatus::Waiting }); } Ok((text, calls)) } /// The CLI's final answer. With stream-json output it prints one JSON line per event and the /// `result` line comes last; a single JSON object is taken as it is. fn answer_of(stdout: &str) -> Option { if let Ok(v) = serde_json::from_str::(stdout.trim()) { return Some(v); } stdout.lines().rev().filter_map(|l| serde_json::from_str::(l.trim()).ok()).find(|v| v["type"].as_str() == Some("result")) } fn usage_of(v: &Value) -> Usage { let g = |k: &str| v["usage"][k].as_u64().unwrap_or(0); // The CLI's own dollar figure is a list-price estimate, not a bill (a subscription pays none): left at zero. Usage { input: g("input_tokens"), output: g("output_tokens"), cache_read: g("cache_read_input_tokens"), cache_write: g("cache_creation_input_tokens"), cost_micros: 0 } } /// One model step through the local `claude` command. Cancelling kills it and gives back nothing /// (as the other providers do). pub fn run(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { let Some(cli) = cli_path() else { return Err(Failure::fatal("找不到 Claude Code(claude 指令)。請先安裝 Claude Code,再重新開啟 AnyBot。".into())); }; let work = std::env::temp_dir().join("anybot-claude-code"); std::fs::create_dir_all(&work).map_err(|e| Failure::fatal(format!("Claude Code 的工作資料夾開不了:{e}")))?; // The system prompt carries the bot's words and memory: a file only the person can read, // not the command line (which `ps` shows). let seq = CALL_SEQ.fetch_add(1, Ordering::Relaxed); let system_file = work.join(format!("system-{}-{seq}.txt", std::process::id())); std::fs::write(&system_file, system_prompt(req)).map_err(|e| Failure::fatal(format!("Claude Code 的設定檔寫不了:{e}")))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&system_file, std::fs::Permissions::from_mode(0o600)); } let outcome = run_child(&cli, &work, &args(req, &system_file), input_line(req), cancel, send); let _ = std::fs::remove_file(&system_file); let (ok, stdout, stderr) = outcome?; let Some(stdout) = stdout else { // Cancelled: the answer is not wanted. return Ok(StepOutput::default()); }; let v: Value = answer_of(&stdout).ok_or_else(|| { let seen = if stdout.trim().is_empty() { stderr.trim() } else { stdout.trim() }; Failure::fatal(format!("Claude Code 回了看不懂的內容:{}", seen.chars().take(300).collect::())) })?; let is_error = v["is_error"].as_bool().unwrap_or(false) || v.get("subtype").is_some_and(|s| s.as_str() != Some("success")); if is_error || !ok { let detail = v["result"].as_str().map(str::to_string).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| stderr.trim().to_string()); return Err(failure_of(&detail)); } let (text, tool_calls) = parse_answer(&v)?; if !text.is_empty() { send(StreamEvent::Text(text.clone())); } for call in &tool_calls { send(StreamEvent::ToolCall(call.clone())); } Ok(StepOutput { text, tool_calls, usage: usage_of(&v), ..StepOutput::default() }) } /// Runs the command with the prompt on stdin. Returns (exited ok, stdout, stderr); stdout is None /// when the step was cancelled. Alive is sent while it runs. fn run_child(cli: &Path, work: &Path, args: &[String], input: String, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result<(bool, Option, String), Failure> { let mut cmd = Command::new(cli); cmd.args(args) .current_dir(work) .env("PATH", crate::cloudbox::tool_path()) // An API key in the environment would switch the login to pay-as-you-go; this path is the subscription. .env_remove("ANTHROPIC_API_KEY") .env_remove("ANTHROPIC_AUTH_TOKEN") // Started from inside a Claude Code session (a developer's terminal), the CLI would refuse to nest. .env_remove("CLAUDECODE") .env_remove("CLAUDE_CODE_ENTRYPOINT") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let mut child = cmd.spawn().map_err(|e| Failure::fatal(format!("打不開 Claude Code({e})。確認它還在,然後重新開啟 AnyBot。")))?; if let Some(mut stdin) = child.stdin.take() { // A thread: a prompt larger than the pipe must not hold this one up. std::thread::spawn(move || { let _ = writeln!(stdin, "{input}"); }); } // The readers own their pipes, so a long answer never fills one and holds the CLI up. let out_pipe = child.stdout.take(); let err_pipe = child.stderr.take(); let out_reader = std::thread::spawn(move || read_to_string(out_pipe)); let err_reader = std::thread::spawn(move || read_to_string(err_pipe)); let started = Instant::now(); let mut last_alive = started; let status = loop { match child.try_wait() { Ok(Some(status)) => break status, Ok(None) => {} Err(e) => return Err(Failure::fatal(format!("Claude Code 的程序出錯:{e}"))), } if cancel.load(Ordering::Relaxed) { let _ = child.kill(); let _ = child.wait(); return Ok((false, None, String::new())); } if started.elapsed() > STEP_TIMEOUT { let _ = child.kill(); let _ = child.wait(); return Err(Failure::fatal("Claude Code 超過 15 分鐘還沒有回答,已停止。".into())); } if last_alive.elapsed() >= ALIVE_EVERY { send(StreamEvent::Alive); last_alive = Instant::now(); } std::thread::sleep(Duration::from_millis(100)); }; let stdout = out_reader.join().unwrap_or_default(); let stderr = err_reader.join().unwrap_or_default(); Ok((status.success(), Some(stdout), stderr)) } fn read_to_string(pipe: Option) -> String { let mut buf = String::new(); if let Some(mut p) = pipe { let _ = std::io::Read::read_to_string(&mut p, &mut buf); } buf } #[cfg(test)] mod tests { use super::*; fn req(history: Vec, tools: Vec) -> ChatRequest { ChatRequest { kind: providers::ProviderKind::ClaudeCode, base_url: String::new(), api_key: String::new(), model: "sonnet".into(), system: "你是助理。".into(), history, tools, session: String::new(), effort: String::new(), } } fn tool(name: &str) -> Value { json!({"name": name, "description": "讀檔案", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}) } #[test] fn system_prompt_lists_tools_and_answer_shape() { let s = system_prompt(&req(vec![], vec![tool("read_file")])); assert!(s.starts_with("你是助理。")); assert!(s.contains("## read_file"), "{s}"); assert!(s.contains("參數(JSON Schema)")); assert!(s.contains("回覆格式")); // No tools: no tool section. assert!(!system_prompt(&req(vec![], vec![])).contains("# 工具")); } #[test] fn input_line_labels_turns_and_sends_pictures_as_blocks() { let mut pic = Message::user("這是什麼"); pic.images = vec!["AAAA".into()]; let mut tool_msg = Message { role: Role::Tool, text: "檔案內容".into(), tool_call_id: "t1".into(), ..Message::default() }; tool_msg.images = vec!["BBBB".into()]; let call = ToolCall { id: "t1".into(), name: "read_file".into(), args: r#"{"path":"a"}"#.into(), status: ToolStatus::Done }; let asked = Message { role: Role::Assistant, text: "我來看".into(), tool_calls: vec![call], ..Message::default() }; let line: Value = serde_json::from_str(&input_line(&req(vec![pic, asked, tool_msg], vec![]))).unwrap(); let content = &line["message"]["content"]; let text = content[0]["text"].as_str().unwrap(); assert!(text.contains("【使用者】\n這是什麼(附圖 1)"), "{text}"); assert!(text.contains("【你呼叫了工具 read_file(id t1)】")); assert!(text.contains("【工具結果(id t1)】\n檔案內容(附圖 2)"), "{text}"); assert_eq!(content[1]["source"]["data"], "AAAA"); assert_eq!(content[2]["source"]["data"], "BBBB"); assert!(text.ends_with("(JSON 格式)。")); } #[test] fn the_answer_is_the_result_line_of_the_stream() { let stream = "{\"type\":\"system\",\"subtype\":\"init\"}\n{\"type\":\"assistant\",\"message\":{}}\n{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"好\"}\n"; let v = answer_of(stream).expect("the result line"); assert_eq!(v["result"].as_str(), Some("好")); let single = answer_of("{\"type\":\"result\",\"result\":\"單行\"}").expect("one object"); assert_eq!(single["result"].as_str(), Some("單行")); assert!(answer_of("不是 JSON").is_none()); } #[test] fn args_run_the_cli_with_no_tools_and_the_schema() { let a = args(&req(vec![], vec![]), Path::new("/tmp/s.txt")); let at = |flag: &str| a.iter().position(|x| x == flag).map(|i| a[i + 1].clone()); assert_eq!(at("--tools").as_deref(), Some("")); assert_eq!(at("--model").as_deref(), Some("sonnet")); assert_eq!(at("--system-prompt-file").as_deref(), Some("/tmp/s.txt")); assert!(at("--json-schema").unwrap().contains("tool_calls")); assert!(a.contains(&"--strict-mcp-config".to_string())); assert!(!a.contains(&"--effort".to_string()), "no effort unless the bot sets one"); let mut r = req(vec![], vec![]); r.effort = "high".into(); r.model = String::new(); let b = args(&r, Path::new("/tmp/s.txt")); assert!(b.windows(2).any(|w| w == ["--effort", "high"])); assert!(b.windows(2).any(|w| w == ["--model", DEFAULT_MODEL])); } #[test] fn answer_becomes_words_and_calls() { let v = json!({"is_error": false, "subtype": "success", "result": "", "structured_output": {"text": "好", "tool_calls": [{"name": "read_file", "arguments": "{\"path\":\"a\"}"}, {"name": "", "arguments": "{}"}, {"name": "list_dir", "arguments": {"path": "."}}]}, "usage": {"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 100}}); let (text, calls) = parse_answer(&v).unwrap_or_else(|e| panic!("{}", e.msg)); assert_eq!(text, "好"); assert_eq!(calls.len(), 2, "an unnamed call is dropped"); assert_eq!(calls[0].name, "read_file"); assert_eq!(calls[0].args, r#"{"path":"a"}"#); assert_eq!(calls[1].args, r#"{"path":"."}"#, "an object argument is kept as JSON text"); assert_ne!(calls[0].id, calls[1].id); let u = usage_of(&v); assert_eq!((u.input, u.output, u.cache_read), (3, 5, 100)); } #[test] fn plain_result_is_the_words_without_calls() { let v = json!({"is_error": false, "subtype": "success", "result": "只是文字"}); let (text, calls) = parse_answer(&v).unwrap_or_else(|e| panic!("{}", e.msg)); assert_eq!((text.as_str(), calls.len()), ("只是文字", 0)); } #[test] fn login_and_limit_failures_say_what_to_do() { assert!(failure_of("Not logged in · Please run /login").msg.contains("還沒有登入")); assert!(failure_of("Claude usage limit reached").msg.starts_with("已達用量上限")); assert!(failure_of("something else").msg.starts_with("Claude Code 出錯:")); } /// A stand-in `claude`: records its flags and its input, and answers with a structured reply. #[cfg(unix)] #[test] fn a_step_runs_the_command_and_reads_its_answer() { use std::os::unix::fs::PermissionsExt; let dir = std::env::temp_dir().join(format!("anybot-claudecli-test-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let script = dir.join("fake-claude"); let seen = dir.join("seen"); std::fs::write( &script, format!( "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{0}.args'\ncat > '{0}.input'\n\ echo '{{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"\",\"structured_output\":{{\"text\":\"你好\",\"tool_calls\":[{{\"name\":\"read_file\",\"arguments\":\"{{\\\"path\\\":\\\"a.txt\\\"}}\"}}]}},\"usage\":{{\"input_tokens\":5,\"output_tokens\":7}}}}'\n", seen.display() ), ) .unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); *CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(script); let cancel = AtomicBool::new(false); let events = Mutex::new(vec![]); let out = run(&req(vec![Message::user("嗨")], vec![tool("read_file")]), &cancel, &|e| { if let StreamEvent::ToolCall(c) = e { events.lock().unwrap().push(c.name); } }); *CLI_FOR_TESTS.lock().unwrap_or_else(|e| e.into_inner()) = None; let out = out.unwrap_or_else(|e| panic!("{}", e.msg)); assert_eq!(out.text, "你好"); assert_eq!(out.tool_calls[0].name, "read_file"); assert_eq!(out.tool_calls[0].args, r#"{"path":"a.txt"}"#); assert_eq!(events.lock().unwrap().as_slice(), ["read_file"]); assert_eq!(out.usage.output, 7); let flags = std::fs::read_to_string(format!("{}.args", seen.display())).unwrap(); assert!(flags.lines().any(|l| l == "--tools")); assert!(flags.lines().any(|l| l == "--no-session-persistence")); let input = std::fs::read_to_string(format!("{}.input", seen.display())).unwrap(); assert!(input.contains("【使用者】") && input.contains("嗨"), "{input}"); let _ = std::fs::remove_dir_all(&dir); } /// The real command, signed in: one short question on the cheapest model. Run by hand; it uses /// a little of the person's Claude quota. #[test] #[ignore = "uses the real claude command and the person's Claude quota"] fn real_cli_answers_when_installed() { assert!(installed(), "claude 指令找不到"); let cancel = AtomicBool::new(false); let mut r = req(vec![Message::user("只回答一個字:好")], vec![]); r.model = "haiku".into(); let out = run(&r, &cancel, &|_| {}).unwrap_or_else(|e| panic!("{}", e.msg)); assert!(!out.text.trim().is_empty(), "the CLI answered with no words"); } }