ailoy 0.3.0

Agents that drive a language model through tool-augmented turns, in a virtx console.
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
use serde::{Deserialize, Serialize};
use url::Url;

use crate::{
    message::{Message, Part, Role},
    tool::{ToolDesc, ToolDescBuilder, ToolFunc, sanitize_tool_name, warn_if_tool_name_too_long},
    tool_func,
};

// ── Tool constructor ──────────────────────────────────────────────────────────

/// Fetch the agent card at `url` and build the A2A agent's [`ToolDesc`] under `name`;
/// the network fetch is why the agent is contacted at registration, not at resolution.
///
/// `name` is the caller's registration key, not the card's name, which may not be
/// a valid function name.
pub(crate) async fn get_a2a_tool_desc(name: &str, url: &Url) -> anyhow::Result<ToolDesc> {
    let base_url = url.to_string();
    let card = discover(&base_url).await?;

    // Description plus a skills list, so the model knows what the remote agent does.
    let description = if card.skills.is_empty() {
        card.description.clone()
    } else {
        let skills = card
            .skills
            .iter()
            .map(|s| format!("* {}: {}", s.name, s.description))
            .collect::<Vec<_>>()
            .join("\n");
        format!("{}\n\n# Skills\n\n{}", card.description, skills)
    };

    let name = sanitize_tool_name(name);
    warn_if_tool_name_too_long(&name);

    Ok(ToolDescBuilder::new(name)
        .description(description)
        // An object with a single `task` string: the model APIs reject a
        // `parameters` schema that is not an object.
        .parameters(crate::to_value!({
            "type": "object",
            "properties": {
                "task": {
                    "type": "string",
                    "description": "The task description to send to the remote agent"
                }
            },
            "required": ["task"]
        }))
        .build())
}

/// Build a [`ToolFunc`] that forwards a task to the A2A agent at `url`.
///
/// Needs no agent card, and so no `await`: everything it sends is in the call
/// arguments, which is what lets `provide` stay synchronous.
pub(crate) fn get_a2a_tool_func(url: &Url) -> ToolFunc {
    let base_url = url.to_string();
    tool_func!(async |args: Value, id: String| -> Message
        with [url = base_url.clone()]
        {
        let task = match args.pointer("/task").and_then(|v| v.as_str()) {
            Some(v) => v.to_string(),
            None => {
                return Message::new(Role::Tool)
                    .with_contents([Part::text(
                        "Error: expected an object with a string 'task' field",
                    )])
                    .with_id(id);
            }
        };
        match message_send(&url, &task).await {
            Ok(text) => Message::new(Role::Tool)
                .with_contents([Part::text(text)])
                .with_id(id),
            Err(e) => Message::new(Role::Tool)
                .with_contents([Part::text(format!("Error: {e}"))])
                .with_id(id),
        }
    })
}

// ── Agent Discovery ──────────────────────────────────────────────────────────

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AgentCard {
    pub(crate) name: String,
    pub(crate) description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) version: Option<String>,
    #[serde(default)]
    pub(crate) skills: Vec<AgentSkill>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) capabilities: Option<AgentCapabilities>,
    #[serde(default = "default_input_modes")]
    pub(crate) default_input_modes: Vec<String>,
    #[serde(default = "default_output_modes")]
    pub(crate) default_output_modes: Vec<String>,
}

fn default_input_modes() -> Vec<String> {
    vec!["text/plain".into()]
}

fn default_output_modes() -> Vec<String> {
    vec!["text/plain".into()]
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AgentSkill {
    pub(crate) id: String,
    pub(crate) name: String,
    pub(crate) description: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) examples: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AgentCapabilities {
    pub(crate) streaming: bool,
}

// ── JSON-RPC 2.0 ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct JsonRpcRequest {
    pub(crate) jsonrpc: String,
    pub(crate) id: serde_json::Value,
    pub(crate) method: String,
    pub(crate) params: MessageSendParams,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct MessageSendParams {
    pub(crate) message: A2AMessage,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct A2AMessage {
    #[serde(default = "message_kind")]
    pub(crate) kind: String,
    pub(crate) role: A2ARole,
    pub(crate) parts: Vec<A2APart>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) message_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) task_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) context_id: Option<String>,
}

