Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ a2a-server = { package = "a2a-server-lf", path = "a2a-server", version = "0.5.3"
a2a-pb = { package = "a2a-pb", path = "a2a-pb", version = "0.3.2" }
a2a-grpc = { package = "a2a-grpc", path = "a2a-grpc", version = "0.3.11", default-features = false }
a2a-slimrpc = { package = "a2a-slimrpc", path = "a2a-slimrpc", version = "0.3.5" }
a2a-collab = { package = "a2a-collab", path = "a2a-collab", version = "0.1.0" }

# Serialization
serde = { version = "1", features = ["derive"] }
Expand Down
1 change: 1 addition & 0 deletions a2acli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ path = "src/main.rs"
[dependencies]
a2a = { workspace = true }
a2a-client = { workspace = true }
a2a-collab = { workspace = true }
async-trait = { workspace = true }
clap = { version = "4.5", features = ["derive", "env"] }
clap_complete = "4.5"
Expand Down
177 changes: 177 additions & 0 deletions a2acli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::time::Duration;
use a2a::*;
use a2a_client::auth::AuthInterceptor;
use a2a_client::{A2AClient, A2AClientFactory, BoxStream};
use a2a_collab::{CollaborativeSession, require_collaborative_extensions};
use clap::parser::ValueSource;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use fileparts::{FilePartSaver, FilePartSource};
Expand Down Expand Up @@ -266,6 +267,40 @@ pub enum Command {
#[arg(value_name = "SHELL")]
shell: clap_complete::Shell,
},
/// Start a collaborative task session with two or more agents (Basic Relay §2.1).
Collaborate(CollaborateCommand),
}

/// Arguments for `a2acli collaborate`.
#[derive(Debug, Clone, Args, PartialEq, Eq)]
pub struct CollaborateCommand {
/// Initial text payload. Shorthand for a single --text-part when no other
/// part flags are given; mutually exclusive with --text-part/--file-part/--data-part.
pub text: Option<String>,

/// Add a text part. Repeatable and order-preserving alongside
/// --file-part/--data-part.
#[arg(long = "text-part")]
pub text_parts: Vec<String>,

/// Add a file part. A local path is inlined as bytes; a URL is carried
/// by reference. Repeatable.
#[arg(long = "file-part")]
pub file_parts: Vec<String>,

/// Add a structured JSON data part. Repeatable.
#[arg(long = "data-part")]
pub data_parts: Vec<String>,

/// Media type for the part flag immediately preceding it.
#[arg(long = "media-type")]
pub media_types: Vec<String>,

/// Agent Card references to include in the session (at least 2). Each value
/// is a bare host, card URL, or local file path — the same forms as
/// --agent-card. Repeatable: --agent CARD1 --agent CARD2.
#[arg(long = "agent", required = true, num_args = 1)]
pub agents: Vec<String>,
}

#[derive(Debug, Clone, Subcommand, PartialEq, Eq)]
Expand Down Expand Up @@ -1000,6 +1035,7 @@ pub async fn run(
}
}
Command::Task { command } => run_task_command(&cli, matches, command).await?,
Command::Collaborate(command) => run_collaborate_command(&cli, command).await?,
}

Ok(())
Expand Down Expand Up @@ -1610,6 +1646,147 @@ fn build_push_notification_config(
})
}

