From a7a3de1e40f09de98934e18fb1e4bc522996f68c Mon Sep 17 00:00:00 2001 From: wsp Date: Fri, 20 Nov 2026 10:27:02 +0800 Subject: [PATCH] fix(tools): Keep deferred specs valid across catalog refreshes Bind loaded specs to the contextual tool definition and provider so unrelated registrations no longer interrupt deferred calls. Apply the same check to native and programmatic calls and preserve compatibility with generation-only receipts in existing sessions. Fixes #4003 --- Cargo.lock | 1 + .../assembly/core/src/agentic/core/message.rs | 1 + .../core/src/agentic/tools/framework.rs | 5 + .../agentic/tools/pipeline/tool_pipeline.rs | 408 ++++++++++-------- .../src/agentic/tools/plugin_host_tool.rs | 37 +- .../core/src/agentic/tools/product_runtime.rs | 2 + .../agentic/tools/product_runtime/catalog.rs | 16 + .../product_runtime/get_tool_spec_tool.rs | 4 +- .../product_runtime/loaded_spec_state.rs | 13 +- .../core/src/agentic/tools/registry.rs | 2 + .../core/src/agentic/tools/tool_adapter.rs | 4 + .../src/agentic/tools/tool_context_runtime.rs | 2 + .../assembly/core/src/external_tools.rs | 4 + src/crates/assembly/core/src/plugin_host.rs | 11 +- .../core/src/service/snapshot/manager.rs | 4 + .../execution/tool-contracts/Cargo.toml | 1 + .../tool-contracts/src/execution_gate.rs | 17 +- .../execution/tool-contracts/src/framework.rs | 111 ++++- .../execution/tool-contracts/src/lib.rs | 2 +- .../tool-contracts/tests/tool_contracts.rs | 106 ++++- 20 files changed, 542 insertions(+), 209 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7e5e879918..80d7db5b85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5796,6 +5796,7 @@ dependencies = [ "openbitfun-runtime-ports", "serde", "serde_json", + "sha2", "tokio", ] diff --git a/src/crates/assembly/core/src/agentic/core/message.rs b/src/crates/assembly/core/src/agentic/core/message.rs index cf1f40f099..47fbbdf4ff 100644 --- a/src/crates/assembly/core/src/agentic/core/message.rs +++ b/src/crates/assembly/core/src/agentic/core/message.rs @@ -849,6 +849,7 @@ mod tests { vec![openbitfun_agent_tools::LoadedDeferredToolSpec { tool_name: "Read".into(), catalog_generation: 4, + spec_fingerprint: None, }]; message.metadata.model_execution = Some(super::ModelExecutionMetadata { model_config_id: "economy".into(), diff --git a/src/crates/assembly/core/src/agentic/tools/framework.rs b/src/crates/assembly/core/src/agentic/tools/framework.rs index 796e43de3b..dd70191c52 100644 --- a/src/crates/assembly/core/src/agentic/tools/framework.rs +++ b/src/crates/assembly/core/src/agentic/tools/framework.rs @@ -92,6 +92,11 @@ pub trait Tool: Send + Sync { None } + /// Stable contextual dispatch target for providers that multiplex same-name tools. + fn deferred_spec_route_id(&self, _context: &ToolUseContext) -> Option { + None + } + /// Rich metadata for dynamic tools. Prefer this over encoding dynamic ownership in tool names. fn dynamic_tool_info(&self) -> Option { self.dynamic_provider_id() diff --git a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs index dc41aa4c24..d9b99543a4 100644 --- a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs +++ b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs @@ -9,7 +9,8 @@ use crate::agentic::core::{ToolCall, ToolExecutionState, ToolResult as ModelTool use crate::agentic::events::types::ToolEventData; use crate::agentic::tools::computer_use_host::ComputerUseHostRef; use crate::agentic::tools::framework::ToolResult as FrameworkToolResult; -use crate::agentic::tools::registry::ToolRegistry; +use crate::agentic::tools::implementations::agent_collaboration::with_collaboration_model_policy; +use crate::agentic::tools::registry::{ToolRef, ToolRegistry}; use crate::agentic::tools::tool_context_runtime; use crate::agentic::tools::tool_context_runtime::ToolUseContext; use crate::agentic::tools::tool_result_storage; @@ -882,84 +883,22 @@ impl PtcToolCallHandler for PtcPipelineToolCallHandler { request: PtcToolSpecRequest, ) -> Result { let mut execution_context = self.context.clone(); - execution_context.loaded_deferred_tool_specs = - self.loaded_deferred_tool_specs.lock().await.clone(); if let Some(allowed_tools) = ToolPipeline::ptc_nested_allowed_tools(&execution_context) { execution_context.allowed_tools = allowed_tools; } - let mut context = tool_context_runtime::build_tool_use_context_for_execution_context( + let context = tool_context_runtime::build_tool_use_context_for_execution_context( &execution_context, None, self.pipeline.computer_use_host.clone(), CancellationToken::new(), None, ); - context.loaded_deferred_tool_specs = execution_context.loaded_deferred_tool_specs.clone(); - - let input = serde_json::json!({ "tool_name": request.tool_name }); - let results = - crate::agentic::tools::product_runtime::resolve_product_get_tool_spec_results( - &input, - &context, - GET_TOOL_SPEC_TOOL_NAME, - ) - .await - .map_err(|error| PortError::new(PortErrorKind::InvalidRequest, error.to_string()))?; - let value = results - .into_iter() - .find_map(|result| match result { - FrameworkToolResult::Result { data, .. } => Some(data), - FrameworkToolResult::StreamChunk { .. } | FrameworkToolResult::Progress { .. } => { - None - } - }) - .ok_or_else(|| { - PortError::new(PortErrorKind::Backend, "GetToolSpec returned no definition") - })?; - - let catalog_generation = value - .get("catalog_generation") - .and_then(serde_json::Value::as_u64) - .ok_or_else(|| { - PortError::new( - PortErrorKind::Backend, - "GetToolSpec result has no catalog generation", - ) - })?; - let tool_name = value - .get("tool_name") - .and_then(serde_json::Value::as_str) - .unwrap_or_default() - .to_string(); - - let tool = self - .pipeline - .tool_registry - .read() - .await - .get_tool(&tool_name) - .ok_or_else(|| { - PortError::new( - PortErrorKind::Backend, - format!("GetToolSpec returned no registered tool: {tool_name}"), - ) - })?; - let object = value.as_object().ok_or_else(|| { - PortError::new( - PortErrorKind::Backend, - "GetToolSpec result is not an object", - ) - })?; - let description = object - .get("description") - .and_then(serde_json::Value::as_str) - .unwrap_or_default() - .to_string(); - let input_schema = object - .get("input_schema") - .cloned() - .unwrap_or_else(|| serde_json::json!({})); - let output_schema = tool.output_schema(); + let detail = crate::agentic::tools::product_runtime::resolve_product_deferred_tool_detail( + &request.tool_name, + &context, + ) + .await + .map_err(|error| PortError::new(PortErrorKind::InvalidRequest, error))?; let language = if self .context .context_vars @@ -971,18 +910,28 @@ impl PtcToolCallHandler for PtcPipelineToolCallHandler { PtcLanguage::TypeScript }; let sdk_source = render_ptc_loaded_tool_sdk( - &PtcToolContract::new(tool_name.clone(), description, input_schema, output_schema), + &PtcToolContract::new( + detail.tool_name.clone(), + detail.description, + detail.input_schema, + detail.output_schema, + ), language, ); let mut loaded = self.loaded_deferred_tool_specs.lock().await; - if let Some(existing) = loaded.iter_mut().find(|spec| spec.tool_name == tool_name) { - existing.catalog_generation = catalog_generation; + let receipt = LoadedDeferredToolSpec { + tool_name: detail.tool_name, + catalog_generation: detail.catalog_generation, + spec_fingerprint: Some(detail.spec_fingerprint), + }; + if let Some(existing) = loaded + .iter_mut() + .find(|spec| spec.tool_name == receipt.tool_name) + { + *existing = receipt; } else { - loaded.push(LoadedDeferredToolSpec { - tool_name, - catalog_generation, - }); + loaded.push(receipt); } Ok(build_ptc_tool_spec_response(language, sdk_source)) } @@ -1735,6 +1684,48 @@ impl ToolPipeline { }); } + async fn admitted_tool( + &self, + task: &ToolTask, + context: &ToolUseContext, + ) -> Result, ToolExecutionAdmissionRejection> { + let name = &task.invocation.effective_tool_name; + let (tool, generation) = { + let registry = self.tool_registry.read().await; + ( + registry.get_tool(name), + registry.current_snapshot_generation(), + ) + }; + let request = ToolExecutionAdmissionRequest { + tool_name: name, + allowed_tools: &task.context.allowed_tools, + runtime_tool_restrictions: &task.context.runtime_tool_restrictions, + deferred_tools: &task.context.deferred_tools, + loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, + current_catalog_generation: generation, + get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, + }; + let fingerprint = async { + let selected = resolve_contextual_tool(tool.clone()?, context)?; + if !openbitfun_agent_tools::ContextualToolManifestItem::is_available_in_context( + selected.as_ref(), + context, + ) + .await + { + return None; + } + let detail = with_collaboration_model_policy( + openbitfun_agent_tools::contextual_tool_spec(selected.as_ref(), context), + ) + .await; + Some(detail.spec_fingerprint) + }; + validate_tool_execution_admission(request, fingerprint).await?; + Ok(tool) + } + async fn prepare_permission_plans(&self, task_ids: &[String]) -> OpenBitFunResult<()> { let mut drafts = Vec::with_capacity(task_ids.len()); let mut ordered_requests = Vec::new(); @@ -1764,27 +1755,10 @@ impl ToolPipeline { { continue; } - let tool = { - let registry = self.tool_registry.read().await; - if validate_tool_execution_admission(ToolExecutionAdmissionRequest { - tool_name: &tool_name, - allowed_tools: &task.context.allowed_tools, - runtime_tool_restrictions: &task.context.runtime_tool_restrictions, - deferred_tools: &task.context.deferred_tools, - loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, - current_catalog_generation: registry.current_snapshot_generation(), - get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, - }) - .is_err() - { - continue; - } - registry.get_tool(&tool_name) - }; - let Some(tool) = tool else { + let tool_context = self.build_tool_use_context(&task, CancellationToken::new()); + let Ok(Some(tool)) = self.admitted_tool(&task, &tool_context).await else { continue; }; - let tool_context = self.build_tool_use_context(&task, CancellationToken::new()); let validation = tool .validate_input(&task.invocation.effective_arguments, Some(&tool_context)) .await; @@ -2652,74 +2626,55 @@ impl ToolPipeline { // Repetition alone is not execution failure: polling and status checks // may legitimately reuse identical arguments. The execution engine // evaluates repeated patterns only after observing actual tool results. - let (admission, tool) = { - let registry = self.tool_registry.read().await; - let admission = validate_tool_execution_admission(ToolExecutionAdmissionRequest { - tool_name: &tool_name, - allowed_tools: &task.context.allowed_tools, - runtime_tool_restrictions: &task.context.runtime_tool_restrictions, - deferred_tools: &task.context.deferred_tools, - loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, - current_catalog_generation: registry.current_snapshot_generation(), - get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, - }); - ( - admission, - registry.get_tool(&tool_name).or_else(|| { - #[cfg(feature = "ptc-runtime")] - { - (tool_name == openbitfun_agent_tools::PTC_RUN_CODE_TOOL_NAME).then(|| { - Arc::new(crate::agentic::tools::implementations::PtcRunCodeTool::new()) - as Arc - }) - } - #[cfg(not(feature = "ptc-runtime"))] - { - None - } - }), - ) - }; - - if let Err(err) = admission { - let error_msg = err.to_string(); - if task.invocation.is_deferred() { - warn!("Deferred tool gateway admission rejected: {}", error_msg); - } else { - warn!("Tool execution admission rejected: {}", error_msg); - } + let cancellation_token = task + .options + .parent_cancellation_token + .as_ref() + .map(CancellationToken::child_token) + .unwrap_or_default(); + let tool_context = self.build_tool_use_context(&task, cancellation_token.clone()); + let tool = match self.admitted_tool(&task, &tool_context).await { + Ok(tool) => tool, + Err(err) => { + let error_msg = err.to_string(); + if task.invocation.is_deferred() { + warn!("Deferred tool gateway admission rejected: {}", error_msg); + } else { + warn!("Tool execution admission rejected: {}", error_msg); + } - self.state_manager - .update_state( - &tool_id, - ToolExecutionState::Failed { - error_detail: None, - error: error_msg, - is_retryable: false, - duration_ms: None, - queue_wait_ms: None, - preflight_ms: None, - confirmation_wait_ms: None, - execution_ms: None, - }, - ) - .await; + self.state_manager + .update_state( + &tool_id, + ToolExecutionState::Failed { + error_detail: None, + error: error_msg, + is_retryable: false, + duration_ms: None, + queue_wait_ms: None, + preflight_ms: None, + confirmation_wait_ms: None, + execution_ms: None, + }, + ) + .await; - return Err(map_tool_execution_admission_rejection(err)); - } + return Err(map_tool_execution_admission_rejection(err)); + } + }; + #[cfg(feature = "ptc-runtime")] + let tool = tool.or_else(|| { + (tool_name == openbitfun_agent_tools::PTC_RUN_CODE_TOOL_NAME).then(|| { + Arc::new(crate::agentic::tools::implementations::PtcRunCodeTool::new()) as ToolRef + }) + }); let registered_tool = tool.ok_or_else(|| { let error_msg = format!("Tool '{}' is not registered or enabled.", tool_name); error!("{}", error_msg); OpenBitFunError::tool(error_msg) })?; - let cancellation_token = task - .options - .parent_cancellation_token - .as_ref() - .map(CancellationToken::child_token) - .unwrap_or_default(); if cancellation_token.is_cancelled() { self.state_manager .update_state( @@ -2738,7 +2693,6 @@ impl ToolPipeline { "Tool was cancelled before validation".to_string(), )); } - let tool_context = self.build_tool_use_context(&task, cancellation_token.clone()); // Keep the registered mux in the execution path. It rechecks the // persisted conflict choice immediately before dispatch and applies // remote fail-closed routing from the full ToolUseContext. @@ -3779,6 +3733,7 @@ mod tests { LoadedDeferredToolSpec { tool_name: tool_name.to_string(), catalog_generation, + spec_fingerprint: None, } } @@ -4770,6 +4725,36 @@ mod tests { } } + #[cfg(feature = "ptc-runtime")] + #[tokio::test] + async fn ptc_get_tool_spec_reloads_the_sdk_and_retains_one_receipt() { + let mut context = test_tool_execution_context(); + context.agent_type = "Claw".into(); + let handler = PtcPipelineToolCallHandler { + pipeline: Arc::new(test_tool_pipeline()), + context, + options: ToolExecutionOptions::default(), + parent_tool_id: "run-code".into(), + loaded_deferred_tool_specs: Default::default(), + }; + for operation in ["first", "repeat"] { + let response = handler + .get_tool_spec(PtcToolSpecRequest { + operation_id: operation.into(), + tool_name: "SessionHistory".into(), + }) + .await + .unwrap(); + assert!(response["sdk_source"] + .as_str() + .unwrap() + .contains("SessionHistory")); + } + let loaded = handler.loaded_deferred_tool_specs.lock().await; + assert_eq!(loaded.len(), 1); + assert!(loaded[0].spec_fingerprint.is_some()); + } + #[cfg(feature = "ptc-runtime")] #[tokio::test] async fn ptc_run_code_dispatches_nested_calls_through_the_pipeline() { @@ -6362,7 +6347,64 @@ mod tests { } #[tokio::test] - async fn deferred_gateway_rejects_registry_refresh_before_execution() { + async fn deferred_gateway_keeps_loaded_spec_across_unrelated_refresh() { + let pipeline = test_tool_pipeline(); + let name = "get_weather"; + register_capturing_test_tool(&pipeline, name, Arc::new(Mutex::new(None))).await; + let mut context = test_tool_execution_context(); + context.allowed_tools = vec![CALL_DEFERRED_TOOL_NAME.into(), name.into()]; + context.deferred_tools = vec![name.into()]; + let use_context = tool_context_runtime::build_tool_use_context_for_execution_context( + &context, + None, + None, + CancellationToken::new(), + None, + ); + let tools = pipeline.tool_registry.read().await.get_all_tools(); + let mut detail = openbitfun_agent_tools::resolve_get_tool_spec_detail( + &tools, + name, + &use_context, + GET_TOOL_SPEC_TOOL_NAME, + ) + .await + .unwrap(); + detail.catalog_generation = current_registry_generation(&pipeline).await; + context.loaded_deferred_tool_specs = + vec![serde_json::from_value(detail.to_value()).unwrap()]; + + register_static_test_tool(&pipeline, "unrelated", json!(null), 0).await; + assert!(current_registry_generation(&pipeline).await > detail.catalog_generation); + let mut call = test_tool_call("before_replace", CALL_DEFERRED_TOOL_NAME); + call.arguments = json!({"tool_name": name, "args": {"city":"Shanghai"}}); + let results = pipeline + .execute_tools( + vec![call.clone()], + context.clone(), + ToolExecutionOptions::default(), + ) + .await + .unwrap(); + assert_eq!(results[0].result.result["received"]["city"], "Shanghai"); + + register_static_test_tool(&pipeline, name, json!({"replacement": true}), 0).await; + call.tool_id = "after_replace".into(); + let results = pipeline + .execute_tools(vec![call], context, ToolExecutionOptions::default()) + .await + .unwrap(); + assert!(results[0].result.is_error); + assert!(results[0] + .result + .result_for_assistant + .as_deref() + .unwrap() + .contains("is stale")); + } + + #[tokio::test] + async fn deferred_gateway_rejects_legacy_receipt_after_registry_refresh() { let pipeline = test_tool_pipeline(); let old_received_arguments = Arc::new(Mutex::new(None)); register_capturing_test_tool( @@ -7269,38 +7311,46 @@ mod tests { assert!(value.get("workspaceServices").is_none()); } - #[test] - fn deferred_tool_admission_allows_missing_catalog_spec() { + #[tokio::test] + async fn deferred_tool_admission_allows_missing_catalog_spec() { let mut task = test_tool_task("tool_1", "WebFetch"); task.context.deferred_tools = vec!["WebFetch".to_string()]; - validate_tool_execution_admission(ToolExecutionAdmissionRequest { - tool_name: &task.tool_call.tool_name, - allowed_tools: &task.context.allowed_tools, - runtime_tool_restrictions: &task.context.runtime_tool_restrictions, - deferred_tools: &task.context.deferred_tools, - loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, - current_catalog_generation: 0, - get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, - }) + validate_tool_execution_admission( + ToolExecutionAdmissionRequest { + tool_name: &task.tool_call.tool_name, + allowed_tools: &task.context.allowed_tools, + runtime_tool_restrictions: &task.context.runtime_tool_restrictions, + deferred_tools: &task.context.deferred_tools, + loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, + current_catalog_generation: 0, + get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, + }, + async { None }, + ) + .await .expect("deferred exposure must not block execution when no spec is loaded"); } - #[test] - fn tool_catalog_rejects_reloading_already_loaded_tool() { + #[tokio::test] + async fn tool_catalog_rejects_reloading_already_loaded_tool() { let mut task = test_tool_task("tool_1", "GetToolSpec"); task.tool_call.arguments = json!({ "tool_name": "WebFetch" }); task.context.loaded_deferred_tool_specs = vec![loaded_spec("WebFetch", 0)]; - let result = validate_tool_execution_admission(ToolExecutionAdmissionRequest { - tool_name: &task.tool_call.tool_name, - allowed_tools: &task.context.allowed_tools, - runtime_tool_restrictions: &task.context.runtime_tool_restrictions, - deferred_tools: &task.context.deferred_tools, - loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, - current_catalog_generation: 0, - get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, - }); + let result = validate_tool_execution_admission( + ToolExecutionAdmissionRequest { + tool_name: &task.tool_call.tool_name, + allowed_tools: &task.context.allowed_tools, + runtime_tool_restrictions: &task.context.runtime_tool_restrictions, + deferred_tools: &task.context.deferred_tools, + loaded_deferred_tool_specs: &task.context.loaded_deferred_tool_specs, + current_catalog_generation: 0, + get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, + }, + async { None }, + ) + .await; assert!( result.is_ok(), diff --git a/src/crates/assembly/core/src/agentic/tools/plugin_host_tool.rs b/src/crates/assembly/core/src/agentic/tools/plugin_host_tool.rs index 52f7eb3080..66f0c75f4b 100644 --- a/src/crates/assembly/core/src/agentic/tools/plugin_host_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/plugin_host_tool.rs @@ -22,6 +22,7 @@ struct PluginHostToolRoute { generation_key: String, revision: String, registration_id: String, + contributor_key: String, description: String, parameters: Value, allowed_runtime_agent_keys: BTreeSet, @@ -172,6 +173,10 @@ impl Tool for PluginHostToolMux { .map(|r| r.parameters) .unwrap_or_else(|| serde_json::json!({"type":"object"})) } + fn deferred_spec_route_id(&self, context: &ToolUseContext) -> Option { + self.route_for(Some(context)) + .map(|route| route.contributor_key) + } fn dynamic_provider_id(&self) -> Option<&str> { Some("opencode-plugin") } @@ -566,12 +571,13 @@ pub(crate) async fn register_workspace_tool( generation_key: &str, revision: &str, registration_id: &str, - id: &str, + tool_ref: &openbitfun_product_domains::plugin_capabilities::PluginToolRef, description: &str, parameters: Value, config_fingerprint: &str, allowed_runtime_agent_keys: BTreeSet, ) { + let id = tool_ref.id(); let mux = { let mut muxes = muxes().write().expect("plugin tool mux lock poisoned"); if let Some(mux) = muxes.get(id) { @@ -604,6 +610,7 @@ pub(crate) async fn register_workspace_tool( generation_key: generation_key.to_string(), revision: revision.to_string(), registration_id: registration_id.to_string(), + contributor_key: tool_ref.contributor().identity_key().to_owned(), description: description.to_string(), parameters, allowed_runtime_agent_keys, @@ -696,6 +703,7 @@ mod tests { generation_key: "generation-test".to_string(), revision: "revision-test".to_string(), registration_id: format!("registration-{instance_id}"), + contributor_key: format!("contributor-{instance_id}"), description: format!("description-{instance_id}"), parameters: json!({"type": "object", "title": instance_id}), allowed_runtime_agent_keys: BTreeSet::from(["plugin-agent".to_string()]), @@ -938,6 +946,32 @@ mod tests { registry.clear_source_workspace(RuntimeHookSource::Plugin, &scope); } + #[tokio::test] + async fn deferred_spec_identifies_the_contributor_across_plugin_reloads() { + use openbitfun_agent_runtime::native_hooks::{RuntimeHookActivation, RuntimeHookSource}; + let scope = "plugin-tool-workspace"; + let registry = openbitfun_agent_runtime::native_hooks::RuntimeHookRegistry::default(); + registry.set_source_activation_for_workspace( + RuntimeHookSource::Plugin, + Some(scope), + RuntimeHookActivation::Ready, + ); + let mux = PluginHostToolMux::new("shared-tool".into(), registry); + let context = context("/workspace", "plugin-agent"); + let mut route = route(client().await, "a"); + mux.set_route(scope.into(), route.clone()); + let tool: &dyn Tool = &mux; + let first = openbitfun_agent_tools::contextual_tool_spec(tool, &context).await; + route.registration_id = "fresh-registration".into(); + mux.set_route(scope.into(), route.clone()); + let reloaded = openbitfun_agent_tools::contextual_tool_spec(tool, &context).await; + assert_eq!(first.spec_fingerprint, reloaded.spec_fingerprint); + route.contributor_key = "another-plugin".into(); + mux.set_route(scope.into(), route); + let switched = openbitfun_agent_tools::contextual_tool_spec(tool, &context).await; + assert_ne!(first.spec_fingerprint, switched.spec_fingerprint); + } + #[tokio::test] async fn remote_workspace_cannot_match_a_local_plugin_tool_route() { use openbitfun_agent_runtime::native_hooks::{RuntimeHookActivation, RuntimeHookSource}; @@ -964,6 +998,7 @@ mod tests { }; assert!(mux.route_for(Some(&remote)).is_none()); + assert!(mux.deferred_spec_route_id(&remote).is_none()); registry.clear_source_workspace(RuntimeHookSource::Plugin, &scope); } diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime.rs index 3218030533..2862a5b246 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime.rs @@ -26,6 +26,8 @@ use snapshot::ProductSnapshotToolWrapper; use std::sync::Arc; pub use call_deferred_tool::CallDeferredTool; +#[cfg(feature = "ptc-runtime")] +pub(crate) use catalog::resolve_product_deferred_tool_detail; pub use catalog::{build_all_tools_info, build_tool_info, ToolInfoDto}; pub(crate) use catalog::{ product_get_tool_spec_runtime, resolve_product_get_tool_spec_results, diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs index c5be1992ae..3f4f90625e 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs @@ -616,6 +616,22 @@ pub(crate) async fn resolve_product_readonly_enabled_tools() -> Vec { .await } +#[cfg(feature = "ptc-runtime")] +pub(crate) async fn resolve_product_deferred_tool_detail( + name: &str, + context: &ToolUseContext, +) -> Result { + with_collaboration_model_policy( + openbitfun_agent_tools::resolve_get_tool_spec_detail_from_provider( + &ProductToolCatalogProvider, + name, + context, + GET_TOOL_SPEC_TOOL_NAME, + ), + ) + .await +} + pub(crate) async fn resolve_product_get_tool_spec_results( input: &Value, context: &ToolUseContext, diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/get_tool_spec_tool.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/get_tool_spec_tool.rs index 59f98cfe94..8dfcc4e064 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/get_tool_spec_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/get_tool_spec_tool.rs @@ -71,7 +71,8 @@ impl Tool for GetToolSpecTool { "tool_name": {"type": "string"}, "description": {"type": "string"}, "input_schema": {"type": "object", "additionalProperties": true}, - "catalog_generation": {"type": "integer"} + "catalog_generation": {"type": "integer"}, + "spec_fingerprint": {"type": "string"} }, "required": ["tool_name", "description", "input_schema", "catalog_generation"], "additionalProperties": false @@ -154,6 +155,7 @@ mod tests { loaded_deferred_tool_specs: vec![openbitfun_agent_tools::LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation, + spec_fingerprint: None, }], model_client: None, primary_model_facts: tool_runtime::context::PrimaryModelFacts::default(), diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/loaded_spec_state.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/loaded_spec_state.rs index 42b1d24111..1deb83c1e6 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/loaded_spec_state.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/loaded_spec_state.rs @@ -101,6 +101,7 @@ fn get_tool_spec_load_observation(message: &Message) -> Option for dyn Tool { + fn deferred_spec_route_id(&self, context: &ToolUseContext) -> Option { + Tool::deferred_spec_route_id(self, context) + } + async fn is_available_in_context(&self, context: &ToolUseContext) -> bool { if matches!(Tool::name(self), "Read" | "Grep" | "Glob" | "LS") && !live_repository_context_allowed(context) diff --git a/src/crates/assembly/core/src/agentic/tools/tool_context_runtime.rs b/src/crates/assembly/core/src/agentic/tools/tool_context_runtime.rs index 9744ae5913..0f92115f63 100644 --- a/src/crates/assembly/core/src/agentic/tools/tool_context_runtime.rs +++ b/src/crates/assembly/core/src/agentic/tools/tool_context_runtime.rs @@ -944,6 +944,7 @@ mod context_facts_tests { LoadedDeferredToolSpec { tool_name: tool_name.to_string(), catalog_generation: 0, + spec_fingerprint: None, } } @@ -1786,6 +1787,7 @@ mod task_context_tests { LoadedDeferredToolSpec { tool_name: tool_name.to_string(), catalog_generation: 0, + spec_fingerprint: None, } } diff --git a/src/crates/assembly/core/src/external_tools.rs b/src/crates/assembly/core/src/external_tools.rs index b6c849c363..6d5c93deeb 100644 --- a/src/crates/assembly/core/src/external_tools.rs +++ b/src/crates/assembly/core/src/external_tools.rs @@ -196,6 +196,10 @@ impl Tool for LoadedExternalTool { self.descriptor.input_schema.clone() } + fn deferred_spec_route_id(&self, _context: &ToolUseContext) -> Option { + Some(self.runtime_target_id.clone()) + } + fn dynamic_provider_id(&self) -> Option<&str> { Some(&self.provider_id) } diff --git a/src/crates/assembly/core/src/plugin_host.rs b/src/crates/assembly/core/src/plugin_host.rs index 98d9a6951e..593ee139f5 100644 --- a/src/crates/assembly/core/src/plugin_host.rs +++ b/src/crates/assembly/core/src/plugin_host.rs @@ -1823,7 +1823,7 @@ async fn register_plugin_tools( } prepared.push(( tool.registration_id.clone(), - tool.id.clone(), + tool_ref, tool.description.clone(), tool.parameters.clone(), allowed_runtime_agent_keys, @@ -1835,7 +1835,8 @@ async fn register_plugin_tools( // publication steps, so a malformed later entry cannot leave a partial // generation installed. let mut names = Vec::with_capacity(prepared.len()); - for (registration_id, id, description, parameters, allowed_runtime_agent_keys) in prepared { + for (registration_id, tool_ref, description, parameters, allowed_runtime_agent_keys) in prepared + { crate::agentic::tools::plugin_host_tool::register_workspace_tool( workspace_scope, workspace_id, @@ -1845,7 +1846,7 @@ async fn register_plugin_tools( generation_key, revision, ®istration_id, - &id, + &tool_ref, &description, parameters, config_fingerprint, @@ -1856,10 +1857,10 @@ async fn register_plugin_tools( "Plugin tool registration committed to Rust registry: workspace={}, instance_id={}, tool_id={}, registration_id={}", workspace_scope, instance_id, - id, + tool_ref.id(), registration_id ); - names.push(id); + names.push(tool_ref.id().to_owned()); } log::info!( "Plugin tool registration completed: workspace={}, instance_id={}, tool_count={}", diff --git a/src/crates/assembly/core/src/service/snapshot/manager.rs b/src/crates/assembly/core/src/service/snapshot/manager.rs index d3603972a4..326ea2cc6e 100644 --- a/src/crates/assembly/core/src/service/snapshot/manager.rs +++ b/src/crates/assembly/core/src/service/snapshot/manager.rs @@ -919,6 +919,10 @@ impl Tool for WrappedTool { self.original_tool.dynamic_provider_id() } + fn deferred_spec_route_id(&self, context: &ToolUseContext) -> Option { + self.original_tool.deferred_spec_route_id(context) + } + fn dynamic_tool_info(&self) -> Option { self.original_tool.dynamic_tool_info() } diff --git a/src/crates/execution/tool-contracts/Cargo.toml b/src/crates/execution/tool-contracts/Cargo.toml index b1cf4db29e..64981caf4e 100644 --- a/src/crates/execution/tool-contracts/Cargo.toml +++ b/src/crates/execution/tool-contracts/Cargo.toml @@ -11,6 +11,7 @@ crate-type = ["rlib"] [dependencies] serde = { workspace = true } +sha2 = { workspace = true } serde_json = { workspace = true } openbitfun-core-types = { path = "../../contracts/core-types" } openbitfun-runtime-ports = { path = "../../contracts/runtime-ports" } diff --git a/src/crates/execution/tool-contracts/src/execution_gate.rs b/src/crates/execution/tool-contracts/src/execution_gate.rs index bdc9c5151e..bcb2fdca6c 100644 --- a/src/crates/execution/tool-contracts/src/execution_gate.rs +++ b/src/crates/execution/tool-contracts/src/execution_gate.rs @@ -35,8 +35,9 @@ impl fmt::Display for ToolExecutionAdmissionRejection { impl std::error::Error for ToolExecutionAdmissionRejection {} -pub fn validate_tool_execution_admission( +pub async fn validate_tool_execution_admission( request: ToolExecutionAdmissionRequest<'_>, + current_fingerprint: impl std::future::Future>, ) -> Result<(), ToolExecutionAdmissionRejection> { validate_tool_allowed_by_list(request.tool_name, request.allowed_tools) .map_err(ToolExecutionAdmissionRejection::AllowedList)?; @@ -44,11 +45,25 @@ pub fn validate_tool_execution_admission( .runtime_tool_restrictions .ensure_tool_allowed(request.tool_name) .map_err(ToolExecutionAdmissionRejection::RuntimeRestriction)?; + let fingerprint = if request + .deferred_tools + .iter() + .any(|name| name == request.tool_name) + && request + .loaded_deferred_tool_specs + .iter() + .any(|spec| spec.tool_name == request.tool_name && spec.spec_fingerprint.is_some()) + { + current_fingerprint.await + } else { + None + }; validate_deferred_tool_usage( request.tool_name, request.deferred_tools, request.loaded_deferred_tool_specs, request.current_catalog_generation, + fingerprint.as_deref(), request.get_tool_spec_tool_name, ) .map_err(ToolExecutionAdmissionRejection::Deferred) diff --git a/src/crates/execution/tool-contracts/src/framework.rs b/src/crates/execution/tool-contracts/src/framework.rs index f125749b60..4ab9a0fdb8 100644 --- a/src/crates/execution/tool-contracts/src/framework.rs +++ b/src/crates/execution/tool-contracts/src/framework.rs @@ -11,6 +11,7 @@ use openbitfun_core_types::ToolImageAttachment; use openbitfun_runtime_ports::DelegationPolicy; use serde::{Deserialize, Serialize}; use serde_json::Value; +use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fmt; use std::marker::PhantomData; @@ -75,6 +76,13 @@ pub enum DeferredToolUsageError { tool_name: String, get_tool_spec_tool_name: String, }, + DefinitionChanged { + tool_name: String, + get_tool_spec_tool_name: String, + }, + ToolUnavailable { + tool_name: String, + }, StaleSpec { tool_name: String, loaded_generation: u64, @@ -93,6 +101,17 @@ impl fmt::Display for DeferredToolUsageError { formatter, "Tool '{tool_name}' has no loaded definition in the current context. Call {get_tool_spec_tool_name} with {{\"tool_name\":\"{tool_name}\"}} to read its full usage instructions and input schema before invoking it. If compaction removed an earlier definition, reload it even if the summary says it was loaded." ), + Self::ToolUnavailable { tool_name } => write!( + formatter, + "Deferred tool '{tool_name}' is unavailable in the current context." + ), + Self::DefinitionChanged { + tool_name, + get_tool_spec_tool_name, + } => write!( + formatter, + "The loaded spec for deferred tool '{tool_name}' is stale because its definition or provider changed. Call {get_tool_spec_tool_name} again before invoking it." + ), Self::StaleSpec { tool_name, loaded_generation, @@ -151,6 +170,7 @@ pub fn validate_deferred_tool_usage( deferred_tools: &[String], loaded_deferred_tool_specs: &[LoadedDeferredToolSpec], current_catalog_generation: u64, + current_spec_fingerprint: Option<&str>, get_tool_spec_tool_name: &str, ) -> Result<(), DeferredToolUsageError> { // The admission helper is shared by direct and deferred calls. A receipt @@ -164,9 +184,21 @@ pub fn validate_deferred_tool_usage( .iter() .find(|loaded| loaded.tool_name == tool_name) { - if loaded.catalog_generation == current_catalog_generation { + if loaded.matches(current_catalog_generation, current_spec_fingerprint) { return Ok(()); } + if loaded.spec_fingerprint.is_some() { + return Err(if current_spec_fingerprint.is_some() { + DeferredToolUsageError::DefinitionChanged { + tool_name: tool_name.to_owned(), + get_tool_spec_tool_name: get_tool_spec_tool_name.to_owned(), + } + } else { + DeferredToolUsageError::ToolUnavailable { + tool_name: tool_name.to_owned(), + } + }); + } return Err(DeferredToolUsageError::StaleSpec { tool_name: tool_name.to_string(), loaded_generation: loaded.catalog_generation, @@ -332,6 +364,8 @@ pub struct GetToolSpecDetail { pub tool_name: String, pub description: String, pub input_schema: Value, + pub output_schema: Value, + pub spec_fingerprint: String, pub catalog_generation: u64, } @@ -342,6 +376,7 @@ impl GetToolSpecDetail { "description": self.description.clone(), "input_schema": self.input_schema.clone(), "catalog_generation": self.catalog_generation, + "spec_fingerprint": self.spec_fingerprint, }) } } @@ -538,6 +573,7 @@ pub struct GetToolSpecLoadObservation<'a> { pub tool_name: &'a str, pub loaded_tool_name: Option<&'a str>, pub catalog_generation: Option, + pub spec_fingerprint: Option<&'a str>, pub is_error: bool, } @@ -545,6 +581,18 @@ pub struct GetToolSpecLoadObservation<'a> { pub struct LoadedDeferredToolSpec { pub tool_name: String, pub catalog_generation: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spec_fingerprint: Option, +} + +impl LoadedDeferredToolSpec { + fn matches(&self, generation: u64, current_fingerprint: Option<&str>) -> bool { + match self.spec_fingerprint.as_deref() { + Some(loaded) => Some(loaded) == current_fingerprint, + // Historical sessions only recorded the global catalog generation. + None => self.catalog_generation == generation, + } + } } pub fn collect_loaded_deferred_tool_specs( @@ -571,6 +619,7 @@ pub fn collect_loaded_deferred_tool_specs( LoadedDeferredToolSpec { tool_name: tool_name.to_string(), catalog_generation, + spec_fingerprint: observation.spec_fingerprint.map(str::to_owned), }, ); } @@ -744,6 +793,11 @@ pub trait ContextualToolManifestItem: ToolRegistryItem where Context: Sync, { + /// Stable dispatch target when one provider exposes multiple routes with the same name. + fn deferred_spec_route_id(&self, _context: &Context) -> Option { + None + } + async fn is_available_in_context(&self, _context: &Context) -> bool { true } @@ -936,18 +990,45 @@ where return Err(format!("Tool '{tool_name}' cannot inspect itself")); } + Ok(contextual_tool_spec(tool.as_ref(), context).await) +} + +/// Materialize the receipt from the same contextual definition that the caller sees. +pub async fn contextual_tool_spec( + tool: &Tool, + context: &Context, +) -> GetToolSpecDetail +where + Tool: ContextualToolManifestItem + ?Sized, + Context: Sync, +{ let description = tool .description_with_context(context) .await .unwrap_or_else(|_| format!("Tool: {}", tool.name())); let input_schema = tool.input_schema_for_model_with_context(context).await; - - Ok(GetToolSpecDetail { - tool_name: tool_name.to_string(), + let output_schema = tool.output_schema(); + let mut contract = serde_json::json!([ + tool.name(), + tool.dynamic_tool_info(), + tool.deferred_spec_route_id(context), + description, + input_schema, + output_schema + ]); + contract.sort_all_objects(); + let spec_fingerprint = format!( + "sha256:{:x}", + Sha256::digest(contract.to_string().as_bytes()) + ); + GetToolSpecDetail { + tool_name: tool.name().to_string(), description, input_schema, + output_schema, + spec_fingerprint, catalog_generation: 0, - }) + } } pub async fn resolve_get_tool_spec_detail_from_provider( @@ -961,10 +1042,15 @@ where Context: Sync, Provider: GetToolSpecCatalogProvider + ?Sized, { + let generation = provider.catalog_generation().await; let deferred_tools = provider .deferred_tools_for_get_tool_spec(Some(context)) .await?; - resolve_get_tool_spec_detail(&deferred_tools, tool_name, context, get_tool_spec_tool_name).await + let mut detail = + resolve_get_tool_spec_detail(&deferred_tools, tool_name, context, get_tool_spec_tool_name) + .await?; + detail.catalog_generation = generation; + Ok(detail) } pub async fn resolve_get_tool_spec_execution_result_from_provider( @@ -980,12 +1066,13 @@ where Provider: GetToolSpecCatalogProvider + ?Sized, { let current_generation = provider.catalog_generation().await; - let loaded_names = loaded_deferred_tool_specs + // Only legacy receipts can establish freshness without resolving the contextual tool. + let legacy_loaded_names = loaded_deferred_tool_specs .iter() - .filter(|spec| spec.catalog_generation == current_generation) + .filter(|spec| spec.matches(current_generation, None)) .map(|spec| spec.tool_name.clone()) .collect::>(); - match resolve_get_tool_spec_execution_plan(input, &loaded_names)? { + match resolve_get_tool_spec_execution_plan(input, &legacy_loaded_names)? { GetToolSpecExecutionPlan::DuplicateLoad(result) => Ok(result), GetToolSpecExecutionPlan::LoadDetail { tool_name } => { let deferred_tools = provider @@ -1002,6 +1089,12 @@ where ) .await .map_err(GetToolSpecExecutionError::Detail)?; + if loaded_deferred_tool_specs.iter().any(|loaded| { + loaded.tool_name == tool_name + && loaded.matches(current_generation, Some(&detail.spec_fingerprint)) + }) { + return Ok(build_get_tool_spec_duplicate_load_result(tool_name)); + } let detail = GetToolSpecDetail { catalog_generation: current_generation, ..detail diff --git a/src/crates/execution/tool-contracts/src/lib.rs b/src/crates/execution/tool-contracts/src/lib.rs index 8bc059cb88..5fbb091b27 100644 --- a/src/crates/execution/tool-contracts/src/lib.rs +++ b/src/crates/execution/tool-contracts/src/lib.rs @@ -59,7 +59,7 @@ pub use framework::{ build_openbitfun_runtime_uri, build_prompt_visible_tool_manifest_definitions, build_tool_manifest_policy_tools, build_tool_path_policy_denial_message, build_tool_runtime_artifact_reference, build_tool_session_runtime_artifact_reference, - collect_loaded_deferred_tool_specs, get_tool_spec_input_schema, + collect_loaded_deferred_tool_specs, contextual_tool_spec, get_tool_spec_input_schema, get_tool_spec_is_concurrency_safe, get_tool_spec_is_readonly, get_tool_spec_short_description, is_miniapp_headless_agent_run, is_miniapp_market_strict_agent_run, is_openbitfun_current_session_uri, is_openbitfun_runtime_uri, is_openbitfun_tool_uri, diff --git a/src/crates/execution/tool-contracts/tests/tool_contracts.rs b/src/crates/execution/tool-contracts/tests/tool_contracts.rs index 058c8a54ea..debc629d84 100644 --- a/src/crates/execution/tool-contracts/tests/tool_contracts.rs +++ b/src/crates/execution/tool-contracts/tests/tool_contracts.rs @@ -1467,6 +1467,7 @@ fn deferred_tool_usage_allows_calls_without_a_loaded_spec() { &deferred_tools, &loaded_deferred_tool_specs, 0, + None, GET_TOOL_SPEC_TOOL_NAME, ) .expect("deferred exposure must not block execution when no spec is loaded"); @@ -1474,12 +1475,14 @@ fn deferred_tool_usage_allows_calls_without_a_loaded_spec() { let loaded_deferred_tool_specs = vec![LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 0, + spec_fingerprint: None, }]; validate_deferred_tool_usage( "WebFetch", &deferred_tools, &loaded_deferred_tool_specs, 0, + None, GET_TOOL_SPEC_TOOL_NAME, ) .expect("loaded deferred tool should be executable"); @@ -1490,8 +1493,10 @@ fn deferred_tool_usage_allows_calls_without_a_loaded_spec() { &[LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 41, + spec_fingerprint: None, }], 42, + None, GET_TOOL_SPEC_TOOL_NAME, ) .expect_err("stale deferred spec should require a reload"); @@ -1504,6 +1509,7 @@ fn deferred_tool_usage_allows_calls_without_a_loaded_spec() { &deferred_tools, &[], 0, + None, GET_TOOL_SPEC_TOOL_NAME, ) .expect("GetToolSpec remains executable"); @@ -1514,8 +1520,10 @@ fn deferred_tool_usage_allows_calls_without_a_loaded_spec() { &[LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 41, + spec_fingerprint: None, }], 42, + None, GET_TOOL_SPEC_TOOL_NAME, ) .expect("a stale receipt must not affect a tool that is no longer deferred"); @@ -1537,8 +1545,8 @@ fn tool_allowed_list_gate_preserves_pipeline_rejection_contract() { ); } -#[test] -fn tool_execution_admission_gate_preserves_pipeline_rejection_order() { +#[tokio::test] +async fn tool_execution_admission_gate_preserves_pipeline_rejection_order() { let mut restrictions = ToolRuntimeRestrictions::default(); restrictions .denied_tool_names @@ -1554,7 +1562,8 @@ fn tool_execution_admission_gate_preserves_pipeline_rejection_order() { get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, }; - let err = validate_tool_execution_admission(request) + let err = validate_tool_execution_admission(request, async { None }) + .await .expect_err("allowed-list should be evaluated before runtime restrictions"); assert!(matches!( @@ -1576,7 +1585,8 @@ fn tool_execution_admission_gate_preserves_pipeline_rejection_order() { get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, }; - let err = validate_tool_execution_admission(request) + let err = validate_tool_execution_admission(request, async { None }) + .await .expect_err("runtime restrictions should run before collapsed unlock"); assert!(matches!( @@ -1593,18 +1603,21 @@ fn tool_execution_admission_gate_preserves_pipeline_rejection_order() { allowed_tools: &["WebFetch".to_string()], runtime_tool_restrictions: &ToolRuntimeRestrictions::default(), deferred_tools: &["WebFetch".to_string()], - loaded_deferred_tool_specs: &[], + loaded_deferred_tool_specs: &[LoadedDeferredToolSpec { + tool_name: "WebFetch".into(), + catalog_generation: 41, + spec_fingerprint: None, + }], current_catalog_generation: 0, get_tool_spec_tool_name: GET_TOOL_SPEC_TOOL_NAME, }; - let err = validate_tool_execution_admission(request) - .expect_err("deferred tool should require GetToolSpec after access gates pass"); + let err = validate_tool_execution_admission(request, async { None }) + .await + .expect_err("stale receipt should be checked after access gates pass"); assert!(matches!(err, ToolExecutionAdmissionRejection::Deferred(_))); - assert!(err - .to_string() - .contains("Call GetToolSpec first with {\"tool_name\":\"WebFetch\"}")); + assert!(err.to_string().contains("is stale")); } #[test] @@ -1866,30 +1879,35 @@ fn get_tool_spec_load_collector_preserves_collapsed_runtime_contract() { tool_name: GET_TOOL_SPEC_TOOL_NAME, loaded_tool_name: Some("WebFetch"), catalog_generation: Some(42), + spec_fingerprint: None, is_error: false, }, GetToolSpecLoadObservation { tool_name: GET_TOOL_SPEC_TOOL_NAME, loaded_tool_name: Some("Read"), catalog_generation: Some(42), + spec_fingerprint: None, is_error: false, }, GetToolSpecLoadObservation { tool_name: GET_TOOL_SPEC_TOOL_NAME, loaded_tool_name: Some("GetFileDiff"), catalog_generation: Some(42), + spec_fingerprint: None, is_error: true, }, GetToolSpecLoadObservation { tool_name: "Read", loaded_tool_name: Some("WebFetch"), catalog_generation: Some(42), + spec_fingerprint: None, is_error: false, }, GetToolSpecLoadObservation { tool_name: GET_TOOL_SPEC_TOOL_NAME, loaded_tool_name: Some("WebFetch"), catalog_generation: Some(42), + spec_fingerprint: None, is_error: false, }, ]; @@ -1902,6 +1920,7 @@ fn get_tool_spec_load_collector_preserves_collapsed_runtime_contract() { vec![LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 42, + spec_fingerprint: None, }] ); } @@ -2071,6 +2090,8 @@ fn get_tool_spec_contract_builds_duplicate_load_result() { #[test] fn get_tool_spec_contract_builds_detail_result() { let result = build_get_tool_spec_detail_result(&openbitfun_agent_tools::GetToolSpecDetail { + output_schema: json!({}), + spec_fingerprint: "test-fingerprint".into(), tool_name: "Git".to_string(), description: "Use & inspect changes.".to_string(), input_schema: json!({ @@ -3086,7 +3107,8 @@ async fn get_tool_spec_detail_resolver_preserves_contextual_detail_contract() { } } }, - "catalog_generation": 0 + "catalog_generation": 0, + "spec_fingerprint": detail.spec_fingerprint }), "detail JSON shape must stay compatible with GetToolSpec execution output" ); @@ -3131,6 +3153,66 @@ async fn get_tool_spec_catalog_provider_preserves_runtime_catalog_contract() { assert_eq!(detail.description, "WebFetch description for Standard"); } +#[tokio::test] +async fn deferred_spec_freshness_tracks_context_and_upgrades_legacy_receipts() { + let provider = ContextualManifestSnapshotProvider { + tools: vec![contextual_manifest_tool( + "WebFetch", + ToolExposure::Deferred, + None, + )], + }; + let runtime = GetToolSpecRuntime::new(&provider, GET_TOOL_SPEC_TOOL_NAME); + let input = json!({"tool_name": "WebFetch"}); + let context = ManifestTestContext { agent: "Standard" }; + let old_payload = json!({"tool_name": "WebFetch", "catalog_generation": 41}); + let legacy: LoadedDeferredToolSpec = serde_json::from_value(old_payload.clone()).unwrap(); + assert_eq!(serde_json::to_value(&legacy).unwrap(), old_payload); + let ToolResult::Result { data, .. } = + runtime.execute(&input, &[legacy], &context).await.unwrap() + else { + panic!("expected definition") + }; + let mut receipt: LoadedDeferredToolSpec = serde_json::from_value(data).unwrap(); + assert!(receipt.spec_fingerprint.is_some()); + receipt.catalog_generation = 100; + let ToolResult::Result { data, .. } = runtime + .execute(&input, std::slice::from_ref(&receipt), &context) + .await + .unwrap() + else { + panic!("expected duplicate hint") + }; + assert_eq!(data["already_loaded"], true); + + // A different contextual schema must invalidate even when the generation matches. + receipt.catalog_generation = 0; + let changed_context = ManifestTestContext { agent: "Explore" }; + let ToolResult::Result { data, .. } = runtime + .execute(&input, std::slice::from_ref(&receipt), &changed_context) + .await + .unwrap() + else { + panic!("expected updated definition") + }; + let updated: LoadedDeferredToolSpec = serde_json::from_value(data).unwrap(); + assert_ne!(receipt.spec_fingerprint, updated.spec_fingerprint); + for (loaded, valid) in [(receipt, false), (updated.clone(), true)] { + assert_eq!( + validate_deferred_tool_usage( + "WebFetch", + &["WebFetch".into()], + &[loaded], + 0, + updated.spec_fingerprint.as_deref(), + GET_TOOL_SPEC_TOOL_NAME + ) + .is_ok(), + valid + ); + } +} + #[tokio::test] async fn get_tool_spec_provider_execution_returns_duplicate_result_without_detail_lookup() { let context = ManifestTestContext { agent: "Standard" }; @@ -3142,6 +3224,7 @@ async fn get_tool_spec_provider_execution_returns_duplicate_result_without_detai &[LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 0, + spec_fingerprint: None, }], &context, GET_TOOL_SPEC_TOOL_NAME, @@ -3330,6 +3413,7 @@ async fn get_tool_spec_runtime_facade_owns_tool_result_vector_adapter_shape() { &[LoadedDeferredToolSpec { tool_name: "WebFetch".to_string(), catalog_generation: 0, + spec_fingerprint: None, }], &context, )