sermo 0.2.1

A Rust client library for interacting with various LLM provider APIs
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
// Copyright 2025 Aquila Labs of Alberta, Canada <matt@cicero.sh>
// Licensed under either the Apache License, Version 2.0 OR the MIT License, at your option.
// You may not use this file except in compliance with one of the Licenses.
// Apache License text: https://www.apache.org/licenses/LICENSE-2.0
// MIT License text: https://opensource.org/licenses/MIT

use super::http::{build_client, get};
use super::{Tool, ToolDefinition, FunctionDefinition, arg_str, arg_usize};
use std::io;
use serde_json::Value;
use atlas_http::HttpResponse;
use std::net::{IpAddr, ToSocketAddrs};
use url::Url;

const DEFAULT_MAX_BYTES: usize = 30_000;
const HARD_MAX_BYTES: usize = 100_000;
const MAX_REDIRECTS: usize = 5;

/// Web fetch tool that retrieves web pages and converts them to markdown.
pub struct WebFetchTool;

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

    pub fn get_definition(&self) -> ToolDefinition {
        ToolDefinition {
            tool_type: "function".to_string(),
            function: FunctionDefinition {
                name: self.name().to_string(),
                description: self.description().to_string(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "URL to fetch (http or https)."
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Byte offset to start reading from (default 0)."
                        },
                        "max_bytes": {
                            "type": "integer",
                            "description": "Maximum number of bytes to return (default 30000, max 100000)."
                        }
                    },
                    "required": ["url"]
                }),
            },
        }
    }
}

impl Tool for WebFetchTool {
    fn name(&self) -> &str {
        "web_fetch"
    }

    fn description(&self) -> &str {
        "Fetch the contents of a URL and return them as markdown or plain text."
    }

    fn execute(&self, arguments: &str) -> Result<String, io::Error> {
        let data: Value = serde_json::from_str(arguments).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("Invalid arguments: {}", e)))?;
        let url = arg_str(&data, "url")?;
        let offset = arg_usize(&data, "offset", 0);
        let max_bytes = arg_usize(&data, "max_bytes", DEFAULT_MAX_BYTES).min(HARD_MAX_BYTES);
        Ok(fetch(url, offset, max_bytes))
    }
}

/// Fetch and convert a URL. Returns a message string rather than an `Err` for
/// anything that is not a programmer error (bad url, blocked host, HTTP errors).
fn fetch(url_str: &str, offset: usize, max_bytes: usize) -> String {
    let mut current = match Url::parse(url_str) {
        Ok(u) => u,
        Err(e) => return format!("fetch failed: invalid url '{}': {}", url_str, e),
    };

    let mut client = build_client();
    let mut hops = 0;

    loop {
        // Validate the current hop (scheme + SSRF). Redirects are re-validated here too.
        if let Err(reason) = check_url(&current) {
            return format!("blocked: {}", reason);
        }

        let res = match get(&mut client, current.as_str()) {
            Ok(r) => r,
            Err(e) => return format!("fetch failed: {}", e),
        };

        let status = res.status_code();

        if (300..400).contains(&status) {
            if hops >= MAX_REDIRECTS {
                return format!("fetch failed: too many redirects (more than {} hops)", MAX_REDIRECTS);
            }
            match res.headers().get_lower("location") {
                Some(location) => match current.join(&location) {
                    Ok(next) => {
                        current = next;
                        hops += 1;
                    }
                    Err(e) => return format!("fetch failed: invalid redirect location '{}': {}", location, e),
                },
                None => return format!("fetch failed: HTTP {} redirect without a Location header", status),
            }
            continue;
        }

        return handle_response(&current, status, &res, offset, max_bytes);
    }
}

/// Validate scheme and that the host resolves only to public addresses.
fn check_url(url: &Url) -> Result<(), String> {
    check_scheme(url)?;

    let host = match url.host_str() {
        Some(h) => h,
        None => return Err("url has no host".to_string()),
    };
    let port = match url.port_or_known_default() {
        Some(p) => p,
        None => return Err(format!("unknown port for '{}'", url)),
    };

    let addrs = match (host, port).to_socket_addrs() {
        Ok(a) => a,
        Err(e) => return Err(format!("could not resolve host '{}': {}", host, e)),
    };

    for addr in addrs {
        if let Some(reason) = block_reason(addr.ip()) {
            return Err(format!("'{}' resolves to a {} ({}); request blocked", host, reason, addr.ip()));
        }
    }

    Ok(())
}

