From cf12944ff8c41299805b70b3d2f974145cf53140 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 12:16:00 +0800 Subject: [PATCH 01/11] Plan move file history, tool bindings and nested execution to branch faces From 9020f08ceff1f625bf38191e807c0ee416d6ca74 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:57:37 +0800 Subject: [PATCH 02/11] Serve pinned tool declarations from their branch ToolBinding owner --- crates/dim-agent-capabilities/src/lib.rs | 1 + .../src/tool_binding.rs | 11 +++ .../src/tool_binding/face.rs | 82 +++++++++++++++++++ .../src/tool_executor.rs | 5 -- crates/dim-app-server/src/lib.rs | 1 - .../tests/transport_flow/branch_typescript.rs | 37 +++++++++ crates/dim-codemode/src/branch.rs | 10 ++- crates/dim-codemode/src/host.rs | 8 +- .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 6 ++ .../rust-agent/generated/services.json | 6 ++ .../rust-agent/plugins/ToolExecution.md | 4 +- docs/design/plugins/CodeMode.md | 7 +- docs/design/service-faces.md | 1 - npm/plugin.d.ts | 9 ++ runtime/fixtures/tool-binding.ts | 33 ++++++++ 16 files changed, 206 insertions(+), 17 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/tool_binding/face.rs create mode 100644 runtime/fixtures/tool-binding.ts diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index fc1a2b8175..aa06324d0a 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -112,6 +112,7 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); + catalog.register_shared_instance(name_of::(), BRANCH_GROUP); register::(catalog, branch); register::(catalog, branch); catalog.register_shared_instance("skillsBranch", BRANCH_GROUP); diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index d058f440f7..701da7c467 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -6,6 +6,8 @@ //! configuration, pins the source sets its prefix may still declare, and //! fixes each request's handlers when Loop binds it, so a call always runs //! the implementation of the version its request declared. +mod face; + use crate::{ context_preparation::ToolSetAdoption, host::{ModelSettings, ToolExecutionContext}, @@ -399,6 +401,7 @@ fn register( } pub struct ToolBindingPlugin { + instance: rutis::host::InstanceId, binding: Key, registry: Key, prompt: Key, @@ -410,6 +413,7 @@ pub struct ToolBindingPlugin { impl ToolBindingPlugin { pub fn new(names: &Names<'_>) -> std::result::Result { Ok(Self { + instance: names.instance(dim_agent_runtime::BRANCH_GROUP)?, binding: names.key()?, registry: names.key()?, prompt: names.key()?, @@ -532,6 +536,13 @@ impl DynPlugin for ToolBindingPlugin { tasks.wait().await; Ok(()) })?; + ctx.provide_at::( + rutis_bridge::session::host_key_in( + &dim_agent_runtime::names::name_of::(), + self.instance, + ), + binding.clone(), + )?; ctx.provide_at(self.binding.clone(), binding)?; Ok(Effect::Done) }) diff --git a/crates/dim-agent-capabilities/src/tool_binding/face.rs b/crates/dim-agent-capabilities/src/tool_binding/face.rs new file mode 100644 index 0000000000..7254215532 --- /dev/null +++ b/crates/dim-agent-capabilities/src/tool_binding/face.rs @@ -0,0 +1,82 @@ +use super::ToolBinding; +use crate::port_faces::{request, unknown_method}; +use dim_agent_types::{ToolDefinition, ToolSourceVersion}; +use rutis_bridge::session::{Error, HostDispatch, Reply, Value, arg}; +use serde::Deserialize; + +const NAME: &str = "toolBinding"; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + request_id: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Bind { + request_id: String, + through: u64, + tools: Vec, + tool_sources: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct BindCurrent { + request_id: String, + declared: Option>, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Transfer { + from: String, + to: String, +} + +impl HostDispatch for ToolBinding { + fn methods(&self) -> Option { + Some(serde_json::json!({ + "bind": "sync", "bindCurrent": "sync", "definitions": "sync", + "transfer": "sync", "release": "sync" + })) + } + + fn invoke(&self, method: &str, args: Value) -> Reply { + match method { + "bind" => { + let data: Bind = request(NAME, args)?; + self.bind( + &data.request_id, + data.through, + &data.tools, + &data.tool_sources, + ) + .map_err(Error::Value)?; + Ok(Value::Undefined) + } + "bindCurrent" => { + let data: BindCurrent = request(NAME, args)?; + arg(&self + .bind_current(&data.request_id, data.declared.as_deref()) + .map_err(Error::Value)?) + } + "definitions" => { + let data: Request = request(NAME, args)?; + arg(&self.definitions(&data.request_id).map_err(Error::Value)?) + } + "transfer" => { + let data: Transfer = request(NAME, args)?; + self.transfer(&data.from, &data.to).map_err(Error::Value)?; + Ok(Value::Undefined) + } + "release" => { + let data: Request = request(NAME, args)?; + self.release(&data.request_id); + Ok(Value::Undefined) + } + _ => Err(unknown_method(NAME, method)), + } + } +} diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index d01521cc85..3a03ff0a08 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -203,11 +203,6 @@ async fn run_child( Ok(result) } impl ToolExecutor { - /// The declarations the request pinned, for a program that may only see - /// the tools its own request declared. - pub fn definitions(&self, request_id: &str) -> Result, String> { - self.binding.definitions(request_id) - } /// 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 /// interrupted executor refuses. diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index e892c17b0b..cf781167f9 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1520,7 +1520,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("timelineFactory", "control"), ("timelineTree", "owner-api"), ("timelineTreeControl", "owner-api"), - ("toolBinding", "hot-path"), ("toolExecutor", "hot-path"), ("uiExtensions", "control"), ("uiHost", "control"), diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 2b1a27572d..b437cb616c 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -554,3 +554,40 @@ async fn node_branch_typescript_writes_and_follows_extension_events() { server.join().await.unwrap(); let _ = std::fs::remove_dir_all(&home); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_tool_binding_transfers_pinned_handlers_in_the_native_owner() { + let mut parts = branch_part(); + parts.rows = vec![ + json!({"id":"tool-binding","name":parts.anchor.parent().unwrap().join("fixtures/tool-binding.ts"),"provides":{}}), + ]; + let (server, _agent) = launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_part("ToolBindingFixture"); + }, + ) + .await; + let mut client = Client::new_version(&server, false, 3).await; + let id = super::session_typescript::new_session(&mut client, json!(["echo", "wait"])).await; + let reply = client + .rpc("session.bindingfixture.pin", json!({"sessionId":id})) + .await; + assert_ok(&reply); + use dim_agent_capabilities::host::ToolDriver; + let echo = MockTools + .definitions() + .into_iter() + .find(|tool| tool.name == "echo") + .unwrap(); + assert_eq!(reply["result"]["echo"], echo.description); + assert_eq!(reply["result"]["current"], reply["result"]["transferred"]); + assert_eq!(reply["result"]["empty"], 0); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/crates/dim-codemode/src/branch.rs b/crates/dim-codemode/src/branch.rs index 086d0705d4..f60e7e1eb8 100644 --- a/crates/dim-codemode/src/branch.rs +++ b/crates/dim-codemode/src/branch.rs @@ -6,6 +6,7 @@ use crate::{ }; use dim_agent_capabilities::{ host::{HostError, ToolExecutionContext}, + tool_binding::ToolBinding, tool_executor::ToolExecutor, }; use dim_agent_runtime::{Names, TimelineIdentity}; @@ -18,6 +19,7 @@ use tokio_util::sync::CancellationToken; pub struct CodeModeBranchPlugin { runs: Key, executor: Key, + binding: Key, identity: Key, config: Arc, } @@ -27,6 +29,7 @@ impl CodeModeBranchPlugin { Ok(Self { runs: names.key()?, executor: names.key()?, + binding: names.key()?, identity: names.key()?, config, }) @@ -42,6 +45,7 @@ impl DynPlugin for CodeModeBranchPlugin { vec![ self.runs.erase(), self.executor.erase(), + self.binding.erase(), self.identity.erase(), ] } @@ -49,8 +53,10 @@ impl DynPlugin for CodeModeBranchPlugin { fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let runs = ctx.require_at(&self.runs)?; - let executor: Arc = - Arc::new(ToolExecutorHost::new(ctx.require_at(&self.executor)?)); + let executor: Arc = Arc::new(ToolExecutorHost::new( + ctx.require_at(&self.executor)?, + ctx.require_at(&self.binding)?, + )); let identity = ctx.require_at(&self.identity)?; let branch = Arc::new(CodeModeBranch { executor, diff --git a/crates/dim-codemode/src/host.rs b/crates/dim-codemode/src/host.rs index a5bf8094ac..c77a933266 100644 --- a/crates/dim-codemode/src/host.rs +++ b/crates/dim-codemode/src/host.rs @@ -1,5 +1,6 @@ use dim_agent_capabilities::{ host::{HostError, ToolExecutionContext}, + tool_binding::ToolBinding, tool_executor::{NestedGate, ToolExecutor}, }; use dim_agent_types::ToolDefinition; @@ -23,17 +24,18 @@ pub trait NestedToolHost: Send + Sync + 'static { pub struct ToolExecutorHost { executor: Arc, + binding: Arc, } impl ToolExecutorHost { - pub fn new(executor: Arc) -> Self { - Self { executor } + pub fn new(executor: Arc, binding: Arc) -> Self { + Self { executor, binding } } } impl NestedToolHost for ToolExecutorHost { fn definitions(&self, request_id: &str) -> Result, String> { - self.executor.definitions(request_id) + self.binding.definitions(request_id) } fn open( diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d2481d5fb9..bc011b0f6d 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -120,7 +120,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `skillsBranch` | branch | SkillsBranch | data | `list` sync | | `timeline` | branch | BranchScope | data | `ancestors` async, `append` async, `branchId` async, `committed` async, `hasPending` async, `query` async, `sequence` async | | `timelineIdentity` | branch | BranchScope | data | `get` async | -| `toolBinding` | branch | ToolBinding | internal(hot-path) | — | +| `toolBinding` | branch | ToolBinding | data | `bind` sync, `bindCurrent` sync, `definitions` sync, `release` sync, `transfer` sync | | `toolExecutor` | branch | ToolExecutor | internal(hot-path) | — | | `wait` | branch | WaitBranch | data | `wait` async | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 998b011461..25ba05b1b9 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -2242,6 +2242,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#toolBinding@main", + "provider": 78, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#wait@main", "provider": 81, diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index 664c670a07..edaca8f7b4 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -1713,6 +1713,12 @@ "provider": 35, "generation": 1, "removing": false + }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#toolBinding@main", + "provider": 48, + "generation": 1, + "removing": false } ] }, diff --git a/docs/architecture/rust-agent/plugins/ToolExecution.md b/docs/architecture/rust-agent/plugins/ToolExecution.md index 7e61be9749..2cbe842e6c 100644 --- a/docs/architecture/rust-agent/plugins/ToolExecution.md +++ b/docs/architecture/rust-agent/plugins/ToolExecution.md @@ -4,6 +4,8 @@ The ToolExecution plugin registers the Session [ToolMethods](ToolMethods.md) rea ## ToolBinding +Loop and Code Mode use the branch [tool binding operations](../../../design/contracts/runtime-owner-operations.md) to pin, read, transfer and release request declarations. + Owner: [tool_binding.rs](../../../../crates/dim-agent-capabilities/src/tool_binding.rs). Adopts a Session tool set into branch model configuration and pins handlers to requests so later registry changes cannot silently replace executing tools. @@ -94,7 +96,7 @@ task, mutex, lifecycle phase or protocol field is needed. | --- | --- | | 作用域 | 分支 | | 注入 | `B:BranchLifecycle`、`B:BranchOpening`、`B:Dispatcher`、`B:Prompt`、`B:Timeline`、`S:ToolRegistry` | -| 提供 | `B:ToolBinding` | +| 提供 | `B:ToolBinding`、`B:dyn HostDispatch#toolBinding` | | 被注入于 | `Loop`、`ToolExecutor` | diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index fd6ad89a50..2ddd87c095 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -356,7 +356,8 @@ The outer approval (when the outer call asks) has no `parent_call_id`. | `partRegistry` | Process | `CodeMode` | Register `CodeModeSession` and `CodeModeBranch`. | | `CodeModeRuns` | Process | `CodeModeSession`, `CodeModeBranch` | Resolve the calling Session and branch's runner; the process plugin provides it. | | `toolRegistry` | Session | `CodeModeSession` | Register the `codemode` tool. | -| `ToolExecutor` | branch | `CodeModeBranch` | Read the pinned declarations, submit child `step/tool-call` batches, run child calls and join the parent gate. | +| `ToolBinding` | branch | `CodeModeBranch` | Read the request’s pinned declarations. | +| `ToolExecutor` | branch | `CodeModeBranch` | Submit child `step/tool-call` batches, run child calls and join the parent gate. | | `TimelineIdentity` | branch | `CodeModeBranch` | The calling Session id and branch id. | | `rquickjs` | library | `CodeModeBranch` | The QuickJS runtime and the `tools` bridge. | @@ -426,7 +427,7 @@ facade access or a Node/TypeScript runtime. | §4.4 core mechanism has no business meaning | The nested invocation service and `parent_call_id` are generic; the contract names no Code Mode type. | | §4.5 atomic batches and ordered dispatch | Child batches are committed and dispatched in sequence. The outer batch stays current; child batches do not take the model batch slot; the outer result is committed once. | | §4.6 context boundary | Child results never enter context. Only the outer `step/tool-result` is model-facing; a value the model needs is in the outer `content`. | -| §4.7 public interaction | The plugin uses `ToolExecutor`, `ToolRegistry`, `CodeModeRuns` and `rquickjs`; it receives no handler or ToolExecutor internals. | +| §4.7 public interaction | The plugin uses `ToolBinding`, `ToolExecutor`, `ToolRegistry`, `CodeModeRuns` and `rquickjs`; it receives no handler or ToolExecutor internals. | | §4.8 infrastructure requirements | R1–R5 state the existing mechanisms, the generic additions, cancellation/reload behavior and the owners. | | §4.9 facts in Timeline | Every child call has a durable `step/tool-call` command and a terminal `step/tool-result`; child effects travel on the child result and the outer result. | | ADR 002 D1 | Process `CodeMode`, Session tool, Branch execution and ToolExecutor each own their own state. | @@ -470,7 +471,7 @@ CodeModeBranch::run(outer_call_id, code, context, cancel): gate = toolExecutor.open(outer_call_id) result = try: quickjs.async_with(|ctx|: - install tools.list / tools.describe from executor.definitions(context.request_id) + install tools.list / tools.describe from toolBinding.definitions({requestId: context.request_id}) install tools.call = Async(|name, args| gate.invoke(ToolCall{name, args}, context, child_cancel)) promise = ctx.eval(async function body) return promise.into_future()) diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index de466837b4..3c1fcd1fd6 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -175,7 +175,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `prompt` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `contextPreparation` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `contextUsage` | branch | ContextUsage | hot-path | 本地请求计数器、请求引用与按序统计;`session.context.usage` 是 App Server RPC。按 #1292 确认是否需要独立插件操作。 | -| `toolBinding` | branch | ToolBinding | hot-path | 待迁移;按 #1292 定义操作面 | | `toolExecutor` | branch | ToolExecutor | hot-path | 待迁移;按 #1292 定义操作面 | | `branchOpening` | branch | BranchScope | hot-path | 待迁移;按 #1292 定义操作面 | | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index c7ea5d1837..42cc289601 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -817,6 +817,15 @@ export interface HooksService { refusal(request: { plugin: string }): [error: string, reason: string | null] | null; } +export type BoundToolDefinition = Omit & { risk?: string }; +export interface ToolBinding { + bind(request: { requestId: string; through: number | bigint; tools: BoundToolDefinition[]; toolSources: { key: string; version: string }[] }): void; + bindCurrent(request: { requestId: string; declared?: BoundToolDefinition[] | null }): BoundToolDefinition[]; + definitions(request: { requestId: string }): BoundToolDefinition[]; + transfer(request: { from: string; to: string }): void; + release(request: { requestId: string }): void; +} + /** The ToolRegistry owner's read-only source status view. */ export interface ToolSourceRejection { version: string; reason: string } export interface ToolSourceStatus { adopted: string | null; rejected: ToolSourceRejection | null } diff --git a/runtime/fixtures/tool-binding.ts b/runtime/fixtures/tool-binding.ts new file mode 100644 index 0000000000..830712311c --- /dev/null +++ b/runtime/fixtures/tool-binding.ts @@ -0,0 +1,33 @@ +import { definePlugin } from '@arcships/rutis' +import type { SessionMethods, ToolBinding } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin({ + name: 'ToolBindingFixture', + inject: ['toolBinding', 'sessionMethods'], + async apply(ctx) { + const binding = ctx.use('toolBinding') + await ctx.use('sessionMethods').register('session.bindingfixture', [ + { name: 'session.bindingfixture.pin', mutating: true, interruption: 'report', progress: false }, + ], async () => { + const declared = binding.bindCurrent({ requestId: 'fixture-current' }) + binding.bind({ requestId: 'fixture-empty', through: 0n, tools: [], toolSources: [] }) + const empty = binding.definitions({ requestId: 'fixture-empty' }) + binding.release({ requestId: 'fixture-empty' }) + binding.transfer({ from: 'fixture-current', to: 'fixture-transferred' }) + const transferred = binding.definitions({ requestId: 'fixture-transferred' }) + binding.release({ requestId: 'fixture-transferred' }) + for (const requestId of ['fixture-current', 'fixture-empty', 'fixture-transferred']) { + binding.bindCurrent({ requestId, declared: [] }) + binding.release({ requestId }) + } + return { kind: 'value', value: { + current: declared.map(tool => tool.name).sort(), + transferred: transferred.map(tool => tool.name), + echo: transferred.find(tool => tool.name === 'echo')?.description ?? null, + empty: empty.length, + } } + }) + }, +}) +export default partRow('branch', part) From f3c4b9b77769c5392149dbae9f56befd0f27b04a Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:07:11 +0800 Subject: [PATCH 03/11] Use the bridge error constructor from main --- crates/dim-agent-capabilities/src/tool_binding/face.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_binding/face.rs b/crates/dim-agent-capabilities/src/tool_binding/face.rs index 7254215532..854b6b0e9e 100644 --- a/crates/dim-agent-capabilities/src/tool_binding/face.rs +++ b/crates/dim-agent-capabilities/src/tool_binding/face.rs @@ -53,22 +53,22 @@ impl HostDispatch for ToolBinding { &data.tools, &data.tool_sources, ) - .map_err(Error::Value)?; + .map_err(Error::value)?; Ok(Value::Undefined) } "bindCurrent" => { let data: BindCurrent = request(NAME, args)?; arg(&self .bind_current(&data.request_id, data.declared.as_deref()) - .map_err(Error::Value)?) + .map_err(Error::value)?) } "definitions" => { let data: Request = request(NAME, args)?; - arg(&self.definitions(&data.request_id).map_err(Error::Value)?) + arg(&self.definitions(&data.request_id).map_err(Error::value)?) } "transfer" => { let data: Transfer = request(NAME, args)?; - self.transfer(&data.from, &data.to).map_err(Error::Value)?; + self.transfer(&data.from, &data.to).map_err(Error::value)?; Ok(Value::Undefined) } "release" => { From fbe88abe68854786dc6b83c1eb11abc56d1dcfed Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:15:26 +0800 Subject: [PATCH 04/11] Expose branch file bindings to native and cross-language file tools --- .../src/file_storage.rs | 1 + .../src/file_storage/face.rs | 2 +- crates/dim-agent-capabilities/src/lib.rs | 4 + .../src/workspace_tools/file_reads.rs | 79 +++++++++++++------ .../src/workspace_tools/file_reads/face.rs | 57 +++++++++++++ .../src/workspace_tools/files.rs | 1 + .../src/workspace_tools/files/codec.rs | 51 ++++-------- .../src/workspace_tools/files/edit.rs | 4 +- .../src/workspace_tools/files/read.rs | 10 +-- .../src/workspace_tools/files/write.rs | 2 +- crates/dim-app-server/src/lib.rs | 1 - .../tests/transport_flow/branch_typescript.rs | 72 +++++++++++++++++ .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 6 ++ .../rust-agent/plugins/WorkspaceTools.md | 4 +- docs/design/service-faces.md | 1 - npm/plugin.d.ts | 13 +++ runtime/fixtures/file-reads.ts | 28 +++++++ 18 files changed, 265 insertions(+), 73 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/workspace_tools/file_reads/face.rs create mode 100644 runtime/fixtures/file-reads.ts diff --git a/crates/dim-agent-capabilities/src/file_storage.rs b/crates/dim-agent-capabilities/src/file_storage.rs index 1bd2a8fcfb..4af9861f9f 100644 --- a/crates/dim-agent-capabilities/src/file_storage.rs +++ b/crates/dim-agent-capabilities/src/file_storage.rs @@ -31,6 +31,7 @@ use tokio_util::sync::CancellationToken; use uuid::Uuid; mod face; +pub(crate) use face::deserialize_name; pub use face::{FsHost, FsPermissions, FsRemove, OpenRead}; /// Read-only reader lifetime observations for filesystem flow tests. diff --git a/crates/dim-agent-capabilities/src/file_storage/face.rs b/crates/dim-agent-capabilities/src/file_storage/face.rs index 633b747d81..dd9da6687e 100644 --- a/crates/dim-agent-capabilities/src/file_storage/face.rs +++ b/crates/dim-agent-capabilities/src/file_storage/face.rs @@ -41,7 +41,7 @@ enum EntryName { Native(OsString), } -fn deserialize_name<'de, D: serde::Deserializer<'de>>( +pub(crate) fn deserialize_name<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> std::result::Result { Ok(match EntryName::deserialize(deserializer)? { diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index aa06324d0a..1eb8cc0a40 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -122,6 +122,10 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); + catalog.register_shared_instance( + name_of::(), + BRANCH_GROUP, + ); catalog.register_shared_instance("branchLine", BRANCH_GROUP); register::(catalog, None); register::(catalog, None); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/file_reads.rs b/crates/dim-agent-capabilities/src/workspace_tools/file_reads.rs index 3dd0389374..c8fa6bc29f 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/file_reads.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/file_reads.rs @@ -5,6 +5,8 @@ //! Overwriting an existing file requires a binding from this branch whose //! operation is still in the model's context (#524). +mod face; + use crate::host::HostError; use dim_agent_runtime::{ Names, QueryComparison, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, @@ -20,27 +22,32 @@ use std::{ sync::{Arc, Mutex}, }; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)] pub enum TextEncoding { Utf8, Utf16Le, Utf16Be, /// Only established by an explicit `read.encoding`; never guessed. + #[serde(deserialize_with = "super::files::deserialize_legacy_encoding")] Legacy { /// The requested name, lowercased, as echoed to the model. name: String, + #[serde(skip_serializing)] encoding: &'static encoding_rs::Encoding, }, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum EncodingSource { Bom, User, Utf8Policy, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] pub enum Bom { None, Utf8, @@ -48,7 +55,8 @@ pub enum Bom { Utf16Be, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] pub enum Eol { None, Lf, @@ -56,7 +64,8 @@ pub enum Eol { Mixed, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TextFileBinding { /// SHA-256 of the raw file bytes. pub raw_revision: [u8; 32], @@ -75,13 +84,16 @@ struct Binding { } /// What `write` may replace an existing file with. -#[derive(Debug)] -pub(crate) enum WriteBinding { +#[derive(Debug, serde::Serialize)] +#[serde(tag = "kind", content = "binding", rename_all = "lowercase")] +pub enum WriteBinding { /// No operation on this branch bound the file. + #[serde(rename = "absent")] None, /// The operation that bound the file was compacted out of the context. Compacted, /// The binding of an operation still in the model's context. + #[serde(rename = "bound")] Text(TextFileBinding), } @@ -100,7 +112,7 @@ impl FileReads { } /// The binding `edit` may use: it checks the model's `oldText` against the /// file itself, so a compaction does not take it away (#524). - pub(crate) fn get(&self, path: &Path) -> Option { + pub fn binding(&self, path: &Path) -> Option { self.bindings .lock() .unwrap() @@ -114,17 +126,24 @@ impl FileReads { } /// The binding `write` may use: only while the operation that established /// it is still in the model's context. - pub(crate) async fn write_binding(&self, path: &Path) -> Result { - let Some(binding) = self.bindings.lock().unwrap().get(path).cloned() else { - return Ok(WriteBinding::None); - }; - Ok(if self.in_context(binding.established).await? { - WriteBinding::Text(binding.text) - } else { - WriteBinding::Compacted - }) + pub fn write_binding( + &self, + path: &Path, + ) -> impl Future> + Send + 'static { + let binding = self.bindings.lock().unwrap().get(path).cloned(); + let timeline = self.timeline.clone(); + async move { + let Some(binding) = binding else { + return Ok(WriteBinding::None); + }; + Ok(if Self::in_context(&timeline, binding.established).await? { + WriteBinding::Text(binding.text) + } else { + WriteBinding::Compacted + }) + } } - pub(crate) fn set(&self, path: PathBuf, text: TextFileBinding, established: u64) { + pub fn record(&self, path: PathBuf, text: TextFileBinding, established: u64) { self.bindings .lock() .unwrap() @@ -140,17 +159,16 @@ impl FileReads { /// compactions this check folds are published before it runs: the model /// call that led to the write tool was written after them, and a batch is /// published only after every batch committed before it. - async fn in_context(&self, established: u64) -> Result { - let now = self.timeline.sequence(); + async fn in_context(timeline: &Timeline, established: u64) -> Result { + let now = timeline.sequence(); if now <= established { return Ok(true); } - let completed = self - .timeline + let completed = timeline .query(TimelineQuery { scope: TimelineQueryScope::Branch, from: Some(TimelinePosition { - branch_id: self.timeline.branch_id(), + branch_id: timeline.branch_id(), sequence: established + 1, }), through: Some(now), @@ -197,8 +215,7 @@ impl FileReads { let [QueryValue::Value { value: retain_from }] = row.values.as_slice() else { unreachable!("completed compaction has a retain_from") }; - let cut = self - .timeline + let cut = timeline .query(TimelineQuery { scope: TimelineQueryScope::Branch, from: None, @@ -241,12 +258,14 @@ impl FileReads { } pub struct FileReadsPlugin { + instance: rutis::host::InstanceId, reads: Key, timeline: Key, } impl FileReadsPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { + instance: names.instance(dim_agent_runtime::BRANCH_GROUP)?, reads: names.key()?, timeline: names.key()?, }) @@ -262,7 +281,15 @@ impl DynPlugin for FileReadsPlugin { fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let timeline = ctx.require_at(&self.timeline)?; - ctx.provide_at(self.reads.clone(), Arc::new(FileReads::new(timeline)))?; + let owner = Arc::new(FileReads::new(timeline)); + ctx.provide_at::( + rutis_bridge::session::host_key_in( + &dim_agent_runtime::names::name_of::(), + self.instance, + ), + owner.clone(), + )?; + ctx.provide_at(self.reads.clone(), owner)?; Ok(Effect::Done) }) } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/file_reads/face.rs b/crates/dim-agent-capabilities/src/workspace_tools/file_reads/face.rs new file mode 100644 index 0000000000..4d7affcaa8 --- /dev/null +++ b/crates/dim-agent-capabilities/src/workspace_tools/file_reads/face.rs @@ -0,0 +1,57 @@ +use super::{FileReads, TextFileBinding}; +use crate::port_faces::{request, unknown_method}; +use rutis_bridge::session::{Error, HostDispatch, Reply, Value, arg}; +use serde::Deserialize; +use std::{ffi::OsString, path::Path}; + +const NAME: &str = "fileReads"; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BindingPath { + #[serde(deserialize_with = "crate::file_storage::deserialize_name")] + path: OsString, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Record { + #[serde(deserialize_with = "crate::file_storage::deserialize_name")] + path: OsString, + binding: TextFileBinding, + established: u64, +} + +impl HostDispatch for FileReads { + fn methods(&self) -> Option { + Some(serde_json::json!({"binding":"sync","writeBinding":"async","record":"sync"})) + } + + fn invoke(&self, method: &str, args: Value) -> Reply { + match method { + "binding" => { + let BindingPath { path } = request(NAME, args)?; + arg(&self.binding(Path::new(&path))) + } + "writeBinding" => { + let BindingPath { path } = request(NAME, args)?; + let read = self.write_binding(Path::new(&path)); + Ok(Value::cancellable_future(async move { + arg(&read + .await + .map_err(|error| Error::value(error.to_string()))?) + })) + } + "record" => { + let Record { + path, + binding, + established, + } = request(NAME, args)?; + self.record(path.into(), binding, established); + Ok(Value::Undefined) + } + _ => Err(unknown_method(NAME, method)), + } + } +} diff --git a/crates/dim-agent-capabilities/src/workspace_tools/files.rs b/crates/dim-agent-capabilities/src/workspace_tools/files.rs index 23e72637db..f4ab2d2d7c 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/files.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/files.rs @@ -10,6 +10,7 @@ )] mod codec; +pub(super) use codec::deserialize_legacy_encoding; mod edit; mod read; mod search; diff --git a/crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs b/crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs index 4aba295fc5..76163545ee 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs @@ -4,7 +4,7 @@ use super::super::file_reads::{Bom, EncodingSource, Eol, TextEncoding, TextFileB use super::failed; use dim_agent_types::ToolResult; use encoding_rs::{DecoderResult, EncoderResult, Encoding}; -use serde_json::{Value, json}; +use serde_json::json; const UTF8_BOM: &[u8] = &[0xef, 0xbb, 0xbf]; const UTF16LE_BOM: &[u8] = &[0xff, 0xfe]; @@ -135,6 +135,22 @@ fn resolve_explicit(input: &str, bom: Option<&TextEncoding>) -> Result>( + deserializer: D, +) -> Result<(String, &'static Encoding), D::Error> { + use serde::{Deserialize, de::Error}; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Legacy { + name: String, + } + let Legacy { name } = Legacy::deserialize(deserializer)?; + match resolve_explicit(&name, None).map_err(|error| D::Error::custom(error.message))? { + TextEncoding::Legacy { name, encoding } => Ok((name, encoding)), + _ => Err(D::Error::custom("expected a legacy encoding")), + } +} + fn detect_bom(head: &[u8]) -> Option<(TextEncoding, Bom)> { if head.starts_with(UTF8_BOM) { Some((TextEncoding::Utf8, Bom::Utf8)) @@ -272,36 +288,3 @@ pub(super) fn normalize_eol(text: &str, eol: Eol) -> String { Eol::None | Eol::Mixed => text.to_owned(), } } - -pub(super) fn encoding_json(encoding: &TextEncoding) -> Value { - match encoding { - TextEncoding::Legacy { name, .. } => json!({ "kind": "legacy", "name": name }), - other => json!({ "kind": kind(other) }), - } -} - -pub(super) fn source_str(source: EncodingSource) -> &'static str { - match source { - EncodingSource::Bom => "bom", - EncodingSource::User => "user", - EncodingSource::Utf8Policy => "utf8-policy", - } -} - -pub(super) fn bom_str(bom: Bom) -> &'static str { - match bom { - Bom::None => "none", - Bom::Utf8 => "utf8", - Bom::Utf16Le => "utf16le", - Bom::Utf16Be => "utf16be", - } -} - -pub(super) fn eol_str(eol: Eol) -> &'static str { - match eol { - Eol::None => "none", - Eol::Lf => "lf", - Eol::Crlf => "crlf", - Eol::Mixed => "mixed", - } -} diff --git a/crates/dim-agent-capabilities/src/workspace_tools/files/edit.rs b/crates/dim-agent-capabilities/src/workspace_tools/files/edit.rs index b3a98e3c8e..bd3e42bbe2 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/files/edit.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/files/edit.rs @@ -187,7 +187,7 @@ pub(super) async fn run( hook(&path); } let _lock = tools.locks.lock(&path, &cancel).await?; - let binding = reads.get(&path); + let binding = reads.binding(&path); let (target, bounded) = (path.clone(), tools.boundary.is_some()); #[cfg(test)] let hook = tools.before_commit.clone(); @@ -206,7 +206,7 @@ pub(super) async fn run( .await?; let (result, binding) = written.map_err(|Cancelled| cancelled())?; if let Some(binding) = binding { - reads.set(path, binding, established); + reads.record(path, binding, established); } Ok(result) } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/files/read.rs b/crates/dim-agent-capabilities/src/workspace_tools/files/read.rs index b7f16302f5..c141c04bb9 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/files/read.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/files/read.rs @@ -164,7 +164,7 @@ pub(super) async fn run( let (result, binding) = outcome; let result = offload(tools, call_id, result).await?; if let Some((path, binding)) = binding { - reads.set(path, binding, established); + reads.record(path, binding, established); } Ok(result) } @@ -338,10 +338,10 @@ fn read_text( "path": display, "size": stat.len, "revision": hex(&binding.raw_revision), - "encoding": codec::encoding_json(&binding.encoding), - "encodingSource": codec::source_str(binding.encoding_source), - "bom": codec::bom_str(binding.bom), - "eol": codec::eol_str(binding.eol), + "encoding": binding.encoding, + "encodingSource": binding.encoding_source, + "bom": binding.bom, + "eol": binding.eol, }); if !text.has_content { return Ok((succeeded("", structured), Some((path, binding)))); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/files/write.rs b/crates/dim-agent-capabilities/src/workspace_tools/files/write.rs index 8c1032fff0..e8d8142649 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/files/write.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/files/write.rs @@ -101,7 +101,7 @@ pub(super) async fn run( .await?; let (result, binding) = written.map_err(|Cancelled| cancelled())?; if let Some(binding) = binding { - reads.set(path, binding, established); + reads.record(path, binding, established); } Ok(result) } diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index cf781167f9..b32b619959 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1495,7 +1495,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("contextPreparation", "hot-path"), ("contextUsage", "hot-path"), ("faultReporter", "hot-path"), - ("fileReads", "hot-path"), ("fileStorage", "object"), ("grokOAuthService", "secret"), ("historyRenderer", "hot-path"), diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index b437cb616c..1126f1354d 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -591,3 +591,75 @@ async fn node_tool_binding_transfers_pinned_handlers_in_the_native_owner() { server.shutdown(); server.join().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_file_reads_round_trips_a_native_binding_used_by_write() { + use dim_agent_capabilities::workspace_tools::{file_reads::FileReads, files::FileTools}; + let root = std::env::temp_dir().join(format!("dim-binding-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&root).unwrap(); + let root = root.canonicalize().unwrap(); + let source = root.join("source.txt"); + let target = root.join("target.txt"); + std::fs::write(&source, b"before").unwrap(); + std::fs::copy(&source, &target).unwrap(); + let mut parts = branch_part(); + parts.rows = vec![ + json!({"id":"file-reads","name":parts.anchor.parent().unwrap().join("fixtures/file-reads.ts"),"provides":{}}), + ]; + let (server, agent) = launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_feature(dim_agent_runtime::Feature::new("FixtureFileReadsOwner") + .branch("FileReads", |names| Ok(Box::new(dim_agent_capabilities::workspace_tools::file_reads::FileReadsPlugin::new(names)?)))); + builder.require_part("FileReadsFixture"); + }, + ) + .await; + let mut client = Client::new_version(&server, false, 3).await; + let id = super::session_typescript::new_session(&mut client, json!(["echo", "wait"])).await; + let reads = agent + .get_session(&id) + .unwrap() + .service::("main") + .unwrap(); + let files = FileTools::new(root.clone(), root.clone(), root.join("outputs")); + let call = |name: &str, input: Value| dim_agent_types::ToolCall { + id: name.to_owned(), + name: name.to_owned(), + input: input.as_object().unwrap().clone(), + }; + let read = files + .execute( + &call("read", json!({"path":source,"encoding":"cp932"})), + &reads, + CancellationToken::new(), + ) + .await + .unwrap(); + assert_ne!(read.is_error, Some(true), "{read:?}"); + let reply = client + .rpc( + "session.filebinding.copy", + json!({"sessionId":id,"source":source,"target":target}), + ) + .await; + assert_ok(&reply); + let written = files + .execute( + &call("write", json!({"path":target,"content":"日"})), + &reads, + CancellationToken::new(), + ) + .await + .unwrap(); + assert_ne!(written.is_error, Some(true), "{written:?}"); + assert_eq!(std::fs::read(target).unwrap(), [0x93, 0xfa]); + server.shutdown(); + server.join().await.unwrap(); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index bc011b0f6d..6b04265046 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -111,7 +111,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `contextPreparation` | branch | ContextPreparation | internal(hot-path) | — | | `contextUsage` | branch | ContextUsage | internal(hot-path) | — | | `dispatcher` | branch | BranchScope | data | `changed` async, `committed` async, `consume` async, `listen` async, `notify` async, `sequence` async | -| `fileReads` | branch | FileReads | internal(hot-path) | — | +| `fileReads` | branch | FileReads | data | `binding` sync, `record` sync, `writeBinding` async | | `inputQueue` | branch | InputQueue | data | `submit` async, `withdraw` async | | `loopState` | branch | Loop | internal(hot-path) | — | | `permission` | branch | Permission | data | `check` async | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 25ba05b1b9..b61ed495f1 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -2212,6 +2212,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#fileReads@main", + "provider": 68, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#inputQueue@main", "provider": 70, diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index f744aacb50..46f863afad 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -477,6 +477,8 @@ empty live preview and unavailable historical captures. ## FileReads +The branch [file binding operations](../../../design/contracts/runtime-owner-operations.md) use the canonical path. `record` takes the Timeline sequence captured at the start of the file operation. + Owner: [workspace_tools/file_reads.rs](../../../../crates/dim-agent-capabilities/src/workspace_tools/file_reads.rs). Records canonical-path bindings for files read on this branch: raw-byte revision, encoding, BOM and line endings. Existing-file `edit` admission requires a binding @@ -523,7 +525,7 @@ a filesystem lock, permission grant or cross-process compare-and-swap. | --- | --- | | 作用域 | 分支 | | 注入 | `B:Timeline` | -| 提供 | `B:FileReads` | +| 提供 | `B:FileReads`、`B:dyn HostDispatch#fileReads` | | 被注入于 | — | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 3c1fcd1fd6..7cf6f42c89 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -179,7 +179,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `branchOpening` | branch | BranchScope | hot-path | 待迁移;按 #1292 定义操作面 | | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | -| `fileReads` | branch | FileReads | hot-path | 待迁移;按 #1292 定义操作面 | | `submitChecks` | session | InputMethods | hot-path | 待迁移;按 #1292 定义操作面 | | `historyRenderer` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `contextModelHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 42cc289601..22112c5178 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -817,6 +817,19 @@ export interface HooksService { refusal(request: { plugin: string }): [error: string, reason: string | null] | null; } +export interface TextFileBinding { + rawRevision: number[]; + encoding: { kind: 'utf8' | 'utf16le' | 'utf16be' } | { kind: 'legacy'; name: string }; + encodingSource: 'bom' | 'user' | 'utf8-policy'; + bom: 'none' | 'utf8' | 'utf16le' | 'utf16be'; + eol: 'none' | 'lf' | 'crlf' | 'mixed'; +} +export interface FileReads { + binding(request: { path: FsEntryName }): TextFileBinding | null; + writeBinding(request: { path: FsEntryName }): Promise<{ kind: 'absent' } | { kind: 'compacted' } | { kind: 'bound'; binding: TextFileBinding }>; + record(request: { path: FsEntryName; binding: TextFileBinding; established: number | bigint }): void; +} + export type BoundToolDefinition = Omit & { risk?: string }; export interface ToolBinding { bind(request: { requestId: string; through: number | bigint; tools: BoundToolDefinition[]; toolSources: { key: string; version: string }[] }): void; diff --git a/runtime/fixtures/file-reads.ts b/runtime/fixtures/file-reads.ts new file mode 100644 index 0000000000..c9025a1c4e --- /dev/null +++ b/runtime/fixtures/file-reads.ts @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict' +import { definePlugin } from '@arcships/rutis' +import type { FileReads, SessionMethods, Services } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin({ + name: 'FileReadsFixture', + inject: ['fileReads', 'timeline', 'sessionMethods'], + async apply(ctx) { + const reads = ctx.use('fileReads') + const timeline = ctx.use('timeline') + await ctx.use('sessionMethods').register('session.filebinding', [ + { name: 'session.filebinding.copy', mutating: true, interruption: 'report', progress: false }, + ], async call => { + const { source, target } = call.params + if (typeof source !== 'string' || typeof target !== 'string') throw new Error('missing path') + const established = await timeline.committed() + const binding = reads.binding({ path: source }) + assert.ok(binding) + assert.deepEqual(binding.encoding, { kind: 'legacy', name: 'cp932' }) + assert.deepEqual(await reads.writeBinding({ path: target }), { kind: 'absent' }) + reads.record({ path: target, binding, established }) + assert.deepEqual(await reads.writeBinding({ path: target }), { kind: 'bound', binding }) + return { kind: 'value', value: {} } + }) + }, +}) +export default partRow('branch', part) From 6f924ab3d8cbb700f52f566d40b27da834ba8e29 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:22:42 +0800 Subject: [PATCH 05/11] Run nested tool calls through branch-owned gate IDs --- crates/dim-agent-capabilities/src/lib.rs | 1 + .../src/tool_executor.rs | 284 +++++++++--------- .../src/tool_executor/face.rs | 101 +++++++ crates/dim-app-server/src/lib.rs | 1 - .../tests/transport_flow/branch_typescript.rs | 69 +++++ crates/dim-codemode/src/host.rs | 18 +- crates/dim-codemode/src/interpreter.rs | 17 +- crates/dim-codemode/src/tests.rs | 32 +- .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 6 + .../rust-agent/generated/services.json | 6 + .../rust-agent/plugins/ToolExecution.md | 6 +- docs/design/plugins/CodeMode.md | 6 +- docs/design/service-faces.md | 1 - npm/plugin.d.ts | 5 + runtime/fixtures/tool-executor.ts | 43 +++ 16 files changed, 414 insertions(+), 184 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/tool_executor/face.rs create mode 100644 runtime/fixtures/tool-executor.ts diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index 1eb8cc0a40..291e700c9f 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -111,6 +111,7 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); + catalog.register_shared_instance(name_of::(), BRANCH_GROUP); register::(catalog, branch); catalog.register_shared_instance(name_of::(), BRANCH_GROUP); register::(catalog, branch); diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index 3a03ff0a08..def90db852 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -1,3 +1,4 @@ +mod face; pub mod read; use crate::{ @@ -17,10 +18,8 @@ use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis::{Ctx, Error}; use std::{ collections::BTreeMap, - future::Future, num::NonZeroU64, panic::AssertUnwindSafe, - pin::Pin, sync::{ Arc, Mutex, atomic::{AtomicU64, AtomicUsize, Ordering}, @@ -36,6 +35,7 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker}; #[derive(Default)] struct ToolState { current: Option, + gates: BTreeMap>, /// The context of the current top-level batch. A nested gate opens only /// for this context. current_context: Option, @@ -54,81 +54,43 @@ pub struct ToolExecutor { timeline: Arc, } -/// The child-call gate of one outer tool call. `invoke` writes a child -/// `step/tool-call` batch and its terminal `step/tool-result`; `close` rejects -/// new children and waits for every child task. -pub trait NestedGate: Send + Sync + 'static { - fn invoke( - &self, - call: ToolCall, - ) -> Pin> + Send + '_>>; - fn close(&self) -> Pin + Send + '_>>; - fn effects(&self) -> Vec; -} - -type ChildEffects = Arc)>>>; - -struct NestedGateImpl { - executor: Arc, +struct NestedGate { + timeline: Arc, + binding: Arc, + approval: Arc, parent_call_id: String, context: ToolExecutionContext, cancel: CancellationToken, tasks: TaskTracker, - state: Mutex, + closing: Mutex, next: AtomicU64, - effects: ChildEffects, + effects: Mutex)>>, } -#[derive(Default)] -struct GateState { - closing: bool, -} - -impl NestedGate for NestedGateImpl { - fn invoke( - &self, - call: ToolCall, - ) -> Pin> + Send + '_>> { - Box::pin(async move { - let (sender, receiver) = oneshot::channel(); - { - let state = self.state.lock().unwrap(); - if state.closing { - return Err(HostError::failed("the Code Mode child gate is closed")); - } - let executor = self.executor.clone(); - let parent_call_id = self.parent_call_id.clone(); - let context = self.context.clone(); - let cancel = self.cancel.clone(); - let effects = self.effects.clone(); - let sequence = self.next.fetch_add(1, Ordering::SeqCst); - self.tasks.spawn(async move { - let result = run_child( - executor, - parent_call_id, - context, - call, - cancel, - sequence, - effects, - ) - .await; - let _ = sender.send(result); - }); +impl NestedGate { + async fn invoke(self: &Arc, call: ToolCall) -> Result { + let (sender, receiver) = oneshot::channel(); + { + let closing = self.closing.lock().unwrap(); + if *closing { + return Err(HostError::failed("the Code Mode child gate is closed")); } - receiver - .await - .unwrap_or_else(|_| Err(HostError::failed("a Code Mode child task ended"))) - }) + let sequence = self.next.fetch_add(1, Ordering::SeqCst); + let gate = self.clone(); + self.tasks.spawn(async move { + let _ = sender.send(gate.run_child(call, sequence).await); + }); + } + receiver + .await + .unwrap_or_else(|_| Err(HostError::failed("a Code Mode child task ended"))) } - fn close(&self) -> Pin + Send + '_>> { - Box::pin(async move { - self.state.lock().unwrap().closing = true; - self.cancel.cancel(); - self.tasks.close(); - let _ = timeout(Duration::from_secs(5), self.tasks.wait()).await; - }) + async fn close(&self) { + *self.closing.lock().unwrap() = true; + self.cancel.cancel(); + self.tasks.close(); + let _ = timeout(Duration::from_secs(5), self.tasks.wait()).await; } fn effects(&self) -> Vec { @@ -139,68 +101,60 @@ impl NestedGate for NestedGateImpl { .flat_map(|(_, effects)| effects) .collect() } -} - -async fn run_child( - executor: Arc, - parent_call_id: String, - context: ToolExecutionContext, - call: ToolCall, - cancel: CancellationToken, - sequence: u64, - effects: ChildEffects, -) -> Result { - let batch = executor - .timeline - .append( - EventDraft::from(EventKind::ToolCall(ToolCallData { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - calls: vec![call.clone()], - })) - .with_parent_call_id(parent_call_id.clone()), - ) - .map_err(|error| HostError::failed(error.to_string()))?; - let child_call_id = call.id.clone(); - let outcome = AssertUnwindSafe(dim_agent_runtime::core::with_parent_call_id( - child_call_id, - async { - execute( - &executor.binding, - &executor.approval, - call.clone(), - context.clone(), - cancel, + async fn run_child(&self, call: ToolCall, sequence: u64) -> Result { + let context = &self.context; + let parent_call_id = &self.parent_call_id; + let batch = self + .timeline + .append( + EventDraft::from(EventKind::ToolCall(ToolCallData { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + calls: vec![call.clone()], + })) + .with_parent_call_id(parent_call_id.clone()), ) - .await - }, - )) - .catch_unwind() - .await; - let result = match outcome { - Ok(Ok(result)) => result, - Ok(Err(error)) => ToolResult::error(error.to_string()), - Err(panic) => ToolResult::error(panic_message(panic)), - }; - if let Some(child_effects) = result.effects.clone() { - effects.lock().unwrap().push((sequence, child_effects)); + .map_err(|error| HostError::failed(error.to_string()))?; + let child_call_id = call.id.clone(); + let outcome = AssertUnwindSafe(dim_agent_runtime::core::with_parent_call_id( + child_call_id, + async { + execute( + &self.binding, + &self.approval, + call.clone(), + context.clone(), + self.cancel.clone(), + ) + .await + }, + )) + .catch_unwind() + .await; + let result = match outcome { + Ok(Ok(result)) => result, + Ok(Err(error)) => ToolResult::error(error.to_string()), + Err(panic) => ToolResult::error(panic_message(panic)), + }; + if let Some(child_effects) = result.effects.clone() { + self.effects.lock().unwrap().push((sequence, child_effects)); + } + self.timeline + .append( + EventDraft::from(EventKind::ToolResult(ToolResultData { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_event_id: Some(batch.id.clone()), + results: vec![ToolCallResult { + call_id: call.id, + result: result.clone(), + }], + })) + .with_parent_call_id(parent_call_id.clone()), + ) + .map_err(|error| HostError::failed(error.to_string()))?; + Ok(result) } - executor - .timeline - .append( - EventDraft::from(EventKind::ToolResult(ToolResultData { - turn_id: context.turn_id, - request_id: context.request_id, - call_event_id: Some(batch.id.clone()), - results: vec![ToolCallResult { - call_id: call.id, - result: result.clone(), - }], - })) - .with_parent_call_id(parent_call_id), - ) - .map_err(|error| HostError::failed(error.to_string()))?; - Ok(result) } impl ToolExecutor { /// Opens the child-call gate for the current top-level batch. A gate @@ -211,8 +165,17 @@ impl ToolExecutor { parent_call_id: String, context: ToolExecutionContext, cancel: CancellationToken, - ) -> Result, HostError> { - let state = self.state.lock().unwrap(); + ) -> Result { + self.open_gate(parent_call_id, context, |_| cancel) + .map(|(id, _)| id) + } + fn open_gate( + &self, + parent_call_id: String, + context: ToolExecutionContext, + cancellation: impl FnOnce(&CancellationToken) -> CancellationToken, + ) -> Result<(String, Arc), HostError> { + let mut state = self.state.lock().unwrap(); if state.closed { return Err(HostError::failed("ToolExecutor is closed")); } @@ -221,25 +184,57 @@ impl ToolExecutor { "ToolExecutor is interrupted: {reason}" ))); } - if state.current.is_none() || state.current_context.as_ref() != Some(&context) { + let Some(batch) = state + .current + .as_ref() + .filter(|_| state.current_context.as_ref() == Some(&context)) + else { return Err(HostError::failed( "no current tool batch accepts a Code Mode child", )); - } - drop(state); - Ok(Arc::new(NestedGateImpl { - executor: self.clone(), + }; + let id = uuid::Uuid::new_v4().to_string(); + let gate = Arc::new(NestedGate { + binding: self.binding.clone(), + approval: self.approval.clone(), + timeline: self.timeline.clone(), parent_call_id, context, - cancel, + cancel: cancellation(batch), tasks: TaskTracker::new(), - state: Mutex::new(GateState::default()), + closing: Mutex::new(false), next: AtomicU64::new(0), - effects: Arc::new(Mutex::new(Vec::new())), - })) + effects: Mutex::default(), + }); + state.gates.insert(id.clone(), gate.clone()); + Ok((id, gate)) + } + pub async fn invoke(&self, gate_id: &str, call: ToolCall) -> Result { + let gate = self + .state + .lock() + .unwrap() + .gates + .get(gate_id) + .cloned() + .ok_or_else(|| HostError::failed("the Code Mode child gate is closed"))?; + gate.invoke(call).await + } + + pub async fn close(&self, gate_id: &str) -> Result, HostError> { + let gate = self + .state + .lock() + .unwrap() + .gates + .remove(gate_id) + .ok_or_else(|| HostError::failed("the Code Mode child gate is closed"))?; + gate.close().await; + Ok(gate.effects()) } } pub struct ToolExecutorPlugin { + instance: rutis::host::InstanceId, pub emit_progress: bool, executor: Key, timeline: Key, @@ -252,6 +247,7 @@ impl ToolExecutorPlugin { pub fn new(names: &Names<'_>) -> Result { Ok(Self { emit_progress: false, + instance: names.instance(dim_agent_runtime::BRANCH_GROUP)?, executor: names.key()?, timeline: names.key()?, dispatcher: names.key()?, @@ -588,12 +584,13 @@ impl DynPlugin for ToolExecutorPlugin { }).catch_unwind().await .map_err(|panic| AgentError::fault("ToolExecutor batch", panic_message(panic))) .and_then(|result| result); - let unloading = { + let (unloading, gates) = { let mut state = worker.state.lock().unwrap(); state.current = None; state.current_context = None; - state.closed || generation.is_cancelled() + (state.closed || generation.is_cancelled(), std::mem::take(&mut state.gates)) }; + futures_util::future::join_all(gates.values().map(|gate| gate.close())).await; let (mut results, mut errors) = match outcome { Ok(settled) => settled, Err(error) => { @@ -662,6 +659,13 @@ impl DynPlugin for ToolExecutorPlugin { }) }), ).await?; + ctx.provide_at::( + rutis_bridge::session::host_key_in( + &dim_agent_runtime::names::name_of::(), + self.instance, + ), + Arc::new(face::Face(service.clone())), + )?; ctx.provide_at(self.executor.clone(), service)?; Ok(Effect::Done) }) diff --git a/crates/dim-agent-capabilities/src/tool_executor/face.rs b/crates/dim-agent-capabilities/src/tool_executor/face.rs new file mode 100644 index 0000000000..5664f3a5ce --- /dev/null +++ b/crates/dim-agent-capabilities/src/tool_executor/face.rs @@ -0,0 +1,101 @@ +use super::{ToolExecutionContext, ToolExecutor}; +use crate::port_faces::{invalid, request, unknown_method}; +use dim_agent_types::ToolCall; +use rutis::host::CtxHost; +use rutis_bridge::session::{Error, HostDispatch, Reply, Value, arg, settle}; +use serde::Deserialize; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; + +const NAME: &str = "toolExecutor"; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Open { + parent_call_id: String, + context: ToolExecutionContext, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Invoke { + gate_id: String, + call: ToolCall, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Close { + gate_id: String, +} + +pub(super) struct Face(pub(super) Arc); + +impl HostDispatch for Face { + fn methods(&self) -> Option { + Some(serde_json::json!({"open":"sync","invoke":"async","close":"async"})) + } + + fn invoke(&self, method: &str, args: Value) -> Reply { + match method { + "open" => { + let args = args.list()?; + let [data, Value::Reference(cancelled)] = args.as_slice() else { + return Err(invalid( + NAME, + "open requires its request and cancellation function", + )); + }; + if !cancelled.is_function() { + return Err(invalid(NAME, "cancellation must be a function")); + } + let Open { + parent_call_id, + context, + } = serde_json::from_value(data.clone().json()?) + .map_err(|error| invalid(NAME, error))?; + let (id, gate) = self + .0 + .open_gate(parent_call_id, context, CancellationToken::child_token) + .map_err(|error| Error::value(error.to_string()))?; + let cancel = gate.cancel.clone(); + let caller = rutis_bridge::session::caller_row() + .map(|row| row.ctx().cancellation_token()) + .unwrap_or_default(); + let cancelled = cancelled.clone(); + gate.tasks.spawn(async move { + tokio::select! { + _ = cancel.cancelled() => return, + _ = caller.cancelled() => {}, + _ = async { + let result = cancelled.call_async(Value::List(vec![])).await?; + settle(result).await + } => {} + } + cancel.cancel(); + }); + arg(&id) + } + "invoke" => { + let Invoke { gate_id, call } = request(NAME, args)?; + let owner = self.0.clone(); + Ok(Value::future(async move { + arg(&ToolExecutor::invoke(&owner, &gate_id, call) + .await + .map_err(|error| Error::value(error.to_string()))?) + })) + } + "close" => { + let Close { gate_id } = request(NAME, args)?; + let owner = self.0.clone(); + Ok(Value::future(async move { + arg(&owner + .close(&gate_id) + .await + .map_err(|error| Error::value(error.to_string()))?) + })) + } + _ => Err(unknown_method(NAME, method)), + } + } +} diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index b32b619959..9ab2cc7541 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1519,7 +1519,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("timelineFactory", "control"), ("timelineTree", "owner-api"), ("timelineTreeControl", "owner-api"), - ("toolExecutor", "hot-path"), ("uiExtensions", "control"), ("uiHost", "control"), ] { diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 1126f1354d..42e28ec413 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -663,3 +663,72 @@ async fn node_file_reads_round_trips_a_native_binding_used_by_write() { server.join().await.unwrap(); std::fs::remove_dir_all(root).unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch() { + use dim_agent_capabilities::host::{HostFuture, ToolExecutionContext}; + use dim_agent_types::{ToolCall, ToolDefinition, ToolResult}; + + struct Tools(tokio::sync::mpsc::UnboundedSender<(String, ToolExecutionContext)>); + impl ToolDriver for Tools { + fn definitions(&self) -> Vec { + MockTools.definitions() + } + fn execute( + &self, + call: ToolCall, + context: ToolExecutionContext, + cancel: CancellationToken, + ) -> HostFuture<'_, ToolResult> { + if call.name == "wait" { + self.0.send((call.id.clone(), context.clone())).unwrap(); + } + MockTools.execute(call, context, cancel) + } + } + + let (started, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut parts = branch_part(); + parts.rows = vec![ + json!({"id":"tool-executor","name":parts.anchor.parent().unwrap().join("fixtures/tool-executor.ts"),"provides":{}}), + ]; + let (server, _agent) = launch_with( + Arc::new(Tools(started)), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_part("ToolExecutorFixture"); + }, + ) + .await; + let mut client = Client::new_version(&server, false, 4).await; + let id = super::session_typescript::new_session(&mut client, json!(["echo", "wait"])).await; + assert_ok( + &client + .rpc( + "session.submit", + json!({"sessionId":id,"branchId":"main","text":"tool:wait {\"millis\":60000}"}), + ) + .await, + ); + let (parent, context) = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv()) + .await + .unwrap() + .unwrap(); + let response = client.rpc("session.nestedfixture.run", json!({"sessionId":id,"parentCallId":parent,"turnId":context.turn_id,"requestId":context.request_id,"branchId":context.branch_id})).await; + assert_ok(&response); + assert_eq!( + response["result"], + json!({"output":"from node","effectCount":0}) + ); + assert_ok( + &client + .rpc("session.stop", json!({"sessionId":id,"branchId":"main"})) + .await, + ); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/crates/dim-codemode/src/host.rs b/crates/dim-codemode/src/host.rs index c77a933266..7c36c7987e 100644 --- a/crates/dim-codemode/src/host.rs +++ b/crates/dim-codemode/src/host.rs @@ -1,9 +1,9 @@ use dim_agent_capabilities::{ - host::{HostError, ToolExecutionContext}, + host::{HostError, HostFuture, ToolExecutionContext}, tool_binding::ToolBinding, - tool_executor::{NestedGate, ToolExecutor}, + tool_executor::ToolExecutor, }; -use dim_agent_types::ToolDefinition; +use dim_agent_types::{ToolCall, ToolDefinition, ToolEffect, ToolResult}; use std::sync::Arc; use tokio_util::sync::CancellationToken; @@ -19,7 +19,9 @@ pub trait NestedToolHost: Send + Sync + 'static { parent_call_id: String, context: ToolExecutionContext, cancel: CancellationToken, - ) -> Result, HostError>; + ) -> Result; + fn invoke<'a>(&'a self, gate_id: &'a str, call: ToolCall) -> HostFuture<'a, ToolResult>; + fn close<'a>(&'a self, gate_id: &'a str) -> HostFuture<'a, Vec>; } pub struct ToolExecutorHost { @@ -43,7 +45,13 @@ impl NestedToolHost for ToolExecutorHost { parent_call_id: String, context: ToolExecutionContext, cancel: CancellationToken, - ) -> Result, HostError> { + ) -> Result { ToolExecutor::open(&self.executor, parent_call_id, context, cancel) } + fn invoke<'a>(&'a self, gate_id: &'a str, call: ToolCall) -> HostFuture<'a, ToolResult> { + Box::pin(self.executor.invoke(gate_id, call)) + } + fn close<'a>(&'a self, gate_id: &'a str) -> HostFuture<'a, Vec> { + Box::pin(self.executor.close(gate_id)) + } } diff --git a/crates/dim-codemode/src/interpreter.rs b/crates/dim-codemode/src/interpreter.rs index 627729a3f4..8db36a4ea3 100644 --- a/crates/dim-codemode/src/interpreter.rs +++ b/crates/dim-codemode/src/interpreter.rs @@ -1,8 +1,5 @@ use crate::{config::CodeModeConfig, host::NestedToolHost}; -use dim_agent_capabilities::{ - host::{HostError, ToolExecutionContext}, - tool_executor::NestedGate, -}; +use dim_agent_capabilities::host::{HostError, ToolExecutionContext}; use dim_agent_types::{JsonObject, ToolCall, ToolEffect, ToolResult}; use rquickjs::{AsyncContext, AsyncRuntime, Function, Object, Promise, prelude::*}; use serde_json::json; @@ -117,6 +114,7 @@ pub(crate) async fn run_program( let cancel_after = cancel.clone(); let calls_after = calls.clone(); let gate_after = gate.clone(); + let executor_after = executor.clone(); let child_cancel_after = child_cancel.clone(); let run = context_handle.async_with(async move |ctx| { let host_tools = Object::new(ctx.clone()).map_err(js_error)?; @@ -146,7 +144,8 @@ pub(crate) async fn run_program( host_tools.set("describe", describe).map_err(js_error)?; let call_scope = CallScope { - gate: gate.clone(), + executor, + gate, cancel: child_cancel.clone(), count: calls.clone(), parallel: parallel.clone(), @@ -192,8 +191,7 @@ pub(crate) async fn run_program( result = timeout_at(deadline, run) => result.ok(), }; child_cancel_after.cancel(); - gate_after.close().await; - let effects = gate_after.effects(); + let effects = executor_after.close(&gate_after).await?; match result { Some(Ok(output)) => Ok(if output.len() > output_limit { @@ -233,7 +231,8 @@ pub(crate) async fn run_program( #[derive(Clone)] struct CallScope { - gate: Arc, + executor: Arc, + gate: String, cancel: CancellationToken, count: Arc, parallel: Arc, @@ -288,7 +287,7 @@ async fn call_nested_tool( name, input, }; - let result = scope.gate.invoke(call).await; + let result = scope.executor.invoke(&scope.gate, call).await; drop(permit); match result { Ok(result) => { diff --git a/crates/dim-codemode/src/tests.rs b/crates/dim-codemode/src/tests.rs index 42603714b0..364a98abcf 100644 --- a/crates/dim-codemode/src/tests.rs +++ b/crates/dim-codemode/src/tests.rs @@ -1,15 +1,15 @@ use crate::{CodeModeConfig, NestedToolHost, interpreter::run_program}; use dim_agent_capabilities::{ - host::{HostError, ToolExecutionContext}, - tool_executor::NestedGate, + host::{HostError, HostFuture, ToolExecutionContext}, tool_registry::definition, }; use dim_agent_types::{ToolCall, ToolContent, ToolDefinition, ToolResult, ToolSource}; use serde_json::json; -use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; use tokio_util::sync::CancellationToken; struct MockHost { + effects: std::sync::Mutex>, definitions: Vec, } @@ -23,22 +23,11 @@ impl NestedToolHost for MockHost { _: String, _: ToolExecutionContext, _: CancellationToken, - ) -> Result, HostError> { - Ok(Arc::new(MockGate { - effects: std::sync::Mutex::new(Vec::new()), - })) + ) -> Result { + Ok("gate".to_owned()) } -} - -struct MockGate { - effects: std::sync::Mutex>, -} -impl NestedGate for MockGate { - fn invoke( - &self, - call: ToolCall, - ) -> Pin> + Send + '_>> { + fn invoke<'a>(&'a self, _: &'a str, call: ToolCall) -> HostFuture<'a, ToolResult> { Box::pin(async move { let result = match call.name.as_str() { "echo" => Ok::(ToolResult::text( @@ -77,12 +66,8 @@ impl NestedGate for MockGate { }) } - fn close(&self) -> Pin + Send + '_>> { - Box::pin(async {}) - } - - fn effects(&self) -> Vec { - self.effects.lock().unwrap().clone() + fn close<'a>(&'a self, _: &'a str) -> HostFuture<'a, Vec> { + Box::pin(async { Ok(std::mem::take(&mut *self.effects.lock().unwrap())) }) } } @@ -98,6 +83,7 @@ fn host() -> Arc { let mut codemode = definition("codemode", "self", json!({"type": "object"})); codemode.source = ToolSource::Extension; Arc::new(MockHost { + effects: Default::default(), definitions: vec![ definition("echo", "echo", json!({"type": "object"})), definition("fail", "fail", json!({"type": "object"})), diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index 6b04265046..300986733d 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -121,7 +121,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `timeline` | branch | BranchScope | data | `ancestors` async, `append` async, `branchId` async, `committed` async, `hasPending` async, `query` async, `sequence` async | | `timelineIdentity` | branch | BranchScope | data | `get` async | | `toolBinding` | branch | ToolBinding | data | `bind` sync, `bindCurrent` sync, `definitions` sync, `release` sync, `transfer` sync | -| `toolExecutor` | branch | ToolExecutor | internal(hot-path) | — | +| `toolExecutor` | branch | ToolExecutor | data | `close` async, `invoke` async, `open` sync | | `wait` | branch | WaitBranch | data | `wait` async | ## Capabilities diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index b61ed495f1..72c8e9bf02 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -2254,6 +2254,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#toolExecutor@main", + "provider": 79, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#wait@main", "provider": 81, diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index edaca8f7b4..d26d9759c2 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -1719,6 +1719,12 @@ "provider": 48, "generation": 1, "removing": false + }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#toolExecutor@main", + "provider": 49, + "generation": 1, + "removing": false } ] }, diff --git a/docs/architecture/rust-agent/plugins/ToolExecution.md b/docs/architecture/rust-agent/plugins/ToolExecution.md index 2cbe842e6c..c2aafc2747 100644 --- a/docs/architecture/rust-agent/plugins/ToolExecution.md +++ b/docs/architecture/rust-agent/plugins/ToolExecution.md @@ -165,6 +165,10 @@ declarations on it travel on that fact ([session boundary A.6](../../../design/contracts/session-boundary.md#a6-tool-effects)); a call it settles without a tool result carries none. Calls in a batch settle before the correlated batch result. +The branch `toolExecutor.open({parentCallId, context}, cancelled)` returns a gate ID for the current batch. +`invoke({gateId, call})` executes the pinned tool and returns its result. +`close({gateId})` closes admission, joins child tasks and returns their effects in invocation order. + One top-level batch runs at once. A child batch carries `parent_call_id`; the top-level consumer ignores child batches, and the nested gate writes their `step/tool-call`/`step/tool-result` and joins them before the outer result. Child @@ -220,7 +224,7 @@ effect before it retries, and reports the work neither as done nor as never run. | --- | --- | | 作用域 | 分支 | | 注入 | `B:Approval`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`B:ToolBinding` | -| 提供 | `B:ToolExecutor` | +| 提供 | `B:ToolExecutor`、`B:dyn HostDispatch#toolExecutor` | | 被注入于 | — | diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index 2ddd87c095..1e86a7a67f 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -468,16 +468,16 @@ CodeModeBranch::run(outer_call_id, code, context, cancel): runtime = AsyncRuntime::new(); runtime.set_memory_limit(max) runtime.set_interrupt_handler(deadline || child_cancel) quickjs = AsyncContext::full(runtime) - gate = toolExecutor.open(outer_call_id) + gateId = toolExecutor.open({parentCallId: outer_call_id, context}, cancelled) result = try: quickjs.async_with(|ctx|: install tools.list / tools.describe from toolBinding.definitions({requestId: context.request_id}) - install tools.call = Async(|name, args| gate.invoke(ToolCall{name, args}, context, child_cancel)) + install tools.call = Async(|name, args| toolExecutor.invoke({gateId, call: {id: child_id, name, input: args}})) promise = ctx.eval(async function body) return promise.into_future()) finally: child_cancel.cancel() - gate.close(reason) + collected_effects = toolExecutor.close({gateId}) drop(program_slot) return ToolResult { content: JSON(result), effects: collected_effects } ``` diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 7cf6f42c89..2ca6a70c9b 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -175,7 +175,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `prompt` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `contextPreparation` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `contextUsage` | branch | ContextUsage | hot-path | 本地请求计数器、请求引用与按序统计;`session.context.usage` 是 App Server RPC。按 #1292 确认是否需要独立插件操作。 | -| `toolExecutor` | branch | ToolExecutor | hot-path | 待迁移;按 #1292 定义操作面 | | `branchOpening` | branch | BranchScope | hot-path | 待迁移;按 #1292 定义操作面 | | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 22112c5178..867c152480 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -831,6 +831,11 @@ export interface FileReads { } export type BoundToolDefinition = Omit & { risk?: string }; +export interface ToolExecutor { + open(request: { parentCallId: string; context: { turnId: string; requestId: string; branchId: string } }, cancelled: () => Promise): string; + invoke(request: { gateId: string; call: { id: string; name: string; input: JsonObject } }): Promise; + close(request: { gateId: string }): Promise; +} export interface ToolBinding { bind(request: { requestId: string; through: number | bigint; tools: BoundToolDefinition[]; toolSources: { key: string; version: string }[] }): void; bindCurrent(request: { requestId: string; declared?: BoundToolDefinition[] | null }): BoundToolDefinition[]; diff --git a/runtime/fixtures/tool-executor.ts b/runtime/fixtures/tool-executor.ts new file mode 100644 index 0000000000..b7053d4984 --- /dev/null +++ b/runtime/fixtures/tool-executor.ts @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict' +import { definePlugin } from '@arcships/rutis' +import type { SessionMethods, ToolExecutor } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin({ + name: 'ToolExecutorFixture', + inject: ['toolExecutor', 'sessionMethods'], + async apply(ctx) { + const executor = ctx.use('toolExecutor') + await ctx.use('sessionMethods').register('session.nestedfixture', [ + { name: 'session.nestedfixture.run', mutating: false, interruption: 'report', progress: false }, + ], async call => { + const { turnId, requestId, branchId, parentCallId } = call.params + if (typeof turnId !== 'string' || typeof requestId !== 'string' || + typeof branchId !== 'string' || typeof parentCallId !== 'string') throw new Error('missing context') + let release!: () => void + const cancelled = new Promise(resolve => { release = resolve }) + const gateId = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => cancelled) + const child = { id: 'nested-echo', name: 'echo', input: { text: 'from node' } } + try { + const result = await executor.invoke({ gateId, call: child }) + const effects = await executor.close({ gateId }) + await assert.rejects(async () => executor.invoke({ gateId, call: child }), /closed/) + assert.ok(typeof result.content === 'string') + assert.deepEqual(effects, []) + const waitingGate = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => cancelled) + const waiting = executor.invoke({ gateId: waitingGate, call: { + id: 'nested-wait', name: 'wait', input: { millis: 60000 }, + } }) + release() + const interrupted = await waiting + assert.equal(interrupted.isError, true) + assert.match(String(interrupted.content), /cancel/i) + assert.deepEqual(await executor.close({ gateId: waitingGate }), []) + return { kind: 'value', value: { output: result.content, effectCount: effects.length } } + } finally { + release() + } + }) + }, +}) +export default partRow('branch', part) From b82c49411294a0d66270f06b2a0ae666520afc6d Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 21:09:20 +0800 Subject: [PATCH 06/11] Bind nested tool calls to their live parent and preserve settled effects --- .../src/tool_binding.rs | 3 + .../src/tool_executor.rs | 275 +++++++++++------- .../tests/transport_flow/branch_typescript.rs | 84 +++++- .../rust-agent/plugins/ToolExecution.md | 2 +- .../contracts/runtime-owner-operations.md | 2 +- runtime/fixtures/tool-binding.ts | 8 +- runtime/fixtures/tool-executor.ts | 23 +- 7 files changed, 289 insertions(+), 108 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 701da7c467..88157834bd 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -212,6 +212,9 @@ impl ToolBinding { /// Moves a request's snapshot to its budget recovery request. pub fn transfer(&self, from: &str, to: &str) -> Result<(), String> { let mut state = self.state.lock().unwrap(); + if from != to && state.snapshots.contains_key(to) && state.snapshots.contains_key(from) { + return Err(format!("request {to} is already bound")); + } let snapshot = state .snapshots .remove(from) diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index def90db852..0d86c50c14 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -17,24 +17,26 @@ use futures_util::FutureExt; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis::{Ctx, Error}; use std::{ - collections::BTreeMap, + collections::{BTreeMap, HashSet}, num::NonZeroU64, panic::AssertUnwindSafe, sync::{ Arc, Mutex, - atomic::{AtomicU64, AtomicUsize, Ordering}, + atomic::{AtomicUsize, Ordering}, }, time::Duration, }; use tokio::{ sync::{oneshot, watch}, - time::timeout, + time::{Instant, timeout_at}, }; use tokio_util::{sync::CancellationToken, task::TaskTracker}; #[derive(Default)] struct ToolState { current: Option, + running_parents: BTreeMap, + call_ids: HashSet, gates: BTreeMap>, /// The context of the current top-level batch. A nested gate opens only /// for this context. @@ -55,56 +57,77 @@ pub struct ToolExecutor { } struct NestedGate { - timeline: Arc, - binding: Arc, - approval: Arc, parent_call_id: String, context: ToolExecutionContext, cancel: CancellationToken, tasks: TaskTracker, - closing: Mutex, - next: AtomicU64, + closing: Mutex>, effects: Mutex)>>, } impl NestedGate { - async fn invoke(self: &Arc, call: ToolCall) -> Result { + fn start( + self: &Arc, + call: ToolCall, + ids: &mut HashSet, + owner: Arc, + ) -> Result>, HostError> { let (sender, receiver) = oneshot::channel(); { let closing = self.closing.lock().unwrap(); - if *closing { + if closing.is_some() { return Err(HostError::failed("the Code Mode child gate is closed")); } - let sequence = self.next.fetch_add(1, Ordering::SeqCst); + if self.cancel.is_cancelled() { + return Err(HostError::Cancelled( + "the Code Mode child gate was cancelled".into(), + )); + } + if !ids.insert(call.id.clone()) { + return Err(HostError::failed(format!( + "tool call {} already exists in this batch", + call.id + ))); + } let gate = self.clone(); - self.tasks.spawn(async move { - let _ = sender.send(gate.run_child(call, sequence).await); - }); + let tracker = owner.tasks.clone(); + self.tasks.spawn(tracker.track_future(async move { + let _ = sender.send(gate.run_child(&owner, call).await); + })); } - receiver - .await - .unwrap_or_else(|_| Err(HostError::failed("a Code Mode child task ended"))) + Ok(receiver) } - async fn close(&self) { - *self.closing.lock().unwrap() = true; + fn stop(&self) -> (Instant, bool) { + let mut closing = self.closing.lock().unwrap(); + let first = closing.is_none(); + let deadline = *closing.get_or_insert_with(|| Instant::now() + Duration::from_secs(5)); self.cancel.cancel(); self.tasks.close(); - let _ = timeout(Duration::from_secs(5), self.tasks.wait()).await; + (deadline, first) + } + + async fn close(&self) { + let (deadline, _) = self.stop(); + let _ = timeout_at(deadline, self.tasks.wait()).await; } fn effects(&self) -> Vec { - let mut collected = std::mem::take(&mut *self.effects.lock().unwrap()); + let mut collected = self.effects.lock().unwrap().clone(); collected.sort_by_key(|(sequence, _)| *sequence); collected .into_iter() .flat_map(|(_, effects)| effects) .collect() } - async fn run_child(&self, call: ToolCall, sequence: u64) -> Result { + async fn run_child( + &self, + owner: &ToolExecutor, + call: ToolCall, + ) -> Result { let context = &self.context; let parent_call_id = &self.parent_call_id; - let batch = self + let batch = owner .timeline .append( EventDraft::from(EventKind::ToolCall(ToolCallData { @@ -119,14 +142,19 @@ impl NestedGate { let outcome = AssertUnwindSafe(dim_agent_runtime::core::with_parent_call_id( child_call_id, async { - execute( - &self.binding, - &self.approval, + let admitted = admit( + &owner.binding, + &owner.approval, call.clone(), - context.clone(), + context, self.cancel.clone(), ) - .await + .await?; + let mut errors = Vec::new(); + let (result, _) = owner + .run_parent(admitted, context.clone(), self.cancel.clone(), &mut errors) + .await; + Ok::<_, HostError>(result) }, )) .catch_unwind() @@ -136,10 +164,8 @@ impl NestedGate { Ok(Err(error)) => ToolResult::error(error.to_string()), Err(panic) => ToolResult::error(panic_message(panic)), }; - if let Some(child_effects) = result.effects.clone() { - self.effects.lock().unwrap().push((sequence, child_effects)); - } - self.timeline + owner + .timeline .append( EventDraft::from(EventKind::ToolResult(ToolResultData { turn_id: context.turn_id.clone(), @@ -153,10 +179,71 @@ impl NestedGate { .with_parent_call_id(parent_call_id.clone()), ) .map_err(|error| HostError::failed(error.to_string()))?; + if let Some(child_effects) = result.effects.clone() { + self.effects + .lock() + .unwrap() + .push((batch.sequence, child_effects)); + } Ok(result) } } impl ToolExecutor { + async fn run_parent( + &self, + admitted: Admitted, + context: ToolExecutionContext, + cancel: CancellationToken, + errors: &mut Vec, + ) -> (ToolResult, &'static str) { + let id = admitted.call.id.clone(); + { + let mut state = self.state.lock().unwrap(); + if cancel.is_cancelled() || state.current_context.as_ref() != Some(&context) { + return ( + ToolResult::error("Tool cancelled before execution"), + "interrupted", + ); + } + state.running_parents.insert(id.clone(), cancel.clone()); + } + let outcome = AssertUnwindSafe(run(admitted, context.clone(), cancel.clone())) + .catch_unwind() + .await; + let gates = { + let mut state = self.state.lock().unwrap(); + if state.current_context.as_ref() == Some(&context) { + state.running_parents.remove(&id); + } + state + .gates + .extract_if(.., |_, gate| { + gate.parent_call_id == id && gate.context == context + }) + .map(|(_, gate)| gate) + .collect::>() + }; + let (mut result, label) = settled(outcome, cancel.is_cancelled(), errors); + if gates.is_empty() { + return (result, label); + } + futures_util::future::join_all(gates.iter().map(|gate| gate.close())).await; + let mut confirmed = Vec::new(); + for gate in gates { + confirmed.extend(gate.effects.lock().unwrap().iter().cloned()); + } + confirmed.sort_by_key(|(sequence, _)| *sequence); + let mut reported = result.effects.clone().unwrap_or_default(); + for effect in confirmed.into_iter().flat_map(|(_, effects)| effects) { + if let Some(index) = reported.iter().position(|item| item == &effect) { + reported.swap_remove(index); + } else { + result.effects.get_or_insert_with(Vec::new).push(effect); + } + } + (result, label) + } + /// 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 /// interrupted executor refuses. @@ -184,41 +271,51 @@ impl ToolExecutor { "ToolExecutor is interrupted: {reason}" ))); } - let Some(batch) = state - .current - .as_ref() + let Some(parent) = state + .running_parents + .get(&parent_call_id) .filter(|_| state.current_context.as_ref() == Some(&context)) else { return Err(HostError::failed( "no current tool batch accepts a Code Mode child", )); }; + let cancel = cancellation(parent); + if parent.is_cancelled() || cancel.is_cancelled() { + return Err(HostError::Cancelled( + "the Code Mode child gate was cancelled".into(), + )); + } let id = uuid::Uuid::new_v4().to_string(); let gate = Arc::new(NestedGate { - binding: self.binding.clone(), - approval: self.approval.clone(), - timeline: self.timeline.clone(), parent_call_id, context, - cancel: cancellation(batch), + cancel, tasks: TaskTracker::new(), - closing: Mutex::new(false), - next: AtomicU64::new(0), + closing: Mutex::new(None), effects: Mutex::default(), }); state.gates.insert(id.clone(), gate.clone()); Ok((id, gate)) } - pub async fn invoke(&self, gate_id: &str, call: ToolCall) -> Result { - let gate = self - .state - .lock() - .unwrap() - .gates - .get(gate_id) - .cloned() - .ok_or_else(|| HostError::failed("the Code Mode child gate is closed"))?; - gate.invoke(call).await + pub async fn invoke( + self: &Arc, + gate_id: &str, + call: ToolCall, + ) -> Result { + let receiver = { + let mut state = self.state.lock().unwrap(); + let gate = state + .gates + .get(gate_id) + .filter(|gate| state.running_parents.contains_key(&gate.parent_call_id)) + .cloned() + .ok_or_else(|| HostError::failed("the Code Mode child gate is closed"))?; + gate.start(call, &mut state.call_ids, self.clone())? + }; + receiver + .await + .unwrap_or_else(|_| Err(HostError::failed("a Code Mode child task ended"))) } pub async fn close(&self, gate_id: &str) -> Result, HostError> { @@ -227,9 +324,14 @@ impl ToolExecutor { .lock() .unwrap() .gates - .remove(gate_id) + .get(gate_id) + .cloned() .ok_or_else(|| HostError::failed("the Code Mode child gate is closed"))?; - gate.close().await; + let (deadline, first) = gate.stop(); + if !first { + return Err(HostError::failed("the Code Mode child gate is closed")); + } + let _ = timeout_at(deadline, gate.tasks.wait()).await; Ok(gate.effects()) } } @@ -382,6 +484,7 @@ impl DynPlugin for ToolExecutorPlugin { let cancel = lifecycle.child_token(); let generation = lifecycle.clone(); state.current = Some(cancel.clone()); + state.call_ids = batch.calls.iter().map(|call| call.id.clone()).collect(); state.current_context = Some(ToolExecutionContext { turn_id: batch.turn_id.clone(), request_id: batch.request_id.clone(), @@ -414,6 +517,7 @@ impl DynPlugin for ToolExecutorPlugin { let (turn, segment_of, mut waiters) = Turn::new(classes, count); let calls = batch.calls.iter().cloned().enumerate().map( |(index, call)| { + let worker = worker.clone(); let binding = binding.clone(); let approval = approval.clone(); let timeline = timeline.clone(); @@ -467,7 +571,6 @@ impl DynPlugin for ToolExecutorPlugin { ); } let span = tracing::info_span!("tool.execute", session_id = %session_id, branch_id = %context.branch_id, turn_id = %context.turn_id, request_id = %context.request_id, call_id = %call.id, outcome = tracing::field::Empty); - let interrupt = cancel.clone(); let (result, outcome) = if cancel.is_cancelled() { (ToolResult::error("Tool cancelled before execution"), "interrupted") } else { @@ -486,42 +589,26 @@ impl DynPlugin for ToolExecutorPlugin { // its own admission is done and every // earlier step settled. A sibling's // admission is not one of them. - let mut settle = |outcome| { - settled( - outcome, - interrupt.is_cancelled(), - &mut errors, - ) - }; - let ahead = |head: &usize| *head >= segment; - if segment > 0 { - let waited = barrier.wait_for(ahead); - let ready = tokio::select! { + let ready = if segment == 0 { + true + } else { + let ahead = |head: &usize| *head >= segment; + let wait = barrier.wait_for(ahead); + tokio::select! { biased; _ = cancel.cancelled() => false, - waited = waited => waited.is_ok(), - }; - if !ready { - (ToolResult::error("Tool cancelled before execution"), "interrupted") - } else { - let outcome = AssertUnwindSafe(run( - admitted, - context.clone(), - cancel.clone(), - )) - .catch_unwind() - .await; - settle(outcome) + r = wait => r.is_ok(), } - } else { - let outcome = AssertUnwindSafe(run( + }; + if ready { + worker.run_parent( admitted, context.clone(), cancel.clone(), - )) - .catch_unwind() - .await; - settle(outcome) + &mut errors, + ).await + } else { + (ToolResult::error("Tool cancelled before execution"), "interrupted") } } Ok(Err(error)) => { @@ -588,9 +675,13 @@ impl DynPlugin for ToolExecutorPlugin { let mut state = worker.state.lock().unwrap(); state.current = None; state.current_context = None; - (state.closed || generation.is_cancelled(), std::mem::take(&mut state.gates)) + state.call_ids.clear(); + state.running_parents.clear(); + let unloading = state.closed || generation.is_cancelled(); + (unloading, std::mem::take(&mut state.gates)) }; - futures_util::future::join_all(gates.values().map(|gate| gate.close())).await; + let closing = gates.values().map(|gate| gate.close()); + futures_util::future::join_all(closing).await; let (mut results, mut errors) = match outcome { Ok(settled) => settled, Err(error) => { @@ -740,18 +831,6 @@ async fn run( } } -/// Admits one call through Approval, then runs its handler. -async fn execute( - binding: &ToolBinding, - approval: &Approval, - call: ToolCall, - context: ToolExecutionContext, - cancel: CancellationToken, -) -> Result { - let admitted = admit(binding, approval, call, &context, cancel.clone()).await?; - run(admitted, context, cancel).await -} - /// The steps of one batch and the barrier between them. /// /// A step is a run of consecutive calls that may share one moment: a call diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 42e28ec413..6d97dac98a 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -588,6 +588,12 @@ async fn node_tool_binding_transfers_pinned_handlers_in_the_native_owner() { assert_eq!(reply["result"]["echo"], echo.description); assert_eq!(reply["result"]["current"], reply["result"]["transferred"]); assert_eq!(reply["result"]["empty"], 0); + assert!( + reply["result"]["collision"] + .as_str() + .unwrap() + .contains("request fixture-empty is already bound") + ); server.shutdown(); server.join().await.unwrap(); } @@ -668,7 +674,7 @@ async fn node_file_reads_round_trips_a_native_binding_used_by_write() { #[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch() { use dim_agent_capabilities::host::{HostFuture, ToolExecutionContext}; - use dim_agent_types::{ToolCall, ToolDefinition, ToolResult}; + use dim_agent_types::{ToolCall, ToolDefinition, ToolEffect, ToolResult}; struct Tools(tokio::sync::mpsc::UnboundedSender<(String, ToolExecutionContext)>); impl ToolDriver for Tools { @@ -684,6 +690,15 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( if call.name == "wait" { self.0.send((call.id.clone(), context.clone())).unwrap(); } + if call.name == "echo" { + return Box::pin(async move { + let mut result = MockTools.execute(call, context, cancel).await?; + result.effects = Some(vec![ToolEffect::FileWritten { + path: "/fixture".into(), + }]); + Ok(result) + }); + } MockTools.execute(call, context, cancel) } } @@ -693,7 +708,7 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( parts.rows = vec![ json!({"id":"tool-executor","name":parts.anchor.parent().unwrap().join("fixtures/tool-executor.ts"),"provides":{}}), ]; - let (server, _agent) = launch_with( + let (server, agent) = launch_with( Arc::new(Tools(started)), ServerConfig { session_typescript: Some(parts), @@ -718,17 +733,78 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( .await .unwrap() .unwrap(); - let response = client.rpc("session.nestedfixture.run", json!({"sessionId":id,"parentCallId":parent,"turnId":context.turn_id,"requestId":context.request_id,"branchId":context.branch_id})).await; + let mut control = Client::new_version(&server, false, 4).await; + let (response, ()) = tokio::join!( + client.rpc( + "session.nestedfixture.run", + json!({ + "sessionId":id,"parentCallId":parent,"turnId":context.turn_id, + "requestId":context.request_id,"branchId":context.branch_id + }) + ), + async { + let (child, _) = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(child, "nested-wait"); + assert_ok( + &control + .rpc("session.nestedfixture.cancel", json!({"sessionId":id,"parentCallId":child,"turnId":context.turn_id,"requestId":context.request_id,"branchId":context.branch_id})) + .await, + ); + } + ); assert_ok(&response); assert_eq!( response["result"], - json!({"output":"from node","effectCount":0}) + json!({"output":"from node","effectCount":1}) ); assert_ok( &client .rpc("session.stop", json!({"sessionId":id,"branchId":"main"})) .await, ); + assert_ok( + &client + .rpc("session.idle", json!({"sessionId":id,"branchId":"main"})) + .await, + ); + let session = agent.get_session(&id).unwrap(); + let events = branch_events(&session, "main", ..).await.unwrap(); + let child_calls = events + .iter() + .filter(|event| { + event.parent_call_id.as_deref() == Some(&parent) + && matches!(event.kind, dim_agent_types::EventKind::ToolCall(_)) + }) + .count(); + assert_eq!(child_calls, 2); + assert!(events.iter().any( + |event| event.parent_call_id.as_deref() == Some("nested-wait") + && matches!(event.kind, dim_agent_types::EventKind::ToolCall(_)) + )); + let parent_result = events + .iter() + .find_map(|event| match &event.kind { + dim_agent_types::EventKind::ToolResult(data) if event.parent_call_id.is_none() => { + data.results.iter().find(|item| item.call_id == parent) + } + _ => None, + }) + .unwrap(); + assert_eq!( + parent_result.result.effects.as_deref(), + Some( + vec![ + ToolEffect::FileWritten { + path: "/fixture".into() + }; + 2 + ] + .as_slice() + ) + ); server.shutdown(); server.join().await.unwrap(); } diff --git a/docs/architecture/rust-agent/plugins/ToolExecution.md b/docs/architecture/rust-agent/plugins/ToolExecution.md index c2aafc2747..b5d0ce483e 100644 --- a/docs/architecture/rust-agent/plugins/ToolExecution.md +++ b/docs/architecture/rust-agent/plugins/ToolExecution.md @@ -165,7 +165,7 @@ declarations on it travel on that fact ([session boundary A.6](../../../design/contracts/session-boundary.md#a6-tool-effects)); a call it settles without a tool result carries none. Calls in a batch settle before the correlated batch result. -The branch `toolExecutor.open({parentCallId, context}, cancelled)` returns a gate ID for the current batch. +The branch `toolExecutor.open({parentCallId, context}, cancelled)` returns a gate ID for a running parent in the current batch. A child ID must be unique within that batch. A cancelled gate refuses further calls. The parent collects confirmed child effects when it settles, including effects from gates its handler left open. `invoke({gateId, call})` executes the pinned tool and returns its result. `close({gateId})` closes admission, joins child tasks and returns their effects in invocation order. diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 2e4e54fbd8..34b12e2c43 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -73,5 +73,5 @@ substitutes a newer head. | Loop and ContextPreparation → HistoryRenderer | `context({branchId, through}) → ContextHistory`, `renderedContext({branchId, through}) → {context, history: HistoryEntry[]}`, `snapshot({context, retainFrom, anchor}) → RecoverySnapshot`, `streamCheckpoint({branchId, through, retainFrom, batch}) → ProjectionCheckpoint`. | | Loop and ModelProvider → ContextPreparation | `prepare({source: ContextPrepareData, projection?}, cancelled) → ModelRequest`, `validate({requestId, request}, cancelled) → void`. Reuse the prepared projection at the original cutoff. | | ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}`. | -| Loop, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind({requestId, through, tools, toolSources}) → void`, `bindCurrent({requestId, declared?}) → ToolDefinition[]`, `definitions({requestId}) → ToolDefinition[]`, `transfer({from, to}) → void`, `release({requestId}) → void`. ToolBinding retains the pinned handler generation. | +| Loop, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind({requestId, through, tools, toolSources}) → void`, `bindCurrent({requestId, declared?}) → ToolDefinition[]`, `definitions({requestId}) → ToolDefinition[]`, `transfer({from, to}) → void`, `release({requestId}) → void`. ToolBinding retains the pinned handler generation. A transfer to another bound request is refused and preserves both bindings. | | Nested tool execution → `toolExecutor` | `open({parentCallId, context}, cancelled) → gateId`, `invoke({gateId, call}) → ToolResult`, `close({gateId}) → ToolEffect[]`. Close joins children in order; interruption releases the gate. | diff --git a/runtime/fixtures/tool-binding.ts b/runtime/fixtures/tool-binding.ts index 830712311c..5701527a2c 100644 --- a/runtime/fixtures/tool-binding.ts +++ b/runtime/fixtures/tool-binding.ts @@ -12,6 +12,12 @@ const part = definePlugin({ ], async () => { const declared = binding.bindCurrent({ requestId: 'fixture-current' }) binding.bind({ requestId: 'fixture-empty', through: 0n, tools: [], toolSources: [] }) + let collision = '' + try { + binding.transfer({ from: 'fixture-current', to: 'fixture-empty' }) + } catch (error) { + collision = String(error) + } const empty = binding.definitions({ requestId: 'fixture-empty' }) binding.release({ requestId: 'fixture-empty' }) binding.transfer({ from: 'fixture-current', to: 'fixture-transferred' }) @@ -25,7 +31,7 @@ const part = definePlugin({ current: declared.map(tool => tool.name).sort(), transferred: transferred.map(tool => tool.name), echo: transferred.find(tool => tool.name === 'echo')?.description ?? null, - empty: empty.length, + empty: empty.length, collision, } } }) }, diff --git a/runtime/fixtures/tool-executor.ts b/runtime/fixtures/tool-executor.ts index b7053d4984..490d20e854 100644 --- a/runtime/fixtures/tool-executor.ts +++ b/runtime/fixtures/tool-executor.ts @@ -8,33 +8,50 @@ const part = definePlugin({ inject: ['toolExecutor', 'sessionMethods'], async apply(ctx) { const executor = ctx.use('toolExecutor') + let cancelChild: (() => void) | undefined await ctx.use('sessionMethods').register('session.nestedfixture', [ { name: 'session.nestedfixture.run', mutating: false, interruption: 'report', progress: false }, + { name: 'session.nestedfixture.cancel', mutating: false, interruption: 'report', progress: false }, ], async call => { const { turnId, requestId, branchId, parentCallId } = call.params if (typeof turnId !== 'string' || typeof requestId !== 'string' || typeof branchId !== 'string' || typeof parentCallId !== 'string') throw new Error('missing context') + if (call.method === 'session.nestedfixture.cancel') { + if (!cancelChild) throw new Error('no child is running') + const gateId = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => new Promise(() => {})) + await executor.invoke({ gateId, call: { id: 'nested-grandchild', name: 'echo', input: { text: 'grandchild' } } }) + assert.deepEqual(await executor.close({ gateId }), [{ kind: 'fileWritten', path: '/fixture' }]) + cancelChild() + return { kind: 'value', value: {} } + } let release!: () => void const cancelled = new Promise(resolve => { release = resolve }) + assert.throws(() => executor.open({ + parentCallId: 'unknown-parent', context: { turnId, requestId, branchId }, + }, () => cancelled), /no current tool batch/) const gateId = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => cancelled) const child = { id: 'nested-echo', name: 'echo', input: { text: 'from node' } } try { const result = await executor.invoke({ gateId, call: child }) + await assert.rejects(async () => executor.invoke({ gateId, call: { ...child, id: parentCallId } }), /already exists/) + await assert.rejects(async () => executor.invoke({ gateId, call: child }), /already exists/) const effects = await executor.close({ gateId }) await assert.rejects(async () => executor.invoke({ gateId, call: child }), /closed/) assert.ok(typeof result.content === 'string') - assert.deepEqual(effects, []) + assert.deepEqual(effects, [{ kind: 'fileWritten', path: '/fixture' }]) const waitingGate = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => cancelled) + cancelChild = release const waiting = executor.invoke({ gateId: waitingGate, call: { id: 'nested-wait', name: 'wait', input: { millis: 60000 }, } }) - release() const interrupted = await waiting assert.equal(interrupted.isError, true) assert.match(String(interrupted.content), /cancel/i) - assert.deepEqual(await executor.close({ gateId: waitingGate }), []) + await assert.rejects(async () => executor.invoke({ gateId: waitingGate, call: child }), /cancel/i) + assert.deepEqual(await executor.close({ gateId: waitingGate }), effects) return { kind: 'value', value: { output: result.content, effectCount: effects.length } } } finally { + cancelChild = undefined release() } }) From 02d607582c42214b6976fe18aa99060993292420 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 00:52:14 +0800 Subject: [PATCH 07/11] Collect nested tool effects in admission order across gates --- crates/dim-agent-capabilities/src/tool_executor.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index 0d86c50c14..7085748733 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -62,7 +62,7 @@ struct NestedGate { cancel: CancellationToken, tasks: TaskTracker, closing: Mutex>, - effects: Mutex)>>, + effects: Mutex)>>, } impl NestedGate { @@ -89,10 +89,11 @@ impl NestedGate { call.id ))); } + let ordinal = ids.len(); let gate = self.clone(); let tracker = owner.tasks.clone(); self.tasks.spawn(tracker.track_future(async move { - let _ = sender.send(gate.run_child(&owner, call).await); + let _ = sender.send(gate.run_child(&owner, call, ordinal).await); })); } Ok(receiver) @@ -114,7 +115,7 @@ impl NestedGate { fn effects(&self) -> Vec { let mut collected = self.effects.lock().unwrap().clone(); - collected.sort_by_key(|(sequence, _)| *sequence); + collected.sort_by_key(|(ordinal, _)| *ordinal); collected .into_iter() .flat_map(|(_, effects)| effects) @@ -124,6 +125,7 @@ impl NestedGate { &self, owner: &ToolExecutor, call: ToolCall, + ordinal: usize, ) -> Result { let context = &self.context; let parent_call_id = &self.parent_call_id; @@ -183,7 +185,7 @@ impl NestedGate { self.effects .lock() .unwrap() - .push((batch.sequence, child_effects)); + .push((ordinal, child_effects)); } Ok(result) } @@ -232,7 +234,7 @@ impl ToolExecutor { for gate in gates { confirmed.extend(gate.effects.lock().unwrap().iter().cloned()); } - confirmed.sort_by_key(|(sequence, _)| *sequence); + confirmed.sort_by_key(|(ordinal, _)| *ordinal); let mut reported = result.effects.clone().unwrap_or_default(); for effect in confirmed.into_iter().flat_map(|(_, effects)| effects) { if let Some(index) = reported.iter().position(|item| item == &effect) { From 87ef53fb721b9da334ba4efbc6f2a708108452f2 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 23:00:37 +0800 Subject: [PATCH 08/11] Settle all confirmed nested effects in admission order --- .../src/tool_executor.rs | 26 ++++++++++--------- .../tests/transport_flow/branch_typescript.rs | 15 ++++++----- runtime/fixtures/tool-executor.ts | 6 ++--- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index 7085748733..8b6ea357d4 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -182,10 +182,7 @@ impl NestedGate { ) .map_err(|error| HostError::failed(error.to_string()))?; if let Some(child_effects) = result.effects.clone() { - self.effects - .lock() - .unwrap() - .push((ordinal, child_effects)); + self.effects.lock().unwrap().push((ordinal, child_effects)); } Ok(result) } @@ -235,20 +232,25 @@ impl ToolExecutor { confirmed.extend(gate.effects.lock().unwrap().iter().cloned()); } confirmed.sort_by_key(|(ordinal, _)| *ordinal); - let mut reported = result.effects.clone().unwrap_or_default(); - for effect in confirmed.into_iter().flat_map(|(_, effects)| effects) { - if let Some(index) = reported.iter().position(|item| item == &effect) { - reported.swap_remove(index); - } else { - result.effects.get_or_insert_with(Vec::new).push(effect); + let children: Vec<_> = confirmed + .into_iter() + .flat_map(|(_, effects)| effects) + .collect(); + if !children.is_empty() { + let reported = result.effects.get_or_insert_with(Vec::new); + for effect in &children { + if let Some(index) = reported.iter().position(|item| item == effect) { + reported.remove(index); + } } + reported.extend(children); } (result, label) } /// 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 - /// interrupted executor refuses. + /// exists only for a running parent in the matching current batch. Nested calls + /// must use distinct call IDs. A closed or interrupted executor refuses. pub fn open( self: &Arc, parent_call_id: String, diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 6d97dac98a..30e2bd7f79 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -692,10 +692,9 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( } if call.name == "echo" { return Box::pin(async move { + let path = format!("/{}", call.id); let mut result = MockTools.execute(call, context, cancel).await?; - result.effects = Some(vec![ToolEffect::FileWritten { - path: "/fixture".into(), - }]); + result.effects = Some(vec![ToolEffect::FileWritten { path }]); Ok(result) }); } @@ -796,11 +795,13 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( assert_eq!( parent_result.result.effects.as_deref(), Some( - vec![ + [ ToolEffect::FileWritten { - path: "/fixture".into() - }; - 2 + path: "/nested-echo".into() + }, + ToolEffect::FileWritten { + path: "/nested-grandchild".into() + }, ] .as_slice() ) diff --git a/runtime/fixtures/tool-executor.ts b/runtime/fixtures/tool-executor.ts index 490d20e854..cc0f11c260 100644 --- a/runtime/fixtures/tool-executor.ts +++ b/runtime/fixtures/tool-executor.ts @@ -20,7 +20,7 @@ const part = definePlugin({ if (!cancelChild) throw new Error('no child is running') const gateId = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => new Promise(() => {})) await executor.invoke({ gateId, call: { id: 'nested-grandchild', name: 'echo', input: { text: 'grandchild' } } }) - assert.deepEqual(await executor.close({ gateId }), [{ kind: 'fileWritten', path: '/fixture' }]) + assert.deepEqual(await executor.close({ gateId }), [{ kind: 'fileWritten', path: '/nested-grandchild' }]) cancelChild() return { kind: 'value', value: {} } } @@ -38,7 +38,7 @@ const part = definePlugin({ const effects = await executor.close({ gateId }) await assert.rejects(async () => executor.invoke({ gateId, call: child }), /closed/) assert.ok(typeof result.content === 'string') - assert.deepEqual(effects, [{ kind: 'fileWritten', path: '/fixture' }]) + assert.deepEqual(effects, [{ kind: 'fileWritten', path: '/nested-echo' }]) const waitingGate = executor.open({ parentCallId, context: { turnId, requestId, branchId } }, () => cancelled) cancelChild = release const waiting = executor.invoke({ gateId: waitingGate, call: { @@ -48,7 +48,7 @@ const part = definePlugin({ assert.equal(interrupted.isError, true) assert.match(String(interrupted.content), /cancel/i) await assert.rejects(async () => executor.invoke({ gateId: waitingGate, call: child }), /cancel/i) - assert.deepEqual(await executor.close({ gateId: waitingGate }), effects) + assert.deepEqual(await executor.close({ gateId: waitingGate }), [{ kind: 'fileWritten', path: '/nested-grandchild' }]) return { kind: 'value', value: { output: result.content, effectCount: effects.length } } } finally { cancelChild = undefined From e53ac59524a97be46c59f5e635643492db87ee01 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 23:06:17 +0800 Subject: [PATCH 09/11] Cover partial reporting of a later nested effect --- .../tests/transport_flow/branch_typescript.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 30e2bd7f79..939b5841e9 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -689,6 +689,16 @@ async fn node_nested_execution_runs_the_pinned_native_tool_in_the_current_batch( ) -> HostFuture<'_, ToolResult> { if call.name == "wait" { self.0.send((call.id.clone(), context.clone())).unwrap(); + if call.id != "nested-wait" { + return Box::pin(async move { + cancel.cancelled().await; + let mut result = ToolResult::error("parent interrupted"); + result.effects = Some(vec![ToolEffect::FileWritten { + path: "/nested-grandchild".into(), + }]); + Ok(result) + }); + } } if call.name == "echo" { return Box::pin(async move { From 1853d97977053bc93f828d214202249bc7c2c0ed Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sun, 22 Nov 2026 00:13:50 +0800 Subject: [PATCH 10/11] Verify the evaluator follow-up from the observed branch history (cherry picked from commit 1148170208402f250d94500002f54c3192bb9908) --- crates/dim-goal/tests/goal_product_flow.rs | 12 ++++++++---- crates/dim-goal/tests/support/mod.rs | 10 +++++++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/dim-goal/tests/goal_product_flow.rs b/crates/dim-goal/tests/goal_product_flow.rs index 645159019d..0a0166d622 100644 --- a/crates/dim-goal/tests/goal_product_flow.rs +++ b/crates/dim-goal/tests/goal_product_flow.rs @@ -1361,11 +1361,15 @@ async fn goal_evaluator_asks_again_and_continues() { // The first evaluator turn ends without a conclusion: Goal asks again on // the evaluator's own line. - wait_goal(&session, &child, r#"kind="evaluate-again""#).await; - let first_end = turn_ends(&session, &child).await[0]; + let (follow_up, history) = + wait_goal_with_history(&session, &child, r#"kind="evaluate-again""#).await; + let first_end = history + .iter() + .find(|event| matches!(event.kind, EventKind::TurnEnd(_))) + .expect("the evaluator's first turn ended before its follow-up"); assert_eq!( - goal_block(&session, &child, r#"kind="evaluate-again""#).await, - texts::evaluate_again(&child, first_end), + follow_up.text, + texts::evaluate_again(&child, first_end.sequence), "the evaluator's follow-up" ); diff --git a/crates/dim-goal/tests/support/mod.rs b/crates/dim-goal/tests/support/mod.rs index cef9a7996b..33710bd4a3 100644 --- a/crates/dim-goal/tests/support/mod.rs +++ b/crates/dim-goal/tests/support/mod.rs @@ -515,6 +515,14 @@ pub async fn goal_writes(session: &Session, branch: &str) -> Vec { /// Waits until a Goal write on `branch` contains `needle`; returns it. pub async fn wait_goal(session: &Session, branch: &str, needle: &str) -> Block { + wait_goal_with_history(session, branch, needle).await.0 +} + +pub async fn wait_goal_with_history( + session: &Session, + branch: &str, + needle: &str, +) -> (Block, Vec>) { tokio::time::timeout(Duration::from_secs(15), async { loop { if let Ok(events) = branch_events(session, branch, ..).await @@ -523,7 +531,7 @@ pub async fn wait_goal(session: &Session, branch: &str, needle: &str) -> Block { .filter_map(|event| block_of(event)) .find(|block| block.text.contains(needle)) { - return block; + return (block, events); } tokio::time::sleep(Duration::from_millis(10)).await; } From f603951ffa3bc7a5be191fd9d72890c5b48a3c61 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sun, 22 Nov 2026 01:08:38 +0800 Subject: [PATCH 11/11] Publish nested tool operations on the mounted ToolExecutor --- crates/dim-agent-capabilities/src/tool_executor.rs | 6 ++++-- .../dim-agent-capabilities/src/tool_executor/face.rs | 10 +++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index 8b6ea357d4..b10ccab840 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -48,6 +48,7 @@ struct ToolState { closed: bool, } pub struct ToolExecutor { + this: std::sync::Weak, state: Mutex, tasks: TaskTracker, errors: Mutex>, @@ -384,7 +385,8 @@ impl DynPlugin for ToolExecutorPlugin { let approval = ctx.require_at(&self.approval)?; let identity = ctx.require_at(&self.identity)?; let emit_progress = self.emit_progress; - let service = Arc::new(ToolExecutor { + let service = Arc::new_cyclic(|this| ToolExecutor { + this: this.clone(), state: Mutex::new(ToolState::default()), tasks: TaskTracker::new(), errors: Mutex::new(Vec::new()), @@ -759,7 +761,7 @@ impl DynPlugin for ToolExecutorPlugin { &dim_agent_runtime::names::name_of::(), self.instance, ), - Arc::new(face::Face(service.clone())), + service.clone(), )?; ctx.provide_at(self.executor.clone(), service)?; Ok(Effect::Done) diff --git a/crates/dim-agent-capabilities/src/tool_executor/face.rs b/crates/dim-agent-capabilities/src/tool_executor/face.rs index 5664f3a5ce..520ab27b0d 100644 --- a/crates/dim-agent-capabilities/src/tool_executor/face.rs +++ b/crates/dim-agent-capabilities/src/tool_executor/face.rs @@ -4,7 +4,6 @@ use dim_agent_types::ToolCall; use rutis::host::CtxHost; use rutis_bridge::session::{Error, HostDispatch, Reply, Value, arg, settle}; use serde::Deserialize; -use std::sync::Arc; use tokio_util::sync::CancellationToken; const NAME: &str = "toolExecutor"; @@ -29,9 +28,7 @@ struct Close { gate_id: String, } -pub(super) struct Face(pub(super) Arc); - -impl HostDispatch for Face { +impl HostDispatch for ToolExecutor { fn methods(&self) -> Option { Some(serde_json::json!({"open":"sync","invoke":"async","close":"async"})) } @@ -55,7 +52,6 @@ impl HostDispatch for Face { } = serde_json::from_value(data.clone().json()?) .map_err(|error| invalid(NAME, error))?; let (id, gate) = self - .0 .open_gate(parent_call_id, context, CancellationToken::child_token) .map_err(|error| Error::value(error.to_string()))?; let cancel = gate.cancel.clone(); @@ -78,7 +74,7 @@ impl HostDispatch for Face { } "invoke" => { let Invoke { gate_id, call } = request(NAME, args)?; - let owner = self.0.clone(); + let owner = self.this.upgrade().expect("mounted ToolExecutor"); Ok(Value::future(async move { arg(&ToolExecutor::invoke(&owner, &gate_id, call) .await @@ -87,7 +83,7 @@ impl HostDispatch for Face { } "close" => { let Close { gate_id } = request(NAME, args)?; - let owner = self.0.clone(); + let owner = self.this.upgrade().expect("mounted ToolExecutor"); Ok(Value::future(async move { arg(&owner .close(&gate_id)