basis 0.19.0

The basis SDK: workspace discovery, run lifecycle, one event stream, and the two seams. No protocol, no transport, no TTY.
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
//! mentra's A2A client as a [`Peer`] (ADR-0038 §3).
//!
//! The exchange — submit with `returnImmediately`, wait for the task to
//! settle within the agent's wait bound (following its stream when the card
//! offers one, polling otherwise, never resending), cancel when the run is
//! cancelled — is mentra's ([`mentra::a2a::exchange`]), and so is the framing
//! that marks the remote agent's words as its own. What this module adds is
//! the hops extension on every message (`docs/a2a/hops-v1.md`, ADR-0030 §9)
//! and the mapping of mentra's answers onto the contract `spawn` is written
//! against.

use std::{sync::Arc, time::SystemTime};

use async_trait::async_trait;
use chrono::{DateTime, SecondsFormat, Utc};
use mentra::a2a::{
    A2aClient, A2aError as ClientError, A2aExchange, A2aExchangeError, A2aRequest, A2aRpcError,
    A2aSend, A2aStillWorking, A2aSubmitted, is_settled, remote_files, remote_output, remote_reply,
    reply_files, settle as settle_task, submit,
    types::{Part, PartContent, TaskState},
};
use serde_json::{Value, json};

use super::HOPS_EXTENSION;
use crate::agents::{
    Attachment, ExchangeBounds, Failure, Message, Outcome, Peer, PeerError, Request, Resolved,
    Started, StillWorking,
};

/// A remote agent reached over A2A.
pub struct A2aPeer {
    client: Arc<A2aClient>,
    /// The name the output is framed under — what the model calls the agent.
    name: String,
}

impl A2aPeer {
    /// Speaks to `client` as the agent the model calls `name`.
    pub fn new(client: Arc<A2aClient>, name: impl Into<String>) -> Self {
        Self {
            client,
            name: name.into(),
        }
    }

    /// The client underneath, for a resolver that keeps one per agent.
    pub fn client(&self) -> &Arc<A2aClient> {
        &self.client
    }
}

impl std::fmt::Debug for A2aPeer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("A2aPeer")
            .field("name", &self.name)
            .field("endpoint", &self.client.endpoint().as_str())
            .finish()
    }
}

impl Resolved {
    /// A remote agent reached over A2A through `client`, called `name`: the
    /// peer is an [`A2aPeer`], the endpoint the client's URL, and the id the
    /// name until [`with_id`](Self::with_id) says otherwise.
    pub fn over_a2a(client: Arc<A2aClient>, name: impl Into<String>) -> Self {
        let name = name.into();
        let endpoint = client.endpoint().to_string();
        Self::new(Arc::new(A2aPeer::new(client, name.clone())), name, endpoint)
    }
}

#[async_trait]
impl Peer for A2aPeer {
    async fn exchange(
        &self,
        request: Request,
        bounds: &ExchangeBounds<'_>,
    ) -> Result<Outcome, PeerError> {
        let request = match request {
            Request::Wait { task_id } => A2aRequest::resume(task_id),
            Request::Send(send) => message(send).into(),
            // `Request` is non-exhaustive for callers outside the crate; a
            // variant this adapter does not know cannot be sent.
            #[allow(unreachable_patterns)]
            _ => return Err(PeerError::Unrecognized),
        };
        let max = self.max_output_bytes();
        let outcome = match submit(&self.client, request).await {
            Ok(A2aSubmitted::Task(task)) if !is_settled(&task.status.state) => {
                (bounds.started)(Started {
                    task_id: task.id.clone(),
                    context_id: Some(task.context_id.clone()),
                });
                settle_task(&self.client, task, bounds.options, bounds.progress).await
            }
            Ok(A2aSubmitted::Task(task)) => Ok(A2aExchange::Settled(task)),
            Ok(A2aSubmitted::Reply(message)) => Ok(A2aExchange::Reply(message)),
            Ok(_) => return Err(PeerError::Unrecognized),
            Err(error) => Err(error),
        };
        map(&self.name, outcome, max)
    }

    fn max_output_bytes(&self) -> usize {
        self.client.limits().max_output_bytes
    }
}

