sayr-engine 0.3.0

A high-performance Rust AI agent runtime inspired by the Agno framework
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
497
498
499
500
//! GitHub toolkit for interacting with GitHub repositories.
//!
//! Provides tools for searching repos, issues, PRs, and reading file contents.

use crate::tool::Tool;
use async_trait::async_trait;
use serde_json::{json, Value};

// ─────────────────────────────────────────────────────────────────────────────
// GitHub Client
// ─────────────────────────────────────────────────────────────────────────────

/// Shared GitHub API client
#[derive(Clone)]
pub struct GitHubClient {
    http: reqwest::Client,
    token: Option<String>,
    base_url: String,
}

impl GitHubClient {
    pub fn new() -> Self {
        Self {
            http: reqwest::Client::new(),
            token: std::env::var("GITHUB_TOKEN").ok(),
            base_url: "https://api.github.com".to_string(),
        }
    }

    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    async fn get(&self, endpoint: &str) -> crate::Result<Value> {
        let mut request = self
            .http
            .get(format!("{}{}", self.base_url, endpoint))
            .header("User-Agent", "sayr-engine/0.3.0")
            .header("Accept", "application/vnd.github.v3+json");

        if let Some(ref token) = self.token {
            request = request.header("Authorization", format!("Bearer {}", token));
        }

        let response = request
            .send()
            .await
            .map_err(|e| crate::error::AgnoError::Protocol(format!("GitHub request failed: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(crate::error::AgnoError::Protocol(format!(
                "GitHub API error {}: {}",
                status, body
            )));
        }

        response
            .json()
            .await
            .map_err(|e| crate::error::AgnoError::Protocol(format!("Failed to parse response: {}", e)))
    }
}

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

// ─────────────────────────────────────────────────────────────────────────────
// Search Repositories Tool
// ─────────────────────────────────────────────────────────────────────────────

/// Tool for searching GitHub repositories
pub struct GitHubSearchReposTool {
    client: GitHubClient,
}

impl GitHubSearchReposTool {
    pub fn new() -> Self {
        Self {
            client: GitHubClient::new(),
        }
    }

