Skip to main content

agentmux_srv_core/backend/memory/
dream_runner.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One Dreams pass, from a queued dream to a proposal waiting for review (SPEC_DREAMS §2, §8).
5//!
6//! The runner takes what the pass read (the caller's job: files from the store, session text from the history), builds
7//! the prompt (`dream_prompt`), makes the one model call through a function the caller supplies, checks the answer
8//! (`dream_proposal`) and records the proposal and what the pass cost. It never writes a memory file: a proposal waits
9//! in the record until a person applies it, and applying is a later step.
10//!
11//! The model call is a parameter, so the runner has no account, no CLI and no spend of its own; a test passes a fake.
12//! The one real call site is the next step, with the account decision (§2.4, D5).
13//!
14//! How a pass ends, so a dream never stays `running`:
15//! - `ready`: the answer was the schema; its operations (possibly none) are recorded;
16//! - `held`: nothing was sent because a rule said wait (there is nothing to read),
17//!   so the dream can be queued again;
18//! - `failed`: the prompt could not be built, the call failed, or the answer was not the schema. What the call cost is
19//!   recorded either way, because the spend happened.
20
21use 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/// What the model call returned.
29#[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    /// `None` when the price is not known (a login's quota is not dollars).
37    pub cost_usd: Option<f64>,
38}
39
40/// A model call that failed. When the call was made and billed before it failed (a timeout after the reply started, a
41/// refused reply), `spent` carries what it used, so the entry still shows the spend; its `text` is ignored.
42#[derive(Debug, Clone, Default)]
43pub struct CallFailed {
44    pub reason: String,
45    pub spent: Option<ModelAnswer>,
46    /// The pass cannot run on the account it was given (signed out, at its usage limit) and must not borrow another:
47    /// it is held with this reason, not failed, and a later trigger tries again.
48    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
57/// What the pass reads and the limits it works under.
58pub struct Pass<'a> {
59    pub dream_id: &'a str,
60    pub memory_kind: &'a str,
61    /// The memory's files, newest change first.
62    pub files: &'a [MemoryFile],
63    /// Session text since the last pass, oldest first (person and agent text only).
64    pub sessions: &'a [Source],
65    pub protected: &'a [String],
66    pub caps: Caps,
67    /// The most a written file may hold, in bytes.
68    pub max_file_bytes: usize,
69}
70
71/// Where the dream is when `run` returns.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum End {
74    /// Proposal recorded, waiting for a person: how many operations, and how many the check dropped.
75    Ready { ops: usize, dropped: usize },
76    Held(String),
77    Failed(String),
78    /// The dream was no longer queued (another caller took it), so nothing ran.
79    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
91/// What the pass read and what the call used, written when the call ends. An unknown dream is an error, not a no-op.
92fn 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
114/// Run one queued dream. `call` receives the prompt and makes the model call; it is not called when a rule holds the
115/// pass back. An `Err` is a store failure the caller should log: the dream is moved to `failed` on a best effort, so
116/// it does not stay `running` (nothing moves a running dream back to the queue).
117pub 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        // Best effort: if the store is what failed, this may fail too, and the caller has the error to log.
128        let _ = finish(store, pass.dream_id, state::FAILED, &format!("the record could not be written: {why}"), now_ms);
129    }
130    ended
131}
132
133/// The dream is `running`.
134async 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;