codetether-agent 4.6.1

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
//! SubTask and SubAgent definitions
//!
//! A SubTask is a unit of work that can be executed in parallel.
//! A SubAgent is a dynamically instantiated agent for executing a subtask.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// A sub-task that can be executed by a sub-agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubTask {
    /// Unique identifier
    pub id: String,

    /// Human-readable name/description
    pub name: String,

    /// The task instruction for the sub-agent
    pub instruction: String,

    /// Specialty/domain for this subtask
    pub specialty: Option<String>,

    /// Dependencies on other subtasks (by ID)
    pub dependencies: Vec<String>,

    /// Priority (higher = more important)
    pub priority: i32,

    /// Maximum steps allowed for this subtask
    pub max_steps: usize,

    /// Input context from parent or dependencies
    pub context: SubTaskContext,

    /// Current status
    pub status: SubTaskStatus,

    /// Assigned sub-agent ID
    pub assigned_agent: Option<String>,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Completion timestamp
    pub completed_at: Option<DateTime<Utc>>,

    /// Stage in the execution plan (0 = can run immediately)
    pub stage: usize,

    /// Explicit override for whether this subtask needs an isolated
    /// git worktree. `None` (the default) runs [`SubTask::needs_worktree`]
    /// heuristics on specialty + instruction; `Some(true)` forces a
    /// worktree; `Some(false)` forces the shared working directory.
    ///
    /// Skipping the worktree for read-only tasks (research, review,
    /// planning, fact-check) saves ~1s of setup, an inode, and
    /// `.git/worktrees` lock contention when running many agents
    /// in parallel. Tasks that edit files should keep the default or
    /// explicitly request a worktree so their edits don't collide with
    /// sibling agents in the same swarm.
    #[serde(default)]
    pub needs_worktree: Option<bool>,
}

impl SubTask {
    /// Create a new subtask
    pub fn new(name: impl Into<String>, instruction: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            instruction: instruction.into(),
            specialty: None,
            dependencies: Vec::new(),
            priority: 0,
            max_steps: 100,
            context: SubTaskContext::default(),
            status: SubTaskStatus::Pending,
            assigned_agent: None,
            created_at: Utc::now(),
            completed_at: None,
            stage: 0,
            needs_worktree: None,
        }
    }

    /// Add a specialty
    pub fn with_specialty(mut self, specialty: impl Into<String>) -> Self {
        self.specialty = Some(specialty.into());
        self
    }

    /// Add dependencies
    pub fn with_dependencies(mut self, deps: Vec<String>) -> Self {
        self.dependencies = deps;
        self
    }

    /// Set priority
    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    /// Set max steps
    pub fn with_max_steps(mut self, max_steps: usize) -> Self {
        self.max_steps = max_steps;
        self
    }

    /// Add context
    pub fn with_context(mut self, context: SubTaskContext) -> Self {
        self.context = context;
        self
    }

    /// Explicitly set whether this subtask needs a worktree.
    ///
    /// `true` forces isolation; `false` forces the shared directory;
    /// omit this call to fall back to [`SubTask::needs_worktree`]
    /// heuristics. See the field docs on [`SubTask::needs_worktree`]
    /// for why this matters in large swarms.
    pub fn with_needs_worktree(mut self, needs: bool) -> Self {
        self.needs_worktree = Some(needs);
        self
    }

    /// Decide whether this subtask should run in an isolated worktree.
    ///
    /// Honours the explicit override when set; otherwise applies a
    /// conservative heuristic:
    ///
    /// - Specialty keywords like `research`, `review`, `analy`,
    ///   `audit`, `plan`, `fact`, `summari`, `search`, `explore`,
    ///   `docs` imply a read-only task → no worktree.
    /// - Instruction keywords like `write`, `edit`, `create`, `fix`,
    ///   `implement`, `refactor`, `apply`, `commit` imply file
    ///   mutation → worktree.
    /// - Unknown tasks default to `true` (worktree) to stay safe
    ///   against accidental cross-agent edit collisions.
    pub fn needs_worktree(&self) -> bool {
        if let Some(explicit) = self.needs_worktree {
            return explicit;
        }
        let haystack_specialty = self.specialty.as_deref().unwrap_or("").to_ascii_lowercase();
        let haystack_instruction = self.instruction.to_ascii_lowercase();

        const READONLY_HINTS: &[&str] = &[
            "research",
            "review",
            "analy",
            "audit",
            "plan",
            "fact",
            "summari",
            "explore",
            "docs",
            "read-only",
            "readonly",
        ];
        const MUTATING_HINTS: &[&str] = &[
            "write",
            "edit",
            "create ",
            "fix",
            "implement",
            "refactor",
            "apply",
            "commit",
            "patch",
            "scaffold",
            "build",
        ];

        if READONLY_HINTS
            .iter()
            .any(|k| haystack_specialty.contains(k))
            && !MUTATING_HINTS
                .iter()
                .any(|k| haystack_instruction.contains(k))
        {
            return false;
        }
        true
    }

    /// Check if this subtask can run (all dependencies complete)
    pub fn can_run(&self, completed: &[String]) -> bool {
        self.dependencies.iter().all(|dep| completed.contains(dep))
    }

    /// Mark as running
    pub fn start(&mut self, agent_id: &str) {
        self.status = SubTaskStatus::Running;
        self.assigned_agent = Some(agent_id.to_string());
    }

    /// Mark as completed
    pub fn complete(&mut self, success: bool) {
        self.status = if success {
            SubTaskStatus::Completed
        } else {
            SubTaskStatus::Failed
        };
        self.completed_at = Some(Utc::now());
    }
}

