Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Send a tool call's thought signature back to Gemini, and show errors it wraps in an array (#991)

BFlat3c5092a6c581
diff --git a/crates/ai/src/anthropic.rs b/crates/ai/src/anthropic.rs
index 8dfc84b7..9b6fd850 100644
--- a/crates/ai/src/anthropic.rs
+++ b/crates/ai/src/anthropic.rs
@@ -122,14 +122,17 @@ pub fn message_json(m: &Msg) -> Value {
let content: Vec<Value> = m
.blocks
.iter()
- .map(|b| match b {
- Block::Text { text } => json!({"type": "text", "text": text}),
- Block::Thinking { thinking, signature } => json!({"type": "thinking", "thinking": thinking, "signature": signature}),
- Block::RedactedThinking { data } => json!({"type": "redacted_thinking", "data": data}),
- Block::ToolUse { id, name, input } => json!({"type": "tool_use", "id": id, "name": name, "input": input}),
- Block::ToolResult { tool_use_id, content, is_error } => {
- json!({"type": "tool_result", "tool_use_id": tool_use_id, "content": content, "is_error": is_error})
- }
+ .filter_map(|b| {
+ Some(match b {
+ Block::Text { text } => json!({"type": "text", "text": text}),
+ Block::Thinking { thinking, signature } => json!({"type": "thinking", "thinking": thinking, "signature": signature}),
+ Block::RedactedThinking { data } => json!({"type": "redacted_thinking", "data": data}),
+ Block::ToolUse { id, name, input } => json!({"type": "tool_use", "id": id, "name": name, "input": input}),
+ Block::ToolExtra { .. } => return None,
+ Block::ToolResult { tool_use_id, content, is_error } => {
+ json!({"type": "tool_result", "tool_use_id": tool_use_id, "content": content, "is_error": is_error})
+ }
+ })
})
.collect();
json!({"role": role, "content": content})
diff --git a/crates/ai/src/context.rs b/crates/ai/src/context.rs
index 9c78f8c8..827a45b9 100644
--- a/crates/ai/src/context.rs
+++ b/crates/ai/src/context.rs
@@ -35,6 +35,7 @@ pub fn estimate_tokens(history: &[Msg]) -> u64 {
Block::Thinking { thinking, .. } => thinking.len(),
Block::RedactedThinking { data } => data.len(),
Block::ToolUse { input, name, .. } => name.len() + input.to_string().len(),
+ Block::ToolExtra { extra, .. } => extra.to_string().len(),
Block::ToolResult { content, .. } => content.len(),
})
.sum();
diff --git a/crates/ai/src/http.rs b/crates/ai/src/http.rs
index 537e9fe7..412e6e05 100644
--- a/crates/ai/src/http.rs
+++ b/crates/ai/src/http.rs
@@ -40,9 +40,11 @@ fn net_error(what: &str, e: ureq::Error) -> ToolError {
/// Turn a non-2xx response into a plain error. Keys are never echoed.
pub fn status_error(what: &str, status: u16, body: &str) -> ToolError {
- let detail: String = serde_json::from_str::<Value>(body)
- .ok()
- .map(|value| response_detail(&value).unwrap_or_else(|| "The service didn't provide an error message.".into()))
+ // Gemini's OpenAI-compatible endpoint wraps its error in a one-item array.
+ let parsed = serde_json::from_str::<Value>(body).ok().map(|v| if let Value::Array(a) = &v { a.first().cloned().unwrap_or(v) } else { v });
+ let detail: String = parsed
+ .as_ref()
+ .map(|value| response_detail(value).unwrap_or_else(|| "The service didn't provide an error message.".into()))
.unwrap_or_else(|| body.chars().take(300).collect())
.chars()
.take(1000)
@@ -55,8 +57,8 @@ pub fn status_error(what: &str, status: u16, body: &str) -> ToolError {
500..=599 => (ErrorCode::EngineMissing, "The service is having trouble. Try again soon, or use another backend."),
_ => (ErrorCode::BadInput, "The request was rejected; see the message."),
};
- let provider = serde_json::from_str::<Value>(body)
- .ok()
+ let provider = parsed
+ .as_ref()
.and_then(|v| v.pointer("/error/code").and_then(Value::as_str).or_else(|| v.pointer("/error/type").and_then(Value::as_str)).map(str::to_string));
ToolError::new(code, format!("{what} answered {status}: {detail}"))
.with_remediation(remediation)
@@ -379,6 +381,8 @@ mod tests {
#[test]
fn status_errors_are_plain() {
+ let e = status_error("Gemini", 400, r#"[{"error":{"code":400,"message":"Function call is missing a thought_signature"}}]"#);
+ assert_eq!(e.message, "Gemini answered 400: Function call is missing a thought_signature");
let e = status_error("Anthropic", 401, r#"{"error":{"message":"invalid x-api-key"}}"#);
assert_eq!(e.code, ErrorCode::NoPermission);
assert!(e.message.contains("invalid x-api-key"));
diff --git a/crates/ai/src/model.rs b/crates/ai/src/model.rs
index a13e76c9..b08e8ecd 100644
--- a/crates/ai/src/model.rs
+++ b/crates/ai/src/model.rs
@@ -26,6 +26,12 @@ pub enum Block {
name: String,
input: Value,
},
+ /// What the server attached to the tool call `tool_use_id`, sent back with it unchanged
+ /// (Gemini's thought signature: a call without it is refused).
+ ToolExtra {
+ tool_use_id: String,
+ extra: Value,
+ },
ToolResult {
tool_use_id: String,
content: String,
diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rs
index cba7b6e9..f274e434 100644
--- a/crates/ai/src/openai.rs
+++ b/crates/ai/src/openai.rs
@@ -274,7 +274,17 @@ pub fn messages_json(m: &Msg, react: bool) -> Vec<Value> {
let calls: Vec<Value> = m
.tool_uses()
.into_iter()
- .map(|(id, name, input)| json!({"id": id, "type": "function", "function": {"name": name, "arguments": input.to_string()}}))
+ .map(|(id, name, input)| {
+ let mut call = json!({"id": id, "type": "function", "function": {"name": name, "arguments": input.to_string()}});
+ let extra = m.blocks.iter().find_map(|b| match b {
+ Block::ToolExtra { tool_use_id, extra } if *tool_use_id == id => Some(extra.clone()),
+ _ => None,
+ });
+ if let (Some(extra), Some(o)) = (extra, call.as_object_mut()) {
+ o.insert("extra_content".into(), extra);
+ }
+ call
+ })
.collect();
if text.is_empty() && calls.is_empty() {
return Vec::new();
@@ -298,6 +308,7 @@ struct CallAcc {
id: String,
name: String,
args: String,
+ extra: Option<Value>,
}
/// Accumulates a streamed chat completion.
@@ -371,6 +382,9 @@ impl ChatStream {
if let Some(a) = c.pointer("/function/arguments").and_then(Value::as_str) {
acc.args.push_str(a);
}
+ if let Some(extra) = c.get("extra_content") {
+ acc.extra = Some(extra.clone());
+ }
}
}
if let Some(f) = choice.get("finish_reason").and_then(Value::as_str) {
@@ -389,7 +403,10 @@ impl ChatStream {
let input =
if c.args.trim().is_empty() { json!({}) } else { serde_json::from_str(&c.args).unwrap_or_else(|_| crate::anthropic::invalid_input(&c.args)) };
let id = if c.id.is_empty() { format!("call_{i}") } else { c.id };
- blocks.push(Block::ToolUse { id, name: c.name, input });
+ blocks.push(Block::ToolUse { id: id.clone(), name: c.name, input });
+ if let Some(extra) = c.extra {
+ blocks.push(Block::ToolExtra { tool_use_id: id, extra });
+ }
}
let stop = match self.finish.as_deref() {
Some(f) => StopReason::parse(f),
@@ -865,6 +882,27 @@ mod tests {
/// #369: OpenRouter routes to an upstream provider per request, and one without tool calling
/// answered "400: Provider returned error". With tools in the request, only providers that
/// support every parameter are used; nothing else changes.
+ /// #978: Gemini refuses a tool call sent back without the thought signature it came with.
+ #[test]
+ fn a_tool_calls_extra_content_goes_back_with_it() {
+ let extra = json!({"google": {"thought_signature": "sig"}});
+ let mut chat = ChatStream::default();
+ for call in [
+ json!({"index": 0, "id": "a", "extra_content": extra, "function": {"name": "look", "arguments": "{\"pa"}}),
+ json!({"index": 0, "function": {"arguments": "th"}}),
+ json!({"index": 1, "id": "b", "function": {"name": "look", "arguments": "{}"}}),
+ ] {
+ let data = json!({"choices": [{"delta": {"tool_calls": [call]}}]}).to_string();
+ chat.apply(&SseEvent { event: None, data }, &mut |_| {}).unwrap();
+ }
+ let message = chat.finish("m").unwrap().message;
+ let wire = messages_json(&message, false);
+ let calls = wire[0]["tool_calls"].as_array().unwrap();
+ assert_eq!(calls[0]["extra_content"], extra, "kept with the call whose arguments were cut off");
+ assert_eq!(calls[0]["function"]["name"], "look");
+ assert!(calls[1].get("extra_content").is_none(), "only on the call it came with");
+ }
+
#[test]
fn gemini_uses_the_google_endpoint_with_a_bearer_key() {
let g = OpenAi::gemini(None, "k".into(), "");
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 2f94f1a8..12e66e12 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -45,6 +45,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions |
| SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field |
| OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs; none over SSH yet). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. No live SSH host or paid generation used |
+| Gemini tool calls | A tool call's `extra_content` (Gemini's thought signature) goes back with it unchanged, so Gemini 3 builders get past their first tool call; errors Gemini wraps in an array show their message (#978) | Unit-tested; not run against the live API |
| Claude desktop app without Claude Code | When the `claude` command isn't found but the Claude desktop app is (Windows: the Store package's `claude-desktop` app alias or the older installer's `AnthropicClaude` folder; macOS: `Claude.app`), the builder dialog under "No coding agent was found" and `ai detect` (on stderr) say the desktop app is installed but building needs Claude Code, installed apart (#259). Typed as `DetectHint` from `AiHub::detect_hints` | A regression finds the app in temp folders laid out as each Windows installer leaves it, and nothing on Linux; a UI test shows the hint in the dialog. On Windows 10 the real Store package's alias was found. Not checked: macOS, the older installer, and a computer with no `claude` installed |
| Missing program paths | A program started by its path (a saved agent program, for one) that has no file there is reported with that path, as possibly moved by an update, with reason `path_missing`, instead of "isn't installed or isn't on your PATH"; a bare name still speaks of PATH. A relative path is looked up where the program starts (on Unix, its working folder), so a script there whose interpreter is missing isn't called a path with no file. It stays a missing program (`EngineMissing`), so builder turns aren't retried (#721). `ai test` names the agent program it ran and the saved one it replaced (`program`, `saved_program_replaced`), and `doctor` says a saved path has no program there | `a_saved_program_that_is_gone_is_named_by_test_and_doctor` runs both with a removed path. A regression starts a program at a path with no file on Windows 10 and checks the message, remediation and reason, with a bare-name control; on Linux (Docker), a relative script with a missing interpreter started in its folder, through `Process` and `Launch`. Not checked: a real Codex desktop update, or the app's Settings screen with a stale path |
| npm agents without Node on Windows | Programs are also looked for in nvm for Windows' version folders (`NVM_HOME`, else `%APPDATA%\nvm`, newest first, after `PATH`), so an npm shim such as `claude.cmd` finds Node when no `nvm use` link exists. When a shim's interpreter is still missing, starting it fails with `EngineMissing`, reason `interpreter_missing`, naming `node` and `nvm use`, instead of Rust's "batch file arguments are invalid" | On Windows 10 (Rust 1.99.1): unit tests for version-folder listing with nvm's own files beside the versions, the missing-interpreter check (no Node, Node on the search path, Node beside the shim) and the error's fields; the existing shim tests, including a real multi-line prompt through Node, and the platform crate's 70 tests pass. The failure was seen with Craft Anything 0.4.0 (Claude Code 1.0.96 npm shim, nvm with no version in use). Not checked: the fixed desktop app or CLI on that machine, and a build through a shim found only in nvm's folders |