返回 CodeWhale
fetch_url.rs
根目录 / crates / engine / src / tools / fetch_url.rs
1 //! Direct-fetch HTTP tool. Complements `web_search` for cases where the user
2 //! already knows the URL — a known repo, a blog post, a spec page — and
3 //! search is overkill or actively unhelpful.
4 //!
5 //! Returns a structured `{url, status, content_type, content, truncated}`
6 //! payload. HTML responses are stripped to readable text by default
7 //! (`format = "markdown"`); pass `format = "raw"` to keep the bytes intact
8 //! when the model wants to do its own parsing.
9
10 use super::handle::{JSONPATH_MAX_BYTES, JSONPATH_MAX_PATH_BYTES, query_jsonpath_bounded};
11 use super::pdf::PdfTextCommand;
12 use super::spec::{
13 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_u64,
14 };
15 use super::web::extract::{DocumentKind, ExtractedDocument, decode_response_body};
16 use super::web::fetch::{
17 DEFAULT_MAX_BYTES, DEFAULT_TIMEOUT, FetchAttempt, FetchOptions, HARD_MAX_BYTES,
18 HARD_MAX_TIMEOUT, Readable, fetch_readable,
19 };
20 use super::web::overflow::bound_text as bound_web_text;
21 #[cfg(test)]
22 use super::web::overflow::inline_char_budget;
23 use async_trait::async_trait;
24 use serde::Serialize;
25 use serde_json::{Value, json};
26 use std::collections::BTreeMap;
27 use std::time::Duration;
28
29 const FETCH_ACCEPT: &str = "text/html,text/markdown,text/plain,application/json,application/pdf,image/*,audio/*,video/*,*/*;q=0.5";
30 const MAX_JSON_FIELDS: usize = 32;
31
32 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
33 enum Format {
34 Text,
35 Markdown,
36 Raw,
37 }
38
39 impl Format {
40 fn parse(value: Option<&str>) -> Result<Self, ToolError> {
41 match value
42 .unwrap_or("markdown")
43 .trim()
44 .to_ascii_lowercase()
45 .as_str()
46 {
47 "text" | "txt" | "plain" => Ok(Self::Text),
48 "markdown" | "md" => Ok(Self::Markdown),
49 "raw" | "html" | "bytes" => Ok(Self::Raw),
50 other => Err(ToolError::invalid_input(format!(
51 "unknown format `{other}` (allowed: text, markdown, raw)"
52 ))),
53 }
54 }
55 }
56
57 #[derive(Debug, Serialize)]
58 struct FetchResponse {
59 ref_id: String,
60 url: String,
61 status: u16,
62 headers: BTreeMap<String, String>,
63 content_type: String,
64 content: String,
65 truncated: bool,
66 #[serde(skip_serializing_if = "std::ops::Not::not")]
67 partial: bool,
68 #[serde(skip_serializing_if = "Option::is_none")]
69 note: Option<String>,
70 receipt: FetchReceipt,
71 #[serde(skip_serializing_if = "Option::is_none")]
72 artifact: Option<String>,
73 #[serde(skip_serializing_if = "Option::is_none")]
74 fields: Option<BTreeMap<String, Vec<Value>>>,
75 }
76
77 #[derive(Debug, Serialize)]
78 struct FetchReceipt {
79 cache_hit: bool,
80 retries: usize,
81 redirects: usize,
82 /// Every request this fetch made, in order: session `cache_hit`, whether
83 /// the attempt bypassed caches, which one produced content, and the
84 /// response headers that explain the cache state (#5904).
85 attempts: Vec<FetchAttempt>,
86 }
87
88 #[derive(Debug)]
89 struct ArtifactWrite {
90 session_id: String,
91 absolute_path: std::path::PathBuf,
92 relative_path: std::path::PathBuf,
93 byte_size: u64,
94 preview: String,
95 }
96
97 pub struct FetchUrlTool;
98
99 #[async_trait]
100 impl ToolSpec for FetchUrlTool {
101 fn name(&self) -> &'static str {
102 "fetch_url"
103 }
104
105 fn model_visible(&self) -> bool {
106 false
107 }
108
109 fn description(&self) -> &'static str {
110 "Fetch a known URL directly (HTTP GET) and return its content with a session-scoped citation ref_id. Use this instead of `curl` in `exec_shell` (whose sandbox policy may deny outbound network) — network-policy aware and properly decoded. Plain-text endpoints (`.md`, `.txt`, `.json`, `.yaml`, `raw.githubusercontent.com`, public APIs) prefer this over the browser/automation stack. For unknown queries, use `web_search` first. If a login or authorization wall is returned, treat the wall as the result; do not claim the protected page was read."
111 }
112
113 fn input_schema(&self) -> Value {
114 json!({
115 "type": "object",
116 "properties": {
117 "url": {
118 "type": "string",
119 "description": "Absolute HTTP/HTTPS URL to fetch."
120 },
121 "format": {
122 "type": "string",
123 "enum": ["text", "markdown", "raw"],
124 "description": "Post-processing for the response body. `markdown` (default) uses readability extraction and real HTML-to-Markdown conversion; `text` returns readable plain text; `raw` preserves textual response bytes. Binary media is saved as a session artifact."
125 },
126 "max_bytes": {
127 "type": "integer",
128 "description": "Truncate response body after this many bytes (default 1,000,000; hard max 10,485,760)."
129 },
130 "timeout_ms": {
131 "type": "integer",
132 "description": "Request timeout in milliseconds (default 15,000; max 60,000)."
133 },
134 "fields": {
135 "type": "array",
136 "maxItems": MAX_JSON_FIELDS,
137 "items": { "type": "string", "maxLength": JSONPATH_MAX_PATH_BYTES },
138 "description": "Optional JSONPath projections for JSON responses. Supports $, .field, [index], [*], and ['field']; returns matches under `fields`. At most 32 paths of 4096 bytes each, 128 steps and 1024 intermediate matches per path, and 1 MiB of aggregate projected fields; narrow the selection on refusal."
139 }
140 },
141 "required": ["url"]
142 })
143 }
144
145 fn capabilities(&self) -> Vec<ToolCapability> {
146 vec![ToolCapability::ReadOnly, ToolCapability::Network]
147 }
148
149 fn approval_requirement(&self) -> ApprovalRequirement {
150 // Read-only HTTP can still disclose local data through a URL or query.
151 // Host allowlisting controls reachability, not approval of this payload.
152 ApprovalRequirement::Required
153 }
154
155 fn supports_parallel(&self) -> bool {
156 true
157 }
158
159 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
160 let url = input
161 .get("url")
162 .and_then(Value::as_str)
163 .ok_or_else(|| ToolError::invalid_input("`url` is required"))?
164 .trim()
165 .to_string();
166
167 if url.is_empty() {
168 return Err(ToolError::invalid_input("`url` cannot be empty"));
169 }
170 let scheme_ok = url.starts_with("http://") || url.starts_with("https://");
171 if !scheme_ok {
172 return Err(ToolError::invalid_input(
173 "only http:// and https:// URLs are supported",
174 ));
175 }
176
177 let format = Format::parse(input.get("format").and_then(Value::as_str))?;
178 let max_bytes =
179 usize::try_from(optional_u64(&input, "max_bytes", DEFAULT_MAX_BYTES as u64)?)
180 .unwrap_or(HARD_MAX_BYTES)
181 .clamp(1, HARD_MAX_BYTES);
182 let timeout_ms = optional_u64(&input, "timeout_ms", DEFAULT_TIMEOUT.as_millis() as u64)?
183 .clamp(1, HARD_MAX_TIMEOUT.as_millis() as u64);
184 let requested_fields = parse_fields(&input)?;
185 // Bound as a reference so the `Fn` extractor can run twice without
186 // moving the field list into its first future.
187 let requested_fields = &requested_fields;
188 // A 2xx that extracts to nothing is re-fetched once past every cache
189 // before it becomes a partial page or an error; the receipt keeps both
190 // attempts (#5904).
191 let readable = fetch_readable(
192 &url,
193 &FetchOptions::new(Duration::from_millis(timeout_ms), max_bytes, FETCH_ACCEPT),
194 context,
195 "fetch_url",
196 |fetched: super::web::fetch::FetchedPayload| {
197 Box::pin(async move {
198 let is_success = (200..300).contains(&fetched.status);
199 let body_text = if requested_fields.is_empty() {
200 None
201 } else {
202 // JSON is never allowed to discover an encoding from body markup.
203 Some(decode_response_body(
204 &fetched.bytes,
205 Some(&fetched.content_type),
206 false,
207 )?)
208 };
209 let fields = match body_text.as_deref() {
210 Some(body) => {
211 project_json_fields(body, &fetched.content_type, requested_fields)?
212 }
213 None => None,
214 };
215 let extracted = extract_fetched_document(
216 format,
217 &fetched.url,
218 &fetched.content_type,
219 &fetched.bytes,
220 fetched.truncated,
221 is_success,
222 body_text.as_deref(),
223 PdfTextCommand::system(Some(context)),
224 )
225 .await?;
226 Ok((extracted, fields))
227 })
228 },
229 )
230 .await?;
231 let super::web::fetch::ReadableFetch {
232 payload: fetched,
233 document,
234 attempts,
235 } = readable;
236 let ((extracted, fields), note) = match document {
237 Readable::Document(document) => (document, None),
238 Readable::Partial(page) => ((page.document, None), Some(page.note)),
239 };
240 let is_success = (200..300).contains(&fetched.status);
241
242 let citation_title = extracted.title.clone();
243 let (processed, artifact_write) = render_extracted(
244 &fetched.url,
245 &fetched.content_type,
246 format,
247 extracted,
248 &fetched.bytes,
249 context,
250 )?;
251 let artifact = artifact_write.as_ref().map(|write| {
252 codewhale_runtime::artifacts::format_artifact_relative_path(&write.relative_path)
253 });
254
255 let citation = super::web::citations::register(
256 &context.state_namespace,
257 &fetched.url,
258 citation_title.as_deref(),
259 )
260 .ok_or_else(|| ToolError::execution_failed("fetched URL could not be registered"))?;
261 let response = FetchResponse {
262 ref_id: citation.ref_id,
263 url: citation.url,
264 status: fetched.status,
265 headers: fetched.headers,
266 content_type: fetched.content_type,
267 content: processed,
268 truncated: fetched.truncated,
269 partial: note.is_some(),
270 note,
271 receipt: FetchReceipt {
272 cache_hit: fetched.cache_hit,
273 retries: fetched.retries,
274 redirects: fetched.redirects,
275 attempts,
276 },
277 artifact,
278 fields,
279 };
280
281 let content = serde_json::to_string_pretty(&response).map_err(|error| {
282 ToolError::execution_failed(format!("failed to serialize response: {error}"))
283 })?;
284 let metadata = artifact_write.map(artifact_metadata);
285
286 if !is_success {
287 // Don't `Err` on 4xx/5xx — the caller often wants to see the body
288 // (e.g. a JSON error envelope). Mark the result as a failure so the
289 // engine renders it as such.
290 return Ok(ToolResult {
291 content,
292 success: false,
293 metadata,
294 });
295 }
296
297 Ok(ToolResult {
298 content,
299 success: true,
300 metadata,
301 })
302 }
303 }
304
305 async fn extract_fetched_document(
306 format: Format,
307 url: &str,
308 content_type: &str,
309 bytes: &[u8],
310 truncated: bool,
311 is_success: bool,
312 decoded_body: Option<&str>,
313 pdf_command: PdfTextCommand<'_>,
314 ) -> super::web::adapter::AdapterResult<ExtractedDocument> {
315 let extraction = if format == Format::Raw
316 && super::web::extract::validate_pdf_response(url, Some(content_type), bytes)?
317 {
318 Ok(ExtractedDocument {
319 kind: DocumentKind::Pdf,
320 title: Some("PDF Document".to_string()),
321 text: String::new(),
322 markdown: String::new(),
323 cleaned_html: None,
324 pdf_pages: None,
325 media_extension: None,
326 })
327 } else {
328 super::web::extract::extract_document_with_pdf_command(
329 url,
330 Some(content_type),
331 bytes,
332 truncated,
333 pdf_command,
334 )
335 .await
336 };
337 match extraction {
338 Ok(document) => Ok(document),
339 Err(error)
340 if error.content()
341 && (format == Format::Raw || !is_success)
342 && is_declared_textual(content_type) =>
343 {
344 let body_text = match decoded_body {
345 Some(body_text) => body_text.to_string(),
346 None => {
347 decode_response_body(bytes, Some(content_type), is_declared_html(content_type))?
348 }
349 };
350 Ok(ExtractedDocument {
351 kind: DocumentKind::Text,
352 title: None,
353 text: body_text.clone(),
354 markdown: body_text,
355 cleaned_html: None,
356 pdf_pages: None,
357 media_extension: None,
358 })
359 }
360 Err(error) => Err(error),
361 }
362 }
363
364 fn is_declared_textual(content_type: &str) -> bool {
365 let content_type = content_type
366 .split(';')
367 .next()
368 .unwrap_or(content_type)
369 .trim()
370 .to_ascii_lowercase();
371 content_type.starts_with("text/")
372 || content_type.contains("html")
373 || content_type.contains("json")
374 || content_type.contains("xml")
375 || content_type.contains("yaml")
376 || content_type.contains("javascript")
377 }
378
379 fn is_declared_html(content_type: &str) -> bool {
380 matches!(
381 content_type
382 .split(';')
383 .next()
384 .unwrap_or(content_type)
385 .trim()
386 .to_ascii_lowercase()
387 .as_str(),
388 "text/html" | "application/xhtml+xml"
389 )
390 }
391
392 fn render_extracted(
393 url: &str,
394 content_type: &str,
395 format: Format,
396 document: ExtractedDocument,
397 bytes: &[u8],
398 context: &ToolContext,
399 ) -> Result<(String, Option<ArtifactWrite>), ToolError> {
400 if document.kind == DocumentKind::Pdf && format != Format::Raw {
401 let extracted = match format {
402 Format::Text => document.text,
403 Format::Markdown => document.markdown,
404 Format::Raw => unreachable!("raw PDF handled below"),
405 };
406 return bound_text(url, extracted, context);
407 }
408
409 if document.kind == DocumentKind::Media || document.kind == DocumentKind::Pdf {
410 let extension = document
411 .media_extension
412 .unwrap_or(if document.kind == DocumentKind::Pdf {
413 "pdf"
414 } else {
415 "bin"
416 });
417 let artifact = write_binary_artifact(url, extension, bytes, context)?;
418 let relative =
419 codewhale_runtime::artifacts::format_artifact_relative_path(&artifact.relative_path);
420 let label = if document.kind == DocumentKind::Pdf {
421 "PDF"
422 } else {
423 "media"
424 };
425 let content =
426 format!("[{label} response saved to {relative}; content type: {content_type}.]");
427 return Ok((content, Some(artifact)));
428 }
429
430 let content = match format {
431 Format::Raw => decode_response_body(
432 bytes,
433 Some(content_type),
434 document.kind == DocumentKind::Html,
435 )?,
436 Format::Text => document.text,
437 Format::Markdown => document.markdown,
438 };
439 bound_text(url, content, context)
440 }
441
442 fn bound_text(
443 url: &str,
444 content: String,
445 context: &ToolContext,
446 ) -> Result<(String, Option<ArtifactWrite>), ToolError> {
447 let bounded = bound_web_text(
448 content,
449 context,
450 |body| fetch_artifact_id(url, body.as_bytes()),
451 "page",
452 )?;
453 let artifact = bounded.artifact.map(|artifact| ArtifactWrite {
454 session_id: artifact.session_id,
455 absolute_path: artifact.absolute_path,
456 relative_path: artifact.relative_path,
457 byte_size: artifact.byte_size,
458 preview: artifact.preview,
459 });
460 Ok((bounded.content, artifact))
461 }
462
463 fn write_binary_artifact(
464 url: &str,
465 extension: &str,
466 bytes: &[u8],
467 context: &ToolContext,
468 ) -> Result<ArtifactWrite, ToolError> {
469 let artifact_id = fetch_artifact_id(url, bytes);
470 let (absolute_path, relative_path) =
471 codewhale_runtime::artifacts::write_session_artifact_bytes(
472 &context.state_namespace,
473 &artifact_id,
474 extension,
475 bytes,
476 )
477 .map_err(|error| {
478 ToolError::execution_failed(format!(
479 "failed to preserve fetched media artifact: {error}"
480 ))
481 })?;
482 Ok(ArtifactWrite {
483 session_id: context.state_namespace.clone(),
484 absolute_path,
485 relative_path,
486 byte_size: bytes.len() as u64,
487 preview: format!("Fetched {extension} artifact from {url}"),
488 })
489 }
490
491 fn fetch_artifact_id(url: &str, bytes: &[u8]) -> String {
492 let mut identity = Vec::with_capacity(url.len() + bytes.len());
493 identity.extend_from_slice(url.as_bytes());
494 identity.extend_from_slice(bytes);
495 let digest = codewhale_runtime::hashing::sha256_hex(&identity);
496 format!("fetch_{}", &digest[..16])
497 }
498
499 fn artifact_metadata(write: ArtifactWrite) -> Value {
500 json!({
501 "spillover_path": write.absolute_path.display().to_string(),
502 "artifact_session_id": write.session_id,
503 "artifact_relative_path": codewhale_runtime::artifacts::format_artifact_relative_path(&write.relative_path),
504 "artifact_byte_size": write.byte_size,
505 "artifact_preview": write.preview,
506 // Every artifact this tool writes is retrievable evidence, so flag it
507 // for the engine's `activate_result_dependencies` (same contract as
508 // the shell-truncation spillover): the next turn auto-activates
509 // `retrieve_tool_result`. Text overflows name that tool in their
510 // footer; binary PDF/media saves name only the saved-artifact path in
511 // their inline pointer, so this flag is what makes that pointer
512 // actionable rather than a dead end.
513 "evidence_available": true,
514 })
515 }
516
517 fn parse_fields(input: &Value) -> Result<Vec<String>, ToolError> {
518 let Some(values) = input.get("fields") else {
519 return Ok(Vec::new());
520 };
521 let Some(values) = values.as_array() else {
522 return Err(ToolError::invalid_input("`fields` must be an array"));
523 };
524 if values.len() > MAX_JSON_FIELDS {
525 return Err(ToolError::invalid_input(
526 "`fields` accepts at most 32 paths",
527 ));
528 }
529 let mut fields = Vec::new();
530 for value in values {
531 let Some(field) = value.as_str() else {
532 return Err(ToolError::invalid_input(
533 "`fields` entries must be JSONPath strings",
534 ));
535 };
536 let field = field.trim();
537 if field.len() > JSONPATH_MAX_PATH_BYTES {
538 return Err(ToolError::invalid_input(
539 "`fields` JSONPath exceeds 4096 bytes",
540 ));
541 }
542 if !field.is_empty() && !fields.iter().any(|existing| existing == field) {
543 fields.push(field.to_string());
544 }
545 }
546 Ok(fields)
547 }
548
549 fn project_json_fields(
550 body_text: &str,
551 content_type: &str,
552 fields: &[String],
553 ) -> Result<Option<BTreeMap<String, Vec<Value>>>, ToolError> {
554 if fields.is_empty() {
555 return Ok(None);
556 }
557 if !content_type.to_ascii_lowercase().contains("json") {
558 return Err(ToolError::invalid_input(
559 "`fields` can only be used with JSON responses",
560 ));
561 }
562 let body_json: Value = serde_json::from_str(body_text).map_err(|e| {
563 ToolError::execution_failed(format!("response body is not valid JSON for `fields`: {e}"))
564 })?;
565 let mut out = BTreeMap::new();
566 let mut projected_bytes = 2usize;
567 for field in fields {
568 if out.contains_key(field) {
569 continue;
570 }
571 let mut counter = codewhale_util::utils::CountingWriter::new();
572 serde_json::to_writer(&mut counter, field).map_err(|error| {
573 ToolError::execution_failed(format!("JSON projection measurement failed: {error}"))
574 })?;
575 projected_bytes = projected_bytes
576 .saturating_add(counter.count())
577 .saturating_add(1 + usize::from(!out.is_empty()));
578 let remaining = JSONPATH_MAX_BYTES
579 .checked_sub(projected_bytes)
580 .ok_or_else(|| {
581 ToolError::invalid_input(
582 "`fields` projection exceeds 1 MiB; request fewer or narrower fields",
583 )
584 })?;
585 let (matches, bytes) =
586 query_jsonpath_bounded(&body_json, field, remaining).map_err(|e| {
587 ToolError::invalid_input(format!("invalid JSONPath `{field}` in `fields`: {e}"))
588 })?;
589 projected_bytes = projected_bytes.saturating_add(bytes);
590 out.insert(field.clone(), matches);
591 }
592 Ok(Some(out))
593 }
594
595 #[cfg(test)]
596 #[path = "fetch_url/tests.rs"]
597 mod pdf_tests;
598
599 #[cfg(test)]
600 mod tests {
601 use super::*;
602 use crate::tools::spec::ToolContext;
603 use std::path::PathBuf;
604
605 struct ArtifactRootRestore(Option<PathBuf>);
606
607 impl Drop for ArtifactRootRestore {
608 fn drop(&mut self) {
609 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
610 }
611 }
612
613 fn ctx() -> ToolContext {
614 ToolContext::new(PathBuf::from("."))
615 }
616
617 /// `fetch_url` can disclose local data through a URL or query, so it always
618 /// asks: the tool declares `Required`, and the default-ask policy resolves
619 /// that to a prompt rather than running it.
620 #[test]
621 fn fetch_url_always_requires_approval() {
622 use crate::tools::spec::{ApprovalRequirement, ToolSpec};
623 assert_eq!(
624 FetchUrlTool.approval_requirement(),
625 ApprovalRequirement::Required
626 );
627 assert!(
628 FetchUrlTool
629 .capabilities()
630 .contains(&ToolCapability::Network)
631 );
632
633 // Under the default Ask posture that requirement resolves to a prompt,
634 // and only full access (or an explicit bypass) lets it through.
635 use crate::core::authority::{ToolPermission, TurnAuthority, resolve_tool_permission};
636 use codewhale_config::AppMode;
637 use codewhale_execpolicy::ApprovalMode;
638 let requirement = FetchUrlTool.approval_requirement();
639 let ask = TurnAuthority::from_effective_fields(
640 AppMode::Agent,
641 true,
642 false,
643 false,
644 ApprovalMode::Suggest,
645 );
646 assert_eq!(
647 resolve_tool_permission(&ask, requirement, false),
648 ToolPermission::Prompt
649 );
650 let never = TurnAuthority::from_effective_fields(
651 AppMode::Agent,
652 true,
653 false,
654 false,
655 ApprovalMode::Never,
656 );
657 assert_eq!(
658 resolve_tool_permission(&never, requirement, false),
659 ToolPermission::Deny
660 );
661 }
662
663 #[test]
664 fn format_parse_accepts_aliases_and_rejects_unknown() {
665 assert_eq!(Format::parse(Some("markdown")).unwrap(), Format::Markdown);
666 assert_eq!(Format::parse(Some("MD")).unwrap(), Format::Markdown);
667 assert_eq!(Format::parse(Some("text")).unwrap(), Format::Text);
668 assert_eq!(Format::parse(Some("raw")).unwrap(), Format::Raw);
669 assert_eq!(Format::parse(None).unwrap(), Format::Markdown);
670 assert!(Format::parse(Some("yaml")).is_err());
671 }
672
673 #[test]
674 fn raw_text_uses_declared_charset_and_rejects_nul_binary() {
675 let document = || ExtractedDocument {
676 kind: DocumentKind::Text,
677 title: None,
678 text: String::new(),
679 markdown: String::new(),
680 cleaned_html: None,
681 pdf_pages: None,
682 media_extension: None,
683 };
684 let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode("café");
685 let (content, artifact) = render_extracted(
686 "https://example.com/plain",
687 "text/plain; charset=windows-1252",
688 Format::Raw,
689 document(),
690 &bytes,
691 &ctx(),
692 )
693 .expect("decode raw text");
694 assert_eq!(content, "café");
695 assert!(artifact.is_none());
696
697 let error = render_extracted(
698 "https://example.com/not-text",
699 "text/plain",
700 Format::Raw,
701 document(),
702 b"binary\0payload",
703 &ctx(),
704 )
705 .expect_err("raw text must retain the binary guard");
706 assert!(error.to_string().contains("NUL bytes"));
707 }
708
709 #[test]
710 fn textual_and_html_fallback_classification_is_exact() {
711 assert!(is_declared_textual("Application/JSON; charset=utf-8"));
712 assert!(is_declared_html("TEXT/HTML; charset=gbk"));
713 assert!(!is_declared_html("text/plain; note=text/html"));
714 assert!(!is_declared_textual("application/octet-stream"));
715 }
716
717 #[test]
718 fn route_budget_overflow_round_trips_through_session_artifact() {
719 let _lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
720 .lock()
721 .unwrap_or_else(|error| error.into_inner());
722 let tmp = tempfile::tempdir().unwrap();
723 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
724 tmp.path().join("sessions"),
725 ));
726 let _restore = ArtifactRootRestore(prior);
727 let context = ToolContext::new(".")
728 .with_state_namespace("fetch-overflow")
729 .with_route_context_window(10_000);
730 let full = "Whale content. ".repeat(200);
731
732 let (inline, artifact) =
733 bound_text("https://example.com/large", full.clone(), &context).unwrap();
734 let artifact = artifact.expect("overflow artifact");
735
736 assert!(inline.contains("retrieve_tool_result"));
737 assert!(inline.chars().count() <= inline_char_budget(&context));
738 assert_eq!(
739 std::fs::read_to_string(&artifact.absolute_path).unwrap(),
740 full
741 );
742 // The footer names `retrieve_tool_result` as the recovery path; the
743 // evidence flag is what makes the engine auto-activate that tool on
744 // the next turn, so the named tool is actually present.
745 let metadata = artifact_metadata(artifact);
746 assert_eq!(
747 metadata.get("evidence_available"),
748 Some(&json!(true)),
749 "artifact metadata must flag retrievable evidence:\n{metadata}"
750 );
751 }
752
753 #[test]
754 fn project_json_fields_returns_requested_jsonpath_matches() {
755 let fields = vec!["$.items[*].name".to_string(), "$.count".to_string()];
756 let projected = project_json_fields(
757 r#"{"items":[{"name":"alpha"},{"name":"beta"}],"count":2}"#,
758 "application/json",
759 &fields,
760 )
761 .expect("project")
762 .expect("some");
763
764 assert_eq!(
765 projected.get("$.items[*].name").unwrap(),
766 &vec![json!("alpha"), json!("beta")]
767 );
768 assert_eq!(projected.get("$.count").unwrap(), &vec![json!(2)]);
769 }
770
771 #[test]
772 fn project_json_fields_rejects_non_json_content_type() {
773 let fields = vec!["$.name".to_string()];
774 let err = project_json_fields("{}", "text/plain", &fields).expect_err("must reject");
775 assert!(format!("{err}").contains("JSON responses"));
776 }
777
778 #[tokio::test]
779 async fn rejects_non_http_schemes() {
780 let tool = FetchUrlTool;
781 let res = tool
782 .execute(json!({"url": "file:///etc/passwd"}), &ctx())
783 .await;
784 let err = res.unwrap_err();
785 assert!(format!("{err:?}").contains("http"));
786 }
787
788 #[tokio::test]
789 async fn rejects_empty_url() {
790 let tool = FetchUrlTool;
791 let res = tool.execute(json!({"url": " "}), &ctx()).await;
792 assert!(res.is_err());
793 }
794
795 #[tokio::test]
796 async fn rejects_missing_url() {
797 let tool = FetchUrlTool;
798 let res = tool.execute(json!({}), &ctx()).await;
799 assert!(res.is_err());
800 }
801
802 #[tokio::test]
803 async fn rejects_localhost_hostname() {
804 let tool = FetchUrlTool;
805 let res = tool
806 .execute(json!({"url": "http://localhost:8080/admin"}), &ctx())
807 .await;
808 let err = res.unwrap_err();
809 assert!(format!("{err}").contains("localhost"));
810 }
811
812 #[tokio::test]
813 async fn network_policy_denies_blocked_host() {
814 use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider};
815 let policy = NetworkPolicy {
816 default: Decision::Deny.into(),
817 allow: vec!["api.deepseek.com".to_string()],
818 deny: vec![],
819 proxy: Vec::new(),
820 proxy_fake_ip_cidrs: Vec::new(),
821 audit: false,
822 };
823 let decider = NetworkPolicyDecider::new(policy, None);
824 let ctx = ToolContext::new(PathBuf::from(".")).with_network_policy(decider);
825 let tool = FetchUrlTool;
826 let res = tool
827 .execute(json!({"url": "https://example.com/foo"}), &ctx)
828 .await;
829 let err = res.expect_err("blocked host should fail");
830 assert!(format!("{err}").contains("blocked"));
831 }
832
833 #[tokio::test]
834 async fn proxy_opt_in_does_not_allow_restricted_ip_literal() {
835 use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider};
836
837 let policy = NetworkPolicy {
838 default: Decision::Allow.into(),
839 allow: Vec::new(),
840 deny: Vec::new(),
841 proxy: vec!["198.18.0.1".to_string()],
842 proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()],
843 audit: false,
844 };
845 let decider = NetworkPolicyDecider::new(policy, None);
846 let ctx = ToolContext::new(PathBuf::from(".")).with_network_policy(decider);
847 let tool = FetchUrlTool;
848
849 let err = tool
850 .execute(json!({"url": "http://198.18.0.1/status"}), &ctx)
851 .await
852 .expect_err("literal restricted IP URLs must stay blocked");
853
854 assert!(format!("{err}").contains("IP 198.18.0.1 is a restricted address"));
855 }
856 }
857
857 lines RUST