diff --git a/crates/plugin-web/src/fetch.rs b/crates/plugin-web/src/fetch.rs index 5e77bce..57695c5 100644 --- a/crates/plugin-web/src/fetch.rs +++ b/crates/plugin-web/src/fetch.rs @@ -336,7 +336,7 @@ impl WebFetch { "type": "integer", "minimum": 1, "maximum": ceiling, - "description": "Maximum number of characters of text to return for this call. Clamped to the configured ceiling. Longer text is truncated on a character boundary and the result is flagged as truncated." + "description": "Maximum number of characters of text to return for this call. Clamped to the configured ceiling. Defaults to a tenth of the model's context window, at about four characters a token, up to that ceiling. Longer text is truncated on a character boundary and the result is flagged as truncated." }, "raw": { "type": "boolean", @@ -355,7 +355,7 @@ impl WebFetch { /// Returns a [`ToolError`] for invalid arguments, a URL the policy /// refuses outright, or a fetch task that did not finish. A page the /// fetch could not render is a soft, trusted output instead. - pub(crate) async fn call(&self, args: serde_json::Value) -> CallResult { + pub(crate) async fn call(&self, args: serde_json::Value, model: Option<&str>) -> CallResult { let url = args .get("url") .and_then(serde_json::Value::as_str) @@ -367,8 +367,9 @@ impl WebFetch { })?; // A per-call `max_chars` is clamped to the configured ceiling; absent, - // the ceiling itself applies. - let max_chars = parse_max_chars(&args, self.client.config.max_chars())?; + // the default for the calling model applies. + let ceiling = self.client.config.max_chars(); + let max_chars = parse_max_chars(&args, ceiling, default_max_chars(model, ceiling))?; let raw = parse_raw(&args)?; @@ -387,17 +388,43 @@ impl WebFetch { } } -/// Parses the optional `max_chars` argument, clamped to `ceiling`. +/// The `max_chars` a call that leaves it out gets: a tenth of the calling +/// model's context window, at about four characters a token, so two fifths +/// of a character per token, and never over `ceiling`. `model` is the JSON +/// text [`ToolCall::model`] lends, and a call with no model, as from a +/// script, or with no positive whole `context` in it, gets `ceiling`. +/// +/// [`ToolCall::model`]: runvil_plugin_sdk::ToolCall::model +fn default_max_chars(model: Option<&str>, ceiling: usize) -> usize { + let context = model + .and_then(|model| serde_json::from_str::(model).ok()) + .and_then(|model| model.get("context")?.as_u64()) + .filter(|context| *context > 0); + let Some(context) = context else { + return ceiling; + }; + let chars = context.saturating_mul(2) / 5; + usize::try_from(chars) + .unwrap_or(usize::MAX) + .clamp(1, ceiling) +} + +/// Parses the optional `max_chars` argument, clamped to `ceiling`, and +/// `default` when the call leaves it out. /// /// # Errors /// Returns an invalid-arguments [`ToolError`] if `max_chars` is present but is /// not a positive integer. -fn parse_max_chars(args: &serde_json::Value, ceiling: usize) -> Result { +fn parse_max_chars( + args: &serde_json::Value, + ceiling: usize, + default: usize, +) -> Result { let Some(value) = args.get("max_chars") else { - return Ok(ceiling); + return Ok(default); }; if value.is_null() { - return Ok(ceiling); + return Ok(default); } let n = value.as_u64().filter(|n| *n >= 1).ok_or_else(|| { ToolError::new( diff --git a/crates/plugin-web/src/fetch/tests-body.rs b/crates/plugin-web/src/fetch/tests-body.rs index 83f3a8b..2d560d7 100644 --- a/crates/plugin-web/src/fetch/tests-body.rs +++ b/crates/plugin-web/src/fetch/tests-body.rs @@ -18,7 +18,7 @@ async fn oversized_html_is_refused() { let url = format!("http://localhost:{port}/large"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an oversized HTML body is a soft return") .text() @@ -41,7 +41,7 @@ async fn declared_content_length_over_cap_is_refused_before_read() { let url = format!("http://localhost:{port}/liar"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a declared Content-Length over the cap is a soft return") .text() @@ -64,7 +64,7 @@ async fn gzip_bomb_refused_on_decompressed_count() { let url = format!("http://localhost:{port}/gzip"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a gzip body that decompresses past the cap is a soft return") .text() @@ -82,7 +82,7 @@ async fn a_short_article_below_a_long_menu_is_returned_and_raw_returns_the_menu( let url = format!("http://localhost:{port}/archive"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an archive fetch must succeed") .text() @@ -99,7 +99,7 @@ async fn a_short_article_below_a_long_menu_is_returned_and_raw_returns_the_menu( assert!(!body.contains("Archive entry"), "got: {body}"); let out = tool - .call(serde_json::json!({ "url": url, "raw": true })) + .call(serde_json::json!({ "url": url, "raw": true }), None) .await .expect("a raw archive fetch must succeed") .text() @@ -125,7 +125,7 @@ async fn a_page_with_no_article_over_max_chars_returns_the_cut_whole_page() { let url = format!("http://localhost:{port}/topics"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a topics fetch must succeed") .text() @@ -148,7 +148,7 @@ async fn a_short_article_under_leading_spaces_is_returned_when_they_push_the_pag let url = format!("http://localhost:{port}/padded"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a padded fetch must succeed") .text() @@ -173,7 +173,10 @@ async fn text_over_max_chars_is_truncated_on_char_boundary() { let max_chars = 25usize; let url = format!("http://localhost:{port}/unicode"); let out = tool - .call(serde_json::json!({ "url": url, "max_chars": max_chars })) + .call( + serde_json::json!({ "url": url, "max_chars": max_chars }), + None, + ) .await .expect("a unicode fetch through allow_exact must succeed") .text() @@ -198,7 +201,10 @@ async fn per_call_max_chars_is_clamped_to_the_configured_ceiling() { let url = format!("http://localhost:{port}/plainbig"); let out = tool - .call(serde_json::json!({ "url": url, "max_chars": 1_000_000 })) + .call( + serde_json::json!({ "url": url, "max_chars": 1_000_000 }), + None, + ) .await .expect("a plain fetch must succeed") .text() @@ -225,7 +231,7 @@ async fn body_one_byte_under_cap_succeeds_untruncated() { let url = format!("http://localhost:{port}/"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a body one byte under the cap must be accepted") .text() @@ -243,7 +249,7 @@ async fn html_is_extracted_and_reports_readability() { let url = format!("http://localhost:{port}/"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a loopback html fetch must succeed") .text() @@ -261,7 +267,7 @@ async fn raw_forces_whole_page_render_keeping_table() { let url = format!("http://localhost:{port}/table"); let out = tool - .call(serde_json::json!({ "url": url, "raw": true })) + .call(serde_json::json!({ "url": url, "raw": true }), None) .await .expect("a raw table fetch must succeed") .text() @@ -282,7 +288,7 @@ async fn json_is_returned_verbatim_as_plain() { let url = format!("http://localhost:{port}/json"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a json fetch must succeed") .text() @@ -304,7 +310,7 @@ async fn oversized_json_is_hard_refused_not_truncated() { let url = format!("http://localhost:{port}/jsonbig"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an oversized json body is a soft return") .text() @@ -326,7 +332,7 @@ async fn flat_text_body_read_failure_is_soft() { // hard error: identical to the HTML and structured routes. A `text()` // return proves the outcome was soft trusted output. let outcome = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a mid-stream flat-text failure must be a soft return, not a hard error"); assert!( @@ -347,7 +353,7 @@ async fn unrecognized_charset_is_refused_naming_the_label() { let url = format!("http://localhost:{port}/badcharset"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an unrecognized charset is a soft return") .text() @@ -363,7 +369,7 @@ async fn pdf_is_refused_naming_the_type() { let url = format!("http://localhost:{port}/pdf"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a pdf response is a soft return") .text() @@ -379,7 +385,7 @@ async fn octet_stream_is_refused() { let url = format!("http://localhost:{port}/octet"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an octet-stream response is a soft return") .text() @@ -395,7 +401,7 @@ async fn absent_content_type_is_refused() { let url = format!("http://localhost:{port}/notype"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an absent content type is a soft return") .text() @@ -411,7 +417,7 @@ async fn latin1_page_decodes_with_declared_charset() { let url = format!("http://localhost:{port}/latin1"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a latin-1 fetch must succeed") .text() @@ -434,7 +440,7 @@ async fn plain_text_over_cap_is_truncated_not_refused() { let url = format!("http://localhost:{port}/plainbig"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("an oversized flat-text body must be truncated, not refused") .text() diff --git a/crates/plugin-web/src/fetch/tests-golden.rs b/crates/plugin-web/src/fetch/tests-golden.rs index 6cf1702..88282a4 100644 --- a/crates/plugin-web/src/fetch/tests-golden.rs +++ b/crates/plugin-web/src/fetch/tests-golden.rs @@ -55,7 +55,10 @@ async fn spawn_golden_server() -> u16 { async fn fetch(path: &str, raw: bool) -> String { let port = spawn_golden_server().await; let out = loopback_tool(port) - .call(serde_json::json!({ "url": format!("http://localhost:{port}{path}"), "raw": raw })) + .call( + serde_json::json!({ "url": format!("http://localhost:{port}{path}"), "raw": raw }), + None, + ) .await .expect("a loopback fetch of a golden page must succeed") .text() diff --git a/crates/plugin-web/src/fetch/tests-policy.rs b/crates/plugin-web/src/fetch/tests-policy.rs index 07100f0..371b089 100644 --- a/crates/plugin-web/src/fetch/tests-policy.rs +++ b/crates/plugin-web/src/fetch/tests-policy.rs @@ -19,7 +19,7 @@ async fn slow_server_past_total_timeout_yields_timeout() { let url = format!("http://localhost:{port}/slow"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a timeout is a soft (recoverable) return") .text() @@ -37,7 +37,7 @@ async fn request_omits_the_cookie_and_authorization_headers() { let tool = loopback_tool(port); let url = format!("http://localhost:{port}/record"); - tool.call(serde_json::json!({ "url": url })) + tool.call(serde_json::json!({ "url": url }), None) .await .expect("a loopback fetch through allow_exact must succeed"); @@ -58,7 +58,7 @@ async fn no_credential_or_referer_survives_a_redirect() { // A query-bearing source URL redirecting to a distinct allowed path: the // target must receive no Cookie, Authorization, or Referer. let url = format!("http://localhost:{port}/redir-record?secret=leak-me"); - tool.call(serde_json::json!({ "url": url })) + tool.call(serde_json::json!({ "url": url }), None) .await .expect("a redirect between loopback paths must succeed"); @@ -82,7 +82,7 @@ async fn fetch_returns_provenance_line_then_content() { let url = format!("http://localhost:{port}/"); let out = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a loopback fetch through allow_exact must succeed") .text() @@ -100,7 +100,7 @@ async fn redirect_to_internal_is_refused_and_target_untouched() { let url = format!("http://localhost:{port}/redir"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a redirect-target policy refusal is a soft (recoverable) return") .text() @@ -161,7 +161,7 @@ async fn redirect_to_internal_via_injected_lookup_never_contacts_target() { let url = format!("http://allowed.test:{redir_port}/go"); // The outcome may be a hard error (the redirect address is blocked) or a // soft return, but it must never include the internal target's body. - if let Ok(output) = tool.call(serde_json::json!({ "url": url })).await { + if let Ok(output) = tool.call(serde_json::json!({ "url": url }), None).await { assert!( !output.text().contains("reached the internal target"), "the internal target body must never be returned" @@ -193,7 +193,7 @@ async fn call_rejects_bad_urls_before_network() { for (raw, reason) in hard_cases { let err = tool - .call(serde_json::json!({ "url": raw })) + .call(serde_json::json!({ "url": raw }), None) .await .expect_err(&format!("expected {raw} to be refused before any network")); assert!( @@ -207,7 +207,7 @@ async fn call_rejects_bad_urls_before_network() { } let soft = tool - .call(serde_json::json!({ "url": "http://example.com/" })) + .call(serde_json::json!({ "url": "http://example.com/" }), None) .await .expect("blocked http scheme must be soft tool text") .text() @@ -225,7 +225,7 @@ async fn soft_return_on_404() { let url = format!("http://localhost:{port}/notfound"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a 404 must be a soft return") .text() @@ -241,7 +241,7 @@ async fn soft_return_on_500() { let url = format!("http://localhost:{port}/error500"); let result = tool - .call(serde_json::json!({ "url": url })) + .call(serde_json::json!({ "url": url }), None) .await .expect("a 500 must be a soft return") .text() @@ -255,7 +255,7 @@ async fn blocked_url_still_hard_fails() { let tool = default_tool(); let err = tool - .call(serde_json::json!({ "url": "https://1.2.3.4/secret" })) + .call(serde_json::json!({ "url": "https://1.2.3.4/secret" }), None) .await .expect_err("a bare IP literal URL must still be a hard error"); diff --git a/crates/plugin-web/src/fetch/tests.rs b/crates/plugin-web/src/fetch/tests.rs index 2b6302b..8f8fd7c 100644 --- a/crates/plugin-web/src/fetch/tests.rs +++ b/crates/plugin-web/src/fetch/tests.rs @@ -26,7 +26,7 @@ use runvil_plugin_sdk::BoxFuture; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio::runtime::Handle; -use super::{FetchClient, WebFetch, on_blocking_thread}; +use super::{FetchClient, WebFetch, default_max_chars, on_blocking_thread, parse_max_chars}; use crate::config::{FetchConfig, FetchConfigBuilder}; use crate::resolver::Lookup; @@ -500,7 +500,7 @@ async fn a_fetch_whose_call_is_dropped_aborts_its_spawned_task() { let tool = loopback_tool(port); let url = format!("http://localhost:{port}/hold"); - let call = tool.call(serde_json::json!({ "url": url })); + let call = tool.call(serde_json::json!({ "url": url }), None); tokio::select! { result = call => panic!("the held fetch must not finish: {result:?}"), requested = requested_rx => requested.expect("the server saw the request"), @@ -512,6 +512,57 @@ async fn a_fetch_whose_call_is_dropped_aborts_its_spawned_task() { .expect("the server reports the hang-up"); } +#[test] +fn a_call_that_leaves_max_chars_out_gets_two_fifths_of_a_char_per_token_of_its_models_context() { + let ceiling = 40_000; + let model = |context: &str| format!(r#"{{"name":"m","context":{context},"thinking":"never"}}"#); + + assert_eq!(default_max_chars(Some(&model("8000")), ceiling), 3_200); + assert_eq!(default_max_chars(Some(&model("32768")), ceiling), 13_107); + assert_eq!(default_max_chars(Some(&model("100000")), ceiling), ceiling); + assert_eq!(default_max_chars(Some(&model("1000000")), ceiling), ceiling); + assert_eq!( + default_max_chars(Some(&model("18446744073709551615")), ceiling), + ceiling + ); + assert_eq!(default_max_chars(Some(&model("1")), ceiling), 1); +} + +#[test] +fn a_call_with_no_model_or_no_usable_context_gets_the_ceiling() { + let ceiling = 40_000; + for model in [ + None, + Some(""), + Some("not json"), + Some("{}"), + Some(r#"{"context":0}"#), + Some(r#"{"context":-8000}"#), + Some(r#"{"context":8000.5}"#), + Some(r#"{"context":"8000"}"#), + Some(r#"{"context":null}"#), + ] { + assert_eq!( + default_max_chars(model, ceiling), + ceiling, + "model: {model:?}" + ); + } +} + +#[test] +fn a_max_chars_the_call_names_wins_over_the_default_up_to_the_ceiling() { + let parse = |args: serde_json::Value| { + parse_max_chars(&args, 40_000, 3_200).expect("the arguments are valid") + }; + + assert_eq!(parse(serde_json::json!({})), 3_200); + assert_eq!(parse(serde_json::json!({ "max_chars": null })), 3_200); + assert_eq!(parse(serde_json::json!({ "max_chars": 20_000 })), 20_000); + assert_eq!(parse(serde_json::json!({ "max_chars": 100 })), 100); + assert_eq!(parse(serde_json::json!({ "max_chars": 1_000_000 })), 40_000); +} + #[path = "tests-body.rs"] mod body; #[path = "tests-golden.rs"] diff --git a/crates/plugin-web/src/lib.rs b/crates/plugin-web/src/lib.rs index 204cc3c..99d137d 100644 --- a/crates/plugin-web/src/lib.rs +++ b/crates/plugin-web/src/lib.rs @@ -41,8 +41,13 @@ //! The answer is trusted output: three header lines, then a blank line, //! then the text. The header lines are `url:`, the URL the text came //! from once every redirect was followed, `truncated:`, and -//! `extraction:`, how the text was made. The text is cut at 40,000 -//! characters, or at `max_chars` when the call names fewer. +//! `extraction:`, how the text was made. The text is cut at `max_chars` +//! characters, which is never over 40,000. A call that leaves `max_chars` +//! out gets a tenth of the context window of the model that asked for it, +//! at about four characters a token, so two fifths of a character per +//! token: 3,200 characters for a window of 8,000 tokens, and 40,000 for one +//! of 100,000 tokens or more. A call with no model, such as one a script +//! makes, gets 40,000. //! //! A call fails as invalid arguments when its arguments do not match the //! tool's parameters, and when the fetch policy can never fetch its URL: diff --git a/crates/plugin-web/src/web-tests.rs b/crates/plugin-web/src/web-tests.rs index bced246..26899d0 100644 --- a/crates/plugin-web/src/web-tests.rs +++ b/crates/plugin-web/src/web-tests.rs @@ -298,7 +298,7 @@ fn the_fetch_tools_schema_is_the_one_a_model_reads_under_the_default_policy() { "type": "integer", "minimum": 1, "maximum": 40_000, - "description": "Maximum number of characters of text to return for this call. Clamped to the configured ceiling. Longer text is truncated on a character boundary and the result is flagged as truncated." + "description": "Maximum number of characters of text to return for this call. Clamped to the configured ceiling. Defaults to a tenth of the model's context window, at about four characters a token, up to that ceiling. Longer text is truncated on a character boundary and the result is flagged as truncated." }, "raw": { "type": "boolean", @@ -452,6 +452,57 @@ fn a_fetch_answers_a_page_as_trusted_markdown_under_its_header() { assert!(text.contains("first substantial paragraph"), "{text}"); } +/// The length of the text under the header of a fetch's output, and +/// whether the header says it was cut. +fn text_chars(output: &ToolOutput) -> (usize, bool) { + let (header, text) = output + .text() + .split_once("\n\n") + .expect("a blank line ends the header"); + (text.chars().count(), header.contains("truncated: true")) +} + +/// A call that leaves `max_chars` out is cut to fit the model that asked +/// for it, which the Host lends with the call, so a model with a small +/// window gets less than one with a large window or a script. +#[test] +fn a_fetch_that_leaves_max_chars_out_fits_the_context_of_the_model_that_asked() { + let page: &'static str = format!( + "

Long

{}
", + "

A sentence of the long article that a model asked to read.

".repeat(500) + ) + .leak(); + // Each server answers one connection, so each call gets its own. + let url = || serve(Reply::Page("200 OK", page)).0; + let loaded = loaded_for_loopback(); + let pack = loaded.new_pack(PACK).expect("the Pack instance is made"); + let call = |mut arguments: Value, model: Option<&str>| { + arguments["url"] = Value::String(url()); + let call = pack.start("fetch", &arguments.to_string()); + let call = match model { + Some(model) => call.with_model(model), + None => call.with_caller(Caller::Script), + }; + let output = call + .run() + .expect("the call follows the contract") + .expect("the fetch succeeds"); + text_chars(&output) + }; + let small = + r#"{"server":"s","name":"small","description":"","context":8000,"thinking":"never"}"#; + let large = + r#"{"server":"s","name":"large","description":"","context":1000000,"thinking":"never"}"#; + + assert_eq!(call(json!({}), Some(small)), (3_200, true)); + assert_eq!(call(json!({}), Some(large)), (LOOPBACK_MAX_CHARS, true)); + assert_eq!(call(json!({}), None), (LOOPBACK_MAX_CHARS, true)); + assert_eq!( + call(json!({ "max_chars": 5_000 }), Some(small)), + (5_000, true) + ); +} + #[test] fn a_page_that_answers_an_http_error_is_a_trusted_output_that_says_so() { let (url, _events) = serve(Reply::Page( diff --git a/crates/plugin-web/src/web.rs b/crates/plugin-web/src/web.rs index 6ce5e0b..d7d9875 100644 --- a/crates/plugin-web/src/web.rs +++ b/crates/plugin-web/src/web.rs @@ -147,7 +147,7 @@ impl Pack for WebPack { // value. let result = match arguments(call.arguments()) { Ok(args) => match call.tool() { - FETCH => self.fetch.call(args).await, + FETCH => self.fetch.call(args, call.model()).await, SEARCH => self.search.call(args, call.resources()).await, other => Err(ToolError::new( ToolErrorKind::Other,