runagent 0.1.49

RunAgent SDK for Rust - Client SDK for interacting with deployed AI agents
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! REST client for HTTP API interactions

use crate::types::{RunAgentError, RunAgentResult};
use crate::utils::config::Config;
use reqwest::{Client, Method, Response};
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;
use url::Url;

/// REST client for API interactions
pub struct RestClient {
    client: Client,
    base_url: String,
    api_key: Option<String>,
    api_prefix: String,
}

impl RestClient {
    /// Create a new REST client with custom configuration
    pub fn new(
        base_url: &str,
        api_key: Option<String>,
        api_prefix: Option<&str>,
    ) -> RunAgentResult<Self> {
        // Increase timeout to 10 minutes (600 seconds) to match agent execution timeout
        let client = Client::builder()
            .timeout(Duration::from_secs(600))
            .user_agent("RunAgent-Rust-SDK/0.1.0")
            .build()?;

        let base_url = base_url.trim_end_matches('/').to_string();
        let api_prefix = api_prefix.unwrap_or("/api/v1").to_string();

        Ok(Self {
            client,
            base_url,
            api_key,
            api_prefix,
        })
    }

    /// Create a default REST client using configuration
    #[allow(clippy::should_implement_trait)]
    pub fn default() -> RunAgentResult<Self> {
        let config = Config::load()?;
        Self::new(&config.base_url(), config.api_key(), Some("/api/v1"))
    }

    fn get_url(&self, path: &str) -> RunAgentResult<Url> {
        let path = path.strip_prefix('/').unwrap_or(path);
        let full_path = format!("{}{}/{}", self.base_url, self.api_prefix, path);
        Url::parse(&full_path).map_err(|e| RunAgentError::validation(format!("Invalid URL: {}", e)))
    }

    async fn handle_response(&self, response: Response) -> RunAgentResult<Value> {
        let status = response.status();

        if status.is_success() {
            let json: Value = response.json().await?;
            Ok(json)
        } else {
            let error_text = response.text().await?;
            let error_msg = if error_text.is_empty() {
                format!("HTTP Error: {}", status)
            } else {
                // Try to parse as JSON to get error details
                if let Ok(json) = serde_json::from_str::<Value>(&error_text) {
                    // Try to extract nested error message
                    if let Some(error_obj) = json.get("error") {
                        if let Some(message) = error_obj.get("message").and_then(|m| m.as_str()) {
                            message.to_string()
                        } else if let Some(detail) = json.get("detail").and_then(|d| d.as_str()) {
                            detail.to_string()
                        } else if let Some(message) = json.get("message").and_then(|m| m.as_str()) {
                            message.to_string()
                        } else if let Some(error) = json.get("error").and_then(|e| e.as_str()) {
                            error.to_string()
                        } else {
                            error_text
                        }
                    } else if let Some(detail) = json.get("detail").and_then(|d| d.as_str()) {
                        detail.to_string()
                    } else if let Some(message) = json.get("message").and_then(|m| m.as_str()) {
                        message.to_string()
                    } else if let Some(error) = json.get("error").and_then(|e| e.as_str()) {
                        error.to_string()
                    } else {
                        error_text
                    }
                } else {
                    error_text
                }
            };

            // Check if error message contains permission/403 info even if status is 500
            if error_msg.contains("permission")
                || error_msg.contains("403")
                || error_msg.contains("do not have permission")
            {
                return Err(RunAgentError::authentication(format!(
                    "Access denied: {}. This usually means:\n  - The agent doesn't belong to your account\n  - Your API key doesn't have permission to access this agent\n  - The agent ID is incorrect", error_msg
                )));
            }

            match status.as_u16() {
                401 => Err(RunAgentError::authentication(error_msg)),
                403 => Err(RunAgentError::authentication(format!(
                    "Access denied: {}. This usually means:\n  - The agent doesn't belong to your account\n  - Your API key doesn't have permission to access this agent\n  - The agent ID is incorrect", error_msg
                ))),
                400 | 422 => Err(RunAgentError::validation(error_msg)),
                404 => Err(RunAgentError::validation(format!("Not found: {}", error_msg))),
                500..=599 => Err(RunAgentError::server(format!("Server error: {}", error_msg))),
                _ => Err(RunAgentError::connection(error_msg)),
            }
        }
    }

