radkit 0.0.5

Rust AI Agent Development Kit
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
//! Integration tests for RequestExecutor orchestration.

#[cfg(all(
    feature = "runtime",
    feature = "test-support",
    not(all(target_os = "wasi", target_env = "p1"))
))]
mod tests {
    use a2a_types::{self as v1, part, Role, TaskState};
    use radkit::agent::{
        Agent, OnInputResult, OnRequestResult, RegisteredSkill, SkillHandler, SkillMetadata,
        SkillSlot,
    };
    use radkit::errors::AgentError;
    use radkit::models::{Content, LlmResponse, TokenUsage};
    use radkit::runtime::context::{ProgressSender, State};
    use radkit::runtime::core::executor::{ExecutorRuntime, RequestExecutor};
    use radkit::runtime::{AgentRuntime, Runtime};
    use radkit::test_support::FakeLlm;
    use serde::{Deserialize, Serialize};
    use std::sync::Arc;
    use uuid::Uuid;

    fn negotiation_response(skill_id: &str) -> radkit::errors::AgentResult<LlmResponse> {
        let decision = serde_json::json!({
            "type": "start_task",
            "skill_id": skill_id,
            "reasoning": "Test selected this skill"
        });
        Ok(LlmResponse::new(
            Content::from_text(serde_json::to_string(&decision).expect("valid JSON")),
            TokenUsage::empty(),
        ))
    }

    fn create_send_request(
        text: &str,
        context_id: Option<String>,
        task_id: Option<String>,
    ) -> v1::SendMessageRequest {
        v1::SendMessageRequest {
            message: Some(v1::Message {
                message_id: Uuid::new_v4().to_string(),
                role: Role::User as i32,
                parts: vec![v1::Part {
                    content: Some(part::Content::Text(text.to_string())),
                    metadata: None,
                    filename: String::new(),
                    media_type: "text/plain".to_string(),
                }],
                context_id: context_id.unwrap_or_default(),
                task_id: task_id.unwrap_or_default(),
                reference_task_ids: vec![],
                extensions: vec![],
                metadata: None,
            }),
            configuration: None,
            metadata: None,
            tenant: String::new(),
        }
    }

    // ============================================================================
    // Test 1: New task creation and immediate completion
    // ============================================================================

    struct ImmediateSkill;

