acton-ai 0.26.0

An agentic AI framework where each agent is an actor
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
//! Web fetch built-in tool.
//!
//! Fetches content from URLs.

use crate::messages::ToolDefinition;
use crate::tools::actor::{ExecuteToolDirect, ToolActor, ToolActorResponse};
use crate::tools::{ToolConfig, ToolError, ToolExecutionFuture, ToolExecutorTrait};
use acton_reactive::prelude::*;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::time::Duration;
use url::Url;

/// Web fetch tool executor.
///
/// Fetches content from URLs with configurable method and headers.
#[derive(Debug, Clone)]
pub struct WebFetchTool {
    /// HTTP client
    client: reqwest::Client,
    /// Maximum response size in bytes
    max_response_size: usize,
}

/// Web fetch tool actor state.
///
/// This actor wraps the `WebFetchTool` executor for per-agent tool spawning.
#[acton_actor]
pub struct WebFetchToolActor;

impl Default for WebFetchTool {
    fn default() -> Self {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(30))
            .user_agent("acton-ai/0.1")
            .build()
            .expect("failed to create HTTP client");

        Self {
            client,
            max_response_size: 5 * 1024 * 1024, // 5MB
        }
    }
}

/// Arguments for the web_fetch tool.
#[derive(Debug, Deserialize)]
struct WebFetchArgs {
    /// URL to fetch
    url: String,
    /// HTTP method (GET or POST)
    #[serde(default = "default_method")]
    method: String,
    /// Optional HTTP headers
    #[serde(default)]
    headers: Option<HashMap<String, String>>,
    /// Optional request body (for POST)
    #[serde(default)]
    body: Option<String>,
    /// Timeout in seconds (default: 30)
    #[serde(default)]
    timeout: Option<u64>,
}

fn default_method() -> String {
    "GET".to_string()
}

impl WebFetchTool {
    /// Creates a new web fetch tool.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a web fetch tool with custom settings.
    #[must_use]
    pub fn with_config(timeout: Duration, max_response_size: usize) -> Self {
        let client = reqwest::Client::builder()
            .timeout(timeout)
            .user_agent("acton-ai/0.1")
            .build()
            .expect("failed to create HTTP client");

        Self {
            client,
            max_response_size,
        }
    }

    /// Returns the tool configuration for registration.
    #[must_use]
    pub fn config() -> ToolConfig {
        use crate::messages::ToolDefinition;

        ToolConfig::new(ToolDefinition {
            name: "web_fetch".to_string(),
            description:
                "Fetch content from a URL. Supports GET and POST methods with custom headers."
                    .to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "url": {
                        "type": "string",
                        "description": "URL to fetch (must be http or https)"
                    },
                    "method": {
                        "type": "string",
                        "enum": ["GET", "POST"],
                        "description": "HTTP method (default: GET)"
                    },
                    "headers": {
                        "type": "object",
                        "description": "Optional HTTP headers",
                        "additionalProperties": {
                            "type": "string"
                        }
                    },
                    "body": {
                        "type": "string",
                        "description": "Optional request body (for POST requests)"
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Timeout in seconds (default: 30, max: 120)",
                        "minimum": 1,
                        "maximum": 120
                    }
                },
                "required": ["url"]
            }),
        })
    }

    /// Validates and normalizes the URL.
    fn validate_url(url: &str) -> Result<String, ToolError> {
        // Parse the URL
        let parsed = Url::parse(url)
            .map_err(|e| ToolError::validation_failed("web_fetch", format!("invalid URL: {e}")))?;

        // Only allow http and https
        match parsed.scheme() {
            "http" | "https" => {}
            scheme => {
                return Err(ToolError::validation_failed(
                    "web_fetch",
                    format!("unsupported URL scheme: {scheme}; only http and https are allowed"),
                ));
            }
        }

        // Block localhost and private IPs for security
        if let Some(host) = parsed.host_str() {
            let is_local = host == "localhost"
                || host == "127.0.0.1"
                || host == "::1"
                || host.starts_with("192.168.")
                || host.starts_with("10.")
                || host.starts_with("172.16.")
                || host.starts_with("172.17.")
                || host.starts_with("172.18.")
                || host.starts_with("172.19.")
                || host.starts_with("172.2")
                || host.starts_with("172.30.")
                || host.starts_with("172.31.");

            if is_local {
                return Err(ToolError::validation_failed(
                    "web_fetch",
                    "cannot fetch from localhost or private IP addresses",
                ));
            }
        }

        Ok(parsed.to_string())
    }
}

