返回 CodeWhale
provider_native_search.rs
根目录 / crates / engine / src / client / provider_native_search.rs
1 //! Narrow provider-native web-search client.
2 //!
3 //! This adapter reuses the active route's authenticated HTTP client without
4 //! exposing credentials to tool code. Route capability facts decide whether
5 //! the adapter is attached; this module only speaks the three documented
6 //! first-party wire contracts.
7
8 use anyhow::{Context, Result, bail};
9 use reqwest::header::{HeaderName, HeaderValue};
10 use serde_json::{Value, json};
11
12 use codewhale_config::ProviderKind;
13
14 use super::wire::read_bounded_response_bytes;
15 use super::{CodewhaleClient, api_url, responses_api_url};
16
17 mod zai;
18
19 mod kimi;
20
21 #[derive(Clone)]
22 pub struct ProviderNativeSearchClient {
23 pub(super) inner: CodewhaleClient,
24 }
25
26 #[derive(Clone)]
27 pub struct ProviderNativeSearchRequest {
28 pub query: String,
29 pub max_results: u8,
30 pub domains: Vec<String>,
31 }
32
33 #[derive(Clone, PartialEq, Eq)]
34 pub struct ProviderNativeCitation {
35 pub url: String,
36 pub title: String,
37 pub snippet: Option<String>,
38 pub published: Option<String>,
39 }
40
41 #[derive(Clone, PartialEq, Eq)]
42 pub struct ProviderNativeSearchResponse {
43 pub answer: Option<String>,
44 pub citations: Vec<ProviderNativeCitation>,
45 /// The provider stopped the answer at its output limit (#6508).
46 pub truncated: bool,
47 }
48
49 /// What the Anthropic and MiMo adapters requested before #6508, kept for a
50 /// model whose output ceiling the catalogue does not document.
51 const PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS: u32 = 2_048;
52
53 /// Ceiling on the output a native-search request asks for (#6508). These are
54 /// single-shot, non-streaming requests: nothing arrives until the whole answer
55 /// is generated, so web_search gives the attempt enough time to generate what
56 /// was asked for (`tools::web_search::native_answer_time_budget`). The clamp
57 /// bounds that wait: at the budget's assumed generation rate, 8,192 tokens is
58 /// about four minutes before a stalled provider falls back to another backend.
59 /// It is not a context or API limit; the model's own output ceiling still
60 /// applies beneath it.
61 const NATIVE_SEARCH_MAX_OUTPUT_TOKENS: u32 = 8_192;
62
63 impl ProviderNativeSearchClient {
64 #[must_use]
65 pub fn new(inner: CodewhaleClient) -> Option<Self> {
66 matches!(
67 inner.api_provider,
68 ProviderKind::Openai
69 | ProviderKind::Anthropic
70 | ProviderKind::Xai
71 | ProviderKind::XiaomiMimo
72 | ProviderKind::Zai
73 | ProviderKind::ModelstudioTokenPlan
74 | ProviderKind::Deepseek
75 | ProviderKind::Moonshot
76 )
77 .then_some(Self { inner })
78 }
79
80 #[must_use]
81 pub fn provider(&self) -> ProviderKind {
82 self.inner.api_provider
83 }
84
85 #[must_use]
86 pub fn model(&self) -> &str {
87 &self.inner.default_model
88 }
89
90 /// Output tokens to request for a native search answer: the search
91 /// model's route ceiling up to [`NATIVE_SEARCH_MAX_OUTPUT_TOKENS`]. When
92 /// the catalogue does not document that ceiling, keep `fallback` (the
93 /// value this adapter always sent) rather than risk a provider rejecting
94 /// a larger request.
95 #[must_use]
96 pub(super) fn answer_output_tokens(&self, fallback: u32) -> u32 {
97 let model = &self.inner.default_model;
98 let route_cap = self.inner.effective_max_output_tokens(model);
99 let documented = matches!(
100 crate::route_budget::output_ceiling_source(self.inner.api_provider, model),
101 crate::route_budget::OutputCeilingSource::Documented(_)
102 );
103 let wanted = if documented {
104 NATIVE_SEARCH_MAX_OUTPUT_TOKENS
105 } else {
106 fallback
107 };
108 wanted.min(route_cap)
109 }
110
111 /// Output tokens this client asks for per native-search answer, or `None`
112 /// for adapters that leave the answer length to the provider's default
113 /// (the Responses and Z.ai adapters). web_search sizes the attempt's time
114 /// budget from this, so the request and the wait cannot disagree.
115 #[must_use]
116 pub fn requested_answer_output_tokens(&self) -> Option<u32> {
117 match self.inner.api_provider {
118 ProviderKind::Anthropic | ProviderKind::XiaomiMimo => {
119 Some(self.answer_output_tokens(PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS))
120 }
121 ProviderKind::Moonshot => {
122 Some(self.answer_output_tokens(kimi::PRIOR_NATIVE_SEARCH_MAX_COMPLETION_TOKENS))
123 }
124 _ => None,
125 }
126 }
127
128 #[must_use]
129 pub fn base_url(&self) -> &str {
130 &self.inner.base_url
131 }
132
133 #[must_use]
134 pub fn host(&self) -> Option<String> {
135 reqwest::Url::parse(&self.inner.base_url)
136 .ok()
137 .and_then(|url| url.host_str().map(str::to_ascii_lowercase))
138 }
139
140 #[must_use]
141 pub fn cache_identity(&self) -> String {
142 format!(
143 "provider-native://{}/{}/{}",
144 self.inner.api_provider.as_str(),
145 self.host().as_deref().unwrap_or("unknown-host"),
146 self.inner.default_model
147 )
148 }
149
150 #[must_use]
151 pub const fn maximum_domain_count(&self) -> Option<usize> {
152 match self.inner.api_provider {
153 ProviderKind::Xai => Some(5),
154 ProviderKind::Openai => Some(100),
155 ProviderKind::Anthropic => None,
156 _ => Some(0),
157 }
158 }
159
160 pub async fn search(
161 &self,
162 request: &ProviderNativeSearchRequest,
163 ) -> Result<ProviderNativeSearchResponse> {
164 // This adapter performs model-backed inference directly instead of
165 // calling `CodewhaleClient::create_message*`. It must therefore join
166 // the same attached-run ownership boundary explicitly. The guard is
167 // retained through response decode so a relay writer cannot start
168 // while this result is still able to feed the interactive turn.
169 let _inference = self.inner.acquire_remote_control_inference_permit().await;
170 if self.inner.api_provider == ProviderKind::Moonshot {
171 // Kimi/Moonshot runs a bounded multi-round agentic search with its
172 // own request/reply loop, so it cannot share the single-shot body
173 // dispatch below. It still runs under the inference permit above.
174 let mut parsed = kimi::search(self, request).await?;
175 parsed.citations.truncate(usize::from(request.max_results));
176 return Ok(parsed);
177 }
178 let body = match self.inner.api_provider {
179 ProviderKind::Openai => build_responses_search_body(
180 &self.inner.default_model,
181 request,
182 ResponsesSearchDialect::Openai,
183 ),
184 ProviderKind::Xai => build_responses_search_body(
185 &self.inner.default_model,
186 request,
187 ResponsesSearchDialect::Xai,
188 ),
189 ProviderKind::ModelstudioTokenPlan => build_responses_search_body(
190 &self.inner.default_model,
191 request,
192 ResponsesSearchDialect::ModelStudio,
193 ),
194 ProviderKind::Deepseek => build_responses_search_body(
195 &self.inner.default_model,
196 request,
197 ResponsesSearchDialect::Deepseek,
198 ),
199 ProviderKind::Anthropic => build_anthropic_search_body(
200 &self.inner.default_model,
201 request,
202 self.requested_answer_output_tokens()
203 .unwrap_or(PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS),
204 ),
205 ProviderKind::XiaomiMimo => build_mimo_search_body(
206 &self.inner.default_model,
207 request,
208 self.requested_answer_output_tokens()
209 .unwrap_or(PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS),
210 ),
211 ProviderKind::Zai => zai::build_body(request, &self.inner.base_url)?,
212 _ => bail!("active provider has no native web-search adapter"),
213 };
214 let url = match self.inner.api_provider {
215 ProviderKind::Openai | ProviderKind::Xai | ProviderKind::ModelstudioTokenPlan => {
216 responses_api_url(
217 &self.inner.base_url,
218 codewhale_config::responses_dialect::ResponsesPathPolicy::VersionedResponses,
219 )
220 }
221 ProviderKind::Deepseek => responses_api_url(
222 &self.inner.base_url,
223 codewhale_config::responses_dialect::bound_responses_path(
224 ProviderKind::Deepseek,
225 &self.inner.base_url,
226 ),
227 ),
228 ProviderKind::Anthropic => anthropic_messages_url(&self.inner.base_url),
229 ProviderKind::XiaomiMimo => api_url(&self.inner.base_url, "chat/completions"),
230 ProviderKind::Zai => api_url(&self.inner.base_url, "web_search"),
231 _ => unreachable!("provider checked above"),
232 };
233 let body_bytes = serde_json::to_vec(&body)
234 .context("failed to serialize provider-native web-search request")?;
235 let response = self
236 .inner
237 .send_with_retry(|| {
238 self.inner
239 .http_client
240 .post(&url)
241 .header("Accept", "application/json")
242 .body(body_bytes.clone())
243 })
244 .await
245 .context("provider-native web search request failed")?;
246 let payload = read_bounded_json(response, MAX_NATIVE_SEARCH_RESPONSE_BYTES).await?;
247 let mut parsed = match self.inner.api_provider {
248 ProviderKind::Openai
249 | ProviderKind::Xai
250 | ProviderKind::ModelstudioTokenPlan
251 | ProviderKind::Deepseek => parse_responses_search(&payload),
252 ProviderKind::Anthropic => parse_anthropic_search(&payload),
253 ProviderKind::XiaomiMimo => parse_mimo_search(&payload),
254 ProviderKind::Zai => zai::parse(&payload),
255 _ => unreachable!("provider checked above"),
256 };
257 parsed.citations.truncate(usize::from(request.max_results));
258 Ok(parsed)
259 }
260
261 pub(super) async fn post_json(
262 &self,
263 url: &str,
264 body: &Value,
265 headers: &[(HeaderName, HeaderValue)],
266 ) -> Result<Value> {
267 let body_bytes = serde_json::to_vec(&body)
268 .context("failed to serialize provider-native web-search request")?;
269 let headers = headers.to_vec();
270 let response = self
271 .inner
272 .send_with_retry(|| {
273 let mut request = self
274 .inner
275 .http_client
276 .post(url)
277 .header("Accept", "application/json")
278 .body(body_bytes.clone());
279 for (name, value) in &headers {
280 request = request.header(name, value);
281 }
282 request
283 })
284 .await
285 .context("provider-native web search request failed")?;
286 read_bounded_json(response, MAX_NATIVE_SEARCH_RESPONSE_BYTES).await
287 }
288
289 pub(super) async fn get_json(&self, url: &str) -> Result<Value> {
290 let response = self
291 .inner
292 .send_with_retry_total_error_body(
293 super::non_streaming_request_envelope(),
294 || {
295 self.inner
296 .http_client
297 .get(url)
298 .header("Accept", "application/json")
299 },
300 &super::ErrorBodyDisclosure::Full,
301 crate::llm_client::RetryOperation::ReadOnly,
302 )
303 .await
304 .context("provider-native web search request failed")?;
305 read_bounded_json(response, MAX_NATIVE_SEARCH_RESPONSE_BYTES).await
306 }
307 }
308
309 const MAX_NATIVE_SEARCH_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
310
311 async fn read_bounded_json(response: reqwest::Response, max_bytes: usize) -> Result<Value> {
312 let bytes = read_bounded_response_bytes(response, max_bytes)
313 .await
314 .context("failed to read provider-native web search response")?;
315 serde_json::from_slice::<Value>(&bytes)
316 .context("provider-native web search returned invalid JSON")
317 }
318
319 #[derive(Clone, Copy)]
320 enum ResponsesSearchDialect {
321 Openai,
322 Xai,
323 ModelStudio,
324 Deepseek,
325 }
326
327 fn search_prompt(request: &ProviderNativeSearchRequest) -> String {
328 format!(
329 "Search the web for the following query and answer only from web sources. \
330 Use concise prose. Cite as many distinct sources as support the answer, up to {}, \
331 each by the exact URL of a page you retrieved; never guess or construct a URL.\n\n{}",
332 request.max_results, request.query
333 )
334 }
335
336 fn build_responses_search_body(
337 model: &str,
338 request: &ProviderNativeSearchRequest,
339 dialect: ResponsesSearchDialect,
340 ) -> Value {
341 let mut tool = json!({ "type": "web_search" });
342 if !request.domains.is_empty()
343 && matches!(
344 dialect,
345 ResponsesSearchDialect::Openai | ResponsesSearchDialect::Xai
346 )
347 {
348 tool["filters"] = json!({ "allowed_domains": request.domains });
349 }
350 let mut body = json!({
351 "model": model,
352 "input": search_prompt(request),
353 "tools": [tool],
354 });
355 match dialect {
356 ResponsesSearchDialect::Openai => {
357 body["tool_choice"] = json!("required");
358 body["store"] = json!(false);
359 body["include"] = json!(["web_search_call.action.sources"]);
360 }
361 ResponsesSearchDialect::Xai => {
362 body["tool_choice"] = json!("required");
363 }
364 ResponsesSearchDialect::ModelStudio => {
365 body["tool_choice"] = json!("required");
366 }
367 ResponsesSearchDialect::Deepseek => {
368 body["tool_choice"] = json!({ "type": "web_search" });
369 }
370 }
371 body
372 }
373
374 fn build_anthropic_search_body(
375 model: &str,
376 request: &ProviderNativeSearchRequest,
377 max_tokens: u32,
378 ) -> Value {
379 let mut tool = json!({
380 "type": "web_search_20250305",
381 "name": "web_search",
382 "max_uses": 1,
383 });
384 if !request.domains.is_empty() {
385 tool["allowed_domains"] = json!(request.domains);
386 }
387 json!({
388 "model": model,
389 "max_tokens": max_tokens,
390 "messages": [{ "role": "user", "content": search_prompt(request) }],
391 "tools": [tool],
392 })
393 }
394
395 fn build_mimo_search_body(
396 model: &str,
397 request: &ProviderNativeSearchRequest,
398 max_completion_tokens: u32,
399 ) -> Value {
400 json!({
401 "model": model,
402 "messages": [{ "role": "user", "content": search_prompt(request) }],
403 "tools": [{
404 "type": "web_search",
405 "max_keyword": 1,
406 "force_search": true,
407 "limit": request.max_results,
408 }],
409 "tool_choice": "auto",
410 "max_completion_tokens": max_completion_tokens,
411 "stream": false,
412 "thinking": { "type": "disabled" },
413 })
414 }
415
416 fn anthropic_messages_url(base_url: &str) -> String {
417 let base = base_url.trim_end_matches('/');
418 if base.ends_with("/v1") {
419 format!("{base}/messages")
420 } else {
421 format!("{base}/v1/messages")
422 }
423 }
424
425 fn parse_responses_search(payload: &Value) -> ProviderNativeSearchResponse {
426 let mut answer_parts = Vec::new();
427 let mut citations = Vec::new();
428 if let Some(output) = payload.get("output").and_then(Value::as_array) {
429 for item in output {
430 let item_type = item.get("type").and_then(Value::as_str);
431 if item_type == Some("web_search_call")
432 && let Some(action) = item.get("action")
433 {
434 if let Some(sources) = action.get("sources").and_then(Value::as_array) {
435 for source in sources {
436 push_citation(&mut citations, citation_from_value(source, None, None));
437 }
438 }
439 push_citation(&mut citations, citation_from_value(action, None, None));
440 }
441
442 if item_type == Some("message")
443 && let Some(content) = item.get("content").and_then(Value::as_array)
444 {
445 for block in content {
446 if matches!(
447 block.get("type").and_then(Value::as_str),
448 Some("output_text" | "text")
449 ) && let Some(text) = block.get("text").and_then(Value::as_str)
450 && !text.trim().is_empty()
451 {
452 answer_parts.push(text.trim().to_string());
453 }
454 if let Some(annotations) = block.get("annotations").and_then(Value::as_array) {
455 for annotation in annotations {
456 push_citation(
457 &mut citations,
458 citation_from_value(annotation, None, None),
459 );
460 }
461 }
462 }
463 }
464 }
465 }
466 if answer_parts.is_empty()
467 && let Some(output_text) = payload.get("output_text").and_then(Value::as_str)
468 && !output_text.trim().is_empty()
469 {
470 answer_parts.push(output_text.trim().to_string());
471 }
472 for answer in &answer_parts {
473 for citation in citations_from_text(answer) {
474 push_citation(&mut citations, Some(citation));
475 }
476 }
477 if let Some(top_level) = payload.get("citations").and_then(Value::as_array) {
478 for citation in top_level {
479 let parsed = citation
480 .as_str()
481 .and_then(|url| citation_from_url(url, None, None, None))
482 .or_else(|| citation_from_value(citation, None, None));
483 push_citation(&mut citations, parsed);
484 }
485 }
486 // A Responses reply cut at its output limit is `incomplete` with reason
487 // `max_output_tokens`; the text it did return is a partial answer.
488 let truncated = payload.get("status").and_then(Value::as_str) == Some("incomplete")
489 && payload
490 .pointer("/incomplete_details/reason")
491 .and_then(Value::as_str)
492 == Some("max_output_tokens");
493 ProviderNativeSearchResponse {
494 answer: joined_answer(answer_parts),
495 citations,
496 truncated,
497 }
498 }
499
500 fn parse_anthropic_search(payload: &Value) -> ProviderNativeSearchResponse {
501 let mut answer_parts = Vec::new();
502 let mut citations = Vec::new();
503 if let Some(content) = payload.get("content").and_then(Value::as_array) {
504 for block in content {
505 match block.get("type").and_then(Value::as_str) {
506 Some("web_search_tool_result") => {
507 if let Some(results) = block.get("content").and_then(Value::as_array) {
508 for result in results {
509 let published = result
510 .get("page_age")
511 .and_then(Value::as_str)
512 .map(str::to_string);
513 push_citation(
514 &mut citations,
515 citation_from_value(result, None, published),
516 );
517 }
518 }
519 }
520 Some("text") => {
521 if let Some(text) = block.get("text").and_then(Value::as_str)
522 && !text.trim().is_empty()
523 {
524 answer_parts.push(text.trim().to_string());
525 }
526 if let Some(block_citations) = block.get("citations").and_then(Value::as_array)
527 {
528 for citation in block_citations {
529 let snippet = citation
530 .get("cited_text")
531 .and_then(Value::as_str)
532 .map(str::to_string);
533 push_citation(
534 &mut citations,
535 citation_from_value(citation, snippet, None),
536 );
537 }
538 }
539 }
540 _ => {}
541 }
542 }
543 }
544 ProviderNativeSearchResponse {
545 answer: joined_answer(answer_parts),
546 citations,
547 truncated: payload.get("stop_reason").and_then(Value::as_str) == Some("max_tokens"),
548 }
549 }
550
551 fn parse_mimo_search(payload: &Value) -> ProviderNativeSearchResponse {
552 let message = payload.pointer("/choices/0/message");
553 let answer = message
554 .and_then(|value| value.get("content"))
555 .and_then(Value::as_str)
556 .map(str::trim)
557 .filter(|text| !text.is_empty())
558 .map(str::to_string);
559 let mut citations = Vec::new();
560 if let Some(annotations) = message
561 .and_then(|value| value.get("annotations"))
562 .and_then(Value::as_array)
563 .or_else(|| payload.get("annotations").and_then(Value::as_array))
564 {
565 for annotation in annotations {
566 let Some(url) = annotation.get("url").and_then(Value::as_str) else {
567 continue;
568 };
569 let title = annotation
570 .get("title")
571 .and_then(Value::as_str)
572 .map(str::to_string);
573 let snippet = annotation
574 .get("summary")
575 .and_then(Value::as_str)
576 .map(str::to_string);
577 let published = annotation
578 .get("publish_time")
579 .and_then(Value::as_str)
580 .map(str::to_string);
581 push_citation(
582 &mut citations,
583 citation_from_url(url, title, snippet, published),
584 );
585 }
586 }
587 ProviderNativeSearchResponse {
588 answer: joined_answer(answer.into_iter().collect()),
589 citations,
590 truncated: finish_reason_is_length(payload.pointer("/choices/0")),
591 }
592 }
593
594 /// A Chat Completions choice that stopped at its output limit.
595 fn finish_reason_is_length(choice: Option<&Value>) -> bool {
596 choice
597 .and_then(|choice| choice.get("finish_reason"))
598 .and_then(Value::as_str)
599 == Some("length")
600 }
601
602 fn citation_from_value(
603 value: &Value,
604 snippet: Option<String>,
605 published: Option<String>,
606 ) -> Option<ProviderNativeCitation> {
607 let url = value.get("url").and_then(Value::as_str)?.trim();
608 let title = value
609 .get("title")
610 .and_then(Value::as_str)
611 .map(str::trim)
612 .filter(|title| !title.is_empty())
613 .map(str::to_string);
614 citation_from_url(url, title, snippet, published)
615 }
616
617 fn citation_from_url(
618 url: &str,
619 title: Option<String>,
620 snippet: Option<String>,
621 published: Option<String>,
622 ) -> Option<ProviderNativeCitation> {
623 let parsed = reqwest::Url::parse(url).ok()?;
624 if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
625 return None;
626 }
627 Some(ProviderNativeCitation {
628 url: url.to_string(),
629 title: title.unwrap_or_else(|| fallback_title(url)),
630 snippet,
631 published,
632 })
633 }
634
635 fn push_citation(
636 citations: &mut Vec<ProviderNativeCitation>,
637 candidate: Option<ProviderNativeCitation>,
638 ) {
639 let Some(candidate) = candidate else {
640 return;
641 };
642 if let Some(existing) = citations
643 .iter_mut()
644 .find(|existing| existing.url == candidate.url)
645 {
646 if existing.title == fallback_title(&existing.url)
647 && candidate.title != fallback_title(&candidate.url)
648 {
649 existing.title = candidate.title;
650 }
651 if existing.snippet.is_none() {
652 existing.snippet = candidate.snippet;
653 }
654 if existing.published.is_none() {
655 existing.published = candidate.published;
656 }
657 return;
658 }
659 citations.push(candidate);
660 }
661
662 fn citations_from_text(text: &str) -> Vec<ProviderNativeCitation> {
663 let mut citations = Vec::new();
664 let mut offset = 0;
665 while offset < text.len() {
666 let remaining = &text[offset..];
667 let relative_start = match (remaining.find("https://"), remaining.find("http://")) {
668 (Some(https), Some(http)) => Some(https.min(http)),
669 (Some(https), None) => Some(https),
670 (None, Some(http)) => Some(http),
671 (None, None) => None,
672 };
673 let Some(relative_start) = relative_start else {
674 break;
675 };
676 let start = offset + relative_start;
677 let tail = &text[start..];
678 // Balanced parentheses belong to the URL (Wikipedia titles such as
679 // `Foo_(bar)` keep their closing paren); an unmatched closer ends it.
680 let mut open_parens = 0_usize;
681 let end = tail
682 .char_indices()
683 .find_map(|(index, ch)| match ch {
684 '(' => {
685 open_parens += 1;
686 None
687 }
688 ')' if open_parens > 0 => {
689 open_parens -= 1;
690 None
691 }
692 _ => (index > 0
693 && (ch.is_whitespace()
694 || matches!(ch, ')' | ']' | '}' | '>' | '"' | '\'' | '`')))
695 .then_some(index),
696 })
697 .unwrap_or(tail.len());
698 let url = tail[..end].trim_end_matches(['.', ',', ';', ':', '!', '?']);
699 push_citation(&mut citations, citation_from_url(url, None, None, None));
700 offset = start + end.max(1);
701 }
702 citations
703 }
704
705 fn fallback_title(url: &str) -> String {
706 let Ok(parsed) = reqwest::Url::parse(url) else {
707 return "Web source".to_string();
708 };
709 let Some(host) = parsed.host_str() else {
710 return "Web source".to_string();
711 };
712 let slug = parsed
713 .path_segments()
714 .and_then(|mut segments| segments.rfind(|segment| !segment.is_empty()));
715 let Some(slug) = slug else {
716 return format!("{host} (home page)");
717 };
718 let words = slug
719 .rsplit_once('.')
720 .filter(|(_, extension)| matches!(*extension, "html" | "htm" | "php" | "asp" | "aspx"))
721 .map_or(slug, |(stem, _)| stem)
722 .split(['-', '_', '+'])
723 .filter(|word| !word.is_empty())
724 .map(|word| {
725 let mut chars = word.chars();
726 chars.next().map_or_else(String::new, |first| {
727 first.to_uppercase().collect::<String>() + chars.as_str()
728 })
729 })
730 .collect::<Vec<_>>()
731 .join(" ");
732 if words.is_empty() {
733 return format!("{host} (home page)");
734 }
735 words.chars().take(120).collect()
736 }
737
738 /// Join the answer parts whole. No per-adapter cap: the provider already
739 /// bounded its output tokens, and the engine's route budget bounds what
740 /// reaches the model inline while keeping the rest recoverable (#6508).
741 fn joined_answer(parts: Vec<String>) -> Option<String> {
742 let joined = parts.join("\n\n");
743 let trimmed = joined.trim();
744 (!trimmed.is_empty()).then(|| trimmed.to_string())
745 }
746
747 #[cfg(test)]
748 mod tests {
749 use super::*;
750 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
751 use wiremock::matchers::{body_partial_json, header, method, path};
752 use wiremock::{Mock, MockServer, ResponseTemplate};
753
754 #[test]
755 fn citation_without_a_provider_title_is_never_a_bare_domain() {
756 let home = citation_from_url("https://www.theverge.com/", None, None, None)
757 .expect("a root URL is a valid citation");
758 assert_ne!(home.title, "www.theverge.com");
759 assert_eq!(home.title, "www.theverge.com (home page)");
760
761 let article = citation_from_url(
762 "https://www.theverge.com/2026/10/21/apple-says-x.html",
763 None,
764 None,
765 None,
766 )
767 .expect("an article URL is a valid citation");
768 assert_eq!(article.title, "Apple Says X");
769 }
770
771 fn request() -> ProviderNativeSearchRequest {
772 ProviderNativeSearchRequest {
773 query: "current release".to_string(),
774 max_results: 3,
775 domains: vec!["example.com".to_string()],
776 }
777 }
778
779 fn xai_client_with_boundary(
780 server: &MockServer,
781 isolated: bool,
782 unrelated: bool,
783 ) -> ProviderNativeSearchClient {
784 let config = {
785 let __cw_config_init_0_0 = Some("xai".to_string());
786 let __cw_config_init_0_1 = Some(ProvidersConfig {
787 xai: ProviderConfig {
788 api_key: Some("xai-test-key".to_string()),
789 base_url: Some(format!("{}/v1", server.uri())),
790 model: Some("grok-4.5".to_string()),
791 ..ProviderConfig::default()
792 },
793 ..ProvidersConfig::default()
794 });
795 let __cw_config_init_0_2 = isolated;
796 let __cw_config_init_0_3 = unrelated;
797 let mut __cw_config_init_0_value: Config = Config::default();
798 __cw_config_init_0_value.provider = __cw_config_init_0_0;
799 __cw_config_init_0_value.providers = __cw_config_init_0_1;
800 __cw_config_init_0_value.runtime_chat_isolated = __cw_config_init_0_2;
801 __cw_config_init_0_value.runtime_thread_inference_unrelated = __cw_config_init_0_3;
802 __cw_config_init_0_value
803 };
804 ProviderNativeSearchClient::new(CodewhaleClient::new(&config).expect("test xAI client"))
805 .expect("xAI native adapter")
806 }
807
808 #[test]
809 fn responses_payload_requires_search_and_keeps_domains_provider_side() {
810 let body =
811 build_responses_search_body("gpt-5.6", &request(), ResponsesSearchDialect::Openai);
812 assert_eq!(body["tools"][0]["type"], "web_search");
813 assert_eq!(
814 body["tools"][0]["filters"]["allowed_domains"][0],
815 "example.com"
816 );
817 assert_eq!(body["tool_choice"], "required");
818 assert_eq!(body["include"][0], "web_search_call.action.sources");
819 }
820
821 #[test]
822 fn modelstudio_payload_uses_required_harness_search_without_filters() {
823 let body = build_responses_search_body(
824 "qwen3.8-max",
825 &request(),
826 ResponsesSearchDialect::ModelStudio,
827 );
828 assert_eq!(body["tools"][0]["type"], "web_search");
829 assert!(body["tools"][0].get("filters").is_none());
830 assert_eq!(body["tool_choice"], "required");
831 assert!(body.get("include").is_none());
832 assert!(body.get("store").is_none());
833 }
834
835 #[test]
836 fn deepseek_payload_uses_its_responses_search_contract() {
837 let body = build_responses_search_body(
838 "deepseek-v4-flash",
839 &request(),
840 ResponsesSearchDialect::Deepseek,
841 );
842 assert_eq!(body["tools"][0]["type"], "web_search");
843 assert!(body["tools"][0].get("filters").is_none());
844 assert_eq!(body["tool_choice"]["type"], "web_search");
845 assert!(body.get("include").is_none());
846 assert!(body.get("store").is_none());
847 }
848
849 #[test]
850 fn anthropic_payload_uses_basic_direct_search_contract() {
851 let body = build_anthropic_search_body("claude-opus-4-8", &request(), 2_048);
852 assert_eq!(body["tools"][0]["type"], "web_search_20250305");
853 assert_eq!(body["tools"][0]["max_uses"], 1);
854 assert_eq!(body["tools"][0]["allowed_domains"][0], "example.com");
855 assert_eq!(body["max_tokens"], 2_048);
856
857 let tiny_route = build_anthropic_search_body("claude-opus-4-8", &request(), 128);
858 assert_eq!(tiny_route["max_tokens"], 128);
859 }
860
861 #[test]
862 fn mimo_payload_forces_bounded_web_search_plugin() {
863 let body = build_mimo_search_body("mimo-v2.5-pro", &request(), 8_192);
864 assert_eq!(body["tools"][0]["type"], "web_search");
865 assert_eq!(body["tools"][0]["force_search"], true);
866 assert_eq!(body["tools"][0]["limit"], 3);
867 assert_eq!(body["max_completion_tokens"], 8_192);
868 assert_eq!(body["thinking"]["type"], "disabled");
869 }
870
871 fn anthropic_client(model: &str) -> ProviderNativeSearchClient {
872 let config = {
873 let __cw_config_init_1_0 = Some("anthropic".to_string());
874 let __cw_config_init_1_1 = Some(ProvidersConfig {
875 anthropic: ProviderConfig {
876 api_key: Some("anthropic-test-key".to_string()),
877 base_url: Some("https://api.anthropic.com".to_string()),
878 model: Some(model.to_string()),
879 ..ProviderConfig::default()
880 },
881 ..ProvidersConfig::default()
882 });
883 let mut __cw_config_init_1_value: Config = Config::default();
884 __cw_config_init_1_value.provider = __cw_config_init_1_0;
885 __cw_config_init_1_value.providers = __cw_config_init_1_1;
886 __cw_config_init_1_value
887 };
888 ProviderNativeSearchClient::new(CodewhaleClient::new(&config).expect("Anthropic client"))
889 .expect("Anthropic native adapter")
890 }
891
892 #[test]
893 fn answer_output_tokens_is_the_model_ceiling_up_to_the_clamp() {
894 // #6508: native answers were requested at 2,048 tokens and silently
895 // cut. A catalogued model now gets its route ceiling, up to the clamp.
896 let client = anthropic_client("claude-opus-4-8");
897 let route_cap = client.inner.effective_max_output_tokens("claude-opus-4-8");
898 assert!(route_cap > PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS);
899 assert_eq!(
900 client.answer_output_tokens(PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS),
901 NATIVE_SEARCH_MAX_OUTPUT_TOKENS.min(route_cap)
902 );
903 // web_search budgets time from the same number the body carries.
904 assert_eq!(
905 client.requested_answer_output_tokens(),
906 Some(NATIVE_SEARCH_MAX_OUTPUT_TOKENS.min(route_cap))
907 );
908
909 // A model the catalogue does not describe keeps the old request size
910 // rather than risk a rejection.
911 let unknown = anthropic_client("claude-unlisted-test-model");
912 assert_eq!(
913 unknown.answer_output_tokens(PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS),
914 PRIOR_NATIVE_SEARCH_OUTPUT_TOKENS
915 );
916 }
917
918 #[test]
919 fn anthropic_stop_reason_max_tokens_sets_truncated() {
920 let cut = parse_anthropic_search(&json!({
921 "stop_reason": "max_tokens",
922 "content": [{ "type": "text", "text": "Partial answer" }]
923 }));
924 assert!(cut.truncated);
925 assert_eq!(cut.answer.as_deref(), Some("Partial answer"));
926
927 let whole = parse_anthropic_search(&json!({
928 "stop_reason": "end_turn",
929 "content": [{ "type": "text", "text": "Whole answer" }]
930 }));
931 assert!(!whole.truncated);
932 }
933
934 #[test]
935 fn responses_incomplete_max_output_tokens_sets_truncated() {
936 let payload = |status: &str, reason: &str| {
937 json!({
938 "status": status,
939 "incomplete_details": { "reason": reason },
940 "output": [{
941 "type": "message",
942 "content": [{ "type": "output_text", "text": "Partial answer" }]
943 }]
944 })
945 };
946 assert!(parse_responses_search(&payload("incomplete", "max_output_tokens")).truncated);
947 assert!(!parse_responses_search(&payload("incomplete", "content_filter")).truncated);
948 assert!(!parse_responses_search(&payload("completed", "")).truncated);
949 }
950
951 #[test]
952 fn mimo_finish_reason_length_sets_truncated() {
953 let payload = |finish_reason: &str| {
954 json!({
955 "choices": [{
956 "finish_reason": finish_reason,
957 "message": { "content": "Partial answer" }
958 }]
959 })
960 };
961 assert!(parse_mimo_search(&payload("length")).truncated);
962 assert!(!parse_mimo_search(&payload("stop")).truncated);
963 }
964
965 #[test]
966 fn responses_parser_separates_answer_and_deduplicated_citations() {
967 let payload = json!({
968 "output": [
969 {
970 "type": "web_search_call",
971 "action": { "sources": [
972 { "url": "https://example.com/a", "title": "Source A" }
973 ] }
974 },
975 {
976 "type": "message",
977 "content": [{
978 "type": "output_text",
979 "text": "Grounded answer.",
980 "annotations": [
981 { "type": "url_citation", "url": "https://example.com/a", "title": "Source A" },
982 { "type": "url_citation", "url": "https://example.org/b", "title": "Source B" }
983 ]
984 }]
985 }
986 ]
987 });
988 let parsed = parse_responses_search(&payload);
989 assert_eq!(parsed.answer.as_deref(), Some("Grounded answer."));
990 assert_eq!(parsed.citations.len(), 2);
991 assert_eq!(parsed.citations[0].title, "Source A");
992 assert_eq!(parsed.citations[1].url, "https://example.org/b");
993 }
994
995 #[test]
996 fn long_native_answers_are_returned_whole() {
997 let long = format!("{} end-of-answer", "grounded sentence. ".repeat(600));
998 assert!(long.chars().count() > 10_000);
999 let payload = json!({
1000 "output": [{
1001 "type": "message",
1002 "content": [{ "type": "output_text", "text": long.clone() }]
1003 }]
1004 });
1005 let parsed = parse_responses_search(&payload);
1006 assert_eq!(parsed.answer.as_deref(), Some(long.trim()));
1007 assert!(parsed.answer.unwrap().ends_with("end-of-answer"));
1008 }
1009
1010 #[test]
1011 fn responses_parser_keeps_final_message_and_opened_pages_only() {
1012 let payload = json!({
1013 "output": [
1014 {
1015 "type": "reasoning",
1016 "content": [{
1017 "type": "reasoning_text",
1018 "text": "private analysis https://reasoning.example/ must stay hidden"
1019 }]
1020 },
1021 {
1022 "type": "web_search_call",
1023 "action": {
1024 "type": "open_page",
1025 "url": "https://github.com/codewhale-hq/CodeWhale"
1026 }
1027 },
1028 {
1029 "type": "message",
1030 "content": [{
1031 "type": "output_text",
1032 "text": "Official repository: https://github.com/codewhale-hq/CodeWhale",
1033 "annotations": []
1034 }]
1035 }
1036 ]
1037 });
1038
1039 let parsed = parse_responses_search(&payload);
1040
1041 assert_eq!(
1042 parsed.answer.as_deref(),
1043 Some("Official repository: https://github.com/codewhale-hq/CodeWhale")
1044 );
1045 assert_eq!(parsed.citations.len(), 1);
1046 assert_eq!(
1047 parsed.citations[0].url,
1048 "https://github.com/codewhale-hq/CodeWhale"
1049 );
1050 }
1051
1052 #[test]
1053 fn anthropic_parser_keeps_result_metadata_and_cited_text_separate() {
1054 let payload = json!({
1055 "content": [
1056 {
1057 "type": "web_search_tool_result",
1058 "content": [{
1059 "type": "web_search_result",
1060 "url": "https://example.com/a",
1061 "title": "Source A",
1062 "page_age": "July 18, 2026"
1063 }]
1064 },
1065 {
1066 "type": "text",
1067 "text": "Grounded answer.",
1068 "citations": [{
1069 "type": "web_search_result_location",
1070 "url": "https://example.com/a",
1071 "title": "Source A",
1072 "cited_text": "Supporting passage"
1073 }]
1074 }
1075 ]
1076 });
1077 let parsed = parse_anthropic_search(&payload);
1078 assert_eq!(parsed.answer.as_deref(), Some("Grounded answer."));
1079 assert_eq!(parsed.citations.len(), 1);
1080 assert_eq!(
1081 parsed.citations[0].published.as_deref(),
1082 Some("July 18, 2026")
1083 );
1084 assert_eq!(
1085 parsed.citations[0].snippet.as_deref(),
1086 Some("Supporting passage")
1087 );
1088 }
1089
1090 #[test]
1091 fn mimo_parser_keeps_non_streaming_annotations() {
1092 let parsed = parse_mimo_search(&json!({
1093 "choices": [{
1094 "message": {
1095 "content": "Grounded answer.",
1096 "annotations": [{
1097 "type": "url_citation",
1098 "url": "https://example.com/weather",
1099 "title": "Weather",
1100 "summary": "Forecast",
1101 "publish_time": "2026-08-28"
1102 }]
1103 }
1104 }]
1105 }));
1106 assert_eq!(parsed.answer.as_deref(), Some("Grounded answer."));
1107 assert_eq!(parsed.citations.len(), 1);
1108 assert_eq!(parsed.citations[0].snippet.as_deref(), Some("Forecast"));
1109 assert_eq!(parsed.citations[0].published.as_deref(), Some("2026-08-28"));
1110 }
1111
1112 #[test]
1113 fn non_http_citations_are_rejected() {
1114 let payload = json!({ "citations": ["javascript:alert(1)"] });
1115 assert!(parse_responses_search(&payload).citations.is_empty());
1116 }
1117
1118 #[test]
1119 fn answer_links_preserve_mixed_scheme_source_order() {
1120 let citations =
1121 citations_from_text("First http://legacy.example/a, then https://secure.example/b.");
1122 assert_eq!(citations.len(), 2);
1123 assert_eq!(citations[0].url, "http://legacy.example/a");
1124 assert_eq!(citations[1].url, "https://secure.example/b");
1125 }
1126
1127 #[test]
1128 fn answer_links_keep_balanced_parenthesis_segments() {
1129 let citations = citations_from_text(
1130 "See https://en.wikipedia.org/wiki/Foo_(bar) and https://en.wikipedia.org/wiki/Baz_(qux_(nested)) for details.",
1131 );
1132 assert_eq!(citations.len(), 2);
1133 assert_eq!(
1134 citations[0].url, "https://en.wikipedia.org/wiki/Foo_(bar)",
1135 "a balanced closing paren is part of the URL"
1136 );
1137 assert_eq!(
1138 citations[1].url, "https://en.wikipedia.org/wiki/Baz_(qux_(nested))",
1139 "nested balanced parens stay intact"
1140 );
1141
1142 let unbalanced = citations_from_text("Broken https://en.wikipedia.org/wiki/Foo_(bar here.");
1143 assert_eq!(
1144 unbalanced[0].url, "https://en.wikipedia.org/wiki/Foo_(bar",
1145 "an unclosed paren cannot extend past the next whitespace"
1146 );
1147 }
1148
1149 #[tokio::test]
1150 async fn xai_adapter_reuses_active_authenticated_transport() {
1151 let server = MockServer::start().await;
1152 Mock::given(method("POST"))
1153 .and(path("/v1/responses"))
1154 .and(header("authorization", "Bearer xai-test-key"))
1155 .and(body_partial_json(json!({
1156 "model": "grok-4.5",
1157 "tools": [{
1158 "type": "web_search",
1159 "filters": { "allowed_domains": ["example.com"] }
1160 }],
1161 "tool_choice": "required"
1162 })))
1163 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1164 "output_text": "Grounded answer.",
1165 "citations": ["https://example.com/source"]
1166 })))
1167 .expect(1)
1168 .mount(&server)
1169 .await;
1170 let config = {
1171 let __cw_config_init_2_0 = Some("xai".to_string());
1172 let __cw_config_init_2_1 = Some(ProvidersConfig {
1173 xai: ProviderConfig {
1174 api_key: Some("xai-test-key".to_string()),
1175 base_url: Some(format!("{}/v1", server.uri())),
1176 model: Some("grok-4.5".to_string()),
1177 ..ProviderConfig::default()
1178 },
1179 ..ProvidersConfig::default()
1180 });
1181 let mut __cw_config_init_2_value: Config = Config::default();
1182 __cw_config_init_2_value.provider = __cw_config_init_2_0;
1183 __cw_config_init_2_value.providers = __cw_config_init_2_1;
1184 __cw_config_init_2_value
1185 };
1186 let inner = CodewhaleClient::new(&config).expect("test xAI client");
1187 let client = ProviderNativeSearchClient::new(inner).expect("xAI native adapter");
1188 let cache_identity = client.cache_identity();
1189 assert!(cache_identity.contains("provider-native://xai/"));
1190 assert!(cache_identity.ends_with("/grok-4.5"));
1191 assert!(!cache_identity.contains("xai-test-key"));
1192
1193 let response = client.search(&request()).await.expect("native search");
1194
1195 assert_eq!(response.answer.as_deref(), Some("Grounded answer."));
1196 assert_eq!(response.citations.len(), 1);
1197 assert_eq!(response.citations[0].url, "https://example.com/source");
1198 }
1199
1200 #[tokio::test]
1201 async fn modelstudio_adapter_uses_token_plan_responses_contract() {
1202 let server = MockServer::start().await;
1203 Mock::given(method("POST"))
1204 .and(path("/v1/responses"))
1205 .and(header("authorization", "Bearer modelstudio-test-key"))
1206 .and(body_partial_json(json!({
1207 "model": "qwen3.8-max",
1208 "tools": [{ "type": "web_search" }],
1209 "tool_choice": "required"
1210 })))
1211 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1212 "output": [{
1213 "type": "web_search_call",
1214 "action": {
1215 "sources": [{
1216 "url": "https://example.com/qwen",
1217 "title": "Qwen source"
1218 }]
1219 }
1220 }]
1221 })))
1222 .expect(1)
1223 .mount(&server)
1224 .await;
1225 let config = {
1226 let __cw_config_init_3_0 = Some("modelstudio-token-plan".to_string());
1227 let __cw_config_init_3_1 = Some(ProvidersConfig {
1228 modelstudio_token_plan: ProviderConfig {
1229 api_key: Some("modelstudio-test-key".to_string()),
1230 base_url: Some(format!("{}/v1", server.uri())),
1231 model: Some("qwen3.8-max".to_string()),
1232 ..ProviderConfig::default()
1233 },
1234 ..ProvidersConfig::default()
1235 });
1236 let mut __cw_config_init_3_value: Config = Config::default();
1237 __cw_config_init_3_value.provider = __cw_config_init_3_0;
1238 __cw_config_init_3_value.providers = __cw_config_init_3_1;
1239 __cw_config_init_3_value
1240 };
1241 let inner = CodewhaleClient::new(&config).expect("test ModelStudio client");
1242 let client = ProviderNativeSearchClient::new(inner).expect("Qwen native adapter");
1243
1244 let response = client.search(&request()).await.expect("native search");
1245
1246 assert_eq!(response.citations.len(), 1);
1247 assert_eq!(response.citations[0].url, "https://example.com/qwen");
1248 }
1249 #[tokio::test]
1250 async fn deepseek_adapter_uses_authenticated_responses_endpoint() {
1251 let server = MockServer::start().await;
1252 Mock::given(method("POST"))
1253 .and(path("/v1/responses"))
1254 .and(header("authorization", "Bearer deepseek-test-key"))
1255 .and(body_partial_json(json!({
1256 "model": "deepseek-v4-flash",
1257 "tools": [{ "type": "web_search" }],
1258 "tool_choice": { "type": "web_search" }
1259 })))
1260 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1261 "output": [
1262 {
1263 "type": "web_search_call",
1264 "action": {
1265 "type": "open_page",
1266 "url": "https://example.com/deepseek"
1267 }
1268 },
1269 {
1270 "type": "message",
1271 "content": [{
1272 "type": "output_text",
1273 "text": "Grounded answer.",
1274 "annotations": []
1275 }]
1276 }
1277 ]
1278 })))
1279 .expect(1)
1280 .mount(&server)
1281 .await;
1282 let config = {
1283 let __cw_config_init_4_0 = Some("deepseek".to_string());
1284 let __cw_config_init_4_1 = Some(ProvidersConfig {
1285 deepseek: ProviderConfig {
1286 api_key: Some("deepseek-test-key".to_string()),
1287 base_url: Some(format!("{}/v1", server.uri())),
1288 model: Some("deepseek-v4-flash".to_string()),
1289 ..ProviderConfig::default()
1290 },
1291 ..ProvidersConfig::default()
1292 });
1293 let mut __cw_config_init_4_value: Config = Config::default();
1294 __cw_config_init_4_value.provider = __cw_config_init_4_0;
1295 __cw_config_init_4_value.providers = __cw_config_init_4_1;
1296 __cw_config_init_4_value
1297 };
1298 let inner = CodewhaleClient::new(&config).expect("test DeepSeek client");
1299 let client = ProviderNativeSearchClient::new(inner).expect("DeepSeek native adapter");
1300
1301 let response = client.search(&request()).await.expect("native search");
1302
1303 assert_eq!(response.answer.as_deref(), Some("Grounded answer."));
1304 assert_eq!(response.citations.len(), 1);
1305 assert_eq!(response.citations[0].url, "https://example.com/deepseek");
1306 }
1307
1308 #[tokio::test]
1309 async fn native_search_obeys_attached_run_ownership_without_blocking_unrelated_runtime() {
1310 let server = MockServer::start().await;
1311 Mock::given(method("POST"))
1312 .and(path("/v1/responses"))
1313 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1314 "output_text": "Grounded answer.",
1315 "citations": ["https://example.com/source"]
1316 })))
1317 .expect(3)
1318 .mount(&server)
1319 .await;
1320 let participant = xai_client_with_boundary(&server, false, false);
1321 let isolated = xai_client_with_boundary(&server, true, false);
1322 let unrelated = xai_client_with_boundary(&server, false, true);
1323
1324 let ownership = crate::client::acquire_runtime_chat_inference_ownership().await;
1325 let participant_request = request();
1326 let mut waiting =
1327 tokio::spawn(async move { participant.search(&participant_request).await });
1328 assert!(
1329 tokio::time::timeout(std::time::Duration::from_millis(40), &mut waiting)
1330 .await
1331 .is_err(),
1332 "provider-native inference from the attached run must wait behind Runtime Chat"
1333 );
1334
1335 tokio::time::timeout(
1336 std::time::Duration::from_secs(1),
1337 isolated.search(&request()),
1338 )
1339 .await
1340 .expect("isolated relay request must not self-deadlock")
1341 .expect("isolated native search fixture");
1342 tokio::time::timeout(
1343 std::time::Duration::from_secs(1),
1344 unrelated.search(&request()),
1345 )
1346 .await
1347 .expect("unrelated Runtime manager stays concurrent")
1348 .expect("unrelated native search fixture");
1349
1350 drop(ownership);
1351 tokio::time::timeout(std::time::Duration::from_secs(1), waiting)
1352 .await
1353 .expect("attached participant resumes after relay settlement")
1354 .expect("participant task")
1355 .expect("participant native search fixture");
1356 }
1357
1358 #[tokio::test]
1359 async fn native_search_rejects_oversized_response_bodies() {
1360 let server = MockServer::start().await;
1361 let oversized = "x".repeat(MAX_NATIVE_SEARCH_RESPONSE_BYTES + 1);
1362 Mock::given(method("POST"))
1363 .and(path("/v1/responses"))
1364 .respond_with(
1365 ResponseTemplate::new(200).set_body_raw(oversized.clone(), "application/json"),
1366 )
1367 .expect(1)
1368 .mount(&server)
1369 .await;
1370 Mock::given(method("POST"))
1371 .and(path("/v1/post-json"))
1372 .respond_with(
1373 ResponseTemplate::new(200).set_body_raw(oversized.clone(), "application/json"),
1374 )
1375 .expect(1)
1376 .mount(&server)
1377 .await;
1378 Mock::given(method("GET"))
1379 .and(path("/v1/get-json"))
1380 .respond_with(ResponseTemplate::new(200).set_body_raw(oversized, "application/json"))
1381 .expect(1)
1382 .mount(&server)
1383 .await;
1384
1385 let client = xai_client_with_boundary(&server, false, false);
1386
1387 let search_err = match client.search(&request()).await {
1388 Ok(_) => panic!("oversized search response must fail"),
1389 Err(err) => err,
1390 };
1391 let search_msg = format!("{search_err:#}");
1392 assert!(search_msg.contains("byte limit"), "{search_msg}");
1393 assert!(!search_msg.contains("invalid JSON"), "{search_msg}");
1394
1395 let post_err = client
1396 .post_json(&format!("{}/v1/post-json", server.uri()), &json!({}), &[])
1397 .await
1398 .expect_err("oversized post_json response must fail");
1399 let post_msg = format!("{post_err:#}");
1400 assert!(post_msg.contains("byte limit"), "{post_msg}");
1401 assert!(!post_msg.contains("invalid JSON"), "{post_msg}");
1402
1403 let get_err = client
1404 .get_json(&format!("{}/v1/get-json", server.uri()))
1405 .await
1406 .expect_err("oversized get_json response must fail");
1407 let get_msg = format!("{get_err:#}");
1408 assert!(get_msg.contains("byte limit"), "{get_msg}");
1409 assert!(!get_msg.contains("invalid JSON"), "{get_msg}");
1410 }
1411 }
1412
1412 lines RUST