apollo-agent 0.7.1

Local-first Rust AI agent runtime — Telegram-first, trait-driven, SurrealDB + RocksDB state layer.
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
//! Dynamic tool system — AI can create, list, and execute custom tools at runtime.
//!
//! Tools are stored in ~/.apollo/tools/<name>/
//!   spec.json  — tool definition (name, description, parameters)
//!   run.v      — V language implementation (preferred, fast compile)
//!   run.py     — Python fallback
//!   run.sh     — Shell fallback
//!
//! The AI uses `create_tool` to write new tools, which are immediately available.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use super::traits::*;
use crate::config::PolicyConfig;
use crate::policy::ExecutionPolicy;
use crate::text::truncate_chars_counted;

/// Directory where dynamic tools live
fn tools_dir() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
    PathBuf::from(home).join(".apollo/tools")
}

/// A dynamic tool loaded from disk
pub struct DynamicTool {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,
    pub tool_dir: PathBuf,
    pub language: String, // "v", "python", "shell"
    policy: Arc<ExecutionPolicy>,
}

#[derive(Serialize, Deserialize)]
struct DynamicToolSpec {
    name: String,
    description: String,
    parameters: serde_json::Value,
    language: Option<String>,
}

impl DynamicTool {
    /// Load a dynamic tool from its directory
    pub fn load(dir: &Path, policy: Arc<ExecutionPolicy>) -> Option<Self> {
        let spec_path = dir.join("spec.json");
        let spec_str = std::fs::read_to_string(&spec_path).ok()?;
        let spec: DynamicToolSpec = serde_json::from_str(&spec_str).ok()?;

        // Determine language from what exists
        let language = if dir.join("run.v").exists() {
            "v".to_string()
        } else if dir.join("run.py").exists() {
            "python".to_string()
        } else if dir.join("run.sh").exists() {
            "shell".to_string()
        } else {
            return None;
        };

        Some(Self {
            name: spec.name,
            description: spec.description,
            parameters: spec.parameters,
            tool_dir: dir.to_path_buf(),
            language,
            policy,
        })
    }

    /// Load all dynamic tools from the tools directory
    pub fn load_all(policy: Arc<ExecutionPolicy>) -> Vec<Self> {
        let dir = tools_dir();
        if !dir.exists() {
            return Vec::new();
        }

        let mut tools = Vec::new();
        if let Ok(entries) = std::fs::read_dir(&dir) {
            for entry in entries.flatten() {
                if entry.path().is_dir() {
                    if let Some(tool) = Self::load(&entry.path(), Arc::clone(&policy)) {
                        tools.push(tool);
                    }
                }
            }
        }
        tools
    }
}

#[async_trait]
impl Tool for DynamicTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: self.name.clone(),
            description: self.description.clone(),
            parameters: self.parameters.clone(),
        }
    }

    async fn execute(&self, arguments: &str) -> anyhow::Result<ToolResult> {
        if !self.policy.allow_dynamic_tools {
            return ExecutionPolicy::deny("Dynamic tool execution is disabled by policy");
        }

        let run_file = match self.language.as_str() {
            "v" => "run.v",
            "python" => "run.py",
            "shell" => "run.sh",
            _ => return Ok(ToolResult::error("Unknown tool language")),
        };

        let run_path = self.tool_dir.join(run_file);

        // `--` keeps a path that starts with `-` from being parsed as a flag
        // (Jules #71). Arguments stay on argv, not through a shell.
        let (program, extra) = match self.language.as_str() {
            "v" => ("v", dynamic_tool_argv("v", &run_path, arguments)),
            "python" => ("python3", dynamic_tool_argv("python", &run_path, arguments)),
            "shell" => ("bash", dynamic_tool_argv("shell", &run_path, arguments)),
            _ => return Ok(ToolResult::error("Unknown language")),
        };
        let extra = extra.ok_or_else(|| anyhow::anyhow!("Unknown language"))?;
        let mut cmd = tokio::process::Command::new(program);
        cmd.args(extra)
            .current_dir(&self.tool_dir)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);
        crate::tools::child_proc::scrub(&mut cmd);
        let output = cmd.output().await?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        let result = if stdout.is_empty() && !stderr.is_empty() {
            stderr
        } else if !stderr.is_empty() {
            format!("{}\n{}", stdout, stderr)
        } else {
            stdout
        };

        // Truncate
        let truncated = match truncate_chars_counted(&result, 20_000) {
            Some((head, dropped)) => format!("{}...\n[truncated {} chars]", head, dropped),
            None => result,
        };

        Ok(if output.status.success() {
            ToolResult::success(truncated)
        } else {
            ToolResult::error(format!(
                "Exit {}: {}",
                output.status.code().unwrap_or(-1),
                truncated
            ))
        })
    }
}

// ============================================================
// create_tool — meta-tool for the AI to create new tools
// ============================================================

pub struct CreateToolTool {
    policy: Arc<ExecutionPolicy>,
}

impl CreateToolTool {
    pub fn new(policy: Arc<ExecutionPolicy>) -> Self {
        Self { policy }
    }
}

#[derive(Deserialize)]
struct CreateToolArgs {
    /// Tool name (lowercase, no spaces)
    name: String,
    /// Tool description
    description: String,
    /// JSON Schema for parameters
    parameters: serde_json::Value,
    /// Source code for the tool
    code: String,
    /// Language: "v" (default), "python", "shell"
    language: Option<String>,
}