    async fn request(
        &self,
        method: Method,
        path: &str,
        data: Option<&Value>,
        params: Option<&HashMap<String, String>>,
    ) -> RunAgentResult<Value> {
        let mut url = self.get_url(path)?;

        // Add API key as token query parameter if available (matching WebSocket behavior)
        if let Some(ref api_key) = self.api_key {
            url.query_pairs_mut().append_pair("token", api_key);
        }

        let mut request_builder = self.client.request(method, url);

        // Add query parameters
        if let Some(params) = params {
            request_builder = request_builder.query(params);
        }

        // Add JSON body for POST/PUT requests
        if let Some(data) = data {
            request_builder = request_builder
                .header("Content-Type", "application/json")
                .json(data);
        }

        // Add Authorization header if API key is available
        if let Some(ref api_key) = self.api_key {
            request_builder =
                request_builder.header("Authorization", format!("Bearer {}", api_key));
        }

        let response = request_builder.send().await?;
        self.handle_response(response).await
    }

    /// Send a GET request
    pub async fn get(&self, path: &str) -> RunAgentResult<Value> {
        self.get_with_params(path, None).await
    }

    /// Send a GET request with query parameters
    pub async fn get_with_params(
        &self,
        path: &str,
        params: Option<&HashMap<String, String>>,
    ) -> RunAgentResult<Value> {
        self.request(Method::GET, path, None, params).await
    }

    /// Send a POST request
    pub async fn post(&self, path: &str, data: &Value) -> RunAgentResult<Value> {
        self.request(Method::POST, path, Some(data), None).await
    }

    /// Send a PUT request
    pub async fn put(&self, path: &str, data: &Value) -> RunAgentResult<Value> {
        self.request(Method::PUT, path, Some(data), None).await
    }

    /// Send a DELETE request
    pub async fn delete(&self, path: &str) -> RunAgentResult<Value> {
        self.request(Method::DELETE, path, None, None).await
    }

    /// Run an agent via REST API
    pub async fn run_agent(
        &self,
        agent_id: &str,
        entrypoint_tag: &str,
        input_args: &[Value],
        input_kwargs: &HashMap<String, Value>,
        user_id: Option<&str>,
        persistent_memory: bool,
    ) -> RunAgentResult<Value> {
        let mut data = serde_json::json!({
            "id": "run_start",
            "entrypoint_tag": entrypoint_tag,
            "input_args": input_args,
            "input_kwargs": input_kwargs,
            "timeout_seconds": 600,
            "async_execution": false
        });

        // Add persistent storage parameters if provided (matches Python SDK)
        if let Some(uid) = user_id {
            if let Some(obj) = data.as_object_mut() {
                obj.insert("user_id".to_string(), serde_json::json!(uid));
            }
        }
        if persistent_memory {
            if let Some(obj) = data.as_object_mut() {
                obj.insert(
                    "persistent_memory".to_string(),
                    serde_json::json!(persistent_memory),
                );
            }
        }

        let path = format!("agents/{}/run", agent_id);
        let url = self.get_url(&path)?;
        tracing::debug!(
            "Running agent {} with entrypoint {} at {}",
            agent_id,
            entrypoint_tag,
            url
        );

        self.post(&path, &data).await
            .map_err(|e| {
                if e.category() == "validation" && e.to_string().contains("Not found") {
                    RunAgentError::validation(format!(
                        "Agent {} not found on server at {}. Check that:\n  - The agent exists and is deployed\n  - The agent ID is correct\n  - The base URL ({}) is correct\n  - Your API key is valid (if required)",
                        agent_id, url, self.base_url
                    ))
                } else {
                    e
                }
            })
    }

