From bc975d6f7de8ab6dad2e3555e09e3ecc5a97b273 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:44:54 +0800 Subject: [PATCH 01/50] feat: add the Session tool mode and the registry projection ToolMode is Session configuration (normal, codemode, shell) and normal is omitted from the stored form. ToolRegistry holds the chosen mode, falls back to normal when the entry tool is not mounted, and projects its callable set into the request's visible declarations and the child delegated set. Refs #2135 --- .../src/tool_registry.rs | 152 ++++++++++++++++++ crates/dim-agent-runtime/src/config.rs | 11 +- crates/dim-agent-types/src/lib.rs | 2 + crates/dim-agent-types/src/tool_mode.rs | 45 ++++++ 4 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 crates/dim-agent-types/src/tool_mode.rs diff --git a/crates/dim-agent-capabilities/src/tool_registry.rs b/crates/dim-agent-capabilities/src/tool_registry.rs index 3850714899..3d5f7ac6ab 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -265,6 +265,9 @@ pub struct ToolRegistry { offered: Mutex>, /// Configured names nothing has registered, reported once each. missing: Mutex>, + /// The operator's chosen mode; the effective one may fall back to + /// `normal` when its entry tool is not mounted. + mode: Mutex, session_id: String, config: Arc, /// Serializes refreshes from read to commit, so an earlier read never @@ -402,6 +405,49 @@ impl ToolRegistry { .cloned() .collect() } + /// The operator's chosen mode. + pub fn tool_mode(&self) -> ToolMode { + *self.mode.lock().unwrap() + } + /// The mode in force: the chosen one, or `normal` when its entry tool is + /// not mounted. + pub fn effective_tool_mode(&self) -> ToolMode { + let declared = self.snapshot().0; + self.effective_of(&declared) + } + fn effective_of(&self, declared: &[ToolDefinition]) -> ToolMode { + let mode = self.tool_mode(); + match mode.entry_tool() { + Some(entry) if declared.iter().any(|tool| tool.name == entry) => mode, + _ => ToolMode::Normal, + } + } + /// Replaces the live mode. It does not re-adopt a tool set: the next + /// request projects the same callable set under the new mode. + pub fn set_tool_mode(&self, mode: ToolMode) { + *self.mode.lock().unwrap() = mode; + } + /// The declarations the model request carries: the callable set projected + /// by the effective mode. + pub fn visible_definitions(&self) -> Vec { + let declared = self.snapshot().0; + let mode = self.effective_of(&declared); + declared + .into_iter() + .filter(|tool| visible_under(mode, &tool.name)) + .collect() + } + /// The tool names a Code Mode program may call; empty in the other modes. + pub fn delegated_definitions(&self) -> Vec { + let declared = self.snapshot().0; + if self.effective_of(&declared) != ToolMode::Codemode { + return Vec::new(); + } + declared + .into_iter() + .filter(|tool| tool.name != "codemode") + .collect() + } /// The current or a still-held replaced version of a key. pub fn source(&self, key: &str, version: &str) -> Option> { let sources = self.sources.lock().unwrap(); @@ -850,6 +896,17 @@ impl HostDispatch for ForeignRegistry { } } +/// Whether `name` is declared under `mode` (§2): `normal` hides both entry +/// tools, `codemode` declares only its entry and `skill`, and `shell` +/// declares only its entry and the two conversation tools. +fn visible_under(mode: ToolMode, name: &str) -> bool { + match mode { + ToolMode::Normal => !matches!(name, "codemode" | "execute"), + ToolMode::Codemode => matches!(name, "codemode" | "skill"), + ToolMode::Shell => matches!(name, "execute" | "ask_user" | "recall"), + } +} + pub fn definition(name: &str, description: &str, schema: serde_json::Value) -> ToolDefinition { ToolDefinition { name: name.into(), @@ -930,6 +987,7 @@ impl DynPlugin for ToolRegistryPlugin { providers: Arc::default(), offered: Mutex::default(), missing: Mutex::default(), + mode: Mutex::new(config.tool_mode), session_id: identity.session_id.clone(), config: config.clone(), refreshing: Mutex::default(), @@ -1028,6 +1086,7 @@ mod tests { providers: Arc::default(), offered: Mutex::default(), missing: Mutex::default(), + mode: Mutex::new(ToolMode::Normal), session_id: "session".into(), config, refreshing: Mutex::default(), @@ -1036,6 +1095,99 @@ mod tests { } } + fn projected(mode: ToolMode, names: &[&str]) -> (Vec, Vec) { + let config = Arc::new(SessionConfig { + tools: Some(names.iter().map(|name| (*name).to_owned()).collect()), + ..Default::default() + }); + let registry = ToolRegistry { + host: names + .iter() + .map(|name| { + Arc::new(ToolContribution { + definition: definition(name, "test", json!({"type": "object"})), + handler: Arc::new(Noop), + }) + }) + .collect(), + configured: config.tools.clone(), + excluded: HashSet::new(), + tools: Arc::default(), + providers: Arc::default(), + offered: Mutex::default(), + missing: Mutex::default(), + mode: Mutex::new(mode), + session_id: "session".into(), + config, + refreshing: Mutex::default(), + sources: Mutex::default(), + state: watch::Sender::new(ToolSourcesState::default()), + }; + let names = |definitions: Vec| { + definitions + .into_iter() + .map(|tool| tool.name) + .collect::>() + }; + ( + names(registry.visible_definitions()), + names(registry.delegated_definitions()), + ) + } + + #[test] + fn the_mode_projects_the_callable_set() { + let names = ["read", "skill", "ask_user", "recall", "codemode", "execute"]; + assert_eq!( + projected(ToolMode::Normal, &names), + ( + vec!["read", "skill", "ask_user", "recall"] + .into_iter() + .map(String::from) + .collect(), + vec![], + ) + ); + assert_eq!( + projected(ToolMode::Codemode, &names), + ( + vec!["skill", "codemode"] + .into_iter() + .map(String::from) + .collect(), + vec!["read", "skill", "ask_user", "recall", "execute"] + .into_iter() + .map(String::from) + .collect(), + ) + ); + assert_eq!( + projected(ToolMode::Shell, &names).0, + vec!["ask_user", "recall", "execute"] + .into_iter() + .map(String::from) + .collect::>() + ); + assert!(projected(ToolMode::Shell, &names).1.is_empty()); + } + + #[test] + fn a_mode_whose_entry_tool_is_absent_runs_normal() { + assert_eq!( + projected(ToolMode::Shell, &["read", "write"]).0, + vec![String::from("read"), String::from("write")] + ); + assert_eq!( + projected(ToolMode::Codemode, &["read", "write"]).0, + vec![String::from("read"), String::from("write")] + ); + assert!( + projected(ToolMode::Codemode, &["read", "write"]) + .1 + .is_empty() + ); + } + #[test] fn an_excluded_tool_is_absent_from_the_all_tools_mount() { let registry = registry(None, vec!["codemode".into()]); diff --git a/crates/dim-agent-runtime/src/config.rs b/crates/dim-agent-runtime/src/config.rs index 1647f1790f..76f68766ae 100644 --- a/crates/dim-agent-runtime/src/config.rs +++ b/crates/dim-agent-runtime/src/config.rs @@ -1,5 +1,5 @@ -pub use dim_agent_types::ModelId; use dim_agent_types::ModelSelection; +pub use dim_agent_types::{ModelId, ToolMode}; use rutis::service; use serde::{Deserialize, Serialize}; use std::sync::{ @@ -75,6 +75,14 @@ pub struct SessionConfig { /// member in place while the Session runs; a fork copies it. #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option, + /// The tool surface the Session runs ([agent tool modes] §2). `normal` is + /// omitted, so a record written before this field reads as `normal`; the + /// native store updates it in place while the Session runs, and a fork + /// copies it. + /// + /// [agent tool modes]: ../../../docs/design/agent-tool-modes.md + #[serde(default, skip_serializing_if = "ToolMode::is_normal")] + pub tool_mode: ToolMode, /// The title the creating caller already knew for the Session, fixed at /// creation. Only `sessions.launch` sets it (#1421); SessionTitle applies /// its text rules and writes it as the first manual title. It stays in the @@ -197,6 +205,7 @@ impl Default for SessionConfig { fn default() -> Self { let model = AgentConfig::default().model; Self { + tool_mode: ToolMode::Normal, permission_policy: crate::PermissionPolicy::default(), cwd: ".".into(), model: ModelSelection { diff --git a/crates/dim-agent-types/src/lib.rs b/crates/dim-agent-types/src/lib.rs index 2f90a4d482..23d9d35bb2 100644 --- a/crates/dim-agent-types/src/lib.rs +++ b/crates/dim-agent-types/src/lib.rs @@ -16,6 +16,7 @@ mod prompt; mod question; pub mod skill_token; mod tool; +mod tool_mode; pub mod v1; pub use activity::*; @@ -31,6 +32,7 @@ pub use profile::*; pub use prompt::*; pub use question::*; pub use tool::*; +pub use tool_mode::*; /// Open JSON object fields at external extension boundaries. pub type JsonObject = serde_json::Map; diff --git a/crates/dim-agent-types/src/tool_mode.rs b/crates/dim-agent-types/src/tool_mode.rs new file mode 100644 index 0000000000..07a928a2f7 --- /dev/null +++ b/crates/dim-agent-types/src/tool_mode.rs @@ -0,0 +1,45 @@ +use serde::{Deserialize, Serialize}; + +/// The working style a Session runs: which tool surface the model sees. The +/// mode is Session configuration and does not change what the Session mounts; +/// see `docs/design/agent-tool-modes.md`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ToolMode { + /// One tool call per decision: every mounted tool except the two entry + /// tools is declared. + #[default] + Normal, + /// One program per step: only `codemode` and `skill` are declared, and a + /// program may call every mounted tool except `codemode`. + Codemode, + /// One persistent shell: only `execute`, `ask_user` and `recall` are + /// declared. + Shell, +} + +impl ToolMode { + /// Whether this is `normal`, the only mode a stored record omits. + pub fn is_normal(&self) -> bool { + matches!(self, Self::Normal) + } + + /// The mode's stable wire name. + pub fn as_str(self) -> &'static str { + match self { + Self::Normal => "normal", + Self::Codemode => "codemode", + Self::Shell => "shell", + } + } + + /// The tool this mode is entered through, if any. A mode whose entry tool + /// is not mounted runs `normal`. + pub fn entry_tool(self) -> Option<&'static str> { + match self { + Self::Normal => None, + Self::Codemode => Some("codemode"), + Self::Shell => Some("execute"), + } + } +} From d187447424ec54e11378ccf5f6cf5fff3cc888a9 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:44:54 +0800 Subject: [PATCH 02/50] feat: expose session.tool_mode and session.create.toolMode session.create accepts toolMode, session.tool_mode.get reports the chosen and effective modes, and session.tool_mode.update writes the record and replaces the live value. The native store keeps the field out of normal records, and hello advertises the create field and the method pair. Refs #2135 --- crates/dim-app-server/src/agents.rs | 13 ++ crates/dim-app-server/src/connection.rs | 3 + crates/dim-app-server/src/lib.rs | 1 + crates/dim-app-server/src/protocol.rs | 5 + .../dim-app-server/src/session_tool_mode.rs | 118 +++++++++++ crates/dim-app-server/src/storage/face.rs | 7 + crates/dim-app-server/src/storage/timeline.rs | 30 +++ crates/dim-app-server/src/transport.rs | 2 + .../dim-app-server/tests/app_server_flow.rs | 1 + .../tests/session_tool_mode_flow.rs | 194 ++++++++++++++++++ 10 files changed, 374 insertions(+) create mode 100644 crates/dim-app-server/src/session_tool_mode.rs create mode 100644 crates/dim-app-server/tests/session_tool_mode_flow.rs diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index ded1b0849b..1db3dfd850 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -2387,6 +2387,19 @@ impl DynPlugin for AgentsPlugin { )) }, )?; + parts.register( + ctx, + dim_agent_runtime::PartScope::Session, + "SessionToolMode", + move |mount| { + Ok(Some( + Box::new(crate::session_tool_mode::SessionToolModePlugin::new( + mount.names, + with_store, + )?) as Box, + )) + }, + )?; let mut builder = self.builder.clone(); let (records, session_store, session_metadata) = match stored { Some((store, native, storage, metadata)) => { diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index cccd28dcc7..ad7ef2a1d2 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -2041,6 +2041,9 @@ impl Connection { if let Some(language) = params.language { config.language = Some(language); } + if let Some(mode) = params.tool_mode { + config.tool_mode = mode; + } let origin = match params.origin { None | Some(SessionOrigin::Client) => SessionOrigin::Client, Some(SessionOrigin::Acp) => SessionOrigin::Acp, diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 6ca05644eb..325ec674b4 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -31,6 +31,7 @@ pub mod provider_settings; pub mod runtime_manager; pub mod session_grants; pub mod session_language; +mod session_tool_mode; pub mod session_typescript; pub mod settings; pub mod settings_methods; diff --git a/crates/dim-app-server/src/protocol.rs b/crates/dim-app-server/src/protocol.rs index b37e7d5166..d8dbe31dc4 100644 --- a/crates/dim-app-server/src/protocol.rs +++ b/crates/dim-app-server/src/protocol.rs @@ -569,6 +569,11 @@ pub struct Create { /// daemons reject unknown fields. #[serde(default, deserialize_with = "optional_non_null")] pub language: Option, + /// The tool surface this Session runs (agent tool modes §5). Absent keeps + /// `normal`; clients send it only when `hello.features` names + /// `session.create.toolMode`, because older daemons reject unknown fields. + #[serde(default, deserialize_with = "optional_non_null")] + pub tool_mode: Option, /// The managed worktree to create with the Session; absent keeps `cwd`. #[serde(default, deserialize_with = "optional_worktree")] pub worktree: Option, diff --git a/crates/dim-app-server/src/session_tool_mode.rs b/crates/dim-app-server/src/session_tool_mode.rs new file mode 100644 index 0000000000..8f90e3a603 --- /dev/null +++ b/crates/dim-app-server/src/session_tool_mode.rs @@ -0,0 +1,118 @@ +//! Session part: `session.tool_mode.get` and `session.tool_mode.update` +//! (agent tool modes §5). The live value belongs to ToolRegistry; the durable +//! copy is the Session's config record. An update writes the record, then +//! replaces the live value. +use crate::storage::Store; +use dim_agent_capabilities::{ + methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params}, + tool_registry::ToolRegistry, +}; +use dim_agent_runtime::{Names, ToolMode}; +use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; +use rutis::{Ctx, Error}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::Arc; + +pub(crate) const NAMESPACE: &str = "session.tool_mode"; +const FAILED: &str = "tool_mode_failed"; + +/// The Session's two tool-mode methods; one per Session instance. +pub(crate) struct SessionToolModePlugin { + tools: Key, + methods: Key, + /// Native storage, when the assembly has it: the record carries the value. + store: Option>, +} +impl SessionToolModePlugin { + pub(crate) fn new(names: &Names<'_>, stored: bool) -> Result { + Ok(Self { + tools: names.key()?, + methods: names.key()?, + store: stored.then(|| names.key()).transpose()?, + }) + } +} +impl DynPlugin for SessionToolModePlugin { + fn name(&self) -> &str { + "SessionToolMode" + } + fn injects(&self) -> Vec { + let mut injects = vec![self.tools.erase(), self.methods.erase()]; + if let Some(store) = &self.store { + injects.push(store.erase()); + } + injects + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { + Box::pin(async move { + let tools = ctx.require_at(&self.tools)?; + let methods = ctx.require_at(&self.methods)?; + let store = match &self.store { + Some(key) => Some(ctx.require_at(key)?), + None => None, + }; + methods.register( + ctx, + NAMESPACE, + vec![ + MethodDecl::new("session.tool_mode.get", false, Interruption::Report), + MethodDecl::new("session.tool_mode.update", true, Interruption::Report), + ], + Arc::new(move |call, _cancel, _| { + let tools = tools.clone(); + let store = store.clone(); + let MethodCall { method, params, .. } = call; + Box::pin(async move { + match method.as_str() { + "session.tool_mode.get" => Ok(value(&tools)), + _ => change(&tools, store.as_deref(), params).await, + } + }) + }), + )?; + Ok(Effect::Done) + }) + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ModeValue { + mode: ToolMode, + effective: ToolMode, +} + +fn value(tools: &ToolRegistry) -> Value { + serde_json::to_value(ModeValue { + mode: tools.tool_mode(), + effective: tools.effective_tool_mode(), + }) + .expect("the tool mode reply is valid JSON") +} + +/// `session.tool_mode.update`: writes the record, then replaces the live +/// value. A failure or a cancellation before the write leaves both unchanged; +/// once the record is written the new value stays stored, and the live value +/// follows it. +async fn change( + tools: &ToolRegistry, + store: Option<&Store>, + input: Value, +) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Params { + session_id: String, + mode: ToolMode, + } + let Params { session_id, mode } = params(input)?; + if let Some(store) = store { + store + .set_session_tool_mode(&session_id, mode) + .await + .map_err(|error| RpcError::app(-32000, FAILED, error.to_string()))?; + } + tools.set_tool_mode(mode); + Ok(value(tools)) +} diff --git a/crates/dim-app-server/src/storage/face.rs b/crates/dim-app-server/src/storage/face.rs index 729b3a5a7b..f6e0d319ef 100644 --- a/crates/dim-app-server/src/storage/face.rs +++ b/crates/dim-app-server/src/storage/face.rs @@ -70,6 +70,13 @@ impl Store { ) -> impl Future> { self.0.set_session_language(session_id, language) } + pub fn set_session_tool_mode( + &self, + session_id: &str, + mode: dim_agent_runtime::ToolMode, + ) -> impl Future> { + self.0.set_session_tool_mode(session_id, mode) + } pub fn creation_record( &self, session_id: &str, diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 33028aea7a..4e4b4229b4 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -1463,6 +1463,36 @@ impl SessionStore { /// Writes the Session's reply language into its config record as one JSON /// member; the rest of the record is unchanged. A missing Session is /// `Closed`. + pub async fn set_session_tool_mode( + &self, + session_id: &str, + mode: dim_agent_runtime::ToolMode, + ) -> Result<()> { + let session = session_id.to_owned(); + self.timeline + .db + .run(move |connection| { + let changed = if mode.is_normal() { + connection.execute( + "UPDATE agent_sessions SET config = json_remove(config, '$.toolMode') \ + WHERE session_id = ?1", + params![&session], + ) + } else { + connection.execute( + "UPDATE agent_sessions SET config = json_set(config, '$.toolMode', ?2) \ + WHERE session_id = ?1", + params![&session, mode.as_str()], + ) + } + .map_err(error)?; + if changed != 1 { + return Err(AgentError::Closed(session)); + } + Ok(()) + }) + .await + } pub async fn set_session_language( &self, session_id: &str, diff --git a/crates/dim-app-server/src/transport.rs b/crates/dim-app-server/src/transport.rs index 90d41a3f4f..289c0f8739 100644 --- a/crates/dim-app-server/src/transport.rs +++ b/crates/dim-app-server/src/transport.rs @@ -823,6 +823,8 @@ async fn run_connection( "session.branch_set_default", "session.create.origin", "session.language", + "session.tool_mode", + "session.create.toolMode", "session.attach.expectedCwd", "session.attach.expectedConfig", ]); diff --git a/crates/dim-app-server/tests/app_server_flow.rs b/crates/dim-app-server/tests/app_server_flow.rs index 812c768a67..4bf2097aad 100644 --- a/crates/dim-app-server/tests/app_server_flow.rs +++ b/crates/dim-app-server/tests/app_server_flow.rs @@ -26,6 +26,7 @@ mod read_image_flow; mod session_files_flow; #[cfg(unix)] mod session_language_flow; +mod session_tool_mode_flow; mod settings_flow; #[path = "storage_flow.rs"] mod storage_flow; diff --git a/crates/dim-app-server/tests/session_tool_mode_flow.rs b/crates/dim-app-server/tests/session_tool_mode_flow.rs new file mode 100644 index 0000000000..4cf6730508 --- /dev/null +++ b/crates/dim-app-server/tests/session_tool_mode_flow.rs @@ -0,0 +1,194 @@ +//! Session tool mode (agent tool modes §5): `session.create.toolMode`, +//! `session.tool_mode.get` and `.update` over public RPC. The assembly mounts +//! neither entry tool, so a chosen `codemode` or `shell` reports `normal` as +//! the mode in force. +use dim_agent_aimux::{AimuxModels, config::ModelConfigFile}; +use dim_agent_capabilities::{adapters::MockTools, defaults}; +use dim_agent_runtime::{AgentBuilder, AgentConfig}; +use dim_app_server::{RunningServer, ServerConfig, serve}; +use serde_json::{Value, json}; +use std::{path::PathBuf, sync::Arc, time::Duration}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::UnixStream, +}; + +struct Home(PathBuf); +impl Home { + fn new() -> Self { + use std::os::unix::fs::PermissionsExt; + let directory = PathBuf::from("/tmp").join(format!("dim-mode-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(directory.join("work")).unwrap(); + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap(); + Self(directory.canonicalize().unwrap()) + } + fn work(&self) -> PathBuf { + self.0.join("work") + } + fn database(&self) -> PathBuf { + self.0.join("dimcode.sqlite") + } +} +impl Drop for Home { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn builder() -> AgentBuilder { + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::install(&mut builder); + defaults::mock_model_hosts(&mut builder); + defaults::tool_host(&mut builder, Arc::new(MockTools)); + builder +} + +async fn launch(home: &Home) -> RunningServer { + let models = AimuxModels::from_config( + serde_json::from_value::(json!({ + "defaultModel": {"providerId": "local", "modelId": "scripted"}, + "providers": [{"id": "local", "kind": "openai-compatible", "baseUrl": "http://127.0.0.1:1/v1", "models": [{"id": "scripted", "contextWindow": 128000, "maxOutputTokens": 4096, "config": {"maxTokens": 64}}]}] + })) + .unwrap(), + ) + .unwrap(); + let config = ServerConfig { + unix_path: Some(home.0.join("server.sock")), + websocket_address: None, + target_home: Some(home.0.clone()), + model_catalog: Some(Arc::new(models)), + ..Default::default() + }; + serve(builder(), config).await.unwrap() +} + +struct Client { + stream: BufReader, + id: u64, +} +impl Client { + async fn connect(server: &RunningServer) -> Self { + let stream = UnixStream::connect(server.unix_path.as_ref().unwrap()) + .await + .unwrap(); + let mut client = Self { + stream: BufReader::new(stream), + id: 0, + }; + client + .rpc( + "hello", + json!({"protocolVersion": 4, "clientKind": "other"}), + ) + .await; + client + } + async fn rpc(&mut self, method: &str, params: Value) -> Value { + self.id += 1; + let request = json!({"jsonrpc": "2.0", "id": self.id, "method": method, "params": params}); + self.stream + .get_mut() + .write_all(format!("{request}\n").as_bytes()) + .await + .unwrap(); + let stream = &mut self.stream; + tokio::time::timeout(Duration::from_secs(30), async move { + loop { + let mut line = String::new(); + assert_ne!(stream.read_line(&mut line).await.unwrap(), 0); + let value: Value = serde_json::from_str(&line).unwrap(); + if value["id"].as_u64() == Some(request["id"].as_u64().unwrap()) { + return value; + } + } + }) + .await + .expect("response deadline") + } + async fn create(&mut self, home: &Home, extra: Value) -> String { + let mut params = json!({"cwd": home.work(), "tools": []}); + for (key, value) in extra.as_object().unwrap() { + params[key] = value.clone(); + } + let created = self.rpc("session.create", params).await; + created["result"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("{created}")) + .to_owned() + } + async fn get(&mut self, session: &str) -> Value { + self.rpc("session.tool_mode.get", json!({"sessionId": session})) + .await + } + async fn update(&mut self, session: &str, mode: &str) -> Value { + self.rpc( + "session.tool_mode.update", + json!({"sessionId": session, "mode": mode}), + ) + .await + } +} + +fn stored_config(home: &Home, session: &str) -> String { + let connection = rusqlite::Connection::open(home.database()).unwrap(); + connection + .query_row( + "SELECT config FROM agent_sessions WHERE session_id = ?1", + [session], + |row| row.get(0), + ) + .unwrap() +} + +#[tokio::test] +async fn a_new_session_starts_normal_and_falls_back_when_the_entry_tool_is_absent() { + let home = Home::new(); + let server = launch(&home).await; + let mut client = Client::connect(&server).await; + let session = client.create(&home, json!({})).await; + + let read = client.get(&session).await; + assert_eq!(read["result"]["mode"], "normal", "{read}"); + assert_eq!(read["result"]["effective"], "normal", "{read}"); + + let updated = client.update(&session, "shell").await; + assert_eq!(updated["result"]["mode"], "shell", "{updated}"); + assert_eq!( + updated["result"]["effective"], "normal", + "the assembly mounts no execute, so shell is not in force: {updated}" + ); + let read = client.get(&session).await; + assert_eq!(read["result"]["mode"], "shell", "{read}"); + assert_eq!(read["result"]["effective"], "normal", "{read}"); + assert!( + stored_config(&home, &session).contains("\"toolMode\":\"shell\""), + "the record carries the choice" + ); + + let updated = client.update(&session, "normal").await; + assert_eq!(updated["result"]["mode"], "normal", "{updated}"); + assert_eq!(updated["result"]["effective"], "normal", "{updated}"); + assert!( + !stored_config(&home, &session).contains("toolMode"), + "normal is omitted from the record" + ); +} + +#[tokio::test] +async fn create_records_the_operators_choice() { + let home = Home::new(); + let server = launch(&home).await; + let mut client = Client::connect(&server).await; + let session = client.create(&home, json!({"toolMode": "codemode"})).await; + + let read = client.get(&session).await; + assert_eq!(read["result"]["mode"], "codemode", "{read}"); + assert_eq!( + read["result"]["effective"], "normal", + "the assembly mounts no codemode, so the chosen mode is not in force: {read}" + ); + assert!( + stored_config(&home, &session).contains("\"toolMode\":\"codemode\""), + "the record carries the creation choice" + ); +} From e2607a2a4ff3def88dbfd610aaf6861daff0c88d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:44:54 +0800 Subject: [PATCH 03/50] docs: carry toolMode in the Session and registry contracts Refs #2135 --- .../rust-agent/plugins/ToolRegistry.md | 19 ++++++++++++++++++- docs/design/contracts/session-access.md | 3 +++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/architecture/rust-agent/plugins/ToolRegistry.md b/docs/architecture/rust-agent/plugins/ToolRegistry.md index d2f668efbf..a515b9e1e2 100644 --- a/docs/architecture/rust-agent/plugins/ToolRegistry.md +++ b/docs/architecture/rust-agent/plugins/ToolRegistry.md @@ -26,10 +26,27 @@ with the flow test that asserts it. | Service | Purpose | | --- | --- | | `S:ToolHost` | Host definitions and execution handlers. | -| `S:SessionConfig` | The mount list (`tools`): which host and registered tools are declared, and in which order. | +| `S:SessionConfig` | The mount list (`tools`): which host and registered tools are declared, and in which order; the Session's `tool_mode`, the chosen working style. | | `S:SessionIdentity` | Supply the owning Session id in a foreign tool's neutral call and the `tool.attach` span. | | `S:SessionLifecycle` | `activated()` starts the background refresh task once the Session is published; `closing()` ends it. | +## Tool modes + +The registry holds the Session's chosen `ToolMode` (initialised from +`SessionConfig.tool_mode`) and projects its callable set under the mode in +force ([agent tool modes](../../../design/agent-tool-modes.md)): + +| Mode | Visible (a request's declarations) | Delegated (a Code Mode child) | +| --- | --- | --- | +| `normal` | every mounted tool except `codemode` and `execute` | none | +| `codemode` | `codemode` and `skill` | every mounted tool except `codemode` | +| `shell` | `execute`, `ask_user` and `recall` | none | + +`effective_tool_mode` falls back to `normal` when the mode's entry tool is not +mounted. `session.tool_mode.update` replaces the live mode through +`set_tool_mode`; the next input application pins it, and neither the projection +nor the update re-adopts the callable set. + ## Handler contract A handler is `ToolHandler`. Besides `execute`, it answers three optional diff --git a/docs/design/contracts/session-access.md b/docs/design/contracts/session-access.md index 5508f15a78..6db6a76799 100644 --- a/docs/design/contracts/session-access.md +++ b/docs/design/contracts/session-access.md @@ -313,6 +313,7 @@ Implemented: every method above, served by Agents' directory part (S2, [#98](htt // SessionConfig (new field; existing: permissionPolicy, cwd, model, systemPrompt, tools?, collaborationRole) { "interactive": true } // false: exec, automation; absent: true { "language": "zh-CN" } // absent: no selection, the base rule stands +{ "toolMode": "shell" } // absent: normal ``` `interactive` means the Session has an interaction counterpart that can answer its questions and approvals: the user through a client, or another Session's or branch's agent (for example a Collaboration leader). It does not require a human. An ACP Session is interactive: the editor answers its approvals. `interactive` is fixed at creation. Assembly never reads it (ADR 002 D3, #30), so the tool set stays the same and a fork keeps the prompt prefix and its KV cache. Plugins that care read it from the Session's config directly: Questions (`ask_user` stays declared and answers that no one is available to answer) and SessionTitle (titles interactive leader Sessions only). @@ -334,6 +335,8 @@ Implemented (C2): `session.create` sets the field, and the native store writes i An update writes the record, replaces the live value and then has Prompt adopt the source. A failure before the record is written leaves the value unchanged. A failure after it, or an `interrupted` reply, leaves the new value stored, and each branch's periodic check delivers it to that branch; a client that receives an error reads the value back with `session.language.get`. +`toolMode` is the Session's working style: `normal`, `codemode` or `shell`, the modes [agent tool modes §2](../agent-tool-modes.md#2-product-behavior) defines. `session.create` accepts `toolMode?`; clients send it only when `hello.features` names `session.create.toolMode`, because older daemons reject unknown fields. `session.tool_mode.get` reports `{mode, effective}` and `session.tool_mode.update {mode}` changes it. The native store omits `normal`, so a record without the member reads as `normal`; a fork copies it. The update writes the record and then replaces ToolRegistry's live value; a failure before the record leaves both unchanged, and after it the new value stays stored and live. The mode's effect on a turn, Goal and admission is the mode design's (§2, §5); this contract only carries the field and the methods. + `tools` is the Session's optional mount list, fixed at creation. `session.create {tools?}` sets it; without the parameter the Session takes its Agent profile's optional `tools`, and a profile without one gives none (the product default). A profile's or member's list limits what that agent sees; a Collaboration member with a list always mounts `agent`. Without a mount list the Session declares every host tool, in the host's order, and every tool a part registers with `toolRegistry`, by name. With one it declares exactly the host and registered tools the list names, in its order; `[]` declares none of them. Other sources' tools (MCP) follow in both cases and are governed by their own configuration. A named tool that nothing has registered is not declared and is reported once; it is declared once something registers it. Duplicate names fail Session creation. Permission decides whether a declared tool's call runs and never changes the declarations ([session-boundary A.5](session-boundary.md#a5-tool-contribution)). The native store writes `tools` only when the Session has a mount list. Not in this contract: `createdBy` (the Session's origin) and the `client` parameter of `session.create` are added when something decides with them. The resource node is a P3 addition (overview §6.3): an additive optional `SessionConfig` field, where a missing value means the control node. From 515259bf34dc5f206fa188cda6e652cd4aeb8afe Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 23:57:39 +0800 Subject: [PATCH 04/50] fix: do not advertise the mode before the surface follows A client that sends toolMode now stores and reads it, but the request still declares every tool. Advertise the control when the projection reaches the request in the next slice. Refs #2135 --- crates/dim-app-server/src/transport.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/dim-app-server/src/transport.rs b/crates/dim-app-server/src/transport.rs index 289c0f8739..90d41a3f4f 100644 --- a/crates/dim-app-server/src/transport.rs +++ b/crates/dim-app-server/src/transport.rs @@ -823,8 +823,6 @@ async fn run_connection( "session.branch_set_default", "session.create.origin", "session.language", - "session.tool_mode", - "session.create.toolMode", "session.attach.expectedCwd", "session.attach.expectedConfig", ]); From 5c196ee032ee85ef934d103e9e1c60c19704ee94 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 00:43:02 +0800 Subject: [PATCH 05/50] feat: project the request surface and admit by origin The InputQueue records the effective tool mode when it applies an input, the turn keeps that pin through compaction and rebuild, and the request declares only the pinned mode's visible set. ToolBinding binds the visible and delegated handlers, checks the caller's set before claim, and the executor exposes only the delegated set to a Code Mode program. Refs #2135 --- .../dim-agent-capabilities/src/agent_loop.rs | 48 +++++++++-- .../src/context_usage.rs | 3 +- .../dim-agent-capabilities/src/input_queue.rs | 21 ++++- .../src/input_queue/recovery.rs | 3 +- .../src/tool_binding.rs | 79 ++++++++++++++++--- .../src/tool_executor.rs | 9 ++- .../src/tool_registry.rs | 42 +++++++--- crates/dim-agent-types/src/events.rs | 9 +++ 8 files changed, 176 insertions(+), 38 deletions(-) diff --git a/crates/dim-agent-capabilities/src/agent_loop.rs b/crates/dim-agent-capabilities/src/agent_loop.rs index d712b50c08..6b33fd6c52 100644 --- a/crates/dim-agent-capabilities/src/agent_loop.rs +++ b/crates/dim-agent-capabilities/src/agent_loop.rs @@ -74,6 +74,9 @@ struct Turn { /// the step deferred still spends one retry budget with the request that /// failed. deferred: Option, + /// The tool mode recorded when the turn's driving input was applied; every + /// request of the turn projects its declarations under it. + tool_mode: ToolMode, } /// An applied input waiting for this Loop to consume it. struct Applied { @@ -81,6 +84,7 @@ struct Applied { /// Sequence of its `input/applied`. sequence: u64, mode: InputMode, + tool_mode: ToolMode, } impl Applied { fn new(event: &AgentEvent, data: &InputAppliedData) -> Self { @@ -88,6 +92,7 @@ impl Applied { id: data.input_id.clone(), sequence: event.sequence, mode: data.mode.unwrap_or_default(), + tool_mode: data.tool_mode.unwrap_or_default(), } } } @@ -232,6 +237,14 @@ impl AgentLoop { return Ok(()); } let id = uuid::Uuid::new_v4().to_string(); + let tool_mode = self + .pending + .lock() + .unwrap() + .iter() + .find(|input| input.mode != InputMode::Append) + .map(|input| input.tool_mode) + .unwrap_or_default(); *slot = Some(Turn { id: id.clone(), open: false, @@ -241,6 +254,7 @@ impl AgentLoop { failed: None, continued: false, deferred: None, + tool_mode, }); self.timeline .append(EventKind::TurnStart(TurnStartData { turn_id: id }).into())?; @@ -657,6 +671,7 @@ impl AgentLoop { fields: vec![ "data.input_id".into(), "data.mode".into(), + "data.tool_mode".into(), "position.sequence".into(), ], }; @@ -676,11 +691,12 @@ impl AgentLoop { value: serde_json::Value::String(id), }, mode, + tool_mode, QueryValue::Value { value: serde_json::Value::Number(sequence), }, ], - ) = <[_; 3]>::try_from(row.values) + ) = <[_; 4]>::try_from(row.values) else { return Err(AgentError::fault( "Loop", @@ -693,9 +709,21 @@ impl AgentLoop { .map_err(|error| AgentError::fault("Loop", error.to_string()))?, QueryValue::Elements { .. } => unreachable!("an applied input mode is scalar"), }; + let tool_mode = match tool_mode { + QueryValue::Missing => ToolMode::default(), + QueryValue::Value { value } => { + serde_json::from_value::>(value) + .map_err(|error| AgentError::fault("Loop", error.to_string()))? + .unwrap_or_default() + } + QueryValue::Elements { .. } => { + unreachable!("an applied input tool mode is scalar") + } + }; pending.push(Applied { id, mode, + tool_mode, sequence: sequence .as_u64() .expect("applied sequences are unsigned integers"), @@ -942,6 +970,7 @@ impl AgentLoop { failed: Some(CAPABILITY_RELOADING.into()), continued: false, deferred: None, + tool_mode: ToolMode::default(), }); query.from = Some(TimelinePosition { branch_id: self.branch.clone(), @@ -1201,6 +1230,7 @@ impl AgentLoop { request_id: String, recovery: Option, chain: Option, + tool_mode: ToolMode, ) -> CancellationToken { let cancel = self.lifecycle.child_token(); let result_cancel = cancel.clone(); @@ -1236,13 +1266,18 @@ impl AgentLoop { Some(tools) => { owner .binding - .bind(&request_id, through, tools, &data.settings.tool_sources) - .map_err(AgentError::InvalidInput)?; - tools.clone() + .bind( + &request_id, + through, + tools, + &data.settings.tool_sources, + tool_mode, + ) + .map_err(AgentError::InvalidInput)? } None => owner .binding - .bind_current(&request_id, None) + .bind_current(&request_id, tool_mode, None) .map_err(AgentError::InvalidInput)?, }), system: data.system.clone(), @@ -1255,7 +1290,7 @@ impl AgentLoop { None => { let mut settings = owner .binding - .prepare(&request_id, |tools| { + .prepare(&request_id, tool_mode, |tools| { owner .prepare .0 @@ -1606,6 +1641,7 @@ impl AgentLoop { request.id.clone(), request.source.clone(), request.chain.clone(), + turn.tool_mode, )); } EventKind::ToolUseStart(data) if request.stage == Stage::Model => { diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index 9e460067d4..f55335b56e 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -1079,7 +1079,8 @@ impl ContextUsage { { return Ok(cached.clone()); } - let (tools, sources) = self.registry.snapshot(); + let tools = self.registry.visible_definitions(); + let (_, sources) = self.registry.snapshot(); let versions = fingerprint( &sources .iter() diff --git a/crates/dim-agent-capabilities/src/input_queue.rs b/crates/dim-agent-capabilities/src/input_queue.rs index 4a411301f9..e05a689f0c 100644 --- a/crates/dim-agent-capabilities/src/input_queue.rs +++ b/crates/dim-agent-capabilities/src/input_queue.rs @@ -6,6 +6,7 @@ use crate::{ host::HostFuture, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, timeline_tree::TreeCommands, + tool_registry::ToolRegistry, }; use dim_agent_runtime::{ AgentError, Dispatcher, InputSnapshot, Names, Registrations, Result, StateCell, Timeline, @@ -23,7 +24,7 @@ use tokio_util::sync::CancellationToken; /// What InputQueue writes for an input it decided on. #[derive(Debug, Clone)] enum Decision { - Apply(String, InputMode), + Apply(String, InputMode, ToolMode), Delete(String, Option), } /// InputQueue's answer to one `input/withdraw`. @@ -191,7 +192,7 @@ impl QueueState { if self.turn.is_none() && mode != InputMode::Append { self.starting = true; } - vec![Decision::Apply(entry.id.clone(), mode)] + vec![Decision::Apply(entry.id.clone(), mode, ToolMode::Normal)] } } /// Consumes `input/message` and decides by its mode when Loop may consume @@ -216,6 +217,9 @@ pub struct InputQueue { answered: tokio::sync::Notify, /// Ends waits when this generation unloads. lifecycle: CancellationToken, + /// The Session's tools: the effective mode is recorded when an input is + /// applied, so its turn keeps that mode. + tools: Arc, } struct WithdrawalWaiter<'a> { @@ -280,6 +284,14 @@ impl InputQueue { } let mut state = self.state.lock().unwrap(); let decisions = state.step(&event); + let mode = self.tools.effective_tool_mode(); + let decisions = decisions + .into_iter() + .map(|decision| match decision { + Decision::Apply(id, queue_mode, _) => Decision::Apply(id, queue_mode, mode), + other => other, + }) + .collect(); let (published, answer) = self.write(decisions, event.sequence)?; self.publish(published, state.queued); if matches!(event.kind, EventKind::InputWithdraw(_)) { @@ -368,6 +380,7 @@ pub struct InputQueuePlugin { dispatcher: Key, tree: Key, identity: Key, + tools: Key, } impl InputQueuePlugin { pub fn new(names: &Names<'_>) -> std::result::Result { @@ -378,6 +391,7 @@ impl InputQueuePlugin { dispatcher: names.key()?, tree: names.key()?, identity: names.key()?, + tools: names.key()?, }) } } @@ -391,6 +405,7 @@ impl DynPlugin for InputQueuePlugin { self.dispatcher.erase(), self.tree.erase(), self.identity.erase(), + self.tools.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -399,6 +414,7 @@ impl DynPlugin for InputQueuePlugin { let dispatcher = ctx.require_at(&self.dispatcher)?; let tree = ctx.require_at(&self.tree)?; let identity = ctx.require_at(&self.identity)?; + let tools = ctx.require_at(&self.tools)?; let queue = Arc::new(InputQueue { state: Mutex::new(QueueState::default()), observable: Arc::new(StateCell::new(InputSnapshot::default())), @@ -409,6 +425,7 @@ impl DynPlugin for InputQueuePlugin { answers: Mutex::new(HashMap::new()), answered: tokio::sync::Notify::new(), lifecycle: ctx.cancellation_token(), + tools, }); let owner = queue.clone(); let read = queue.clone(); diff --git a/crates/dim-agent-capabilities/src/input_queue/recovery.rs b/crates/dim-agent-capabilities/src/input_queue/recovery.rs index 5eb945b71b..2fae5198e5 100644 --- a/crates/dim-agent-capabilities/src/input_queue/recovery.rs +++ b/crates/dim-agent-capabilities/src/input_queue/recovery.rs @@ -64,11 +64,12 @@ impl InputQueue { let mut drafts = Vec::new(); for decision in decisions { match decision { - Decision::Apply(input_id, mode) => { + Decision::Apply(input_id, mode, tool_mode) => { drafts.push( EventKind::InputApplied(InputAppliedData { input_id, mode: Some(mode), + tool_mode: Some(tool_mode), }) .into(), ); diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 99f7e2777e..06f26b5089 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -10,7 +10,7 @@ use crate::{ context_preparation::ToolSetAdoption, host::{ModelSettings, ToolExecutionContext}, prompt::{Prompt, ToolAdoptOutcome}, - tool_registry::{ToolClaim, ToolContribution, ToolRegistry, ToolSourceSet}, + tool_registry::{ToolClaim, ToolContribution, ToolRegistry, ToolSourceSet, project}, }; use dim_agent_runtime::{ AgentError, BranchLifecycle, Dispatcher, Names, QueryFilter, QueryOperand, QueryOutput, @@ -22,7 +22,7 @@ use futures_util::FutureExt; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis::{Ctx, Error}; use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, panic::AssertUnwindSafe, sync::{Arc, Mutex}, }; @@ -30,6 +30,10 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker}; struct Snapshot { tools: HashMap>, + /// The request's declarations: top-level calls may name only these. + visible: HashSet, + /// The names a Code Mode child may call; empty outside `codemode`. + delegated: HashSet, /// Keeps the versions this request declared alive until it is released. _sets: Vec>, /// What the request's handlers claimed before their batch was published, @@ -82,7 +86,8 @@ impl ToolBinding { through: u64, tools: &[ToolDefinition], tool_sources: &[ToolSourceVersion], - ) -> Result<(), String> { + mode: ToolMode, + ) -> Result, String> { let sets = tool_sources .iter() .map(|source| { @@ -96,8 +101,9 @@ impl ToolBinding { }) }) .collect::, _>>()?; + let (visible, delegated) = project(mode, tools); let mut bound = HashMap::new(); - for tool in tools { + for tool in visible.iter().chain(delegated.iter()) { let handler = sets .iter() .flat_map(|set| set.tools.iter()) @@ -108,7 +114,7 @@ impl ToolBinding { bound.insert(tool.name.clone(), handler); } let mut state = self.state.lock().unwrap(); - register(&mut state, request_id, bound, sets)?; + register(&mut state, request_id, bound, sets, &visible, &delegated)?; if let Some(newest) = state .pins .iter() @@ -118,7 +124,7 @@ impl ToolBinding { { state.pins.retain(|(sequence, _)| *sequence >= newest); } - Ok(()) + Ok(visible) } /// Binds a request whose configuration declares no tool part: declares @@ -127,25 +133,28 @@ impl ToolBinding { pub fn bind_current( &self, request_id: &str, + mode: ToolMode, declared: Option<&[ToolDefinition]>, ) -> Result, String> { let (definitions, sets) = self.registry.snapshot(); let tools = declared.unwrap_or(&definitions); - self.bind_snapshot(request_id, tools, sets)?; - Ok(tools.to_vec()) + self.bind_snapshot(request_id, tools, sets, mode) } pub(crate) fn prepare( &self, request_id: &str, + mode: ToolMode, prepare: impl FnOnce(&[ToolDefinition]) -> dim_agent_runtime::Result, ) -> dim_agent_runtime::Result { let (definitions, sets) = self.registry.snapshot(); - let settings = prepare(&definitions)?; + let visible = project(mode, &definitions).0; + let settings = prepare(&visible)?; self.bind_snapshot( request_id, settings.tools.as_deref().unwrap_or_default(), sets, + mode, ) .map_err(AgentError::InvalidInput)?; Ok(settings) @@ -156,9 +165,11 @@ impl ToolBinding { request_id: &str, tools: &[ToolDefinition], sets: Vec>, - ) -> Result<(), String> { + mode: ToolMode, + ) -> Result, String> { + let (visible, delegated) = project(mode, tools); let mut bound = HashMap::new(); - for tool in tools { + for tool in visible.iter().chain(delegated.iter()) { let handler = self .registry .fixed(&tool.name) @@ -172,7 +183,9 @@ impl ToolBinding { .ok_or_else(|| format!("tool {} has no handler", tool.name))?; bound.insert(tool.name.clone(), handler); } - register(&mut self.state.lock().unwrap(), request_id, bound, sets) + let mut state = self.state.lock().unwrap(); + register(&mut state, request_id, bound, sets, &visible, &delegated)?; + Ok(visible) } /// The tool a call of `request_id` runs: its definition (for admission) @@ -190,9 +203,24 @@ impl ToolBinding { .ok_or_else(|| format!("Unknown tool: {name}")) } - /// Every declaration the request pinned, sorted by name, from the + /// Every visible declaration the request pinned, sorted by name, from the /// request's snapshot only. pub fn definitions(&self, request_id: &str) -> Result, String> { + self.definitions_where(request_id, |snapshot, name| snapshot.visible.contains(name)) + } + + /// Every delegated declaration the request pinned, sorted by name. + pub fn delegated_definitions(&self, request_id: &str) -> Result, String> { + self.definitions_where(request_id, |snapshot, name| { + snapshot.delegated.contains(name) + }) + } + + fn definitions_where( + &self, + request_id: &str, + include: impl Fn(&Snapshot, &str) -> bool, + ) -> Result, String> { let state = self.state.lock().unwrap(); let snapshot = state .snapshots @@ -201,12 +229,33 @@ impl ToolBinding { let mut definitions = snapshot .tools .values() + .filter(|tool| include(snapshot, &tool.definition.name)) .map(|tool| tool.definition.clone()) .collect::>(); definitions.sort_by(|left, right| left.name.cmp(&right.name)); Ok(definitions) } + /// Whether a call may name `name`: a top-level call only inside the + /// request's visible set, a Code Mode child only inside its delegated set. + pub fn admit(&self, request_id: &str, name: &str, child: bool) -> Result<(), String> { + let state = self.state.lock().unwrap(); + let snapshot = state + .snapshots + .get(request_id) + .ok_or_else(|| format!("request {request_id} has no active tool binding"))?; + let allowed = if child { + &snapshot.delegated + } else { + &snapshot.visible + }; + if allowed.contains(name) { + Ok(()) + } else { + Err(format!("Unknown tool: {name}")) + } + } + /// 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(); @@ -383,6 +432,8 @@ fn register( request_id: &str, tools: HashMap>, sets: Vec>, + visible: &[ToolDefinition], + delegated: &[ToolDefinition], ) -> Result<(), String> { if state.snapshots.contains_key(request_id) { return Err(format!("request {request_id} is already bound")); @@ -391,6 +442,8 @@ fn register( request_id.to_owned(), Snapshot { tools, + visible: visible.iter().map(|tool| tool.name.clone()).collect(), + delegated: delegated.iter().map(|tool| tool.name.clone()).collect(), _sets: sets, claims: HashMap::new(), }, diff --git a/crates/dim-agent-capabilities/src/tool_executor.rs b/crates/dim-agent-capabilities/src/tool_executor.rs index d01521cc85..53eaca6e28 100644 --- a/crates/dim-agent-capabilities/src/tool_executor.rs +++ b/crates/dim-agent-capabilities/src/tool_executor.rs @@ -203,10 +203,9 @@ 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. + /// The declarations the request delegated to a Code Mode program. pub fn definitions(&self, request_id: &str) -> Result, String> { - self.binding.definitions(request_id) + self.binding.delegated_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 @@ -691,6 +690,10 @@ async fn admit( context: &ToolExecutionContext, cancel: CancellationToken, ) -> Result { + let child = dim_agent_runtime::core::current_parent_call_id().is_some(); + binding + .admit(&context.request_id, &call.name, child) + .map_err(HostError::failed)?; let tool = match binding.handler(&context.request_id, &call.name) { Ok(tool) => tool, // An unknown tool is denied here, without an approval question. diff --git a/crates/dim-agent-capabilities/src/tool_registry.rs b/crates/dim-agent-capabilities/src/tool_registry.rs index 3d5f7ac6ab..d021148d47 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -431,22 +431,12 @@ impl ToolRegistry { /// by the effective mode. pub fn visible_definitions(&self) -> Vec { let declared = self.snapshot().0; - let mode = self.effective_of(&declared); - declared - .into_iter() - .filter(|tool| visible_under(mode, &tool.name)) - .collect() + project(self.tool_mode(), &declared).0 } /// The tool names a Code Mode program may call; empty in the other modes. pub fn delegated_definitions(&self) -> Vec { let declared = self.snapshot().0; - if self.effective_of(&declared) != ToolMode::Codemode { - return Vec::new(); - } - declared - .into_iter() - .filter(|tool| tool.name != "codemode") - .collect() + project(self.tool_mode(), &declared).1 } /// The current or a still-held replaced version of a key. pub fn source(&self, key: &str, version: &str) -> Option> { @@ -907,6 +897,34 @@ fn visible_under(mode: ToolMode, name: &str) -> bool { } } +/// Projects `declared` under `mode`: the request's `visible` declarations and +/// the child `delegated` set. A mode whose entry tool is not in `declared` +/// runs `normal`. +pub(crate) fn project( + mode: ToolMode, + declared: &[ToolDefinition], +) -> (Vec, Vec) { + let mode = match mode.entry_tool() { + Some(entry) if declared.iter().any(|tool| tool.name == entry) => mode, + _ => ToolMode::Normal, + }; + let visible = declared + .iter() + .filter(|tool| visible_under(mode, &tool.name)) + .cloned() + .collect(); + let delegated = if mode == ToolMode::Codemode { + declared + .iter() + .filter(|tool| tool.name != "codemode") + .cloned() + .collect() + } else { + Vec::new() + }; + (visible, delegated) +} + pub fn definition(name: &str, description: &str, schema: serde_json::Value) -> ToolDefinition { ToolDefinition { name: name.into(), diff --git a/crates/dim-agent-types/src/events.rs b/crates/dim-agent-types/src/events.rs index 2aaf70133d..a02b1eeff6 100644 --- a/crates/dim-agent-types/src/events.rs +++ b/crates/dim-agent-types/src/events.rs @@ -285,6 +285,15 @@ pub struct InputAppliedData { deserialize_with = "crate::optional_non_null" )] pub mode: Option, + /// The tool mode in force when the input was applied; the turn keeps it. + /// Absent in records written before the field and in samples against the + /// frozen contract, and reads as `normal`. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::optional_non_null" + )] + pub tool_mode: Option, } /// Loop took an applied input into the turn; history places the input here. From 4de3892fd48a46940c395738715365e63683e6cd Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 00:43:02 +0800 Subject: [PATCH 06/50] test: carry the applied tool mode and cover the mode surface Fixtures write the optional tool_mode field, the codemode flow selects codemode mode, and the session tool mode flow covers create, update, fallback and the codemode declaration. Refs #2135 --- .../tests/context_flow.rs | 2 + .../tests/recall_flow.rs | 1 + crates/dim-agent-types/examples/compat.rs | 1 + .../tests/session_tool_mode_flow.rs | 128 ++++++++++++++++-- crates/dim-app-server/tests/storage_flow.rs | 1 + .../tests/storage_flow/property_queries.rs | 1 + .../tests/storage_flow/queue_recovery.rs | 1 + .../tests/transport_flow/codemode.rs | 2 +- .../tests/transport_flow/fork.rs | 3 + crates/dim-migration/src/native.rs | 1 + tests/integration/tests/wait_protocol.rs | 2 + 11 files changed, 134 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/context_flow.rs b/crates/dim-agent-capabilities/tests/context_flow.rs index 87395924e4..d786a572fb 100644 --- a/crates/dim-agent-capabilities/tests/context_flow.rs +++ b/crates/dim-agent-capabilities/tests/context_flow.rs @@ -1451,6 +1451,7 @@ async fn restoring_each_preparation_handoff_settles_without_replaying_work() { EventKind::InputApplied(InputAppliedData { input_id: input.id.clone(), mode: Some(InputMode::Queue), + tool_mode: None, }) .into(), ) @@ -1830,6 +1831,7 @@ async fn restoring_pending_inputs_runs_each_queued_input_in_its_own_turn() { EventKind::InputApplied(InputAppliedData { input_id: first.id.clone(), mode: Some(InputMode::Queue), + tool_mode: None, }) .into(), ) diff --git a/crates/dim-agent-capabilities/tests/recall_flow.rs b/crates/dim-agent-capabilities/tests/recall_flow.rs index 4d71c2ef4b..7c6af84ccb 100644 --- a/crates/dim-agent-capabilities/tests/recall_flow.rs +++ b/crates/dim-agent-capabilities/tests/recall_flow.rs @@ -2700,6 +2700,7 @@ fn an_input_that_never_counted_and_thinking_are_not_told() { recorded.push(EventKind::InputApplied(InputAppliedData { input_id: pending.clone(), mode: Some(InputMode::Queue), + tool_mode: None, })); let taken = recorded.push(input_message("counted once")); recorded.push(turn_start("t1")); diff --git a/crates/dim-agent-types/examples/compat.rs b/crates/dim-agent-types/examples/compat.rs index 92ff504260..ffea695c81 100644 --- a/crates/dim-agent-types/examples/compat.rs +++ b/crates/dim-agent-types/examples/compat.rs @@ -85,6 +85,7 @@ fn native_events() -> Vec { EventKind::InputApplied(InputAppliedData { input_id: "rust-1".into(), mode: Some(InputMode::Queue), + tool_mode: None, }), EventKind::TurnStart(TurnStartData { turn_id: turn() }), EventKind::ModelStart(StepData { diff --git a/crates/dim-app-server/tests/session_tool_mode_flow.rs b/crates/dim-app-server/tests/session_tool_mode_flow.rs index 4cf6730508..df2d08dd21 100644 --- a/crates/dim-app-server/tests/session_tool_mode_flow.rs +++ b/crates/dim-app-server/tests/session_tool_mode_flow.rs @@ -4,7 +4,9 @@ //! the mode in force. use dim_agent_aimux::{AimuxModels, config::ModelConfigFile}; use dim_agent_capabilities::{adapters::MockTools, defaults}; -use dim_agent_runtime::{AgentBuilder, AgentConfig}; +use dim_agent_runtime::testing::chain_events; +use dim_agent_runtime::{AgentBuilder, AgentConfig, Session}; +use dim_agent_types::{EventKind, ModelRequest}; use dim_app_server::{RunningServer, ServerConfig, serve}; use serde_json::{Value, json}; use std::{path::PathBuf, sync::Arc, time::Duration}; @@ -35,15 +37,18 @@ impl Drop for Home { } } -fn builder() -> AgentBuilder { +fn builder(codemode: bool) -> AgentBuilder { let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::install(&mut builder); + if codemode { + dim_codemode::install(&mut builder); + } defaults::mock_model_hosts(&mut builder); defaults::tool_host(&mut builder, Arc::new(MockTools)); builder } -async fn launch(home: &Home) -> RunningServer { +async fn launch(home: &Home, codemode: bool) -> RunningServer { let models = AimuxModels::from_config( serde_json::from_value::(json!({ "defaultModel": {"providerId": "local", "modelId": "scripted"}, @@ -59,7 +64,7 @@ async fn launch(home: &Home) -> RunningServer { model_catalog: Some(Arc::new(models)), ..Default::default() }; - serve(builder(), config).await.unwrap() + serve(builder(codemode), config).await.unwrap() } struct Client { @@ -129,6 +134,23 @@ impl Client { } } +fn live_session(server: &RunningServer, id: &str) -> Session { + server.agent().unwrap().get_session(id).unwrap() +} + +async fn last_request(session: &Session) -> Arc { + chain_events(session, "main", ..) + .await + .unwrap() + .iter() + .filter_map(|event| match &event.kind { + EventKind::ModelCall(data) => Some(data.request.clone()), + _ => None, + }) + .next_back() + .expect("a model request") +} + fn stored_config(home: &Home, session: &str) -> String { let connection = rusqlite::Connection::open(home.database()).unwrap(); connection @@ -140,10 +162,10 @@ fn stored_config(home: &Home, session: &str) -> String { .unwrap() } -#[tokio::test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_new_session_starts_normal_and_falls_back_when_the_entry_tool_is_absent() { let home = Home::new(); - let server = launch(&home).await; + let server = launch(&home, false).await; let mut client = Client::connect(&server).await; let session = client.create(&home, json!({})).await; @@ -174,10 +196,10 @@ async fn a_new_session_starts_normal_and_falls_back_when_the_entry_tool_is_absen ); } -#[tokio::test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn create_records_the_operators_choice() { let home = Home::new(); - let server = launch(&home).await; + let server = launch(&home, false).await; let mut client = Client::connect(&server).await; let session = client.create(&home, json!({"toolMode": "codemode"})).await; @@ -192,3 +214,93 @@ async fn create_records_the_operators_choice() { "the record carries the creation choice" ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_chosen_mode_without_its_entry_tool_declares_the_normal_surface() { + let home = Home::new(); + let server = launch(&home, false).await; + let mut client = Client::connect(&server).await; + let created = client + .rpc( + "session.create", + json!({"cwd": home.work(), "toolMode": "codemode"}), + ) + .await; + let session = created["result"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("{created}")) + .to_owned(); + let submitted = client + .rpc( + "session.submit", + json!({"sessionId": session, "branchId": "main", "text": "hello"}), + ) + .await; + assert!(submitted.get("error").is_none(), "{submitted}"); + let idle = client + .rpc( + "session.idle", + json!({"sessionId": session, "branchId": "main"}), + ) + .await; + assert!(idle.get("error").is_none(), "{idle}"); + let request = last_request(&live_session(&server, &session)).await; + let names = request + .tools + .as_ref() + .expect("a normal request declares tools") + .iter() + .map(|tool| tool.name.clone()) + .collect::>(); + assert!( + !names.is_empty(), + "the normal surface is not empty: {names:?}" + ); + assert!( + !names.iter().any(|name| name == "codemode"), + "normal hides the entry tool: {names:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codemode_declares_only_its_entry_and_skill() { + let home = Home::new(); + let server = launch(&home, true).await; + let mut client = Client::connect(&server).await; + let created = client + .rpc( + "session.create", + json!({"cwd": home.work(), "toolMode": "codemode", "tools": ["codemode", "skill"]}), + ) + .await; + let session = created["result"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("{created}")) + .to_owned(); + let mode = client.get(&session).await; + assert_eq!(mode["result"]["effective"], "codemode", "{mode}"); + let submitted = client + .rpc( + "session.submit", + json!({"sessionId": session, "branchId": "main", "text": "hello"}), + ) + .await; + assert!(submitted.get("error").is_none(), "{submitted}"); + let idle = client + .rpc( + "session.idle", + json!({"sessionId": session, "branchId": "main"}), + ) + .await; + assert!(idle.get("error").is_none(), "{idle}"); + let request = last_request(&live_session(&server, &session)).await; + let mut names = request + .tools + .as_ref() + .expect("a codemode request declares tools") + .iter() + .map(|tool| tool.name.clone()) + .collect::>(); + names.sort(); + assert_eq!(names, ["codemode"], "{names:?}"); +} diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index e9689ef492..24bb3e249b 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -1985,6 +1985,7 @@ async fn conditional_steer_recovers_checked_candidates_once_and_preserves_old_in write(EventKind::InputApplied(InputAppliedData { input_id: driving.id.clone(), mode: Some(InputMode::Queue), + tool_mode: None, })); let checked = |text: &str| { let mut data = input(text, InputMode::Steer); diff --git a/crates/dim-app-server/tests/storage_flow/property_queries.rs b/crates/dim-app-server/tests/storage_flow/property_queries.rs index a4335efbe3..e5cca7a7e5 100644 --- a/crates/dim-app-server/tests/storage_flow/property_queries.rs +++ b/crates/dim-app-server/tests/storage_flow/property_queries.rs @@ -132,6 +132,7 @@ async fn indexed_input_controls_do_not_compare_every_selected_identity_against_e EventKind::InputApplied(InputAppliedData { input_id: id.clone(), mode: Some(InputMode::Append), + tool_mode: None, }), )); ids.push(json!(id)); diff --git a/crates/dim-app-server/tests/storage_flow/queue_recovery.rs b/crates/dim-app-server/tests/storage_flow/queue_recovery.rs index 010d5268a3..4db49aa0bd 100644 --- a/crates/dim-app-server/tests/storage_flow/queue_recovery.rs +++ b/crates/dim-app-server/tests/storage_flow/queue_recovery.rs @@ -200,6 +200,7 @@ async fn queue_resume_reuses_an_application_written_by_an_older_owner_after_a_sa EventKind::InputApplied(InputAppliedData { input_id: input_id.clone(), mode: Some(InputMode::Queue), + tool_mode: None, }), ), ], diff --git a/crates/dim-app-server/tests/transport_flow/codemode.rs b/crates/dim-app-server/tests/transport_flow/codemode.rs index 28e57c3471..64903db5c3 100644 --- a/crates/dim-app-server/tests/transport_flow/codemode.rs +++ b/crates/dim-app-server/tests/transport_flow/codemode.rs @@ -167,7 +167,7 @@ async fn a_product_style_app_server_runs_codemode_and_writes_child_facts() { let created = client .rpc( "session.create", - json!({"cwd":std::env::temp_dir(),"tools":["codemode","echo"]}), + json!({"cwd":std::env::temp_dir(),"tools":["codemode","echo"],"toolMode":"codemode"}), ) .await; assert_ok(&created); diff --git a/crates/dim-app-server/tests/transport_flow/fork.rs b/crates/dim-app-server/tests/transport_flow/fork.rs index 91384feeb6..ba3a9654e4 100644 --- a/crates/dim-app-server/tests/transport_flow/fork.rs +++ b/crates/dim-app-server/tests/transport_flow/fork.rs @@ -657,6 +657,7 @@ async fn fork_checks_rest_points_without_scanning_completed_history() { EventKind::InputApplied(InputAppliedData { input_id: id.clone(), mode: Some(InputMode::Queue), + tool_mode: None, }) .into(), EventKind::InputConsumed(InputConsumedData { @@ -673,6 +674,7 @@ async fn fork_checks_rest_points_without_scanning_completed_history() { EventKind::InputApplied(InputAppliedData { input_id: wake_id.clone(), mode: Some(InputMode::Steer), + tool_mode: None, }) .into(), EventKind::InputConsumed(InputConsumedData { input_id: wake_id }).into(), @@ -728,6 +730,7 @@ async fn fork_checks_rest_points_without_scanning_completed_history() { EventKind::InputApplied(InputAppliedData { input_id: "pending-wake".into(), mode: Some(InputMode::Steer), + tool_mode: None, }) .into(), EventKind::InputConsumed(InputConsumedData { diff --git a/crates/dim-migration/src/native.rs b/crates/dim-migration/src/native.rs index f7cd140493..abae00916e 100644 --- a/crates/dim-migration/src/native.rs +++ b/crates/dim-migration/src/native.rs @@ -696,6 +696,7 @@ pub(crate) fn history(data: &SessionData) -> Result> { EventKind::InputApplied(InputAppliedData { input_id: id.clone(), mode: Some(InputMode::Append), + tool_mode: None, }), None, now, diff --git a/tests/integration/tests/wait_protocol.rs b/tests/integration/tests/wait_protocol.rs index 3b33ec1994..31888bec99 100644 --- a/tests/integration/tests/wait_protocol.rs +++ b/tests/integration/tests/wait_protocol.rs @@ -403,6 +403,7 @@ async fn wait_timeline_traces_match_the_notification_contract() { EventKind::InputApplied(InputAppliedData { input_id: input_id(position), mode: None, + tool_mode: None, }) .into(), ) @@ -474,6 +475,7 @@ async fn wait_timeline_traces_match_the_notification_contract() { EventKind::InputApplied(InputAppliedData { input_id: input_id(0), mode: None, + tool_mode: None, }) .into(), ) From 46336cfcd33d8038b81eed570e0c8584a7c9acc7 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 01:09:36 +0800 Subject: [PATCH 07/50] fix: explain the input queue's registry dependency and guard the Unix test Refs #2135 --- crates/dim-app-server/tests/app_server_flow.rs | 1 + docs/architecture/rust-agent/plugins/InputQueue.md | 1 + 2 files changed, 2 insertions(+) diff --git a/crates/dim-app-server/tests/app_server_flow.rs b/crates/dim-app-server/tests/app_server_flow.rs index 4bf2097aad..cbffa2417c 100644 --- a/crates/dim-app-server/tests/app_server_flow.rs +++ b/crates/dim-app-server/tests/app_server_flow.rs @@ -26,6 +26,7 @@ mod read_image_flow; mod session_files_flow; #[cfg(unix)] mod session_language_flow; +#[cfg(unix)] mod session_tool_mode_flow; mod settings_flow; #[path = "storage_flow.rs"] diff --git a/docs/architecture/rust-agent/plugins/InputQueue.md b/docs/architecture/rust-agent/plugins/InputQueue.md index ef3c879f76..82994862cc 100644 --- a/docs/architecture/rust-agent/plugins/InputQueue.md +++ b/docs/architecture/rust-agent/plugins/InputQueue.md @@ -75,6 +75,7 @@ observable input queue. | `B:Timeline` | Commit withdrawal commands and atomic application or withdrawal results. | | `S:TreeCommands` | Reach the validating branch input entry for `submit`. | | `B:TimelineIdentity` | Identify the branch for `submit`. | +| `S:ToolRegistry` | Read the effective tool mode when an input is applied; the applied record carries it to the turn. | ### Data face From 58ff3ef44810e921df1435c7d2508a991c8d77a8 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:04:42 +0800 Subject: [PATCH 08/50] fix: bind the callable when the host prepares the request The prepare path passed the visible list back into the binding, so the delegated set was re-projected from visible and lost the child tools. Bind the callable instead. Minimal Sessions select shell, and the Code Mode flows select codemode, matching the design. Refs #2135 --- crates/dim-agent-capabilities/src/tool_binding.rs | 9 ++------- .../dim-app-server/tests/transport_flow/shell_input.rs | 3 ++- crates/dim-codemode/tests/flow.rs | 1 + tests/integration/tests/minimal_execution.rs | 1 + 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 06f26b5089..110df26392 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -150,13 +150,8 @@ impl ToolBinding { let (definitions, sets) = self.registry.snapshot(); let visible = project(mode, &definitions).0; let settings = prepare(&visible)?; - self.bind_snapshot( - request_id, - settings.tools.as_deref().unwrap_or_default(), - sets, - mode, - ) - .map_err(AgentError::InvalidInput)?; + self.bind_snapshot(request_id, &definitions, sets, mode) + .map_err(AgentError::InvalidInput)?; Ok(settings) } diff --git a/crates/dim-app-server/tests/transport_flow/shell_input.rs b/crates/dim-app-server/tests/transport_flow/shell_input.rs index d6da9c2df1..0e6e0ba454 100644 --- a/crates/dim-app-server/tests/transport_flow/shell_input.rs +++ b/crates/dim-app-server/tests/transport_flow/shell_input.rs @@ -1849,7 +1849,8 @@ async fn a_recorded_run_is_one_append_input_for_the_next_request() { "\n$ echo hi\nhi\n\n"}]}) ); assert!(events.iter().any(|event| event["name"] == "applied" - && event["data"] == json!({"input_id": input["id"], "mode": "append"}))); + && event["data"] + == json!({"input_id": input["id"], "mode": "append", "tool_mode": "normal"}))); assert!( events.iter().all(|event| event["type"] != "turn"), "{events:?}" diff --git a/crates/dim-codemode/tests/flow.rs b/crates/dim-codemode/tests/flow.rs index a5b8f71814..20a5f5a97a 100644 --- a/crates/dim-codemode/tests/flow.rs +++ b/crates/dim-codemode/tests/flow.rs @@ -192,6 +192,7 @@ impl Fixture { tools: Some(tools), interactive, permission_policy, + tool_mode: dim_agent_runtime::ToolMode::Codemode, ..SessionConfig::default() }, Default::default(), diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index a6a8129f63..17dcd2d99b 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -268,6 +268,7 @@ impl Harness { let mut config = SessionConfig { cwd: self.cwd.to_string_lossy().into_owned(), tools: Some(vec!["execute".into()]), + tool_mode: dim_agent_runtime::ToolMode::Shell, permission_policy: PermissionPolicy { preset: PermissionPreset::FullAccess, ..Default::default() From 2494abf4fc16b88e51adfb1a022fc65f1bba4732 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:08:20 +0800 Subject: [PATCH 09/50] feat: register execute as a tool and route the live stop ShellTools registers the execute tool with ToolRegistry instead of providing the Session's ToolHost. The product profile mounts ShellSession and the tool; the minimal profile binds an empty ToolHost. session.exec.stop asks the branch's live ExecStop first and falls back to BackgroundExec. Refs #2135 --- crates/dim-agent-capabilities/src/defaults.rs | 32 ++++++++++++++ .../dim-agent-capabilities/src/shell_tools.rs | 42 ++++++++++--------- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/crates/dim-agent-capabilities/src/defaults.rs b/crates/dim-agent-capabilities/src/defaults.rs index 027f73bfe7..0b0d6fd941 100644 --- a/crates/dim-agent-capabilities/src/defaults.rs +++ b/crates/dim-agent-capabilities/src/defaults.rs @@ -246,6 +246,7 @@ pub fn install_minimal_execution( )?)) }), ); + tool_host(builder, Arc::new(NoTools)); crate::shell_tools::install(builder); crate::prompt_sources::install(builder); crate::skills::install(builder); @@ -294,6 +295,14 @@ pub fn install_local_execution_with( crate::prompt_sources::DATE_CHECK, prompt_sources, ); + builder.require_feature( + Feature::new("ShellSession").branch("ShellSession", |names| { + Ok(Box::new(crate::shell_session::ShellSessionPlugin::session( + names, + )?)) + }), + ); + crate::shell_tools::install(builder); crate::skills::install(builder); } @@ -324,6 +333,29 @@ pub fn install_compaction( } /// Installs `driver` as the Session `ToolHost`. +/// A `ToolHost` with no host tools: the minimal profile's only tool is +/// `execute`, registered by [`crate::shell_tools`]. +pub struct NoTools; + +impl ToolDriver for NoTools { + fn definitions(&self) -> Vec { + Vec::new() + } + + fn execute( + &self, + _: dim_agent_types::ToolCall, + _: crate::host::ToolExecutionContext, + _: tokio_util::sync::CancellationToken, + ) -> crate::host::HostFuture<'_, dim_agent_types::ToolResult> { + Box::pin(async { + Err(crate::host::HostError::failed( + "this profile has no host tools", + )) + }) + } +} + pub fn tool_host(builder: &mut AgentBuilder, driver: Arc) { crate::register_names(builder); builder.session_value(Arc::new(ToolHost(driver))); diff --git a/crates/dim-agent-capabilities/src/shell_tools.rs b/crates/dim-agent-capabilities/src/shell_tools.rs index 235f47f5db..330dc5e49d 100644 --- a/crates/dim-agent-capabilities/src/shell_tools.rs +++ b/crates/dim-agent-capabilities/src/shell_tools.rs @@ -4,10 +4,11 @@ //! dispatches execution. use crate::{ - host::{ToolDriver, ToolExecutionContext, ToolHost}, + host::{HostError, HostFuture, ToolExecutionContext}, host_platform::{HostPlatform, ISOLATION_SUMMARY}, shell_session::{CallContext, ShellSession}, timeline_tree::TreeCommands, + tool_registry::{ToolContribution, ToolHandler, ToolRegistry}, }; use dim_agent_runtime::{AgentBuilder, Names}; use dim_agent_types::{ToolCall, ToolResult}; @@ -43,33 +44,26 @@ fn execute_definition(platform: &HostPlatform) -> dim_agent_types::ToolDefinitio ) } -/// The tool driver. -struct ShellToolsDriver { - platform: Arc, +/// The `execute` handler. +struct ShellTool { tree: Arc, } -impl ToolDriver for ShellToolsDriver { - fn definitions(&self) -> Vec { - let mut definition = execute_definition(&self.platform); - definition.risk = Some("execute_process".into()); - vec![definition] - } - +impl ToolHandler for ShellTool { fn execute( &self, call: ToolCall, context: ToolExecutionContext, cancel: tokio_util::sync::CancellationToken, - ) -> crate::host::HostFuture<'_, ToolResult> { + ) -> HostFuture<'_, ToolResult> { let tree = self.tree.clone(); Box::pin(async move { let branch = tree .get(&context.branch_id) - .map_err(|e| crate::host::HostError::failed(e.to_string()))?; + .map_err(|e| HostError::failed(e.to_string()))?; let session = branch .service::() - .map_err(|e| crate::host::HostError::failed(e.to_string()))?; + .map_err(|e| HostError::failed(e.to_string()))?; let input = call.input; let command = input .get("command") @@ -92,7 +86,7 @@ impl ToolDriver for ShellToolsDriver { session .run(command, call_context, timeout_ms, run_in_background, cancel) .await - .map_err(|e| crate::host::HostError::failed(e.to_string())) + .map_err(|e| HostError::failed(e.to_string())) }) } } @@ -108,7 +102,7 @@ pub fn install(builder: &mut AgentBuilder) { /// The plugin. pub struct ShellToolsPlugin { - host: Key, + tools: Key, platform: Key, tree: Key, } @@ -116,7 +110,7 @@ pub struct ShellToolsPlugin { impl ShellToolsPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { - host: names.key()?, + tools: names.key()?, platform: names.key()?, tree: names.key()?, }) @@ -128,14 +122,22 @@ impl DynPlugin for ShellToolsPlugin { "ShellTools" } fn injects(&self) -> Vec { - vec![self.platform.erase(), self.tree.erase()] + vec![self.tools.erase(), self.platform.erase(), self.tree.erase()] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { + let tools = ctx.require_at(&self.tools)?; let platform = ctx.require_at(&self.platform)?; let tree = ctx.require_at(&self.tree)?; - let driver = Arc::new(ShellToolsDriver { platform, tree }); - ctx.provide_at(self.host.clone(), Arc::new(ToolHost(driver)))?; + let mut definition = execute_definition(&platform); + definition.risk = Some("execute_process".into()); + tools.register( + ctx, + ToolContribution { + definition, + handler: Arc::new(ShellTool { tree }), + }, + )?; Ok(Effect::Done) }) } From 87f66a837a353b24d5987bb8cb1e070a46f6f034 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:20:33 +0800 Subject: [PATCH 10/50] feat: settle goals on an effective shell transition ToolRegistry provides the internal ModeTransition service; the mode update asks it to settle before the record and live value. Goal registers a handler that pauses every active branch with a reason-mode pause text, refuses set/resume while shell is in force, and pauses instead of writing a continuation. PromptSources drops the Windows file-encoding guidance in shell mode. Refs #2135 --- crates/dim-agent-capabilities/src/lib.rs | 1 + .../src/prompt_sources.rs | 11 ++- .../src/tool_registry.rs | 78 ++++++++++++++++++- .../dim-app-server/src/session_tool_mode.rs | 21 ++++- crates/dim-goal/src/branch.rs | 17 +++- crates/dim-goal/src/session.rs | 66 +++++++++++++++- crates/dim-goal/src/text.rs | 17 ++++ 7 files changed, 201 insertions(+), 10 deletions(-) diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index b07b480373..b9a6fa1315 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -79,6 +79,7 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, session); register::(catalog, session); register::(catalog, session); + register::(catalog, session); catalog.register_shared_instance("toolSourcesView", SESSION_GROUP); register::(catalog, session); catalog.register_shared_instance("initialPromptConfiguration", SESSION_GROUP); diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index e9549f0101..1f020f2f29 100644 --- a/crates/dim-agent-capabilities/src/prompt_sources.rs +++ b/crates/dim-agent-capabilities/src/prompt_sources.rs @@ -12,6 +12,7 @@ use crate::{ prompt::Prompt, prompt_registry::{PromptRegistry, PromptRegistryPlugin, targets}, prompt_state::PromptSnapshot, + tool_registry::ToolRegistry, }; use dim_agent_runtime::{ AgentBuilder, BranchLifecycle, BranchPhase, ConfigureUpdate, Names, PromptSourceTarget, @@ -254,6 +255,7 @@ fn environment( shell: &ShellStatus, cwd: &str, policy: &PromptSourcesConfig, + shell_mode: bool, ) -> String { let os = match platform.os { Os::Macos => "darwin", @@ -287,7 +289,7 @@ fn environment( OutputEncoding::Unknown => "unknown", }, )); - if platform.os == Os::Windows { + if platform.os == Os::Windows && !shell_mode { let guidance = policy .file_encoding_guidance .as_deref() @@ -478,6 +480,7 @@ impl PromptSourcesBranch { struct Sources { platform: Arc, config: Arc, + tools: Arc, today: Today, stopped: CancellationToken, policy: PromptSourcesConfig, @@ -526,6 +529,7 @@ impl LoadPrompt for Sources { &self.platform.exec_shell().await, &self.config.cwd, &self.policy, + self.tools.effective_tool_mode() == dim_agent_types::ToolMode::Shell, )), PromptDelivery::State, 200, @@ -566,6 +570,7 @@ impl LoadPrompt for Sources { pub struct PromptSourcesPlugin { platform: Key, config: Key, + tools: Key, registry: Key, language: Key, settings: Option>, @@ -586,6 +591,7 @@ impl PromptSourcesPlugin { Ok(Self { platform: names.key()?, config: names.key()?, + tools: names.key()?, registry: names.key()?, language: names.key()?, settings: names @@ -605,6 +611,7 @@ impl DynPlugin for PromptSourcesPlugin { vec![ self.platform.erase(), self.config.erase(), + self.tools.erase(), self.registry.erase(), ] } @@ -612,6 +619,7 @@ impl DynPlugin for PromptSourcesPlugin { Box::pin(async move { let platform = ctx.require_at(&self.platform)?; let config = ctx.require_at(&self.config)?; + let tools = ctx.require_at(&self.tools)?; let registry = ctx.require_at(&self.registry)?; // Apply runs once per Session instance: builder rows cannot // reload, and every rebuilt daemon or fork creates a new @@ -640,6 +648,7 @@ impl DynPlugin for PromptSourcesPlugin { let sources: Arc = Arc::new(Sources { platform, config, + tools, today: self.today.clone(), stopped: ctx.cancellation_token(), policy, diff --git a/crates/dim-agent-capabilities/src/tool_registry.rs b/crates/dim-agent-capabilities/src/tool_registry.rs index d021148d47..2401a5cb57 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -249,6 +249,67 @@ struct Offered { set: Arc, } +/// Why a tool-mode transition settles: the operator changed the mode, or a +/// registration made the chosen mode effective. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModeChangeCause { + Update, + Registration, +} + +type ModeSettleHandler = + Arc HostFuture<'static, ()> + Send + Sync>; + +/// The Session's internal mode-transition service: Goal registers a handler +/// that settles a transition before the mode changes or is published. +pub struct ModeTransition { + handlers: Mutex>, + next: std::sync::atomic::AtomicU64, +} + +impl Default for ModeTransition { + fn default() -> Self { + Self { + handlers: Mutex::new(Vec::new()), + next: std::sync::atomic::AtomicU64::new(1), + } + } +} + +impl ModeTransition { + /// Registers a handler until its returned id is removed. + pub fn register(&self, handler: ModeSettleHandler) -> u64 { + let id = self + .next + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.handlers.lock().unwrap().push((id, handler)); + id + } + pub fn remove(&self, id: u64) { + self.handlers.lock().unwrap().retain(|(held, _)| *held != id); + } + /// Runs every registered handler in registration order. + pub async fn settle( + &self, + mode: ToolMode, + cause: ModeChangeCause, + ) -> Result<(), HostError> { + let handlers: Vec<_> = self + .handlers + .lock() + .unwrap() + .iter() + .map(|(_, handler)| handler.clone()) + .collect(); + for handler in handlers { + if let Err(error) = handler(mode, cause).await { + return Err(error); + } + } + Ok(()) + } +} + pub struct ToolRegistry { /// Every host tool, in the host's order; a part cannot register one of /// these names. @@ -268,6 +329,7 @@ pub struct ToolRegistry { /// The operator's chosen mode; the effective one may fall back to /// `normal` when its entry tool is not mounted. mode: Mutex, + transition: Arc, session_id: String, config: Arc, /// Serializes refreshes from read to commit, so an earlier read never @@ -405,6 +467,14 @@ impl ToolRegistry { .cloned() .collect() } + /// The mode in force if `mode` were chosen now. + pub fn effective_of_mode(&self, mode: ToolMode) -> ToolMode { + let declared = self.snapshot().0; + match mode.entry_tool() { + Some(entry) if declared.iter().any(|tool| tool.name == entry) => mode, + _ => ToolMode::Normal, + } + } /// The operator's chosen mode. pub fn tool_mode(&self) -> ToolMode { *self.mode.lock().unwrap() @@ -940,6 +1010,7 @@ pub fn definition(name: &str, description: &str, schema: serde_json::Value) -> T pub struct ToolRegistryPlugin { session: InstanceId, registry: Key, + transition: Key, view: Key, host: Key, config: Key, @@ -951,6 +1022,7 @@ impl ToolRegistryPlugin { Ok(Self { session: names.instance(dim_agent_runtime::SESSION_GROUP)?, registry: names.key()?, + transition: names.key()?, view: names.key()?, host: names.key()?, config: names.key()?, @@ -1006,6 +1078,7 @@ impl DynPlugin for ToolRegistryPlugin { offered: Mutex::default(), missing: Mutex::default(), mode: Mutex::new(config.tool_mode), + transition: Arc::new(ModeTransition::default()), session_id: identity.session_id.clone(), config: config.clone(), refreshing: Mutex::default(), @@ -1064,7 +1137,8 @@ impl DynPlugin for ToolRegistryPlugin { ), Arc::new(ForeignRegistry(registry.clone())), )?; - ctx.provide_at(self.registry.clone(), registry)?; + ctx.provide_at(self.registry.clone(), registry.clone())?; + ctx.provide_at(self.transition.clone(), registry.transition.clone())?; Ok(Effect::Done) }) } @@ -1105,6 +1179,7 @@ mod tests { offered: Mutex::default(), missing: Mutex::default(), mode: Mutex::new(ToolMode::Normal), + transition: Arc::new(ModeTransition::default()), session_id: "session".into(), config, refreshing: Mutex::default(), @@ -1135,6 +1210,7 @@ mod tests { offered: Mutex::default(), missing: Mutex::default(), mode: Mutex::new(mode), + transition: Arc::new(ModeTransition::default()), session_id: "session".into(), config, refreshing: Mutex::default(), diff --git a/crates/dim-app-server/src/session_tool_mode.rs b/crates/dim-app-server/src/session_tool_mode.rs index 8f90e3a603..d3a65c71de 100644 --- a/crates/dim-app-server/src/session_tool_mode.rs +++ b/crates/dim-app-server/src/session_tool_mode.rs @@ -5,7 +5,7 @@ use crate::storage::Store; use dim_agent_capabilities::{ methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params}, - tool_registry::ToolRegistry, + tool_registry::{ModeChangeCause, ModeTransition, ToolRegistry}, }; use dim_agent_runtime::{Names, ToolMode}; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; @@ -20,6 +20,7 @@ const FAILED: &str = "tool_mode_failed"; /// The Session's two tool-mode methods; one per Session instance. pub(crate) struct SessionToolModePlugin { tools: Key, + transition: Key, methods: Key, /// Native storage, when the assembly has it: the record carries the value. store: Option>, @@ -28,6 +29,7 @@ impl SessionToolModePlugin { pub(crate) fn new(names: &Names<'_>, stored: bool) -> Result { Ok(Self { tools: names.key()?, + transition: names.key()?, methods: names.key()?, store: stored.then(|| names.key()).transpose()?, }) @@ -38,7 +40,11 @@ impl DynPlugin for SessionToolModePlugin { "SessionToolMode" } fn injects(&self) -> Vec { - let mut injects = vec![self.tools.erase(), self.methods.erase()]; + let mut injects = vec![ + self.tools.erase(), + self.transition.erase(), + self.methods.erase(), + ]; if let Some(store) = &self.store { injects.push(store.erase()); } @@ -47,6 +53,7 @@ impl DynPlugin for SessionToolModePlugin { fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let tools = ctx.require_at(&self.tools)?; + let transition = ctx.require_at(&self.transition)?; let methods = ctx.require_at(&self.methods)?; let store = match &self.store { Some(key) => Some(ctx.require_at(key)?), @@ -61,12 +68,13 @@ impl DynPlugin for SessionToolModePlugin { ], Arc::new(move |call, _cancel, _| { let tools = tools.clone(); + let transition = transition.clone(); let store = store.clone(); let MethodCall { method, params, .. } = call; Box::pin(async move { match method.as_str() { "session.tool_mode.get" => Ok(value(&tools)), - _ => change(&tools, store.as_deref(), params).await, + _ => change(&tools, &transition, store.as_deref(), params).await, } }) }), @@ -97,6 +105,7 @@ fn value(tools: &ToolRegistry) -> Value { /// follows it. async fn change( tools: &ToolRegistry, + transition: &ModeTransition, store: Option<&Store>, input: Value, ) -> Result { @@ -107,6 +116,12 @@ async fn change( mode: ToolMode, } let Params { session_id, mode } = params(input)?; + if tools.effective_of_mode(mode) == ToolMode::Shell { + transition + .settle(ToolMode::Shell, ModeChangeCause::Update) + .await + .map_err(|error| RpcError::app(-32000, FAILED, error.to_string()))?; + } if let Some(store) = store { store .set_session_tool_mode(&session_id, mode) diff --git a/crates/dim-goal/src/branch.rs b/crates/dim-goal/src/branch.rs index 5940f2a274..349c4403d1 100644 --- a/crates/dim-goal/src/branch.rs +++ b/crates/dim-goal/src/branch.rs @@ -5,7 +5,7 @@ use crate::fold::{self, Conclusion, ConclusionAction, Decision, Fold, TurnEnd}; use crate::text::{self, GoalTexts, Live}; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::{timeline_tree::TreeCommands, tool_registry::ToolRegistry}; use dim_agent_runtime::{ AgentError, BoxFuture, BranchLifecycle, BranchOptions, Dispatcher, Names, QueryComparison, QueryFilter, QueryOperand, QueryOrder, QueryOrderKey, QueryOutput, QueryPage, QueryPick, @@ -52,6 +52,7 @@ pub(crate) enum Change { objective: String, }, Pause, + PauseMode, Resume, Clear, Report { @@ -68,6 +69,7 @@ impl Change { Self::Set { objective, judge } => text::set(branch, objective, *judge), Self::Edit { objective } => text::edit(branch, objective), Self::Pause => text::pause(branch), + Self::PauseMode => text::pause_mode(branch), Self::Resume => text::resume(branch), Self::Clear => text::clear(branch), Self::Report { completed, summary } => text::report( @@ -180,6 +182,7 @@ pub struct GoalBranch { session: Key, texts: Arc, changes: Changes, + tools: Key, } impl GoalBranch { @@ -194,6 +197,7 @@ impl GoalBranch { session: names.key()?, texts, changes, + tools: names.key()?, }) } } @@ -211,6 +215,7 @@ impl DynPlugin for GoalBranch { self.identity.erase(), self.phase.erase(), self.session.erase(), + self.tools.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -222,6 +227,7 @@ impl DynPlugin for GoalBranch { let identity = ctx.require_at(&self.identity)?; let phase = ctx.require_at(&self.phase)?; let session = ctx.require_at(&self.session)?; + let tools = ctx.require_at(&self.tools)?; let stop = CancellationToken::new(); let (resolved, _) = watch::channel(false); let (stepped, _) = watch::channel(0); @@ -238,6 +244,7 @@ impl DynPlugin for GoalBranch { texts: self.texts.clone(), phase: phase.clone(), session: session.clone(), + tools, stop: stop.clone(), tasks: TaskTracker::new(), work: TaskTracker::new(), @@ -482,6 +489,7 @@ struct Owner { texts: Arc, phase: Arc, session: Arc, + tools: Arc, stop: CancellationToken, tasks: TaskTracker, work: TaskTracker, @@ -679,7 +687,7 @@ impl Owner { let operation = match &change { Change::Set { .. } => "set", Change::Edit { .. } => "edit", - Change::Pause => "pause", + Change::Pause | Change::PauseMode => "pause", Change::Resume => "resume", Change::Clear => "clear", Change::Report { @@ -2106,6 +2114,11 @@ impl Owner { let Some(Decision::Continuation { count, idle }) = decision else { return Ok(()); }; + if self.tools.effective_tool_mode() == dim_agent_types::ToolMode::Shell { + drop(write); + self.change(Change::PauseMode).await?; + return Ok(()); + } let input = text::continuation(&self.branch_id, count, limit, idle, after, &self.texts); if self.write_if_head(input, through).await?.is_some() { diff --git a/crates/dim-goal/src/session.rs b/crates/dim-goal/src/session.rs index 43da5c48d6..c95c4c8014 100644 --- a/crates/dim-goal/src/session.rs +++ b/crates/dim-goal/src/session.rs @@ -7,14 +7,18 @@ use crate::branch::{Change, Changes}; use crate::text::{self, OBJECTIVE_LIMIT, SUMMARY_LIMIT}; use dim_agent_capabilities::{ - host::{HostFuture, ToolExecutionContext}, + host::{HostError, HostFuture, ToolExecutionContext}, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, reply}, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, timeline_tree::TreeCommands, - tool_registry::{ToolContribution, ToolHandler, ToolRegistry}, + tool_registry::{ + ModeChangeCause, ModeTransition, ToolContribution, ToolHandler, ToolRegistry, + }, }; use dim_agent_runtime::{Names, SessionIdentity, TimelineKey}; -use dim_agent_types::{ToolCall, ToolDefinition, ToolResult, ToolSource}; +use dim_agent_types::{ + GoalViewStatus, ToolCall, ToolDefinition, ToolMode, ToolResult, ToolSource, +}; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::{Value, json}; @@ -24,6 +28,7 @@ use tokio_util::sync::CancellationToken; pub struct GoalSession { tree: Key, tools: Key, + transition: Key, methods: Key, guide: Key, identity: Key, @@ -35,6 +40,7 @@ impl GoalSession { Ok(Self { tree: names.key()?, tools: names.key()?, + transition: names.key()?, methods: names.key()?, guide: names.key()?, identity: names.key()?, @@ -51,6 +57,7 @@ impl DynPlugin for GoalSession { vec![ self.tree.erase(), self.tools.erase(), + self.transition.erase(), self.methods.erase(), self.guide.erase(), self.identity.erase(), @@ -60,6 +67,7 @@ impl DynPlugin for GoalSession { Box::pin(async move { let tree = ctx.require_at(&self.tree)?; let tools = ctx.require_at(&self.tools)?; + let transition = ctx.require_at(&self.transition)?; let methods = ctx.require_at(&self.methods)?; let guide = ctx.require_at(&self.guide)?; let identity = ctx.require_at(&self.identity)?; @@ -91,10 +99,52 @@ impl DynPlugin for GoalSession { }), }, )?; + let settle_tree = tree.clone(); + let settle_changes = self.changes.clone(); + let settle_session = identity.session_id.clone(); + let settle = transition.register(Arc::new( + move |mode: ToolMode, _cause: ModeChangeCause| { + let tree = settle_tree.clone(); + let changes = settle_changes.clone(); + let session_id = settle_session.clone(); + Box::pin(async move { + if mode != ToolMode::Shell { + return Ok(()); + } + for info in tree.list() { + let key = TimelineKey { + session_id: session_id.clone(), + branch_id: info.id.clone(), + }; + let Ok(read) = changes.current(&key).await else { + continue; + }; + if !matches!( + read.goal.as_ref().map(|goal| &goal.status), + Some(GoalViewStatus::Active) + ) { + continue; + } + if let Err(error) = + changes.change(&key, Change::PauseMode).await + { + return Err(HostError::failed(error.to_string())); + } + } + Ok(()) + }) + }, + )); + let settle_transition = transition.clone(); + ctx.effect(move || async move { + settle_transition.remove(settle); + Ok(()) + })?; let owner = Arc::new(Owner { tree, identity, changes: self.changes.clone(), + tools: tools.clone(), }); methods.register( ctx, @@ -147,6 +197,7 @@ struct Owner { tree: Arc, identity: Arc, changes: Changes, + tools: Arc, } impl Owner { @@ -167,6 +218,15 @@ impl Owner { let op = method .strip_prefix("session.goal.") .ok_or_else(|| RpcError::invalid(format!("unknown method {method}")))?; + if matches!(op, "set" | "resume") + && self.tools.effective_tool_mode() == dim_agent_types::ToolMode::Shell + { + return Err(RpcError::app( + -32000, + "goal_unavailable_in_shell_mode", + "The goal cannot be set or resumed while shell mode is in force", + )); + } let change = match op { "set" | "edit" => { let objective = diff --git a/crates/dim-goal/src/text.rs b/crates/dim-goal/src/text.rs index 048fa835ee..b0d03214b7 100644 --- a/crates/dim-goal/src/text.rs +++ b/crates/dim-goal/src/text.rs @@ -432,6 +432,23 @@ pub fn pause(branch: &str) -> InputMessageData { ) } +pub fn pause_mode(branch: &str) -> InputMessageData { + input( + vec![Block::new( + vec![ + ("kind", "goal".to_owned()), + ("op", "pause".to_owned()), + ("reason", "mode".to_owned()), + ("branch", branch.to_owned()), + ], + vec![format!( + "The Session switched to shell mode and paused the goal for branch {branch}." + )], + )], + InputMode::Append, + ) +} + pub fn resume(branch: &str) -> InputMessageData { input( vec![Block::new( From 64abfb25445638f3226ce818bd09f501b51ff144 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:26:11 +0800 Subject: [PATCH 11/50] docs: document the shell parts and the mode faces Refs #2135 --- crates/dim-app-server/src/lib.rs | 3 ++ .../rust-agent/plugins/PromptSources.md | 1 + .../rust-agent/plugins/ShellSession.md | 33 +++++++++++++++++++ .../rust-agent/plugins/ShellTools.md | 27 +++++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 docs/architecture/rust-agent/plugins/ShellSession.md create mode 100644 docs/architecture/rust-agent/plugins/ShellTools.md diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 325ec674b4..fdef46b437 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1685,6 +1685,7 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("contextPreparation", "hot-path"), ("contextUsage", "hot-path"), ("fileReads", "hot-path"), + ("execStop", "control"), ("fileStorage", "object"), ("grokOAuthService", "secret"), ("historyRenderer", "hot-path"), @@ -1693,6 +1694,7 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { // Session creation calls it directly; no leaf needs the service. ("managedWorktrees", "hot-path"), ("mentionIndex", "host-resource"), + ("modeTransition", "control"), ("modelHost", "owner-api"), ("openAICodexOAuthService", "secret"), ("prepareContextHost", "hot-path"), @@ -1703,6 +1705,7 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("serverControl", "control"), ("sessionStore", "owner-api"), ("settingsService", "owner-api"), + ("shellSession", "control"), ("timelineFactory", "control"), ("timelineTree", "owner-api"), ("timelineTreeControl", "owner-api"), diff --git a/docs/architecture/rust-agent/plugins/PromptSources.md b/docs/architecture/rust-agent/plugins/PromptSources.md index 86b07aae9d..1539794e7e 100644 --- a/docs/architecture/rust-agent/plugins/PromptSources.md +++ b/docs/architecture/rust-agent/plugins/PromptSources.md @@ -88,6 +88,7 @@ from branch adoption. | Service | Purpose | | --- | --- | | `P:HostPlatform` | Home, environment and shell/platform context. | +| `S:ToolRegistry` | The effective tool mode: `shell` drops the Windows file-encoding guidance. | | `S:SessionConfig` | Working directory, Session context and the reply language a record carries. | | `S:PromptRegistry` | Register each of its sources by name, until this part unloads. | diff --git a/docs/architecture/rust-agent/plugins/ShellSession.md b/docs/architecture/rust-agent/plugins/ShellSession.md new file mode 100644 index 0000000000..6180299296 --- /dev/null +++ b/docs/architecture/rust-agent/plugins/ShellSession.md @@ -0,0 +1,33 @@ +# ShellSession + +Owner: [shell_session.rs](../../../../crates/dim-agent-capabilities/src/shell_session.rs). +The branch's persistent shell: one PTY per branch, started on its first +command, with cwd, environment, shell variables and jobs kept across calls. +It provides the branch's `ShellSession` and its `dyn ExecStop`, so the +Session's `execute` tool and the stop route reach it per branch. + +## ShellSession + +The branch part is mounted by the profile's ShellSession feature. It owns the +PTY, the command queue and the background jobs; `execute` resolves the calling +branch's service, and `session.exec.stop` asks the same branch's `ExecStop` +before falling back to `BackgroundExec`. + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:BackgroundExec` | Recover a shell task whose facts were committed but whose owner is gone. | +| `B:Timeline` | Commit command starts, output and terminal ends. | +| `B:Dispatcher` | Deliver the completion notice and wake the Session. | +| `B:BranchLifecycle` | Wait for the branch to be published and stop the shell on closing. | +| `P:HostPlatform` | The shell executable and platform dialect. | +| `S:SessionConfig` | The Session's cwd and execution preferences. | +| `B:TimelineIdentity` | Identify the branch in its facts and notices. | + +### Tests + +`tests/integration/tests/minimal_execution.rs` covers the shell's persistence, +occupancy, background jobs, output bounds, stop and close. The App Server's +`transport_flow::shell_input` and `transport_flow::exec_shell_settings` cover +the product paths. diff --git a/docs/architecture/rust-agent/plugins/ShellTools.md b/docs/architecture/rust-agent/plugins/ShellTools.md new file mode 100644 index 0000000000..d3b83547ac --- /dev/null +++ b/docs/architecture/rust-agent/plugins/ShellTools.md @@ -0,0 +1,27 @@ +# ShellTools + +Owner: [shell_tools.rs](../../../../crates/dim-agent-capabilities/src/shell_tools.rs). +The Session part that declares the `execute` tool. It registers the tool with +`ToolRegistry`; the handler resolves the calling branch's `ShellSession` per +call, so the tool works in `shell` and `codemode` modes without a second +Session `ToolHost`. + +## ShellTools + +The part is mounted by the profile's ShellTools feature. The tool's risk is +`execute_process`; the mode projection hides `execute` outside `shell` and a +`codemode` program reaches it through `delegated`. + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:ToolRegistry` | Register `execute` for the Session. | +| `P:HostPlatform` | The environment line in the tool description. | +| `S:TreeCommands` | Resolve the calling branch's `ShellSession`. | + +### Tests + +The minimal-execution integration suite runs `execute` through the tool +surface; the App Server's `session_tool_mode_flow` asserts the mode +projection. From 274d0f65465819b4b60f60b2719f4f2c747b7ef6 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:28:11 +0800 Subject: [PATCH 12/50] fix: use the settle handler's question mark Refs #2135 --- crates/dim-agent-capabilities/src/tool_registry.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/dim-agent-capabilities/src/tool_registry.rs b/crates/dim-agent-capabilities/src/tool_registry.rs index 2401a5cb57..6df4d92bb7 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -302,9 +302,7 @@ impl ModeTransition { .map(|(_, handler)| handler.clone()) .collect(); for handler in handlers { - if let Err(error) = handler(mode, cause).await { - return Err(error); - } + handler(mode, cause).await?; } Ok(()) } From 3fa49385291c5391102a6dfbccc0c8eea8b02518 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:46:46 +0800 Subject: [PATCH 13/50] fix: read the tool mode without refreshing providers The input application and the environment prompt source read the mode on paths that must not wait on a tool source; read the current sets instead of refreshing. Bind the host's declarations when it prepares the request, and list the mode methods in the transport test's expectation. Refs #2135 --- .../dim-agent-capabilities/src/input_queue.rs | 2 +- .../src/prompt_sources.rs | 2 +- .../src/tool_binding.rs | 34 +++++++------------ .../src/tool_registry.rs | 8 +++++ .../tests/transport_flow/session_methods.rs | 3 ++ 5 files changed, 25 insertions(+), 24 deletions(-) diff --git a/crates/dim-agent-capabilities/src/input_queue.rs b/crates/dim-agent-capabilities/src/input_queue.rs index e05a689f0c..c3fa27eeaf 100644 --- a/crates/dim-agent-capabilities/src/input_queue.rs +++ b/crates/dim-agent-capabilities/src/input_queue.rs @@ -284,7 +284,7 @@ impl InputQueue { } let mut state = self.state.lock().unwrap(); let decisions = state.step(&event); - let mode = self.tools.effective_tool_mode(); + let mode = self.tools.effective_tool_mode_now(); let decisions = decisions .into_iter() .map(|decision| match decision { diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index 1f020f2f29..d1a2a7ad93 100644 --- a/crates/dim-agent-capabilities/src/prompt_sources.rs +++ b/crates/dim-agent-capabilities/src/prompt_sources.rs @@ -529,7 +529,7 @@ impl LoadPrompt for Sources { &self.platform.exec_shell().await, &self.config.cwd, &self.policy, - self.tools.effective_tool_mode() == dim_agent_types::ToolMode::Shell, + self.tools.effective_tool_mode_now() == dim_agent_types::ToolMode::Shell, )), PromptDelivery::State, 200, diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 110df26392..441a1d4cd5 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -102,19 +102,8 @@ impl ToolBinding { }) .collect::, _>>()?; let (visible, delegated) = project(mode, tools); - let mut bound = HashMap::new(); - for tool in visible.iter().chain(delegated.iter()) { - let handler = sets - .iter() - .flat_map(|set| set.tools.iter()) - .find(|candidate| candidate.definition.name == tool.name) - .cloned() - .or_else(|| self.registry.fixed(&tool.name)) - .ok_or_else(|| format!("tool {} has no handler", tool.name))?; - bound.insert(tool.name.clone(), handler); - } + self.bind_snapshot(request_id, &visible, &delegated, sets)?; let mut state = self.state.lock().unwrap(); - register(&mut state, request_id, bound, sets, &visible, &delegated)?; if let Some(newest) = state .pins .iter() @@ -138,7 +127,9 @@ impl ToolBinding { ) -> Result, String> { let (definitions, sets) = self.registry.snapshot(); let tools = declared.unwrap_or(&definitions); - self.bind_snapshot(request_id, tools, sets, mode) + let (visible, delegated) = project(mode, tools); + self.bind_snapshot(request_id, &visible, &delegated, sets)?; + Ok(visible) } pub(crate) fn prepare( @@ -148,9 +139,10 @@ impl ToolBinding { prepare: impl FnOnce(&[ToolDefinition]) -> dim_agent_runtime::Result, ) -> dim_agent_runtime::Result { let (definitions, sets) = self.registry.snapshot(); - let visible = project(mode, &definitions).0; - let settings = prepare(&visible)?; - self.bind_snapshot(request_id, &definitions, sets, mode) + let (available, delegated) = project(mode, &definitions); + let settings = prepare(&available)?; + let visible = settings.tools.as_deref().unwrap_or_default(); + self.bind_snapshot(request_id, visible, &delegated, sets) .map_err(AgentError::InvalidInput)?; Ok(settings) } @@ -158,11 +150,10 @@ impl ToolBinding { fn bind_snapshot( &self, request_id: &str, - tools: &[ToolDefinition], + visible: &[ToolDefinition], + delegated: &[ToolDefinition], sets: Vec>, - mode: ToolMode, - ) -> Result, String> { - let (visible, delegated) = project(mode, tools); + ) -> Result<(), String> { let mut bound = HashMap::new(); for tool in visible.iter().chain(delegated.iter()) { let handler = self @@ -179,8 +170,7 @@ impl ToolBinding { bound.insert(tool.name.clone(), handler); } let mut state = self.state.lock().unwrap(); - register(&mut state, request_id, bound, sets, &visible, &delegated)?; - Ok(visible) + register(&mut state, request_id, bound, sets, visible, delegated) } /// The tool a call of `request_id` runs: its definition (for admission) diff --git a/crates/dim-agent-capabilities/src/tool_registry.rs b/crates/dim-agent-capabilities/src/tool_registry.rs index 6df4d92bb7..73be8100eb 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -483,6 +483,14 @@ impl ToolRegistry { let declared = self.snapshot().0; self.effective_of(&declared) } + /// The effective mode from the current sets, without reading providers: + /// for callers on the input or prompt path that must not wait on a + /// source read. + pub fn effective_tool_mode_now(&self) -> ToolMode { + let sources = self.sources.lock().unwrap(); + let declared = self.declared(&sources); + self.effective_of(&declared) + } fn effective_of(&self, declared: &[ToolDefinition]) -> ToolMode { let mode = self.tool_mode(); match mode.entry_tool() { diff --git a/crates/dim-app-server/tests/transport_flow/session_methods.rs b/crates/dim-app-server/tests/transport_flow/session_methods.rs index 79e7545a3e..1c40ca9c84 100644 --- a/crates/dim-app-server/tests/transport_flow/session_methods.rs +++ b/crates/dim-app-server/tests/transport_flow/session_methods.rs @@ -417,6 +417,8 @@ async fn contributed_session_methods_dispatch_through_the_session_they_name() { {"name": "session.language.get", "mutating": false}, {"name": "session.language.update", "mutating": true}, {"name": "session.tool.get", "mutating": false}, + {"name": "session.tool_mode.get", "mutating": false}, + {"name": "session.tool_mode.update", "mutating": true}, {"name": "session.turn.get", "mutating": false}, ]}) ); @@ -507,6 +509,7 @@ async fn a_reloading_or_closed_session_namespace_answers_as_specified() { {"name": "session.input.pending", "mutating": false}, {"name": "session.input.withdraw", "mutating": true}, {"name": "session.language.get", "mutating": false}, {"name": "session.language.update", "mutating": true}, {"name": "session.tool.get", "mutating": false}, + {"name": "session.tool_mode.get", "mutating": false}, {"name": "session.tool_mode.update", "mutating": true}, {"name": "session.turn.get", "mutating": false}]}) ); gate.notify_one(); From 1647ef4776c6e9b4a6d28d00df9b54d8e98c0909 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:56:43 +0800 Subject: [PATCH 14/50] feat: choose the tool mode in the web composer The composer menu offers normal, codemode and shell, reads the Session's mode with session.tool_mode.get, writes it with session.tool_mode.update, and remembers the last choice for the next session.create. The daemon advertises the mode methods again now that the surface follows. Refs #2135 --- crates/dim-app-server/src/transport.rs | 2 + npm/client-protocol.d.ts | 6 ++ web/src/features/chat/ChatPage.test.ts | 1 + web/src/features/chat/ChatPage.vue | 13 +++- web/src/features/chat/ComposerPanel.vue | 9 ++- .../features/chat/ComposerToolModeMenu.vue | 67 +++++++++++++++++++ web/src/i18n/en.ts | 9 +++ web/src/i18n/zh-CN.ts | 9 +++ web/src/rpc/read.ts | 15 +++++ web/src/stores/chat.ts | 25 ++++++- web/src/stores/sessions.ts | 2 + 11 files changed, 153 insertions(+), 5 deletions(-) create mode 100644 web/src/features/chat/ComposerToolModeMenu.vue diff --git a/crates/dim-app-server/src/transport.rs b/crates/dim-app-server/src/transport.rs index 90d41a3f4f..289c0f8739 100644 --- a/crates/dim-app-server/src/transport.rs +++ b/crates/dim-app-server/src/transport.rs @@ -823,6 +823,8 @@ async fn run_connection( "session.branch_set_default", "session.create.origin", "session.language", + "session.tool_mode", + "session.create.toolMode", "session.attach.expectedCwd", "session.attach.expectedConfig", ]); diff --git a/npm/client-protocol.d.ts b/npm/client-protocol.d.ts index e5889b3b58..f3d54f4234 100644 --- a/npm/client-protocol.d.ts +++ b/npm/client-protocol.d.ts @@ -136,6 +136,12 @@ export type PermissionPolicy = { /** `session.permission.get`: the policy of `main` and the version a change must expect. */ export type PermissionState = { version: number; policy: PermissionPolicy } +/** The Session tool modes, named as the server's `ToolMode` serializes them. */ +export type ToolMode = "normal" | "codemode" | "shell" + +/** `session.tool_mode.get` and `.update`: the chosen mode and the mode in force. */ +export type ToolModeState = { mode: ToolMode; effective: ToolMode } + /** A message the server holds in the queue of a running branch: the operator's own blocks in order, one line of them, its Skills and its stored images. */ export type QueuedInput = { id: string; text: string; skills?: string[]; hooks?: number; content: OperatorBlock[]; user: UserInput } diff --git a/web/src/features/chat/ChatPage.test.ts b/web/src/features/chat/ChatPage.test.ts index 3197852423..a574e14341 100644 --- a/web/src/features/chat/ChatPage.test.ts +++ b/web/src/features/chat/ChatPage.test.ts @@ -78,6 +78,7 @@ async function mountPage(defaultBranchId: string, status: "ready" | "failed" = " rows: [], running: false, stopping: false, + toolMode: undefined, retry: undefined, sessionRunning: false, approvals: [], diff --git a/web/src/features/chat/ChatPage.vue b/web/src/features/chat/ChatPage.vue index ecb4ef7174..6facf45562 100644 --- a/web/src/features/chat/ChatPage.vue +++ b/web/src/features/chat/ChatPage.vue @@ -10,7 +10,7 @@ import QueuedInputs from "./QueuedInputs.vue" import QuestionPrompt from "./QuestionPrompt.vue" import { WebChatTimeline } from "../../chat-ui/timeline" import ExtensionMenu from "../extensions/ExtensionMenu.vue" -import { ROOT_BRANCH_ID, type ContextUsage, type DraftAttachments, type ModelId, type PermissionPreset, type QueuedInput, type SubmitMode, type WithdrawResult } from "../../rpc/protocol" +import { ROOT_BRANCH_ID, type ContextUsage, type DraftAttachments, type ModelId, type PermissionPreset, type QueuedInput, type SubmitMode, type ToolMode, type WithdrawResult } from "../../rpc/protocol" import { goalCall, goalObjective, parseGoalRequest, type Goal, type GoalStatus } from "../../goal" import { intervalSeconds, loopReport, parseLoopRequest } from "../../loop" import { useChatStore } from "../../stores/chat" @@ -34,6 +34,7 @@ const forkConfirm = ref>() watch(() => props.sessionId, (id) => chat.open(id), { immediate: true }) const view = computed(() => chat.views[props.sessionId]) +watch(() => view.value?.status, (status) => { if (status === "ready") void chat.loadToolMode(props.sessionId) }, { immediate: true }) const summary = computed(() => sessions.byId.get(props.sessionId)) const title = computed(() => summary.value?.title ?? summary.value?.preview ?? t("sidebar.untitled")) const parentId = computed(() => summary.value?.parentSessionId) @@ -54,6 +55,15 @@ watch(() => [view.value?.status, view.value?.methods.includes("session.skills")] const found = await chat.sessionSkills(props.sessionId).catch((): Array<{ name: string; description: string; userInvocable: boolean }> => []) skills.value = found.filter((skill) => skill.userInvocable).map(({ name, description }) => ({ name, description })) }, { immediate: true }) +const toolModeControl = computed(() => { + const session = view.value + if (session?.status !== "ready" || !connection.supports("session.tool_mode") || !connection.supports("session.tool_mode.update")) return undefined + return { state: session.toolMode, select: selectToolMode } +}) +async function selectToolMode(mode: ToolMode): Promise { + localStorage.setItem("dim.toolMode", mode) + await chat.setToolMode(props.sessionId, mode) +} const permissionControl = computed(() => { const session = view.value if (session?.status !== "ready" || !connection.supports("session.permission.get") || !connection.supports("session.permission.update")) return undefined @@ -416,6 +426,7 @@ async function fork(): Promise { :stores-pastes="storesPastes" :search-files="searchFiles" :permission="permissionControl" + :tool-mode="toolModeControl" :stop="stop" :held="view.queued" :withdraw-held="view.methods.includes('session.input.withdraw') ? withdrawHeld : undefined" diff --git a/web/src/features/chat/ComposerPanel.vue b/web/src/features/chat/ComposerPanel.vue index a697644622..94797c4a46 100644 --- a/web/src/features/chat/ComposerPanel.vue +++ b/web/src/features/chat/ComposerPanel.vue @@ -2,7 +2,7 @@ import { computed, nextTick, onActivated, onMounted, onUnmounted, ref, useId, watch } from "vue" import { useRoute, useRouter } from "vue-router" import { useI18n } from "vue-i18n" -import type { DraftAttachments, FileCandidate, ModelId, PermissionPreset, PermissionPolicy, QueuedInput, RestoredImage, SubmitMode, UserInput, WithdrawResult } from "../../rpc/protocol" +import type { DraftAttachments, FileCandidate, ModelId, PermissionPreset, PermissionPolicy, QueuedInput, RestoredImage, SubmitMode, ToolMode, ToolModeState, UserInput, WithdrawResult } from "../../rpc/protocol" import { linkMentions, mentionTrigger, type FileMention, type MentionTrigger } from "../../mentions" import { SKILL_TOKEN_PREFIX, namesSkillToken, skillCommandQuery, skillSegments, startsWithSkillToken } from "../../skill-token" import { useComposerStore } from "../../stores/composer" @@ -11,6 +11,7 @@ import { useSessionsStore } from "../../stores/sessions" import { useConnectionStore } from "../../stores/connection" import ComposerModelMenu from "./ComposerModelMenu.vue" import ComposerPermissionMenu from "./ComposerPermissionMenu.vue" +import ComposerToolModeMenu from "./ComposerToolModeMenu.vue" import type { ModelMenuPreview } from "./new-session-model" import { quoteInto } from "./quote" @@ -66,6 +67,8 @@ const props = withDefaults(defineProps<{ searchFiles?: (query: string) => Promise /** The Session policy and its independent controls; absent where permission methods are unavailable. */ permission?: { policy: PermissionPolicy | undefined; select: (preset: PermissionPreset) => Promise } + /** The Session tool mode and its control; absent where mode methods are unavailable. */ + toolMode?: { state: ToolModeState | undefined; select: (mode: ToolMode) => Promise } stop?: (branchId?: string) => Promise /** * The messages the server holds for this branch, oldest first: the composer @@ -98,6 +101,7 @@ const field = ref() const highlightBody = ref() const modelMenu = ref>() const permissionMenu = ref>() +const toolModeMenu = ref>() const menuId = useId() const text = ref("") const sending = ref(false) @@ -162,6 +166,7 @@ const availableCommands = computed(() => ([ { category: "session", name: "loop", available: props.sessionCommands?.loop !== undefined }, { category: "model", name: "effort", available: props.sessionCommands?.effort !== undefined }, { category: "model", name: "permissions", available: props.permission !== undefined && props.variant !== "panel" }, + { category: "model", name: "toolMode", available: props.toolMode !== undefined && props.variant !== "panel" }, { category: "session", name: "lines", available: props.openLines !== undefined }, { category: "session", name: "new", available: true }, { category: "session", name: "scheduled", available: connection.supports("schedule.list") }, @@ -681,6 +686,7 @@ async function runCommand(name: typeof availableCommands.value[number]["name"]): error.value = cause instanceof Error ? cause.message : String(cause) } } else if (name === "permissions") permissionMenu.value?.open() + else if (name === "toolMode") toolModeMenu.value?.open() else if (name === "compact" || name === "usage") await props.sessionCommands?.[name]?.(line) else if (name === "fork") await props.sessionCommands?.fork?.() } @@ -843,6 +849,7 @@ defineExpose({ focus: () => field.value?.focus(), quote })