traitclaw-core 1.0.0

Core traits, types, and runtime for the TraitClaw AI Agent Framework
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
//! Tool execution strategies for configurable concurrency.
//!
//! By default, tools are executed sequentially. Use [`ParallelStrategy`] for
//! concurrent execution or [`AdaptiveStrategy`] to let the [`Tracker`] decide.
//!
//! [`Tracker`]: crate::traits::tracker::Tracker

use std::sync::Arc;

use async_trait::async_trait;

use crate::traits::guard::{Guard, GuardResult};
use crate::traits::tool::ErasedTool;
use crate::traits::tracker::Tracker;
use crate::types::action::Action;
use crate::types::agent_state::AgentState;
use crate::types::tool_call::ToolCall;

/// A pending tool call to be executed by a strategy.
#[derive(Debug, Clone)]
pub struct PendingToolCall {
    /// Unique identifier for the tool call.
    pub id: String,
    /// Name of the tool to invoke.
    pub name: String,
    /// JSON arguments for the tool.
    pub arguments: serde_json::Value,
}

impl From<&ToolCall> for PendingToolCall {
    fn from(tc: &ToolCall) -> Self {
        Self {
            id: tc.id.clone(),
            name: tc.name.clone(),
            arguments: tc.arguments.clone(),
        }
    }
}

/// The result of executing a single tool call.
#[derive(Debug, Clone)]
pub struct ToolResult {
    /// ID of the tool call this result corresponds to.
    pub id: String,
    /// Output string (may be an error message if execution failed).
    pub output: String,
}

/// Trait for pluggable tool execution strategies.
///
/// Implementations control how a batch of tool calls are executed —
/// sequentially, in parallel, or with custom logic.
#[async_trait]
pub trait ExecutionStrategy: Send + Sync {
    /// Execute a batch of tool calls and return results.
    async fn execute_batch(
        &self,
        calls: Vec<PendingToolCall>,
        tools: &[Arc<dyn ErasedTool>],
        guards: &[Arc<dyn Guard>],
        state: &AgentState,
    ) -> Vec<ToolResult>;
}

// ───────────────────────────── Sequential ─────────────────────────────

/// Execute tool calls one at a time in order.
///
/// This is the default strategy — safe and predictable.
pub struct SequentialStrategy;

#[async_trait]
impl ExecutionStrategy for SequentialStrategy {
    async fn execute_batch(
        &self,
        calls: Vec<PendingToolCall>,
        tools: &[Arc<dyn ErasedTool>],
        guards: &[Arc<dyn Guard>],
        _state: &AgentState,
    ) -> Vec<ToolResult> {
        let mut results = Vec::with_capacity(calls.len());
        for call in calls {
            let output = execute_single(&call, tools, guards).await;
            results.push(ToolResult {
                id: call.id,
                output,
            });
        }
        results
    }
}

// ───────────────────────────── Parallel ─────────────────────────────

/// Execute tool calls concurrently with bounded concurrency.
pub struct ParallelStrategy {
    /// Maximum number of concurrent tool executions.
    pub max_concurrency: usize,
}

impl ParallelStrategy {
    /// Create a parallel strategy with the given concurrency limit.
    #[must_use]
    pub fn new(max_concurrency: usize) -> Self {
        Self {
            max_concurrency: max_concurrency.max(1),
        }
    }
}

#[async_trait]
impl ExecutionStrategy for ParallelStrategy {
    async fn execute_batch(
        &self,
        calls: Vec<PendingToolCall>,
        tools: &[Arc<dyn ErasedTool>],
        guards: &[Arc<dyn Guard>],
        _state: &AgentState,
    ) -> Vec<ToolResult> {
        use tokio::sync::Semaphore;

        let semaphore = Arc::new(Semaphore::new(self.max_concurrency));
        let tools = Arc::new(tools.to_vec());
        let guards = Arc::new(guards.to_vec());

        // P3 fix: pre-clone call IDs before moving calls into spawned tasks,
        // so we can attribute errors correctly if a task panics.
        let call_ids: Vec<String> = calls.iter().map(|c| c.id.clone()).collect();
        let mut handles = Vec::with_capacity(calls.len());

        for call in calls {
            let sem = semaphore.clone();
            let tools = tools.clone();
            let guards = guards.clone();

            handles.push(tokio::spawn(async move {
                let _permit = sem.acquire().await.expect("semaphore closed");
                let output = execute_single(&call, &tools, &guards).await;
                ToolResult {
                    id: call.id,
                    output,
                }
            }));
        }

        let mut results = Vec::with_capacity(handles.len());
        for (i, handle) in handles.into_iter().enumerate() {
            match handle.await {
                Ok(result) => results.push(result),
                Err(e) => results.push(ToolResult {
                    id: call_ids[i].clone(),
                    output: format!("Error: task panicked: {e}"),
                }),
            }
        }
        results
    }
}

