codetether-agent 4.5.7

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
//! Tool system
//!
//! Tools are the executable capabilities available to agents.

pub mod advanced_edit;
pub mod agent;
pub mod avatar;
pub mod bash;
#[path = "bash_github/mod.rs"]
mod bash_github;
mod bash_identity;
mod bash_shell;
pub mod batch;
pub mod browserctl;
pub mod codesearch;
pub mod confirm_edit;
pub mod confirm_multiedit;
pub mod edit;
pub mod file;
pub mod file_extras;
pub mod go;
pub mod image;
pub mod invalid;
pub mod k8s_tool;
pub mod lsp;
pub mod mcp_bridge;
pub mod mcp_tools;
pub mod memory;
pub mod morph_backend;
pub mod multiedit;
pub mod okr;
pub mod patch;
pub mod plan;
pub mod podcast;
pub mod prd;
pub mod question;
pub mod ralph;
pub mod readonly;
pub mod relay_autochat;
pub mod rlm;
pub mod sandbox;
pub mod search;
pub mod skill;
pub mod swarm_execute;
pub mod swarm_share;
pub mod task;
pub mod todo;
pub mod undo;
pub mod voice;
pub mod webfetch;
pub mod websearch;
pub mod youtube;

use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

use crate::provider::Provider;
pub use mcp_tools::{McpToolManager, McpToolWrapper};
pub use sandbox::{PluginManifest, PluginRegistry, SigningKey, hash_bytes, hash_file};

/// A tool that can be executed by an agent
#[async_trait]
pub trait Tool: Send + Sync {
    /// Tool identifier
    fn id(&self) -> &str;

    /// Human-readable name
    fn name(&self) -> &str;

    /// Description for the LLM
    fn description(&self) -> &str;

    /// JSON Schema for parameters
    fn parameters(&self) -> Value;

    /// Execute the tool with given arguments
    async fn execute(&self, args: Value) -> Result<ToolResult>;
}

/// Result from tool execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    pub output: String,
    pub success: bool,
    #[serde(default)]
    pub metadata: HashMap<String, Value>,
}

impl ToolResult {
    pub fn success(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            success: true,
            metadata: HashMap::new(),
        }
    }

    pub fn error(message: impl Into<String>) -> Self {
        Self {
            output: message.into(),
            success: false,
            metadata: HashMap::new(),
        }
    }

    /// Create a structured error with code, tool name, missing fields, and example
    ///
    /// This helps LLMs self-correct by providing actionable information about what went wrong.
    pub fn structured_error(
        code: &str,
        tool: &str,
        message: &str,
        missing_fields: Option<Vec<&str>>,
        example: Option<Value>,
    ) -> Self {
        let mut error_obj = serde_json::json!({
            "code": code,
            "tool": tool,
            "message": message,
        });

        if let Some(fields) = missing_fields {
            error_obj["missing_fields"] = serde_json::json!(fields);
        }

        if let Some(ex) = example {
            error_obj["example"] = ex;
        }

        let output = serde_json::to_string_pretty(&serde_json::json!({
            "error": error_obj
        }))
        .unwrap_or_else(|_| format!("Error: {}", message));

        let mut metadata = HashMap::new();
        metadata.insert("error_code".to_string(), serde_json::json!(code));
        metadata.insert("tool".to_string(), serde_json::json!(tool));

        Self {
            output,
            success: false,
            metadata,
        }
    }

    pub fn with_metadata(mut self, key: impl Into<String>, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Truncate `output` to at most `max_bytes`, tagging `metadata.truncated`
    /// with the original length when truncation occurs.
    ///
    /// Uses UTF-8-safe truncation. When the output fits, returns `self`
    /// unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use codetether_agent::tool::ToolResult;
    ///
    /// let r = ToolResult::success("x".repeat(1_000)).truncate_to(100);
    /// assert!(r.output.len() <= 100 + 32); // + marker
    /// assert!(r.metadata.contains_key("truncated"));
    /// ```
    pub fn truncate_to(mut self, max_bytes: usize) -> Self {
        if self.output.len() <= max_bytes {
            return self;
        }
        let original_len = self.output.len();
        let head = crate::util::truncate_bytes_safe(&self.output, max_bytes);
        self.output =
            format!("{head}\n…[truncated: {original_len} bytes, showing first {max_bytes}]");
        self.metadata.insert(
            "truncated".to_string(),
            serde_json::json!({
                "original_bytes": original_len,
                "shown_bytes": max_bytes,
            }),
        );
        self
    }
}