/// `a2acli collaborate` — Basic Relay model (spec §2.1).
///
/// 1. Resolve each `--agent` reference to an AgentCard and build a client.
/// 2. Pre-flight: verify every agent declares both required extension URIs.
/// 3. Send the initial message to all agents via streaming.
/// 4. Merge all streams. For each event: print it, then relay a translated
/// copy to every *other* agent (echo suppression).
async fn run_collaborate_command(cli: &Cli, command: &CollaborateCommand) -> Result<(), CliError> {
if command.agents.len() < 2 {
return Err(CliError::InvalidInput(
"collaborate requires at least 2 --agent references".to_string(),
));
}

let parts = resolve_collaborate_parts(command)?;
let http = build_http_client(cli)?;
let factory = A2AClientFactory::builder().build();

let mut agents: Vec<(String, A2AClient<Box<dyn a2a_client::Transport>>)> =
Vec::with_capacity(command.agents.len());
for reference in &command.agents {
let card = fetch_card_for_reference(reference, &http).await?;
require_collaborative_extensions(&card).map_err(CliError::A2A)?;
let label = card.name.clone();
let mut client = factory.create_from_card(&card).await?;
if let Some(ref t) = cli.tenant {
client = client.with_tenant(t.clone());
}
agents.push((label, client));
}

let initial_request = SendMessageRequest {
message: Message::new(Role::User, parts),
configuration: None,
metadata: None,
tenant: cli.tenant.clone(),
};

let mut stream = CollaborativeSession::new(agents)
.start(initial_request)
.await
.map_err(CliError::A2A)?;

let deadline = tokio::time::Instant::now() + cli.timeout;
loop {
match tokio::time::timeout_at(deadline, stream.next()).await {
Err(_elapsed) => break,
Ok(None) => break,
Ok(Some((label, event))) => match cli.output {
OutputFormat::Json => {
let line = serde_json::to_string(&serde_json::json!({
"agent": &label,
"event": &event,
}))?;
println!("{line}");
}
OutputFormat::Text => {
for line in event.render_text().lines() {
println!("[{label}] {line}");
}
}
},
}
}

Ok(())
}

/// Build parts from a `CollaborateCommand` using the same logic as `MessageCommand`.
fn resolve_collaborate_parts(command: &CollaborateCommand) -> Result<Vec<Part>, CliError> {
if command.text_parts.is_empty()
&& command.file_parts.is_empty()
&& command.data_parts.is_empty()
{
return match command.text.as_deref() {
Some(text) => Ok(vec![Part::text(text)]),
None => Err(CliError::InvalidInput(
"message must have at least one part: pass text, or use \
--text-part/--file-part/--data-part"
.to_string(),
)),
};
}
if command.text.is_some() {
return Err(CliError::InvalidInput(
"the positional message text cannot be combined with \
--text-part/--file-part/--data-part; pass it as --text-part instead"
.to_string(),
));
}
// Simple ordered assembly: text parts first, then file, then data.
// A full order-preserving implementation would need ArgMatches indices.
let mut parts: Vec<Part> = Vec::new();
for t in &command.text_parts {
parts.push(Part::text(t));
}
for f in &command.file_parts {
let content = std::fs::read(f).map_err(|source| CliError::ReadFile {
path: f.clone(),
source,
})?;
parts.push(Part::raw(content));
}
for d in &command.data_parts {
let value: Value = if d == "-" {
serde_json::from_reader(std::io::stdin())?
} else if d.starts_with('{') || d.starts_with('[') {
serde_json::from_str(d)?
} else {
let text = std::fs::read_to_string(d).map_err(|source| CliError::ReadFile {
path: d.clone(),
source,
})?;
serde_json::from_str(&text)?
};
parts.push(Part::data(value));
}
Ok(parts)
}

/// Fetch an AgentCard from a reference string (host, URL, or file path).
async fn fetch_card_for_reference(
reference: &str,
http: &reqwest::Client,
) -> Result<AgentCard, CliError> {
match normalize_card_reference(reference) {
CardReference::File(path) => Ok(read_agent_card_file(&path)?.0),
CardReference::Url(url) => {
let raw: Value = http
.get(&url)
.send()
.await?
.error_for_status()?
.json()
.await?;
serde_json::from_value(raw)
.map_err(|error| CliError::CardInvalid(format!("{url}: {error}")))
}
}
}

/// Every push-notification subcommand is gated on the card declaring
/// `pushNotifications` (§13.3). None of them has a non-push equivalent, so
/// an undeclared capability fails with the reason rather than spending a
Expand Down
Loading