Skip to main content

mermaid_cli/providers/
ctx.rs

1//! Per-call context passed to providers and tool executors.
2//!
3//! The two structs below are the single point where per-turn
4//! cancellation + progress reporting + session identity meet a
5//! specific provider call. Everything a model or tool adapter needs
6//! to participate in structured concurrency is here.
7//!
8//! - `StreamContext` is handed to a `ModelProvider::chat()`. It
9//!   carries the cancellation token for the turn and a bounded mpsc
10//!   sink for streaming events. The adapter `select!`s on
11//!   `token.cancelled()` inside its read loop and awaits
12//!   `sink.send(event)` — if the main loop is drowning, the `await`
13//!   applies natural backpressure and the provider's TCP buffer fills
14//!   instead of the channel growing unbounded.
15//!
16//! - `ExecContext` is handed to a `ToolExecutor::execute()`. Same
17//!   token (so Ctrl+C cancels tools too) plus a progress sink and
18//!   identifiers so the reducer can match results to the call that
19//!   produced them.
20
21use mermaid_domain::ProgressEvent;
22use std::path::PathBuf;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicUsize, Ordering};
25
26use tokio::sync::mpsc;
27use tokio_util::sync::CancellationToken;
28
29use mermaid_domain::{Msg, ToolCallId, TurnId};
30use mermaid_model::models::tool_call::ToolCall as ModelToolCall;
31use mermaid_model::models::{ChatMessage, FinishReason, ProviderContinuation, TokenUsage};
32use mermaid_runtime::SafetyMode;
33
34use super::approval::ApprovalBroker;
35use super::auto_classifier::AutoClassifier;
36use super::questions::QuestionBroker;
37
38/// Shared, byte-exact budget for decoded HTTP response data in one turn.
39/// Clones point at the same atomic counter, so parallel tool calls and batched
40/// queries cannot each claim the full allowance independently.
41#[derive(Clone, Debug)]
42pub struct WebByteBudget {
43    used: Arc<AtomicUsize>,
44}
45
46impl WebByteBudget {
47    pub(crate) fn shared(used: Arc<AtomicUsize>) -> Self {
48        Self { used }
49    }
50
51    #[cfg(test)]
52    pub(crate) fn isolated() -> Self {
53        Self::shared(Arc::new(AtomicUsize::new(0)))
54    }
55
56    /// Charge decoded bytes without allowing the shared total to cross the
57    /// fixed per-turn limit. An overflowing charge atomically saturates the
58    /// counter so every later response observes an exhausted budget before it
59    /// polls another body.
60    // Nightly renamed `fetch_update` to `try_update` and deprecated the old
61    // name. `try_update` is not stable, so the call cannot be migrated yet and
62    // the deprecation cannot be avoided — and since the `[lints.rust]
63    // warnings = "deny"` table landed in every manifest, a warning the nightly
64    // toolchain emits is a hard error in the test build now, not only in
65    // clippy. That is what turned this into a red nightly leg.
66    //
67    // `#[allow]` and not `#[expect]`: on stable there is no deprecation to
68    // fulfil, so an expectation would itself become the warning on the
69    // toolchain that matters most. Delete both of these once `try_update`
70    // reaches the MSRV.
71    /// # Errors
72    ///
73    /// `Err(limit)` — the fixed per-turn cap — when this charge would cross
74    /// it, or when it was already reached. The counter is saturated either
75    /// way, so once one charge fails every later one does too; the `Err`
76    /// payload is the limit, not the amount over it.
77    #[allow(deprecated, reason = "try_update is not stable yet; see above")]
78    pub fn charge(&self, bytes: usize) -> Result<usize, usize> {
79        let limit = mermaid_model::constants::MAX_WEB_TURN_BYTES;
80        let prior = self
81            .used
82            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |used| {
83                Some(used.saturating_add(bytes).min(limit))
84            })
85            .expect("web byte budget update always supplies a value");
86        let next = prior.saturating_add(bytes);
87        if prior >= limit || next > limit {
88            Err(limit)
89        } else {
90            Ok(next)
91        }
92    }
93
94    #[must_use]
95    pub fn remaining(&self) -> usize {
96        mermaid_model::constants::MAX_WEB_TURN_BYTES
97            .saturating_sub(self.used.load(Ordering::Acquire))
98    }
99}
100
101/// What a `ModelProvider::chat()` receives.
102#[derive(Debug)]
103pub struct StreamContext {
104    pub token: CancellationToken,
105    pub sink: mpsc::Sender<StreamEvent>,
106    pub turn: TurnId,
107}
108
109impl StreamContext {
110    #[must_use]
111    pub fn new(token: CancellationToken, sink: mpsc::Sender<StreamEvent>, turn: TurnId) -> Self {
112        Self { token, sink, turn }
113    }
114}
115
116/// One event emitted during a streaming model call — the adapters' own type,
117/// re-exported rather than redefined.
118///
119/// This was a second enum with the same five variants, and the only thing it
120/// added was a richer `Done` — which cost a translation layer that could only
121/// fill those extra fields with `None`, because the adapter-side `Done` it
122/// mapped from carried a bare token count. `mermaid_model`'s `Done` carries
123/// the whole terminal payload now, so there is nothing left for a second type
124/// to add.
125pub use mermaid_model::models::StreamEvent;
126
127/// Final response returned by `ModelProvider::chat()` after the
128/// stream drains. Carries what the reducer can't derive from the
129/// stream events themselves: token usage and opaque provider continuation.
130#[derive(Debug, Clone)]
131pub struct FinalResponse {
132    pub usage: Option<TokenUsage>,
133    pub provider_continuation: Option<ProviderContinuation>,
134    pub tool_calls: Vec<ModelToolCall>,
135    pub stop_reason: Option<FinishReason>,
136}
137
138/// What the turn's scope supplies to every tool call it owns: cancellation,
139/// the Ctrl+B background signal, and the shared web-byte budget sibling
140/// calls charge together. One of the three hats the old 24-argument
141/// dispatch wore; the other two are [`mermaid_domain::ToolDispatch`]
142/// (reducer-stamped session/policy context) and [`ToolServices`]
143/// (runner-bound services).
144#[derive(Debug, Clone)]
145pub struct TurnSignals {
146    pub token: CancellationToken,
147    pub background: CancellationToken,
148    pub web_bytes: Arc<AtomicUsize>,
149}
150
151impl Default for TurnSignals {
152    /// Fresh, never-fired tokens and a zero budget — the test default;
153    /// the live path always builds from the owning `TurnScope`.
154    fn default() -> Self {
155        Self {
156            token: CancellationToken::new(),
157            background: CancellationToken::new(),
158            web_bytes: Arc::new(AtomicUsize::new(0)),
159        }
160    }
161}
162
163/// What the runner binds for the session, independent of any one call:
164/// the project root, the startup `Config`, daemon task ownership, and the
165/// interaction back-channels (approval, questions, checklist, the
166/// turn-independent notify channel, the Auto-mode classifier).
167pub struct ToolServices {
168    pub workdir: PathBuf,
169    pub config: Arc<mermaid_domain::Config>,
170    pub task_id: Option<String>,
171    pub notify: Option<mpsc::Sender<Msg>>,
172    pub classifier: Option<Arc<dyn AutoClassifier>>,
173    pub approval: Option<ApprovalBroker>,
174    pub questions: Option<QuestionBroker>,
175    pub tasks: Option<crate::providers::tasks::TaskBroker>,
176}
177
178/// What a `ToolExecutor::execute()` receives.
179pub struct ExecContext {
180    pub token: CancellationToken,
181    /// Ctrl+B "background this" signal, parallel to `token`. Tools that can
182    /// detach a running child (`execute_command`, agent) select on it; the live
183    /// path sets it from the turn scope, tests leave it never-fired.
184    pub background: CancellationToken,
185    /// Turn-independent channel back to the main reducer loop. Detached work
186    /// (a backgrounded subagent) reports through this after the owning turn
187    /// is gone — the per-turn `progress` channel dies with the turn. `None`
188    /// in tests and contexts that never detach.
189    pub notify: Option<mpsc::Sender<Msg>>,
190    pub progress: mpsc::Sender<ProgressEvent>,
191    pub call_id: ToolCallId,
192    pub turn: TurnId,
193    pub workdir: PathBuf,
194    /// Parent session's `domain::Config`. Needed by `SubagentTool` so the
195    /// child reducer uses the same Ollama host, reasoning prefs, MCP
196    /// servers, etc. Other tools don't consult it — keeping it as a
197    /// typed field (rather than a global) means the dependency is
198    /// explicit in the signature.
199    pub config: Arc<mermaid_domain::Config>,
200    /// Parent session's active model id (e.g. `"anthropic/claude-opus-4-7"`).
201    /// Subagents inherit this so they hit the same provider.
202    pub model_id: String,
203    /// Durable daemon task that owns this tool call, when execution was
204    /// launched through the runtime task queue.
205    pub task_id: Option<String>,
206    /// Conversation id of the interactive session dispatching this call —
207    /// stamped by the reducer onto `Cmd::ExecuteTool` so checkpoints can be
208    /// anchored to a conversation position. `None` on headless/daemon paths.
209    pub session_id: Option<String>,
210    /// Conversation length (`messages().len()`) at dispatch; pairs with
211    /// `session_id` for checkpoint anchoring (see `CheckpointOrigin`).
212    pub message_index: Option<i64>,
213    /// Per-session scratch directory, when the session has one materialized
214    /// (`Msg::ScratchpadReady`). Stamped by the reducer onto
215    /// `Cmd::ExecuteTool`; like `background`/`notify` it is field-set after
216    /// construction on the live path — `None` in tests and before the
217    /// directory is confirmed on disk.
218    pub scratchpad: Option<PathBuf>,
219    /// Live safety mode for this call (from the session, not the static
220    /// config). The policy gate builds its `PolicyEngine` from this.
221    pub safety_mode: SafetyMode,
222    /// The conversation that led to this call, passed to the Auto-mode
223    /// classifier so it can judge whether an action is aligned.
224    pub goal: mermaid_domain::UserGoal,
225    /// LLM classifier for `SafetyMode::Auto`. `Some` only when the effective
226    /// mode is `Auto` and a provider is bound; the gate awaits it to resolve a
227    /// `PolicyDecision::Classify`. `None` ⇒ the gate fails safe (escalate).
228    pub classifier: Option<Arc<dyn AutoClassifier>>,
229    /// Inline-approval back-channel (interactive runs only). `Some` lets the
230    /// gate prompt the user and park until they answer; `None` (headless) falls
231    /// back to the out-of-band DB-approval flow.
232    pub approval: Option<ApprovalBroker>,
233    /// Inline-question back-channel for `ask_user_question` (interactive runs
234    /// only). `Some` lets the tool park until the user answers; `None`
235    /// (headless) makes the tool proceed with best judgment instead of blocking.
236    pub questions: Option<QuestionBroker>,
237    /// The checklist broker for the task tools (single writer for all task
238    /// state). Present on every live path — interactive, headless, and
239    /// subagent runners each own one; `None` only in bare test contexts,
240    /// where the tools degrade to a graceful no-op.
241    pub tasks: Option<crate::providers::tasks::TaskBroker>,
242    /// Decoded web bytes accepted by every sibling tool call in this turn.
243    /// The effect runner replaces the constructor default with the owning
244    /// `TurnScope` counter so parallel calls share one aggregate budget.
245    pub web_bytes: Arc<AtomicUsize>,
246}
247
248impl std::fmt::Debug for ExecContext {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        // `classifier` is a trait object (no `Debug`); render its presence.
251        f.debug_struct("ExecContext")
252            .field("call_id", &self.call_id)
253            .field("turn", &self.turn)
254            .field("workdir", &self.workdir)
255            .field("model_id", &self.model_id)
256            .field("task_id", &self.task_id)
257            .field("session_id", &self.session_id)
258            .field("message_index", &self.message_index)
259            .field("scratchpad", &self.scratchpad)
260            .field("safety_mode", &self.safety_mode)
261            .field("goal", &self.goal)
262            .field(
263                "classifier",
264                &self.classifier.as_ref().map(|_| "<dyn AutoClassifier>"),
265            )
266            .field(
267                "approval",
268                &self.approval.as_ref().map(|_| "<ApprovalBroker>"),
269            )
270            .field(
271                "questions",
272                &self.questions.as_ref().map(|_| "<QuestionBroker>"),
273            )
274            .field("tasks", &self.tasks.as_ref().map(|_| "<TaskBroker>"))
275            .finish_non_exhaustive()
276    }
277}
278
279impl ExecContext {
280    /// Total construction from the three hats — no post-construction
281    /// field-sets. The struct itself stays flat (every tool reads
282    /// `ctx.token`, `ctx.workdir`, … unchanged); only assembly is grouped.
283    ///
284    /// `dispatch.session_id` is the conversation id (always present on the
285    /// live path); an empty id — bare test contexts — maps to `None` so
286    /// checkpoint anchoring stays "unanchored" rather than keyed to `""`.
287    #[must_use]
288    pub fn assemble(
289        turn: TurnId,
290        call_id: ToolCallId,
291        progress: mpsc::Sender<ProgressEvent>,
292        signals: TurnSignals,
293        dispatch: mermaid_domain::ToolDispatch,
294        services: ToolServices,
295    ) -> Self {
296        let session_id = (!dispatch.session_id.is_empty()).then(|| dispatch.session_id.clone());
297        Self {
298            token: signals.token,
299            background: signals.background,
300            web_bytes: signals.web_bytes,
301            notify: services.notify,
302            progress,
303            call_id,
304            turn,
305            workdir: services.workdir,
306            config: services.config,
307            model_id: dispatch.model_id,
308            task_id: services.task_id,
309            message_index: session_id.as_ref().map(|_| dispatch.message_index as i64),
310            session_id,
311            scratchpad: dispatch.scratchpad,
312            safety_mode: dispatch.safety_mode,
313            goal: dispatch.goal,
314            classifier: services.classifier,
315            approval: services.approval,
316            questions: services.questions,
317            tasks: services.tasks,
318        }
319    }
320
321    /// Charge decoded web bytes to this turn without ever crossing the fixed
322    /// aggregate limit. Returns the new total on success.
323    ///
324    /// # Errors
325    ///
326    /// [`WebByteBudget::charge`]'s: `Err(limit)` once this turn's aggregate
327    /// web budget is spent.
328    pub fn charge_web_bytes(&self, bytes: usize) -> Result<usize, usize> {
329        self.web_budget().charge(bytes)
330    }
331
332    /// A cloneable handle for transport code to charge each decoded chunk at
333    /// the point it is accepted, including failed responses and retries.
334    #[must_use]
335    pub fn web_budget(&self) -> WebByteBudget {
336        WebByteBudget::shared(self.web_bytes.clone())
337    }
338
339    /// Checkpoint provenance for this call — every checkpoint-creating tool
340    /// passes this so file snapshots anchor to the conversation position
341    /// that produced them (rewind/fork surfaces them by anchor).
342    #[must_use]
343    pub fn checkpoint_origin(&self) -> mermaid_runtime::CheckpointOrigin {
344        mermaid_runtime::CheckpointOrigin {
345            task_id: self.task_id.clone(),
346            session_id: self.session_id.clone(),
347            message_index: self.message_index,
348        }
349    }
350}
351
352/// Narrow shim from the reducer's `ChatRequest` to the adapter-facing
353/// messages. Providers often want to mutate the last assistant
354/// message (e.g. Anthropic `cache_control` injection); this helper
355/// clones the slice as owned so the provider can do that without
356/// fighting the borrow checker.
357#[must_use]
358pub fn clone_messages(msgs: &[ChatMessage]) -> Vec<ChatMessage> {
359    msgs.to_vec()
360}
361
362/// Builder that lets tests construct a pair of `StreamContext` +
363/// receiver without needing a runtime. Used by provider unit tests
364/// and by integration harnesses in C9.
365#[cfg(any(test, feature = "test-support"))]
366#[must_use]
367pub fn test_stream_context(turn: TurnId) -> (StreamContext, mpsc::Receiver<StreamEvent>) {
368    let token = CancellationToken::new();
369    let (tx, rx) = mpsc::channel(64);
370    (StreamContext::new(token, tx, turn), rx)
371}
372
373/// Builder counterpart for `ExecContext`. Uses a `Config` pinned to
374/// `SafetyMode::FullAccess` (the production default is now `Auto`) so tool
375/// unit tests exercise the tool's own behavior rather than the approval
376/// gate. Tests that specifically exercise policy gating should construct
377/// `ExecContext::assemble` directly with their chosen safety mode.
378#[cfg(any(test, feature = "test-support"))]
379#[must_use]
380pub fn test_exec_context(
381    turn: TurnId,
382    call_id: ToolCallId,
383    workdir: PathBuf,
384) -> (ExecContext, mpsc::Receiver<ProgressEvent>) {
385    let mut config = mermaid_domain::Config::default();
386    config.safety.mode = mermaid_runtime::SafetyMode::FullAccess;
387    test_exec_context_with_config(turn, call_id, workdir, config)
388}
389
390/// [`test_exec_context`] with an explicit `Config` (e.g. `exec.pty = false`
391/// to pin the pipe spawn path, or a `safety.mode` other than `FullAccess`).
392/// The context's safety mode follows `config.safety.mode`, so gate tests can
393/// pick a mode without hand-rolling `ExecContext::assemble`.
394#[cfg(any(test, feature = "test-support"))]
395#[must_use]
396pub fn test_exec_context_with_config(
397    turn: TurnId,
398    call_id: ToolCallId,
399    workdir: PathBuf,
400    config: mermaid_domain::Config,
401) -> (ExecContext, mpsc::Receiver<ProgressEvent>) {
402    let (tx, rx) = mpsc::channel(64);
403    let safety_mode = config.safety.mode;
404    let config = Arc::new(config);
405    (
406        ExecContext::assemble(
407            turn,
408            call_id,
409            tx,
410            TurnSignals::default(),
411            mermaid_domain::ToolDispatch {
412                model_id: String::new(),
413                safety_mode,
414                goal: mermaid_domain::UserGoal::default(),
415                reasoning: mermaid_model::models::ReasoningLevel::default(),
416                session_id: String::new(),
417                message_index: 0,
418                scratchpad: None,
419            },
420            ToolServices {
421                workdir,
422                config,
423                task_id: None,
424                notify: None,
425                classifier: None,
426                approval: None,
427                questions: None,
428                tasks: None,
429            },
430        ),
431        rx,
432    )
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438    use std::path::PathBuf;
439
440    #[tokio::test]
441    async fn stream_context_carries_token_and_turn() {
442        let (ctx, _rx) = test_stream_context(TurnId(5));
443        assert_eq!(ctx.turn, TurnId(5));
444        assert!(!ctx.token.is_cancelled());
445    }
446
447    #[tokio::test]
448    async fn exec_context_propagates_cancel_signal() {
449        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(2), PathBuf::from("/tmp"));
450        let token = ctx.token.clone();
451        tokio::spawn(async move {
452            token.cancel();
453        });
454        // Wait until cancelled.
455        ctx.token.cancelled().await;
456        assert!(ctx.token.is_cancelled());
457    }
458
459    #[tokio::test]
460    async fn progress_event_round_trips_through_channel() {
461        let (ctx, mut rx) = test_exec_context(TurnId(1), ToolCallId(2), PathBuf::from("/tmp"));
462        ctx.progress
463            .send(ProgressEvent::Status("halfway".to_string()))
464            .await
465            .expect("send");
466        match rx.recv().await.expect("recv") {
467            ProgressEvent::Status(s) => assert_eq!(s, "halfway"),
468            _ => panic!("wrong variant"),
469        }
470    }
471
472    #[test]
473    fn web_budget_is_atomic_and_never_crosses_the_turn_limit() {
474        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(2), PathBuf::from("/tmp"));
475        assert_eq!(ctx.charge_web_bytes(1024), Ok(1024));
476        let remaining = mermaid_model::constants::MAX_WEB_TURN_BYTES - 1024;
477        assert_eq!(
478            ctx.charge_web_bytes(remaining),
479            Ok(mermaid_model::constants::MAX_WEB_TURN_BYTES)
480        );
481        assert_eq!(
482            ctx.charge_web_bytes(1),
483            Err(mermaid_model::constants::MAX_WEB_TURN_BYTES)
484        );
485    }
486
487    #[test]
488    fn web_budget_overflow_saturates_and_stays_exhausted() {
489        let budget = WebByteBudget::isolated();
490        let limit = mermaid_model::constants::MAX_WEB_TURN_BYTES;
491        assert_eq!(budget.charge(limit - 1), Ok(limit - 1));
492        assert_eq!(budget.charge(2), Err(limit));
493        assert_eq!(budget.remaining(), 0);
494        assert_eq!(budget.charge(0), Err(limit));
495        assert_eq!(budget.charge(usize::MAX), Err(limit));
496        assert_eq!(budget.remaining(), 0);
497    }
498}