Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

fix Grok web search: 400s on Claude Code's tool declarations, unrenderable hosted-search blocks, and seized tools (#112)

Alex Kugele60cf008e198
diff --git a/docs/src/content/docs/providers/grok.md b/docs/src/content/docs/providers/grok.md
index d3cc3a4..3ed3fdd 100644
--- a/docs/src/content/docs/providers/grok.md
+++ b/docs/src/content/docs/providers/grok.md
@@ -36,11 +36,22 @@ ANTHROPIC_SMALL_FAST_MODEL=grok-4.6 \
The proxy translates Claude messages, function tools, tool results, thinking controls, token usage, and streaming events. Grok reasoning text appears as Claude Code thinking blocks.
-Claude Code hosted search tools map to Grok-native tools:
-
-- General web queries use hosted web search.
-- X queries use hosted `x_search`.
-- Citations and search usage return in Anthropic-compatible content and usage fields.
+Search reaches Grok-native tools when the caller asks for it:
+
+- Anthropic's `web_search_20250305` declaration maps to Grok hosted web search.
+ The Grok CLI endpoint accepts the minimal declaration without domain or
+ location constraints.
+- A caller-managed search tool remains a function tool for the caller to run.
+- An X or Twitter query is additionally offered hosted `x_search`, which the
+ model can use or ignore alongside the caller's tools.
+- Citations and search usage return in Anthropic-compatible usage fields.
+- `CCP_GROK_HOSTED_SEARCH=1` enables a policy where hosted tools replace caller
+ search tools and explicit search turns require a tool call.
+
+A hosted search is reported as a text block naming the query.
+`CCP_GROK_SEARCH_BLOCKS=native` preserves `server_tool_use` plus
+`web_search_tool_result` or `x_search_tool_result` for clients that consume
+hosted-tool blocks.
## OpenAI-compatible APIs
@@ -70,9 +81,16 @@ Traffic captures redact Anthropic image data and upstream image data URLs.
- `CCP_GROK_BASE_URL` or `grok.baseUrl` changes the API base URL.
- `CCP_GROK_CLIENT_VERSION` or `grok.clientVersion` changes the client version header.
- `CCP_GROK_TOOL_IMAGE` selects `omit`, `reattach`, `inline`, or `reject`.
+- `CCP_GROK_HOSTED_SEARCH` enables hosted search replacement and forcing.
+- `CCP_GROK_SEARCH_BLOCKS` selects `text` or `native` hosted-search reporting.
See [Configuration](/reference/configuration/) for defaults.
## Limitations and troubleshooting
+The Grok CLI hosted web-search endpoint has no equivalent for Anthropic's
+`max_uses`, domain filters, or user location. The proxy accepts and omits a
+valid `max_uses` value, while non-null domain and location constraints return a
+request error rather than weakening the requested search scope.
+
A successful login does not guarantee every model is enabled for the account or region. Model rejection and upstream errors are surfaced to Claude Code. Use `grok auth status` for token state, inspect the failed request in the monitor, and use the structured log or error capture for the full redacted response.
diff --git a/docs/src/content/docs/reference/compatibility-and-limitations.md b/docs/src/content/docs/reference/compatibility-and-limitations.md
index 9710a43..2dcd30b 100644
--- a/docs/src/content/docs/reference/compatibility-and-limitations.md
+++ b/docs/src/content/docs/reference/compatibility-and-limitations.md
@@ -68,6 +68,9 @@ claude-code-proxy targets Claude Code's practical Anthropic API usage rather tha
- Model availability varies by account and region.
- Hosted general web search and X search are translated with citations and usage.
+- Hosted web search omits `max_uses` because the Grok CLI endpoint exposes no
+ equivalent cap. Non-null domain filters and user location are rejected because
+ dropping them would weaken the caller's requested search scope.
- The implemented multimodal path does not claim general image or video compatibility.
## Cursor Agent
diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md
index 4165a87..f5936f2 100644
--- a/docs/src/content/docs/reference/configuration.md
+++ b/docs/src/content/docs/reference/configuration.md
@@ -133,6 +133,8 @@ Proxy URLs may use `http`, `https`, `socks4`, `socks4a`, `socks5`, or `socks5h`.
| `CCP_GROK_BASE_URL` | `grok.baseUrl` | `https://cli-chat-proxy.grok.com/v1` | Changes the Responses API base URL. |
| `CCP_GROK_CLIENT_VERSION` | `grok.clientVersion` | `0.2.93` | Changes the Grok client version header. |
| `CCP_GROK_TOOL_IMAGE` | none | `omit` | Selects `omit`, `reattach`, `inline`, or `reject` image handling. |
+| `CCP_GROK_HOSTED_SEARCH` | none | off | Set to `1`, `on`, or `true` to let hosted search tools replace the caller's own search tools and force them on an explicit search turn. |
+| `CCP_GROK_SEARCH_BLOCKS` | none | `text` | Selects how a hosted search is reported: `text` for a text block, `native` for `server_tool_use` plus a `*_tool_result` block. |
## OpenCode Go
diff --git a/src/config.rs b/src/config.rs
index 10c7dc6..15c0b07 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -454,6 +454,59 @@ pub fn warn_grok_tool_image_mode_once(log: &crate::logging::Logger) {
}
}
+// ---------------------------------------------------------------------------
+// Grok hosted-search policy (CCP_GROK_HOSTED_SEARCH)
+// ---------------------------------------------------------------------------
+
+/// Whether the Grok translator replaces caller search tools with xAI-hosted
+/// search and requires hosted tool use on explicit search turns.
+///
+/// The disabled policy preserves caller tools, instructions, and tool choice.
+/// It adds `x_search` only to X-specific turns because the caller has no
+/// equivalent access to xAI's X index.
+///
+/// The enabled policy favors xAI-hosted search and citations. Hosted tools
+/// replace caller search implementations, matching turns receive search
+/// guidance, and explicit search turns use `tool_choice: required`.
+///
+/// Set `CCP_GROK_HOSTED_SEARCH` to `1`, `on`, or `true` to enable this policy.
+pub fn parse_grok_hosted_search(raw: Option<&str>) -> bool {
+ matches!(raw.map(str::trim), Some("1" | "on" | "true"))
+}
+
+pub fn grok_hosted_search() -> bool {
+ parse_grok_hosted_search(std::env::var("CCP_GROK_HOSTED_SEARCH").ok().as_deref())
+}
+
+// ---------------------------------------------------------------------------
+// Grok hosted-search block shape (CCP_GROK_SEARCH_BLOCKS)
+// ---------------------------------------------------------------------------
+
+/// How a hosted search that xAI ran is reported to the client.
+///
+/// `Text` projects the search query into a standard `text` block.
+///
+/// `Native` preserves the Anthropic server-tool shape: `server_tool_use`
+/// followed by `web_search_tool_result` or `x_search_tool_result`. Select this
+/// shape for clients that consume hosted-tool blocks.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GrokSearchBlocks {
+ Text,
+ Native,
+}
+
+pub fn parse_grok_search_blocks(raw: Option<&str>) -> GrokSearchBlocks {
+ match raw.map(str::trim) {
+ Some("native") => GrokSearchBlocks::Native,
+ // Text is the compatibility-safe fallback for empty or unknown values.
+ _ => GrokSearchBlocks::Text,
+ }
+}
+
+pub fn grok_search_blocks() -> GrokSearchBlocks {
+ parse_grok_search_blocks(std::env::var("CCP_GROK_SEARCH_BLOCKS").ok().as_deref())
+}
+
struct ResolvedOpenCodeConfig {
api_key: Option<String>,
api_key_source: Option<&'static str>,
diff --git a/src/providers/grok/translate/accumulate.rs b/src/providers/grok/translate/accumulate.rs
index 8ce62e9..c6c644d 100644
--- a/src/providers/grok/translate/accumulate.rs
+++ b/src/providers/grok/translate/accumulate.rs
@@ -1,6 +1,8 @@
use std::collections::HashMap;
use super::reducer::{ReducerEvent, reduce_upstream_bytes};
+use super::search_text::search_line;
+use crate::config::GrokSearchBlocks;
use crate::traffic::TrafficCapture;
use serde_json::Value;
@@ -17,6 +19,24 @@ pub fn accumulate_response_with_traffic(
message_id: &str,
model: &str,
traffic: Option<&TrafficCapture>,
+) -> anyhow::Result<Value> {
+ accumulate_response_with_options(
+ upstream,
+ message_id,
+ model,
+ traffic,
+ crate::config::grok_search_blocks(),
+ )
+}
+
+/// Tests choose the hosted-search block shape directly rather than through the
+/// environment.
+pub fn accumulate_response_with_options(
+ upstream: &[u8],
+ message_id: &str,
+ model: &str,
+ traffic: Option<&TrafficCapture>,
+ search_blocks: GrokSearchBlocks,
) -> anyhow::Result<Value> {
let mut capture = traffic.map(TrafficCapture::stream_capture);
let mut decoder = super::stream::SseDecoder::default();
@@ -136,6 +156,17 @@ pub fn accumulate_response_with_traffic(
name,
query,
} => {
+ if search_blocks == GrokSearchBlocks::Text {
+ // One text block, not two. Blocks are collected into an
+ // array here and addressed through `block_positions`, so
+ // leaving `result_index` unmapped costs nothing. The
+ // streaming path emits an empty second block instead,
+ // because there the index goes on the wire.
+ block_positions.insert(index, blocks.len());
+ blocks
+ .push(serde_json::json!({"type":"text","text":search_line(&name,&query)}));
+ continue;
+ }
block_positions.insert(index, blocks.len());
blocks.push(serde_json::json!({"type":"server_tool_use","id":id,"name":name,"input":{"query":query}}));
block_positions.insert(result_index, blocks.len());
@@ -201,6 +232,55 @@ fn finish_capture(
mod tests {
use super::*;
+ const HOSTED_WEB_SEARCH: &[u8] = b"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\"}}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"action\":{\"query\":\"rust news\"}}}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"Result\"}\n\ndata: {\"type\":\"response.output_text.done\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n";
+
+ #[test]
+ fn accumulated_hosted_search_renders_as_text_by_default() {
+ let response = accumulate_response_with_options(
+ HOSTED_WEB_SEARCH,
+ "message",
+ "grok-4.5",
+ None,
+ GrokSearchBlocks::Text,
+ )
+ .unwrap();
+ let types: Vec<&str> = response["content"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|block| block["type"].as_str().unwrap())
+ .collect();
+ // One text block represents the search and one contains the answer.
+ assert_eq!(types, vec!["text", "text"]);
+ assert_eq!(response["content"][0]["text"], "[web search: rust news]\n");
+ assert_eq!(
+ response["usage"]["server_tool_use"]["web_search_requests"],
+ 1
+ );
+ }
+
+ #[test]
+ fn accumulated_hosted_search_keeps_the_native_shape_on_request() {
+ let response = accumulate_response_with_options(
+ HOSTED_WEB_SEARCH,
+ "message",
+ "grok-4.5",
+ None,
+ GrokSearchBlocks::Native,
+ )
+ .unwrap();
+ let types: Vec<&str> = response["content"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|block| block["type"].as_str().unwrap())
+ .collect();
+ assert_eq!(
+ types,
+ vec!["server_tool_use", "web_search_tool_result", "text"]
+ );
+ }
+
#[test]
fn accumulate_response_tracks_two_interleaved_tool_calls() {
let input = b"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"first\"}}\n\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\",\"call_id\":\"call_2\",\"name\":\"second\"}}\n\ndata: {\"type\":\"response.function_call_arguments.delta\",\"call_id\":\"call_1\",\"delta\":\"{\\\"value\\\":1}\"}\n\ndata: {\"type\":\"response.function_call_arguments.delta\",\"call_id\":\"call_2\",\"delta\":\"{\\\"value\\\":2}\"}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"call_2\"}}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"call_1\"}}\n\ndata: {\"type\":\"response.completed\",\"response\":{}}\n\n";
diff --git a/src/providers/grok/translate/mod.rs b/src/providers/grok/translate/mod.rs
index 3e9f944..9b72326 100644
--- a/src/providers/grok/translate/mod.rs
+++ b/src/providers/grok/translate/mod.rs
@@ -2,4 +2,5 @@ pub mod accumulate;
pub mod model_allowlist;
pub mod reducer;
pub mod request;
+pub mod search_text;
pub mod stream;
diff --git a/src/providers/grok/translate/request.rs b/src/providers/grok/translate/request.rs
index 328ebd3..3300781 100644
--- a/src/providers/grok/translate/request.rs
+++ b/src/providers/grok/translate/request.rs
@@ -85,10 +85,20 @@ pub struct GrokTool {
pub from_date: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to_date: Option<String>,
+ #[serde(skip)]
+ choice_name: Option<String>,
}
impl GrokTool {
fn hosted(kind: &str) -> Self {
+ Self::hosted_for_choice(kind, None)
+ }
+
+ fn hosted_named(kind: &str, name: &str) -> Self {
+ Self::hosted_for_choice(kind, Some(name))
+ }
+
+ fn hosted_for_choice(kind: &str, choice_name: Option<&str>) -> Self {
Self {
kind: kind.into(),
name: None,
@@ -98,6 +108,7 @@ impl GrokTool {
excluded_x_handles: None,
from_date: None,
to_date: None,
+ choice_name: choice_name.map(str::to_string),
}
}
@@ -111,6 +122,7 @@ impl GrokTool {
excluded_x_handles: None,
from_date: None,
to_date: None,
+ choice_name: Some(name.into()),
}
}
}
@@ -135,43 +147,72 @@ pub fn translate_request_with_mode(
req: &MessagesRequest,
model: String,
image_mode: GrokToolImageMode,
+) -> anyhow::Result<GrokResponsesRequest> {
+ translate_request_with_options(req, model, image_mode, crate::config::grok_hosted_search())
+}
+
+/// `hosted_search` selects how xAI's hosted search tools reach the model. When
+/// disabled, the translator offers `x_search` only for X-specific turns and
+/// preserves every caller tool. When enabled, hosted tools replace caller
+/// search tools and explicit search turns require a tool call. Tests pass the
+/// policy directly so their behavior is independent of process configuration.
+pub fn translate_request_with_options(
+ req: &MessagesRequest,
+ model: String,
+ image_mode: GrokToolImageMode,
+ hosted_search: bool,
) -> anyhow::Result<GrokResponsesRequest> {
reject_unknown_top_level(req)?;
let mut instructions = parse_system(req.extra.get("system"))?;
- let mut tools = parse_tools(req.extra.get("tools"))?;
+ let mut tools = parse_tools(req.extra.get("tools"), hosted_search)?;
let hosted_web_search = tools
.as_ref()
.is_some_and(|tools| tools.iter().any(|tool| tool.kind == "web_search"));
let dedicated_x_search = tools
.as_ref()
.is_some_and(|tools| tools.iter().any(|tool| tool.kind == "x_search"));
- let x_search_intent = requests_x_search(req);
- let force_x_search = dedicated_x_search || x_search_intent;
- let force_web_search = !force_x_search && hosted_web_search && requests_web_search(req);
- if force_x_search {
- tools = Some(vec![GrokTool::hosted("x_search")]);
- } else if force_web_search {
- tools = Some(vec![GrokTool::hosted("web_search")]);
- } else {
+ let mut forced_hosted_tool = false;
+ if hosted_search {
+ // The enabled policy favors xAI-hosted search and citations over the
+ // caller's search implementation. Explicit search turns expose only
+ // the selected hosted tool and require a tool call.
+ let force_x_search = dedicated_x_search || requests_x_search(req);
+ let force_web_search = !force_x_search && hosted_web_search && requests_web_search(req);
+ if force_x_search {
+ tools = Some(vec![GrokTool::hosted("x_search")]);
+ } else if force_web_search {
+ tools = Some(vec![GrokTool::hosted("web_search")]);
+ } else {
+ let tools = tools.get_or_insert_default();
+ if !tools.iter().any(|tool| tool.kind == "x_search") {
+ tools.push(GrokTool::hosted("x_search"));
+ }
+ }
+ if hosted_web_search {
+ append_guidance(
+ &mut instructions,
+ "For general web searches, use the hosted web_search tool. Do not use shell commands, HTTP clients, or local tools to search the web.",
+ );
+ }
+ if force_x_search {
+ append_guidance(
+ &mut instructions,
+ "For requests to search X or Twitter, use the hosted x_search tool. XSearch accepts a query and supports allowed_x_handles, excluded_x_handles, from_date, and to_date filters. Do not use Bash, curl, HTTP clients, or general web_search for X searches.",
+ );
+ }
+ forced_hosted_tool = force_x_search || force_web_search;
+ } else if requests_x_search(req) {
+ // The disabled policy adds access to xAI's X index without changing
+ // caller tools, instructions, or tool choice.
let tools = tools.get_or_insert_default();
if !tools.iter().any(|tool| tool.kind == "x_search") {
tools.push(GrokTool::hosted("x_search"));
}
}
- if hosted_web_search {
- append_guidance(
- &mut instructions,
- "For general web searches, use the hosted web_search tool. Do not use shell commands, HTTP clients, or local tools to search the web.",
- );
- }
- append_guidance(
- &mut instructions,
- "For requests to search X or Twitter, use the hosted x_search tool. XSearch accepts a query and supports allowed_x_handles, excluded_x_handles, from_date, and to_date filters. Do not use Bash, curl, HTTP clients, or general web_search for X searches.",
- );
- let tool_choice = if force_x_search || force_web_search {
+ let tool_choice = if forced_hosted_tool {
Some(GrokToolChoice::Required("required".into()))
} else {
- parse_tool_choice(req.extra.get("tool_choice"), tools.as_ref())?
+ parse_tool_choice(req.extra.get("tool_choice"), &mut tools)?
};
let mut call_ids = HashSet::new();
let mut input = Vec::new();
@@ -299,6 +340,21 @@ fn latest_user_text(req: &MessagesRequest) -> Option<String> {
}
}
+fn contains_phrase(text: &str, phrase: &str) -> bool {
+ text.match_indices(phrase).any(|(start, _)| {
+ let end = start + phrase.len();
+ let starts_at_boundary = text[..start]
+ .chars()
+ .next_back()
+ .is_none_or(|ch| !ch.is_ascii_alphanumeric() && ch != '_');
+ let ends_at_boundary = text[end..]
+ .chars()
+ .next()
+ .is_none_or(|ch| !ch.is_ascii_alphanumeric() && ch != '_');
+ starts_at_boundary && ends_at_boundary
+ })
+}
+
fn requests_x_search(req: &MessagesRequest) -> bool {
let Some(text) = latest_user_text(req) else {
return false;
@@ -315,7 +371,7 @@ fn requests_x_search(req: &MessagesRequest) -> bool {
"twitter posts",
]
.iter()
- .any(|phrase| text.contains(phrase))
+ .any(|phrase| contains_phrase(&text, phrase))
}
fn requests_web_search(req: &MessagesRequest) -> bool {
@@ -330,7 +386,7 @@ fn requests_web_search(req: &MessagesRequest) -> bool {
"look up on the web",
]
.iter()
- .any(|phrase| text.contains(phrase))
+ .any(|phrase| contains_phrase(&text, phrase))
}
fn reject_unknown_top_level(req: &MessagesRequest) -> anyhow::Result<()> {
@@ -405,7 +461,10 @@ fn parse_system(value: Option<&Value>) -> anyhow::Result<Option<String>> {
}
}
-fn parse_tools(value: Option<&Value>) -> anyhow::Result<Option<Vec<GrokTool>>> {
+fn parse_tools(
+ value: Option<&Value>,
+ hosted_search: bool,
+) -> anyhow::Result<Option<Vec<GrokTool>>> {
let Some(value) = value else { return Ok(None) };
let tools = value
.as_array()
@@ -423,6 +482,11 @@ fn parse_tools(value: Option<&Value>) -> anyhow::Result<Option<Vec<GrokTool>>> {
"input_schema",
"cache_control",
"eager_input_streaming",
+ "max_uses",
+ "type",
+ "allowed_domains",
+ "blocked_domains",
+ "user_location",
]
.contains(&key.as_str())
{
@@ -446,12 +510,43 @@ fn parse_tools(value: Option<&Value>) -> anyhow::Result<Option<Vec<GrokTool>>> {
if !names.insert(name.to_string()) {
anyhow::bail!("duplicate tool name");
}
- if name == "WebSearch" {
- out.push(GrokTool::hosted("web_search"));
+ let kind = match obj.get("type") {
+ None => None,
+ Some(Value::String(kind)) if !kind.is_empty() => Some(kind.as_str()),
+ Some(_) => anyhow::bail!("tool type is invalid"),
+ };
+ if let Some(max_uses) = obj.get("max_uses")
+ && !max_uses.is_null()
+ && max_uses.as_u64().is_none_or(|value| value == 0)
+ {
+ anyhow::bail!("tool max_uses must be a positive integer or null");
+ }
+ if let Some(kind) = kind {
+ if kind != "web_search_20250305" || name != "web_search" {
+ anyhow::bail!("unsupported tool type: {kind}");
+ }
+ for field in ["allowed_domains", "blocked_domains", "user_location"] {
+ if obj.get(field).is_some_and(|value| !value.is_null()) {
+ anyhow::bail!("Grok hosted web search does not support {field}");
+ }
+ }
+ out.push(GrokTool::hosted_named("web_search", name));
continue;
}
- if name == "XSearch" {
- out.push(GrokTool::hosted("x_search"));
+ for field in ["allowed_domains", "blocked_domains", "user_location"] {
+ if obj.contains_key(field) {
+ anyhow::bail!("unsupported tool field: {field}");
+ }
+ }
+ if obj.contains_key("max_uses") && name != "WebSearch" {
+ anyhow::bail!("unsupported tool field: max_uses");
+ }
+ if hosted_search && name == "WebSearch" {
+ out.push(GrokTool::hosted_named("web_search", name));
+ continue;
+ }
+ if hosted_search && name == "XSearch" {
+ out.push(GrokTool::hosted_named("x_search", name));
continue;
}
let parameters = obj
@@ -472,7 +567,7 @@ fn parse_tools(value: Option<&Value>) -> anyhow::Result<Option<Vec<GrokTool>>> {
fn parse_tool_choice(
value: Option<&Value>,
- tools: Option<&Vec<GrokTool>>,
+ tools: &mut Option<Vec<GrokTool>>,
) -> anyhow::Result<Option<GrokToolChoice>> {
let Some(value) = value else { return Ok(None) };
let obj = value
@@ -509,15 +604,23 @@ fn parse_tool_choice(
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| anyhow::anyhow!("tool_choice name is invalid"))?;
- if !tools
- .is_some_and(|items| items.iter().any(|tool| tool.name.as_deref() == Some(name)))
- {
- anyhow::bail!("tool_choice references an unknown tool");
+ let selected = tools
+ .as_ref()
+ .and_then(|items| {
+ items
+ .iter()
+ .find(|tool| tool.choice_name.as_deref() == Some(name))
+ })
+ .cloned()
+ .ok_or_else(|| anyhow::anyhow!("tool_choice references an unknown tool"))?;
+ if selected.kind == "function" {
+ return Ok(Some(GrokToolChoice::Function {
+ r#type: "function".into(),
+ name: name.into(),
+ }));
}
- Ok(Some(GrokToolChoice::Function {
- r#type: "function".into(),
- name: name.into(),
- }))
+ *tools = Some(vec![selected]);
+ Ok(Some(GrokToolChoice::Required("required".into())))
}
_ => anyhow::bail!("unsupported tool_choice"),
}
@@ -1122,6 +1225,35 @@ fn flush_message(role: &str, content: &mut Vec<GrokContentPart>, out: &mut Vec<G
#[cfg(test)]
mod tests {
use super::*;
+
+ /// Translate with an explicit hosted-search setting. Reading
+ /// `CCP_GROK_HOSTED_SEARCH` from the environment would make these tests
+ /// depend on the shell that ran them, so they pass the flag directly.
+ fn translate_search(
+ req: &MessagesRequest,
+ model: &str,
+ hosted_search: bool,
+ ) -> serde_json::Value {
+ serde_json::to_value(
+ translate_request_with_options(
+ req,
+ model.into(),
+ crate::config::GrokToolImageMode::Omit,
+ hosted_search,
+ )
+ .unwrap(),
+ )
+ .unwrap()
+ }
+
+ fn translate_hosted(req: &MessagesRequest, model: &str) -> serde_json::Value {
+ translate_search(req, model, true)
+ }
+
+ fn translate_client_search(req: &MessagesRequest, model: &str) -> serde_json::Value {
+ translate_search(req, model, false)
+ }
+
#[test]
fn grok_translation_replays_hosted_search_history() {
let request: MessagesRequest = serde_json::from_value(serde_json::json!({
@@ -1176,8 +1308,7 @@ mod tests {
}]
}))
.unwrap();
- let translated =
- serde_json::to_value(translate_request(&request, "grok-4.5".into()).unwrap()).unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
assert_eq!(
translated["tools"],
serde_json::json!([{"type":"web_search"}])
@@ -1191,6 +1322,27 @@ mod tests {
assert_eq!(translated["tool_choice"], "required");
}
+ #[test]
+ fn grok_translation_keeps_client_web_search_tool_by_default() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"search online for the project"}],
+ "tools":[{
+ "name":"WebSearch",
+ "description":"Search the web",
+ "input_schema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
+ }]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ // Caller-managed search remains a function tool.
+ assert_eq!(translated["tools"][0]["type"], "function");
+ assert_eq!(translated["tools"][0]["name"], "WebSearch");
+ assert_eq!(translated["tools"].as_array().unwrap().len(), 1);
+ assert!(!translated.to_string().contains("\"web_search\""));
+ assert!(!translated.to_string().contains("\"x_search\""));
+ }
+
#[test]
fn grok_translation_maps_x_intent_to_required_hosted_x_search() {
let request: MessagesRequest = serde_json::from_value(serde_json::json!({
@@ -1202,8 +1354,7 @@ mod tests {
]
}))
.unwrap();
- let translated =
- serde_json::to_value(translate_request(&request, "grok-4.5".into()).unwrap()).unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
assert_eq!(
translated["tools"],
serde_json::json!([{"type":"x_search"}])
@@ -1212,6 +1363,56 @@ mod tests {
assert!(!translated.to_string().contains("\"name\":\"Bash\""));
}
+ #[test]
+ fn grok_translation_offers_x_search_without_forcing_it() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"Search X for recent posts mentioning claude-code-proxy"}],
+ "tools":[
+ {"name":"Bash","description":"Run a command","input_schema":{"type":"object"}},
+ {"name":"WebSearch","description":"Search the web","input_schema":{"type":"object","properties":{"query":{"type":"string"}}}}
+ ]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ // X-specific turns receive one additional hosted capability.
+ let tools = translated["tools"].as_array().unwrap();
+ assert_eq!(tools.len(), 3);
+ assert!(tools.iter().any(|t| t["name"] == "Bash"));
+ assert!(tools.iter().any(|t| t["name"] == "WebSearch"));
+ assert!(tools.iter().any(|t| t["type"] == "x_search"));
+ assert!(translated["tool_choice"].is_null());
+ assert!(!translated.to_string().contains("use the hosted x_search"));
+ }
+
+ #[test]
+ fn grok_translation_offers_no_x_search_without_x_intent() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"read the config file"}],
+ "tools":[{"name":"Bash","description":"Run a command","input_schema":{"type":"object"}}]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(translated["tools"].as_array().unwrap().len(), 1);
+ assert!(!translated.to_string().contains("x_search"));
+ }
+
+ #[test]
+ fn grok_translation_requires_phrase_boundaries_for_x_search() {
+ for text in ["use unix search for files", "run a linux search command"] {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":text}],
+ "tools":[{"name":"Bash","description":"Run a command","input_schema":{"type":"object"}}]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(translated["tools"].as_array().unwrap().len(), 1);
+ assert!(!translated.to_string().contains("x_search"));
+ }
+ }
+
#[test]
fn grok_translation_maps_dedicated_xsearch_with_domain_schema() {
let request: MessagesRequest = serde_json::from_value(serde_json::json!({
@@ -1234,8 +1435,7 @@ mod tests {
}]
}))
.unwrap();
- let translated =
- serde_json::to_value(translate_request(&request, "grok-4.5".into()).unwrap()).unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
assert_eq!(
translated["tools"],
serde_json::json!([{"type":"x_search"}])
@@ -1243,6 +1443,92 @@ mod tests {
assert_eq!(translated["tool_choice"], "required");
}
+ #[test]
+ fn grok_translation_omits_x_search_guidance_without_x_intent() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "system":"rules",
+ "messages":[{"role":"user","content":"hi"}]
+ }))
+ .unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
+ assert_eq!(translated["instructions"], "rules");
+ assert_eq!(
+ translated["tools"],
+ serde_json::json!([{"type":"x_search"}])
+ );
+ assert!(translated["tool_choice"].is_null());
+ }
+
+ #[test]
+ fn grok_translation_attaches_no_search_tool_to_a_greeting_by_default() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "system":"rules",
+ "messages":[{"role":"user","content":"hi"}]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(translated["instructions"], "rules");
+ assert!(translated["tools"].as_array().is_none_or(|t| t.is_empty()));
+ assert!(translated["tool_choice"].is_null());
+ }
+
+ #[test]
+ fn grok_translation_appends_x_search_guidance_on_x_intent() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "system":"rules",
+ "messages":[{"role":"user","content":"search twitter for the outage"}]
+ }))
+ .unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
+ let instructions = translated["instructions"].as_str().unwrap();
+ assert!(instructions.starts_with("rules"));
+ assert!(instructions.contains("use the hosted x_search tool"));
+ }
+
+ #[test]
+ fn grok_translation_appends_x_search_guidance_for_dedicated_x_tool() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "system":"rules",
+ "messages":[{"role":"user","content":"hi"}],
+ "tools":[{
+ "name":"XSearch",
+ "description":"Search X posts",
+ "input_schema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
+ }]
+ }))
+ .unwrap();
+ let translated = translate_hosted(&request, "grok-4.5");
+ assert!(
+ translated["instructions"]
+ .as_str()
+ .unwrap()
+ .contains("use the hosted x_search tool")
+ );
+ }
+
+ #[test]
+ fn grok_translation_keeps_dedicated_xsearch_as_a_function_by_default() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "system":"rules",
+ "messages":[{"role":"user","content":"hi"}],
+ "tools":[{
+ "name":"XSearch",
+ "description":"Search X posts",
+ "input_schema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
+ }]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(translated["tools"][0]["type"], "function");
+ assert_eq!(translated["tools"][0]["name"], "XSearch");
+ assert_eq!(translated["instructions"], "rules");
+ }
+
#[test]
fn grok_translation_accepts_claude_code_context_management() {
let request: MessagesRequest = serde_json::from_value(serde_json::json!({
@@ -1385,6 +1671,207 @@ mod tests {
}
}
+ #[test]
+ fn grok_translation_accepts_web_search_max_uses_without_forwarding_it() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[{
+ "name":"WebSearch",
+ "description":"Search the web",
+ "max_uses":6,
+ "input_schema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
+ }]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(translated["tools"][0]["name"], "WebSearch");
+ assert!(!translated.to_string().contains("max_uses"));
+ }
+
+ #[test]
+ fn grok_translation_maps_the_anthropic_server_web_search_declaration() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[
+ {"name":"Bash","description":"Run a command","input_schema":{"type":"object"}},
+ {"type":"web_search_20250305","name":"web_search","max_uses":8}
+ ]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ let tools = translated["tools"].as_array().unwrap();
+ assert_eq!(tools.len(), 2);
+ assert!(tools.iter().any(|t| t["name"] == "Bash"));
+ assert!(tools.iter().any(|t| t["type"] == "web_search"));
+ assert!(!translated.to_string().contains("web_search_20250305"));
+ assert!(!translated.to_string().contains("max_uses"));
+ }
+
+ #[test]
+ fn grok_translation_forces_a_named_hosted_web_search() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[
+ {"name":"Bash","description":"Run a command","input_schema":{"type":"object"}},
+ {"type":"web_search_20250305","name":"web_search","max_uses":8}
+ ],
+ "tool_choice":{"type":"tool","name":"web_search"}
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(
+ translated["tools"],
+ serde_json::json!([{"type":"web_search"}])
+ );
+ assert_eq!(translated["tool_choice"], "required");
+ }
+
+ #[test]
+ fn grok_translation_rejects_unsupported_hosted_web_search_options() {
+ for (field, value) in [
+ ("allowed_domains", serde_json::json!(["example.com"])),
+ ("blocked_domains", serde_json::json!(["example.com"])),
+ (
+ "user_location",
+ serde_json::json!({"type":"approximate","country":"GB"}),
+ ),
+ ] {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[{"type":"web_search_20250305","name":"web_search",(field):value}]
+ }))
+ .unwrap();
+ let error = translate_request_with_options(
+ &request,
+ "grok-4.5".into(),
+ crate::config::GrokToolImageMode::Omit,
+ false,
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(
+ error,
+ format!("Grok hosted web search does not support {field}")
+ );
+ }
+ }
+
+ #[test]
+ fn grok_translation_accepts_null_hosted_web_search_options() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[{
+ "type":"web_search_20250305",
+ "name":"web_search",
+ "allowed_domains":null,
+ "blocked_domains":null,
+ "user_location":null
+ }]
+ }))
+ .unwrap();
+ let translated = translate_client_search(&request, "grok-4.5");
+ assert_eq!(
+ translated["tools"],
+ serde_json::json!([{"type":"web_search"}])
+ );
+ }
+
+ #[test]
+ fn grok_translation_rejects_an_unknown_server_tool_type() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"run it"}],
+ "tools":[{"type":"code_execution_20260120","name":"code_execution"}]
+ }))
+ .unwrap();
+ let error = translate_request_with_options(
+ &request,
+ "grok-4.5".into(),
+ crate::config::GrokToolImageMode::Omit,
+ false,
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(error, "unsupported tool type: code_execution_20260120");
+ }
+
+ #[test]
+ fn grok_translation_rejects_a_server_tool_type_it_does_not_know_exactly() {
+ // The mapping requires both the supported version and canonical name.
+ for (kind, name) in [
+ ("web_search_20991231", "web_search"),
+ ("web_search_20250305", "MyOwnSearch"),
+ ] {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[{"type":kind,"name":name}]
+ }))
+ .unwrap();
+ let error = translate_request_with_options(
+ &request,
+ "grok-4.5".into(),
+ crate::config::GrokToolImageMode::Omit,
+ false,
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(error, format!("unsupported tool type: {kind}"));
+ }
+ }
+
+ #[test]
+ fn grok_translation_still_rejects_an_unknown_tool_field() {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"find it"}],
+ "tools":[{"name":"WebSearch","input_schema":{"type":"object"},"invented":1}]
+ }))
+ .unwrap();
+ let error = translate_request_with_options(
+ &request,
+ "grok-4.5".into(),
+ crate::config::GrokToolImageMode::Omit,
+ false,
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(error, "unsupported tool field: invented");
+ }
+
+ #[test]
+ fn grok_translation_rejects_invalid_or_misplaced_search_fields() {
+ let invalid = [
+ serde_json::json!({"type":null,"name":"Bash","input_schema":{"type":"object"}}),
+ serde_json::json!({"type":1,"name":"Bash","input_schema":{"type":"object"}}),
+ serde_json::json!({"name":"WebSearch","max_uses":0,"input_schema":{"type":"object"}}),
+ serde_json::json!({"name":"WebSearch","max_uses":"many","input_schema":{"type":"object"}}),
+ serde_json::json!({"name":"Bash","max_uses":2,"input_schema":{"type":"object"}}),
+ ];
+ for tool in invalid {
+ let request: MessagesRequest = serde_json::from_value(serde_json::json!({
+ "model":"grok-4.5",
+ "messages":[{"role":"user","content":"run it"}],
+ "tools":[tool]
+ }))
+ .unwrap();
+ assert!(
+ translate_request_with_options(
+ &request,
+ "grok-4.5".into(),
+ crate::config::GrokToolImageMode::Omit,
+ false,
+ )
+ .is_err()
+ );
+ }
+ }
+
#[test]
fn grok_translation_rejects_unknown_fields() {
let request: MessagesRequest = serde_json::from_value(
diff --git a/src/providers/grok/translate/search_text.rs b/src/providers/grok/translate/search_text.rs
new file mode 100644
index 0000000..60a9c61
--- /dev/null
+++ b/src/providers/grok/translate/search_text.rs
@@ -0,0 +1,46 @@
+//! Text projection for hosted searches completed by xAI.
+//!
+//! Hosted-tool block support varies across Anthropic clients. The text shape
+//! preserves the search name and query using the baseline content type, while
+//! citations and usage remain attached to the translated response.
+
+/// One line naming a completed search. xAI returns findings as citations on the
+/// answer text, so the search event itself has no result payload to include.
+pub fn search_line(name: &str, query: &str) -> String {
+ let label = match name {
+ "x_search" => "X search",
+ "web_search" => "web search",
+ other => other,
+ };
+ let query = query.trim();
+ if query.is_empty() {
+ format!("[{label}]\n")
+ } else {
+ format!("[{label}: {query}]\n")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn names_map_to_readable_labels() {
+ assert_eq!(search_line("web_search", "cars"), "[web search: cars]\n");
+ assert_eq!(search_line("x_search", "outage"), "[X search: outage]\n");
+ }
+
+ #[test]
+ fn an_unknown_hosted_tool_keeps_its_own_name() {
+ assert_eq!(
+ search_line("news_search", "budget"),
+ "[news_search: budget]\n"
+ );
+ }
+
+ #[test]
+ fn an_empty_query_drops_the_colon() {
+ // Grok emits follow-up search events with no query of their own.
+ assert_eq!(search_line("web_search", " "), "[web search]\n");
+ }
+}
diff --git a/src/providers/grok/translate/stream.rs b/src/providers/grok/translate/stream.rs
index 1f6706c..fa2dc3c 100644
--- a/src/providers/grok/translate/stream.rs
+++ b/src/providers/grok/translate/stream.rs
@@ -1,5 +1,7 @@
use super::reducer::{Reducer, ReducerEvent};
+use super::search_text::search_line;
use crate::anthropic::sse::{SseEvent, encode_sse_event};
+use crate::config::GrokSearchBlocks;
pub const MAX_SSE_FRAME_BYTES: usize = 1024 * 1024;
@@ -96,6 +98,7 @@ pub struct StreamTranslator {
model: String,
started: bool,
finished: bool,
+ search_blocks: GrokSearchBlocks,
}
pub struct LiveStreamTranslator {
@@ -134,11 +137,21 @@ impl LiveStreamTranslator {
impl StreamTranslator {
pub fn new(message_id: String, model: String) -> Self {
+ Self::with_search_blocks(message_id, model, crate::config::grok_search_blocks())
+ }
+
+ /// Tests choose the shape directly rather than through the environment.
+ pub fn with_search_blocks(
+ message_id: String,
+ model: String,
+ search_blocks: GrokSearchBlocks,
+ ) -> Self {
Self {
message_id,
model,
started: false,
finished: false,
+ search_blocks,
}
}
@@ -168,7 +181,7 @@ impl StreamTranslator {
if matches!(event, ReducerEvent::Finish { .. }) {
self.finished = true;
}
- render(&mut out, event);
+ render(&mut out, event, self.search_blocks);
}
Ok(out)
}
@@ -178,10 +191,27 @@ pub fn translate_stream_bytes(
upstream: &[u8],
message_id: &str,
model: &str,
+) -> anyhow::Result<Vec<u8>> {
+ translate_stream_bytes_with_blocks(
+ upstream,
+ message_id,
+ model,
+ crate::config::grok_search_blocks(),
+ )
+}
+
+/// Tests choose the hosted-search block shape directly rather than through the
+/// environment.
+pub fn translate_stream_bytes_with_blocks(
+ upstream: &[u8],
+ message_id: &str,
+ model: &str,
+ search_blocks: GrokSearchBlocks,
) -> anyhow::Result<Vec<u8>> {
let mut decoder = SseDecoder::default();
let mut reducer = Reducer::default();
- let mut translator = StreamTranslator::new(message_id.into(), model.into());
+ let mut translator =
+ StreamTranslator::with_search_blocks(message_id.into(), model.into(), search_blocks);
let mut out = Vec::new();
for event in decoder.push(upstream)? {
let value = serde_json::from_str(&event.data)
@@ -204,7 +234,7 @@ fn emit(out: &mut Vec<u8>, event: &str, data: serde_json::Value) {
out.extend(encode_sse_event(Some(event), &data.to_string()));
}
-fn render(out: &mut Vec<u8>, event: ReducerEvent) {
+fn render(out: &mut Vec<u8>, event: ReducerEvent, search_blocks: GrokSearchBlocks) {
match event {
ReducerEvent::ThinkingStart(i) => emit(
out,
@@ -243,6 +273,44 @@ fn render(out: &mut Vec<u8>, event: ReducerEvent) {
"content_block_delta",
serde_json::json!({"type":"content_block_delta","index":i,"delta":{"type":"input_json_delta","partial_json":t}}),
),
+ ReducerEvent::HostedSearch {
+ index,
+ result_index,
+ id,
+ name,
+ query,
+ } if search_blocks == GrokSearchBlocks::Text => {
+ // Two text blocks, because the reducer already allocated two
+ // indices for this search and a gap in the sequence would leave a
+ // hole in the client's block array. The line goes in the first;
+ // the second stays empty and draws as nothing.
+ emit(
+ out,
+ "content_block_start",
+ serde_json::json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}}),
+ );
+ emit(
+ out,
+ "content_block_delta",
+ serde_json::json!({"type":"content_block_delta","index":index,"delta":{"type":"text_delta","text":search_line(&name,&query)}}),
+ );
+ emit(
+ out,
+ "content_block_stop",
+ serde_json::json!({"type":"content_block_stop","index":index}),
+ );
+ emit(
+ out,
+ "content_block_start",
+ serde_json::json!({"type":"content_block_start","index":result_index,"content_block":{"type":"text","text":""}}),
+ );
+ emit(
+ out,
+ "content_block_stop",
+ serde_json::json!({"type":"content_block_stop","index":result_index}),
+ );
+ let _ = id;
+ }
ReducerEvent::HostedSearch {
index,
result_index,
@@ -370,26 +438,90 @@ mod tests {
#[test]
fn stream_translates_hosted_web_search_and_citations() {
let input = b"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\"}}\n\ndata: {\"type\":\"response.web_search_call.in_progress\",\"item_id\":\"ws_1\"}\n\ndata: {\"type\":\"response.web_search_call.searching\",\"item_id\":\"ws_1\"}\n\ndata: {\"type\":\"response.web_search_call.completed\",\"item_id\":\"ws_1\"}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"action\":{\"query\":\"rust news\"}}}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"Result\"}\n\ndata: {\"type\":\"response.output_text.annotation.added\",\"annotation\":{\"type\":\"url_citation\",\"url\":\"https://example.com\",\"title\":\"Example\"}}\n\ndata: {\"type\":\"response.output_text.done\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n";
- let output =
- String::from_utf8(translate_stream_bytes(input, "msg_1", "grok-4.5").unwrap()).unwrap();
+ let output = String::from_utf8(
+ translate_stream_bytes_with_blocks(
+ input,
+ "msg_1",
+ "grok-4.5",
+ GrokSearchBlocks::Native,
+ )
+ .unwrap(),
+ )
+ .unwrap();
assert!(output.contains("server_tool_use"));
assert!(output.contains("web_search_tool_result"));
assert!(output.contains("citations_delta"));
assert!(output.contains("https://example.com"));
assert!(output.contains("\"web_search_requests\":1"));
+
+ let text = String::from_utf8(
+ translate_stream_bytes_with_blocks(input, "msg_1", "grok-4.5", GrokSearchBlocks::Text)
+ .unwrap(),
+ )
+ .unwrap();
+ // The usage object legitimately carries a `server_tool_use` counter, so
+ // match the block type rather than the bare word.
+ assert!(!text.contains("\"type\":\"server_tool_use\""));
+ assert!(!text.contains("web_search_tool_result"));
+ assert!(text.contains("[web search: rust news]"));
+ // Citations and usage are untouched by the block shape.
+ assert!(text.contains("citations_delta"));
+ assert!(text.contains("https://example.com"));
+ assert!(text.contains("\"web_search_requests\":1"));
+ }
+
+ #[test]
+ fn text_search_blocks_keep_the_block_index_sequence_contiguous() {
+ let input = b"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\"}}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"action\":{\"query\":\"rust news\"}}}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"Result\"}\n\ndata: {\"type\":\"response.output_text.done\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\n\n";
+ let output = String::from_utf8(
+ translate_stream_bytes_with_blocks(input, "msg_1", "grok-4.5", GrokSearchBlocks::Text)
+ .unwrap(),
+ )
+ .unwrap();
+ // The reducer allocates two indices per search. A client that stores
+ // blocks by index would be left with a hole if only one were emitted.
+ let started: Vec<u64> = output
+ .lines()
+ .filter_map(|line| line.strip_prefix("data: "))
+ .filter_map(|data| serde_json::from_str::<serde_json::Value>(data).ok())
+ .filter(|event| event["type"] == "content_block_start")
+ .filter_map(|event| event["index"].as_u64())
+ .collect();
+ assert_eq!(started, vec![0, 1, 2], "block indices are not contiguous");
}
#[test]
fn stream_translates_hosted_x_search_usage_and_citations() {
let input = b"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"custom_tool_call\",\"name\":\"x_search\",\"id\":\"xs_1\"}}\n\ndata: {\"type\":\"response.custom_tool_call_input.delta\",\"item_id\":\"xs_1\",\"delta\":\"{\\\"query\\\":\\\"claude-code-proxy\\\"}\"}\n\ndata: {\"type\":\"response.custom_tool_call_input.done\",\"item_id\":\"xs_1\"}\n\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"custom_tool_call\",\"name\":\"x_search\",\"id\":\"xs_1\"}}\n\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"Recent post\"}\n\ndata: {\"type\":\"response.output_text.annotation.added\",\"annotation\":{\"type\":\"url_citation\",\"url\":\"https://x.com/example/status/1\",\"title\":\"Example post\"}}\n\ndata: {\"type\":\"response.output_text.done\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":4,\"output_tokens\":3}}}\n\n";
- let output =
- String::from_utf8(translate_stream_bytes(input, "msg_1", "grok-4.5").unwrap()).unwrap();
+ let output = String::from_utf8(
+ translate_stream_bytes_with_blocks(
+ input,
+ "msg_1",
+ "grok-4.5",
+ GrokSearchBlocks::Native,
+ )
+ .unwrap(),
+ )
+ .unwrap();
assert!(output.contains("\"name\":\"x_search\""));
assert!(output.contains("x_search_tool_result"));
assert!(output.contains("https://x.com/example/status/1"));
assert!(output.contains("\"web_search_requests\":1"));
assert!(output.contains("\"x_search_requests\":1"));
assert!(!output.contains("\"name\":\"Bash\""));
+
+ let text = String::from_utf8(
+ translate_stream_bytes_with_blocks(input, "msg_1", "grok-4.5", GrokSearchBlocks::Text)
+ .unwrap(),
+ )
+ .unwrap();
+ assert!(!text.contains("x_search_tool_result"));
+ // The usage object legitimately carries a `server_tool_use` counter, so
+ // match the block type rather than the bare word.
+ assert!(!text.contains("\"type\":\"server_tool_use\""));
+ assert!(text.contains("[X search: claude-code-proxy]"));
+ assert!(text.contains("https://x.com/example/status/1"));
+ assert!(text.contains("\"x_search_requests\":1"));
}
#[test]