Skip to main content

agentmux_srv/server/app_api/
dream_run.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Queueing and running a personal-memory dream (docs/specs/SPEC_DREAMS_BACKGROUND_MEMORY_ORGANIZING_2026_11_27.md
5//! §3, §5, §10 step 2): `queue_dream` adds one to the record, `run_next` takes the queued dream the schedule says may
6//! run now and runs one pass over the agent's memory files, and `start_loop` calls it once a minute.
7//!
8//! Dreams are **off until the person turns them on** (`dreams:enabled` in settings, default off): while off every queued
9//! dream waits and nothing is sent to a model. The model (`dreams:model`) and the most tokens one pass reads
10//! (`dreams:maxtokens`) are settings too. The account is the dreamed agent's own (`dream_model`).
11//!
12//! Not here yet: the triggers that queue a dream by themselves (a compaction, idle, the nightly sweep), the session text
13//! a pass reads (`sessions` is empty: a pass reads the memory files only), and Global Memory.
14
15use std::future::Future;
16use std::path::Path;
17use std::time::UNIX_EPOCH;
18
19use super::{AppState, SelfOwner};
20use crate::backend::memory::dream_model::{self, Route, DEFAULT_MODEL};
21use crate::backend::memory::dream_prompt::Caps;
22use crate::backend::memory::dream_proposal::MemoryFile;
23use crate::backend::memory::native_files::{agent_dream_account, DreamAccount};
24use crate::backend::memory::dream_runner::{run, CallFailed, End, ModelAnswer, Pass};
25use crate::backend::memory::dream_schedule::{pick, Candidate, Signals};
26use crate::backend::storage::agent_native_memory_versions::content_hash;
27use crate::backend::storage::dreams::{memory_kind, state as dstate, trigger, Dream};
28
29pub(crate) const SETTING_ENABLED: &str = "dreams:enabled";
30pub(crate) const SETTING_MODEL: &str = "dreams:model";
31pub(crate) const SETTING_MAX_TOKENS: &str = "dreams:maxtokens";
32
33/// What the person set for Dreams.
34#[derive(Debug, Clone, PartialEq)]
35pub(crate) struct Settings {
36    pub enabled: bool,
37    pub model: String,
38    /// The most tokens a pass reads, counted at the measured rate: the notes that do not fit are left out and the entry says so.
39    pub max_tokens: u64,
40}
41
42impl Default for Settings {
43    fn default() -> Self {
44        Self { enabled: false, model: DEFAULT_MODEL.to_string(), max_tokens: Caps::default().max_input_tokens }
45    }
46}
47
48pub(crate) fn settings_from_extra(extra: &std::collections::HashMap<String, serde_json::Value>) -> Settings {
49    let d = Settings::default();
50    Settings {
51        enabled: extra.get(SETTING_ENABLED).and_then(|v| v.as_bool()).unwrap_or(d.enabled),
52        model: extra.get(SETTING_MODEL).and_then(|v| v.as_str()).filter(|m| !m.trim().is_empty()).map(str::to_string).unwrap_or(d.model),
53        max_tokens: extra.get(SETTING_MAX_TOKENS).and_then(|v| v.as_u64()).filter(|n| *n >= 1_000).unwrap_or(d.max_tokens),
54    }
55}
56
57fn settings(state: &AppState) -> Settings {
58    settings_from_extra(&state.config_watcher.get_settings().extra)
59}
60
61/// Queue a dream of an agent's personal memory. One at a time per agent: an agent that has a dream queued or running
62/// gets none more.
63pub(crate) fn queue_dream(state: &AppState, agent_id: &str, trigger_kind: &str, now_ms: i64) -> Result<String, String> {
64    const L: &str = "dream.queue";
65    let agent = state
66        .mstore
67        .agent_def_get(agent_id)
68        .map_err(|e| format!("{L}: store: {e}"))?
69        .ok_or_else(|| format!("{L}: no agent {agent_id}"))?;
70    if agent.is_seeded != 0 {
71        return Err(format!("{L}: {} is a template, not an agent with a memory", agent.name));
72    }
73    let open = state
74        .id_store
75        .dream_list(Some(memory_kind::PERSONAL), Some(&agent.id), None, 50)
76        .map_err(|e| format!("{L}: store: {e}"))?;
77    if let Some(d) = open.iter().find(|d| d.state == dstate::QUEUED || d.state == dstate::RUNNING) {
78        return Err(format!("{L}: a dream of this memory is already {}", d.state));
79    }
80    let id = uuid::Uuid::new_v4().to_string();
81    state
82        .id_store
83        .dream_insert(&Dream::queued(&id, memory_kind::PERSONAL, &agent.id, trigger_kind, now_ms))
84        .map_err(|e| format!("{L}: store: {e}"))?;
85    Ok(id)
86}
87
88/// The memory folder's notes, newest change first, each with its hash. Files that are not `.md` notes are not memory.
89fn memory_files(dir: &Path) -> Result<Vec<MemoryFile>, String> {
90    let mut rows: Vec<(std::time::SystemTime, MemoryFile)> = Vec::new();
91    let entries = match std::fs::read_dir(dir) {
92        Ok(e) => e,
93        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
94        Err(e) => return Err(format!("read_dir: {e}")),
95    };
96    for entry in entries {
97        let entry = entry.map_err(|e| format!("read_dir: {e}"))?;
98        let name = entry.file_name().to_string_lossy().into_owned();
99        let Ok(meta) = entry.metadata() else { continue };
100        if !name.ends_with(".md") || !meta.is_file() {
101            continue;
102        }
103        let text = String::from_utf8_lossy(&std::fs::read(entry.path()).map_err(|e| format!("{name}: {e}"))?).into_owned();
104        rows.push((meta.modified().unwrap_or(UNIX_EPOCH), MemoryFile { hash: content_hash(&text), name, text }));
105    }
106    rows.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));
107    Ok(rows.into_iter().map(|(_, f)| f).collect())
108}
109
110/// What `run_next` hands the model call: the model and the account's config folder (`None`: the default sign-in).
111pub(crate) struct Call {
112    pub model: String,
113    pub config_dir: Option<String>,
114}
115
116/// Run the one queued dream the schedule allows now, if any: returns its id and how it ended. `account` says which account
117/// an agent's pass runs on; `call` makes the model call for the pass. `call` is not called when a rule holds the pass back,
118/// nor when the agent's account cannot be resolved: that pass is held with the reason, and no other account is tried.
119pub(crate) async fn run_next<A, C, Fut>(state: &AppState, settings: &Settings, now_ms: i64, account: A, call: C) -> Result<Option<(String, End)>, String>
120where
121    A: FnOnce(&str) -> DreamAccount,
122    C: FnOnce(Call, String) -> Fut,
123    Fut: Future<Output = Result<ModelAnswer, CallFailed>>,
124{
125    const L: &str = "dream.run";
126    let all = state.id_store.dream_list(Some(memory_kind::PERSONAL), None, None, 50).map_err(|e| format!("{L}: store: {e}"))?;
127    let queued: Vec<&Dream> = all.iter().filter(|d| d.state == dstate::QUEUED).collect();
128    if queued.is_empty() {
129        return Ok(None);
130    }
131    let signals = Signals { paused: !settings.enabled, pass_running: all.iter().any(|d| d.state == dstate::RUNNING), ..Default::default() };
132    // What each candidate's memory holds. A memory that cannot be read is left out of this round and logged.
133    let mut facts: Vec<(&Dream, std::path::PathBuf, Vec<MemoryFile>)> = Vec::new();
134    for d in queued {
135        let read = SelfOwner::Uid(&d.agent_id).dir_for_write(&state.mstore).map_err(|e| e.to_string()).and_then(|dir| memory_files(&dir).map(|f| (dir, f)));
136        match read {
137            Ok((dir, files)) => facts.push((d, dir, files)),
138            Err(e) => tracing::warn!(dream = %d.id, "{L}: the memory could not be read: {e}"),
139        }
140    }
141    let candidates: Vec<Candidate> = facts
142        .iter()
143        .map(|(d, _, files)| Candidate {
144            dream: d,
145            agent_mid_turn: false,
146            memory_changed: true,
147            new_session_text: false,
148            conflict_copies: files.iter().filter(|f| f.name.contains("__conflict_")).count(),
149            memory_bytes: files.iter().map(|f| f.text.len() as u64).sum(),
150            spent_today_micro_usd: 0,
151        })
152        .collect();
153    let Some(i) = pick(&candidates, &signals) else { return Ok(None) };
154    let (dream, _dir, files) = &facts[i];
155    let (config_dir, unusable) = match account(&dream.agent_id) {
156        DreamAccount::Dir(dir) => (Some(dir), None),
157        DreamAccount::Default => (None, None),
158        DreamAccount::Unresolved(why) => (None, Some(why)),
159    };
160    let pass = Pass {
161        dream_id: &dream.id,
162        memory_kind: &dream.memory_kind,
163        files,
164        sessions: &[],
165        protected: &[],
166        caps: Caps { max_input_tokens: settings.max_tokens, ..Caps::default() },
167        max_file_bytes: crate::server::native_memory_handlers::MAX_MEMORY_FILE_BYTES as usize,
168    };
169    let route = Call { model: settings.model.clone(), config_dir };
170    let end = run(&state.id_store, &pass, now_ms, move |prompt| async move {
171        if let Some(reason) = unusable {
172            return Err(CallFailed { reason, spent: None, skip: true });
173        }
174        call(route, prompt).await
175    })
176    .await?;
177    Ok(Some((dream.id.clone(), end)))
178}
179
180/// How long a pass may be `running` before it is taken for dead: the gate and the call each have the call limit, and a
181/// minute is left for reading the notes and writing the record.
182const STALE_AFTER_MS: i64 = 2 * dream_model::CALL_TIMEOUT.as_millis() as i64 + 60_000;
183
184/// End the dreams left `running` by a srv that quit, or by a loop that died, mid-pass: nothing else moves them, and a
185/// `running` dream blocks every later pass and its agent's next dream. A dream running for `older_than_ms` or more is
186/// moved to `failed`; `0` at startup takes them all, since no pass of this srv has begun. Returns how many it ended.
187pub(crate) fn sweep_interrupted(state: &AppState, now_ms: i64, older_than_ms: i64) -> usize {
188    let Ok(all) = state.id_store.dream_list(Some(memory_kind::PERSONAL), None, None, 200) else { return 0 };
189    let mut ended = 0;
190    for d in all.iter().filter(|d| d.state == dstate::RUNNING) {
191        let since = d.started_at_ms.unwrap_or(d.created_at_ms);
192        if now_ms.saturating_sub(since) < older_than_ms {
193            continue;
194        }
195        match state.id_store.dream_move(&d.id, dstate::RUNNING, dstate::FAILED, "interrupted: the pass did not end (srv quit or the pass stopped)", "", now_ms) {
196            Ok(true) => ended += 1,
197            Ok(false) => {}
198            Err(e) => tracing::warn!(dream = %d.id, "dream.sweep: {e}"),
199        }
200    }
201    ended
202}
203
204/// The real call: the CLI of the provider, on the agent's account.
205async fn call_cli(c: Call, prompt: String) -> Result<ModelAnswer, CallFailed> {
206    let Some(cli_path) = crate::ambient::cli_locator::locate("claude").await else {
207        return Err(CallFailed::from("the Claude CLI is not installed".to_string()));
208    };
209    dream_model::invoke(&Route { cli_path, model: c.model, config_dir: c.config_dir }, &prompt).await
210}
211
212/// One round of the loop: nothing happens while Dreams are off.
213pub(crate) async fn tick(state: &AppState) {
214    let settings = settings(state);
215    if !settings.enabled {
216        return;
217    }
218    let now = agentmux_common::time::now_ms();
219    let ended = sweep_interrupted(state, now, STALE_AFTER_MS);
220    if ended > 0 {
221        tracing::warn!(ended, "dream pass: ended passes that ran past the limit");
222    }
223    match run_next(state, &settings, now, |id| agent_dream_account(&state.mstore, id), call_cli).await {
224        Ok(Some((id, end))) => tracing::info!(dream = %id, ?end, "dream pass ended"),
225        Ok(None) => {}
226        Err(e) => tracing::warn!("dream pass: {e}"),
227    }
228}
229
230/// Start the loop once per srv: a round a minute. Without a runtime (a test that registers every handler) it starts
231/// nothing and a later call may still start it.
232pub(crate) fn start_loop(state: &AppState) {
233    static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
234    let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
235    if STARTED.swap(true, std::sync::atomic::Ordering::SeqCst) {
236        return;
237    }
238    let state = state.clone();
239    runtime.spawn(async move {
240        // A pass left `running` by the srv that quit before this one is over: nothing of this srv has begun.
241        let ended = sweep_interrupted(&state, agentmux_common::time::now_ms(), 0);
242        if ended > 0 {
243            tracing::warn!(ended, "dream pass: ended passes interrupted by the last srv");
244        }
245        let mut every = tokio::time::interval(std::time::Duration::from_secs(60));
246        every.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
247        loop {
248            every.tick().await;
249            tick(&state).await;
250        }
251    });
252}
253
254/// A pass the person asked for: queued as a `person` dream, which the loop runs at its next round.
255pub(crate) fn dream_now(state: &AppState, agent_id: &str, now_ms: i64) -> Result<String, String> {
256    queue_dream(state, agent_id, trigger::PERSON, now_ms)
257}
258
259#[cfg(test)]
260#[path = "tests/dream_run_tests.rs"]
261mod tests;