/// mentra's answer, as the contract says it.
fn map(
    name: &str,
    outcome: Result<A2aExchange, A2aExchangeError>,
    max: usize,
) -> Result<Outcome, PeerError> {
    match outcome {
        Ok(A2aExchange::Reply(message)) => Ok(Outcome::Replied {
            text: remote_reply(name, &message, max),
            files: attachments(reply_files(&message)),
            context_id: message.context_id,
        }),
        Ok(A2aExchange::Settled(task)) => {
            let text = remote_output(name, &task, max);
            let files = attachments(remote_files(&task));
            let task_id = task.id.clone();
            let context_id = Some(task.context_id.clone());
            Ok(match task.status.state {
                TaskState::InputRequired => Outcome::NeedsInput {
                    task_id,
                    context_id,
                    text,
                    files,
                },
                TaskState::AuthRequired => Outcome::NeedsAuthorization {
                    task_id,
                    context_id,
                    text,
                    files,
                },
                TaskState::Failed | TaskState::Rejected | TaskState::Canceled => Outcome::Failed {
                    task_id,
                    context_id,
                    text,
                    files,
                    how: match task.status.state {
                        TaskState::Rejected => Failure::Rejected,
                        TaskState::Canceled => Failure::Canceled,
                        _ => Failure::Failed,
                    },
                },
                _ => Outcome::Finished {
                    task_id,
                    context_id,
                    text,
                    files,
                },
            })
        }
        Ok(A2aExchange::StillWorking { task, reason }) => Ok(Outcome::Working {
            text: remote_output(name, &task, max),
            files: attachments(remote_files(&task)),
            task_id: task.id,
            context_id: Some(task.context_id),
            why: match reason {
                A2aStillWorking::WaitBound(waited) => StillWorking::WaitBound(waited),
                _ => StillWorking::RunStopping,
            },
        }),
        Ok(_) => Err(PeerError::Unrecognized),
        Err(error) if task_not_found(&error) => Err(PeerError::UnknownTask),
        // mentra's error carries no server text and no header value.
        Err(A2aExchangeError::Send(error)) => Err(PeerError::Send(error.to_string())),
        Err(A2aExchangeError::Poll { task_id, error }) => Err(PeerError::Check {
            task_id,
            error: error.to_string(),
        }),
        Err(A2aExchangeError::Abandoned {
            task_id, canceled, ..
        }) => Err(PeerError::Abandoned {
            task_id,
            canceled: canceled.map_err(|error| error.to_string()),
        }),
        Err(error) => Err(PeerError::Send(error.to_string())),
    }
}

/// Whether the agent answered that it does not know the task asked about.
fn task_not_found(error: &A2aExchangeError) -> bool {
    let not_found = |error: &ClientError| {
        matches!(
            error,
            ClientError::Rpc {
                error: A2aRpcError::TaskNotFound,
                ..
            }
        )
    };
    match error {
        A2aExchangeError::Send(error) | A2aExchangeError::Poll { error, .. } => not_found(error),
        _ => false,
    }
}

/// The A2A message for `send`: continuing its context, answering its task,
/// and saying which hop it is.
fn message(send: Message) -> A2aSend {
    let mut message = A2aSend::new(send.text)
        .with_extension(HOPS_EXTENSION)
        .with_metadata(HOPS_EXTENSION, hop_metadata(send.hop, send.deadline));
    if let Some(task_id) = send.answering {
        message = message.with_task_id(task_id);
    }
    if let Some(context_id) = send.context_id {
        message = message.with_context_id(context_id);
    }
    // A delegation's parameters are the request's metadata, beside the
    // message — the hops extension keeps the message's own (ADR-0040).
    for (key, value) in send.metadata.into_iter().flatten() {
        message = message.with_request_metadata(key, value);
    }
    // Files go after the text, each a `raw` part (ADR-0041).
    for file in send.files {
        let mut part = Part::raw(file.data).with_media_type(file.media_type);
        if let Some(name) = file.name {
            part = part.with_filename(name);
        }
        message = message.with_part(part);
    }
    message
}

