nexil 0.6.2

Provider-agnostic LLM toolkit — streaming, tool calls, tape storage, OAuth
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Tool execution helpers for Conduit.

use crate::core::errors::{ConduitError, ErrorKind};
use crate::core::results::{ErrorPayload, ToolExecution};
use crate::core::tool_calls::normalize_tool_calls;
use crate::tools::context::ToolContext;
use crate::tools::schema::{Tool, ToolResult};
use serde_json::Value;
use std::collections::HashMap;

/// Executes tool calls parsed from LLM responses.
#[derive(Debug, Clone)]
pub struct ToolExecutor;

impl ToolExecutor {
    /// Create a new `ToolExecutor`.
    pub fn new() -> Self {
        Self
    }

    /// Execute tool calls synchronously by blocking on the async runtime.
    ///
    /// Prefer `execute_async` instead.
    ///
    /// # Panics
    /// Panics if called from within an async runtime context.
    pub fn execute(
        &self,
        response: ToolCallResponse,
        tools: &[Tool],
        context: Option<&ToolContext>,
    ) -> Result<ToolExecution, ConduitError> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| {
                ConduitError::new(ErrorKind::Unknown, format!("Failed to create runtime: {e}"))
            })?;
        rt.block_on(self.execute_async(response, tools, context))
    }

    /// Execute tool calls asynchronously.
    pub async fn execute_async(
        &self,
        response: ToolCallResponse,
        tools: &[Tool],
        context: Option<&ToolContext>,
    ) -> Result<ToolExecution, ConduitError> {
        let tool_calls = self.normalize_response(response)?;
        let tool_map = self.build_tool_map(tools);

        if tool_map.is_empty() {
            if !tool_calls.is_empty() {
                return Err(ConduitError::new(
                    ErrorKind::Tool,
                    "No runnable tools are available.",
                ));
            }
            return Ok(ToolExecution::default());
        }

        let mut results = Vec::with_capacity(tool_calls.len());
        let mut first_error: Option<ErrorPayload> = None;

        for call in &tool_calls {
            match self.handle_tool_call(call, &tool_map, context).await {
                Ok(result) => results.push(result),
                Err(err) => {
                    let payload = ErrorPayload::new(err.kind, &err.message);
                    let err_value = serde_json::to_value(&payload).unwrap_or(Value::Null);
                    if first_error.is_none() {
                        first_error = Some(payload);
                    }
                    results.push(err_value);
                }
            }
        }

        Ok(ToolExecution {
            tool_calls,
            tool_results: results,
            error: first_error,
        })
    }

    /// Resolve a single tool call to (name, tool, args).
    fn resolve_tool_call<'a>(
        &self,
        call: &'a Value,
        tool_map: &'a HashMap<String, &'a Tool>,
    ) -> Result<(&'a str, &'a Tool, Value), ConduitError> {
        let obj = call.as_object().ok_or_else(|| {
            ConduitError::new(ErrorKind::InvalidInput, "Each tool call must be an object.")
        })?;

        let function = obj
            .get("function")
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                ConduitError::new(
                    ErrorKind::InvalidInput,
                    "Tool call is missing function object.",
                )
            })?;

        let name = function
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ConduitError::new(ErrorKind::InvalidInput, "Tool call is missing name.")
            })?;

        let tool = self.resolve_tool(name, tool_map).ok_or_else(|| {
            ConduitError::new(ErrorKind::Tool, format!("Unknown tool name: {name}."))
        })?;
        let resolved_name = tool.name.as_str();

        let raw_args = function
            .get("arguments")
            .cloned()
            .unwrap_or(Value::Object(Default::default()));
        let args = self.normalize_tool_args(resolved_name, raw_args)?;

        Ok((resolved_name, tool, args))
    }

    /// Resolve a tool name with dot/underscore alias fallback.
    fn resolve_tool<'a>(
        &self,
        name: &str,
        tool_map: &'a HashMap<String, &'a Tool>,
    ) -> Option<&'a Tool> {
        tool_map
            .get(name)
            .copied()
            .or_else(|| {
                if name.contains('_') {
                    tool_map.get(&name.replace('_', ".")).copied()
                } else {
                    None
                }
            })
            .or_else(|| {
                if name.contains('.') {
                    tool_map.get(&name.replace('.', "_")).copied()
                } else {
                    None
                }
            })
    }

    /// Handle a single tool call, invoking the handler.
    async fn handle_tool_call(
        &self,
        call: &Value,
        tool_map: &HashMap<String, &Tool>,
        context: Option<&ToolContext>,
    ) -> ToolResult {
        let (name, tool, args) = self.resolve_tool_call(call, tool_map)?;

        if tool.context && context.is_none() {
            return Err(ConduitError::new(
                ErrorKind::InvalidInput,
                format!("Tool '{name}' requires context but none was provided."),
            ));
        }

        let ctx = if tool.context { context.cloned() } else { None };

        tool.run(args, ctx).await.map_err(|e| {
            ConduitError::new(
                ErrorKind::Tool,
                format!("Tool '{name}' execution failed: {e}"),
            )
        })
    }

    /// Normalize a response from the model into a list of tool call objects.
    fn normalize_response(&self, response: ToolCallResponse) -> Result<Vec<Value>, ConduitError> {
        match response {
            ToolCallResponse::Json(s) => {
                let parsed: Value = serde_json::from_str(&s).map_err(|e| {
                    ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!("Tool response is not valid JSON: {e}"),
                    )
                })?;
                self.normalize_response(ToolCallResponse::Value(parsed))
            }
            ToolCallResponse::Value(val) => match val {
                Value::Array(arr) => self.normalize_tool_calls(arr),
                Value::Object(obj) => {
                    if let Some(output) = obj.get("output").and_then(|v| v.as_array()) {
                        self.normalize_tool_calls(output.to_vec())
                    } else if let Some(content) = obj.get("content").and_then(|v| v.as_array()) {
                        self.normalize_tool_calls(content.to_vec())
                    } else if let Some(tool_calls) =
                        obj.get("tool_calls").and_then(|v| v.as_array())
                    {
                        self.normalize_tool_calls(tool_calls.to_vec())
                    } else {
                        self.normalize_tool_calls(vec![Value::Object(obj)])
                    }
                }
                _ => Err(ConduitError::new(
                    ErrorKind::InvalidInput,
                    "Tool response must be a list of objects.",
                )),
            },
            ToolCallResponse::List(list) => self.normalize_tool_calls(list),
        }
    }

    fn normalize_tool_calls(&self, raw_calls: Vec<Value>) -> Result<Vec<Value>, ConduitError> {
        let normalized = normalize_tool_calls(&raw_calls);
        if raw_calls.is_empty() || !normalized.is_empty() {
            return Ok(normalized);
        }

        Err(ConduitError::new(
            ErrorKind::InvalidInput,
            "Tool response did not contain any valid tool calls.",
        ))
    }

    /// Build a name -> Tool lookup from a slice of tools.
    fn build_tool_map<'a>(&self, tools: &'a [Tool]) -> HashMap<String, &'a Tool> {
        let mut map = HashMap::new();
        for tool in tools {
            if tool.is_runnable() && !tool.name.is_empty() {
                map.insert(tool.name.clone(), tool);
            }
        }
        map
    }

    /// Parse arguments from string or object form.
    fn normalize_tool_args(&self, tool_name: &str, args: Value) -> Result<Value, ConduitError> {
        match args {
            Value::String(s) => {
                let parsed: Value = serde_json::from_str(&s).map_err(|_| {
                    ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!("Tool '{tool_name}' arguments are not valid JSON."),
                    )
                })?;
                if parsed.is_object() {
                    Ok(parsed)
                } else {
                    Err(ConduitError::new(
                        ErrorKind::InvalidInput,
                        format!("Tool '{tool_name}' arguments must be an object."),
                    ))
                }
            }
            Value::Object(_) => Ok(args),
            _ => Err(ConduitError::new(
                ErrorKind::InvalidInput,
                format!("Tool '{tool_name}' arguments must be an object."),
            )),
        }
    }
}