/// Pure scheme check (http/https only).
fn check_scheme(url: &Url) -> Result<(), String> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Err(format!("unsupported scheme '{}' (only http and https are allowed)", url.scheme()));
    }
    Ok(())
}

/// Return a human-readable reason the IP is blocked, or `None` if it is public.
fn block_reason(ip: IpAddr) -> Option<&'static str> {
    match ip {
        IpAddr::V4(v4) => {
            if v4.is_loopback() {
                Some("loopback address")
            } else if v4.is_private() {
                Some("private (RFC1918) address")
            } else if v4.is_link_local() {
                Some("link-local address")
            } else if v4.is_unspecified() {
                Some("unspecified address")
            } else {
                None
            }
        }
        IpAddr::V6(v6) => {
            if v6.is_loopback() {
                Some("loopback address")
            } else if v6.is_unique_local() {
                Some("IPv6 unique-local address")
            } else if v6.is_unicast_link_local() {
                Some("IPv6 link-local address")
            } else if v6.is_unspecified() {
                Some("unspecified address")
            } else {
                None
            }
        }
    }
}

fn is_blocked_ip(ip: IpAddr) -> bool {
    block_reason(ip).is_some()
}

fn handle_response(url: &Url, status: u16, res: &HttpResponse, offset: usize, max_bytes: usize) -> String {
    let content_type = res.headers().get_lower("content-type").unwrap_or_default();
    let body = res.body();

    if !(200..300).contains(&status) {
        return format!("fetch failed: HTTP {}\n\n{}", status, excerpt(&body, 500));
    }

    if is_binary_content_type(&content_type) {
        let size = res.headers().get_lower("content-length").and_then(|s| s.trim().parse::<usize>().ok()).unwrap_or_else(|| body.len());
        return format!("not fetched: binary content ({}), {} bytes", content_type, size);
    }

    let (full, extraction, title) = if is_html_content_type(&content_type) {
        let (content, extraction, title) = html_to_content(&body, url.as_str());
        (content, Some(extraction), title)
    } else {
        (body, None, None)
    };

    let total = full.len();
    let shown = truncate(&full, offset, max_bytes);

    build_output(url.as_str(), status, &content_type, title.as_deref(), extraction, total, &shown)
}

/// Convert HTML to markdown, choosing readability vs. fallback.
fn html_to_content(html: &str, final_url: &str) -> (String, &'static str, Option<String>) {
    let fallback = match convert_html_fallback(html) {
        Ok(md) => md,
        Err(_) => String::new(),
    };
    let fallback_len = fallback.len();

    match lectito::extract(html, Some(final_url), &lectito::ReadabilityOptions::default()) {
        Ok(Some(article)) => {
            let text_len = article.text_content.len();
            let too_short = fallback_len > 0 && (text_len as f64) < (fallback_len as f64) * 0.2;
            let title = article.title.clone().or_else(|| html_title(html));
            if too_short {
                (fallback, "fallback", title)
            } else {
                (article.markdown, "readability", title)
            }
        }
        _ => (fallback, "fallback", html_title(html)),
    }
}

fn convert_html_fallback(html: &str) -> Result<String, String> {
    let converter = htmd::HtmlToMarkdown::builder().skip_tags(vec!["script", "style", "nav", "header", "footer", "aside", "noscript"]).build();
    converter.convert(html).map_err(|e| e.to_string())
}

fn html_title(html: &str) -> Option<String> {
    let document = scraper::Html::parse_document(html);
    let sel = scraper::Selector::parse("title").ok()?;
    document.select(&sel).next().map(|el| el.text().collect::<String>().trim().to_string())
}

fn is_html_content_type(content_type: &str) -> bool {
    let ct = content_type.to_ascii_lowercase();
    ct.contains("text/html") || ct.contains("application/xhtml+xml")
}

fn is_binary_content_type(content_type: &str) -> bool {
    let ct = content_type.to_ascii_lowercase();
    [
        "image/",
        "audio/",
        "video/",
        "font/",
        "application/pdf",
        "application/zip",
        "application/gzip",
        "application/x-gzip",
        "application/x-tar",
        "application/x-compressed",
        "application/x-7z-compressed",
        "application/x-rar-compressed",
        "application/octet-stream",
        "application/vnd.",
        "application/wasm",
    ]
    .iter()
    .any(|p| ct.contains(p))
        || ct.contains("binary")
}

