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 std::path::PathBuf;
22use std::sync::Arc;
23
24use tokio::sync::mpsc;
25use tokio_util::sync::CancellationToken;
26
27use crate::domain::{ToolCallId, TurnId};
28use crate::models::tool_call::ToolCall as ModelToolCall;
29use crate::models::{ChatMessage, ReasoningChunk, TokenUsage};
30use crate::runtime::SafetyMode;
31
32use super::approval::ApprovalBroker;
33use super::auto_classifier::AutoClassifier;
34
35/// What a `ModelProvider::chat()` receives.
36#[derive(Debug)]
37pub struct StreamContext {
38    pub token: CancellationToken,
39    pub sink: mpsc::Sender<StreamEvent>,
40    pub turn: TurnId,
41}
42
43impl StreamContext {
44    pub fn new(token: CancellationToken, sink: mpsc::Sender<StreamEvent>, turn: TurnId) -> Self {
45        Self { token, sink, turn }
46    }
47}
48
49/// One event emitted during a streaming model call. Adapters MUST
50/// emit exactly one `Done` at the end of a successful stream. `Text`
51/// and `Reasoning` may interleave. `ToolCall` events typically arrive
52/// near the end but the contract is "before `Done`".
53#[derive(Debug, Clone)]
54pub enum StreamEvent {
55    Text(String),
56    Reasoning(ReasoningChunk),
57    ToolCall(ModelToolCall),
58    /// Optional — some providers emit a signature mid-stream
59    /// (Anthropic). Adapters that only have it at the end can attach
60    /// it to `Done` instead.
61    ThinkingSignature(String),
62    /// Stream complete. Carries final token usage (None if unknown)
63    /// and any terminal thinking signature.
64    Done {
65        usage: Option<TokenUsage>,
66        thinking_signature: Option<String>,
67    },
68}
69
70/// Final response returned by `ModelProvider::chat()` after the
71/// stream drains. Carries what the reducer can't derive from the
72/// stream events themselves — token usage and the opaque thinking
73/// signature needed for Anthropic extended-thinking continuation.
74#[derive(Debug, Clone)]
75pub struct FinalResponse {
76    pub usage: Option<TokenUsage>,
77    pub thinking_signature: Option<String>,
78    pub tool_calls: Vec<ModelToolCall>,
79}
80
81/// What a `ToolExecutor::execute()` receives.
82pub struct ExecContext {
83    pub token: CancellationToken,
84    pub progress: mpsc::Sender<ProgressEvent>,
85    pub call_id: ToolCallId,
86    pub turn: TurnId,
87    pub workdir: PathBuf,
88    /// Parent session's `app::Config`. Needed by `SubagentTool` so the
89    /// child reducer uses the same Ollama host, reasoning prefs, MCP
90    /// servers, etc. Other tools don't consult it — keeping it as a
91    /// typed field (rather than a global) means the dependency is
92    /// explicit in the signature.
93    pub config: Arc<crate::app::Config>,
94    /// Parent session's active model id (e.g. `"anthropic/claude-opus-4-7"`).
95    /// Subagents inherit this so they hit the same provider.
96    pub model_id: String,
97    /// Durable daemon task that owns this tool call, when execution was
98    /// launched through the runtime task queue.
99    pub task_id: Option<String>,
100    /// Effective live safety mode for this call (from the session, not the
101    /// static config). The policy gate builds its `PolicyEngine` from this.
102    pub safety_mode: SafetyMode,
103    /// The user's stated intent for the turn (latest user message), passed to
104    /// the Auto-mode classifier so it can judge whether an action is aligned.
105    pub intent: Option<String>,
106    /// LLM classifier for `SafetyMode::Auto`. `Some` only when the effective
107    /// mode is `Auto` and a provider is bound; the gate awaits it to resolve a
108    /// `PolicyDecision::Classify`. `None` ⇒ the gate fails safe (escalate).
109    pub classifier: Option<Arc<dyn AutoClassifier>>,
110    /// Inline-approval back-channel (interactive runs only). `Some` lets the
111    /// gate prompt the user and park until they answer; `None` (headless) falls
112    /// back to the out-of-band DB-approval flow.
113    pub approval: Option<ApprovalBroker>,
114}
115
116impl std::fmt::Debug for ExecContext {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        // `classifier` is a trait object (no `Debug`); render its presence.
119        f.debug_struct("ExecContext")
120            .field("call_id", &self.call_id)
121            .field("turn", &self.turn)
122            .field("workdir", &self.workdir)
123            .field("model_id", &self.model_id)
124            .field("task_id", &self.task_id)
125            .field("safety_mode", &self.safety_mode)
126            .field("intent", &self.intent)
127            .field(
128                "classifier",
129                &self.classifier.as_ref().map(|_| "<dyn AutoClassifier>"),
130            )
131            .field(
132                "approval",
133                &self.approval.as_ref().map(|_| "<ApprovalBroker>"),
134            )
135            .finish_non_exhaustive()
136    }
137}
138
139impl ExecContext {
140    #[allow(clippy::too_many_arguments)]
141    pub fn new(
142        token: CancellationToken,
143        progress: mpsc::Sender<ProgressEvent>,
144        call_id: ToolCallId,
145        turn: TurnId,
146        workdir: PathBuf,
147        config: Arc<crate::app::Config>,
148        model_id: String,
149        task_id: Option<String>,
150        safety_mode: SafetyMode,
151        intent: Option<String>,
152        classifier: Option<Arc<dyn AutoClassifier>>,
153        approval: Option<ApprovalBroker>,
154    ) -> Self {
155        Self {
156            token,
157            progress,
158            call_id,
159            turn,
160            workdir,
161            config,
162            model_id,
163            task_id,
164            safety_mode,
165            intent,
166            classifier,
167            approval,
168        }
169    }
170}
171
172/// Tool-side progress event. The reducer already knows `ToolStarted`
173/// and `ToolFinished`; this carries everything in between (streaming
174/// subprocess output, long-running download status, multimodal
175/// artifacts like inline screenshots, and nested activity from
176/// subagents).
177#[derive(Debug, Clone)]
178pub enum ProgressEvent {
179    /// Partial stdout/stderr chunk.
180    Output(String),
181    /// Arbitrary status string for display.
182    Status(String),
183    /// Byte-count progress for long downloads/transfers. `total` is
184    /// None when the producer doesn't know the final size.
185    Bytes { done: u64, total: Option<u64> },
186    /// Binary artifact produced mid-execution (screenshot preview,
187    /// generated file, etc.). MIME string determines routing in the
188    /// reducer — `image/*` attaches inline to the active assistant
189    /// message; anything else lands on the status line as a label.
190    Artifact {
191        mime: String,
192        data: Vec<u8>,
193        caption: Option<String>,
194    },
195    /// A child subagent just started or finished a tool call. Carries
196    /// the CHILD's call identity + tool name + phase so the parent UI
197    /// can surface it without needing to recurse into the child's
198    /// event vocabulary.
199    SubagentToolCall {
200        child_call_id: ToolCallId,
201        tool_name: String,
202        phase: SubagentPhase,
203    },
204    /// A chunk of assistant text produced by a child subagent. Mostly
205    /// UI flavor — lets the parent status line show what the sub is
206    /// "saying" in real time.
207    SubagentText(String),
208}
209
210/// Phase a subagent tool-call is in, from the parent's perspective.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub enum SubagentPhase {
213    Started,
214    Finished,
215    Errored,
216}
217
218/// Narrow shim from the reducer's `ChatRequest` to the adapter-facing
219/// messages. Providers often want to mutate the last assistant
220/// message (e.g. Anthropic cache_control injection); this helper
221/// clones the slice as owned so the provider can do that without
222/// fighting the borrow checker.
223pub fn clone_messages(msgs: &[ChatMessage]) -> Vec<ChatMessage> {
224    msgs.to_vec()
225}
226
227/// Builder that lets tests construct a pair of `StreamContext` +
228/// receiver without needing a runtime. Used by provider unit tests
229/// and by integration harnesses in C9.
230pub fn test_stream_context(turn: TurnId) -> (StreamContext, mpsc::Receiver<StreamEvent>) {
231    let token = CancellationToken::new();
232    let (tx, rx) = mpsc::channel(64);
233    (StreamContext::new(token, tx, turn), rx)
234}
235
236/// Builder counterpart for `ExecContext`. Uses a `Config` pinned to
237/// `SafetyMode::FullAccess` (the production default is now `Ask`) so tool
238/// unit tests exercise the tool's own behavior rather than the approval
239/// gate. Tests that specifically exercise policy gating should construct
240/// `ExecContext::new` directly with their chosen safety mode.
241pub fn test_exec_context(
242    turn: TurnId,
243    call_id: ToolCallId,
244    workdir: PathBuf,
245) -> (ExecContext, mpsc::Receiver<ProgressEvent>) {
246    let token = CancellationToken::new();
247    let (tx, rx) = mpsc::channel(64);
248    let mut config = crate::app::Config::default();
249    config.safety.mode = crate::runtime::SafetyMode::FullAccess;
250    let config = Arc::new(config);
251    (
252        ExecContext::new(
253            token,
254            tx,
255            call_id,
256            turn,
257            workdir,
258            config,
259            String::new(),
260            None,
261            crate::runtime::SafetyMode::FullAccess,
262            None,
263            None,
264            None,
265        ),
266        rx,
267    )
268}
269
270/// Convenience: build a Send+Sync sharable sink for tests.
271pub fn arc_sink(tx: mpsc::Sender<StreamEvent>) -> Arc<mpsc::Sender<StreamEvent>> {
272    Arc::new(tx)
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use std::path::PathBuf;
279
280    #[tokio::test]
281    async fn stream_context_carries_token_and_turn() {
282        let (ctx, _rx) = test_stream_context(TurnId(5));
283        assert_eq!(ctx.turn, TurnId(5));
284        assert!(!ctx.token.is_cancelled());
285    }
286
287    #[tokio::test]
288    async fn exec_context_propagates_cancel_signal() {
289        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(2), PathBuf::from("/tmp"));
290        let token = ctx.token.clone();
291        tokio::spawn(async move {
292            token.cancel();
293        });
294        // Wait until cancelled.
295        ctx.token.cancelled().await;
296        assert!(ctx.token.is_cancelled());
297    }
298
299    #[tokio::test]
300    async fn progress_event_round_trips_through_channel() {
301        let (ctx, mut rx) = test_exec_context(TurnId(1), ToolCallId(2), PathBuf::from("/tmp"));
302        ctx.progress
303            .send(ProgressEvent::Status("halfway".to_string()))
304            .await
305            .expect("send");
306        match rx.recv().await.expect("recv") {
307            ProgressEvent::Status(s) => assert_eq!(s, "halfway"),
308            _ => panic!("wrong variant"),
309        }
310    }
311}