/// The files among `parts` that came as bytes, each with its media type —
/// the one the agent declared, or else what the bytes and name say. A file by
/// URL is not fetched (ADR-0041 §4): it stays in the text, as a URL.
fn attachments(parts: Vec<&Part>) -> Vec<Attachment> {
    parts
        .into_iter()
        .filter_map(|part| {
            let PartContent::Raw(data) = &part.content else {
                return None;
            };
            let name = part.filename.clone();
            let media_type = part
                .media_type
                .clone()
                .filter(|declared| !declared.trim().is_empty())
                .unwrap_or_else(|| {
                    mentra::media::media_type(name.as_deref().unwrap_or_default(), data).to_string()
                });
            Some(Attachment::new(name, media_type, data.clone()))
        })
        .collect()
}

/// The object the hops extension puts under its URI in a message's metadata
/// (`docs/a2a/hops-v1.md`): this message's hop, and when this side stops
/// waiting, which the run's options already hold as the earlier of its own
/// and any it inherited — so a deadline only shrinks across a hop, which is
/// the extension's rule.
fn hop_metadata(hop: u32, deadline: Option<SystemTime>) -> Value {
    let mut object = json!({ "hop": hop });
    if let Some(deadline) = deadline {
        object["deadline"] = Value::String(
            DateTime::<Utc>::from(deadline).to_rfc3339_opts(SecondsFormat::Millis, true),
        );
    }
    object
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use mentra::a2a::types::{Artifact, Part, Task, TaskStatus};

    use super::*;

    const NAME: &str = "reviewer";
    const MAX: usize = 64 * 1024;

    #[test]
    fn a_delegations_parameters_are_the_requests_metadata() {
        let mut parameters = serde_json::Map::new();
        parameters.insert("project".into(), serde_json::json!("lama"));
        let send = message(Message::new("where is login?").with_metadata(Some(parameters)));
        assert_eq!(
            send.request_metadata.get("project"),
            Some(&serde_json::json!("lama"))
        );
        assert!(
            send.metadata.contains_key(HOPS_EXTENSION),
            "the message keeps its own metadata for the hops extension"
        );
        assert!(!send.metadata.contains_key("project"), "not in the message");
        assert!(message(Message::new("hi")).request_metadata.is_empty());
    }

    fn task(state: TaskState, answer: Option<&str>) -> Task {
        Task {
            id: "task-1".to_string(),
            context_id: "context-1".to_string(),
            status: TaskStatus {
                state,
                message: None,
                timestamp: None,
            },
            artifacts: answer.map(|text| {
                vec![Artifact {
                    artifact_id: "result".to_string(),
                    name: None,
                    description: None,
                    parts: vec![Part::text(text.to_string())],
                    metadata: None,
                    extensions: None,
                }]
            }),
            history: None,
            metadata: None,
        }
    }

    fn not_found(method: &'static str) -> ClientError {
        ClientError::Rpc {
            method,
            error: A2aRpcError::TaskNotFound,
        }
    }

    #[test]
    fn a_messages_files_follow_its_text_as_raw_parts() {
        let send = message(
            Message::new("why is it red?").with_files(vec![Attachment::new(
                Some("login.png".into()),
                "image/png",
                vec![0x89, b'P'],
            )]),
        );
        assert_eq!(send.parts.len(), 1);
        let part = &send.parts[0];
        assert_eq!(part.filename.as_deref(), Some("login.png"));
        assert_eq!(part.media_type.as_deref(), Some("image/png"));
        assert_eq!(part.content, PartContent::Raw(vec![0x89, b'P']));
    }

    #[test]
    fn a_task_returns_its_inline_files_and_leaves_a_url_in_the_text() {
        let mut settled = task(TaskState::Completed, Some("here"));
        let parts = &mut settled.artifacts.as_mut().unwrap()[0].parts;
        parts.push(Part::raw(b"\x89PNG\r\n\x1a\nrest".to_vec()).with_filename("shot.png"));
        parts.push(Part::url("https://example.com/big.zip").with_filename("big.zip"));

        let Ok(Outcome::Finished { text, files, .. }) =
            map(NAME, Ok(A2aExchange::Settled(settled)), MAX)
        else {
            panic!("finished");
        };
        assert_eq!(
            files,
            vec![Attachment::new(
                Some("shot.png".into()),
                "image/png",
                b"\x89PNG\r\n\x1a\nrest".to_vec()
            )],
            "an undeclared type is read off the bytes"
        );
        assert!(text.contains("https://example.com/big.zip"), "{text}");
    }

    #[test]
    fn every_message_says_which_hop_it_is_and_when_this_side_stops_waiting() {
        let deadline = std::time::UNIX_EPOCH + Duration::from_millis(1_791_000_000_123);
        let message = message(Message::new("look").at_hop(3, Some(deadline)));

        assert_eq!(message.extensions, vec![HOPS_EXTENSION.to_string()]);
        assert_eq!(
            message.metadata.get(HOPS_EXTENSION),
            Some(&json!({"hop": 3, "deadline": "2026-10-03T04:00:00.123Z"}))
        );
    }

    #[test]
    fn a_top_level_caller_sends_hop_one_and_no_deadline_it_does_not_have() {
        let message = message(Message::new("look"));
        assert_eq!(
            message.metadata.get(HOPS_EXTENSION),
            Some(&json!({"hop": 1}))
        );
        assert_eq!(message.task_id, None);
        assert_eq!(message.context_id, None);
    }

    #[test]
    fn a_message_continues_its_context_and_answers_its_task() {
        let message = message(
            Message::new("yes")
                .in_context(Some("context-1".to_string()))
                .answering(Some("task-1".to_string())),
        );
        assert_eq!(message.context_id.as_deref(), Some("context-1"));
        assert_eq!(message.task_id.as_deref(), Some("task-1"));
    }

    #[test]
    fn each_task_state_is_one_outcome() {
        let finished = map(
            NAME,
            Ok(A2aExchange::Settled(task(
                TaskState::Completed,
                Some("looks good"),
            ))),
            MAX,
        )
        .expect("finished");
        let Outcome::Finished {
            task_id,
            context_id,
            text,
            files,
        } = finished
        else {
            panic!("{finished:?}");
        };
        assert_eq!(task_id, "task-1");
        assert_eq!(context_id.as_deref(), Some("context-1"));
        assert!(text.contains("looks good"), "{text}");
        assert!(files.is_empty());

        assert!(matches!(
            map(
                NAME,
                Ok(A2aExchange::Settled(task(TaskState::InputRequired, None))),
                MAX
            ),
            Ok(Outcome::NeedsInput { .. })
        ));
        assert!(matches!(
            map(
                NAME,
                Ok(A2aExchange::Settled(task(TaskState::AuthRequired, None))),
                MAX
            ),
            Ok(Outcome::NeedsAuthorization { .. })
        ));
        for (state, how) in [
            (TaskState::Failed, Failure::Failed),
            (TaskState::Rejected, Failure::Rejected),
            (TaskState::Canceled, Failure::Canceled),
        ] {
            assert!(matches!(
                map(NAME, Ok(A2aExchange::Settled(task(state, None))), MAX),
                Ok(Outcome::Failed { how: got, .. }) if got == how
            ));
        }
        assert!(matches!(
            map(
                NAME,
                Ok(A2aExchange::StillWorking {
                    task: task(TaskState::Working, None),
                    reason: A2aStillWorking::WaitBound(Duration::from_secs(300)),
                }),
                MAX
            ),
            Ok(Outcome::Working {
                why: StillWorking::WaitBound(waited),
                ..
            }) if waited == Duration::from_secs(300)
        ));
    }

    #[test]
    fn a_task_the_agent_does_not_know_is_unknown_whichever_call_said_so() {
        assert_eq!(
            map(NAME, Err(A2aExchangeError::Send(not_found("GetTask"))), MAX),
            Err(PeerError::UnknownTask)
        );
        assert_eq!(
            map(
                NAME,
                Err(A2aExchangeError::Poll {
                    task_id: "task-1".to_string(),
                    error: not_found("GetTask"),
                }),
                MAX
            ),
            Err(PeerError::UnknownTask)
        );
    }

    #[test]
    fn other_failures_keep_their_kind_and_say_no_more_than_mentra_does() {
        assert!(matches!(
            map(
                NAME,
                Err(A2aExchangeError::Send(ClientError::Transport("connection reset"))),
                MAX
            ),
            Err(PeerError::Send(text)) if text.contains("connection reset")
        ));
        assert!(matches!(
            map(
                NAME,
                Err(A2aExchangeError::Poll {
                    task_id: "task-1".to_string(),
                    error: ClientError::Connect,
                }),
                MAX
            ),
            Err(PeerError::Check { task_id, .. }) if task_id == "task-1"
        ));
    }
}