From a2209356fe989619c0f12725e32e313c19ff6eb0 Mon Sep 17 00:00:00 2001 From: zerob13 Date: Mon, 23 Nov 2026 11:35:38 +0800 Subject: [PATCH] fix(tool-binding): tell a missing binding from an unknown tool ToolBinding's handler, definitions and transfer returned a String, so ToolExecutor wrote the internal 'request has no active tool binding' text into the tool result the model reads. They now return BindingError: UnknownTool keeps its model-facing text, NoActiveBinding is a runtime defect that is logged with its request id while the model reads only that the call did not run, and Loop reports a failed transfer as its own fault instead of invalid input. A flow test pins that a binding reload during a request settles the call as a reload without internal text. Refs #2028 --- .../dim-agent-capabilities/src/agent_loop.rs | 2 +- .../src/tool_binding.rs | 32 +++-- .../src/tool_executor.rs | 20 ++- .../tests/host_flows.rs | 116 ++++++++++++++++++ .../rust-agent/tool-contributions.md | 4 +- 5 files changed, 161 insertions(+), 13 deletions(-) diff --git a/crates/dim-agent-capabilities/src/agent_loop.rs b/crates/dim-agent-capabilities/src/agent_loop.rs index d712b50c08..345e07c19f 100644 --- a/crates/dim-agent-capabilities/src/agent_loop.rs +++ b/crates/dim-agent-capabilities/src/agent_loop.rs @@ -1211,7 +1211,7 @@ impl AgentLoop { owner .binding .transfer(&source.request_id, &request_id) - .map_err(AgentError::InvalidInput)?; + .map_err(|error| AgentError::fault("Loop", error.to_string()))?; source.turn_id = turn_id.clone(); source.request_id = request_id.clone(); return Ok((source, None)); diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 99f7e2777e..ee9f778e3a 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -51,6 +51,20 @@ struct State { snapshots: HashMap, } +/// Why a request's pinned tools cannot be read or moved. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BindingError { + /// The request holds no snapshot: it was never bound, or it was already + /// released. Loop and ToolExecutor reach only bound requests, so for them + /// this is a defect. + #[error("request {0} has no active tool binding")] + NoActiveBinding(String), + /// The request's snapshot has no tool of this name: the call names a tool + /// its request did not declare. + #[error("Unknown tool: {0}")] + UnknownTool(String), +} + pub struct ToolBinding { registry: Arc, state: Mutex, @@ -177,27 +191,31 @@ impl ToolBinding { /// The tool a call of `request_id` runs: its definition (for admission) /// and its handler, from the request's snapshot only. - pub fn handler(&self, request_id: &str, name: &str) -> Result, String> { + pub fn handler( + &self, + request_id: &str, + name: &str, + ) -> Result, BindingError> { let state = self.state.lock().unwrap(); let snapshot = state .snapshots .get(request_id) - .ok_or_else(|| format!("request {request_id} has no active tool binding"))?; + .ok_or_else(|| BindingError::NoActiveBinding(request_id.to_owned()))?; snapshot .tools .get(name) .cloned() - .ok_or_else(|| format!("Unknown tool: {name}")) + .ok_or_else(|| BindingError::UnknownTool(name.to_owned())) } /// Every declaration the request pinned, sorted by name, from the /// request's snapshot only. - pub fn definitions(&self, request_id: &str) -> Result, String> { + pub fn definitions(&self, request_id: &str) -> Result, BindingError> { let state = self.state.lock().unwrap(); let snapshot = state .snapshots .get(request_id) - .ok_or_else(|| format!("request {request_id} has no active tool binding"))?; + .ok_or_else(|| BindingError::NoActiveBinding(request_id.to_owned()))?; let mut definitions = snapshot .tools .values() @@ -208,12 +226,12 @@ impl ToolBinding { } /// Moves a request's snapshot to its budget recovery request. - pub fn transfer(&self, from: &str, to: &str) -> Result<(), String> { + pub fn transfer(&self, from: &str, to: &str) -> Result<(), BindingError> { let mut state = self.state.lock().unwrap(); let snapshot = state .snapshots .remove(from) - .ok_or_else(|| format!("request {from} has no active tool binding"))?; + .ok_or_else(|| BindingError::NoActiveBinding(from.to_owned()))?; state.snapshots.insert(to.to_owned(), snapshot); Ok(()) } diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index d01521cc85..3c08a9f2b0 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -3,7 +3,7 @@ pub mod read; use crate::{ approval::{AdmitCall, Approval}, host::*, - tool_binding::ToolBinding, + tool_binding::{BindingError, ToolBinding}, tool_registry::{ToolClaim, ToolConcurrency, ToolContribution}, }; use dim_agent_runtime::{ @@ -206,7 +206,7 @@ impl ToolExecutor { /// The declarations the request pinned, for a program that may only see /// the tools its own request declared. pub fn definitions(&self, request_id: &str) -> Result, String> { - self.binding.definitions(request_id) + self.binding.definitions(request_id).map_err(refusal) } /// Opens the child-call gate for the current top-level batch. A gate /// exists only while its context matches the current batch; a closed or @@ -694,7 +694,7 @@ async fn admit( let tool = match binding.handler(&context.request_id, &call.name) { Ok(tool) => tool, // An unknown tool is denied here, without an approval question. - Err(message) => return Err(HostError::failed(message)), + Err(error) => return Err(HostError::failed(refusal(error))), }; let claim = binding.take_claim(&context.request_id, &call.id); let risk = tool.handler.risk(&call).or(tool.definition.risk.as_deref()); @@ -723,6 +723,20 @@ async fn admit( Ok(Admitted { tool, claim, call }) } +/// The model-facing text of a call its request's binding refuses. An unknown +/// tool is the model's to correct; a missing binding is this runtime's defect, +/// logged with its request id, and the model reads only that the call did not +/// run. +fn refusal(error: BindingError) -> String { + match error { + BindingError::UnknownTool(_) => error.to_string(), + BindingError::NoActiveBinding(_) => { + tracing::error!(%error, "a tool call reached ToolExecutor without its request's binding"); + "Tool was not executed: its request has no tool binding".into() + } + } +} + /// Runs an admitted call through its handler. async fn run( admitted: Admitted, diff --git a/crates/dim-agent-capabilities/tests/host_flows.rs b/crates/dim-agent-capabilities/tests/host_flows.rs index 0af29380c5..5c9ed06044 100644 --- a/crates/dim-agent-capabilities/tests/host_flows.rs +++ b/crates/dim-agent-capabilities/tests/host_flows.rs @@ -5104,6 +5104,122 @@ async fn tool_result_estimates(with_image: bool) -> Vec { estimates } +/// Holds its first reply until released, then proposes one `echo` call; +/// later replies echo. +struct HeldToolCall { + entered: Arc, + release: Arc, + first: AtomicBool, +} +impl ModelDriver for HeldToolCall { + fn invoke( + &self, + request: Arc, + connection: ModelConnection, + cancel: CancellationToken, + ) -> HostFuture<'_, ModelStream> { + if self.first.swap(false, Ordering::SeqCst) { + Box::pin(async move { + self.entered.notify_one(); + self.release.notified().await; + let call = ToolCall { + id: "held-call".into(), + name: "echo".into(), + input: serde_json::json!({"text": "held"}) + .as_object() + .unwrap() + .clone(), + }; + Ok(Box::pin(futures_util::stream::iter([ + Ok(ModelChunk::MessageStart { + message_id: "held".into(), + }), + Ok(ModelChunk::ToolStart { + id: call.id.clone(), + name: call.name.clone(), + }), + Ok(ModelChunk::ToolUse(call)), + Ok(ModelChunk::MessageStop { + message_id: "held".into(), + reason: ModelStopReason::ToolUse, + }), + ])) as ModelStream) + }) + } else { + EchoModel.invoke(request, connection, cancel) + } + } +} + +/// ToolBinding reloads while the model streams a request it bound: its +/// consumers reload with it, so the call is never admitted against the new +/// generation, which holds no snapshot for the request. The call settles as +/// a reload settlement, and no internal request id reaches the model. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_call_whose_binding_reloaded_settles_as_a_reload_without_internal_text() { + tokio::time::timeout(Duration::from_secs(10), async { + let entered = Arc::new(Notify::new()); + let release = Arc::new(Notify::new()); + let builder = builder( + Arc::new(HeldToolCall { + entered: entered.clone(), + release: release.clone(), + first: AtomicBool::new(true), + }), + Arc::new(MockTools), + ); + let agent = MinimalHost::start(&builder).await.unwrap(); + let session = agent + .create_session(SessionConfig::default()) + .await + .unwrap(); + session + .submit("go".into(), InputMode::Queue, "main") + .await + .unwrap(); + entered.notified().await; + let binding = session + .branch_diagnostics("main") + .unwrap() + .plugins + .iter() + .find(|plugin| plugin.name == "ToolBinding") + .unwrap() + .id; + agent.root().view(binding).unwrap().restart().await.unwrap(); + release.notify_one(); + session.idle("main").await.unwrap(); + let events = chain_events(&session, "main", ..).await.unwrap(); + let result = events + .iter() + .find_map(|event| match &event.kind { + EventKind::ToolResult(data) => data + .results + .iter() + .find(|item| item.call_id == "held-call") + .map(|item| item.result.clone()), + _ => None, + }) + .expect("the held call settles"); + assert_eq!( + result.content, + ToolContent::Text(format!("Tool was not executed: {CAPABILITY_RELOADING}")), + "model-facing text of a call whose binding reloaded" + ); + assert!(events.iter().any(|event| matches!( + &event.kind, + EventKind::TurnEnd(TurnEndData { + outcome: TurnOutcome::Failed { error }, + .. + }) if error == CAPABILITY_RELOADING + ))); + assert!(session.failure().is_none()); + agent.close().await.unwrap(); + }) + .await + .unwrap(); +} + #[tokio::test] async fn a_tool_result_image_counts_as_one_image_in_the_estimate() { let with = tool_result_estimates(true).await; diff --git a/docs/architecture/rust-agent/tool-contributions.md b/docs/architecture/rust-agent/tool-contributions.md index 10abddd1a7..14b9d4ea92 100644 --- a/docs/architecture/rust-agent/tool-contributions.md +++ b/docs/architecture/rust-agent/tool-contributions.md @@ -279,8 +279,8 @@ Rust 绑定的 `ToolSourcesView::get/subscribe` 直接读取同一个状态和 w | `bind(request_id, through, tools, tool_sources)` | Loop | 前缀(至 `through`)中已采用配置的声明与来源版本 → 登记快照;成功后按 7.6 释放旧 pin | `tool source @ is unavailable`;`tool has no handler`(声明名在所绑集合与固定表中都不存在);`request_id` 已登记 | | `bind_current(request_id, declared: Option<_>)` | Loop | `None`:配置没有工具部分,声明注册表当前的宿主与注册工具;`Some`:核对显式声明 → 按注册表当前状态登记快照 | 声明名不存在或与当前定义不等 | | `prepare(request_id, prepare)` | Loop | 捕获并持有当前声明与来源集合,让宿主从这些声明选择本请求的工具,再以同一快照绑定其返回的声明 | 宿主准备失败;声明名不存在或与捕获的定义不等 | -| `handler(request_id, name)` | ToolExecutor | → 快照中的 `Arc`(`handler` 用于执行;审批用 `handler.risk(call)` 给出的单次 risk,没有时用 `definition.risk`) | `request has no active tool binding`;`Unknown tool: `。ToolExecutor 写成工具错误结果 | -| `transfer(from, to)` | Loop(预算恢复) | 原请求快照改登记到新 `request_id` | `from` 无快照 | +| `handler(request_id, name)` | ToolExecutor | → 快照中的 `Arc`(`handler` 用于执行;审批用 `handler.risk(call)` 给出的单次 risk,没有时用 `definition.risk`) | `UnknownTool`:快照里没有该名字,ToolExecutor 写成工具错误结果 `Unknown tool: `;`NoActiveBinding`:请求没有快照,对 ToolExecutor 是缺陷,记录带 id 的错误日志,模型只读到 `Tool was not executed: its request has no tool binding` | +| `transfer(from, to)` | Loop(预算恢复) | 原请求快照改登记到新 `request_id` | `NoActiveBinding`:`from` 无快照,Loop 以自身故障结束回合 | | `release(request_id)` | Loop | 释放快照;不存在时无操作 | — | | `retain_only(request_id: Option<_>)` | Loop(重建后) | 释放其余快照 | — |