rho-coding-agent 3.6.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::{
    fs,
    path::{Path, PathBuf},
};

use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
use serde_json::{json, Value};
use url::Url;

use rho_tools::tool::ToolError;

use super::FetchedTarget;

pub(in crate::tools::web) async fn fetch_via_api(
    client: &reqwest::Client,
    github: &GitHubTarget,
    token: Option<&str>,
) -> Result<FetchedTarget, ToolError> {
    let api_url = api_url(github);
    let content = match github.kind {
        GitHubKind::Blob => github_api_file_content(client, &api_url, token).await?,
        GitHubKind::Root | GitHubKind::Tree | GitHubKind::Commit => {
            format_github_api(&github_api_json(client, &api_url, token).await?)
        }
    };
    Ok(FetchedTarget {
        title: Some(format!("{}/{}", github.owner, github.repo)),
        content,
        metadata: json!({"mode": "github_api"}),
    })
}

pub(in crate::tools::web) fn api_url(github: &GitHubTarget) -> String {
    match github.kind {
        GitHubKind::Root | GitHubKind::Tree | GitHubKind::Blob => format!(
            "https://api.github.com/repos/{}/{}/contents/{}{}",
            github.owner,
            github.repo,
            github.path,
            github
                .ref_name
                .as_ref()
                .map(|ref_name| format!("?ref={ref_name}"))
                .unwrap_or_default()
        ),
        GitHubKind::Commit => format!(
            "https://api.github.com/repos/{}/{}/commits/{}",
            github.owner,
            github.repo,
            github.ref_name.as_deref().unwrap_or("HEAD")
        ),
    }
}

pub(in crate::tools::web) fn clone_url(github: &GitHubTarget) -> String {
    format!("https://github.com/{}/{}.git", github.owner, github.repo)
}

/// Environment overrides that let `git` authenticate GitHub clones.
///
/// The token travels as a scoped `http.<url>.extraheader` config value instead
/// of a URL userinfo component, so it never appears in the command line (world
/// readable through the process table) or in the cloned repository's
/// `remote.origin.url`.
pub(in crate::tools::web) fn clone_credential_environment(
    token: Option<&str>,
) -> Vec<(String, String)> {
    let Some(token) = token else {
        return Vec::new();
    };
    let header = format!(
        "Authorization: Basic {}",
        BASE64_STANDARD.encode(format!("x-access-token:{token}"))
    );
    vec![
        ("GIT_CONFIG_COUNT".into(), "1".into()),
        (
            "GIT_CONFIG_KEY_0".into(),
            "http.https://github.com/.extraheader".into(),
        ),
        ("GIT_CONFIG_VALUE_0".into(), header),
    ]
}

pub(in crate::tools::web) fn format_github_api(value: &Value) -> String {
    if let Some(entries) = value.as_array() {
        return entries
            .iter()
            .filter_map(format_github_entry)
            .collect::<Vec<_>>()
            .join("\n");
    }
    if let Some(formatted) = format_github_commit(value) {
        return formatted;
    }
    serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
}

fn format_github_entry(value: &Value) -> Option<String> {
    let name = value
        .get("name")
        .or_else(|| value.get("path"))
        .and_then(Value::as_str)?;
    let kind = match value.get("type").and_then(Value::as_str) {
        Some("dir") => "dir",
        Some("file") => "file",
        Some(other) => other,
        None => "file",
    };
    Some(format!("{kind} {name}"))
}

fn format_github_commit(value: &Value) -> Option<String> {
    let sha = value.get("sha").and_then(Value::as_str)?;
    value.get("commit")?;
    let message = value
        .pointer("/commit/message")
        .and_then(Value::as_str)
        .unwrap_or("")
        .lines()
        .next()
        .unwrap_or("");
    let mut lines = vec![format!("commit {sha}")];
    if !message.is_empty() {
        lines.push(message.to_string());
    }
    if let Some(files) = value.get("files").and_then(Value::as_array) {
        for file in files {
            let path = file
                .get("filename")
                .and_then(Value::as_str)
                .unwrap_or("file");
            let status = file
                .get("status")
                .and_then(Value::as_str)
                .unwrap_or("changed");
            lines.push(format!("{status} {path}"));
        }
    }
    Some(lines.join("\n"))
}

