Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): cooperative cancel (#4368)
Eric Hayes1436f67ca8d4
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 9a6f21d86e..f41df86e66 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -74,6 +74,7 @@ dependencies = ["strum","thiserror 2.0.18","tokio",+ "tokio-util","tracing","utoipa","workspace-hack",@@ -251,6 +252,7 @@ dependencies = ["serde","serde_json","thiserror 2.0.18",+ "tokio-util","tracing","utoipa","workspace-hack",@@ -14559,6 +14561,7 @@ dependencies = ["regex-automata","regex-syntax","reqwest 0.13.4",+ "rig-core","rmcp","rsa","rustc-hash 2.1.2",diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.tomlindex a40d845f0c..8f47f7b8ad 100644--- a/rust/cloud-storage/agent/Cargo.toml+++ b/rust/cloud-storage/agent/Cargo.toml@@ -32,7 +32,10 @@ macro_env_var = { path = "../macro_env_var" }macro_user_id = { path = "../macro_user_id" }prompt = { path = "../prompt" }workspace-hack = { version = "0.1", path = "../workspace-hack" }+tokio-util.workspace = true[dev-dependencies]model-entity = { path = "../model-entity" }non_empty = { path = "../non_empty" }+# Enable rig's scripted MockCompletionModel for tests (fake AI streams).+rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-api-non-strict-tools", features = ["test-utils"] }diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rsindex 7c0e686c4f..94538d2a9b 100644--- a/rust/cloud-storage/agent/src/agent_loop.rs+++ b/rust/cloud-storage/agent/src/agent_loop.rs@@ -1,4 +1,7 @@/// The main entry point: [`AgentLoop`] and [`Session`].+#[cfg(test)]+mod test;+use crate::error::AgentError;use crate::hook::{RegisterFn, ToolRouter};use crate::model::PredefinedModel;@@ -8,10 +11,11 @@ use crate::tool_adapter::DynToolSetAdapter;use ai_toolset::{RequestContext, SearchableTool, ToolLoader, ToolSet as AiToolSet};use ai_usage::{UsageContext, UsageRecorder};use rig_core::message::Message;-use rig_core::tool::server::ToolServer;+use rig_core::tool::server::{ToolServer, ToolServerHandle};use std::future::Future;use std::pin::Pin;use std::sync::{Arc, Mutex, RwLock};+use tokio_util::sync::CancellationToken;const DEFAULT_MAX_TURNS: usize = 16;const DEFAULT_MAX_TOKENS: u64 = 16_000;@@ -83,6 +87,39 @@ impl AgentLoop {system_prompt: &str,usage_ctx: UsageContext,) -> Session+ where+ Context: Clone + Send + Sync + 'static,+ {+ // The frontend selects the model by api id; route it to the provider+ // that serves it (falling back to the default on unknown / unavailable+ // ids). The router owns provider-specific agent construction.+ self.session_with(+ toolset,+ context,+ system_prompt,+ usage_ctx,+ |handle, prompt, max_turns, max_tokens| {+ ModelRouter::shared()+ .expect("failed to initialize model router")+ .agent(&self.model, handle, prompt, max_turns, max_tokens)+ },+ )+ .await+ }++ /// Like [`Self::session`], but the agent is built by `build` from the live+ /// tool-server handle and the finalized system prompt. Production routes the+ /// model through [`ModelRouter`]; tests inject a fake completion model. The+ /// rest of the per-session wiring (tool adapters, tool search, cancellation+ /// token) is identical either way.+ async fn session_with<Context>(+ &self,+ toolset: Arc<dyn AiToolSet<Context> + Send + Sync>,+ context: Arc<Context>,+ system_prompt: &str,+ usage_ctx: UsageContext,+ build: impl FnOnce(ToolServerHandle, &str, usize, u64) -> ProviderAgent,+ ) -> SessionwhereContext: Clone + Send + Sync + 'static,{@@ -103,9 +140,10 @@ impl AgentLoop {buffer.lock().expect("loaded_buffer poisoned").extend(tools)})};- let request_context = Arc::new(RwLock::new(- RequestContext::new(usage_ctx.user.clone()).with_tool_search(Arc::new(catalog), loader),- ));+ let request_context =+ RequestContext::new(usage_ctx.user.clone()).with_tool_search(Arc::new(catalog), loader);+ // TODO this is cringe, make request context a RW lock newtype+ let request_context_rw = Arc::new(RwLock::new(request_context.clone()));// Keep a handle to the toolset so the stream bridge can resolve MCP// routing info (service / display name) for tool calls. This is the@@ -117,7 +155,7 @@ impl AgentLoop {let adapters = DynToolSetAdapter::from_toolset(toolset.clone(),context.clone(),- request_context.clone(),+ request_context_rw.clone(),);let handle = ToolServer::new().run();@@ -142,13 +180,12 @@ impl AgentLoop {let handle = handle.clone();let toolset = toolset.clone();let context = context.clone();- let request_context = request_context.clone();Arc::new(move |tools: Vec<SearchableTool>| {let handle = handle.clone();let toolset = toolset.clone();let context = context.clone();- let request_context = request_context.clone();let loaded_names = loaded_names.clone();+ let request_context_rw = request_context_rw.clone();Box::pin(async move {for tool in tools {// Skip tools already loaded this session.@@ -164,7 +201,7 @@ impl AgentLoop {tool.schema,toolset.clone(),context.clone(),- request_context.clone(),+ request_context_rw.clone(),);if let Err(e) = handle.add_tool(adapter).await {tracing::warn!(error = ?e, "failed to load searched tool");@@ -186,18 +223,7 @@ impl AgentLoop {system_prompt.push_str(§ion);}- // The frontend selects the model by api id; route it to the provider- // that serves it (falling back to the default on unknown / unavailable- // ids). The router owns provider-specific agent construction.- let agent = ModelRouter::shared()- .expect("failed to initialize model router")- .agent(- &self.model,- handle,- &system_prompt,- self.max_turns,- self.max_tokens,- );+ let agent = build(handle, &system_prompt, self.max_turns, self.max_tokens);Session {agent,@@ -209,8 +235,39 @@ impl AgentLoop {recorder: self.recorder.clone(),usage_ctx,model: self.model.clone(),+ request_context,}}++ /// Start a session backed by a caller-supplied (fake) completion model+ /// instead of routing through [`ModelRouter`]. Exercises the real+ /// per-session wiring and the public [`Session`] surface+ /// ([`Session::cancellable`], [`Session::send_message`]) without a provider.+ #[cfg(test)]+ pub(crate) async fn test_session<Context, M>(+ &self,+ toolset: Arc<dyn AiToolSet<Context> + Send + Sync>,+ context: Arc<Context>,+ system_prompt: &str,+ usage_ctx: UsageContext,+ model: M,+ ) -> Session+ where+ Context: Clone + Send + Sync + 'static,+ M: rig_core::completion::CompletionModel + 'static,+ M::StreamingResponse: rig_core::completion::GetTokenUsage + Send + Sync,+ {+ self.session_with(+ toolset,+ context,+ system_prompt,+ usage_ctx,+ move |handle, prompt, max_turns, max_tokens| {+ ProviderAgent::test(model, prompt, max_turns, max_tokens, handle)+ },+ )+ .await+ }}/// A single streaming conversation session.@@ -226,9 +283,15 @@ pub struct Session {recorder: Arc<dyn UsageRecorder>,usage_ctx: UsageContext,model: String,+ request_context: RequestContext,}impl Session {+ /// get the cancel token for this session+ pub fn cancellable(self) -> (Self, CancellationToken) {+ let cancel_token = self.request_context.cancel.clone();+ (self, cancel_token)+ }/// Send a message and stream the response.////// The returned stream yields [`StreamPart`] items compatible with the@@ -258,6 +321,7 @@ impl Session {self.recorder.clone(),self.usage_ctx.clone(),self.model.clone(),+ self.request_context.clone(),).await;diff --git a/rust/cloud-storage/agent/src/agent_loop/test.rs b/rust/cloud-storage/agent/src/agent_loop/test.rsnew file mode 100644index 0000000000..08673ffbd0--- /dev/null+++ b/rust/cloud-storage/agent/src/agent_loop/test.rs@@ -0,0 +1,153 @@+//! Agent loop behavior tests.+//!+//! These drive the public session surface used by DCS — [`AgentLoop`] →+//! [`super::Session::cancellable`] → [`super::Session::send_message`] — with a+//! fake completion model injected via [`AgentLoop::test_session`], so the real+//! per-session wiring (tool adapters, cancellation token) is exercised.++use crate::AgentLoop;+use crate::stream::{StreamPart, ToolResponse};+use ai_toolset::{+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolResult,+ ToolSet as AiToolSet,+};+use ai_usage::{AiFeature, UsageContext, UsageEvent, UsageRecorder};+use futures::StreamExt;+use macro_user_id::user_id::MacroUserIdStr;+use rig_core::message::Message;+use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};+use schemars::JsonSchema;+use serde::Deserialize;+use std::sync::Arc;+use tokio::sync::Notify;++/// Records nothing — token usage isn't under test here.+struct NoOpRecorder;+impl UsageRecorder for NoOpRecorder {+ fn record(&self, _event: UsageEvent) {}+}++fn test_loop() -> AgentLoop {+ AgentLoop::new(Arc::new(NoOpRecorder))+ .with_max_turns(8)+ .with_max_tokens(1024)+}++fn test_user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").expect("valid user id")+}++/// Shared service state handed to the tool. `started` lets the tool announce+/// that it has begun executing so the test can cancel only *after* the+/// `on_tool_call` guard has passed — otherwise the agent loop would terminate+/// before the tool ever runs and no tool response would be produced.+#[derive(Clone)]+struct TestCtx {+ started: Arc<Notify>,+}++/// A tool that would run forever, but cooperatively returns a normal response+/// when the request is cancelled. It reads the cancellation token off the+/// [`RequestContext`] it is handed — exactly how a real long-running tool+/// consumes `request_context.cancel`.+#[derive(Deserialize, JsonSchema)]+#[schemars(+ title = "infinite_tool",+ description = "Runs until the request is cancelled."+)]+struct InfiniteTool {}++#[async_trait::async_trait]+impl AsyncTool<TestCtx> for InfiniteTool {+ type Output = serde_json::Value;++ async fn call(+ &self,+ service_context: ServiceContext<TestCtx>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ service_context.started.notify_one();+ tokio::select! {+ _ = request_context.cancel.cancelled() => {+ Ok(serde_json::json!({ "status": "cancelled" }))+ }+ // The "infinite" work that never finishes on its own.+ _ = std::future::pending::<()>() => {+ unreachable!("pending future never resolves")+ }+ }+ }+}++/// A fake AI stream that calls an infinite tool exercises cooperative+/// cancellation: cancelling the session while the tool is running makes the+/// tool return (via `request_context.cancel`), and that return surfaces as a+/// tool response in the message stream.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn cancelling_running_tool_yields_a_tool_response() {+ // Turn 1: the model calls the infinite tool. Turn 2 (reached once the+ // tool returns) just finalizes so the agentic loop terminates.+ let model = MockCompletionModel::from_stream_turns([+ vec![+ MockStreamEvent::tool_call("call-1", "infinite_tool", serde_json::json!({})),+ MockStreamEvent::final_response_with_default_usage(),+ ],+ vec![MockStreamEvent::final_response_with_default_usage()],+ ]);++ let started = Arc::new(Notify::new());+ let context = Arc::new(TestCtx {+ started: started.clone(),+ });+ let toolset: Arc<dyn AiToolSet<TestCtx> + Send + Sync> =+ Arc::new(AsyncToolCollection::<TestCtx>::new().add_tool::<InfiniteTool, TestCtx>());++ let usage_ctx = UsageContext::new(AiFeature::Chat, test_user());+ let session = test_loop()+ .test_session(toolset, context, "test preamble", usage_ctx, model)+ .await;+ let (mut session, cancel) = session.cancellable();++ // Cancel once the tool is actually executing.+ tokio::spawn(async move {+ started.notified().await;+ cancel.cancel();+ });++ let mut stream = session+ .send_message(vec![Message::user("run the infinite tool")])+ .await+ .expect("send_message should start the stream");++ let mut parts = Vec::new();+ while let Some(item) = stream.next().await {+ if let Ok(part) = item {+ parts.push(part);+ }+ }++ // The tool call appears in the stream...+ let tool_call_id = parts+ .iter()+ .find_map(|part| match part {+ StreamPart::ToolCall(call) if call.name == "infinite_tool" => Some(call.id.clone()),+ _ => None,+ })+ .expect("expected a tool call for infinite_tool");++ // ...and it has a response, produced by the tool returning cooperatively+ // when `request_context.cancel` fired.+ let response = parts+ .iter()+ .find_map(|part| match part {+ StreamPart::ToolResponse(ToolResponse::Json { id, json, .. })+ if *id == tool_call_id =>+ {+ Some(json.clone())+ }+ _ => None,+ })+ .expect("expected a tool response for the infinite tool call");++ assert_eq!(response, serde_json::json!({ "status": "cancelled" }));+}diff --git a/rust/cloud-storage/agent/src/error.rs b/rust/cloud-storage/agent/src/error.rsindex df90011df3..d7e8d3b8d6 100644--- a/rust/cloud-storage/agent/src/error.rs+++ b/rust/cloud-storage/agent/src/error.rs@@ -32,3 +32,24 @@ pub enum AgentError {#[error(transparent)]RigHttpClient(#[from] rig_core::http_client::Error),}++impl AgentError {+ /// is the error caused by a cancellation+ pub fn was_cancelled(&self) -> bool {+ use rig_core::agent::StreamingError;+ use rig_core::completion::PromptError;+ match self {+ // A direct prompt error.+ Self::Prompt(PromptError::PromptCancelled { .. }) => true,+ // The agent loop streams its errors, so a cancellation surfaces+ // wrapped: `Streaming(Prompt(PromptCancelled { .. }))`.+ Self::Streaming(StreamingError::Prompt(e)) => {+ matches!(**e, PromptError::PromptCancelled { .. })+ }+ _ => false,+ }+ }+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/agent/src/error/test.rs b/rust/cloud-storage/agent/src/error/test.rsnew file mode 100644index 0000000000..8e0ec4324e--- /dev/null+++ b/rust/cloud-storage/agent/src/error/test.rs@@ -0,0 +1,39 @@+use super::*;+use rig_core::agent::StreamingError;+use rig_core::completion::{CompletionError, PromptError};++fn prompt_cancelled() -> PromptError {+ PromptError::PromptCancelled {+ chat_history: Vec::new(),+ reason: "user cancelled".to_string(),+ }+}++#[test]+fn streaming_wrapped_cancellation_is_detected() {+ // The agent loop streams its errors, so a user cancellation reaches callers+ // wrapped as `Streaming(Prompt(PromptCancelled { .. }))` — not the bare+ // `Prompt` variant. This is the shape DCS actually sees.+ let err = AgentError::Streaming(StreamingError::Prompt(Box::new(prompt_cancelled())));+ assert!(err.was_cancelled());+}++#[test]+fn direct_prompt_cancellation_is_detected() {+ let err = AgentError::Prompt(prompt_cancelled());+ assert!(err.was_cancelled());+}++#[test]+fn non_cancellation_streaming_error_is_not_cancelled() {+ let err = AgentError::Streaming(StreamingError::Completion(CompletionError::ProviderError(+ "boom".to_string(),+ )));+ assert!(!err.was_cancelled());+}++#[test]+fn unrelated_error_is_not_cancelled() {+ let err = AgentError::UnknownModel("foo/bar".to_string());+ assert!(!err.was_cancelled());+}diff --git a/rust/cloud-storage/agent/src/hook.rs b/rust/cloud-storage/agent/src/hook.rsindex 56200f4bd4..e0b1c40c6e 100644--- a/rust/cloud-storage/agent/src/hook.rs+++ b/rust/cloud-storage/agent/src/hook.rs@@ -13,6 +13,7 @@ use std::future::Future;use std::pin::Pin;use std::sync::{Arc, Mutex};use tokio::sync::mpsc;+use tokio_util::sync::CancellationToken;/// Resolves a tool name to its routing [`ToolInfo`] via the session's toolset.///@@ -30,6 +31,8 @@ pub type ToolRouter = Arc<dyn Fn(&str) -> Option<ToolInfo> + Send + Sync>;pub type RegisterFn =Arc<dyn Fn(Vec<SearchableTool>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;+static CANCELLED_REASON: &str = "user cancelled";+/// Sends [`StreamPart`] items through an unbounded channel as the RIG agentic/// loop produces events.#[derive(Clone)]@@ -41,6 +44,8 @@ pub struct StreamBridge {loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,/// Registers drained tools with the live tool server.register_loaded: RegisterFn,+ /// the user has requested the stream stop+ cancel: CancellationToken,}impl StreamBridge {@@ -55,6 +60,7 @@ impl StreamBridge {routing: ToolRouter,loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,register_loaded: RegisterFn,+ cancel: CancellationToken,) -> (Self,mpsc::UnboundedReceiver<Result<StreamPart, AgentError>>,@@ -66,6 +72,7 @@ impl StreamBridge {routing,loaded_buffer,register_loaded,+ cancel,},rx,)@@ -79,7 +86,13 @@ where{async fn on_text_delta(&self, text_delta: &str, _aggregated_text: &str) -> HookAction {let _ = self.tx.send(Ok(StreamPart::Content(text_delta.to_owned())));- HookAction::Continue+ if self.cancel.is_cancelled() {+ HookAction::Terminate {+ reason: CANCELLED_REASON.into(),+ }+ } else {+ HookAction::Continue+ }}async fn on_tool_call(@@ -89,6 +102,11 @@ whereinternal_call_id: &str,args: &str,) -> ToolCallHookAction {+ if self.cancel.is_cancelled() {+ return ToolCallHookAction::Terminate {+ reason: CANCELLED_REASON.into(),+ };+ }let json = serde_json::from_str(args).unwrap_or(serde_json::Value::Null);let id = tool_call_id.unwrap_or_else(|| internal_call_id.to_owned());let mcp = (self.routing)(tool_name).map(|i| match i {diff --git a/rust/cloud-storage/agent/src/hook/test.rs b/rust/cloud-storage/agent/src/hook/test.rsindex 7c8eedb253..28af058c01 100644--- a/rust/cloud-storage/agent/src/hook/test.rs+++ b/rust/cloud-storage/agent/src/hook/test.rs@@ -34,7 +34,8 @@ async fn on_tool_result_drains_buffer_and_registers_loaded_tools() {]));let (register, registered) = recording_register();let routing: ToolRouter = Arc::new(|_| None);- let (bridge, _rx) = StreamBridge::channel(routing, buffer.clone(), register);+ let token = CancellationToken::new();+ let (bridge, _rx) = StreamBridge::channel(routing, buffer.clone(), register, token);let action = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_result(&bridge,@@ -65,7 +66,8 @@ async fn on_tool_result_registers_nothing_when_buffer_empty() {let buffer = Arc::new(Mutex::new(Vec::new()));let (register, registered) = recording_register();let routing: ToolRouter = Arc::new(|_| None);- let (bridge, _rx) = StreamBridge::channel(routing, buffer, register);+ let token = CancellationToken::new();+ let (bridge, _rx) = StreamBridge::channel(routing, buffer, register, token);let _ = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_result(&bridge,diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex 72500f2430..a290004613 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -20,7 +20,6 @@ pub use agent_loop::{AgentLoop, Session};pub use completion::{complete, complete_with_history};pub use convert::{merge_consecutive_parts, to_rig_messages};pub use error::AgentError;-pub use hook::StreamBridge;pub use model::PredefinedModel;pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};diff --git a/rust/cloud-storage/agent/src/model/router.rs b/rust/cloud-storage/agent/src/model/router.rsindex 046cc2499a..75cecaf2d7 100644--- a/rust/cloud-storage/agent/src/model/router.rs+++ b/rust/cloud-storage/agent/src/model/router.rs@@ -19,7 +19,7 @@ use std::borrow::Cow;use std::collections::HashMap;use std::sync::{Arc, Mutex, OnceLock};-use ai_toolset::SearchableTool;+use ai_toolset::{RequestContext, SearchableTool};use ai_usage::{UsageContext, UsageRecorder};use futures::StreamExt;use macro_env_var::env_var;@@ -127,6 +127,10 @@ pub(crate) enum ProviderAgent {OpenAiChatCompletions(Agent<openai::completion::CompletionModel>),/// An agent over the OpenAI Responses model.OpenAiResponses(Agent<openai::responses_api::ResponsesCompletionModel>),+ /// A test-only agent over an arbitrary completion model (e.g. a scripted+ /// fake), type-erased so the enum itself stays non-generic.+ #[cfg(test)]+ Test(Box<dyn DynStreamAgent>),}impl ProviderAgent {@@ -144,6 +148,7 @@ impl ProviderAgent {recorder: Arc<dyn UsageRecorder>,usage_ctx: UsageContext,model: String,+ request_context: RequestContext,) -> ChatCompletionStream<'static> {match self {ProviderAgent::Anthropic(agent) => {@@ -158,6 +163,7 @@ impl ProviderAgent {recorder,usage_ctx,model,+ request_context.clone(),).await}@@ -173,6 +179,7 @@ impl ProviderAgent {recorder,usage_ctx,model,+ request_context.clone(),).await}@@ -188,9 +195,27 @@ impl ProviderAgent {recorder,usage_ctx,model,+ request_context.clone(),).await}+ #[cfg(test)]+ ProviderAgent::Test(agent) => {+ agent+ .run_stream_dyn(+ prompt,+ history,+ max_turns,+ routing,+ loaded_buffer,+ register_loaded,+ recorder,+ usage_ctx,+ model,+ request_context.clone(),+ )+ .await+ }}}}@@ -381,12 +406,18 @@ async fn drive_stream<M>(recorder: Arc<dyn UsageRecorder>,usage_ctx: UsageContext,model: String,+ request_context: RequestContext,) -> ChatCompletionStream<'static>whereM: CompletionModel + 'static,M::StreamingResponse: GetTokenUsage + Send + Sync,{- let (bridge, mut rx) = StreamBridge::channel(routing, loaded_buffer, register_loaded);+ let (bridge, mut rx) = StreamBridge::channel(+ routing,+ loaded_buffer,+ register_loaded,+ request_context.cancel.clone(),+ );let mut rig_stream = agent.stream_prompt(prompt)@@ -445,6 +476,92 @@ whereBox::pin(stream)}+/// Test-only type erasure so [`ProviderAgent`] can hold an arbitrary+/// [`Agent<M>`] (e.g. a scripted fake model) without the enum becoming generic.+/// Mirrors the production arms: it just drives [`drive_stream`].+#[cfg(test)]+pub(crate) trait DynStreamAgent: Send + Sync {+ #[allow(clippy::too_many_arguments)]+ fn run_stream_dyn<'a>(+ &'a self,+ prompt: Message,+ history: Vec<Message>,+ max_turns: usize,+ routing: ToolRouter,+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,+ register_loaded: RegisterFn,+ recorder: Arc<dyn UsageRecorder>,+ usage_ctx: UsageContext,+ model: String,+ request_context: RequestContext,+ ) -> std::pin::Pin<+ Box<dyn std::future::Future<Output = ChatCompletionStream<'static>> + Send + 'a>,+ >;+}++#[cfg(test)]+impl<M> DynStreamAgent for Agent<M>+where+ M: CompletionModel + 'static,+ M::StreamingResponse: GetTokenUsage + Send + Sync,+{+ fn run_stream_dyn<'a>(+ &'a self,+ prompt: Message,+ history: Vec<Message>,+ max_turns: usize,+ routing: ToolRouter,+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,+ register_loaded: RegisterFn,+ recorder: Arc<dyn UsageRecorder>,+ usage_ctx: UsageContext,+ model: String,+ request_context: RequestContext,+ ) -> std::pin::Pin<+ Box<dyn std::future::Future<Output = ChatCompletionStream<'static>> + Send + 'a>,+ > {+ Box::pin(drive_stream(+ self,+ prompt,+ history,+ max_turns,+ routing,+ loaded_buffer,+ register_loaded,+ recorder,+ usage_ctx,+ model,+ request_context,+ ))+ }+}++#[cfg(test)]+impl ProviderAgent {+ /// Build a test-only [`ProviderAgent`] backed by `model` (a fake completion+ /// model), wired through the same [`build_agent`] used in production.+ pub(crate) fn test<M>(+ model: M,+ system_prompt: &str,+ max_turns: usize,+ max_tokens: u64,+ handle: ToolServerHandle,+ ) -> Self+ where+ M: CompletionModel + 'static,+ M::StreamingResponse: GetTokenUsage + Send + Sync,+ {+ ProviderAgent::Test(Box::new(build_agent(+ model,+ None,+ handle,+ system_prompt,+ max_turns,+ max_tokens,+ )))+ }+}+#[cfg(test)]mod test {use super::*;diff --git a/rust/cloud-storage/ai_tools/src/subagent.rs b/rust/cloud-storage/ai_tools/src/subagent.rsindex 855aae36fd..4fade6467b 100644--- a/rust/cloud-storage/ai_tools/src/subagent.rs+++ b/rust/cloud-storage/ai_tools/src/subagent.rs@@ -3,6 +3,7 @@ use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolRuse async_trait::async_trait;use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use tokio::select;use crate::ToolServiceContext;@@ -35,23 +36,33 @@ impl AsyncTool<ToolServiceContext> for Subagent {async fn call(&self,service_context: ServiceContext<ToolServiceContext>,- _request_context: RequestContext,+ request_context: RequestContext,) -> ToolResult<Self::Output> {// Subagents have no feature of their own — their usage rolls up into the// feature that spawned them, carried on the service context.- let result = agent::complete(+ //+ // Cooperative cancellation: race the completion against the request's+ // cancel token. If the user cancels, drop the in-flight completion and+ // report "cancelled" rather than a partial or errored result.+ let completion = agent::complete(SUBAGENT_MODEL,SUBAGENT_PROMPT,&self.task,service_context.recorder.as_ref(),service_context.usage_context.clone(),- )- .await- .map_err(|e| ToolCallError {- description: "subagent encountered an error".to_string(),- internal_error: e,- })?;-- Ok(SubagentResponse { result })+ );++ select! {+ biased;+ _ = request_context.cancel.cancelled() => Ok(SubagentResponse {+ result: "cancelled".to_string(),+ }),+ result = completion => result+ .map_err(|e| ToolCallError {+ description: "subagent encountered an error".to_string(),+ internal_error: e,+ })+ .map(|result| SubagentResponse { result }),+ }}}diff --git a/rust/cloud-storage/ai_toolset/Cargo.toml b/rust/cloud-storage/ai_toolset/Cargo.tomlindex 7815ce4c5f..1eb7115baf 100644--- a/rust/cloud-storage/ai_toolset/Cargo.toml+++ b/rust/cloud-storage/ai_toolset/Cargo.toml@@ -17,3 +17,4 @@ axum = { workspace = true }axum-macros = { workspace = true }tracing = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }+tokio-util.workspace = truediff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rsindex 19eaffee40..15102cf8e3 100644--- a/rust/cloud-storage/ai_toolset/src/context.rs+++ b/rust/cloud-storage/ai_toolset/src/context.rs@@ -2,6 +2,7 @@ use crate::tool_search::{SearchableTool, ToolLoader};use macro_user_id::user_id::MacroUserIdStr;use std::ops::{Deref, DerefMut};use std::sync::Arc;+use tokio_util::sync::CancellationToken;/// Service context wrapper for shared state passed to tools.///@@ -36,6 +37,9 @@ pub struct RequestContext {/// Loader used by `SearchTools` to load matched tools into the active/// request. `None` when tool search is not wired up (e.g. non-agent callers).pub tool_loader: Option<ToolLoader>,+ /// user has requested stream stop+ /// long-running tools should comsume this+ pub cancel: CancellationToken,}impl RequestContext {@@ -46,6 +50,7 @@ impl RequestContext {user_id,searchable_tools: Arc::new(Vec::new()),tool_loader: None,+ cancel: CancellationToken::new(),}}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rsindex 99e2c28cf0..62f095c410 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs@@ -488,7 +488,7 @@ fn stream_and_save_message(// the whole subscription; the subscription itself is moved into the// stream closure so the Redis subscriber task is aborted when the stream// finishes.- let cancellation_token = cancellation_sub.token.clone();+ let user_cancellsation = cancellation_sub.token.clone();let payload_stream = stream! {// Keep the subscription alive for the duration of the stream. When@@ -514,15 +514,18 @@ fn stream_and_save_message();let agent_loop =AgentLoop::new(tool_context.recorder.clone()).with_model(&model);++let rig_messages = agent::to_rig_messages(&request);let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Chat, user_id.clone()).with_entity(macro_uuid::string_to_uuid(&chat_id).ok());// Carry the feature on the context so tool-spawned subagents attribute to it.let mut tool_context = tool_context;tool_context.usage_context = usage_ctx.clone();- let mut session = agent_loop+ let (mut session, cancel) = agent_loop.session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)- .await;+ .await+ .cancellable();// Create the AI stream - yield error if it failslet mut ai_stream = match session.send_message(rig_messages).await {@@ -546,15 +549,21 @@ fn stream_and_save_message(loop {let next_item = tokio::select! {- biased;- _ = cancellation_token.cancelled() => {- tracing::info!(chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "AI stream cancelled by user");+ // A `CancellationToken` stays cancelled once fired, so this+ // branch must be disabled after it runs (`if !was_cancelled`).+ // Otherwise `biased` would re-take it every iteration and never+ // poll `ai_stream`, so the cooperative end (`Ok(None)`) is never+ // observed and the stream "stays alive". After cancelling the+ // agent we keep draining until it winds down and ends.+ _ = user_cancellsation.cancelled(), if !cancel.is_cancelled() => {+ cancel.cancel();was_cancelled = true;- None+ continue;}timed = tokio::time::timeout(idle_timeout, ai_stream.next()) => {match timed {- Ok(item) => item,+ Ok(Some(item)) => item,+ Ok(None) => break,Err(_) => {tracing::error!(chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "AI stream idle timeout: no token received within {idle_timeout:?}");let stream_error = StreamError::InternalError {@@ -563,21 +572,18 @@ fn stream_and_save_message(if let Ok(json) = serde_json::to_value(ChatStream::Error(stream_error)) {yield json;}- None+ break}}}};- let Some(response) = next_item else { break; };- tracing::trace!("{:#?}", response);-if !is_first_token {is_first_token = true;log::log_timing(log::LatencyMetric::TimeToFirstToken, &model, now.elapsed());}- match response {+ match next_item {Ok(response_chunk) => {// Accumulate the part for persistence; the accumulator merges// consecutive text/thinking when accessed below. Parts with no@@ -599,6 +605,9 @@ fn stream_and_save_message(}}Err(e) => {+ if e.was_cancelled() {+ break;+ }tracing::error!(error=?e, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "error in AI stream");let stream_error = StreamError::InternalError {stream_id: stream_id.clone(),diff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.tomlindex 44a6578a69..2e9758b5ff 100644--- a/rust/cloud-storage/workspace-hack/Cargo.toml+++ b/rust/cloud-storage/workspace-hack/Cargo.toml@@ -89,6 +89,7 @@ redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }+rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-api-non-strict-tools", features = ["test-utils"] }rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }rsa = { version = "0.9", features = ["getrandom", "sha1"] }rustc-hash = { version = "2" }@@ -208,6 +209,7 @@ redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "std", "unicode"] }regex-syntax = { version = "0.8" }reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }+rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-api-non-strict-tools", features = ["test-utils"] }rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }rsa = { version = "0.9", features = ["getrandom", "sha1"] }rustc-hash = { version = "2" }