1use 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
25struct DynamicEntry {
30 source: Arc<dyn DynamicToolSource>,
31 cache: std::sync::Mutex<(u64, Vec<ToolDefinition>)>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum ToolRegistryError {
37 #[error("dynamic source already registered: {0}")]
39 DuplicateSource(String),
40 #[error("no dynamic source registered: {0}")]
42 UnknownSource(String),
43}
44
45pub struct ToolExecutor {
50 tools: HashMap<String, Arc<dyn Tool>>,
51 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 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 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 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 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 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 pub async fn tool_surface(&self) -> ToolSurface {
151 let mut definitions: Vec<ToolDefinition> =
152 self.tools.values().map(|t| t.definition()).collect();
153
154 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 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 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 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 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 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 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 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 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 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 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 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
446fn 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}