Skip to main content

agentmux_srv_core/ambient/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Ambient Model Call (AMC) gateway — the single mandatory path for every
5//! non-user-driven ("ambient") model call in the backend: cheap, background
6//! LLM calls that augment the UX (e.g. summarizing what an agent is doing
7//! for the pane header / Swarm tree) rather than answering a user's own
8//! turn. See `docs/specs/SPEC_AMBIENT_MODEL_CALLS_FRAMEWORK_2026_07_03.md`.
9//!
10//! Every ambient call is keyed by `(entity_id, purpose)` and carries a
11//! caller-supplied generation (monotonic per entity — e.g. a turn counter).
12//! The gateway:
13//!   - cancels a lower-generation in-flight call for the same key the moment
14//!     a higher-generation one is admitted (real subprocess cancellation via
15//!     the returned `CancellationToken`, not just a discard-on-arrival check)
16//!   - rejects a request whose generation is not strictly greater than the
17//!     highest one already admitted for that key (stale-on-arrival — the
18//!     caller does no work at all, not even a discarded one)
19//!
20//! This does NOT track token usage itself — callers record usage through the
21//! normal per-call-site accounting path (tagged by purpose), same as any
22//! other RPC result. The gateway's job is coalescing/cancellation only.
23
24pub mod call;
25pub mod cli_locator;
26pub mod cli;
27pub mod digest;
28pub mod limits;
29pub mod outcome;
30pub mod prompt;
31pub mod purpose;
32pub mod reply;
33pub mod sanitize;
34pub mod spend;
35pub mod tasks;
36pub mod title;
37pub mod validate;
38
39use std::collections::HashMap;
40use std::sync::{Mutex, OnceLock};
41
42use tokio_util::sync::CancellationToken;
43
44/// Identifies one class of ambient call for a specific entity, e.g.
45/// `(block_id, "activity_summary")`. `purpose` is a short stable string —
46/// also suitable for tagging cost/usage dashboards by call category.
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48pub struct AmbientCallKey {
49    pub entity_id: String,
50    pub purpose: &'static str,
51}
52
53impl AmbientCallKey {
54    pub fn new(entity_id: impl Into<String>, purpose: &'static str) -> Self {
55        Self { entity_id: entity_id.into(), purpose }
56    }
57}
58
59struct InFlight {
60    generation: u64,
61    cancel: CancellationToken,
62}
63
64#[derive(Default)]
65struct GatewayState {
66    inflight: HashMap<AmbientCallKey, InFlight>,
67}
68
69pub struct AmbientGateway {
70    state: Mutex<GatewayState>,
71}
72
73static GATEWAY: OnceLock<AmbientGateway> = OnceLock::new();
74
75/// The process-wide ambient-call gateway singleton.
76pub fn gateway() -> &'static AmbientGateway {
77    GATEWAY.get_or_init(|| AmbientGateway { state: Mutex::new(GatewayState::default()) })
78}
79
80/// Outcome of admitting a request for a key at a given generation.
81pub enum Admission<'a> {
82    /// This is the newest request seen for the key — proceed. Holding the
83    /// guard for the duration of the call gives access to its cancellation
84    /// token; dropping the guard (end of scope, any return path) clears the
85    /// in-flight entry unless a newer request has already replaced it.
86    Proceed(AmbientCallGuard<'a>),
87    /// A request at this generation-or-newer is already in flight, or has
88    /// already completed, for this key — do no work at all.
89    StaleOnArrival,
90}
91
92impl AmbientGateway {
93    /// Admit a request for `key` at `generation`. If an older in-flight
94    /// request exists for the same key, it is cancelled (its cancellation
95    /// token is triggered — the caller holding that token is responsible
96    /// for actually killing its subprocess). If `generation` is not
97    /// strictly greater than the generation already recorded for this key,
98    /// returns `StaleOnArrival` without mutating any state.
99    pub fn admit(&self, key: AmbientCallKey, generation: u64) -> Admission<'_> {
100        let mut state = self.state.lock().unwrap();
101        if let Some(existing) = state.inflight.get(&key) {
102            if generation <= existing.generation {
103                return Admission::StaleOnArrival;
104            }
105            existing.cancel.cancel();
106        }
107        let cancel = CancellationToken::new();
108        state.inflight.insert(
109            key.clone(),
110            InFlight { generation, cancel: cancel.clone() },
111        );
112        Admission::Proceed(AmbientCallGuard {
113            gateway: self,
114            key,
115            generation,
116            cancel,
117        })
118    }
119}
120
121/// Held for the duration of one admitted ambient call.
122pub struct AmbientCallGuard<'a> {
123    gateway: &'a AmbientGateway,
124    key: AmbientCallKey,
125    generation: u64,
126    cancel: CancellationToken,
127}
128
129impl AmbientCallGuard<'_> {
130    /// Cancellation token for this call. Race it against the subprocess
131    /// (`tokio::select!`) and kill the child if it fires — a newer request
132    /// for the same key has superseded this one.
133    pub fn cancellation(&self) -> CancellationToken {
134        self.cancel.clone()
135    }
136}
137
138impl Drop for AmbientCallGuard<'_> {
139    fn drop(&mut self) {
140        let mut state = self.gateway.state.lock().unwrap();
141        // Only clear if we're still the entry of record — a newer request
142        // may have already replaced it (and its own guard owns the clear).
143        if let Some(entry) = state.inflight.get(&self.key) {
144            if entry.generation == self.generation {
145                state.inflight.remove(&self.key);
146            }
147        }
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    fn key(id: &str) -> AmbientCallKey {
156        AmbientCallKey::new(id, "activity_summary")
157    }
158
159    #[test]
160    fn first_request_is_admitted() {
161        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
162        match gw.admit(key("block-1"), 1) {
163            Admission::Proceed(_) => {}
164            Admission::StaleOnArrival => panic!("first request should be admitted"),
165        };
166    }
167
168    #[test]
169    fn older_or_equal_generation_is_stale_on_arrival() {
170        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
171        let _guard = match gw.admit(key("block-1"), 5) {
172            Admission::Proceed(g) => g,
173            Admission::StaleOnArrival => panic!("gen 5 should be admitted"),
174        };
175        match gw.admit(key("block-1"), 5) {
176            Admission::StaleOnArrival => {}
177            Admission::Proceed(_) => panic!("equal generation must be rejected"),
178        }
179        match gw.admit(key("block-1"), 3) {
180            Admission::StaleOnArrival => {}
181            Admission::Proceed(_) => panic!("older generation must be rejected"),
182        };
183    }
184
185    #[test]
186    fn newer_generation_cancels_the_older_inflight_request() {
187        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
188        let guard1 = match gw.admit(key("block-1"), 1) {
189            Admission::Proceed(g) => g,
190            Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
191        };
192        let cancel1 = guard1.cancellation();
193        assert!(!cancel1.is_cancelled());
194
195        let _guard2 = match gw.admit(key("block-1"), 2) {
196            Admission::Proceed(g) => g,
197            Admission::StaleOnArrival => panic!("gen 2 should be admitted"),
198        };
199        assert!(cancel1.is_cancelled(), "admitting gen 2 must cancel gen 1's token");
200    }
201
202    #[test]
203    fn different_keys_do_not_interfere() {
204        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
205        let guard1 = match gw.admit(key("block-1"), 1) {
206            Admission::Proceed(g) => g,
207            Admission::StaleOnArrival => panic!("block-1 gen 1 should be admitted"),
208        };
209        match gw.admit(key("block-2"), 1) {
210            Admission::Proceed(_) => {}
211            Admission::StaleOnArrival => panic!("block-2 gen 1 should be admitted independently"),
212        }
213        assert!(!guard1.cancellation().is_cancelled(), "unrelated key must not cancel block-1");
214    }
215
216    #[test]
217    fn dropping_the_guard_clears_the_slot_for_a_later_retry_at_the_same_generation() {
218        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
219        {
220            let _guard = match gw.admit(key("block-1"), 1) {
221                Admission::Proceed(g) => g,
222                Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
223            };
224        } // guard dropped here — slot cleared
225        match gw.admit(key("block-1"), 1) {
226            Admission::Proceed(_) => {}
227            Admission::StaleOnArrival => {
228                panic!("gen 1 should be admittable again once the prior call finished")
229            }
230        };
231    }
232
233    #[test]
234    fn stale_guard_dropping_does_not_clear_a_newer_inflight_entry() {
235        let gw = AmbientGateway { state: Mutex::new(GatewayState::default()) };
236        let guard1 = match gw.admit(key("block-1"), 1) {
237            Admission::Proceed(g) => g,
238            Admission::StaleOnArrival => panic!("gen 1 should be admitted"),
239        };
240        let _guard2 = match gw.admit(key("block-1"), 2) {
241            Admission::Proceed(g) => g,
242            Admission::StaleOnArrival => panic!("gen 2 should be admitted"),
243        };
244        drop(guard1); // superseded guard drops — must NOT clear gen 2's slot
245        match gw.admit(key("block-1"), 2) {
246            Admission::StaleOnArrival => {}
247            Admission::Proceed(_) => {
248                panic!("gen 2 is still in flight; dropping the stale gen-1 guard must not clear it")
249            }
250        };
251    }
252}