Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/dim-agent-capabilities/src/agent_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
32 changes: 25 additions & 7 deletions crates/dim-agent-capabilities/src/tool_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,20 @@ struct State {
snapshots: HashMap<String, Snapshot>,
}

/// 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<ToolRegistry>,
state: Mutex<State>,
Expand Down Expand Up @@ -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<Arc<ToolContribution>, String> {
pub fn handler(
&self,
request_id: &str,
name: &str,
) -> Result<Arc<ToolContribution>, 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<Vec<ToolDefinition>, String> {
pub fn definitions(&self, request_id: &str) -> Result<Vec<ToolDefinition>, 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()
Expand All @@ -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(())
}
Expand Down
20 changes: 17 additions & 3 deletions crates/dim-agent-capabilities/src/tool_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<Vec<ToolDefinition>, 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
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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,
Expand Down
116 changes: 116 additions & 0 deletions crates/dim-agent-capabilities/tests/host_flows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5104,6 +5104,122 @@ async fn tool_result_estimates(with_image: bool) -> Vec<f64> {
estimates
}

/// Holds its first reply until released, then proposes one `echo` call;
/// later replies echo.
struct HeldToolCall {
entered: Arc<Notify>,
release: Arc<Notify>,
first: AtomicBool,
}
impl ModelDriver for HeldToolCall {
fn invoke(
&self,
request: Arc<ModelRequest>,
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;
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/rust-agent/tool-contributions.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,8 @@ Rust 绑定的 `ToolSourcesView::get/subscribe` 直接读取同一个状态和 w
| `bind(request_id, through, tools, tool_sources)` | Loop | 前缀(至 `through`)中已采用配置的声明与来源版本 → 登记快照;成功后按 7.6 释放旧 pin | `tool source <key>@<version> is unavailable`;`tool <name> 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<ToolContribution>`(`handler` 用于执行;审批用 `handler.risk(call)` 给出的单次 risk,没有时用 `definition.risk`) | `request <id> has no active tool binding`;`Unknown tool: <name>`。ToolExecutor 写成工具错误结果 |
| `transfer(from, to)` | Loop(预算恢复) | 原请求快照改登记到新 `request_id` | `from` 无快照 |
| `handler(request_id, name)` | ToolExecutor | → 快照中的 `Arc<ToolContribution>`(`handler` 用于执行;审批用 `handler.risk(call)` 给出的单次 risk,没有时用 `definition.risk`) | `UnknownTool`:快照里没有该名字,ToolExecutor 写成工具错误结果 `Unknown tool: <name>`;`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(重建后) | 释放其余快照 | — |

Expand Down