#[async_trait]
impl Tool for CreateToolTool {
    fn name(&self) -> &str {
        "create_tool"
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "create_tool".to_string(),
            description: "Create a new custom tool. The tool becomes immediately available. Write the implementation in V (preferred), Python, or shell. The code receives arguments as a JSON string via argv[1] (V/Python) or $1 (shell).".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Tool name (lowercase, alphanumeric + underscores)"
                    },
                    "description": {
                        "type": "string",
                        "description": "What the tool does"
                    },
                    "parameters": {
                        "type": "object",
                        "description": "JSON Schema for the tool's input parameters"
                    },
                    "code": {
                        "type": "string",
                        "description": "Source code for the tool implementation"
                    },
                    "language": {
                        "type": "string",
                        "enum": ["v", "python", "shell"],
                        "description": "Implementation language (default: v)"
                    }
                },
                "required": ["name", "description", "parameters", "code"]
            }),
        }
    }

    async fn execute(&self, arguments: &str) -> anyhow::Result<ToolResult> {
        if !self.policy.allow_dynamic_tools {
            return ExecutionPolicy::deny("Dynamic tool creation is disabled by policy");
        }

        let args: CreateToolArgs = serde_json::from_str(arguments)?;

        // Validate name
        if !args.name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return Ok(ToolResult::error(
                "Tool name must be alphanumeric + underscores only",
            ));
        }

        let language = args.language.unwrap_or_else(|| "v".to_string());
        let tool_dir = tools_dir().join(&args.name);

        // Create directory
        std::fs::create_dir_all(&tool_dir)?;

        // Write spec.json
        let spec = DynamicToolSpec {
            name: args.name.clone(),
            description: args.description.clone(),
            parameters: args.parameters,
            language: Some(language.clone()),
        };
        std::fs::write(
            tool_dir.join("spec.json"),
            serde_json::to_string_pretty(&spec)?,
        )?;

        // Write implementation
        let filename = match language.as_str() {
            "v" => "run.v",
            "python" => "run.py",
            "shell" => "run.sh",
            _ => {
                return Ok(ToolResult::error(
                    "Unsupported language. Use: v, python, shell",
                ))
            }
        };

        std::fs::write(tool_dir.join(filename), &args.code)?;

        // Make shell scripts executable
        if language == "shell" {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let perms = std::fs::Permissions::from_mode(0o755);
                std::fs::set_permissions(tool_dir.join(filename), perms)?;
            }
        }

        // Verify the tool can be loaded
        match DynamicTool::load(&tool_dir, Arc::clone(&self.policy)) {
            Some(t) => Ok(ToolResult::success(format!(
                "✅ Tool '{}' created successfully!\n\
                Language: {}\n\
                Location: {}\n\
                Parameters: {}\n\n\
                Note: The tool is saved but requires a bot restart to be available in the current session. \
                It will be auto-loaded on next startup.",
                t.name, language, tool_dir.display(), serde_json::to_string_pretty(&t.parameters)?
            ))),
            None => Ok(ToolResult::error(format!(
                "Tool created but failed to load. Check {} in {}",
                filename,
                tool_dir.display()
            ))),
        }
    }
}

// ============================================================
// list_custom_tools — see what tools have been created
// ============================================================

pub struct ListCustomToolsTool;

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

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

#[async_trait]
impl Tool for ListCustomToolsTool {
    fn name(&self) -> &str {
        "list_custom_tools"
    }

    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "list_custom_tools".to_string(),
            description: "List all custom tools created by the AI.".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {}
            }),
        }
    }

    async fn execute(&self, _arguments: &str) -> anyhow::Result<ToolResult> {
        let tools = DynamicTool::load_all(Arc::new(ExecutionPolicy::from_config(
            &PolicyConfig::default(),
        )));
        if tools.is_empty() {
            return Ok(ToolResult::success(
                "No custom tools created yet.\n\
                Use create_tool to make one!\n\n\
                Example: create a V tool that fetches weather, a Python data processor, etc.",
            ));
        }

        let mut output = format!("Custom tools ({}):\n\n", tools.len());
        for t in &tools {
            output.push_str(&format!(
                "{} ({}) — {}\n  Location: {}\n",
                t.name,
                t.language,
                t.description,
                t.tool_dir.display()
            ));
        }
        Ok(ToolResult::success(output))
    }
}

/// argv for executing a dynamic tool, including `--` so a leading `-` in the
/// script path cannot be parsed as a flag.
pub(crate) fn dynamic_tool_argv(
    language: &str,
    run_path: &std::path::Path,
    arguments: &str,
) -> Option<Vec<std::ffi::OsString>> {
    match language {
        "v" => Some(vec![
            std::ffi::OsString::from("run"),
            run_path.as_os_str().to_os_string(),
            std::ffi::OsString::from(arguments),
        ]),
        "python" | "shell" => Some(vec![
            std::ffi::OsString::from("--"),
            run_path.as_os_str().to_os_string(),
            std::ffi::OsString::from(arguments),
        ]),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn shell_and_python_insert_end_of_options_before_script() {
        let path = Path::new("-c");
        let args = dynamic_tool_argv("shell", path, r#"{"x":1}"#).unwrap();
        assert_eq!(args[0], "--");
        assert_eq!(args[1], path.as_os_str());
        assert_eq!(args[2], r#"{"x":1}"#);

        let args = dynamic_tool_argv("python", path, "{}").unwrap();
        assert_eq!(args[0], "--");
        assert_eq!(args[1], path.as_os_str());
    }

    #[test]
    fn v_does_not_insert_end_of_options_after_run() {
        let path = Path::new("run.v");
        let args = dynamic_tool_argv("v", path, "{}").unwrap();
        assert_eq!(args[0], "run");
        assert_eq!(args[1], path.as_os_str());
        assert_ne!(args[1], "--");
    }
}