codetether-agent 4.0.0

A2A-native AI coding agent for the CodeTether ecosystem
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
//! Swarm Execute Tool - Parallel task execution across multiple agents
//!
//! This tool enables LLM-driven parallel execution of tasks across multiple
//! sub-agents in a swarm pattern, with configurable concurrency and aggregation.

use super::{Tool, ToolResult};
use crate::provider::{ProviderRegistry, parse_model_string};
use crate::swarm::executor::run_agent_loop;
use crate::tool::ToolRegistry;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

pub struct SwarmExecuteTool;

impl SwarmExecuteTool {
    pub fn new() -> Self {
        Self
    }
}

impl Default for SwarmExecuteTool {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Clone)]
struct TaskInput {
    id: Option<String>,
    name: String,
    instruction: String,
    #[allow(dead_code)]
    specialty: Option<String>,
}

#[derive(serde::Serialize)]
struct TaskResult {
    task_id: String,
    task_name: String,
    success: bool,
    output: String,
    error: Option<String>,
    steps: usize,
    tool_calls: usize,
}

#[async_trait]
impl Tool for SwarmExecuteTool {
    fn id(&self) -> &str {
        "swarm_execute"
    }

    fn name(&self) -> &str {
        "Swarm Execute"
    }

    fn description(&self) -> &str {
        "Execute multiple tasks in parallel across multiple sub-agents. \
         Each task runs independently in its own agent context. \
         Returns aggregated results from all swarm participants. \
         Handles partial failures gracefully based on aggregation strategy."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "tasks": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string",
                                "description": "Unique identifier for this task (auto-generated if not provided)"
                            },
                            "name": {
                                "type": "string",
                                "description": "Human-readable name for this task"
                            },
                            "instruction": {
                                "type": "string",
                                "description": "The instruction for the sub-agent to execute"
                            },
                            "specialty": {
                                "type": "string",
                                "description": "Optional specialty for the sub-agent (e.g., 'Code Writer', 'Researcher', 'Tester')"
                            }
                        },
                        "required": ["name", "instruction"]
                    },
                    "description": "Array of tasks to execute in parallel"
                },
                "concurrency_limit": {
                    "type": "integer",
                    "description": "Maximum number of concurrent agents (default: 5)",
                    "default": 5
                },
                "aggregation_strategy": {
                    "type": "string",
                    "enum": ["all", "first_error", "best_effort"],
                    "description": "How to aggregate results: 'all' (all must succeed), 'first_error' (stop on first error), 'best_effort' (collect all, report failures)",
                    "default": "best_effort"
                },
                "model": {
                    "type": "string",
                    "description": "Model to use for sub-agents (provider/model format, e.g., 'anthropic/claude-sonnet-4-20250514'). Defaults to configured default."
                },
                "max_steps": {
                    "type": "integer",
                    "description": "Maximum steps per sub-agent (default: 50)",
                    "default": 50
                },
                "timeout_secs": {
                    "type": "integer",
                    "description": "Timeout per sub-agent in seconds (default: 300)",
                    "default": 300
                }
            },
            "required": ["tasks"]
        })
    }

    async fn execute(&self, params: Value) -> Result<ToolResult> {
        let example = json!({
            "tasks": [{"name": "Task 1", "instruction": "Do something"}],
            "concurrency_limit": 5,
            "aggregation_strategy": "best_effort"
        });

        // Parse tasks array
        let tasks_val = match params.get("tasks").and_then(|v| v.as_array()) {
            Some(arr) if !arr.is_empty() => arr,
            Some(_) => {
                return Ok(ToolResult::structured_error(
                    "INVALID_FIELD",
                    "swarm_execute",
                    "tasks array must contain at least one task",
                    Some(vec!["tasks"]),
                    Some(example),
                ));
            }
            None => {
                return Ok(ToolResult::structured_error(
                    "MISSING_FIELD",
                    "swarm_execute",
                    "tasks is required and must be an array of task objects with 'name' and 'instruction' fields",
                    Some(vec!["tasks"]),
                    Some(example),
                ));
            }
        };

        let mut tasks = Vec::new();
        for (i, task_val) in tasks_val.iter().enumerate() {
            let name = match task_val.get("name").and_then(|v| v.as_str()) {
                Some(s) => s.to_string(),
                None => {
                    return Ok(ToolResult::structured_error(
                        "INVALID_FIELD",
                        "swarm_execute",
                        &format!("tasks[{i}].name is required and must be a string"),
                        Some(vec!["name"]),
                        Some(json!({"name": "Task Name", "instruction": "Do something"})),
                    ));
                }
            };
            let instruction = match task_val.get("instruction").and_then(|v| v.as_str()) {
                Some(s) => s.to_string(),
                None => {
                    return Ok(ToolResult::structured_error(
                        "INVALID_FIELD",
                        "swarm_execute",
                        &format!("tasks[{i}].instruction is required and must be a string"),
                        Some(vec!["instruction"]),
                        Some(json!({"name": name, "instruction": "What the sub-agent should do"})),
                    ));
                }
            };
            tasks.push(TaskInput {
                id: task_val
                    .get("id")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                name,
                instruction,
                specialty: task_val
                    .get("specialty")
                    .and_then(|v| v.as_str())
                    .map(String::from),
            });
        }

        let concurrency_limit = params
            .get("concurrency_limit")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or(5);
        let aggregation_strategy = params
            .get("aggregation_strategy")
            .and_then(|v| v.as_str())
            .unwrap_or("best_effort")
            .to_string();
        let model = params
            .get("model")
            .and_then(|v| v.as_str())
            .map(String::from);
        let max_steps = params
            .get("max_steps")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize)
            .unwrap_or(50);
        let timeout_secs = params
            .get("timeout_secs")
            .and_then(|v| v.as_u64())
            .unwrap_or(300);

        let concurrency = concurrency_limit.min(20).max(1);

        tracing::info!(
            task_count = tasks.len(),
            concurrency = concurrency,
            strategy = %aggregation_strategy,
            "Starting swarm execution"
        );

        // Get provider registry from Vault
        let providers = ProviderRegistry::from_vault()
            .await
            .context("Failed to load providers")?;
        let provider_list = providers.list();

        if provider_list.is_empty() {
            return Ok(ToolResult::error(
                "No providers available for swarm execution",
            ));
        }

        // Determine model to use
        let (provider_name, model_name) = if let Some(ref model_str) = model {
            let (prov, mod_id) = parse_model_string(model_str);
            let prov = prov.map(|p| if p == "zhipuai" { "zai" } else { p });
            (
                prov.filter(|p| provider_list.contains(p))
                    .unwrap_or(provider_list[0])
                    .to_string(),
                mod_id.to_string(),
            )
        } else {
            // Default to GLM-5 via Z.AI for swarm
            let provider = if provider_list.contains(&"zai") {
                "zai".to_string()
            } else if provider_list.contains(&"openrouter") {
                "openrouter".to_string()
            } else {
                provider_list[0].to_string()
            };
            let model = "glm-5".to_string();
            (provider, model)
        };

        let provider = providers
            .get(&provider_name)
            .context("Failed to get provider")?;

        tracing::info!(provider = %provider_name, model = %model_name, "Using provider for swarm");

        // Get tool definitions (filtered for sub-agents)
        let tools = Self::get_subagent_tools();

        // System prompt for sub-agents
        let system_prompt = r#"You are a sub-agent in a swarm execution context.