impl Default for ToolExecutor {
    fn default() -> Self {
        Self::new()
    }
}

/// Wrapper for the various shapes a tool-call response can take.
pub enum ToolCallResponse {
    /// Raw JSON string.
    Json(String),
    /// Already-parsed JSON value.
    Value(Value),
    /// Pre-split list of tool call objects.
    List(Vec<Value>),
}

impl From<String> for ToolCallResponse {
    fn from(s: String) -> Self {
        Self::Json(s)
    }
}

impl From<&str> for ToolCallResponse {
    fn from(s: &str) -> Self {
        Self::Json(s.to_string())
    }
}

impl From<Value> for ToolCallResponse {
    fn from(v: Value) -> Self {
        Self::Value(v)
    }
}

impl From<Vec<Value>> for ToolCallResponse {
    fn from(v: Vec<Value>) -> Self {
        Self::List(v)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::schema::Tool;
    use serde_json::json;

    fn make_echo_tool() -> Tool {
        Tool::new(
            "echo",
            "Echo the input",
            json!({"type": "object", "properties": {"msg": {"type": "string"}}}),
            |args, _ctx| {
                Box::pin(async move {
                    let msg = args.get("msg").and_then(|v| v.as_str()).unwrap_or("(none)");
                    Ok(json!({"echoed": msg}))
                })
            },
        )
    }

    fn make_failing_tool() -> Tool {
        Tool::new(
            "fail",
            "Always fails",
            json!({"type": "object", "properties": {}}),
            |_args, _ctx| {
                Box::pin(
                    async move { Err(ConduitError::new(ErrorKind::Tool, "intentional failure")) },
                )
            },
        )
    }

    fn tool_call_json(name: &str, args: Value) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": name,
                "arguments": args,
            }
        })
    }

    // ----- ToolExecutor basic creation -----

    #[test]
    fn test_executor_creation() {
        let executor = ToolExecutor::new();
        let default_executor = ToolExecutor::default();
        // Both should be usable; ToolExecutor is a unit struct
        let _ = format!("{:?}", executor);
        let _ = format!("{:?}", default_executor);
    }

    // ----- execute_async with mock tool -----

    #[tokio::test]
    async fn test_execute_async_single_tool_call() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let call = tool_call_json("echo", json!({"msg": "hello"}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[echo], None)
            .await
            .unwrap();

        assert_eq!(result.tool_calls.len(), 1);
        assert_eq!(result.tool_results.len(), 1);
        assert!(result.error.is_none());
        assert_eq!(result.tool_results[0]["echoed"], "hello");
    }

    #[tokio::test]
    async fn test_execute_async_accepts_responses_function_call_shape() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let call = json!({
            "type": "function_call",
            "call_id": "call_123",
            "name": "echo",
            "arguments": "{\"msg\": \"hello\"}"
        });

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[echo], None)
            .await
            .unwrap();

        assert!(result.error.is_none());
        assert_eq!(result.tool_calls[0]["id"], "call_123");
        assert_eq!(result.tool_calls[0]["function"]["name"], "echo");
        assert_eq!(result.tool_results[0]["echoed"], "hello");
    }

    #[tokio::test]
    async fn test_execute_async_multiple_tool_calls() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let calls = vec![
            tool_call_json("echo", json!({"msg": "first"})),
            tool_call_json("echo", json!({"msg": "second"})),
        ];

        let result = executor
            .execute_async(ToolCallResponse::List(calls), &[echo], None)
            .await
            .unwrap();

        assert_eq!(result.tool_calls.len(), 2);
        assert_eq!(result.tool_results.len(), 2);
        assert!(result.error.is_none());
        assert_eq!(result.tool_results[0]["echoed"], "first");
        assert_eq!(result.tool_results[1]["echoed"], "second");
    }

    // ----- Unknown tool name -----

    #[tokio::test]
    async fn test_execute_async_unknown_tool_name() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let call = tool_call_json("nonexistent", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[echo], None)
            .await
            .unwrap();

        // Should have an error for the unknown tool
        assert!(result.error.is_some());
        assert_eq!(result.error.unwrap().kind, ErrorKind::Tool);
    }

    #[tokio::test]
    async fn test_execute_async_resolves_underscore_alias_for_dotted_tool() {
        let executor = ToolExecutor::new();
        let tool = Tool::new(
            "tape.info",
            "Tape info",
            json!({"type": "object", "properties": {}}),
            |_args, _ctx| Box::pin(async { Ok(json!({"ok": true})) }),
        );
        let call = tool_call_json("tape_info", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[tool], None)
            .await
            .unwrap();

        assert!(result.error.is_none());
        assert_eq!(result.tool_results[0]["ok"], true);
    }

    #[tokio::test]
    async fn test_execute_async_resolves_dotted_alias_for_underscore_tool() {
        let executor = ToolExecutor::new();
        let tool = Tool::new(
            "tape_info",
            "Tape info",
            json!({"type": "object", "properties": {}}),
            |_args, _ctx| Box::pin(async { Ok(json!({"ok": true})) }),
        );
        let call = tool_call_json("tape.info", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[tool], None)
            .await
            .unwrap();

        assert!(result.error.is_none());
        assert_eq!(result.tool_results[0]["ok"], true);
    }

    // ----- No tools available -----

    #[tokio::test]
    async fn test_execute_async_no_tools_with_calls_errors() {
        let executor = ToolExecutor::new();
        let call = tool_call_json("echo", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[], None)
            .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind, ErrorKind::Tool);
    }

    #[tokio::test]
    async fn test_execute_async_no_tools_no_calls_ok() {
        let executor = ToolExecutor::new();

        let result = executor
            .execute_async(ToolCallResponse::List(vec![]), &[], None)
            .await
            .unwrap();

        assert!(result.tool_calls.is_empty());
        assert!(result.tool_results.is_empty());
        assert!(result.error.is_none());
    }

    // ----- Tool that fails -----

    #[tokio::test]
    async fn test_execute_async_tool_failure_captured_in_error() {
        let executor = ToolExecutor::new();
        let fail = make_failing_tool();
        let call = tool_call_json("fail", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[fail], None)
            .await
            .unwrap();

        assert!(result.error.is_some());
        let err = result.error.unwrap();
        assert_eq!(err.kind, ErrorKind::Tool);
        assert!(err.message.contains("execution failed"));
    }

    // ----- normalize_response -----

    #[tokio::test]
    async fn test_normalize_response_json_string() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let json_str =
            serde_json::to_string(&vec![tool_call_json("echo", json!({"msg": "hi"}))]).unwrap();

        let result = executor
            .execute_async(ToolCallResponse::Json(json_str), &[echo], None)
            .await
            .unwrap();

        assert_eq!(result.tool_results.len(), 1);
        assert_eq!(result.tool_results[0]["echoed"], "hi");
    }

    #[tokio::test]
    async fn test_normalize_response_single_object() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let single = tool_call_json("echo", json!({"msg": "single"}));

        let result = executor
            .execute_async(ToolCallResponse::Value(single), &[echo], None)
            .await
            .unwrap();

        assert_eq!(result.tool_results.len(), 1);
        assert_eq!(result.tool_results[0]["echoed"], "single");
    }

    #[tokio::test]
    async fn test_normalize_response_invalid_json() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();

        let result = executor
            .execute_async(
                ToolCallResponse::Json("not-json".to_string()),
                &[echo],
                None,
            )
            .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidInput);
    }

    #[tokio::test]
    async fn test_normalize_response_rejects_primitive() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();

        let result = executor
            .execute_async(ToolCallResponse::Value(json!(42)), &[echo], None)
            .await;

        assert!(result.is_err());
    }

    // ----- String arguments parsing -----

    #[tokio::test]
    async fn test_string_arguments_are_parsed() {
        let executor = ToolExecutor::new();
        let echo = make_echo_tool();
        let call = json!({
            "type": "function",
            "function": {
                "name": "echo",
                "arguments": "{\"msg\": \"from_string\"}"
            }
        });

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[echo], None)
            .await
            .unwrap();

        assert_eq!(result.tool_results[0]["echoed"], "from_string");
    }

    // ----- ToolCallResponse conversions -----

    #[test]
    fn test_tool_call_response_from_string() {
        let resp: ToolCallResponse = String::from("[]").into();
        matches!(resp, ToolCallResponse::Json(_));
    }

    #[test]
    fn test_tool_call_response_from_str() {
        let resp: ToolCallResponse = "[]".into();
        matches!(resp, ToolCallResponse::Json(_));
    }

    #[test]
    fn test_tool_call_response_from_value() {
        let resp: ToolCallResponse = json!([]).into();
        matches!(resp, ToolCallResponse::Value(_));
    }

    #[test]
    fn test_tool_call_response_from_vec() {
        let resp: ToolCallResponse = vec![json!({})].into();
        matches!(resp, ToolCallResponse::List(_));
    }

    // ----- Context-requiring tool without context -----

    #[tokio::test]
    async fn test_context_tool_without_context_errors() {
        let tool = Tool::with_context(
            "ctx_tool",
            "Needs context",
            json!({"type": "object", "properties": {}}),
            |_args, _ctx| Box::pin(async { Ok(json!("ok")) }),
        );
        let executor = ToolExecutor::new();
        let call = tool_call_json("ctx_tool", json!({}));

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[tool], None)
            .await
            .unwrap();

        assert!(result.error.is_some());
        assert!(result.error.unwrap().message.contains("requires context"));
    }

    // ----- Context-requiring tool with context -----

    #[tokio::test]
    async fn test_context_tool_with_context_succeeds() {
        let tool = Tool::with_context(
            "ctx_tool",
            "Needs context",
            json!({"type": "object", "properties": {}}),
            |_args, ctx| {
                Box::pin(async move {
                    let run_id = ctx.map(|c| c.run_id).unwrap_or_default();
                    Ok(json!({"run_id": run_id}))
                })
            },
        );
        let executor = ToolExecutor::new();
        let call = tool_call_json("ctx_tool", json!({}));
        let context = ToolContext::new("test-run-123");

        let result = executor
            .execute_async(ToolCallResponse::List(vec![call]), &[tool], Some(&context))
            .await
            .unwrap();

        assert!(result.error.is_none());
        assert_eq!(result.tool_results[0]["run_id"], "test-run-123");
    }
}