Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ai): coerce non-object tool_use input and stop logging previous_memory (#5565)

Eric Hayes7dd814e31d74
diff --git a/crates/agent/src/convert.rs b/crates/agent/src/convert.rs
index a81d3c6094..5b0f1c8bc4 100644
--- a/crates/agent/src/convert.rs
+++ b/crates/agent/src/convert.rs
@@ -145,12 +145,17 @@ fn convert_assistant(msg: &ChatMessage) -> Vec<Message> {
AssistantMessagePart::ToolCall { name, json, id }
| AssistantMessagePart::McpToolCall { name, json, id, .. } => {
saw_tool_call = true;
+ // Anthropic requires tool_use.input to be an object; older persisted
+ // messages may carry a non-object value from before this was enforced
+ // at the source (see hook.rs on_tool_call), so coerce here too.
+ let input = if json.is_object() {
+ json.clone()
+ } else {
+ serde_json::json!({})
+ };
assistant_parts.push(AssistantContent::ToolCall(
- ToolCall::new(
- replay_item_id(id),
- ToolFunction::new(name.clone(), json.clone()),
- )
- .with_call_id(replay_call_id(id)),
+ ToolCall::new(replay_item_id(id), ToolFunction::new(name.clone(), input))
+ .with_call_id(replay_call_id(id)),
));
}
AssistantMessagePart::ToolCallResponseJson { id, json, .. } => {
diff --git a/crates/agent/src/hook.rs b/crates/agent/src/hook.rs
index d66717e587..1dcabbc9cb 100644
--- a/crates/agent/src/hook.rs
+++ b/crates/agent/src/hook.rs
@@ -171,7 +171,10 @@ where
reason: CANCELLED_REASON.into(),
};
}
- let json = serde_json::from_str(args).unwrap_or(serde_json::Value::Null);
+ let json = serde_json::from_str(args)
+ .ok()
+ .filter(serde_json::Value::is_object)
+ .unwrap_or_else(|| serde_json::json!({}));
let id = tool_call_id.unwrap_or_else(|| internal_call_id.to_owned());
let mcp = (self.routing)(tool_name).map(|i| match i {
ToolInfo::ExternalTool {
diff --git a/crates/agent/src/test/test_convert.rs b/crates/agent/src/test/test_convert.rs
index 9d4626332b..c13dc2f334 100644
--- a/crates/agent/src/test/test_convert.rs
+++ b/crates/agent/src/test/test_convert.rs
@@ -311,6 +311,33 @@ fn trailing_separator_ids_are_trimmed_before_replay() {
}
}
+/// Anthropic's Messages API rejects a `tool_use.input` that is not a JSON
+/// object. Older persisted messages may carry a non-object `json` (e.g. from
+/// before the source of the value started guaranteeing an object); replay
+/// must coerce it to `{}` rather than resending the bad value.
+#[test]
+fn tool_call_with_non_object_json_coerces_to_empty_object() {
+ for bad in [json!(null), json!("oops"), json!([1, 2, 3])] {
+ let msg = assistant_parts(vec![AssistantMessagePart::ToolCall {
+ name: "ListSkills".to_owned(),
+ json: bad.clone(),
+ id: "call_1".to_owned(),
+ }]);
+ let messages = to_rig_messages(&[msg]);
+ let Message::Assistant { content, .. } = &messages[0] else {
+ panic!("expected assistant message");
+ };
+ let AssistantContent::ToolCall(call) = content.first() else {
+ panic!("expected tool call");
+ };
+ assert_eq!(
+ call.function.arguments,
+ json!({}),
+ "non-object json {bad:?} must coerce to an empty object"
+ );
+ }
+}
+
#[test]
fn mcp_tool_call_converts_like_regular_tool_call() {
let msg = assistant_parts(vec![AssistantMessagePart::McpToolCall {
diff --git a/crates/agent/src/test/test_hook.rs b/crates/agent/src/test/test_hook.rs
index 2b2d7e5326..46fd84a63d 100644
--- a/crates/agent/src/test/test_hook.rs
+++ b/crates/agent/src/test/test_hook.rs
@@ -1,6 +1,9 @@
use crate::hook::*;
+use crate::stream::StreamPart;
use ai_toolset::SearchableTool;
-use rig_core::agent::{HookAction, InvalidToolCallContext, InvalidToolCallHookAction, PromptHook};
+use rig_core::agent::{
+ HookAction, InvalidToolCallContext, InvalidToolCallHookAction, PromptHook, ToolCallHookAction,
+};
use rig_core::providers::anthropic::completion::CompletionModel as AnthropicModel;
use schemars::Schema;
use std::pin::Pin;
@@ -88,6 +91,74 @@ async fn on_tool_result_registers_nothing_when_buffer_empty() {
assert!(registered.lock().unwrap().is_empty());
}
+/// A bare bridge with no routing, no loaded-tool buffer, and an empty
+/// searchable catalog, for exercising [`StreamBridge::on_tool_call`] in
+/// isolation.
+fn bare_bridge() -> (
+ StreamBridge,
+ tokio::sync::mpsc::UnboundedReceiver<Result<StreamPart, crate::AgentError>>,
+) {
+ let (register, _registered) = recording_register();
+ StreamBridge::channel(
+ Arc::new(|_| None),
+ Arc::new(Mutex::new(Vec::new())),
+ register,
+ Arc::new(vec![]),
+ CancellationToken::new(),
+ )
+}
+
+#[tokio::test]
+async fn on_tool_call_parses_object_args() {
+ let (bridge, mut rx) = bare_bridge();
+
+ let action = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_call(
+ &bridge,
+ "Search",
+ None,
+ "call-1",
+ "{\"query\":\"cats\"}",
+ )
+ .await;
+
+ assert!(matches!(action, ToolCallHookAction::Continue));
+ let Ok(StreamPart::ToolCall(tool_call)) = rx.try_recv().unwrap() else {
+ panic!("expected a tool call");
+ };
+ assert_eq!(tool_call.json, serde_json::json!({"query": "cats"}));
+}
+
+/// Anthropic's Messages API rejects a `tool_use.input` that is not a JSON
+/// object. A zero-argument tool call can arrive with an empty or otherwise
+/// non-object `args` string; the hook must always hand back an object so a
+/// bad value never gets persisted into chat history and replayed later.
+#[tokio::test]
+async fn on_tool_call_coerces_non_object_args_to_empty_object() {
+ for args in ["", "null", "\"oops\"", "[1,2,3]", "not json at all"] {
+ let (bridge, mut rx) = bare_bridge();
+
+ let action = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_call(
+ &bridge,
+ "ListSkills",
+ None,
+ "call-1",
+ args,
+ )
+ .await;
+
+ assert!(matches!(action, ToolCallHookAction::Continue));
+ let Ok(StreamPart::ToolCall(tool_call)) = rx.try_recv().unwrap() else {
+ panic!("expected a tool call for args {args:?}");
+ };
+ assert_eq!(
+ tool_call.json,
+ serde_json::json!({}),
+ "args {args:?} must coerce to an empty object, not {:?}",
+ tool_call.json
+ );
+ }
+}
+
/// An [`InvalidToolCallContext`] for a model-emitted call to `tool_name`.
fn invalid_call(tool_name: &str) -> InvalidToolCallContext {
InvalidToolCallContext {
diff --git a/crates/memory/src/domain/service.rs b/crates/memory/src/domain/service.rs
index e025b666ec..73428baa40 100644
--- a/crates/memory/src/domain/service.rs
+++ b/crates/memory/src/domain/service.rs
@@ -152,7 +152,9 @@ impl<Rpo> MemoryServiceImpl<Rpo>
where
Rpo: MemoryRepo,
{
- #[tracing::instrument(skip(self), err)]
+ // `previous_memory` carries the user's full personal-memory profile; it
+ // must never be captured as a span field or it ends up verbatim in logs.
+ #[tracing::instrument(skip(self, previous_memory), err)]
async fn generate_memory(
&self,
user: macro_user_id::user_id::MacroUserIdStr<'static>,