// ───────────────────────────── Adaptive ─────────────────────────────

/// Adaptive strategy that queries [`Tracker::recommended_concurrency()`] to
/// decide whether to run sequentially or in parallel.
pub struct AdaptiveStrategy {
    tracker: Arc<dyn Tracker>,
}

impl AdaptiveStrategy {
    /// Create an adaptive strategy that uses the given tracker.
    #[must_use]
    pub fn new(tracker: Arc<dyn Tracker>) -> Self {
        Self { tracker }
    }
}

#[async_trait]
impl ExecutionStrategy for AdaptiveStrategy {
    async fn execute_batch(
        &self,
        calls: Vec<PendingToolCall>,
        tools: &[Arc<dyn ErasedTool>],
        guards: &[Arc<dyn Guard>],
        state: &AgentState,
    ) -> Vec<ToolResult> {
        let concurrency = self.tracker.recommended_concurrency(state);
        if concurrency <= 1 {
            SequentialStrategy
                .execute_batch(calls, tools, guards, state)
                .await
        } else {
            ParallelStrategy::new(concurrency)
                .execute_batch(calls, tools, guards, state)
                .await
        }
    }
}

// ───────────────────────────── Helpers ─────────────────────────────

/// Execute a single tool call with guard checks.
async fn execute_single(
    call: &PendingToolCall,
    tools: &[Arc<dyn ErasedTool>],
    guards: &[Arc<dyn Guard>],
) -> String {
    let action = Action::ToolCall {
        name: call.name.clone(),
        arguments: call.arguments.clone(),
    };

    // Guard checks — catch_unwind for external guard safety (Story 7.4)
    for guard in guards {
        let guard_name = guard.name().to_string();
        let action_ref = &action;

        let guard_span = tracing::info_span!(
            target: "traitclaw::guard",
            "guard.check",
            guard.name = guard_name.as_str(),
            guard.result = tracing::field::Empty,
        );
        let _g = guard_span.enter();

        let result =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| guard.check(action_ref)));

        match result {
            Ok(GuardResult::Allow) => {
                guard_span.record("guard.result", "allow");
            }
            Ok(GuardResult::Deny { reason, .. }) => {
                guard_span.record("guard.result", "deny");
                return format!("Error: Action blocked by guard: {reason}");
            }
            Ok(GuardResult::Sanitize { warning, .. }) => {
                guard_span.record("guard.result", "sanitize");
                tracing::info!(
                    target: "traitclaw::guard",
                    guard = guard_name.as_str(),
                    "Guard sanitized: {warning}"
                );
            }
            Err(_) => {
                guard_span.record("guard.result", "panic");
                // Guard panicked — default to Deny for safety (P3 code review)
                tracing::warn!(
                    target: "traitclaw::guard",
                    guard = guard_name.as_str(),
                    "Guard panicked — denying action for safety"
                );
                return format!("Error: Action blocked — guard '{guard_name}' panicked");
            }
        }
    }

    // Find and execute tool
    let tool_span = tracing::info_span!(
        target: "traitclaw::tool",
        "tool.call",
        tool.name = call.name.as_str(),
        tool.success = tracing::field::Empty,
    );
    let _t = tool_span.enter();

    if let Some(tool) = tools.iter().find(|t| t.name() == call.name) {
        match tool.execute_json(call.arguments.clone()).await {
            Ok(output) => {
                tool_span.record("tool.success", true);
                serde_json::to_string(&output)
                    .unwrap_or_else(|e| format!("Error serializing output: {e}"))
            }
            Err(e) => {
                tool_span.record("tool.success", false);
                format!("Error executing tool: {e}")
            }
        }
    } else {
        tool_span.record("tool.success", false);
        let available: Vec<_> = tools.iter().map(|t| t.name().to_string()).collect();
        format!(
            "Error: Tool '{}' not found. Available: {}",
            call.name,
            available.join(", ")
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::guard::NoopGuard;

    struct AddTool;

    #[async_trait]
    impl ErasedTool for AddTool {
        fn name(&self) -> &'static str {
            "add"
        }
        fn description(&self) -> &'static str {
            "Adds two numbers"
        }
        fn schema(&self) -> crate::traits::tool::ToolSchema {
            crate::traits::tool::ToolSchema {
                name: "add".into(),
                description: "add".into(),
                parameters: serde_json::json!({}),
            }
        }
        async fn execute_json(
            &self,
            _args: serde_json::Value,
        ) -> std::result::Result<serde_json::Value, crate::Error> {
            Ok(serde_json::json!("result"))
        }
    }

    fn make_calls(n: usize) -> Vec<PendingToolCall> {
        (0..n)
            .map(|i| PendingToolCall {
                id: format!("call-{i}"),
                name: "add".into(),
                arguments: serde_json::json!({}),
            })
            .collect()
    }

    #[tokio::test]
    async fn test_sequential_executes_in_order() {
        let strategy = SequentialStrategy;
        let tools: Vec<Arc<dyn ErasedTool>> = vec![Arc::new(AddTool)];
        let guards: Vec<Arc<dyn Guard>> = vec![Arc::new(NoopGuard)];

        let state = AgentState::new(crate::types::model_info::ModelTier::Small, 4096);

        let results = strategy
            .execute_batch(make_calls(3), &tools, &guards, &state)
            .await;

        assert_eq!(results.len(), 3);
        assert_eq!(results[0].id, "call-0");
        assert_eq!(results[1].id, "call-1");
        assert_eq!(results[2].id, "call-2");
        // All should succeed
        for r in &results {
            assert!(!r.output.starts_with("Error"), "unexpected: {}", r.output);
        }
    }

    #[tokio::test]
    async fn test_parallel_executes_concurrently() {
        let strategy = ParallelStrategy::new(4);
        let tools: Vec<Arc<dyn ErasedTool>> = vec![Arc::new(AddTool)];
        let guards: Vec<Arc<dyn Guard>> = vec![Arc::new(NoopGuard)];

        let state = AgentState::new(crate::types::model_info::ModelTier::Small, 4096);

        let results = strategy
            .execute_batch(make_calls(5), &tools, &guards, &state)
            .await;

        assert_eq!(results.len(), 5);
        for r in &results {
            assert!(!r.output.starts_with("Error"), "unexpected: {}", r.output);
        }
    }

    #[tokio::test]
    async fn test_guard_blocks_propagate() {
        use crate::traits::guard::{Guard, GuardResult};

        struct DenyGuard;
        impl Guard for DenyGuard {
            fn name(&self) -> &'static str {
                "deny"
            }
            fn check(&self, _action: &Action) -> GuardResult {
                GuardResult::Deny {
                    reason: "blocked".into(),
                    severity: crate::traits::guard::GuardSeverity::High,
                }
            }
        }

        let strategy = SequentialStrategy;
        let tools: Vec<Arc<dyn ErasedTool>> = vec![Arc::new(AddTool)];
        let guards: Vec<Arc<dyn Guard>> = vec![Arc::new(DenyGuard)];

        let state = AgentState::new(crate::types::model_info::ModelTier::Small, 4096);

        let results = strategy
            .execute_batch(make_calls(1), &tools, &guards, &state)
            .await;

        assert_eq!(results.len(), 1);
        assert!(results[0].output.contains("blocked"));
    }

    #[tokio::test]
    async fn test_guard_panic_defaults_to_deny() {
        use crate::traits::guard::{Guard, GuardResult};

        struct PanicGuard;
        impl Guard for PanicGuard {
            fn name(&self) -> &'static str {
                "panic_guard"
            }
            fn check(&self, _action: &Action) -> GuardResult {
                panic!("intentional panic in guard");
            }
        }

        let strategy = SequentialStrategy;
        let tools: Vec<Arc<dyn ErasedTool>> = vec![Arc::new(AddTool)];
        let guards: Vec<Arc<dyn Guard>> = vec![Arc::new(PanicGuard)];

        let state = AgentState::new(crate::types::model_info::ModelTier::Small, 4096);

        let results = strategy
            .execute_batch(make_calls(1), &tools, &guards, &state)
            .await;

        assert_eq!(results.len(), 1);
        // P3: panicking guard should deny, not allow
        assert!(
            results[0].output.contains("panicked"),
            "Expected deny on panic, got: {}",
            results[0].output
        );
    }

    #[tokio::test]
    async fn test_tool_not_found_returns_error() {
        let strategy = SequentialStrategy;
        let tools: Vec<Arc<dyn ErasedTool>> = vec![]; // no tools registered
        let guards: Vec<Arc<dyn Guard>> = vec![Arc::new(NoopGuard)];

        let state = AgentState::new(crate::types::model_info::ModelTier::Small, 4096);

        let calls = vec![PendingToolCall {
            id: "c1".into(),
            name: "nonexistent".into(),
            arguments: serde_json::json!({}),
        }];

        let results = strategy.execute_batch(calls, &tools, &guards, &state).await;

        assert_eq!(results.len(), 1);
        assert!(
            results[0].output.contains("not found"),
            "Expected 'not found', got: {}",
            results[0].output
        );
    }
}