fn message_kind() -> String {
    "message".into()
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum A2ARole {
    User,
    Agent,
}

#[derive(Clone, Debug)]
pub(crate) enum A2APart {
    Text { text: String },
}

#[derive(Serialize)]
struct TextPartSer<'a> {
    kind: &'static str,
    text: &'a str,
}

impl Serialize for A2APart {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            A2APart::Text { text } => TextPartSer { kind: "text", text }.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for A2APart {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let map: serde_json::Map<String, serde_json::Value> =
            serde_json::Map::deserialize(deserializer)?;
        if let Some(text) = map.get("text").and_then(|v| v.as_str()) {
            Ok(A2APart::Text {
                text: text.to_owned(),
            })
        } else {
            Err(serde::de::Error::missing_field("text"))
        }
    }
}

// ── Task ─────────────────────────────────────────────────────────────────────

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Task {
    #[serde(default = "task_kind")]
    pub(crate) kind: String,
    pub(crate) id: String,
    pub(crate) context_id: String,
    pub(crate) status: TaskStatus,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) history: Vec<A2AMessage>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) artifacts: Vec<serde_json::Value>,
}

fn task_kind() -> String {
    "task".into()
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct TaskStatus {
    pub(crate) state: TaskState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) timestamp: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum TaskState {
    Submitted,
    Working,
    Completed,
    Failed,
}

// ── JSON-RPC Response ─────────────────────────────────────────────────────────

#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct JsonRpcResponse {
    pub(crate) jsonrpc: String,
    pub(crate) id: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) result: Option<Task>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) error: Option<JsonRpcError>,
}

impl JsonRpcResponse {
    #[cfg(test)]
    pub(crate) fn success(id: serde_json::Value, task: Task) -> Self {
        Self {
            jsonrpc: "2.0".into(),
            id,
            result: Some(task),
            error: None,
        }
    }

    #[cfg(test)]
    pub(crate) fn error(id: serde_json::Value, code: i32, message: impl Into<String>) -> Self {
        Self {
            jsonrpc: "2.0".into(),
            id,
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
            }),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct JsonRpcError {
    pub(crate) code: i32,
    pub(crate) message: String,
}

// ── Client functions ──────────────────────────────────────────────────────────

/// Fetch an agent's card from `{base_url}/.well-known/agent-card.json`.
pub(crate) async fn discover(base_url: &str) -> anyhow::Result<AgentCard> {
    let url = format!(
        "{}/.well-known/agent-card.json",
        base_url.trim_end_matches('/')
    );
    let card = reqwest::get(&url)
        .await?
        .error_for_status()?
        .json::<AgentCard>()
        .await?;
    Ok(card)
}

/// Send a task to an A2A agent via JSON-RPC `message/send` and return the text response.
pub(crate) async fn message_send(base_url: &str, task: &str) -> anyhow::Result<String> {
    let url = base_url.trim_end_matches('/').to_string();
    let req = JsonRpcRequest {
        jsonrpc: "2.0".into(),
        id: serde_json::Value::Number(1.into()),
        method: "message/send".into(),
        params: MessageSendParams {
            message: A2AMessage {
                kind: "message".into(),
                role: A2ARole::User,
                parts: vec![A2APart::Text {
                    text: task.to_string(),
                }],
                message_id: Some(uuid::Uuid::new_v4().to_string()),
                task_id: None,
                context_id: None,
            },
        },
    };

    let resp = reqwest::Client::new()
        .post(&url)
        .json(&req)
        .send()
        .await?
        .error_for_status()?
        .json::<JsonRpcResponse>()
        .await?;

    if let Some(err) = resp.error {
        return Err(anyhow::anyhow!("A2A error {}: {}", err.code, err.message));
    }

    let task_result = resp
        .result
        .ok_or_else(|| anyhow::anyhow!("A2A response missing result"))?;
    let text = task_result
        .history
        .iter()
        .find(|m| m.role == A2ARole::Agent)
        // `A2APart` has only a text variant, so the first part is the answer;
        // `find_map` would suggest a filter that does not exist.
        .and_then(|m| m.parts.first())
        .map(|p| match p {
            A2APart::Text { text } => text.clone(),
        })
        .ok_or_else(|| anyhow::anyhow!("No text in A2A agent response"))?;

    Ok(text)
}

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

#[cfg(test)]
mod tests {
    use axum::{
        Json, Router,
        routing::{get, post},
    };
    use futures::StreamExt as _;