async fn github_api_file_content(
    client: &reqwest::Client,
    url: &str,
    token: Option<&str>,
) -> Result<String, ToolError> {
    let value = github_api_json(client, url, token).await?;
    let encoding = value.get("encoding").and_then(Value::as_str);
    let content = value
        .get("content")
        .and_then(Value::as_str)
        .ok_or_else(|| {
            ToolError::Message("GitHub API response did not include file content".into())
        })?;
    if encoding == Some("base64") {
        let compact = content.lines().collect::<String>();
        let bytes = BASE64_STANDARD.decode(compact).map_err(|err| {
            ToolError::Message(format!("GitHub file content was not base64: {err}"))
        })?;
        return String::from_utf8(bytes).map_err(ToolError::Utf8);
    }
    Ok(content.to_string())
}

async fn github_api_json(
    client: &reqwest::Client,
    url: &str,
    token: Option<&str>,
) -> Result<Value, ToolError> {
    let mut request = client.get(url).header("User-Agent", "rho-coding-agent");
    if let Some(token) = token {
        request = request.bearer_auth(token);
    }
    request
        .send()
        .await
        .map_err(|err| ToolError::Message(format!("GitHub API request failed: {err}")))?
        .error_for_status()
        .map_err(|err| ToolError::Message(format!("GitHub API request failed: {err}")))?
        .json()
        .await
        .map_err(|err| ToolError::Message(format!("GitHub API response was not JSON: {err}")))
}

/// The GitHub token of whoever `credentials` belong to: `GITHUB_TOKEN`,
/// else `GH_TOKEN`, in their environment.
pub(in crate::tools::web) fn token(
    credentials: &dyn rho_providers::credentials::CredentialStore,
) -> Option<String> {
    credentials
        .environment_variable("GITHUB_TOKEN")
        .or_else(|| credentials.environment_variable("GH_TOKEN"))
}

pub(in crate::tools::web) async fn read_clone(
    github: &GitHubTarget,
    local_path: &Path,
) -> Result<FetchedTarget, ToolError> {
    let target_path = local_path.join(&github.path);
    match github.kind {
        GitHubKind::Root | GitHubKind::Tree => {
            let dir = if github.kind == GitHubKind::Root {
                local_path
            } else {
                &target_path
            };
            let tree = directory_listing(dir)?;
            let readme = find_readme(dir).and_then(|path| fs::read_to_string(path).ok());
            let content = format!(
                "GitHub repository {}/{}\n\n{}{}",
                github.owner,
                github.repo,
                tree,
                readme
                    .as_ref()
                    .map(|readme| format!("\n\nREADME:\n{readme}"))
                    .unwrap_or_default()
            );
            Ok(FetchedTarget {
                title: Some(format!("{}/{}", github.owner, github.repo)),
                content,
                metadata: json!({"mode": "clone"}),
            })
        }
        GitHubKind::Blob => {
            let content = fs::read_to_string(&target_path)?;
            Ok(FetchedTarget {
                title: Some(github.path.clone()),
                content,
                metadata: json!({"mode": "clone"}),
            })
        }
        GitHubKind::Commit => Err(ToolError::Message(
            "commit URLs must use the GitHub API fetch plan".into(),
        )),
    }
}

fn directory_listing(path: &Path) -> Result<String, ToolError> {
    let mut entries = fs::read_dir(path)?
        .map(|entry| {
            let entry = entry?;
            let file_type = entry.file_type()?;
            let suffix = if file_type.is_dir() { "/" } else { "" };
            Ok(format!("{}{}", entry.file_name().to_string_lossy(), suffix))
        })
        .collect::<Result<Vec<_>, std::io::Error>>()?;
    entries.sort();
    Ok(entries.join("\n"))
}

fn find_readme(path: &Path) -> Option<PathBuf> {
    ["README.md", "README.txt", "README"]
        .into_iter()
        .map(|name| path.join(name))
        .find(|path| path.is_file())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::tools::web) enum GitHubKind {
    Root,
    Tree,
    Blob,
    Commit,
}