    #[cfg_attr(
        all(target_os = "wasi", target_env = "p1"),
        async_trait::async_trait(?Send)
    )]
    #[cfg_attr(
        not(all(target_os = "wasi", target_env = "p1")),
        async_trait::async_trait
    )]
    impl SkillHandler for ImmediateSkill {
        async fn on_request(
            &self,
            _state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            _content: Content,
        ) -> Result<OnRequestResult, AgentError> {
            Ok(OnRequestResult::Completed {
                message: Some(Content::from_text("Task completed immediately!")),
                artifacts: vec![],
            })
        }

        async fn on_input_received(
            &self,
            _state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            _input: Content,
        ) -> Result<OnInputResult, AgentError> {
            unreachable!("immediate skill should not receive input")
        }
    }

    impl RegisteredSkill for ImmediateSkill {
        fn metadata() -> std::sync::Arc<SkillMetadata> {
            std::sync::Arc::new(SkillMetadata::new(
                "immediate",
                "Immediate Skill",
                "Completes immediately",
                &[],
                &[],
                &[],
                &[],
            ))
        }
    }

    #[tokio::test]
    async fn test_new_task_immediate_completion() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("immediate")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(ImmediateSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let result = executor
            .handle_send_message(create_send_request("Hello", None, None))
            .await;
        assert!(result.is_ok(), "send_message should succeed");

        match result.unwrap().payload {
            Some(v1::send_message_response::Payload::Task(task)) => {
                assert_eq!(
                    task.status.as_ref().unwrap().state,
                    TaskState::Completed as i32
                );
                assert!(!task.history.is_empty(), "should have messages in history");
            }
            _ => panic!("expected Task result"),
        }
    }

    // ============================================================================
    // Test 2: Task requires input and continuation
    // ============================================================================

    #[derive(Serialize, Deserialize, Clone, Debug)]
    enum GreetingSlot {
        AwaitingName,
    }

    struct GreetingSkill;

    #[cfg_attr(
        all(target_os = "wasi", target_env = "p1"),
        async_trait::async_trait(?Send)
    )]
    #[cfg_attr(
        not(all(target_os = "wasi", target_env = "p1")),
        async_trait::async_trait
    )]
    impl SkillHandler for GreetingSkill {
        async fn on_request(
            &self,
            _state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            _content: Content,
        ) -> Result<OnRequestResult, AgentError> {
            Ok(OnRequestResult::InputRequired {
                message: Content::from_text("What is your name?"),
                slot: SkillSlot::new(GreetingSlot::AwaitingName),
            })
        }

        async fn on_input_received(
            &self,
            state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            input: Content,
        ) -> Result<OnInputResult, AgentError> {
            let slot: GreetingSlot = state.slot()?.expect("slot should be available");
            match slot {
                GreetingSlot::AwaitingName => {
                    let name = input.first_text().unwrap_or("Friend");
                    Ok(OnInputResult::Completed {
                        message: Some(Content::from_text(format!("Hello, {}!", name))),
                        artifacts: vec![],
                    })
                }
            }
        }
    }

    impl RegisteredSkill for GreetingSkill {
        fn metadata() -> std::sync::Arc<SkillMetadata> {
            std::sync::Arc::new(SkillMetadata::new(
                "greeting",
                "Greeting Skill",
                "Greets user by name",
                &[],
                &[],
                &[],
                &[],
            ))
        }
    }

    #[tokio::test]
    async fn test_task_continuation_with_input() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("greeting")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(GreetingSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let result1 = executor
            .handle_send_message(create_send_request("Greet me", None, None))
            .await
            .unwrap();
        let (context_id, task_id) = match result1.payload {
            Some(v1::send_message_response::Payload::Task(task)) => {
                assert_eq!(
                    task.status.as_ref().unwrap().state,
                    TaskState::InputRequired as i32
                );
                (task.context_id, task.id)
            }
            _ => panic!("expected Task result"),
        };

        let result2 = executor
            .handle_send_message(create_send_request(
                "Alice",
                Some(context_id),
                Some(task_id),
            ))
            .await
            .unwrap();
        match result2.payload {
            Some(v1::send_message_response::Payload::Task(task)) => {
                assert_eq!(
                    task.status.as_ref().unwrap().state,
                    TaskState::Completed as i32
                );
                let final_msg = task
                    .history
                    .iter()
                    .rfind(|msg| msg.role == Role::Agent as i32)
                    .expect("should have agent message");
                let text = match &final_msg.parts[0].content {
                    Some(part::Content::Text(t)) => t,
                    _ => panic!("expected text content"),
                };
                assert!(text.contains("Hello, Alice!"), "should greet by name");
            }
            _ => panic!("expected Task result"),
        }
    }

    // ============================================================================
    // Test 3: Task failure
    // ============================================================================

    struct FailingSkill;

    #[cfg_attr(
        all(target_os = "wasi", target_env = "p1"),
        async_trait::async_trait(?Send)
    )]
    #[cfg_attr(
        not(all(target_os = "wasi", target_env = "p1")),
        async_trait::async_trait
    )]
    impl SkillHandler for FailingSkill {
        async fn on_request(
            &self,
            _state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            _content: Content,
        ) -> Result<OnRequestResult, AgentError> {
            Err(AgentError::Internal {
                component: "FailingSkill".to_string(),
                reason: "Intentional failure for testing".to_string(),
            })
        }

        async fn on_input_received(
            &self,
            _state: &mut State,
            _progress: &ProgressSender,
            _runtime: &dyn AgentRuntime,
            _input: Content,
        ) -> Result<OnInputResult, AgentError> {
            unreachable!()
        }
    }

    impl RegisteredSkill for FailingSkill {
        fn metadata() -> std::sync::Arc<SkillMetadata> {
            std::sync::Arc::new(SkillMetadata::new(
                "failing",
                "Failing Skill",
                "Always fails",
                &[],
                &[],
                &[],
                &[],
            ))
        }
    }

    #[tokio::test]
    async fn test_task_failure() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("failing")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(FailingSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let result = executor
            .handle_send_message(create_send_request("Do something", None, None))
            .await;

        assert!(result.is_err(), "Should fail when skill throws error");
        match result.unwrap_err() {
            AgentError::Internal { component, reason } => {
                assert_eq!(component, "FailingSkill");
                assert!(reason.contains("Intentional failure"));
            }
            other => panic!("Expected Internal error, got {:?}", other),
        }
    }

    // ============================================================================
    // Test 4: Task retrieval
    // ============================================================================

    #[tokio::test]
    async fn test_get_task() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("immediate")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(ImmediateSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let send_result = executor
            .handle_send_message(create_send_request("test", None, None))
            .await
            .unwrap();
        let task_id = match send_result.payload {
            Some(v1::send_message_response::Payload::Task(task)) => task.id,
            _ => panic!("expected Task"),
        };

        let get_result = executor
            .handle_get_task(v1::GetTaskRequest {
                id: task_id.clone(),
                history_length: None,
                tenant: String::new(),
            })
            .await;

        assert!(get_result.is_ok(), "should retrieve task");
        let retrieved_task = get_result.unwrap();
        assert_eq!(retrieved_task.id, task_id);
        assert_eq!(
            retrieved_task.status.as_ref().unwrap().state,
            TaskState::Completed as i32
        );
    }

    // ============================================================================
    // Test 5: Invalid task ID
    // ============================================================================

    #[tokio::test]
    async fn test_get_nonexistent_task() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("immediate")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(ImmediateSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let result = executor
            .handle_get_task(v1::GetTaskRequest {
                id: "nonexistent-task-id".to_string(),
                history_length: None,
                tenant: String::new(),
            })
            .await;

        assert!(result.is_err(), "should fail for nonexistent task");
        match result.unwrap_err() {
            AgentError::TaskNotFound { task_id } => {
                assert_eq!(task_id, "nonexistent-task-id");
            }
            _ => panic!("expected TaskNotFound error"),
        }
    }

    // ============================================================================
    // Test 6: Continue with wrong context_id/task_id combination
    // ============================================================================

    #[tokio::test]
    async fn test_invalid_context_task_combination() {
        let llm = FakeLlm::with_responses("fake-llm", [negotiation_response("greeting")]);
        let runtime = Runtime::builder(Agent::builder().with_skill(GreetingSkill).build(), llm)
            .build()
            .into_shared();
        let executor_runtime: Arc<dyn ExecutorRuntime> = runtime.clone();
        let executor = RequestExecutor::new(executor_runtime);

        let result1 = executor
            .handle_send_message(create_send_request("Hello", None, None))
            .await
            .unwrap();
        let task1_id = match result1.payload {
            Some(v1::send_message_response::Payload::Task(task)) => task.id,
            _ => panic!("expected Task"),
        };

        let result2 = executor
            .handle_send_message(create_send_request(
                "Continue",
                Some("wrong-context-id".to_string()),
                Some(task1_id),
            ))
            .await;
        assert!(result2.is_err(), "should fail with mismatched context/task");
    }
}