/// Context passed to a subtask
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SubTaskContext {
    /// Parent task information
    pub parent_task: Option<String>,

    /// Results from dependency subtasks
    pub dependency_results: HashMap<String, String>,

    /// Shared files or resources
    pub shared_resources: Vec<String>,

    /// Additional metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Status of a subtask
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubTaskStatus {
    /// Waiting to be scheduled
    Pending,

    /// Waiting for dependencies
    Blocked,

    /// Currently executing
    Running,

    /// Successfully completed
    Completed,

    /// Failed with error
    Failed,

    /// Cancelled by orchestrator
    Cancelled,

    /// Timed out
    TimedOut,
}

/// A sub-agent executing a subtask
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubAgent {
    /// Unique identifier
    pub id: String,

    /// Display name
    pub name: String,

    /// Specialty/role (e.g., "AI Researcher", "Code Writer", "Fact Checker")
    pub specialty: String,

    /// The subtask this agent is working on
    pub subtask_id: String,

    /// Current status
    pub status: SubAgentStatus,

    /// Number of steps taken
    pub steps: usize,

    /// Tool calls made
    pub tool_calls: Vec<ToolCallRecord>,

    /// Accumulated output
    pub output: String,

    /// Model being used
    pub model: String,

    /// Provider
    pub provider: String,

    /// Creation timestamp
    pub created_at: DateTime<Utc>,

    /// Last activity timestamp
    pub last_active: DateTime<Utc>,
}

impl SubAgent {
    /// Create a new sub-agent for a subtask
    pub fn new(
        name: impl Into<String>,
        specialty: impl Into<String>,
        subtask_id: impl Into<String>,
        model: impl Into<String>,
        provider: impl Into<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            specialty: specialty.into(),
            subtask_id: subtask_id.into(),
            status: SubAgentStatus::Initializing,
            steps: 0,
            tool_calls: Vec::new(),
            output: String::new(),
            model: model.into(),
            provider: provider.into(),
            created_at: now,
            last_active: now,
        }
    }

    /// Record a tool call
    pub fn record_tool_call(&mut self, name: &str, success: bool) {
        self.tool_calls.push(ToolCallRecord {
            name: name.to_string(),
            timestamp: Utc::now(),
            success,
        });
        self.steps += 1;
        self.last_active = Utc::now();
    }

    /// Append to output
    pub fn append_output(&mut self, text: &str) {
        self.output.push_str(text);
        self.last_active = Utc::now();
    }

    /// Set status
    pub fn set_status(&mut self, status: SubAgentStatus) {
        self.status = status;
        self.last_active = Utc::now();
    }
}

/// Status of a sub-agent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubAgentStatus {
    /// Being initialized
    Initializing,

    /// Actively working
    Working,

    /// Waiting for resource/dependency
    Waiting,

    /// Successfully completed
    Completed,

    /// Failed
    Failed,

    /// Terminated by orchestrator
    Terminated,
}

/// Record of a tool call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallRecord {
    pub name: String,
    pub timestamp: DateTime<Utc>,
    pub success: bool,
}

/// Determine whether an error message represents a transient failure that
/// is safe to retry (network issues, rate limiting, timeouts).
///
/// Returns `true` if the error is likely transient and a retry may succeed.
pub fn is_transient_error(error: &str) -> bool {
    let lower = error.to_ascii_lowercase();
    // Rate limiting
    if lower.contains("rate limit")
        || lower.contains("ratelimit")
        || lower.contains("too many requests")
        || lower.contains("429")
    {
        return true;
    }
    // Timeout / connection issues
    if lower.contains("timeout")
        || lower.contains("timed out")
        || lower.contains("connection reset")
        || lower.contains("connection refused")
        || lower.contains("broken pipe")
        || lower.contains("network")
        || lower.contains("socket")
        || lower.contains("io error")
    {
        return true;
    }
    // Transient server errors
    if lower.contains("503")
        || lower.contains("502")
        || lower.contains("504")
        || lower.contains("service unavailable")
        || lower.contains("bad gateway")
        || lower.contains("gateway timeout")
        || lower.contains("overloaded")
        || lower.contains("temporarily unavailable")
    {
        return true;
    }
    false
}

/// Result of a subtask execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubTaskResult {
    /// Subtask ID
    pub subtask_id: String,

    /// Sub-agent ID that executed it
    pub subagent_id: String,

    /// Whether it succeeded
    pub success: bool,

    /// Result text
    pub result: String,

    /// Number of steps taken
    pub steps: usize,

    /// Tool calls made
    pub tool_calls: usize,

    /// Execution time (milliseconds)
    pub execution_time_ms: u64,

    /// Any error message
    pub error: Option<String>,

    /// Artifacts produced
    pub artifacts: Vec<String>,

    /// Number of retry attempts before this result was produced
    #[serde(default)]
    pub retry_count: u32,
}