impl ToolExecutorTrait for WebFetchTool {
    fn execute(&self, args: Value) -> ToolExecutionFuture {
        let client = self.client.clone();
        let max_size = self.max_response_size;

        Box::pin(async move {
            let args: WebFetchArgs = serde_json::from_value(args).map_err(|e| {
                ToolError::validation_failed("web_fetch", format!("invalid arguments: {e}"))
            })?;

            // Validate empty URL early
            if args.url.is_empty() {
                return Err(ToolError::validation_failed(
                    "web_fetch",
                    "url cannot be empty",
                ));
            }

            // Validate URL
            let url = Self::validate_url(&args.url)?;

            // Build request
            let method = args.method.to_uppercase();
            let mut request = match method.as_str() {
                "GET" => client.get(&url),
                "POST" => client.post(&url),
                _ => {
                    return Err(ToolError::validation_failed(
                        "web_fetch",
                        format!("unsupported method: {method}; use GET or POST"),
                    ));
                }
            };

            // Add custom headers
            if let Some(headers) = args.headers {
                let mut header_map = HeaderMap::new();
                for (key, value) in headers {
                    let name = HeaderName::try_from(key.as_str()).map_err(|e| {
                        ToolError::validation_failed(
                            "web_fetch",
                            format!("invalid header name: {e}"),
                        )
                    })?;
                    let val = HeaderValue::try_from(value.as_str()).map_err(|e| {
                        ToolError::validation_failed(
                            "web_fetch",
                            format!("invalid header value: {e}"),
                        )
                    })?;
                    header_map.insert(name, val);
                }
                request = request.headers(header_map);
            }

            // Add body for POST
            if let Some(body) = args.body {
                if method == "POST" {
                    request = request.body(body);
                }
            }

            // Set timeout
            if let Some(timeout_secs) = args.timeout {
                let timeout = Duration::from_secs(timeout_secs.min(120));
                request = request.timeout(timeout);
            }

            // Execute request
            let response = request.send().await.map_err(|e| {
                if e.is_timeout() {
                    ToolError::timeout("web_fetch", Duration::from_secs(args.timeout.unwrap_or(30)))
                } else if e.is_connect() {
                    ToolError::execution_failed("web_fetch", format!("connection failed: {e}"))
                } else {
                    ToolError::execution_failed("web_fetch", format!("request failed: {e}"))
                }
            })?;

            let status = response.status();
            let status_code = status.as_u16();
            let headers: HashMap<String, String> = response
                .headers()
                .iter()
                .filter_map(|(k, v)| {
                    v.to_str()
                        .ok()
                        .map(|s| (k.as_str().to_string(), s.to_string()))
                })
                .collect();

            // Get content type
            let content_type = headers
                .get("content-type")
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());

            // Read body with size limit
            let bytes = response.bytes().await.map_err(|e| {
                ToolError::execution_failed("web_fetch", format!("failed to read response: {e}"))
            })?;

            let (body, truncated) = if bytes.len() > max_size {
                (
                    String::from_utf8_lossy(&bytes[..max_size]).to_string(),
                    true,
                )
            } else {
                (String::from_utf8_lossy(&bytes).to_string(), false)
            };

            Ok(json!({
                "status_code": status_code,
                "success": status.is_success(),
                "content_type": content_type,
                "body": body,
                "body_length": bytes.len(),
                "truncated": truncated,
                "headers": headers
            }))
        })
    }

    fn validate_args(&self, args: &Value) -> Result<(), ToolError> {
        let args: WebFetchArgs = serde_json::from_value(args.clone()).map_err(|e| {
            ToolError::validation_failed("web_fetch", format!("invalid arguments: {e}"))
        })?;

        if args.url.is_empty() {
            return Err(ToolError::validation_failed(
                "web_fetch",
                "url cannot be empty",
            ));
        }

        // Validate URL format
        Self::validate_url(&args.url)?;

        Ok(())
    }
}