    use super::*;
    use crate::{datatype::Value, tool::ToolProvider};

    fn test_card() -> AgentCard {
        AgentCard {
            name: "test-agent".into(),
            description: "A test agent".into(),
            url: None,
            version: Some("1.0.0".into()),
            skills: vec![AgentSkill {
                id: "test".into(),
                name: "Test Skill".into(),
                description: "Does something".into(),
                tags: vec![],
                examples: vec![],
            }],
            capabilities: None,
            default_input_modes: vec!["text/plain".into()],
            default_output_modes: vec!["text/plain".into()],
        }
    }

    #[tokio::test]
    async fn test_discover_parses_card() -> anyhow::Result<()> {
        let card = test_card();
        let card_clone = card.clone();
        let app = Router::new().route(
            "/.well-known/agent-card.json",
            get(move || async move { Json(card_clone.clone()) }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move { axum::serve(listener, app).await.ok() });

        let base_url = format!("http://{}", addr);
        let fetched = discover(&base_url).await?;
        assert_eq!(fetched.name, "test-agent");
        assert_eq!(fetched.description, "A test agent");
        assert_eq!(fetched.skills[0].id, "test");
        Ok(())
    }

    #[tokio::test]
    async fn test_message_send_parses_response() -> anyhow::Result<()> {
        let app = Router::new().route(
            "/",
            post(|Json(req): Json<JsonRpcRequest>| async move {
                let agent_msg = A2AMessage {
                    kind: "message".into(),
                    role: A2ARole::Agent,
                    parts: vec![A2APart::Text {
                        text: "Hello from agent".into(),
                    }],
                    message_id: Some("msg-1".into()),
                    task_id: Some("task-1".into()),
                    context_id: Some("ctx-1".into()),
                };
                let task = Task {
                    kind: "task".into(),
                    id: "task-1".into(),
                    context_id: "ctx-1".into(),
                    status: TaskStatus {
                        state: TaskState::Completed,
                        timestamp: None,
                    },
                    history: vec![agent_msg],
                    artifacts: vec![],
                };
                Json(JsonRpcResponse::success(req.id, task))
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move { axum::serve(listener, app).await.ok() });

        let base_url = format!("http://{}", addr);
        let text = message_send(&base_url, "Say hello").await?;
        assert_eq!(text, "Hello from agent");
        Ok(())
    }

    #[tokio::test]
    async fn test_message_send_handles_error() -> anyhow::Result<()> {
        let app = Router::new().route(
            "/",
            post(|Json(req): Json<JsonRpcRequest>| async move {
                Json(JsonRpcResponse::error(
                    req.id,
                    -32000,
                    "Something went wrong",
                ))
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let addr = listener.local_addr()?;
        tokio::spawn(async move { axum::serve(listener, app).await.ok() });

        let base_url = format!("http://{}", addr);
        let result = message_send(&base_url, "do something").await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Something went wrong")
        );
        Ok(())
    }

    // ── Tool construction ─────────────────────────────────────────────────────

    /// A card server plus a `message/send` endpoint, i.e. a whole A2A agent.
    async fn test_agent() -> Url {
        let card = test_card();
        let app = Router::new()
            .route(
                "/.well-known/agent-card.json",
                get(move || {
                    let card = card.clone();
                    async move { Json(card) }
                }),
            )
            .route(
                "/",
                post(|Json(req): Json<JsonRpcRequest>| async move {
                    let echoed = match &req.params.message.parts[0] {
                        A2APart::Text { text } => text.clone(),
                    };
                    let task = Task {
                        kind: "task".into(),
                        id: "task-1".into(),
                        context_id: "ctx-1".into(),
                        status: TaskStatus {
                            state: TaskState::Completed,
                            timestamp: None,
                        },
                        history: vec![A2AMessage {
                            kind: "message".into(),
                            role: A2ARole::Agent,
                            parts: vec![A2APart::Text {
                                text: format!("did: {echoed}"),
                            }],
                            message_id: Some("msg-1".into()),
                            task_id: Some("task-1".into()),
                            context_id: Some("ctx-1".into()),
                        }],
                        artifacts: vec![],
                    };
                    Json(JsonRpcResponse::success(req.id, task))
                }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move { axum::serve(listener, app).await.ok() });
        Url::parse(&format!("http://{addr}")).unwrap()
    }

    #[tokio::test]
    async fn test_desc_parameters_are_an_object_schema() -> anyhow::Result<()> {
        let url = test_agent().await;
        let desc = get_a2a_tool_desc("remote", &url).await?;

        // Not a bare `{"type":"string"}`: OpenAI, Anthropic and Gemini all take
        // `parameters` verbatim and reject a non-object schema.
        let params = serde_json::Value::from(desc.parameters);
        assert_eq!(params["type"], "object");
        assert_eq!(params["properties"]["task"]["type"], "string");
        assert_eq!(params["required"][0], "task");
        Ok(())
    }

    #[tokio::test]
    async fn test_desc_uses_the_callers_name_not_the_cards() -> anyhow::Result<()> {
        let url = test_agent().await;
        // The card calls itself "test-agent"; the registry key is what matters.
        let desc = get_a2a_tool_desc("my_remote", &url).await?;
        assert_eq!(desc.name, "my_remote");
        Ok(())
    }

    #[tokio::test]
    async fn test_desc_name_is_sanitized() -> anyhow::Result<()> {
        let url = test_agent().await;
        let desc = get_a2a_tool_desc("my remote/agent", &url).await?;
        assert_eq!(desc.name, "my_remote_agent");
        Ok(())
    }

    #[tokio::test]
    async fn test_desc_folds_skills_into_the_description() -> anyhow::Result<()> {
        let url = test_agent().await;
        let desc = get_a2a_tool_desc("remote", &url).await?;
        let description = desc.description.unwrap();
        assert!(description.starts_with("A test agent"));
        assert!(description.contains("* Test Skill: Does something"));
        Ok(())
    }

    // ── Through the provider ──────────────────────────────────────────────────

    #[tokio::test]
    async fn test_provided_func_sends_the_task() -> anyhow::Result<()> {
        let url = test_agent().await;
        let desc = get_a2a_tool_desc("remote", &url).await?;

        let mut provider = ToolProvider::empty();
        provider.insert_a2a(desc.name.clone(), url);
        let funcs = provider.provide(&[desc])?;

        // Pure: no console is borrowed to reach the network.
        let out = funcs
            .get("remote")
            .expect("the agent was registered")
            .call_pure(crate::to_value!({ "task": "say hi" }), "call-1")
            .expect("A2A tools are pure")
            .next()
            .await
            .expect("one output");

        assert_eq!(out.message.contents[0].as_text(), Some("did: say hi"));
        assert_eq!(out.message.id.as_deref(), Some("call-1"));
        Ok(())
    }

    #[tokio::test]
    async fn test_missing_task_field_is_reported_not_sent() -> anyhow::Result<()> {
        let url = test_agent().await;
        let desc = get_a2a_tool_desc("remote", &url).await?;

        let mut provider = ToolProvider::empty();
        provider.insert_a2a(desc.name.clone(), url);
        let funcs = provider.provide(&[desc])?;

        let out = funcs
            .get("remote")
            .unwrap()
            .call_pure(Value::object_empty(), "call-1")
            .unwrap()
            .next()
            .await
            .unwrap();

        let text = out.message.contents[0].as_text().unwrap();
        assert!(text.starts_with("Error:"), "got {text}");
        assert!(text.contains("task"), "got {text}");
        Ok(())
    }

    #[tokio::test]
    async fn test_unreachable_agent_surfaces_as_text() -> anyhow::Result<()> {
        // Nothing is listening here; the call must come back as a tool message
        // the model can read, not as a panic or a dropped stream.
        let url = Url::parse("http://127.0.0.1:1")?;
        let mut provider = ToolProvider::empty();
        provider.insert_a2a("dead", url);

        let desc = ToolDescBuilder::new("dead")
            .parameters(crate::to_value!({ "type": "object" }))
            .build();
        let funcs = provider.provide(&[desc])?;

        let out = funcs
            .get("dead")
            .unwrap()
            .call_pure(crate::to_value!({ "task": "anything" }), "call-1")
            .unwrap()
            .next()
            .await
            .unwrap();

        assert!(
            out.message.contents[0]
                .as_text()
                .unwrap()
                .starts_with("Error:"),
            "got {:?}",
            out.message.contents[0]
        );
        Ok(())
    }
}