    /// Get agent architecture information
    pub async fn get_agent_architecture(&self, agent_id: &str) -> RunAgentResult<Value> {
        let path = format!("agents/{}/architecture", agent_id);
        let url = self.get_url(&path)?;
        tracing::debug!("Fetching agent architecture for {} at {}", agent_id, url);
        let response = self.get(&path).await
            .map_err(|e| {
                if e.category() == "validation" && e.to_string().contains("Not found") {
                    RunAgentError::validation(format!(
                        "Agent {} not found at {}. Check that:\n  - The agent ID is correct\n  - The agent exists and is deployed\n  - Your API key has access to this agent\n  - The base URL ({}) is correct",
                        agent_id, url, self.base_url
                    ))
                } else {
                    e
                }
            })?;

        if let Some(success) = response.get("success").and_then(|v| v.as_bool()) {
            if success {
                if let Some(data) = response.get("data") {
                    return Ok(data.clone());
                }
                return Err(RunAgentError::execution(
                    "ARCHITECTURE_MISSING",
                    "Architecture response missing data",
                    Some("Redeploy the agent or ensure entrypoints are configured.".to_string()),
                    Some(response),
                ));
            }

            let (code, message, suggestion) = if let Some(error_obj) = response.get("error") {
                if let Some(obj) = error_obj.as_object() {
                    (
                        obj.get("code")
                            .and_then(|c| c.as_str())
                            .unwrap_or("UNKNOWN_ERROR")
                            .to_string(),
                        obj.get("message")
                            .and_then(|m| m.as_str())
                            .unwrap_or("Failed to retrieve agent architecture")
                            .to_string(),
                        obj.get("suggestion")
                            .and_then(|s| s.as_str())
                            .map(|s| s.to_string()),
                    )
                } else if let Some(msg) = error_obj.as_str() {
                    ("UNKNOWN_ERROR".to_string(), msg.to_string(), None)
                } else {
                    (
                        "UNKNOWN_ERROR".to_string(),
                        "Failed to retrieve agent architecture".to_string(),
                        None,
                    )
                }
            } else {
                (
                    "UNKNOWN_ERROR".to_string(),
                    response
                        .get("message")
                        .and_then(|m| m.as_str())
                        .unwrap_or("Failed to retrieve agent architecture")
                        .to_string(),
                    None,
                )
            };

            return Err(RunAgentError::execution(
                code,
                message,
                suggestion,
                Some(response),
            ));
        }

        Ok(response)
    }

    /// Health check
    pub async fn health_check(&self) -> RunAgentResult<Value> {
        self.get("health").await
    }

    /// Validate API connection
    pub async fn validate_api_connection(&self) -> RunAgentResult<Value> {
        match self.health_check().await {
            Ok(_response) => {
                let mut result = serde_json::json!({
                    "success": true,
                    "api_connected": true,
                    "base_url": self.base_url
                });

                if self.api_key.is_some() {
                    // Test authentication if API key is provided
                    match self.get_local_db_limits().await {
                        Ok(limits_result) => {
                            result["api_authenticated"] = limits_result
                                .get("api_validated")
                                .unwrap_or(&Value::Bool(false))
                                .clone();
                            result["enhanced_limits"] = limits_result
                                .get("enhanced_limits")
                                .unwrap_or(&Value::Bool(false))
                                .clone();
                        }
                        Err(_) => {
                            result["api_authenticated"] = Value::Bool(false);
                            result["enhanced_limits"] = Value::Bool(false);
                        }
                    }
                } else {
                    result["api_authenticated"] = Value::Bool(false);
                    result["enhanced_limits"] = Value::Bool(false);
                    result["message"] = Value::String("No API key provided".to_string());
                }

                Ok(result)
            }
            Err(e) => Ok(serde_json::json!({
                "success": false,
                "api_connected": false,
                "error": format!("API health check failed: {}", e)
            })),
        }
    }

