Skip to content

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

Rust

Respect stop reasons before running native tool calls (#544)

Afloat6615caa7e4bf
diff --git a/crates/ai/src/agent.rs b/crates/ai/src/agent.rs
index cfbf9581..f846d32e 100644
--- a/crates/ai/src/agent.rs
+++ b/crates/ai/src/agent.rs
@@ -371,6 +371,7 @@ impl AgentLoop {
}
StopReason::PauseTurn => {
self.history.push(result.message);
+ self.record_unrun_tools(&uses);
continue;
}
StopReason::ToolUse if !uses.is_empty() => {
@@ -399,6 +400,7 @@ impl AgentLoop {
}
_ => {
self.history.push(result.message);
+ self.record_unrun_tools(&uses);
break;
}
}
@@ -414,6 +416,22 @@ impl AgentLoop {
});
}
+ /// Pair retained calls left unexecuted by a stop reason before reusing the history.
+ fn record_unrun_tools(&mut self, uses: &[(String, String, Value)]) {
+ if uses.is_empty() {
+ return;
+ }
+ let blocks = uses
+ .iter()
+ .map(|(id, _, _)| Block::ToolResult {
+ tool_use_id: id.clone(),
+ content: "Not run: the reply stopped without requesting tool execution.".into(),
+ is_error: true,
+ })
+ .collect();
+ self.history.push(Msg { role: Speaker::User, blocks });
+ }
+
/// Keep the conversation in its transcript file, when it has one.
fn save_transcript(&self) {
if let Some(p) = &self.cfg.transcript
diff --git a/crates/ai/src/openai.rs b/crates/ai/src/openai.rs
index c83ab562..6ddbbb48 100644
--- a/crates/ai/src/openai.rs
+++ b/crates/ai/src/openai.rs
@@ -303,8 +303,8 @@ impl ChatStream {
None if self.done => StopReason::EndTurn,
None => return Err(ToolError::new(ErrorCode::Truncated, "The answer stream ended early.")),
};
- // Some servers say "stop" even when they emitted tool calls.
- let stop = if has_calls { StopReason::ToolUse } else { stop };
+ // Some servers say "stop" for tool calls. A limit or refusal must still prevent execution.
+ let stop = if has_calls && stop == StopReason::EndTurn { StopReason::ToolUse } else { stop };
let model = if self.model.is_empty() { fallback_model.to_string() } else { self.model };
Ok(TurnResult { message: Msg { role: Speaker::Assistant, blocks }, stop, usage: self.usage, model })
}
@@ -455,6 +455,33 @@ mod tests {
);
}
+ #[test]
+ fn native_tool_calls_preserve_terminal_stop_reasons() {
+ for (finish, expected) in [
+ (Some("length"), StopReason::MaxTokens),
+ (Some("content_filter"), StopReason::Refusal),
+ (Some("pause_turn"), StopReason::PauseTurn),
+ (Some("provider_stop"), StopReason::Other("provider_stop".into())),
+ (Some("tool_calls"), StopReason::ToolUse),
+ (Some("stop"), StopReason::ToolUse),
+ (None, StopReason::ToolUse),
+ ] {
+ let mut stream = ChatStream::default();
+ let call = json!({"choices":[{"delta":{"tool_calls":[{
+ "index":0,"id":"call_a","function":{"name":"core_session_show","arguments":"{}"}
+ }]}}]});
+ stream.apply(&SseEvent { event: None, data: call.to_string() }, &mut |_| {}).unwrap();
+ if let Some(reason) = finish {
+ let end = json!({"choices":[{"delta":{},"finish_reason":reason}]});
+ stream.apply(&SseEvent { event: None, data: end.to_string() }, &mut |_| {}).unwrap();
+ }
+ stream.apply(&SseEvent { event: None, data: "[DONE]".into() }, &mut |_| {}).unwrap();
+ let result = stream.finish("m").unwrap();
+ assert_eq!(result.stop, expected, "finish_reason={finish:?}");
+ assert_eq!(result.message.tool_uses(), vec![("call_a".into(), "core_session_show".into(), json!({}))]);
+ }
+ }
+
#[test]
fn wire_messages() {
let o = OpenAi::openrouter(None, "k".into(), "");
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index ecb66aea..1c893abf 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -460,6 +460,105 @@ fn openai_streaming_tool_loop() {
assert_eq!(msgs[3]["tool_call_id"], "call_a");
}
+#[test]
+fn native_tool_stop_reasons_are_respected_before_execution() {
+ for (finish, run_tool) in [("length", false), ("content_filter", false), ("stop", true), ("tool_calls", true)] {
+ let first = chat_sse(&[
+ json!({"choices":[{"delta":{"tool_calls":[{
+ "index":0,"id":"call_a","type":"function","function":{"name":"core_session_show","arguments":"{}"}
+ }]}}]}),
+ json!({"choices":[{"delta":{},"finish_reason":finish}]}),
+ ]);
+ let mut responses = vec![(200, "text/event-stream", first)];
+ if finish != "content_filter" {
+ let last = chat_sse(&[json!({"choices":[{"delta":{"content":"Done."},"finish_reason":"stop"}]})]);
+ responses.push((200, "text/event-stream", last));
+ }
+ let (url, seen) = mock(responses);
+ let (h, _dir) = hub();
+ add(&h, "GPT", BackendKind::Openai, &url, Some("sk-test"));
+ let mut conversation = h.start(Some("GPT"), false).unwrap();
+ let events = run(&mut conversation, "status?");
+ let started = events.iter().filter(|event| matches!(event, AgentEvent::ToolStarted { .. })).count();
+ let completed = events.iter().filter(|event| matches!(event, AgentEvent::ToolFinished { tool, ok: true, .. } if tool == "core_session_show")).count();
+ assert_eq!(started, usize::from(run_tool), "finish_reason={finish}: {events:?}");
+ assert_eq!(completed, usize::from(run_tool), "finish_reason={finish}: {events:?}");
+ let seen = seen.lock().unwrap();
+ if finish == "content_filter" {
+ assert_eq!(seen.len(), 1, "a refused turn must not request a continuation");
+ assert!(events.iter().any(|event| matches!(event, AgentEvent::Error { message, .. } if message.contains("declined"))));
+ } else {
+ assert_eq!(seen.len(), 2);
+ let messages = seen[1].body["messages"].as_array().unwrap();
+ let result = messages.last().unwrap();
+ assert_eq!(result["role"], "tool");
+ assert_eq!(result["tool_call_id"], "call_a");
+ assert_eq!(result["content"].as_str().unwrap().starts_with("Not run: the reply hit the output limit"), finish == "length");
+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "Done.")));
+ }
+ }
+}
+
+fn assert_unexecuted_native_tool_calls_are_paired(finish: &str) {
+ let first = chat_sse(&[
+ json!({"choices":[{"delta":{"content":"Stopped before executing.","tool_calls":[
+ {"index":0,"id":"call_a","type":"function","function":{"name":"core_session_show","arguments":"{}"}},
+ {"index":1,"id":"call_b","type":"function","function":{"name":"core_session_show","arguments":"{}"}}
+ ]}}]}),
+ json!({"choices":[{"delta":{},"finish_reason":finish}]}),
+ ]);
+ let last = chat_sse(&[json!({"choices":[{"delta":{"content":"Done."},"finish_reason":"stop"}]})]);
+ let (url, seen) = mock(vec![(200, "text/event-stream", first), (200, "text/event-stream", last)]);
+ let (h, _dir) = hub();
+ add(&h, "GPT", BackendKind::Openai, &url, Some("sk-test"));
+ let mut conversation = h.start(Some("GPT"), false).unwrap();
+ let mut events = run(&mut conversation, "status?");
+ if finish != "pause_turn" {
+ assert_eq!(seen.lock().unwrap().len(), 1, "{finish} must wait for the next user turn");
+ events.extend(run(&mut conversation, "Continue when ready."));
+ }
+ assert!(
+ !events.iter().any(|event| matches!(event, AgentEvent::ToolStarted { .. } | AgentEvent::ToolFinished { .. } | AgentEvent::ConsentNeeded { .. })),
+ "stopped calls must not run or ask for consent: {events:?}"
+ );
+ assert!(!events.iter().any(|event| matches!(event, AgentEvent::Error { .. })), "{events:?}");
+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "Done.")), "{events:?}");
+ let seen = seen.lock().unwrap();
+ assert_eq!(seen.len(), 2, "{finish}: one stopped response and one continuation");
+ let messages = seen[1].body["messages"].as_array().unwrap();
+ let call_at = messages.iter().position(|message| message["tool_calls"].is_array()).unwrap();
+ assert_eq!(messages[call_at]["tool_calls"].as_array().unwrap().len(), 2);
+ assert_eq!(messages[call_at]["content"], "Stopped before executing.");
+ for (offset, id) in ["call_a", "call_b"].into_iter().enumerate() {
+ let result = messages.get(call_at + offset + 1);
+ assert_eq!(result.and_then(|message| message["role"].as_str()), Some("tool"), "{finish}: each retained call needs a result: {messages:?}");
+ let result = result.unwrap();
+ assert_eq!(result["tool_call_id"], id);
+ assert!(result["content"].as_str().unwrap().starts_with("Not run:"), "{result:?}");
+ }
+ if finish == "pause_turn" {
+ assert_eq!(messages.last().unwrap()["tool_call_id"], "call_b", "a pause continues without another user request");
+ } else {
+ assert_eq!(messages.last().unwrap()["role"], "user");
+ assert_eq!(messages.last().unwrap()["content"], "Continue when ready.");
+ }
+}
+
+#[test]
+fn paused_native_tool_calls_keep_history_paired() {
+ assert_unexecuted_native_tool_calls_are_paired("pause_turn");
+}
+
+#[test]
+fn sequence_stopped_native_tool_calls_keep_history_paired() {
+ assert_unexecuted_native_tool_calls_are_paired("stop_sequence");
+}
+
+#[test]
+fn provider_stopped_native_tool_calls_keep_history_paired() {
+ assert_unexecuted_native_tool_calls_are_paired("provider_stop");
+}
+
#[test]
fn local_server_without_tools_falls_back_to_react() {
let t1 = chat_sse(&[json!({"choices":[{"delta":{"content":"Thought: check\nAction: core_session_show\nAction Input: {}"},"finish_reason":"stop"}]})]);
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 19b1828f..d41582eb 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -196,6 +196,9 @@ been run live.
`invalid message content type: <nil>`: send an empty string
- [ ] Understand a tool call a model writes as JSON in its text (#417). The fallback protocol reads
only `Action:` and `Action Input:` lines, so anything else ends the turn with nothing done
+- [x] Preserve `length` and `content_filter` stop reasons on native tool-call streams; a parsed
+ call must not override truncation or refusal and execute tools. Pair other retained
+ unexecuted calls with results before the conversation continues — PR #544
- [ ] Accept a tool argument of a near type, such as a list for a string, or answer so the model
can correct it (#498)
- [ ] Find how each local server is told its context size and set it, or stop with a plain message
diff --git a/docs/STATUS.md b/docs/STATUS.md
index a21332b7..088d97a5 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -46,6 +46,22 @@ bytes. Reading or unpacking preserves those bytes. Synthetic graphs cover UTF-16
surrogate pair), Latin1 and binary members across both supported module-record and offsets-block
sizes. A freshly compiled Bun program and the CLI/MCP transport were not run for this correction.
+### Native tool-call stop reasons
+
+Native OpenAI-compatible tool calls retain a reported output limit or refusal instead of
+replacing it with a tool-use stop. The conversation can therefore reject those calls before
+running a tool, including calls whose arguments happen to be valid JSON. A normal `stop`
+with tool calls still works for servers that omit `tool_calls` as the finish reason.
+Calls retained after a pause or another terminal stop get matching non-execution results,
+so subsequent requests keep valid tool-call history. A pause continues the same turn;
+terminal stops wait for the next user message.
+Checked with streamed-call fixtures and HTTP/SSE stand-ins through the real conversation
+and engine loop. Three history-pairing regressions fail without the follow-up and pass with
+it. The affected crate's 223 tests and Clippy checks passed locally. The initial stop-reason
+correction also passed [hosted CI](https://github.com/storytold/craft-anything/actions/runs/41587580930)
+in PR #544. This correction concerns reported finish reasons; handling of a missing finish
+reason is unchanged. No live provider or local-model build was run.
+
### Linux Unreal setup
Unreal installations registered in `~/.config/Epic/UnrealEngine/Install.ini` are found on Linux.
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 9e0e2fc2..e74e9ca6 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -385,6 +385,11 @@ the final check failed a finished build; Try again then studied the original aga
builder the first brief. A run decides what's left from what the project records, not from which
button started it, and a check that couldn't look says nothing about the build.
+**A stopped tool call broke the next request.** Retaining a stopped assistant reply kept its
+tool calls without matching results. The next model request then carried unpaired calls.
+Every retained call needs a matching result, including an explicit non-execution result.
+Test the next serialized request as well as whether a tool ran.
+
**A filter written for one kind of text, run on another.** The stand-in's secret scan was written for
API answers, then also ran on recorded scripts: `this.token=t` became `[dropped]` and the scripts
broke, and "Basic Membership" lost a word. It also tested whole tokens, so a secret inside a URL or