    pub fn with_client(client: GitHubClient) -> Self {
        Self { client }
    }
}

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

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

    fn description(&self) -> &str {
        "Search GitHub repositories by query. Returns repository names, descriptions, stars, and URLs."
    }

    fn parameters(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query for repositories"
                },
                "language": {
                    "type": "string",
                    "description": "Filter by programming language"
                },
                "sort": {
                    "type": "string",
                    "enum": ["stars", "forks", "updated"],
                    "description": "Sort by stars, forks, or recently updated"
                }
            },
            "required": ["query"]
        }))
    }

    async fn call(&self, input: Value) -> crate::Result<Value> {
        let query = input["query"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'query' parameter".into()))?;

        let mut search_query = query.to_string();
        
        if let Some(lang) = input["language"].as_str() {
            search_query.push_str(&format!(" language:{}", lang));
        }

        let sort = input["sort"].as_str().unwrap_or("stars");
        
        let endpoint = format!(
            "/search/repositories?q={}&sort={}&per_page=10",
            urlencoding::encode(&search_query),
            sort
        );

        let response = self.client.get(&endpoint).await?;

        let items = response["items"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|repo| {
                        json!({
                            "name": repo["full_name"],
                            "description": repo["description"],
                            "stars": repo["stargazers_count"],
                            "forks": repo["forks_count"],
                            "language": repo["language"],
                            "url": repo["html_url"]
                        })
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        Ok(json!({
            "query": query,
            "total_count": response["total_count"],
            "repositories": items
        }))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Get Repository Tool
// ─────────────────────────────────────────────────────────────────────────────

/// Tool for getting repository details
pub struct GitHubGetRepoTool {
    client: GitHubClient,
}

impl GitHubGetRepoTool {
    pub fn new() -> Self {
        Self {
            client: GitHubClient::new(),
        }
    }

    pub fn with_client(client: GitHubClient) -> Self {
        Self { client }
    }
}

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

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

    fn description(&self) -> &str {
        "Get detailed information about a GitHub repository."
    }

    fn parameters(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "owner": {
                    "type": "string",
                    "description": "Repository owner (user or organization)"
                },
                "repo": {
                    "type": "string",
                    "description": "Repository name"
                }
            },
            "required": ["owner", "repo"]
        }))
    }

    async fn call(&self, input: Value) -> crate::Result<Value> {
        let owner = input["owner"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'owner' parameter".into()))?;
        let repo = input["repo"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'repo' parameter".into()))?;

        let endpoint = format!("/repos/{}/{}", owner, repo);
        let response = self.client.get(&endpoint).await?;

        Ok(json!({
            "name": response["full_name"],
            "description": response["description"],
            "stars": response["stargazers_count"],
            "forks": response["forks_count"],
            "open_issues": response["open_issues_count"],
            "language": response["language"],
            "topics": response["topics"],
            "default_branch": response["default_branch"],
            "created_at": response["created_at"],
            "updated_at": response["updated_at"],
            "url": response["html_url"]
        }))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// List Issues Tool
// ─────────────────────────────────────────────────────────────────────────────

/// Tool for listing repository issues
pub struct GitHubListIssuesTool {
    client: GitHubClient,
}

impl GitHubListIssuesTool {
    pub fn new() -> Self {
        Self {
            client: GitHubClient::new(),
        }
    }

    pub fn with_client(client: GitHubClient) -> Self {
        Self { client }
    }
}

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

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

    fn description(&self) -> &str {
        "List issues from a GitHub repository."
    }

    fn parameters(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "owner": {
                    "type": "string",
                    "description": "Repository owner"
                },
                "repo": {
                    "type": "string",
                    "description": "Repository name"
                },
                "state": {
                    "type": "string",
                    "enum": ["open", "closed", "all"],
                    "description": "Filter by issue state"
                }
            },
            "required": ["owner", "repo"]
        }))
    }

    async fn call(&self, input: Value) -> crate::Result<Value> {
        let owner = input["owner"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'owner' parameter".into()))?;
        let repo = input["repo"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'repo' parameter".into()))?;
        let state = input["state"].as_str().unwrap_or("open");

        let endpoint = format!("/repos/{}/{}/issues?state={}&per_page=20", owner, repo, state);
        let response = self.client.get(&endpoint).await?;

        let issues = response
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter(|issue| issue["pull_request"].is_null()) // Exclude PRs
                    .map(|issue| {
                        json!({
                            "number": issue["number"],
                            "title": issue["title"],
                            "state": issue["state"],
                            "author": issue["user"]["login"],
                            "labels": issue["labels"].as_array().map(|l| 
                                l.iter().filter_map(|x| x["name"].as_str()).collect::<Vec<_>>()
                            ),
                            "created_at": issue["created_at"],
                            "url": issue["html_url"]
                        })
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        Ok(json!({
            "repository": format!("{}/{}", owner, repo),
            "state": state,
            "issues": issues,
            "count": issues.len()
        }))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Read File Tool
// ─────────────────────────────────────────────────────────────────────────────

/// Tool for reading file contents from a repository
pub struct GitHubReadFileTool {
    client: GitHubClient,
}

impl GitHubReadFileTool {
    pub fn new() -> Self {
        Self {
            client: GitHubClient::new(),
        }
    }

    pub fn with_client(client: GitHubClient) -> Self {
        Self { client }
    }
}

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

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

    fn description(&self) -> &str {
        "Read the contents of a file from a GitHub repository."
    }

    fn parameters(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "owner": {
                    "type": "string",
                    "description": "Repository owner"
                },
                "repo": {
                    "type": "string",
                    "description": "Repository name"
                },
                "path": {
                    "type": "string",
                    "description": "Path to the file in the repository"
                },
                "ref": {
                    "type": "string",
                    "description": "Branch, tag, or commit SHA (default: main branch)"
                }
            },
            "required": ["owner", "repo", "path"]
        }))
    }

    async fn call(&self, input: Value) -> crate::Result<Value> {
        let owner = input["owner"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'owner' parameter".into()))?;
        let repo = input["repo"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'repo' parameter".into()))?;
        let path = input["path"]
            .as_str()
            .ok_or_else(|| crate::error::AgnoError::Protocol("missing 'path' parameter".into()))?;

        let mut endpoint = format!("/repos/{}/{}/contents/{}", owner, repo, path);
        if let Some(git_ref) = input["ref"].as_str() {
            endpoint.push_str(&format!("?ref={}", git_ref));
        }

        let response = self.client.get(&endpoint).await?;

        // Decode base64 content
        let content = response["content"]
            .as_str()
            .map(|c| {
                let cleaned = c.replace('\n', "");
                use base64::Engine;
                base64::engine::general_purpose::STANDARD
                    .decode(&cleaned)
                    .ok()
                    .and_then(|bytes| String::from_utf8(bytes).ok())
            })
            .flatten();

        Ok(json!({
            "path": path,
            "name": response["name"],
            "size": response["size"],
            "sha": response["sha"],
            "content": content,
            "encoding": response["encoding"],
            "url": response["html_url"]
        }))
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// GitHub Toolkit
// ─────────────────────────────────────────────────────────────────────────────

use crate::tool::ToolRegistry;

/// Register all GitHub tools with a registry
pub fn register_github_tools(registry: &mut ToolRegistry) {
    let client = GitHubClient::new();
    registry.register(GitHubSearchReposTool::with_client(client.clone()));
    registry.register(GitHubGetRepoTool::with_client(client.clone()));
    registry.register(GitHubListIssuesTool::with_client(client.clone()));
    registry.register(GitHubReadFileTool::with_client(client));
}

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

    #[test]
    fn test_github_tools_creation() {
        let search = GitHubSearchReposTool::new();
        assert_eq!(search.name(), "github_search_repos");

        let get_repo = GitHubGetRepoTool::new();
        assert_eq!(get_repo.name(), "github_get_repo");

        let issues = GitHubListIssuesTool::new();
        assert_eq!(issues.name(), "github_list_issues");

        let read_file = GitHubReadFileTool::new();
        assert_eq!(read_file.name(), "github_read_file");
    }
}