rskit-agent 0.2.0-alpha.1

Agentic loop — Provider + Tools + Hooks in a turn-based execution engine
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
//! Agent — the multi-turn agentic execution loop.

use std::sync::Arc;

use rskit_llm::provider::Provider;

use crate::config::AgentConfig;

mod component;
mod run;
mod stream;

/// A multi-turn agentic loop that drives an LLM provider, executes tool calls,
/// and emits hook events at each lifecycle point.
pub struct Agent {
    provider: Arc<dyn Provider>,
    config: AgentConfig,
}

impl Agent {
    /// Create a new agent with the given provider and configuration.
    pub fn new(provider: Arc<dyn Provider>, config: AgentConfig) -> Self {
        Self { provider, config }
    }

    /// Create a new agent with the locked default configuration.
    pub fn with_defaults(provider: Arc<dyn Provider>) -> Self {
        Self::new(provider, AgentConfig::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::pin::Pin;

    use futures::{Stream, StreamExt};
    use rskit_ai::Capabilities;
    use rskit_ai::StreamEventRef;
    use rskit_ai::chat::count_tokens_approx;
    use rskit_errors::AppError;
    use rskit_hook::{HookError, HookRegistry};
    use rskit_llm::types::{
        self, AssistantMessage, CompletionRequest, CompletionResponse, Message, Usage,
    };
    use rskit_resilience::{ConstantBackoff, Policy, RetryPolicy};
    use rskit_tool::{Context, Registry};
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::time::Duration;

    use crate::types::{AgentEvent, StopReason};

    // ── Mock provider ───────────────────────────────────────────────────

    struct MockProvider {
        responses: Vec<CompletionResponse>,
        call_count: AtomicU32,
    }

    impl MockProvider {
        fn new(responses: Vec<CompletionResponse>) -> Self {
            Self {
                responses,
                call_count: AtomicU32::new(0),
            }
        }

        fn single_text(text: &str) -> Self {
            Self::new(vec![CompletionResponse {
                message: AssistantMessage {
                    content: types::text_content(text),
                    tool_calls: vec![],
                    usage: None,
                },
                model: "mock".to_string(),
                usage: Usage {
                    input_tokens: 10,
                    output_tokens: 5,
                    cached_tokens: 0,
                    reasoning_tokens: 0,
                },
                stop_reason: Some(rskit_llm::FinishReason::Stop),
            }])
        }
    }

    #[async_trait]
    impl rskit_provider::Provider for MockProvider {
        fn name(&self) -> &'static str {
            "mock"
        }
    }

    #[async_trait]
    impl rskit_provider::RequestResponse<CompletionRequest, CompletionResponse> for MockProvider {
        async fn execute(&self, input: CompletionRequest) -> Result<CompletionResponse, AppError> {
            self.complete(input).await
        }
    }

    #[async_trait]
    impl Provider for MockProvider {
        async fn complete(
            &self,
            _request: CompletionRequest,
        ) -> Result<CompletionResponse, AppError> {
            let idx = self.call_count.fetch_add(1, Ordering::SeqCst) as usize;
            if idx < self.responses.len() {
                Ok(self.responses[idx].clone())
            } else {
                // Return last response for any additional calls
                Ok(self.responses.last().unwrap().clone())
            }
        }

        async fn stream(
            &self,
            _request: CompletionRequest,
        ) -> Result<Pin<Box<dyn Stream<Item = StreamEventRef> + Send>>, AppError> {
            Ok(Box::pin(futures::stream::empty()))
        }

        fn capabilities(&self) -> Capabilities {
            Capabilities {
                tool_use: true,
                streaming: false,
                max_input_tokens: Some(128_000),
                max_output_tokens: Some(4_096),
                ..Default::default()
            }
        }

        fn count_tokens(&self, messages: &[Message]) -> usize {
            count_tokens_approx(messages)
        }
    }

    // ── Tests ───────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_agent_simple_completion() {
        let provider = Arc::new(MockProvider::single_text("Hello!"));
        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: None,
                system_prompt: "You are helpful.".to_string(),
                max_turns: 5,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("Hi")]).await.unwrap();
        assert_eq!(result.turn_count, 1);
        assert!(matches!(result.stop_reason, StopReason::EndTurn));
        assert_eq!(result.total_usage.input_tokens, 10);
        assert_eq!(result.total_usage.output_tokens, 5);
    }

    #[tokio::test]
    async fn test_agent_max_turns() {
        // Provider always returns tool calls → agent loops until max_turns
        let tool_call_response = CompletionResponse {
            message: AssistantMessage {
                content: vec![],
                tool_calls: vec![rskit_llm::ToolUseBlock {
                    id: "tc_1".to_string(),
                    name: "test_tool".to_string(),
                    input: serde_json::json!({"x": 1}).as_object().cloned().unwrap(),
                }],
                usage: None,
            },
            model: "mock".to_string(),
            usage: Usage {
                input_tokens: 5,
                output_tokens: 5,
                cached_tokens: 0,
                reasoning_tokens: 0,
            },
            stop_reason: Some(rskit_llm::FinishReason::ToolUse),
        };

        let provider = Arc::new(MockProvider::new(vec![tool_call_response]));

        // No tools registered → tool calls will fail, but loop continues
        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: None,
                system_prompt: "sys".to_string(),
                max_turns: 3,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("go")]).await.unwrap();
        assert_eq!(result.turn_count, 3);
        assert!(matches!(result.stop_reason, StopReason::MaxTurns));
    }

    #[tokio::test]
    async fn test_agent_with_tool() {
        use rskit_tool::{from_fn, text_result};
        use schemars::JsonSchema;
        use serde::Deserialize;

        #[derive(Deserialize, JsonSchema)]
        struct AddInput {
            a: i32,
            b: i32,
        }

        let registry = Arc::new(Registry::new());
        let attempts = Arc::new(AtomicU32::new(0));
        let attempts_for_tool = Arc::clone(&attempts);
        registry
            .register(
                from_fn(
                    "add",
                    "Add two numbers",
                    move |_ctx: Context, input: AddInput| {
                        let attempts = Arc::clone(&attempts_for_tool);
                        async move {
                            let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                            if attempt == 0 {
                                Err(AppError::connection_failed("add"))
                            } else {
                                Ok(text_result(&format!("{}", input.a + input.b)))
                            }
                        }
                    },
                )
                .unwrap(),
            )
            .unwrap();

        // First call: model requests tool
        let tool_call_resp = CompletionResponse {
            message: AssistantMessage {
                content: vec![],
                tool_calls: vec![rskit_llm::ToolUseBlock {
                    id: "tc_1".to_string(),
                    name: "add".to_string(),
                    input: serde_json::json!({"a": 2, "b": 3})
                        .as_object()
                        .cloned()
                        .unwrap(),
                }],
                usage: None,
            },
            model: "mock".to_string(),
            usage: Usage {
                input_tokens: 10,
                output_tokens: 5,
                cached_tokens: 0,
                reasoning_tokens: 0,
            },
            stop_reason: Some(rskit_llm::FinishReason::ToolUse),
        };

        // Second call: model returns final text
        let final_resp = CompletionResponse {
            message: AssistantMessage {
                content: types::text_content("The answer is 5"),
                tool_calls: vec![],
                usage: None,
            },
            model: "mock".to_string(),
            usage: Usage {
                input_tokens: 15,
                output_tokens: 8,
                cached_tokens: 0,
                reasoning_tokens: 0,
            },
            stop_reason: Some(rskit_llm::FinishReason::Stop),
        };

        let provider = Arc::new(MockProvider::new(vec![tool_call_resp, final_resp]));

        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: Some(registry),
                hooks: None,
                system_prompt: "You are a calculator.".to_string(),
                max_turns: 5,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: Some(
                    Policy::new().with_retry(
                        RetryPolicy::new()
                            .with_max_attempts(2)
                            .with_constant_backoff(ConstantBackoff::new(Duration::from_millis(1)))
                            .with_jitter(false),
                    ),
                ),
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("What is 2+3?")]).await.unwrap();
        assert_eq!(attempts.load(Ordering::SeqCst), 2);
        assert_eq!(result.turn_count, 2);
        assert!(matches!(result.stop_reason, StopReason::EndTurn));
        // Usage should be summed
        assert_eq!(result.total_usage.input_tokens, 25);
        assert_eq!(result.total_usage.output_tokens, 13);
    }

    #[tokio::test]
    async fn test_agent_max_budget() {
        let tool_call_response = CompletionResponse {
            message: AssistantMessage {
                content: vec![],
                tool_calls: vec![rskit_llm::ToolUseBlock {
                    id: "tc_1".to_string(),
                    name: "noop".to_string(),
                    input: serde_json::Map::new(),
                }],
                usage: None,
            },
            model: "mock".to_string(),
            usage: Usage {
                input_tokens: 50,
                output_tokens: 50,
                cached_tokens: 0,
                reasoning_tokens: 0,
            },
            stop_reason: Some(rskit_llm::FinishReason::ToolUse),
        };

        let provider = Arc::new(MockProvider::new(vec![tool_call_response]));

        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: None,
                system_prompt: "sys".to_string(),
                max_turns: 100,
                max_tokens: 80, // Budget of 80 tokens total
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("go")]).await.unwrap();
        assert!(matches!(result.stop_reason, StopReason::MaxTokens));
    }

    #[tokio::test]
    async fn max_budget_stops_after_final_response_without_tool_calls() {
        let provider = Arc::new(MockProvider::new(vec![CompletionResponse {
            message: AssistantMessage {
                content: types::text_content("large final response"),
                tool_calls: vec![],
                usage: None,
            },
            model: "mock".to_string(),
            usage: Usage {
                input_tokens: 50,
                output_tokens: 50,
                cached_tokens: 0,
                reasoning_tokens: 0,
            },
            stop_reason: Some(rskit_llm::FinishReason::Stop),
        }]));

        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: None,
                system_prompt: "sys".to_string(),
                max_turns: 5,
                max_tokens: 80,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("go")]).await.unwrap();
        assert!(matches!(result.stop_reason, StopReason::MaxTokens));
        assert_eq!(result.turn_count, 1);
    }

    #[tokio::test]
    async fn test_agent_hook_fatal_error_stops() {
        let provider = Arc::new(MockProvider::single_text("Hello"));
        let hooks = Arc::new(HookRegistry::new());

        let _unsub = hooks.on::<crate::hooks::TurnStart>(crate::turn_start_type(), |_, _| {
            Err(HookError::fatal("blocked by policy"))
        });

        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: Some(hooks),
                system_prompt: "sys".to_string(),
                max_turns: 5,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let result = agent.run(vec![types::user("hi")]).await.unwrap();
        assert!(matches!(result.stop_reason, StopReason::Aborted));
        assert_eq!(result.turn_count, 0);
    }

    #[tokio::test]
    async fn hook_observes_request_without_mutation_surface() {
        let provider = Arc::new(MockProvider::single_text("done"));
        let hooks = Arc::new(HookRegistry::new());
        let observed = Arc::new(AtomicU32::new(0));
        let observed_clone = Arc::clone(&observed);

        let _unsub =
            hooks.on::<crate::hooks::PreLLMCall>(crate::pre_llm_call_type(), move |_, event| {
                assert_eq!(event.request.model, "test-model");
                observed_clone.fetch_add(1, Ordering::SeqCst);
                Ok(())
            });

        let agent = Agent::new(
            provider,
            AgentConfig {
                hooks: Some(hooks),
                system_prompt: "sys".to_string(),
                model: "test-model".to_string(),
                ..AgentConfig::default()
            },
        );

        let result = agent.run(vec![types::user("hi")]).await.unwrap();
        assert!(matches!(result.stop_reason, StopReason::EndTurn));
        assert_eq!(observed.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_agent_hook_counts() {
        let provider = Arc::new(MockProvider::single_text("done"));
        let hooks = Arc::new(HookRegistry::new());

        let pre_count = Arc::new(AtomicU32::new(0));
        let post_count = Arc::new(AtomicU32::new(0));

        let pc = pre_count.clone();
        let _unsub1 =
            hooks.on::<crate::hooks::PreLLMCall>(crate::pre_llm_call_type(), move |_, _| {
                pc.fetch_add(1, Ordering::SeqCst);
                Ok(())
            });

        let poc = post_count.clone();
        let _unsub2 =
            hooks.on::<crate::hooks::PostLLMCall>(crate::post_llm_call_type(), move |_, _| {
                poc.fetch_add(1, Ordering::SeqCst);
                Ok(())
            });

        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: Some(hooks),
                system_prompt: "sys".to_string(),
                max_turns: 5,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        agent.run(vec![types::user("hi")]).await.unwrap();
        assert_eq!(pre_count.load(Ordering::SeqCst), 1);
        assert_eq!(post_count.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_agent_stream() {
        let provider = Arc::new(MockProvider::single_text("streamed"));
        let agent = Agent::new(
            provider,
            AgentConfig {
                tools: None,
                hooks: None,
                system_prompt: "sys".to_string(),
                max_turns: 5,
                max_tokens: 100_000,
                wall_clock: Duration::from_mins(1),
                max_tool_calls: 50,
                tool_concurrency: 4,
                tool_timeout: Duration::from_secs(30),
                policy: None,
                context_strategy: None,
                model: String::new(),
            },
        );

        let stream = agent.stream(vec![types::user("hi")]);
        let events: Vec<AgentEvent> = stream.collect().await;
        assert_eq!(events.len(), 3);
        assert!(matches!(
            events.first(),
            Some(AgentEvent::TurnStart { turn: 0 })
        ));
        assert!(matches!(
            events.get(1),
            Some(AgentEvent::TurnComplete {
                turn: 0,
                usage: Usage {
                    input_tokens: 10,
                    output_tokens: 5,
                    cached_tokens: 0,
                    reasoning_tokens: 0,
                },
                ..
            })
        ));
        assert!(matches!(events.last(), Some(AgentEvent::Complete { .. })));
    }

    #[tokio::test]
    async fn agent_component_lifecycle_is_named_and_healthy() {
        use rskit_component::Component;

        let agent = Agent::with_defaults(Arc::new(MockProvider::single_text("ok")));

        assert_eq!(Component::name(&agent), "rskit-agent");
        agent.start().await.expect("start is a no-op success");
        agent.stop().await.expect("stop is a no-op success");

        let health = agent.health();
        assert!(health.is_healthy());
    }
}