agentmux_srv_core/backend/memory/
dream_model.rs1use std::time::Duration;
22
23use super::dream_runner::{CallFailed, ModelAnswer};
24
25pub const DEFAULT_MODEL: &str = "claude-sonnet-5-5";
27
28pub const CALL_TIMEOUT: Duration = Duration::from_secs(180);
30
31pub const SYSTEM_PROMPT: &str = "You answer with one JSON object and nothing else.";
33
34#[derive(Debug, Clone)]
36pub struct Route {
37 pub cli_path: String,
39 pub model: String,
40 pub config_dir: Option<String>,
42}
43
44pub fn args(model: &str) -> Vec<String> {
46 [
47 "-p", "--output-format", "json", "--model", model, "--tools", "", "--max-turns", "1", "--no-session-persistence",
48 "--disable-slash-commands", "--strict-mcp-config", "--system-prompt", SYSTEM_PROMPT,
49 ]
50 .iter()
51 .map(|a| a.to_string())
52 .collect()
53}
54
55pub fn envs(config_dir: Option<&str>) -> Vec<(&'static str, String)> {
57 let mut env = vec![("CLAUDE_CODE_DISABLE_CLAUDE_MDS", "1".to_string()), ("CLAUDE_CODE_DISABLE_AUTO_MEMORY", "1".to_string())];
58 if let Some(dir) = config_dir.filter(|d| !d.trim().is_empty()) {
59 env.push(("CLAUDE_CONFIG_DIR", dir.to_string()));
60 }
61 env
62}
63
64const ACCOUNT_UNUSABLE: [(&str, &str); 7] = [
67 ("usage limit", "the account is at its usage limit"),
68 ("limit reached", "the account is at its usage limit"),
69 ("rate limit", "the account is at its usage limit"),
70 ("/login", "the account is signed out"),
71 ("invalid api key", "the account is signed out"),
72 ("token has expired", "the account is signed out"),
73 ("not logged in", "the account is signed out"),
74];
75
76pub fn account_unusable(error_text: &str) -> Option<&'static str> {
78 let lower = error_text.to_lowercase();
79 ACCOUNT_UNUSABLE.iter().find(|(needle, _)| lower.contains(needle)).map(|(_, why)| *why)
80}
81
82fn failed(reason: String) -> CallFailed {
83 match account_unusable(&reason) {
84 Some(why) => CallFailed { reason: why.to_string(), spent: None, skip: true },
85 None => CallFailed { reason, spent: None, skip: false },
86 }
87}
88
89pub fn parse(stdout: &str, model: &str) -> Result<ModelAnswer, CallFailed> {
91 let v: serde_json::Value = serde_json::from_str(stdout.trim()).map_err(|e| failed(format!("the CLI's answer is not JSON: {e}")))?;
92 let usage = &v["usage"];
93 let n = |k: &str| usage[k].as_u64().unwrap_or(0);
94 let used = ModelAnswer {
95 text: v["result"].as_str().unwrap_or_default().to_string(),
96 model: model.to_string(),
97 account_id: String::new(),
98 input_tokens: n("input_tokens") + n("cache_creation_input_tokens") + n("cache_read_input_tokens"),
99 output_tokens: n("output_tokens"),
100 cost_usd: None,
102 };
103 if v["is_error"].as_bool().unwrap_or(false) {
104 let reason = if used.text.is_empty() { format!("the CLI reported an error ({})", v["subtype"].as_str().unwrap_or("unknown")) } else { used.text.clone() };
105 let mut f = failed(reason);
106 if !f.skip && (used.input_tokens > 0 || used.output_tokens > 0) {
107 f.spent = Some(ModelAnswer { text: String::new(), ..used });
108 }
109 return Err(f);
110 }
111 Ok(used)
112}
113
114type Finished = (std::process::ExitStatus, Vec<u8>, Vec<u8>);
116
117async fn run_child(mut cmd: tokio::process::Command, prompt: &[u8], limit: Duration) -> Result<Finished, CallFailed> {
121 crate::backend::process_tracker::registry::own_process_group(&mut cmd);
122 let mut child = agentmux_common::process::KillGroupOnDrop(
123 cmd.stdin(std::process::Stdio::piped())
124 .stdout(std::process::Stdio::piped())
125 .stderr(std::process::Stdio::piped())
126 .kill_on_drop(true)
127 .spawn()
128 .map_err(|e| CallFailed::from(format!("the CLI did not start: {e}")))?,
129 );
130 crate::backend::process_tracker::registry::record_untracked_cli(child.id());
131 let mut stdin = child.stdin.take().ok_or_else(|| CallFailed::from("the CLI has no input".to_string()))?;
132 let mut out = child.stdout.take().ok_or_else(|| CallFailed::from("the CLI has no output".to_string()))?;
133 let mut err = child.stderr.take().ok_or_else(|| CallFailed::from("the CLI has no error output".to_string()))?;
134 let work = async {
135 use tokio::io::{AsyncReadExt, AsyncWriteExt};
136 let send = async {
138 let sent = stdin.write_all(prompt).await;
139 drop(stdin);
140 sent
141 };
142 let (mut o, mut e) = (Vec::new(), Vec::new());
143 let read = async { tokio::try_join!(out.read_to_end(&mut o), err.read_to_end(&mut e)) };
144 let (sent, read) = tokio::join!(send, read);
145 if let Err(e) = sent {
147 if e.kind() != std::io::ErrorKind::BrokenPipe {
148 return Err(CallFailed::from(format!("the prompt was not sent: {e}")));
149 }
150 }
151 read.map_err(|e| CallFailed::from(format!("the CLI's output was not read: {e}")))?;
152 let status = child.wait().await.map_err(|e| CallFailed::from(format!("the CLI's exit was not read: {e}")))?;
153 Ok((status, o, e))
154 };
155 match tokio::time::timeout(limit, work).await {
156 Ok(done) => done,
157 Err(_) => {
158 let _ = agentmux_common::process::kill_child_and_group(&mut child).await;
159 Err(CallFailed::from(format!("the CLI ran past {} seconds", limit.as_secs().max(1))))
160 }
161 }
162}
163
164pub async fn invoke(route: &Route, prompt: &str) -> Result<ModelAnswer, CallFailed> {
166 let _gate = tokio::time::timeout(CALL_TIMEOUT, crate::identity::token_warmup::ambient_gate(route.config_dir.as_deref()))
168 .await
169 .map_err(|_| CallFailed::from("the account's first turn did not end in time".to_string()))?;
170 let mut cmd = crate::backend::pane_env::make_cli_cmd(&route.cli_path);
171 cmd.args(args(&route.model));
172 for (k, v) in envs(route.config_dir.as_deref()) {
173 cmd.env(k, v);
174 }
175 if let Some(dir) = crate::ambient::cli::ambient_call_cwd() {
176 cmd.current_dir(dir);
177 }
178 let (status, stdout, stderr) = run_child(cmd, prompt.as_bytes(), CALL_TIMEOUT).await?;
179 let stdout = String::from_utf8_lossy(&stdout);
180 if !status.success() && !stdout.trim_start().starts_with('{') {
182 let tail: String = String::from_utf8_lossy(&stderr).split_whitespace().collect::<Vec<_>>().join(" ");
183 let tail: String = tail.chars().rev().take(300).collect::<Vec<_>>().into_iter().rev().collect();
184 return Err(failed(format!("the CLI exited with {status}: {tail}")));
185 }
186 parse(&stdout, &route.model)
187}
188
189#[cfg(test)]
190#[path = "dream_model_tests.rs"]
191mod tests;