#[derive(Debug)]
pub(in crate::tools::web) struct GitHubTarget {
    pub(in crate::tools::web) owner: String,
    pub(in crate::tools::web) repo: String,
    pub(in crate::tools::web) kind: GitHubKind,
    pub(in crate::tools::web) ref_name: Option<String>,
    pub(in crate::tools::web) path: String,
}

pub(in crate::tools::web) fn parse_url(input: &str) -> Option<GitHubTarget> {
    let url = Url::parse(input).ok()?;
    if url.host_str()? != "github.com" {
        return None;
    }
    let segments = url.path_segments()?.collect::<Vec<_>>();
    if segments.len() < 2 {
        return None;
    }
    let owner = segments[0].to_string();
    let repo = segments[1].trim_end_matches(".git").to_string();
    if !is_safe_repository_segment(&owner) || !is_safe_repository_segment(&repo) {
        return None;
    }
    match segments.get(2).copied() {
        None | Some("") => Some(GitHubTarget {
            owner,
            repo,
            kind: GitHubKind::Root,
            ref_name: None,
            path: String::new(),
        }),
        Some("tree") | Some("blob") => {
            let kind = if segments[2] == "tree" {
                GitHubKind::Tree
            } else {
                GitHubKind::Blob
            };
            let (ref_name, path) = split_github_ref_and_path(kind, &segments[3..]);
            if !ref_name.as_deref().is_none_or(is_safe_ref_name) {
                return None;
            }
            Some(GitHubTarget {
                owner,
                repo,
                kind,
                ref_name,
                path,
            })
        }
        Some("commit") => {
            let ref_name = segments.get(3).map(|value| (*value).to_string());
            if !ref_name.as_deref().is_none_or(is_safe_ref_name) {
                return None;
            }
            Some(GitHubTarget {
                owner,
                repo,
                kind: GitHubKind::Commit,
                ref_name,
                path: String::new(),
            })
        }
        _ => None,
    }
}

/// GitHub owner and repository names use a restricted character set. Rejecting
/// anything else keeps interpolated API URLs and `git` arguments unambiguous.
fn is_safe_repository_segment(value: &str) -> bool {
    !value.is_empty()
        && !value.starts_with('-')
        && value.chars().all(|character| {
            character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_')
        })
}

/// A ref reaches `git fetch` as a positional argument, so a leading dash would
/// be parsed as an option. Remaining checks follow `git check-ref-format
/// --allow-onelevel`, which permits valid branch characters such as `$` and `+`.
fn is_safe_ref_name(value: &str) -> bool {
    if value.is_empty() || value == "@" || value.starts_with('-') {
        return false;
    }
    if value.starts_with('/') || value.ends_with('/') || value.ends_with('.') {
        return false;
    }
    if value.contains("..") || value.contains("//") || value.contains("@{") || value.contains('\\')
    {
        return false;
    }
    if value.bytes().any(|byte| {
        byte < 0x20
            || byte == 0x7f
            || matches!(byte, b' ' | b'~' | b'^' | b':' | b'?' | b'*' | b'[')
    }) {
        return false;
    }
    value.split('/').all(|component| {
        !component.is_empty() && !component.starts_with('.') && !component.ends_with(".lock")
    })
}

fn split_github_ref_and_path(_kind: GitHubKind, segments: &[&str]) -> (Option<String>, String) {
    if segments.is_empty() {
        return (None, String::new());
    }
    if segments.len() == 1 {
        return (Some(segments[0].to_string()), String::new());
    }

    let split_at = find_github_path_start(segments).unwrap_or(1);
    (
        Some(segments[..split_at].join("/")),
        segments[split_at..].join("/"),
    )
}

fn find_github_path_start(segments: &[&str]) -> Option<usize> {
    (1..segments.len()).find(|index| is_common_github_path_start(segments[*index]))
}

fn is_common_github_path_start(segment: &str) -> bool {
    matches!(
        segment,
        "src"
            | "docs"
            | "doc"
            | "test"
            | "tests"
            | "crates"
            | "packages"
            | "package"
            | "examples"
            | "example"
            | "scripts"
            | "script"
            | "tools"
            | "tool"
            | "app"
            | "apps"
            | "lib"
            | "libs"
            | "cmd"
            | "components"
            | "component"
            | "internal"
            | "pkg"
            | ".github"
    )
}