    /// Get local database limits from backend API
    pub async fn get_local_db_limits(&self) -> RunAgentResult<Value> {
        if self.api_key.is_none() {
            return Ok(serde_json::json!({
                "success": false,
                "error": "No API key provided",
                "default_limit": 5,
                "current_limit": 5,
                "has_api_key": false,
                "enhanced_limits": false
            }));
        }

        tracing::info!("Checking API limits...");

        match self.get("limits/agents").await {
            Ok(response) => {
                let max_agents = response
                    .get("max_agents")
                    .and_then(|v| v.as_i64())
                    .unwrap_or(5);
                let enhanced = max_agents > 5;
                let unlimited = max_agents == -1;

                if enhanced {
                    tracing::info!(
                        "Enhanced limits active: {} agents",
                        if unlimited {
                            "unlimited".to_string()
                        } else {
                            max_agents.to_string()
                        }
                    );
                }

                Ok(serde_json::json!({
                    "success": true,
                    "max_agents": if unlimited { 999 } else { max_agents },
                    "current_limit": if unlimited { 999 } else { max_agents },
                    "default_limit": 5,
                    "has_api_key": true,
                    "enhanced_limits": enhanced,
                    "tier_info": response.get("tier_info").unwrap_or(&Value::Null),
                    "features": response.get("features").unwrap_or(&Value::Array(vec![])),
                    "expires_at": response.get("expires_at").unwrap_or(&Value::Null),
                    "unlimited": unlimited,
                    "api_validated": true
                }))
            }
            Err(e) => {
                let error_msg = if e.category() == "authentication" {
                    "API key invalid or expired - using default limits"
                } else {
                    "API connection failed - using default limits"
                };

                tracing::warn!("{}", error_msg);

                Ok(serde_json::json!({
                    "success": false,
                    "error": format!("{}", e),
                    "default_limit": 5,
                    "current_limit": 5,
                    "has_api_key": true,
                    "enhanced_limits": false,
                    "api_validated": false
                }))
            }
        }
    }

    /// Upload agent to remote server
    pub async fn upload_agent(
        &self,
        folder_path: &str,
        metadata: Option<&HashMap<String, Value>>,
    ) -> RunAgentResult<Value> {
        // This would implement file upload functionality
        // For now, return a placeholder
        let _folder_path = folder_path;
        let _metadata = metadata;

        Err(RunAgentError::generic(
            "Upload functionality not yet implemented",
        ))
    }

    /// Start a remote agent
    pub async fn start_agent(
        &self,
        agent_id: &str,
        config: Option<&HashMap<String, Value>>,
    ) -> RunAgentResult<Value> {
        let data = config.cloned().unwrap_or_default();
        let path = format!("agents/{}/start", agent_id);
        self.post(&path, &serde_json::json!(data)).await
    }

    /// Get agent status
    pub async fn get_agent_status(&self, agent_id: &str) -> RunAgentResult<Value> {
        let path = format!("agents/{}/status", agent_id);
        self.get(&path).await
    }
}

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

    #[test]
    fn test_url_construction() {
        let client = RestClient::new("http://localhost:8000", None, Some("/api/v1")).unwrap();
        let url = client.get_url("agents/test").unwrap();
        assert_eq!(url.as_str(), "http://localhost:8000/api/v1/agents/test");
    }

    #[test]
    fn test_url_construction_with_leading_slash() {
        let client = RestClient::new("http://localhost:8000", None, Some("/api/v1")).unwrap();
        let url = client.get_url("/agents/test").unwrap();
        assert_eq!(url.as_str(), "http://localhost:8000/api/v1/agents/test");
    }

    #[test]
    fn test_client_creation() {
        let client = RestClient::new("http://localhost:8000", None, None);
        assert!(client.is_ok());
    }
}