Skip to main content

agentmux_srv_core/backend/memory/
dream_model.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The model call of a Dreams pass (docs/specs/SPEC_DREAMS_BACKGROUND_MEMORY_ORGANIZING_2026_11_27.md §2.3, §8): the
5//! provider's CLI run once, with no tools, on Dreams' own system prompt, on the account the dreamed agent is assigned
6//! to. It is not the ambient call of `ambient::cli`, which is Haiku-only, answers within 45 seconds and takes its
7//! sign-in from an open pane: a pass reads up to 100k tokens and takes about a minute, and the agent is usually stopped.
8//!
9//! What the call does so that it is only the pass's text and nothing else:
10//! - **Dreams' own prompt only.** `--system-prompt` replaces the CLI's default prompt, and the two switches
11//!   `CLAUDE_CODE_DISABLE_CLAUDE_MDS` and `CLAUDE_CODE_DISABLE_AUTO_MEMORY` keep the CLI from reading any project
12//!   instruction or auto-memory file (the bare CLI otherwise adds about 29k tokens of its own to every call).
13//! - **No tools, one turn, nothing saved**, and a scratch working folder of its own, so the call never lands in an
14//!   agent's own history.
15//! - **The agent's own account.** `CLAUDE_CONFIG_DIR` is the config folder of the account the agent is assigned to; with
16//!   none recorded the machine's default sign-in is used. A sign-in that has ended, or an account at its usage limit,
17//!   skips the pass (`CallFailed::skip`): it never borrows another account, and a later trigger tries again.
18//! - **Cost is plan quota**, not dollars: the answer carries the tokens (cache writes and reads counted as input) and no
19//!   price.
20
21use std::time::Duration;
22
23use super::dream_runner::{CallFailed, ModelAnswer};
24
25/// The model a pass runs on unless a setting names another (the lab's evidence so far).
26pub const DEFAULT_MODEL: &str = "claude-sonnet-5-5";
27
28/// The most a call may run, spawn to exit: a pass of 100k tokens took 40 to 53 seconds in the lab.
29pub const CALL_TIMEOUT: Duration = Duration::from_secs(180);
30
31/// The CLI's system prompt for a pass. The pass's own prompt (`dream_prompt`) carries the task and the schema.
32pub const SYSTEM_PROMPT: &str = "You answer with one JSON object and nothing else.";
33
34/// Where the call runs and on whom.
35#[derive(Debug, Clone)]
36pub struct Route {
37    /// The CLI's path (`ambient::cli_locator::locate("claude")`).
38    pub cli_path: String,
39    pub model: String,
40    /// The config folder of the agent's account; `None` runs on the machine's default sign-in.
41    pub config_dir: Option<String>,
42}
43
44/// The CLI's arguments: the prompt itself goes in on stdin.
45pub 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
55/// The environment the call adds to the CLI's own.
56pub 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
64/// Words in a CLI's error that mean this account cannot be used now, whoever's quota or sign-in it is: the pass is
65/// skipped, not failed, and no other account is tried.
66const 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
76/// Why a failed call means the account cannot be used, or `None` for any other failure.
77pub 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
89/// The answer in the CLI's `--output-format json` result.
90pub 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        // Plan quota, not dollars.
101        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
114/// What a finished child left: its exit, its output and its error output.
115type Finished = (std::process::ExitStatus, Vec<u8>, Vec<u8>);
116
117/// Spawn `cmd`, give it `prompt` on stdin, and wait for its output and its exit: all of it within one `limit`. A child
118/// that stalls before it reads its input (a prompt larger than the pipe), one that never ends its output, and one that
119/// closes its output but does not exit are all stopped at the limit, with its whole process group.
120async 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        // The prompt goes in while the output is read, so neither waits on the other.
137        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        // A child that ended without reading its input closes the pipe: its own error says why.
146        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
164/// Run the CLI once on `prompt`.
165pub async fn invoke(route: &Route, prompt: &str) -> Result<ModelAnswer, CallFailed> {
166    // Not on an account whose first spawn is still refreshing its token (#6081).
167    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    // A failed CLI usually still printed its JSON result, with the reason in it.
181    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;