/// Cut to the nearest char boundary at or before `byte`.
fn floor_char_boundary(s: &str, mut byte: usize) -> usize {
    if byte >= s.len() {
        return s.len();
    }
    while !s.is_char_boundary(byte) {
        byte -= 1;
    }
    byte
}

/// Apply offset then max_bytes, both on char boundaries.
fn truncate(full: &str, offset: usize, max_bytes: usize) -> String {
    let total = full.len();
    let start = floor_char_boundary(full, offset);
    let rest = &full[start..];
    let end = floor_char_boundary(rest, max_bytes);
    let shown = &rest[..end];
    let truncated = (start + end) < total;

    if truncated {
        let next_offset = start + end;
        format!("{}\n[truncated: showing bytes {}-{} of {}. Call again with offset={} for more.]", shown, start, next_offset, total, next_offset)
    } else {
        shown.to_string()
    }
}

/// Short body excerpt for error responses.
fn excerpt(body: &str, max: usize) -> String {
    let body = body.trim();
    let end = floor_char_boundary(body, max);
    if end < body.len() {
        format!("{}...", &body[..end])
    } else {
        body.to_string()
    }
}

fn build_output(final_url: &str, status: u16, content_type: &str, title: Option<&str>, extraction: Option<&str>, total: usize, shown: &str) -> String {
    let mut header = String::new();
    header.push_str(&format!("url: {}\n", final_url));
    header.push_str(&format!("status: {}\n", status));
    header.push_str(&format!("content-type: {}\n", content_type));
    if let Some(t) = title {
        if !t.is_empty() {
            header.push_str(&format!("title: {}\n", t));
        }
    }
    if let Some(e) = extraction {
        header.push_str(&format!("extraction: {}\n", e));
    }
    header.push_str(&format!("size: {} bytes\n", total));

    let safe_url = final_url.replace('"', "%22");
    let neutralized = shown.replace("</web_content>", "<\\/web_content>");

    format!("{}\n<web_content url=\"{}\" untrusted=\"true\">\n{}\n</web_content>", header, safe_url, neutralized)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr};

    #[test]
    fn truncate_does_not_split_multibyte_chars() {
        // 'é' is two bytes; max_bytes=3 lands in the middle of a char.
        let s = "aébc";
        assert_eq!(floor_char_boundary(s, 3), 3);
        let out = truncate(s, 0, 3);
        assert!(out.starts_with("aé"));
    }

    #[test]
    fn truncate_reports_remaining_bytes() {
        let s = "hello world";
        let out = truncate(s, 0, 5);
        assert_eq!(out, "hello\n[truncated: showing bytes 0-5 of 11. Call again with offset=5 for more.]");
    }

    #[test]
    fn truncate_applies_offset_on_char_boundary() {
        let s = "aébcdef";
        // offset 2 is mid 'é'; should snap to 1.
        let out = truncate(s, 2, 5);
        assert!(out.starts_with("ébc"));
    }

    #[test]
    fn truncate_no_truncation_when_short() {
        let out = truncate("short", 0, 100);
        assert_eq!(out, "short");
    }

    #[test]
    fn ipv4_blocklist() {
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))));
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))));
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1))));
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
        assert!(is_blocked_ip(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))));
        assert!(!is_blocked_ip(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))));
    }

    #[test]
    fn ipv6_blocklist() {
        assert!(is_blocked_ip(IpAddr::V6(Ipv6Addr::LOCALHOST)));
        assert!(is_blocked_ip(IpAddr::V6(Ipv6Addr::UNSPECIFIED)));
        assert!(is_blocked_ip("fc00::1".parse().unwrap()));
        assert!(is_blocked_ip("fe80::1".parse().unwrap()));
        assert!(!is_blocked_ip("2606:4700:4700::1111".parse().unwrap()));
    }

    #[test]
    fn scheme_rejection() {
        let ftp = Url::parse("ftp://example.com/file").unwrap();
        assert!(check_scheme(&ftp).is_err());
        let http = Url::parse("http://example.com/").unwrap();
        assert!(check_scheme(&http).is_ok());
        let https = Url::parse("https://example.com/").unwrap();
        assert!(check_scheme(&https).is_ok());
    }

    #[test]
    fn excerpt_respects_char_boundary() {
        let out = excerpt("éééé", 3);
        assert_eq!(out, "é...");
    }
}