agentmux_srv_core/backend/memory/
dream_runner.rs1use std::future::Future;
22
23use super::dream_prompt::{self, Built, Caps, Input, Refused};
24use super::dream_proposal::{self, Context, MemoryFile, Source};
25use crate::backend::storage::dreams::{state, DreamResult};
26use crate::backend::storage::store::Store;
27
28#[derive(Debug, Clone, Default)]
30pub struct ModelAnswer {
31 pub text: String,
32 pub model: String,
33 pub account_id: String,
34 pub input_tokens: u64,
35 pub output_tokens: u64,
36 pub cost_usd: Option<f64>,
38}
39
40#[derive(Debug, Clone, Default)]
43pub struct CallFailed {
44 pub reason: String,
45 pub spent: Option<ModelAnswer>,
46 pub skip: bool,
49}
50
51impl From<String> for CallFailed {
52 fn from(reason: String) -> Self {
53 Self { reason, spent: None, skip: false }
54 }
55}
56
57pub struct Pass<'a> {
59 pub dream_id: &'a str,
60 pub memory_kind: &'a str,
61 pub files: &'a [MemoryFile],
63 pub sessions: &'a [Source],
65 pub protected: &'a [String],
66 pub caps: Caps,
67 pub max_file_bytes: usize,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum End {
74 Ready { ops: usize, dropped: usize },
76 Held(String),
77 Failed(String),
78 NotQueued,
80}
81
82fn read_set_json(built: &Built) -> String {
83 let rows: Vec<_> = built
84 .sources
85 .iter()
86 .map(|s| serde_json::json!({ "kind": s.label, "name": s.name, "bytes": s.text.len() }))
87 .collect();
88 serde_json::Value::Array(rows).to_string()
89}
90
91fn record_result(store: &Store, dream_id: &str, built: &Built, caps_hit: &[String], used: &ModelAnswer) -> Result<(), String> {
93 let result = DreamResult {
94 model: used.model.clone(),
95 account_id: used.account_id.clone(),
96 read_set: read_set_json(built),
97 caps_hit: serde_json::json!(caps_hit).to_string(),
98 input_tokens: used.input_tokens as i64,
99 output_tokens: used.output_tokens as i64,
100 cost: used.cost_usd,
101 };
102 if store.dream_set_result(dream_id, &result).map_err(|e| e.to_string())? {
103 Ok(())
104 } else {
105 Err(format!("dream {dream_id} is not in the record"))
106 }
107}
108
109fn finish(store: &Store, dream_id: &str, to: &str, detail: &str, now_ms: i64) -> Result<(), String> {
110 let moved = store.dream_move(dream_id, state::RUNNING, to, detail, "", now_ms).map_err(|e| e.to_string())?;
111 if moved { Ok(()) } else { Err(format!("dream {dream_id} was not running when it ended")) }
112}
113
114pub async fn run<F, Fut>(store: &Store, pass: &Pass<'_>, now_ms: i64, call: F) -> Result<End, String>
118where
119 F: FnOnce(String) -> Fut,
120 Fut: Future<Output = Result<ModelAnswer, CallFailed>>,
121{
122 if !store.dream_move(pass.dream_id, state::QUEUED, state::RUNNING, "", "", now_ms).map_err(|e| e.to_string())? {
123 return Ok(End::NotQueued);
124 }
125 let ended = run_started(store, pass, now_ms, call).await;
126 if let Err(why) = &ended {
127 let _ = finish(store, pass.dream_id, state::FAILED, &format!("the record could not be written: {why}"), now_ms);
129 }
130 ended
131}
132
133async fn run_started<F, Fut>(store: &Store, pass: &Pass<'_>, now_ms: i64, call: F) -> Result<End, String>
135where
136 F: FnOnce(String) -> Fut,
137 Fut: Future<Output = Result<ModelAnswer, CallFailed>>,
138{
139 let input = Input {
140 dream_id: pass.dream_id,
141 memory_kind: pass.memory_kind,
142 files: pass.files,
143 sessions: pass.sessions,
144 protected: pass.protected,
145 };
146 let built = match dream_prompt::build(&input, &pass.caps) {
147 Ok(b) => b,
148 Err(Refused::Nothing) => {
149 finish(store, pass.dream_id, state::HELD, "nothing to read", now_ms)?;
150 return Ok(End::Held("nothing to read".into()));
151 }
152 Err(e) => {
153 let why = format!("the prompt was not built: {e:?}");
154 finish(store, pass.dream_id, state::FAILED, &why, now_ms)?;
155 return Ok(End::Failed(why));
156 }
157 };
158 let answer = match call(built.prompt.clone()).await {
159 Ok(a) => a,
160 Err(e) => {
161 if let Some(spent) = &e.spent {
162 record_result(store, pass.dream_id, &built, &built.caps_hit, spent)?;
163 }
164 if e.skip {
165 let why = format!("skipped: {}", e.reason);
166 finish(store, pass.dream_id, state::HELD, &why, now_ms)?;
167 return Ok(End::Held(why));
168 }
169 let why = format!("the model call failed: {}", e.reason);
170 finish(store, pass.dream_id, state::FAILED, &why, now_ms)?;
171 return Ok(End::Failed(why));
172 }
173 };
174
175 let omitted: Vec<String> =
176 pass.files.iter().filter(|f| !built.included.iter().any(|i| i.name == f.name)).map(|f| f.name.clone()).collect();
177 let ctx = Context {
178 files: &built.included,
179 omitted: &omitted,
180 sources: &built.sources,
181 protected: pass.protected,
182 max_file_bytes: pass.max_file_bytes,
183 max_ops: pass.caps.max_ops,
184 };
185 let checked = dream_proposal::validate(&answer.text, pass.dream_id, &ctx);
186 let mut caps_hit = built.caps_hit.clone();
187 if let Ok(o) = &checked {
188 caps_hit.extend(o.dropped.iter().map(|d| format!("operation {} dropped: {}", d.index, d.why)));
189 }
190 record_result(store, pass.dream_id, &built, &caps_hit, &answer)?;
191
192 match checked {
193 Err(why) => {
194 let why = format!("the answer was refused: {why}");
195 finish(store, pass.dream_id, state::FAILED, &why, now_ms)?;
196 Ok(End::Failed(why))
197 }
198 Ok(outcome) => {
199 store.dream_ops_insert(pass.dream_id, &outcome.ops).map_err(|e| e.to_string())?;
200 finish(store, pass.dream_id, state::READY, "", now_ms)?;
201 Ok(End::Ready { ops: outcome.ops.len(), dropped: outcome.dropped.len() })
202 }
203 }
204}
205
206#[cfg(test)]
207#[path = "dream_runner_tests.rs"]
208mod tests;