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