Skip to main content

causa_runtime/
executor.rs

1//! Tool batch dispatch — dedup-then-parallel execution with panic isolation,
2//! call-deadline backstop, and token-limit truncation with artifact spill.
3//! Also the tool-catalog composition point: static Rust tools
4//! and dynamic sources (`DynamicToolSource`, e.g. MCP servers) merge into
5//! one dispatch path; the driver only consumes the assembled surface.
6
7use crate::budget::TokenCounter;
8use crate::composition::ToolBridge;
9use crate::config::ToolOutputLimits;
10use causa_kernel::CallControl;
11use causa_kernel::ToolCallPayload;
12use causa_kernel::{
13    ArtifactHint, ArtifactStore, DynamicToolSource, Tool, ToolCallContext, ToolDefinition,
14    ToolSurface,
15};
16use causa_kernel::{
17    ArtifactKind, ArtifactRef, ToolOutput, ToolOutputMeta, ToolResultPayload, ToolResultStatus,
18    Truncation,
19};
20use futures_util::FutureExt;
21use std::collections::HashMap;
22use std::sync::Arc;
23use tracing::Instrument;
24
25/// One registered dynamic source plus its executor-side listing cache.
26/// The cache is keyed by the source's own change signal
27/// ([`DynamicToolSource::version`]) so a stable catalog costs no
28/// round-trip on surface assembly.
29struct DynamicEntry {
30    source: Arc<dyn DynamicToolSource>,
31    cache: std::sync::Mutex<(u64, Vec<ToolDefinition>)>,
32}
33
34/// Dynamic-source registry failures.
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum ToolRegistryError {
37    /// A dynamic source with this id is already registered.
38    #[error("dynamic source already registered: {0}")]
39    DuplicateSource(String),
40    /// No dynamic source registered under this id.
41    #[error("no dynamic source registered: {0}")]
42    UnknownSource(String),
43}
44
45/// The tool dispatcher: static tools plus registered dynamic sources
46/// behind one execution path — parallel batch dispatch with per-call
47/// panic isolation, a call-deadline backstop, and token-limit truncation
48/// with artifact spill.
49pub struct ToolExecutor {
50    tools: HashMap<String, Arc<dyn Tool>>,
51    /// Registered dynamic sources; interior-mutable because the executor
52    /// lives in an `Arc` shared with the driver.
53    dynamic: std::sync::RwLock<Vec<DynamicEntry>>,
54}
55
56impl std::fmt::Debug for ToolExecutor {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("ToolExecutor")
59            .field("tools", &self.tools.keys().collect::<Vec<_>>())
60            .field(
61                "dynamic",
62                &self
63                    .dynamic
64                    .read()
65                    .expect("dynamic lock")
66                    .iter()
67                    .map(|e| e.source.id().to_string())
68                    .collect::<Vec<_>>(),
69            )
70            .finish()
71    }
72}
73
74impl ToolExecutor {
75    /// Build from static tools, keyed by each tool's `definition().name`.
76    pub fn from_vec(tools: Vec<Arc<dyn Tool>>) -> Self {
77        let mut map = HashMap::new();
78        for t in tools {
79            map.insert(t.definition().name.clone(), t);
80        }
81        Self {
82            tools: map,
83            dynamic: std::sync::RwLock::new(Vec::new()),
84        }
85    }
86
87    /// Build from an explicit name → tool map; the keys are the caller's
88    /// responsibility.
89    pub fn from_map(map: HashMap<String, Arc<dyn Tool>>) -> Self {
90        Self {
91            tools: map,
92            dynamic: std::sync::RwLock::new(Vec::new()),
93        }
94    }
95
96    /// Register a dynamic tool source. Its current listing
97    /// enters [`ToolExecutor::tool_surface`], and dispatch routes exactly
98    /// the names that listing advertised (listing membership — naming is
99    /// the source's own business); a name already present in the static
100    /// map keeps winning.
101    pub fn register_dynamic(
102        &self,
103        source: Arc<dyn DynamicToolSource>,
104    ) -> Result<(), ToolRegistryError> {
105        let mut dynamic = self.dynamic.write().expect("dynamic lock");
106        if dynamic.iter().any(|e| e.source.id() == source.id()) {
107            return Err(ToolRegistryError::DuplicateSource(source.id().to_string()));
108        }
109        dynamic.push(DynamicEntry {
110            source,
111            cache: std::sync::Mutex::new((u64::MAX, Vec::new())),
112        });
113        Ok(())
114    }
115
116    /// Remove a dynamic source; returns it for reconnect-and-reregister
117    /// flows.
118    pub fn unregister_dynamic(
119        &self,
120        id: &str,
121    ) -> Result<Arc<dyn DynamicToolSource>, ToolRegistryError> {
122        let mut dynamic = self.dynamic.write().expect("dynamic lock");
123        let pos = dynamic
124            .iter()
125            .position(|e| e.source.id() == id)
126            .ok_or_else(|| ToolRegistryError::UnknownSource(id.to_string()))?;
127        Ok(dynamic.remove(pos).source)
128    }
129
130    /// Ids of the registered dynamic sources.
131    pub fn dynamic_ids(&self) -> Vec<String> {
132        self.dynamic
133            .read()
134            .expect("dynamic lock")
135            .iter()
136            .map(|e| e.source.id().to_string())
137            .collect()
138    }
139
140    /// Assemble the model-facing tool surface: every static tool plus the
141    /// current listing of every reachable dynamic source. A source that
142    /// fails to list keeps serving its last good listing (with a warning);
143    /// a source with no cached listing yet is skipped — either way the
144    /// turn proceeds and the host can unregister/reconnect. Static names
145    /// win collisions, exactly as dispatch does.
146    ///
147    /// Lock discipline: registry and cache guards are never held across
148    /// an `await` — each source is snapshot before the `list()` call and
149    /// re-locked to publish the result (clippy `await_holding_lock`).
150    pub async fn tool_surface(&self) -> ToolSurface {
151        let mut definitions: Vec<ToolDefinition> =
152            self.tools.values().map(|t| t.definition()).collect();
153
154        // Snapshot the dynamic registry so no `RwLockReadGuard` crosses an
155        // await. Each entry is cloned as `(source, cached_version, cached_defs)`.
156        let snapshot: Vec<(Arc<dyn DynamicToolSource>, u64, Vec<ToolDefinition>)> = {
157            let dynamic = self.dynamic.read().expect("dynamic lock");
158            dynamic
159                .iter()
160                .map(|entry| {
161                    let cache = entry.cache.lock().expect("source cache lock");
162                    (entry.source.clone(), cache.0, cache.1.clone())
163                })
164                .collect()
165        };
166
167        for (source, cached_version, cached_defs) in snapshot {
168            let observed = source.version();
169            let listing = if observed == cached_version && cached_version != u64::MAX {
170                Some(cached_defs)
171            } else {
172                match source.list().await {
173                    Ok(fresh) => {
174                        // Publish the refreshed listing back into the cache
175                        // (re-lock by id — the source is still registered).
176                        let dynamic = self.dynamic.read().expect("dynamic lock");
177                        if let Some(entry) = dynamic.iter().find(|e| e.source.id() == source.id()) {
178                            let mut cache = entry.cache.lock().expect("source cache lock");
179                            // Another concurrent surface assembly may have
180                            // already refreshed; keep the newest.
181                            if cache.0 != observed {
182                                cache.0 = observed;
183                                cache.1 = fresh.clone();
184                            }
185                        }
186                        Some(fresh)
187                    }
188                    Err(e) => {
189                        tracing::warn!(
190                            source = source.id(),
191                            error = %e,
192                            "dynamic tool source failed to list; serving its last good listing"
193                        );
194                        (!cached_defs.is_empty()).then_some(cached_defs)
195                    }
196                }
197            };
198            if let Some(defs) = listing {
199                // Surface must match dispatch: a dynamic name that collides
200                // with a static tool is not advertised (the static tool
201                // keeps winning there too).
202                definitions.extend(
203                    defs.into_iter()
204                        .filter(|d| !self.tools.contains_key(&d.name)),
205                );
206            }
207        }
208        ToolSurface::from_definitions(definitions)
209    }
210
211    /// Find the dynamic source owning `tool_name` — routing is by listing
212    /// membership: a source is dispatched exactly the names it advertised
213    /// in [`ToolExecutor::tool_surface`] (the same cache), so naming stays
214    /// the implementor's business and the model can only call what the
215    /// surface showed. Returns the source and its advertised definition
216    /// for the bridge. The registry/cache locks never cross an await.
217    fn find_dynamic(
218        &self,
219        tool_name: &str,
220    ) -> Option<(Arc<dyn DynamicToolSource>, ToolDefinition)> {
221        let dynamic = self.dynamic.read().expect("dynamic lock");
222        dynamic.iter().find_map(|entry| {
223            let cache = entry.cache.lock().expect("source cache lock");
224            cache
225                .1
226                .iter()
227                .find(|d| d.name == tool_name)
228                .map(|d| (entry.source.clone(), d.clone()))
229        })
230    }
231
232    /// Execute a single ToolCallPayload with panic isolation, a call-deadline
233    /// backstop, and token-limit truncation. Returns the recorded result
234    /// only — the caller owns the unknown-outcome action (in the reference
235    /// driver that is the turn policy, resolved by the executed tool name
236    /// before dispatch). The `effective_limits` argument is the already
237    /// chosen per-call limit: the runner resolves the fallback /
238    /// per-tool-name override by the executed name before dispatch; a
239    /// standalone caller passes the limit it wants.
240    pub async fn execute_with_limits(
241        &self,
242        payload: ToolCallPayload,
243        control: CallControl,
244        store: Option<Arc<dyn ArtifactStore>>,
245        token_counter: Option<Arc<dyn TokenCounter>>,
246        effective_limits: ToolOutputLimits,
247    ) -> ToolResultPayload {
248        // One `agent.tool` span per dispatch, name and id only. Entered
249        // per poll via `Instrument`, so the future stays `Send`.
250        let span = tracing::info_span!(
251            "agent.tool",
252            tool_name = %payload.tool_name,
253            call_id = %payload.call_id.0
254        );
255        self.execute_with_limits_inner(payload, control, store, token_counter, effective_limits)
256            .instrument(span)
257            .await
258    }
259
260    async fn execute_with_limits_inner(
261        &self,
262        payload: ToolCallPayload,
263        control: CallControl,
264        store: Option<Arc<dyn ArtifactStore>>,
265        token_counter: Option<Arc<dyn TokenCounter>>,
266        effective_limits: ToolOutputLimits,
267    ) -> ToolResultPayload {
268        // Route: the static map first, then dynamic sources by listing
269        // membership. A dynamic call is wrapped in a [`ToolBridge`] and
270        // runs the exact static path below — panic isolation, call-deadline
271        // backstop, truncation — one code path, one error mapping (the
272        // bridge's).
273        let tool: Option<Arc<dyn Tool>> = match self.tools.get(&payload.tool_name) {
274            Some(tool) => Some(tool.clone()),
275            None => self
276                .find_dynamic(&payload.tool_name)
277                .map(|(source, definition)| {
278                    Arc::new(ToolBridge::new(source, definition)) as Arc<dyn Tool>
279                }),
280        };
281        let Some(tool) = tool else {
282            return ToolResultPayload {
283                call_id: payload.call_id.clone(),
284                status: ToolResultStatus::Rejected,
285                output: ToolOutput::new(
286                    serde_json::json!({"error": format!("unknown tool: {}", payload.tool_name)}),
287                ),
288                media: Vec::new(),
289            };
290        };
291
292        let ctx = ToolCallContext {
293            call_id: payload.call_id.clone(),
294            tool_name: payload.tool_name.clone(),
295            arguments: payload.arguments.clone(),
296        };
297        let store_ref: Option<&dyn ArtifactStore> =
298            store.as_deref().map(|s| s as &dyn ArtifactStore);
299
300        // Panic isolation plus call-deadline backstop: a tool that
301        // neither returns nor observes CallControl still yields a structured
302        // UnknownOutcome instead of hanging the turn.
303        let fut = {
304            let tool = tool.clone();
305            let control = control.clone();
306            std::panic::AssertUnwindSafe(async move {
307                tool.execute_with_store(&ctx, &control, store_ref).await
308            })
309            .catch_unwind()
310        };
311        let mut result = match control.deadline() {
312            Some(deadline) => match tokio::time::timeout_at(deadline.into(), fut).await {
313                Ok(Ok(r)) => r,
314                Ok(Err(_)) => Self::panicked_outcome(&payload),
315                Err(_) => Self::deadline_backstop_outcome(&payload),
316            },
317            None => match fut.await {
318                Ok(r) => r,
319                Err(_) => Self::panicked_outcome(&payload),
320            },
321        };
322
323        // Token-limit truncation (middle truncation + artifact spill).
324        // Shape note: on truncation `content` is REPLACED by a JSON string
325        // (head + notice + tail) regardless of the original `Value` shape —
326        // an object or array observation becomes a string on the wire. The
327        // `truncation: Middle` marker and the artifact ref are how consumers
328        // detect this.
329        //
330        // Budget note: the retained head+tail is sized against the DECLARED
331        // limit, not the original size — the notice and the JSON-string
332        // wrapping are part of the measured output. Every candidate is
333        // re-estimated with the wired estimator and the data budget shrinks
334        // until the result fits, so the committed content re-estimates at or
335        // under `max_tokens` — with one defined floor: when the limit is
336        // smaller than the notice's own estimate, the notice alone is
337        // emitted (nothing smaller is representable).
338        let effective_limit = effective_limits.max_tokens;
339
340        let estimate = |value: &serde_json::Value| -> usize {
341            if let Some(counter) = &token_counter {
342                counter.estimate_value(value)
343            } else {
344                // The driver's fallback opinion — single home in `defaults`.
345                crate::defaults::placeholder_token_estimate_value(value)
346            }
347        };
348        let estimated = estimate(&result.output.content);
349
350        if estimated > effective_limit {
351            let content_str = serde_json::to_string(&result.output.content)
352                .unwrap_or_else(|_| result.output.content.to_string());
353            let data_bytes = serde_json::to_vec(&result.output.content)
354                .unwrap_or_else(|_| content_str.clone().into_bytes());
355
356            let artifact: Option<ArtifactRef> = if let Some(store_arc) = &store {
357                let hint = ArtifactHint {
358                    tool_name: payload.tool_name.clone(),
359                    call_id: payload.call_id.clone(),
360                    kind: ArtifactKind::FullOutput,
361                };
362                store_arc.persist(&data_bytes, hint).await.ok()
363            } else {
364                None
365            };
366
367            let notice = if let Some(ref a) = artifact {
368                format!(
369                    "\n...[truncated: original {} tokens, artifact:{}]...\n",
370                    estimated, a.id
371                )
372            } else {
373                format!(
374                    "\n...[truncated: original {} tokens, showing head+tail]...\n",
375                    estimated
376                )
377            };
378
379            // Initial data budget under the chars/4 heuristic with the
380            // notice's own footprint reserved; the loop re-measures every
381            // candidate with the wired estimator, so any counter converges.
382            // The cut floors at budget/8 (geometric convergence) and 1
383            // (termination); budget 0 leaves the notice as the floor.
384            let mut data_budget = effective_limit
385                .saturating_sub(estimate(&serde_json::Value::String(notice.clone())))
386                .saturating_mul(4);
387            let mut preview_value;
388            loop {
389                let (head, tail) = split_head_tail(&content_str, data_budget);
390                let candidate = serde_json::Value::String(format!("{head}{notice}{tail}"));
391                let candidate_tokens = estimate(&candidate);
392                let fits = candidate_tokens <= effective_limit;
393                preview_value = candidate;
394                if fits || data_budget == 0 {
395                    break;
396                }
397                let cut = (candidate_tokens - effective_limit)
398                    .saturating_mul(4)
399                    .max(data_budget / 8)
400                    .max(1);
401                data_budget = data_budget.saturating_sub(cut);
402            }
403
404            result.output.content = preview_value;
405            result.output.truncation = Truncation::Middle;
406            result.output.artifact = artifact;
407            let prev_meta = result.output.meta.take();
408            result.output.meta = Some(ToolOutputMeta {
409                duration_ms: prev_meta.as_ref().and_then(|m| m.duration_ms),
410                original_tokens: Some(estimated),
411                extra: prev_meta.as_ref().and_then(|m| m.extra.clone()),
412            });
413        }
414
415        result
416    }
417
418    fn panicked_outcome(payload: &ToolCallPayload) -> ToolResultPayload {
419        ToolResultPayload {
420            call_id: payload.call_id.clone(),
421            status: ToolResultStatus::Failed,
422            output: ToolOutput::new(serde_json::json!({"error": "tool panicked"})),
423            media: Vec::new(),
424        }
425    }
426
427    fn deadline_backstop_outcome(payload: &ToolCallPayload) -> ToolResultPayload {
428        ToolResultPayload {
429            call_id: payload.call_id.clone(),
430            status: ToolResultStatus::UnknownOutcome,
431            output: ToolOutput {
432                content: serde_json::json!({"error": "tool did not return before call deadline"}),
433                truncation: Truncation::None,
434                meta: Some(ToolOutputMeta {
435                    duration_ms: None,
436                    original_tokens: None,
437                    extra: Some(serde_json::json!({"reason": "call_deadline_backstop"})),
438                }),
439                artifact: None,
440            },
441            media: Vec::new(),
442        }
443    }
444}
445
446/// Head+tail preview split of `s` totalling at most `budget` bytes
447/// (60% head / 40% tail), each cut at a char boundary and never
448/// overlapping — the retained amount follows the budget, never the
449/// original size.
450fn split_head_tail(s: &str, budget: usize) -> (&str, &str) {
451    let kept = budget.min(s.len());
452    let head_end = floor_char_boundary(s, kept * 3 / 5);
453    let tail_start = ceil_char_boundary(s, s.len() - (kept - head_end));
454    (&s[..head_end], &s[tail_start..])
455}
456
457fn floor_char_boundary(s: &str, mut idx: usize) -> usize {
458    if idx >= s.len() {
459        return s.len();
460    }
461    while idx > 0 && !s.is_char_boundary(idx) {
462        idx -= 1;
463    }
464    idx
465}
466fn ceil_char_boundary(s: &str, mut idx: usize) -> usize {
467    if idx >= s.len() {
468        return s.len();
469    }
470    while idx < s.len() && !s.is_char_boundary(idx) {
471        idx += 1;
472    }
473    idx
474}