agentmux_srv/server/app_api/
dream_run.rs1use 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#[derive(Debug, Clone, PartialEq)]
35pub(crate) struct Settings {
36 pub enabled: bool,
37 pub model: String,
38 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
61pub(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
88fn 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
110pub(crate) struct Call {
112 pub model: String,
113 pub config_dir: Option<String>,
114}
115
116pub(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 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
180const STALE_AFTER_MS: i64 = 2 * dream_model::CALL_TIMEOUT.as_millis() as i64 + 60_000;
183
184pub(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
204async 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
212pub(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
230pub(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 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
254pub(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;