impl ToolActor for WebFetchToolActor {
    fn name() -> &'static str {
        "web_fetch"
    }

    fn definition() -> ToolDefinition {
        WebFetchTool::config().definition
    }

    async fn spawn(runtime: &mut ActorRuntime) -> ActorHandle {
        let mut builder = runtime.new_actor_with_name::<Self>("web_fetch_tool".to_string());

        builder.act_on::<ExecuteToolDirect>(|actor, envelope| {
            let msg = envelope.message();
            let correlation_id = msg.correlation_id.clone();
            let tool_call_id = msg.tool_call_id.clone();
            let args = msg.args.clone();
            let broker = actor.broker().clone();

            Reply::pending(async move {
                let tool = WebFetchTool::new();
                let result = tool.execute(args).await;

                let response = match result {
                    Ok(value) => {
                        let result_str = serde_json::to_string(&value)
                            .unwrap_or_else(|e| format!("{{\"error\": \"{}\"}}", e));
                        ToolActorResponse::success(correlation_id, tool_call_id, result_str)
                    }
                    Err(e) => ToolActorResponse::error(correlation_id, tool_call_id, e.to_string()),
                };

                broker.broadcast(response).await;
            })
        });

        builder.start().await
    }
}

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

    #[test]
    fn validate_url_accepts_https() {
        let result = WebFetchTool::validate_url("https://example.com/path");
        assert!(result.is_ok());
    }

    #[test]
    fn validate_url_accepts_http() {
        let result = WebFetchTool::validate_url("http://example.com/path");
        assert!(result.is_ok());
    }

    #[test]
    fn validate_url_rejects_ftp() {
        let result = WebFetchTool::validate_url("ftp://example.com/file");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unsupported"));
    }

    #[test]
    fn validate_url_rejects_localhost() {
        let result = WebFetchTool::validate_url("http://localhost/api");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("localhost"));
    }

    #[test]
    fn validate_url_rejects_private_ip() {
        let result = WebFetchTool::validate_url("http://192.168.1.1/api");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("private"));

        let result = WebFetchTool::validate_url("http://10.0.0.1/api");
        assert!(result.is_err());
    }

    #[test]
    fn validate_url_rejects_invalid() {
        let result = WebFetchTool::validate_url("not a url");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("invalid"));
    }

    #[tokio::test]
    async fn web_fetch_empty_url_rejected() {
        let tool = WebFetchTool::new();
        let result = tool.execute(json!({"url": ""})).await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));
    }

    #[tokio::test]
    async fn web_fetch_invalid_method_rejected() {
        let tool = WebFetchTool::new();
        let result = tool
            .execute(json!({
                "url": "https://example.com",
                "method": "DELETE"
            }))
            .await;

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("unsupported method"));
    }

    #[test]
    fn config_has_correct_schema() {
        let config = WebFetchTool::config();
        assert_eq!(config.definition.name, "web_fetch");
        assert!(config.definition.description.contains("Fetch"));

        let schema = &config.definition.input_schema;
        assert!(schema["properties"]["url"].is_object());
        assert!(schema["properties"]["method"].is_object());
        assert!(schema["properties"]["headers"].is_object());
        assert!(schema["properties"]["body"].is_object());
        assert!(schema["properties"]["timeout"].is_object());
    }

    #[test]
    fn default_method_is_get() {
        assert_eq!(default_method(), "GET");
    }
}