/// Default per-tool-output byte budget. Tunable at runtime via the
/// `CODETETHER_TOOL_OUTPUT_MAX_BYTES` environment variable. Chosen to keep a
/// single tool result well under typical provider context windows even after
/// JSON re-encoding overhead.
pub const DEFAULT_TOOL_OUTPUT_MAX_BYTES: usize = 64 * 1024;

/// Resolve the current tool-output byte budget from env, falling back to
/// [`DEFAULT_TOOL_OUTPUT_MAX_BYTES`]. Invalid values fall back to the default.
pub fn tool_output_budget() -> usize {
    std::env::var("CODETETHER_TOOL_OUTPUT_MAX_BYTES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_TOOL_OUTPUT_MAX_BYTES)
}

/// Registry of available tools
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
    plugin_registry: PluginRegistry,
}

impl std::fmt::Debug for ToolRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolRegistry")
            .field("tools", &self.tools.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl ToolRegistry {
    pub fn new() -> Self {
        let _ = std::any::TypeId::of::<McpToolManager>();
        let _ = std::any::TypeId::of::<McpToolWrapper>();
        Self {
            tools: HashMap::new(),
            plugin_registry: PluginRegistry::from_env(),
        }
    }

    /// Get a reference to the plugin registry for managing signed plugins.
    pub fn plugins(&self) -> &PluginRegistry {
        &self.plugin_registry
    }

    /// Register a tool
    pub fn register(&mut self, tool: Arc<dyn Tool>) {
        self.tools.insert(tool.id().to_string(), tool);
    }

    /// Get a tool by ID
    pub fn get(&self, id: &str) -> Option<Arc<dyn Tool>> {
        self.tools.get(id).cloned()
    }

    /// List all tool IDs
    pub fn list(&self) -> Vec<&str> {
        self.tools.keys().map(|s| s.as_str()).collect()
    }

    /// Get tool definitions for LLM
    pub fn definitions(&self) -> Vec<crate::provider::ToolDefinition> {
        self.tools
            .values()
            .map(|t| crate::provider::ToolDefinition {
                name: t.id().to_string(),
                description: t.description().to_string(),
                parameters: t.parameters(),
            })
            .collect()
    }

    /// Register multiple tools at once
    pub fn register_all(&mut self, tools: Vec<Arc<dyn Tool>>) {
        for tool in tools {
            self.register(tool);
        }
    }

    /// Remove a tool by ID
    pub fn unregister(&mut self, id: &str) -> Option<Arc<dyn Tool>> {
        self.tools.remove(id)
    }

    /// Check if a tool exists
    pub fn contains(&self, id: &str) -> bool {
        self.tools.contains_key(id)
    }

    /// Get the number of registered tools
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Create registry with all default tools (without batch)
    pub fn with_defaults() -> Self {
        let mut registry = Self::new();

        registry.register(Arc::new(file::ReadTool::new()));
        registry.register(Arc::new(file::WriteTool::new()));
        registry.register(Arc::new(file::ListTool::new()));
        registry.register(Arc::new(file::GlobTool::new()));
        registry.register(Arc::new(file_extras::TreeTool::new()));
        registry.register(Arc::new(file_extras::FileInfoTool::new()));
        registry.register(Arc::new(file_extras::HeadTailTool::new()));
        registry.register(Arc::new(file_extras::DiffTool::new()));
        registry.register(Arc::new(search::GrepTool::new()));
        registry.register(Arc::new(advanced_edit::AdvancedEditTool::new()));
        registry.register(Arc::new(edit::EditTool::new()));
        registry.register(Arc::new(bash::BashTool::new()));
        registry.register(Arc::new(lsp::LspTool::with_root(
            std::env::current_dir()
                .map(|p| format!("file://{}", p.display()))
                .unwrap_or_default(),
        )));
        registry.register(Arc::new(webfetch::WebFetchTool::new()));
        registry.register(Arc::new(multiedit::MultiEditTool::new()));
        registry.register(Arc::new(websearch::WebSearchTool::new()));
        registry.register(Arc::new(browserctl::BrowserCtlTool::new()));
        registry.register(Arc::new(codesearch::CodeSearchTool::new()));
        registry.register(Arc::new(patch::ApplyPatchTool::new()));
        registry.register(Arc::new(todo::TodoReadTool::new()));
        registry.register(Arc::new(todo::TodoWriteTool::new()));
        registry.register(Arc::new(question::QuestionTool::new()));
        registry.register(Arc::new(task::TaskTool::new()));
        registry.register(Arc::new(plan::PlanEnterTool::new()));
        registry.register(Arc::new(plan::PlanExitTool::new()));
        registry.register(Arc::new(skill::SkillTool::new()));
        registry.register(Arc::new(memory::MemoryTool::new()));
        registry.register(Arc::new(ralph::RalphTool::new()));
        registry.register(Arc::new(prd::PrdTool::new()));
        registry.register(Arc::new(undo::UndoTool));
        registry.register(Arc::new(voice::VoiceTool::new()));
        registry.register(Arc::new(podcast::PodcastTool::new()));
        registry.register(Arc::new(youtube::YouTubeTool::new()));
        registry.register(Arc::new(avatar::AvatarTool::new()));
        registry.register(Arc::new(image::ImageTool::new()));
        registry.register(Arc::new(mcp_bridge::McpBridgeTool::new()));
        registry.register(Arc::new(okr::OkrTool::new()));
        // Edit tools with confirmation (diff display before applying)
        registry.register(Arc::new(confirm_edit::ConfirmEditTool::new()));
        registry.register(Arc::new(confirm_multiedit::ConfirmMultiEditTool::new()));
        // Swarm result sharing between sub-agents
        registry.register(Arc::new(swarm_share::SwarmShareTool::with_defaults()));
        // Register the invalid tool handler for graceful error handling
        registry.register(Arc::new(invalid::InvalidTool::new()));
        // Agent orchestration tool
        registry.register(Arc::new(agent::AgentTool::new()));
        // Swarm execution tool for parallel task execution
        registry.register(Arc::new(swarm_execute::SwarmExecuteTool::new()));
        // Relay autochat tool for autonomous agent communication
        registry.register(Arc::new(relay_autochat::RelayAutoChatTool::new()));
        // Go tool for autonomous OKR→PRD→Ralph pipeline
        registry.register(Arc::new(go::GoTool::new()));
        // Kubernetes management tool
        registry.register(Arc::new(k8s_tool::K8sTool::new()));

        registry
    }

    /// Create registry with provider for tools that need it (like RalphTool)
    pub fn with_provider(provider: Arc<dyn Provider>, model: String) -> Self {
        let mut registry = Self::new();

        registry.register(Arc::new(file::ReadTool::new()));
        registry.register(Arc::new(file::WriteTool::new()));
        registry.register(Arc::new(file::ListTool::new()));
        registry.register(Arc::new(file::GlobTool::new()));
        registry.register(Arc::new(file_extras::TreeTool::new()));
        registry.register(Arc::new(file_extras::FileInfoTool::new()));
        registry.register(Arc::new(file_extras::HeadTailTool::new()));
        registry.register(Arc::new(file_extras::DiffTool::new()));
        registry.register(Arc::new(search::GrepTool::new()));
        registry.register(Arc::new(advanced_edit::AdvancedEditTool::new()));
        registry.register(Arc::new(edit::EditTool::new()));
        registry.register(Arc::new(bash::BashTool::new()));
        registry.register(Arc::new(lsp::LspTool::with_root(
            std::env::current_dir()
                .map(|p| format!("file://{}", p.display()))
                .unwrap_or_default(),
        )));
        registry.register(Arc::new(webfetch::WebFetchTool::new()));
        registry.register(Arc::new(multiedit::MultiEditTool::new()));
        registry.register(Arc::new(websearch::WebSearchTool::new()));
        registry.register(Arc::new(browserctl::BrowserCtlTool::new()));
        registry.register(Arc::new(codesearch::CodeSearchTool::new()));
        registry.register(Arc::new(patch::ApplyPatchTool::new()));
        registry.register(Arc::new(todo::TodoReadTool::new()));
        registry.register(Arc::new(todo::TodoWriteTool::new()));
        registry.register(Arc::new(question::QuestionTool::new()));
        registry.register(Arc::new(task::TaskTool::new()));
        registry.register(Arc::new(plan::PlanEnterTool::new()));
        registry.register(Arc::new(plan::PlanExitTool::new()));
        registry.register(Arc::new(skill::SkillTool::new()));
        registry.register(Arc::new(memory::MemoryTool::new()));
        registry.register(Arc::new(rlm::RlmTool::new(
            Arc::clone(&provider),
            model.clone(),
            crate::rlm::RlmConfig::default(),
        )));
        // RalphTool with provider for autonomous execution
        registry.register(Arc::new(ralph::RalphTool::with_provider(provider, model)));
        registry.register(Arc::new(prd::PrdTool::new()));
        registry.register(Arc::new(undo::UndoTool));
        registry.register(Arc::new(voice::VoiceTool::new()));
        registry.register(Arc::new(podcast::PodcastTool::new()));
        registry.register(Arc::new(youtube::YouTubeTool::new()));
        registry.register(Arc::new(avatar::AvatarTool::new()));
        registry.register(Arc::new(image::ImageTool::new()));
        registry.register(Arc::new(mcp_bridge::McpBridgeTool::new()));
        registry.register(Arc::new(okr::OkrTool::new()));
        // Edit tools with confirmation (diff display before applying)
        registry.register(Arc::new(confirm_edit::ConfirmEditTool::new()));
        registry.register(Arc::new(confirm_multiedit::ConfirmMultiEditTool::new()));
        // Swarm result sharing between sub-agents
        registry.register(Arc::new(swarm_share::SwarmShareTool::with_defaults()));
        // Register the invalid tool handler for graceful error handling
        registry.register(Arc::new(invalid::InvalidTool::new()));
        // Agent orchestration tool
        registry.register(Arc::new(agent::AgentTool::new()));
        // Swarm execution tool for parallel task execution
        registry.register(Arc::new(swarm_execute::SwarmExecuteTool::new()));
        // Relay autochat tool for autonomous agent communication
        registry.register(Arc::new(relay_autochat::RelayAutoChatTool::new()));
        // Go tool for autonomous OKR→PRD→Ralph pipeline
        registry.register(Arc::new(go::GoTool::new()));
        // Kubernetes management tool
        registry.register(Arc::new(k8s_tool::K8sTool::new()));

        registry
    }

    /// Create Arc-wrapped registry with batch tool properly initialized.
    /// The batch tool needs a weak reference to the registry, so we use
    /// a two-phase initialization pattern.
    pub fn with_defaults_arc() -> Arc<Self> {
        let mut registry = Self::with_defaults();

        // Create batch tool without registry reference
        let batch_tool = Arc::new(batch::BatchTool::new());
        registry.register(batch_tool.clone());

        // Wrap registry in Arc
        let registry = Arc::new(registry);

        // Now give batch tool a weak reference to the registry
        batch_tool.set_registry(Arc::downgrade(&registry));

        registry
    }

    /// Create Arc-wrapped registry with provider and batch tool properly initialized.
    /// The batch tool needs a weak reference to the registry, so we use
    /// a two-phase initialization pattern.
    #[allow(dead_code)]
    pub fn with_provider_arc(provider: Arc<dyn Provider>, model: String) -> Arc<Self> {
        let mut registry = Self::with_provider(provider, model);

        // Create batch tool without registry reference
        let batch_tool = Arc::new(batch::BatchTool::new());
        registry.register(batch_tool.clone());

        // Wrap registry in Arc
        let registry = Arc::new(registry);

        // Now give batch tool a weak reference to the registry
        batch_tool.set_registry(Arc::downgrade(&registry));

        registry
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::with_defaults()
    }
}