Module: Legion::CLI::Chat::WebFetch
- Defined in:
- lib/legion/cli/chat/web_fetch.rb
Defined Under Namespace
Classes: FetchError
Constant Summary collapse
- MAX_BODY =
1 MB
1_048_576- MAX_REDIRECTS =
5- TIMEOUT =
15- CONTEXT_LIMIT =
chars injected into conversation
12_000
Class Method Summary collapse
- .clean_whitespace(text) ⇒ Object
- .convert_blocks!(text) ⇒ Object
- .convert_formatting!(text) ⇒ Object
- .convert_headings!(text) ⇒ Object
- .convert_links!(text) ⇒ Object
- .convert_lists!(text) ⇒ Object
- .fetch(url) ⇒ Object
- .follow_redirects(uri, limit = MAX_REDIRECTS) ⇒ Object
- .html?(content_type) ⇒ Boolean
- .html_to_markdown(html) ⇒ Object
- .parse_uri(url) ⇒ Object
- .replace_close_tags!(text, tag, replacement) ⇒ Object
- .replace_open_tags!(text, tag, replacement) ⇒ Object
- .replace_self_closing!(text, tag, replacement) ⇒ Object
- .replace_tag_blocks!(text, tag) ⇒ Object
- .strip_html_comments!(text) ⇒ Object
- .strip_invisible!(text) ⇒ Object
- .strip_remaining_tags!(text) ⇒ Object
- .strip_tag_blocks!(text, tag) ⇒ Object
- .truncate(text, limit) ⇒ Object
Class Method Details
.clean_whitespace(text) ⇒ Object
267 268 269 270 271 272 273 274 275 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 267 def clean_whitespace(text) text = text.gsub(' ', ' ') .gsub('&', '&') .gsub('<', '<') .gsub('>', '>') .gsub('"', '"') .gsub(''', "'") text.gsub(/\n{3,}/, "\n\n").gsub(/ +/, ' ').strip end |
.convert_blocks!(text) ⇒ Object
242 243 244 245 246 247 248 249 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 242 def convert_blocks!(text) replace_tag_blocks!(text, 'pre') { |inner| "\n```\n#{inner}\n```\n" } replace_tag_blocks!(text, 'blockquote') { |inner| "\n> #{inner}\n" } (text, 'p', "\n\n") (text, 'p', "\n") replace_self_closing!(text, 'br', "\n") replace_self_closing!(text, 'hr', "\n---\n") end |
.convert_formatting!(text) ⇒ Object
236 237 238 239 240 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 236 def convert_formatting!(text) %w[b strong].each { |t| replace_tag_blocks!(text, t) { |inner| "**#{inner}**" } } %w[i em].each { |t| replace_tag_blocks!(text, t) { |inner| "*#{inner}*" } } replace_tag_blocks!(text, 'code') { |inner| "`#{inner}`" } end |
.convert_headings!(text) ⇒ Object
183 184 185 186 187 188 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 183 def convert_headings!(text) (1..6).each do |n| prefix = '#' * n replace_tag_blocks!(text, "h#{n}") { |inner| "\n#{prefix} #{inner}\n" } end end |
.convert_links!(text) ⇒ Object
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 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 190 def convert_links!(text) result = String.new pos = 0 while pos < text.length open_idx = text.index(/<a[\s>]/mi, pos) break unless open_idx close_idx = text.index(%r{</a\s*>}mi, open_idx) unless close_idx result << text[pos..] pos = text.length break end result << text[pos...open_idx] tag_end = text.index('>', open_idx) if tag_end && tag_end < close_idx tag = text[open_idx..tag_end] href = tag[/href=["']([^"']*)["']/i, 1] inner = text[(tag_end + 1)...close_idx] result << if href "[#{inner}](#{href})" else inner end else # Malformed opening tag — preserve the inner text up to the closing tag result << text[open_idx...close_idx] end close_end = text.index('>', close_idx) pos = close_end ? close_end + 1 : close_idx + 4 end result << text[pos..] if pos < text.length text.replace(result) end |
.convert_lists!(text) ⇒ Object
228 229 230 231 232 233 234 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 228 def convert_lists!(text) replace_tag_blocks!(text, 'li') { |inner| "\n- #{inner}" } (text, 'ul', "\n") (text, 'ul', "\n") (text, 'ol', "\n") (text, 'ol', "\n") end |
.fetch(url) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 20 def fetch(url) uri = parse_uri(url) body, content_type = follow_redirects(uri) text = if html?(content_type) html_to_markdown(body) else body end truncate(text.strip, CONTEXT_LIMIT) end |
.follow_redirects(uri, limit = MAX_REDIRECTS) ⇒ Object
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 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 43 def follow_redirects(uri, limit = MAX_REDIRECTS) raise FetchError, 'Too many redirects' if limit.zero? http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') http.open_timeout = TIMEOUT http.read_timeout = TIMEOUT request = Net::HTTP::Get.new(uri.request_uri) request['User-Agent'] = 'LegionIO/1.0 (CLI web fetch)' request['Accept'] = 'text/html, text/plain, application/json' response = http.request(request) case response when Net::HTTPRedirection location = response['location'] new_uri = URI.parse(location) new_uri = URI.join(uri, location) unless new_uri.host follow_redirects(new_uri, limit - 1) when Net::HTTPSuccess body = response.body&.dup&.force_encoding('UTF-8') || '' raise FetchError, "Response too large (#{body.bytesize} bytes)" if body.bytesize > MAX_BODY [body, response['content-type']] else raise FetchError, "HTTP #{response.code}: #{response.}" end rescue SocketError => e raise FetchError, "Connection failed: #{e.}" rescue Net::OpenTimeout, Net::ReadTimeout raise FetchError, "Request timed out (#{TIMEOUT}s)" rescue OpenSSL::SSL::SSLError => e raise FetchError, "SSL error: #{e.}" end |
.html?(content_type) ⇒ Boolean
79 80 81 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 79 def html?(content_type) content_type&.include?('text/html') || false end |
.html_to_markdown(html) ⇒ Object
83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 83 def html_to_markdown(html) text = html.dup strip_invisible!(text) convert_headings!(text) convert_links!(text) convert_lists!(text) convert_formatting!(text) convert_blocks!(text) (text) clean_whitespace(text) end |
.parse_uri(url) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 33 def parse_uri(url) url = "https://#{url}" unless url.match?(%r{\Ahttps?://}) uri = URI.parse(url) raise FetchError, "Invalid URL: #{url}" unless uri.is_a?(URI::HTTP) uri rescue URI::InvalidURIError raise FetchError, "Invalid URL: #{url}" end |
.replace_close_tags!(text, tag, replacement) ⇒ Object
161 162 163 164 165 166 167 168 169 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 161 def (text, tag, replacement) pat = %r{</#{tag}\s*>}mi loop do match = pat.match(text) break unless match text[match.begin(0)..(match.end(0) - 1)] = replacement end end |
.replace_open_tags!(text, tag, replacement) ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 149 def (text, tag, replacement) loop do idx = text.index(/<#{tag}[\s>]/mi) break unless idx close = text.index('>', idx) break unless close text[idx..close] = replacement end end |
.replace_self_closing!(text, tag, replacement) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 171 def replace_self_closing!(text, tag, replacement) loop do idx = text.index(%r{<#{tag}[\s>/]}mi) break unless idx close = text.index('>', idx) break unless close text[idx..close] = replacement end end |
.replace_tag_blocks!(text, tag) ⇒ Object
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 129 def replace_tag_blocks!(text, tag) loop do open_idx = text.index(/<#{tag}[\s>]/mi) break unless open_idx tag_end = text.index('>', open_idx) break unless tag_end close_pat = %r{</#{tag}\s*>}mi close_match = close_pat.match(text, tag_end) if close_match inner = text[(tag_end + 1)...close_match.begin(0)] replacement = yield(inner) text[open_idx..(close_match.end(0) - 1)] = replacement else text[open_idx..] = '' end end end |
.strip_html_comments!(text) ⇒ Object
100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 100 def strip_html_comments!(text) loop do open_idx = text.index('<!--') break unless open_idx close_idx = text.index('-->', open_idx + 4) if close_idx text[open_idx..(close_idx + 2)] = '' else text[open_idx..] = '' end end end |
.strip_invisible!(text) ⇒ Object
95 96 97 98 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 95 def strip_invisible!(text) %w[script style nav footer].each { |tag| strip_tag_blocks!(text, tag) } strip_html_comments!(text) end |
.strip_remaining_tags!(text) ⇒ Object
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 251 def (text) result = String.new(capacity: text.length) pos = 0 while pos < text.length open_idx = text.index('<', pos) unless open_idx result << text[pos..] break end result << text[pos...open_idx] close_idx = text.index('>', open_idx) pos = close_idx ? close_idx + 1 : text.length end text.replace(result) end |
.strip_tag_blocks!(text, tag) ⇒ Object
114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 114 def strip_tag_blocks!(text, tag) loop do open_idx = text.index(/<#{tag}[\s>]/mi) break unless open_idx close_pat = %r{</#{tag}\s*>}mi close_match = close_pat.match(text, open_idx) if close_match text[open_idx..(close_match.end(0) - 1)] = '' else text[open_idx..] = '' end end end |
.truncate(text, limit) ⇒ Object
277 278 279 280 281 |
# File 'lib/legion/cli/chat/web_fetch.rb', line 277 def truncate(text, limit) return text if text.length <= limit text[0, limit] + "\n\n[... truncated at #{limit} characters]" end |