Your role is to execute the given task independently and report your results.
Focus on completing your specific task efficiently.
Use available tools to accomplish your goal.
When done, provide a clear summary of what you accomplished.
Share any intermediate results using the swarm_share tool so other agents can benefit."#;

        // Execute tasks concurrently using semaphore for rate limiting
        let semaphore = Arc::new(tokio::sync::Semaphore::new(concurrency));
        let mut join_handles = Vec::new();

        for task_input in tasks.clone() {
            let semaphore = semaphore.clone();
            let provider = provider.clone();
            let tools = tools.clone();
            let system_prompt = system_prompt.to_string();
            let task_id = task_input
                .id
                .clone()
                .unwrap_or_else(|| format!("task_{}", uuid::Uuid::new_v4()));
            let model_name = model_name.clone();
            let max_steps = max_steps;
            let timeout_secs = timeout_secs;

            let handle = tokio::spawn(async move {
                let _permit = semaphore.acquire().await.unwrap();

                let user_prompt = format!(
                    "Task: {}\nSpecialty: {}\n\nInstruction: {}",
                    task_input.name,
                    task_input
                        .specialty
                        .as_deref()
                        .unwrap_or("Generalist execution"),
                    task_input.instruction
                );

                let (output, steps, tool_calls, exit) = run_agent_loop(
                    provider,
                    &model_name,
                    &system_prompt,
                    &user_prompt,
                    tools,
                    Arc::new(ToolRegistry::new()),
                    max_steps,
                    timeout_secs,
                    None,
                    task_id.clone(),
                    None,
                    None,
                )
                .await?;

                let success = matches!(exit, crate::swarm::executor::AgentLoopExit::Completed)
                    || matches!(exit, crate::swarm::executor::AgentLoopExit::MaxStepsReached);

                Ok::<TaskResult, anyhow::Error>(TaskResult {
                    task_id,
                    task_name: task_input.name,
                    success,
                    output,
                    error: if success {
                        None
                    } else {
                        Some(format!("{:?}", exit))
                    },
                    steps,
                    tool_calls,
                })
            });

            join_handles.push(handle);
        }

        // Wait for all tasks to complete
        let mut results: Vec<TaskResult> = Vec::new();
        let mut failures = 0;

        for handle in join_handles {
            match handle.await {
                Ok(Ok(result)) => {
                    if !result.success {
                        failures += 1;

                        // Handle aggregation strategies
                        match aggregation_strategy.as_str() {
                            "all" => {
                                // Return immediately on first failure
                                return Ok(ToolResult::success(
                                    json!({
                                        "status": "failed",
                                        "failed_task": result.task_name,
                                        "error": result.error,
                                        "results": [result],
                                        "summary": {
                                            "total": 1,
                                            "success": 0,
                                            "failures": 1
                                        }
                                    })
                                    .to_string(),
                                ));
                            }
                            "first_error" => {
                                return Ok(ToolResult::success(
                                    json!({
                                        "status": "error",
                                        "error": result.error,
                                        "failed_task": result.task_name,
                                        "completed_tasks": results.len(),
                                        "results": results,
                                    })
                                    .to_string(),
                                ));
                            }
                            _ => {} // "best_effort" - continue collecting
                        }
                    }
                    results.push(result);
                }
                Ok(Err(e)) => {
                    failures += 1;
                    tracing::error!(error = %e, "Task execution failed");
                }
                Err(e) => {
                    failures += 1;
                    tracing::error!(error = %e, "Task join failed");
                }
            }
        }

        // Build aggregation response
        let total = results.len();
        let successes = results.iter().filter(|r| r.success).count();

        let response = if failures == 0 {
            json!({
                "status": "success",
                "results": results,
                "summary": {
                    "total": total,
                    "success": successes,
                    "failures": failures
                }
            })
        } else {
            match aggregation_strategy.as_str() {
                "all" => json!({
                    "status": "partial_failure",
                    "results": results,
                    "summary": {
                        "total": total,
                        "success": successes,
                        "failures": failures
                    }
                }),
                "first_error" => json!({
                    "status": "error",
                    "results": results,
                    "summary": {
                        "total": total,
                        "success": successes,
                        "failures": failures
                    }
                }),
                _ => json!({
                    "status": "partial_success",
                    "results": results,
                    "summary": {
                        "total": total,
                        "success": successes,
                        "failures": failures
                    }
                }),
            }
        };

        Ok(ToolResult::success(response.to_string()))
    }
}

impl SwarmExecuteTool {
    /// Get tool definitions suitable for sub-agents
    fn get_subagent_tools() -> Vec<crate::provider::ToolDefinition> {
        // Filter out interactive/blocking tools that don't work well for sub-agents
        let registry = ToolRegistry::new();
        registry
            .definitions()
            .into_iter()
            .filter(|t| {
                !matches!(
                    t.name.as_str(),
                    "question"
                        | "confirm_edit"
                        | "confirm_multiedit"
                        | "plan_enter"
                        | "plan_exit"
                        | "swarm_execute"
                        | "agent"
                )
            })
            .collect()
    }
}