diff --git a/crates/dim-agent-capabilities/src/agent_loop.rs b/crates/dim-agent-capabilities/src/agent_loop.rs index d712b50c08..2d4f3a0d82 100644 --- a/crates/dim-agent-capabilities/src/agent_loop.rs +++ b/crates/dim-agent-capabilities/src/agent_loop.rs @@ -422,9 +422,11 @@ impl AgentLoop { .history .rendered_context(&self.timeline, through) .await?; + let tool_mode = self.binding.effective_mode(); let Some(request) = configured_request( &crate::context_policy::PolicyContext::from_context(context.clone()), &history, + tool_mode, ) else { return failed("Context is not configured; adopt a model first".into()); }; @@ -1205,8 +1207,11 @@ impl AgentLoop { let cancel = self.lifecycle.child_token(); let result_cancel = cancel.clone(); let owner = self.clone(); + let mut through = through; self.tasks.spawn(async move { let work = AssertUnwindSafe(async { + let tool_mode = owner.binding.effective_mode(); + through = through.max(owner.timeline.sequence()); if let Some(mut source) = recovery { owner .binding @@ -1236,13 +1241,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 +1265,7 @@ impl AgentLoop { None => { let mut settings = owner .binding - .prepare(&request_id, |tools| { + .prepare(&request_id, tool_mode, |tools| { owner .prepare .0 diff --git a/crates/dim-agent-capabilities/src/context_policy.rs b/crates/dim-agent-capabilities/src/context_policy.rs index 8b08bc9cf9..13b6ca91d1 100644 --- a/crates/dim-agent-capabilities/src/context_policy.rs +++ b/crates/dim-agent-capabilities/src/context_policy.rs @@ -400,14 +400,20 @@ fn checkpoint(data: &ContextCompactionData) -> Option { pub(crate) fn configured_request( context: &PolicyContext, history: &[HistoryEntry], + tool_mode: ToolMode, ) -> Option> { let data = context.configuration()?; + let tools = data + .settings + .tools + .as_ref() + .map(|tools| crate::tool_registry::project(tool_mode, tools).0); Some(Arc::new( ModelSettings { provider_id: data.settings.provider_id.clone(), model_id: data.settings.model_id.clone(), capability_snapshot: data.settings.capability_snapshot.clone(), - tools: data.settings.tools.clone(), + tools, system: data.system.clone(), config: crate::context_model::adopted_config( data.settings.capability_snapshot.as_ref(), diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index 9e460067d4..c0a446a053 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -4,9 +4,9 @@ use crate::{ tool_registry::ToolRegistry, }; use dim_agent_runtime::{ - AgentError, BranchLifecycle, Dispatcher, Names, QueryFilter, QueryOperand, QueryOutput, - QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Result, Timeline, TimelineQuery, - TimelineQueryScope, + AgentError, BranchLifecycle, Dispatcher, Names, QueryFilter, QueryOperand, QueryOrder, + QueryOrderKey, QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Result, + Timeline, TimelineQuery, TimelineQueryDirection, TimelineQueryScope, }; use dim_agent_types::*; use futures_util::FutureExt; @@ -1013,9 +1013,7 @@ impl ContextUsage { .await .map_err(ContextOpError::Read)? .ok_or_else(|| ContextOpError::Read(fault("missing initialized usage total")))?; - if let Some(Configuration::Ready { counter }) = &summary.configuration - && counter.configured_tools != Some(true) - { + if let Some(Configuration::Ready { counter }) = &summary.configuration { let model = view .model .as_ref() @@ -1024,6 +1022,9 @@ impl ContextUsage { .current_tools(counter, model.as_ref(), through) .await .map_err(ContextOpError::Read)?; + if fixed.fixed == counter.fixed { + return reading(through, &summary, None); + } let counter_model = model .contribution_counter() .ok_or_else(|| ContextOpError::Read(fault("missing additive counter")))?; @@ -1043,24 +1044,60 @@ impl ContextUsage { reading(through, &summary, None) } + /// The tools the last model request at or before `through` declared. + async fn request_tools(&self, through: u64) -> Result>> { + let reply = self + .timeline + .query(TimelineQuery { + scope: TimelineQueryScope::Branch, + from: None, + through: Some(through), + include_publishing: false, + query: QuerySpec { + filter: Some(QueryFilter::In { + value: QueryOperand::Field { + path: "kind".into(), + }, + values: vec![serde_json::json!("model/call")], + }), + select: QuerySelect::Fields { + fields: vec!["data.request.tools".into()], + }, + group_by: vec![], + pick: None, + order_by: vec![QueryOrder { + key: QueryOrderKey::Position, + direction: TimelineQueryDirection::Descending, + }], + }, + page: Some(QueryPage { + limit: NonZeroU64::MIN, + after: None, + }), + }) + .await?; + let Some(value) = (match &reply.result { + QueryOutput::Rows { rows } => { + rows.first().and_then(|row| match row.values.as_slice() { + [QueryValue::Value { value }] => Some(value.clone()), + _ => None, + }) + } + _ => None, + }) else { + return Ok(None); + }; + Ok(serde_json::from_value::>>(value) + .ok() + .flatten()) + } + async fn current_tools( &self, configuration: &CounterConfiguration, model: &dyn ContextModel, through: u64, ) -> Result { - if configuration.configured_tools.is_none() - && self - .configured_tools(&configuration.event_id, through) - .await? - { - return Ok(DynamicFixed { - configuration: configuration.event_id.clone(), - versions: String::new(), - identity: configuration.request_identity.clone(), - fixed: configuration.fixed, - }); - } let sources = self.registry.sources(); let versions = fingerprint( &sources @@ -1068,6 +1105,17 @@ impl ContextUsage { .map(|source| (&source.key, &source.version)) .collect::>(), )?; + let tools = self + .request_tools(through) + .await? + .unwrap_or_else(|| self.registry.visible_definitions()); + let tools_fingerprint = fingerprint( + &tools + .iter() + .map(|tool| (&tool.name, &tool.description)) + .collect::>(), + )?; + let versions = format!("{versions}:{tools_fingerprint}"); if let Some(cached) = self .dynamic_fixed .lock() @@ -1079,13 +1127,6 @@ impl ContextUsage { { return Ok(cached.clone()); } - let (tools, sources) = self.registry.snapshot(); - let versions = fingerprint( - &sources - .iter() - .map(|source| (&source.key, &source.version)) - .collect::>(), - )?; let mut system = self .fields(&configuration.event_id, through, &["data.system"]) .await?; diff --git a/crates/dim-agent-capabilities/src/defaults.rs b/crates/dim-agent-capabilities/src/defaults.rs index 027f73bfe7..21306ad8a3 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); } @@ -323,6 +332,29 @@ pub fn install_compaction( ); } +/// 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", + )) + }) + } +} + /// Installs `driver` as the Session `ToolHost`. pub fn tool_host(builder: &mut AgentBuilder, driver: Arc) { crate::register_names(builder); diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index b07b480373..08d9d3f1c6 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -149,6 +149,7 @@ impl PublicService for shell_session::ShellSession {} impl PublicService for dyn exec_stop::ExecStop {} impl PublicService for workspace_tools::file_reads::FileReads {} impl PublicService for timeline_tree::BranchLine {} +impl PublicService for tool_registry::ToolRegistry {} impl PublicService for timeline_tree::TreeCommands {} impl PublicService for prompt_sources::PromptSourcesBranch {} impl PublicService for wait::Wait {} diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index e9549f0101..d1a2a7ad93 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_now() == 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/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) }) } diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index 99f7e2777e..1e0a604867 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, @@ -74,6 +78,11 @@ fn current(registry: &ToolRegistry) -> (ToolSetAdoption, Vec> } impl ToolBinding { + /// The mode in force for a step with no open turn. + pub fn effective_mode(&self) -> ToolMode { + self.registry.effective_tool_mode_now() + } + /// Fixes the handlers of `request_id` to the tools its prefix (through /// `through`) adopted, then releases the pins no later prefix declares. pub fn bind( @@ -82,7 +91,8 @@ impl ToolBinding { through: u64, tools: &[ToolDefinition], tool_sources: &[ToolSourceVersion], - ) -> Result<(), String> { + mode: ToolMode, + ) -> Result, String> { let sets = tool_sources .iter() .map(|source| { @@ -96,19 +106,13 @@ impl ToolBinding { }) }) .collect::, _>>()?; - let mut bound = HashMap::new(); - for tool in tools { - 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); - } + let mode = match mode.entry_tool() { + Some(entry) if tools.iter().any(|tool| tool.name == entry) => mode, + _ => ToolMode::Normal, + }; + let (visible, delegated) = project(mode, tools); + self.bind_snapshot(request_id, &visible, &delegated, sets)?; let mut state = self.state.lock().unwrap(); - register(&mut state, request_id, bound, sets)?; if let Some(newest) = state .pins .iter() @@ -118,7 +122,7 @@ impl ToolBinding { { state.pins.retain(|(sequence, _)| *sequence >= newest); } - Ok(()) + Ok(visible) } /// Binds a request whose configuration declares no tool part: declares @@ -127,38 +131,40 @@ 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()) + let (visible, delegated) = project(self.registry.effective_of_mode(mode), tools); + self.bind_snapshot(request_id, &visible, &delegated, sets)?; + Ok(visible) } 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)?; - self.bind_snapshot( - request_id, - settings.tools.as_deref().unwrap_or_default(), - sets, - ) - .map_err(AgentError::InvalidInput)?; + 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) } fn bind_snapshot( &self, request_id: &str, - tools: &[ToolDefinition], + visible: &[ToolDefinition], + delegated: &[ToolDefinition], sets: Vec>, ) -> Result<(), String> { 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 +178,8 @@ 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) } /// The tool a call of `request_id` runs: its definition (for admission) @@ -190,9 +197,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 +223,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(); @@ -246,6 +289,9 @@ impl ToolBinding { let claims: Vec<_> = calls .iter() .filter_map(|call| { + if !snapshot.visible.contains(&call.name) { + return None; + } let tool = snapshot.tools.get(&call.name)?; Some((call.id.clone(), tool.handler.claim(call, context)?)) }) @@ -383,6 +429,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 +439,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 3850714899..32ce062dab 100644 --- a/crates/dim-agent-capabilities/src/tool_registry.rs +++ b/crates/dim-agent-capabilities/src/tool_registry.rs @@ -265,6 +265,11 @@ 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, + /// Serializes the record write and the live replacement of an update. + mode_update: tokio::sync::Mutex<()>, session_id: String, config: Arc, /// Serializes refreshes from read to commit, so an earlier read never @@ -402,6 +407,59 @@ 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() + } + /// 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) + } + /// 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() { + Some(entry) if declared.iter().any(|tool| tool.name == entry) => mode, + _ => ToolMode::Normal, + } + } + /// Holds the update gate across the record write and the live change. + pub async fn lock_mode(&self) -> tokio::sync::MutexGuard<'_, ()> { + self.mode_update.lock().await + } + /// 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; + project(self.effective_of(&declared), &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; + 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> { let sources = self.sources.lock().unwrap(); @@ -850,6 +908,45 @@ 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 dialogue 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" | "goal_update" | "recall"), + } +} + +/// 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(), @@ -930,6 +1027,8 @@ impl DynPlugin for ToolRegistryPlugin { providers: Arc::default(), offered: Mutex::default(), missing: Mutex::default(), + mode: Mutex::new(config.tool_mode), + mode_update: tokio::sync::Mutex::new(()), session_id: identity.session_id.clone(), config: config.clone(), refreshing: Mutex::default(), @@ -988,7 +1087,7 @@ impl DynPlugin for ToolRegistryPlugin { ), Arc::new(ForeignRegistry(registry.clone())), )?; - ctx.provide_at(self.registry.clone(), registry)?; + ctx.provide_at(self.registry.clone(), registry.clone())?; Ok(Effect::Done) }) } @@ -1028,6 +1127,8 @@ mod tests { providers: Arc::default(), offered: Mutex::default(), missing: Mutex::default(), + mode: Mutex::new(ToolMode::Normal), + mode_update: tokio::sync::Mutex::new(()), session_id: "session".into(), config, refreshing: Mutex::default(), @@ -1036,6 +1137,115 @@ 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), + mode_update: tokio::sync::Mutex::new(()), + 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", + "goal_update", + "recall", + "codemode", + "execute", + ]; + assert_eq!( + projected(ToolMode::Normal, &names), + ( + vec!["read", "skill", "ask_user", "goal_update", "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", + "goal_update", + "recall", + "execute" + ] + .into_iter() + .map(String::from) + .collect(), + ) + ); + assert_eq!( + projected(ToolMode::Shell, &names).0, + vec!["ask_user", "goal_update", "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..5222f8e12c --- /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`, `goal_update` 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"), + } + } +} 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/cli.rs b/crates/dim-app-server/src/cli.rs index a69547337b..fd9d8c7365 100644 --- a/crates/dim-app-server/src/cli.rs +++ b/crates/dim-app-server/src/cli.rs @@ -348,6 +348,10 @@ pub fn run_with( .init(); let mut config = ServerConfig { websocket_address: Some(([127, 0, 0, 1], 8787).into()), + tool_modes: vec![ + dim_agent_types::ToolMode::Codemode, + dim_agent_types::ToolMode::Shell, + ], ..Default::default() }; #[cfg(debug_assertions)] diff --git a/crates/dim-app-server/src/collaboration.rs b/crates/dim-app-server/src/collaboration.rs index 823dadc1aa..f7e951992e 100644 --- a/crates/dim-app-server/src/collaboration.rs +++ b/crates/dim-app-server/src/collaboration.rs @@ -324,6 +324,10 @@ impl Collaboration { let mut config = crate::agents::session_config(&host.profile, self.index.session_defaults()); config.cwd = leader.config().cwd.clone(); + config.tool_mode = leader + .session_service::() + .map(|registry| registry.tool_mode()) + .map_err(|error| member_create_failed(error.to_string()))?; config.permission_policy = permission; config.collaboration_role = CollaborationRole::Member; if let Some(model) = inherited { 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..f95f1abc28 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; @@ -93,6 +94,9 @@ pub struct ServerConfig { pub daemon_profile: protocol::DaemonProfile, /// Admission is disabled until the product execution profile is installed. pub session_execution: bool, + /// The tool modes the assembly can serve: `hello.features` advertises each + /// as `session.tool_mode.`. + pub tool_modes: Vec, pub model_catalog: Option>, /// The override `DIM_USER_AGENT` names, read and validated once by the /// process that hosts models and passed to this Server's Aimux part. @@ -150,6 +154,7 @@ impl Default for ServerConfig { session_typescript: None, daemon_profile: protocol::DaemonProfile::Mock, session_execution: true, + tool_modes: vec![], model_catalog: None, user_agent: None, file_roots: vec![], @@ -1684,6 +1689,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"), @@ -1702,6 +1708,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/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..006519b2b1 --- /dev/null +++ b/crates/dim-app-server/src/session_tool_mode.rs @@ -0,0 +1,119 @@ +//! 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)?; + let _gate = tools.lock_mode().await; + 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..939a500733 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", ]); @@ -862,6 +864,17 @@ async fn run_connection( } } if trusted && hub.config().local_execution() { + for mode in &hub.config().tool_modes { + match mode { + dim_agent_types::ToolMode::Codemode => { + features.push("session.tool_mode.codemode") + } + dim_agent_types::ToolMode::Shell => { + features.push("session.tool_mode.shell") + } + dim_agent_types::ToolMode::Normal => {} + } + } features.extend(LOCAL_EXECUTION_METHODS); } if local { diff --git a/crates/dim-app-server/tests/app_server_flow.rs b/crates/dim-app-server/tests/app_server_flow.rs index 812c768a67..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,8 @@ 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"] 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..49a0116e43 --- /dev/null +++ b/crates/dim-app-server/tests/session_tool_mode_flow.rs @@ -0,0 +1,428 @@ +//! 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, + history::HistoryRenderer, + host::{HostFuture, ModelChunk, ModelConnection, ModelDriver, ModelStopReason, ModelStream}, +}; +use dim_agent_runtime::testing::chain_events; +use dim_agent_runtime::{AgentBuilder, AgentConfig, Session}; +use dim_agent_types::{EventKind, ModelRequest, Role, ToolCall, TurnOutcome}; +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, +}; +use tokio_util::sync::CancellationToken; + +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(codemode: bool) -> AgentBuilder { + builder_with_model(codemode, None) +} + +fn builder_with_model(codemode: bool, model: Option>) -> AgentBuilder { + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::install(&mut builder); + if codemode { + dim_codemode::install(&mut builder); + } + match model { + Some(model) => { + defaults::mock_model_hosts_with_model(&mut builder, HistoryRenderer::default(), model) + } + None => defaults::mock_model_hosts(&mut builder), + } + defaults::tool_host(&mut builder, Arc::new(MockTools)); + builder +} + +/// The model calls a tool the request does not declare, then answers. +struct HiddenCallModel; + +impl ModelDriver for HiddenCallModel { + fn invoke( + &self, + request: Arc, + _: ModelConnection, + _: CancellationToken, + ) -> HostFuture<'_, ModelStream> { + let answered = request + .messages + .iter() + .any(|message| message.role == Role::ToolResult); + let chunks = if answered { + vec![ + Ok(ModelChunk::MessageStart { + message_id: "done".into(), + }), + Ok(ModelChunk::Text("done".into())), + Ok(ModelChunk::TextEnd), + Ok(ModelChunk::MessageStop { + message_id: "done".into(), + reason: ModelStopReason::EndTurn, + }), + ] + } else { + vec![ + Ok(ModelChunk::MessageStart { + message_id: "hidden".into(), + }), + Ok(ModelChunk::ToolStart { + id: "h1".into(), + name: "echo".into(), + }), + Ok(ModelChunk::ToolUse(ToolCall { + id: "h1".into(), + name: "echo".into(), + input: serde_json::from_value(json!({"text": "hi"})).expect("echo input"), + })), + Ok(ModelChunk::MessageStop { + message_id: "hidden".into(), + reason: ModelStopReason::ToolUse, + }), + ] + }; + Box::pin(async move { Ok(Box::pin(futures_util::stream::iter(chunks)) as ModelStream) }) + } +} + +async fn launch_with(home: &Home, builder: AgentBuilder) -> RunningServer { + serve(builder, config(home)).await.unwrap() +} + +fn config(home: &Home) -> ServerConfig { + 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(); + 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() + } +} + +async fn launch(home: &Home, codemode: bool) -> RunningServer { + launch_with(home, builder(codemode)).await +} + +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 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 + .query_row( + "SELECT config FROM agent_sessions WHERE session_id = ?1", + [session], + |row| row.get(0), + ) + .unwrap() +} + +#[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, false).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(flavor = "multi_thread", worker_threads = 2)] +async fn create_records_the_operators_choice() { + let home = Home::new(); + let server = launch(&home, false).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" + ); +} + +#[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:?}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_top_level_call_outside_the_mode_is_refused() { + let home = Home::new(); + let server = launch_with( + &home, + builder_with_model(true, Some(Arc::new(HiddenCallModel))), + ) + .await; + let mut client = Client::connect(&server).await; + let created = client + .rpc( + "session.create", + json!({"cwd": home.work(), "toolMode": "codemode", "tools": ["codemode", "echo"]}), + ) + .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 events = chain_events(&live_session(&server, &session), "main", ..) + .await + .unwrap(); + let refused = events.iter().any(|event| { + matches!( + &event.kind, + EventKind::TurnEnd(data) + if matches!( + &data.outcome, + TurnOutcome::Failed { error } + if error.contains("Tool was not offered in this request: echo") + ) + ) + }); + assert!(refused, "the top-level echo call is refused: {events:?}"); +} 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..f346b9c755 100644 --- a/crates/dim-app-server/tests/storage_flow/queue_recovery.rs +++ b/crates/dim-app-server/tests/storage_flow/queue_recovery.rs @@ -1,6 +1,7 @@ use super::*; use dim_agent_runtime::InputSnapshot; use serde_json::json; +use std::sync::Arc; fn builder(store: &Arc) -> AgentBuilder { let mut builder = AgentBuilder::new(AgentConfig::default()); diff --git a/crates/dim-app-server/tests/transport_flow/codemode.rs b/crates/dim-app-server/tests/transport_flow/codemode.rs index 28e57c3471..f52ee76ea2 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); @@ -264,6 +264,65 @@ async fn a_product_style_app_server_runs_codemode_and_writes_child_facts() { expected, "numeric usage matches the actual model request, excluding child execution facts" ); + + let updated = client + .rpc( + "session.tool_mode.update", + json!({"sessionId":session,"mode":"normal"}), + ) + .await; + assert_ok(&updated); + assert_eq!(updated["result"]["effective"], "normal", "{updated}"); + assert_ok( + &client + .rpc( + "session.submit", + json!({"sessionId":session,"branchId":"main","text":"plain"}), + ) + .await, + ); + assert_ok( + &client + .rpc( + "session.idle", + json!({"sessionId":session,"branchId":"main"}), + ) + .await, + ); + let mut request = model.0.lock().unwrap().as_ref().unwrap().as_ref().clone(); + let names: Vec<_> = request + .tools + .as_ref() + .expect("the normal request declares tools") + .iter() + .map(|tool| tool.name.clone()) + .collect(); + assert_eq!(names, ["echo"], "the switch declares only normal's tools"); + let usage = client + .rpc( + "session.context.usage", + json!({"sessionId":session,"branchId":"main"}), + ) + .await; + assert_ok(&usage); + let context = dim_agent_capabilities::history::HistoryRenderer::default() + .context_in( + &loaded, + "main", + usage["result"]["through"].as_u64().unwrap(), + ) + .await + .unwrap(); + request.messages = dim_agent_capabilities::history::context_messages( + &context, + &dim_agent_capabilities::history::project_context_history(&context).unwrap(), + ); + let expected = window_facts(1_000_000, 64., &request).count_tokens(&request); + assert_eq!( + usage["result"]["estimatedInputTokens"].as_f64().unwrap(), + expected, + "a mode-only change reprices the visible declarations" + ); server.shutdown(); server.join().await.unwrap(); } diff --git a/crates/dim-app-server/tests/transport_flow/collaboration.rs b/crates/dim-app-server/tests/transport_flow/collaboration.rs index a7e9b36329..9e16bcc4db 100644 --- a/crates/dim-app-server/tests/transport_flow/collaboration.rs +++ b/crates/dim-app-server/tests/transport_flow/collaboration.rs @@ -1124,6 +1124,13 @@ async fn plugin_tools_off_removes_the_plugin_tool_from_every_session() { .as_str() .unwrap() .to_owned(); + let updated = client + .rpc( + "session.tool_mode.update", + json!({"sessionId": lead, "mode": "codemode"}), + ) + .await; + assert_ok(&updated); say( &mut client, &lead, @@ -1140,6 +1147,31 @@ async fn plugin_tools_off_removes_the_plugin_tool_from_every_session() { returned(&mut client, &lead, &lead_session, 1).await; let member = next_member(&lead_session, 0).await; let member_session = poll("member session", async || agent.get_session(&member)).await; + let member_mode = client + .rpc("session.tool_mode.get", json!({"sessionId": member})) + .await; + assert_eq!( + member_mode["result"]["mode"], "codemode", + "the member inherits the leader's live choice: {member_mode}" + ); + assert_eq!( + member_mode["result"]["effective"], "normal", + "the member falls back when its mount list has no codemode: {member_mode}" + ); + let switched = client + .rpc( + "session.tool_mode.update", + json!({"sessionId": lead, "mode": "normal"}), + ) + .await; + assert_ok(&switched); + let member_after = client + .rpc("session.tool_mode.get", json!({"sessionId": member})) + .await; + assert_eq!( + member_after["result"]["mode"], "codemode", + "a later creator switch leaves the member's choice: {member_after}" + ); let member_tools = model_tools(&member_session).await; assert!( declares(&member_tools, "echo"), 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(); diff --git a/crates/dim-cli/src/configure.rs b/crates/dim-cli/src/configure.rs index af9bb8412c..0815e262a4 100644 --- a/crates/dim-cli/src/configure.rs +++ b/crates/dim-cli/src/configure.rs @@ -10,6 +10,14 @@ use dim_agent_types::ModelPreferences; use serde::Deserialize; use serde_json::json; +/// The tool mode the interface last saved for new Sessions, read from the +/// interface's `config.json` (the Session host carries no UI dependency). +pub(crate) fn saved_tool_mode(home: &std::path::Path) -> Option { + let text = std::fs::read_to_string(home.join("config.json")).ok()?; + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + value.get("tool_mode")?.as_str().map(str::to_owned) +} + #[derive(Deserialize)] struct Configured { outcome: String, diff --git a/crates/dim-cli/src/lib.rs b/crates/dim-cli/src/lib.rs index 64736942ab..2512f50696 100644 --- a/crates/dim-cli/src/lib.rs +++ b/crates/dim-cli/src/lib.rs @@ -587,6 +587,7 @@ pub(crate) async fn session_create_from_options( options: &Options, ) -> Result { let mut params = session_create_params(options); + add_creation_tool_mode(client, options, &mut params); options.creation_startup(&mut params); add_creation_worktree(client, options, &mut params)?; if let Some(preferences) = options.creation_preferences() { @@ -599,6 +600,20 @@ pub(crate) async fn session_create_from_options( /// `session.create.worktree` refuses the member as an unknown field. const WORKTREE_UNSUPPORTED: &str = "This daemon cannot create a Session in a managed worktree; upgrade it or start the Session without --worktree"; +/// Adds the saved tool mode when the daemon serves it. +pub(crate) fn add_creation_tool_mode( + client: &client::Client, + options: &Options, + params: &mut serde_json::Value, +) { + if client.offers("session.create.toolMode") + && let Some(mode) = crate::configure::saved_tool_mode(&options.home) + && matches!(mode.as_str(), "normal" | "codemode" | "shell") + { + params["toolMode"] = serde_json::json!(mode); + } +} + /// Adds the `worktree` member `--worktree` asks for. It is sent only when the /// request asks for one, and only to a daemon whose `hello.features` names /// `session.create.worktree`, because an older daemon rejects it as an diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index 033d354132..3e807a149b 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -204,6 +204,12 @@ pub enum Command { line: String, session: Origin, }, + /// Reads the Session's tool mode for the `/settings` row. + ReadToolMode, + /// Writes the Session's tool mode. + SetToolMode { + mode: String, + }, /// Interrupt the run on the line the key was pressed on, unless the /// Session has changed since (design §14). Stop { @@ -1344,6 +1350,13 @@ pub enum Update { Stopped { error: Option, }, + /// The Session's tool mode, chosen and in force. + ToolMode { + mode: String, + effective: String, + available: Vec, + saved: bool, + }, /// `session.branch_set_default` refused the chosen line: the lines panel /// shows the reason on the line the choice was made on (design §14). LineRefusal { diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index be41670de3..3e1e5a0916 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -168,6 +168,12 @@ impl SessionPort for SessionHost { } } +#[derive(serde::Deserialize)] +struct ToolModeState { + mode: String, + effective: String, +} + impl SessionHost { /// Runs the session on `client`, the connection the composition root /// took from the client tree, composing management text in `language`, @@ -727,6 +733,39 @@ struct CancelNotice { branch_id: String, } +impl Worker { + fn tool_modes(&self) -> Vec { + let mut modes = vec!["normal".to_owned()]; + if self.client.supports(&["session.tool_mode.codemode"]) { + modes.push("codemode".to_owned()); + } + if self.client.supports(&["session.tool_mode.shell"]) { + modes.push("shell".to_owned()); + } + modes + } + + async fn read_tool_mode(&mut self) { + if self.session_id.is_empty() || !self.client.supports(&["session.tool_mode"]) { + return; + } + let params = json!({"sessionId": self.session_id}); + match self + .client + .typed::("session.tool_mode.get", params) + .await + { + Ok(state) => self.send(Update::ToolMode { + mode: state.mode, + effective: state.effective, + available: self.tool_modes(), + saved: false, + }), + Err(error) => self.send(Update::Notice(format!("tool mode: {error}"))), + } + } +} + impl Worker { fn new( options: Options, @@ -876,6 +915,8 @@ impl Worker { object.remove("permissionPolicy"); // Creation-only member: `session.model.preview` denies it. object.remove("worktree"); + // Creation-only member: `session.model.preview` denies it. + object.remove("toolMode"); self.client.typed("session.model.preview", params).await }) .await??; @@ -900,6 +941,7 @@ impl Worker { session_create_from_options(&mut self.client, &self.options).await? } else { let mut params = session_create_params(&self.options); + crate::add_creation_tool_mode(&self.client, &self.options, &mut params); // `session_create_params` contacts no daemon, so the member // `--worktree` asks for is added here; the initial path adds it // in `session_create_from_options`. @@ -2009,6 +2051,28 @@ impl Worker { Command::QueryModels { query, after } => { self.send_models(query, after, 1).await; } + Command::ReadToolMode => self.read_tool_mode().await, + Command::SetToolMode { mode } => { + if !self.session_id.is_empty() && self.client.supports(&["session.tool_mode"]) { + let params = json!({"sessionId": self.session_id, "mode": mode}); + match self + .client + .typed::("session.tool_mode.update", params) + .await + { + Ok(state) => self.send(Update::ToolMode { + mode: state.mode, + effective: state.effective, + available: self.tool_modes(), + saved: true, + }), + Err(error) => { + self.send(Update::Notice(format!("tool mode: {error}"))); + self.read_tool_mode().await; + } + } + } + } Command::ReadIsolation => { if !self.client.supports(&["settings.read", "settings.update"]) { self.send(Update::Isolation(Err( diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index f6c7101910..6bbef13b35 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -911,6 +911,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "Prompts: {error}", + "Tools" => "Werkzeuge", + "Tool mode" => "Werkzeugmodus", + "Normal" => "Normal", + "Code Mode" => "Code-Modus", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index 3292d8b1d8..dd5b657c6b 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -917,6 +917,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "Prompts: {error}", + "Tools" => "Herramientas", + "Tool mode" => "Modo de herramienta", + "Normal" => "Normal", + "Code Mode" => "Modo código", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index b066d6ef27..c833589911 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -907,6 +907,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field} : {error}", "Prompts: {error}" => "Prompts : {error}", + "Tools" => "Outils", + "Tool mode" => "Mode d'outil", + "Normal" => "Normal", + "Code Mode" => "Mode code", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index 6293732781..04037b1d0d 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -887,6 +887,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "Prompt: {error}", + "Tools" => "Alat", + "Tool mode" => "Mode alat", + "Normal" => "Normal", + "Code Mode" => "Mode kode", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index 120662199f..59eea9e470 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -867,6 +867,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}:{error}", "Prompts: {error}" => "プロンプト:{error}", + "Tools" => "ツール", + "Tool mode" => "ツールモード", + "Normal" => "通常", + "Code Mode" => "コードモード", + "Shell" => "シェル", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index f8340d7771..7861057638 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -847,6 +847,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "프롬프트: {error}", + "Tools" => "도구", + "Tool mode" => "도구 모드", + "Normal" => "일반", + "Code Mode" => "코드 모드", + "Shell" => "셸", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index 1c8b9e55ef..2c504d06f8 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -905,6 +905,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "Prompts: {error}", + "Tools" => "Ferramentas", + "Tool mode" => "Modo de ferramenta", + "Normal" => "Normal", + "Code Mode" => "Modo código", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 31406eb63e..e4c61f26c5 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -913,6 +913,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}: {error}", "Prompts: {error}" => "Prompts: {error}", + "Tools" => "Ferramentas", + "Tool mode" => "Modo de ferramenta", + "Normal" => "Normal", + "Code Mode" => "Modo código", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index 4478b25ce7..ed8795c1a5 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -792,6 +792,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}:{error}", "Prompts: {error}" => "提示词:{error}", + "Tools" => "工具", + "Tool mode" => "工具模式", + "Normal" => "普通", + "Code Mode" => "代码模式", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 9db33eaa3b..05e9caf252 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -807,6 +807,11 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "{field}: {error}" => "{field}:{error}", "Prompts: {error}" => "提示詞:{error}", + "Tools" => "工具", + "Tool mode" => "工具模式", + "Normal" => "一般", + "Code Mode" => "程式碼模式", + "Shell" => "Shell", _ => return None, }) } diff --git a/crates/dim-cli/src/ui/settings_panel.rs b/crates/dim-cli/src/ui/settings_panel.rs index b507b3d41e..ad792a69c5 100644 --- a/crates/dim-cli/src/ui/settings_panel.rs +++ b/crates/dim-cli/src/ui/settings_panel.rs @@ -21,6 +21,8 @@ //! │ Permissions │ //! │ Permission Workspace write › │ //! │ Process isolation › │ +//! │ Tools │ +//! │ Tool mode Normal › │ //! │ 1 / 11 · ↑↓ move · enter select · ←→/space change · esc close │ //! ╰──────────────────────────────────────────────╯ //! ``` @@ -54,6 +56,7 @@ pub struct Values { /// `None` is a read that has not happened or failed. pub prompts: [Option; 3], pub permission: String, + pub tool_mode: String, } /// One row: a switch flips in place, a link opens its picker. @@ -74,9 +77,10 @@ pub enum Setting { SkillsPrompt, Permission, Isolation, + ToolMode, } -const ROWS: [(Setting, &str); 15] = [ +const ROWS: [(Setting, &str); 16] = [ (Setting::Theme, "theme"), (Setting::Language, "language"), (Setting::StartupForm, "startup-form"), @@ -92,6 +96,7 @@ const ROWS: [(Setting, &str); 15] = [ (Setting::SkillsPrompt, "skills-prompt"), (Setting::Permission, "permission"), (Setting::Isolation, "isolation"), + (Setting::ToolMode, "tool-mode"), ]; impl Setting { @@ -250,6 +255,8 @@ impl SettingsPanel { row(Setting::Permission, "Permission", link(&values.permission)), row(Setting::Isolation, "Process isolation", link("")), ]); + items.push(Item::heading(t("Tools"))); + items.push(row(Setting::ToolMode, "Tool mode", link(&values.tool_mode))); let mut list = ListPanel::new("Settings", HINT, "", "", "", false).without_filter(); list.set_items(Ok(items), Some(select.id())); list.set_hint(t(hint_for(select)).to_owned()); @@ -285,6 +292,12 @@ impl SettingsPanel { } } + /// Shows the mode a read or write reported. + pub fn set_tool_mode(&mut self, value: &str) { + self.list + .set_detail(Setting::ToolMode.id(), format!("{value} ›")); + } + /// Shows that the prompts source could not be read. pub fn set_prompts_unavailable(&mut self) { self.prompts = [None; 3]; diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 276079dffd..1979834c8f 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -1271,6 +1271,9 @@ struct App { /// it back into the draft. unsent: Option, permission_policy: Option, + tool_mode: String, + tool_mode_effective: String, + tool_mode_available: Vec, /// The main branch's context use. context: Option, /// The first attempt tag of the next `/login` panel, so a closed panel's @@ -1722,6 +1725,9 @@ impl App { initial: None, unsent: None, send_now: None, + tool_mode: "normal".into(), + tool_mode_effective: "normal".into(), + tool_mode_available: vec!["normal".into()], permission_policy: Some(dim_agent_types::PermissionPolicy { preset: dim_agent_types::PermissionPreset::WorkspaceWrite, ..Default::default() @@ -2187,6 +2193,9 @@ impl App { panel.set_policy(None); } self.permission_policy = None; + self.tool_mode = "normal".into(); + self.tool_mode_effective = "normal".into(); + self.tool_mode_available = vec!["normal".into()]; if let Some(Prompt::Settings(panel)) = &self.prompt { self.open_settings(panel.selected()); } @@ -2806,6 +2815,29 @@ impl App { } }, Update::PermissionsUnknown => self.show_permission_unknown(), + Update::ToolMode { + mode, + effective, + available, + saved, + } => { + self.tool_mode = mode.clone(); + self.tool_mode_effective = effective.clone(); + self.tool_mode_available = available; + if saved + && let Some(error) = + crate::ui::config::write(&self.home, "tool_mode", mode.clone().into()) + { + self.notices.push(error); + } + if let Some(Prompt::Settings(panel)) = &mut self.prompt { + panel.set_tool_mode(&tool_mode_row( + &mode, + &effective, + &self.tool_mode_available, + )); + } + } Update::PermissionSelected(preset) => { let label = format!("Permission: {}", crate::permission::name(preset)); let message = crate::ui::config::write( @@ -5146,6 +5178,7 @@ impl App { self.host.send(Command::ReadSuggestionSetting); } self.host.send(Command::ReadPromptSettings); + self.host.send(Command::ReadToolMode); self.open_settings(Setting::Theme); } (Some("recording"), None, None) => { @@ -5188,6 +5221,11 @@ impl App { .as_ref() .map(|setting| setting.document.enabled), prompts: self.prompt_origins(), + tool_mode: tool_mode_row( + &self.tool_mode, + &self.tool_mode_effective, + &self.tool_mode_available, + ), permission: self.permission_policy.as_ref().map_or_else( || "Unavailable".to_owned(), |policy| crate::permission::name(policy.preset).to_owned(), @@ -5226,6 +5264,17 @@ impl App { let panel = ApprovalsPanel::new(self.permission_policy.as_ref()); self.open_prompt(Prompt::Approvals(panel)); } + Setting::ToolMode => { + if !self.session_id.is_empty() { + let next = next_tool_mode(&self.tool_mode); + self.tool_mode = next.to_owned(); + self.host.send(Command::SetToolMode { + mode: next.to_owned(), + }); + } + self.settings_return = None; + self.open_settings(setting); + } Setting::Isolation => { let panel = crate::ui::isolation_panel::IsolationPanel::new(); self.open_prompt(Prompt::Isolation(Box::new(panel))); @@ -9816,6 +9865,34 @@ fn termux_height_only(previous_columns: u16, size: (u16, u16), termux: bool) -> termux && size.0 == previous_columns } +fn next_tool_mode(mode: &str) -> &'static str { + match mode { + "normal" => "codemode", + "codemode" => "shell", + _ => "normal", + } +} + +fn tool_mode_row(chosen: &str, effective: &str, available: &[String]) -> String { + let unavailable = effective != chosen && !available.iter().any(|mode| mode.as_str() == chosen); + let chosen = tool_mode_label(chosen); + let effective = tool_mode_label(effective); + match (unavailable, chosen == effective) { + (true, _) => format!("{chosen} (unavailable) → {effective}"), + (false, true) => chosen, + (false, false) => format!("{chosen} → {effective}"), + } +} + +fn tool_mode_label(mode: &str) -> String { + t(match mode { + "codemode" => "Code Mode", + "shell" => "Shell", + _ => "Normal", + }) + .to_owned() +} + #[cfg(test)] mod tests { use dim_agent_types::ContentBlock; @@ -14602,6 +14679,7 @@ mod tests { app.run_command(command, ""); if command == "settings" { app.handle_input(key(KeyCode::End)); + app.handle_input(key(KeyCode::Up)); if via_permissions { app.handle_input(key(KeyCode::Up)); } 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/docs/architecture/rust-agent/plugins/ContextUsage.md b/docs/architecture/rust-agent/plugins/ContextUsage.md index 90ee7d82ff..c11e126f22 100644 --- a/docs/architecture/rust-agent/plugins/ContextUsage.md +++ b/docs/architecture/rust-agent/plugins/ContextUsage.md @@ -12,7 +12,7 @@ contributions and request calibration under [ContextUsage](../../../design/plugi | `B:Dispatcher` | Observe publication and report owned failures. | | `B:BranchLifecycle` | Start after activation and stop when closing. | | `S:ContextModelHost` | Resolve the additive counter and algorithm. | -| `S:ToolRegistry` | Read current declarations when configuration does not specify tools. | +| `S:ToolRegistry` | Read the live projection as the fallback before the first request declares tools. | ## Events and lifetime @@ -37,7 +37,7 @@ confirmed to retain that projection. A compaction adopted after that projection Current reads use the in-memory totals. Earlier compression cuts seek cumulative numbers using epoch, branch ordinal and source sequence. A missing predecessor makes statistics unavailable until an actual request establishes a new total; no history recount fills that gap. -Current dynamic tools use a small version/identity/fixed-number cache; no handler +The fixed tool cost is the last model request's declarations; before the first request it falls back to the registry's live projection. Current dynamic tools use a small version/identity/fixed-number cache; no handler binding or extra Timeline event is required. New messages are counted once and fixed controls are reused. The first stable projection establishes the same existing request association before invocation, so its provider measurement can calibrate the next request. Settled-output projection is shared with history. Provider calibration uses one Weak reference to the actual numerically verified diff --git a/docs/architecture/rust-agent/plugins/Loop.md b/docs/architecture/rust-agent/plugins/Loop.md index 6e79b410e1..4115bd2114 100644 --- a/docs/architecture/rust-agent/plugins/Loop.md +++ b/docs/architecture/rust-agent/plugins/Loop.md @@ -107,6 +107,13 @@ step's resumption starts. The turn accepts this automatic continuation at most once. An output-limit stop is not a failure of the turn: it ends Completed, and its `step/model-output-end` stays for diagnostics. +### Tool mode + +A request declares the visible set of the Session's live effective mode at +preparation. The mode is Session configuration, not a Timeline fact: a switch +applies to the next request prepared after it, and a request already being +prepared keeps the mode it read. + ### The continuation's tool boundary This continuation declares tools because the failed request ran none of the 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..3d0388152c --- /dev/null +++ b/docs/architecture/rust-agent/plugins/ShellSession.md @@ -0,0 +1,34 @@ +# 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. | +| `S:SessionLifecycle` | Wait for the Session to be published and stop the shell when it closes. | +| `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. diff --git a/docs/architecture/rust-agent/plugins/ToolRegistry.md b/docs/architecture/rust-agent/plugins/ToolRegistry.md index d2f668efbf..a1a23e1a00 100644 --- a/docs/architecture/rust-agent/plugins/ToolRegistry.md +++ b/docs/architecture/rust-agent/plugins/ToolRegistry.md @@ -26,10 +26,31 @@ 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`, `goal_update` 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. + +The operator's update writes the record and replaces the live mode; a +registration is an ordinary source refresh. A request declares the visible set +of the live effective mode. + ## Handler contract A handler is `ToolHandler`. Besides `execute`, it answers three optional diff --git a/docs/design/agent-tool-modes.md b/docs/design/agent-tool-modes.md index eb32053ea4..cf9c3680e4 100644 --- a/docs/design/agent-tool-modes.md +++ b/docs/design/agent-tool-modes.md @@ -1,7 +1,7 @@ # Agent tool modes: normal, codemode and shell Status: Draft. Scope: process (mode availability), Session (the mode and the tool surface), -branch (the mode a turn pins). +branch (the mode its requests read). Issue: [#2135](https://github.com/arcships/dim/issues/2135). Delivery status belongs in the issue. Today the model has one way to act: one tool call per decision, with every tool declared before the @@ -90,13 +90,13 @@ mean something, not a simplification. `codemode` and `shell` declare what the table lists: their entry tool and the extras their mode needs. `codemode` adds `skill`, whose instructions the model reads directly; `shell` has no -program, so it adds `ask_user` and `recall`. `normal` declares the work tools. +program, so it adds `ask_user`, `goal_update` and `recall`. `normal` declares the work tools. | Mode | Declared | A program may call | Hidden | | --- | --- | --- | --- | | `normal` (default) | every tool except `codemode` and `execute` | — | `codemode`, `execute` | | `codemode` | `codemode`, `skill` | every tool except `codemode` | — | -| `shell` | `execute`, `ask_user`, `recall` | — | every other tool | +| `shell` | `execute`, `ask_user`, `goal_update`, `recall` | — | every other tool | - `codemode` loses no reach: its program calls every tool except `codemode`, so images, the web, MCP, lines, agents, schedules, settings and the shell are all available inside a program. @@ -105,73 +105,12 @@ program, so it adds `ask_user` and `recall`. `normal` declares the work tools. are calls, not declarations. - `skill` is declared because the model needs the instructions directly; a program may call it too, but loading them through a program would only return them as data. -- `shell` is the shell, plus `ask_user` and `recall`, because it has no program to carry them. It - cannot load a skill, read an image, call an MCP tool, open a line, start a member, schedule or - manage settings and plugins. Those are the mode's boundary: a task that needs one runs in another - mode. +- `shell` is the shell, plus `ask_user`, `goal_update` and `recall`, because it has no program to + carry them. It cannot load a skill, read an image, call an MCP tool, open a line, start a member, + schedule or manage settings and plugins. Those are the mode's boundary: a task that needs one runs + in another mode. - What each entry tool must provide to carry its mode is §7. -### Goals in shell mode - -`shell` declares no `goal_update`, so a Session whose mode **in force** is `shell` cannot complete -or block a goal. Everything below keys on the mode in force — the `effective` value -`session.tool_mode.get` reports — never on the chosen mode. The one exception is an update, which -hands Goal the pending mode and Goal checks that it would be effective. - -- **Service.** `ToolRegistry` provides the internal Session `ToolModeTransition` service. Its one - operation is `settle(mode, cause)`, with cause `update` or `registration`. Goal registers one - handler in `apply`; the registry removes it with the part's registration when the part unloads or - reloads. With no handler the call succeeds and changes nothing (no active Goal). A failure blocks - the record write for an update and the publish for a registration, and the caller reports it. -- **Update.** `session.tool_mode.update` calls `settle(pending, update)` before the record write and - waits. Goal settles only when that mode would be effective `shell` — its entry tool is in the - callable set — because a chosen `shell` without `execute` runs `normal`. -- **Registration.** When the entry tool registers and makes `shell` effective without an update, - `ToolRegistry` holds the Session's mode gate from before `settle(shell, registration)` through - the publish. The handler takes the mode and cause as data; it does not read the published value. - While the switch runs, an application that is pending does not block the withdrawal or the - pause: both are still delivered, the switch completes, and the first new `shell` request is - prepared only after the pause is applied. An application that completes after the switch pins - `shell`; a `set`/`resume` that waits on the gate is refused after the publish. A failure leaves - the projection at `normal` and records a fault. A withdrawal that removes the entry tool runs - `normal` and does not resume a paused goal. -- **Settle.** The Goal Session part fans out to every branch with an active goal: it writes - `paused` with reason `mode`, a pause input text with a `mode` phrase as an `Append` input, so it - precedes the next turn (Goal state alone does not enter the model context), and withdraws the - input it queued — the `set`/`resume` trigger and any automatic continuation — when the InputQueue - has not applied it. An applied input was already handed over; the settle does not withdraw it. - The applied record carries the mode and the turn keeps it (§4). -- **Order.** The update runs under the Session's mode gate with Goal's settle first; its order and - failure rule are §5's. A Goal failure stops the update before the mode changes. -- **Activation.** `session.goal.set` and `resume` take the same mode gate and check the effective - mode at their commit boundary. A `resume` that arrives after the settle and before the publish - waits on the gate and is refused once `shell` is effective; one that commits before the settle is - paused, and its unapplied trigger and continuation are withdrawn, by the settle. Either - interleaving is safe. -- **Guarantee.** A turn that starts in `shell` after the pause is committed carries the pause text - in its history, and its requests declare no `goal_update`. A failed update leaves the old mode in - force, as above, so a `normal` turn still declares `goal_update`, when it is mounted, while the - goal is paused. -- While `shell` is in force, a new continuation pauses the goal instead of continuing. -- `session.goal.set` and `session.goal.resume` are refused while `shell` is in force, with a named - error; `pause`, `edit`, `clear` and `get` keep working. -- Leaving `shell` does not resume the goal: the operator resumes it explicitly, as Goal already - requires for a paused goal. -- A completed or blocked goal stays as it is. - -Goal's owner states this lifecycle and its acceptance cases in [Goal](plugins/Goal.md); this design -sets the requirement and writes no Goal fact itself. - -Rules that hold in every mode: - -- Approval and Permission are unchanged. Each call is admitted under the called tool's own risk, - including a Code Mode child call; approving `codemode` approves no child. -- Tool sources are unchanged. MCP servers, extension tools and other registered tools still - contribute to the Session's tool set; the mode decides what the model sees and, in `codemode`, - what a program may call. It does not enable or disable a source. -- Apart from the mode control and the Goal control in §8, client surfaces are unchanged. Mention - search (`session.files`), command-output paging, skills, approvals and settings work in every - mode. ## 3. Who owns the mode @@ -182,7 +121,7 @@ may change it behind the operator's back. | Situation | Rule | Why | | --- | --- | --- | | A new Session from a client | starts in the mode the request names, or `normal` when it names none; the client sends the mode it last used | the operator should not re-choose for every Session | -| A running Session | the operator can switch it at any time; an input applied after the switch uses the new mode, a turn already started or already applied keeps its pin (an in-process budget recovery reuses it; a process restart settles the in-flight request), and a call already admitted finishes | otherwise a change of style means abandoning the conversation | +| A running Session | the operator can switch it at any time; the next request prepared after the switch uses the new mode, a request already being prepared keeps the mode it read (an in-process budget recovery reuses it; a process restart settles the in-flight request), and a call already admitted finishes | otherwise a change of style means abandoning the conversation | | A branch (line) | has no mode of its own; every line of a Session runs the Session's mode | a line is the same agent; a line in another mode would hand the agent tools the operator excluded | | A member Session | starts in its creator Session's current mode, and the operator can switch it like any Session | the member is the same agent doing delegated work; the model must not decide how the agent acts | | The model | never chooses or changes a mode | it is the operator's choice of capability | @@ -207,7 +146,7 @@ owns this projection. Three terms: | --- | --- | --- | --- | | `normal` | every tool except `codemode` and `execute` | none | — | | `codemode` | `codemode`, `skill` | every tool except `codemode` | the Session runs `normal` | -| `shell` | `execute`, `ask_user`, `recall` | none | the Session runs `normal` | +| `shell` | `execute`, `ask_user`, `goal_update`, `recall` | none | the Session runs `normal` | - The sets follow §2 and name no other tool: a new tool is declared in `normal`, callable from a `codemode` program and hidden in `shell`, so it needs no edit here. @@ -220,19 +159,13 @@ owns this projection. Three terms: - A Code Mode program discovers and calls exactly the `delegated` set: `tools.list` and `tools.describe` project it, and `tools.call` admits inside it. `codemode` itself is never delegated, so a program cannot nest one. -- The Loop holds the turn's mode. The InputQueue records the effective mode when it applies an - input, at its serial position on the Dispatcher, and the turn — even one deferred for compaction - or recovered after a restart — uses that recorded mode; the applied record carries it, so a - rebuild recovers it. Every request of the turn uses the pin, together with the callable set - ToolBinding pins today. A switch - takes effect with the next applied input, not with the next request, and needs no re-adoption: - the branch's configuration, the version pins and the source sets stay as they are. A request - retried through its own source (an in-process budget recovery) keeps the pin; a process restart - settles the in-flight request as the loop already does and does not reissue it; the request that - follows a tool result keeps the turn's pin. An applied input keeps its mode: a continuation - applied under `normal` finishes under `normal`. A turn that pins `shell` is one whose input was - applied after the live value, and it waits for the committed pause text to be adopted before its - first request; the Dispatcher keeps running while it waits. +- The Loop reads the live effective mode when it prepares a request. The mode is Session + configuration, not a Timeline fact: a switch applies to the next request prepared after it, a + request already being prepared keeps the mode it read, and a request after a tool result reads + again. No re-adoption is needed: the branch's configuration, the version pins and the source sets + stay as they are. A request retried through its own source (an in-process budget recovery) keeps + the mode it read; a process restart settles the in-flight request as the loop already does and + does not reissue it. - A tool that is only delegated never appears in a prompt, a declaration or the usage counter; `skill` is in both sets. - The mount list and an Agent profile's tool list narrow the surface and never widen it. `normal` @@ -261,20 +194,19 @@ The mode is Session configuration; there is no daemon-wide default to maintain. The mode is live for the Session's lifetime: -- `ToolRegistry` holds the Session's current mode, initialised from the configuration. The - InputQueue records it when it applies an input; nothing re-adopts a tool set when it changes. +- `ToolRegistry` holds the Session's current mode, initialised from the configuration. A request + reads it when it is prepared; nothing re-adopts a tool set when it changes. - `session.tool_mode.get` returns `{mode, effective}`: the mode the operator chose and the one in force. A mode whose entry tool is absent stays chosen and is not in force; that is the fallback. - `session.tool_mode.update` runs, in order: Goal settles for the pending mode when it would be - effective `shell` (§2), the record is written, the live value is replaced. A failure before the - record write leaves the mode pair unchanged and a committed Goal pause in place; once the record - is written, a later cancellation keeps the new value stored, so the record and the live value do - not diverge. The pair is advertised as `session.tool_mode`, like `session.language`. + `session.tool_mode.update` writes the record and replaces the live value. A cancellation before + the record write leaves the mode pair unchanged; once the record is written, a later cancellation + keeps the new value stored, so the record and the live value do not diverge. The pair is + advertised as `session.tool_mode`, like `session.language`. - The model has no tool for this; it is a client method only. ```text session.create.toolMode ──▶ SessionConfig.toolMode ──▶ ToolRegistry (live mode) - ├─ a turn pins the mode ──▶ visible ──▶ model request, usage + ├─ a request reads the live mode ──▶ visible ──▶ model request, usage ├─ a top-level call checks `visible` ──▶ admit or refuse └─ a child call checks `delegated` ──▶ admit or refuse session.tool_mode.update ──▶ live mode + stored record @@ -283,10 +215,8 @@ session.create.toolMode ──▶ SessionConfig.toolMode ──▶ ToolRegistry A member Session records the creating Session's current mode when it is created. Switching the creator later does not change it: the member is its own Session with its own operator control. -## 6. Shell mode's tool -The product's local-execution profile does not mount the persistent shell today; `execute` exists -only in the minimal-execution profile, where `ShellTools` takes the Session's single `ToolHost`. +## 6. Shell mode's tool - The product profile mounts `ShellSession` (branch) and the shell tool in every Session, so a `shell` or `codemode` Session can use it. `ShellSession` starts no OS process until its first @@ -324,7 +254,7 @@ are its requirements; the ones marked missing are follow-up work, not part of th `codemode`: -- Discovery and call (`tools.list`, `tools.describe`, `tools.call`) over the turn's pinned set, +- Discovery and call (`tools.list`, `tools.describe`, `tools.call`) over the request's set, everything except `codemode`. Exists. - **Content blocks on return.** A child result can carry image blocks (`read` of an image, an MCP result), and they reach the model only if the return path rebuilds them. When the returned value @@ -397,15 +327,13 @@ there is no default row to set. The picker lists all three modes; `normal` is always available, and `codemode` or `shell` is shown as unavailable when its `hello.features` entry is absent. A switch takes effect from the next -applied input, and the row shows the effective mode, so a mode that fell back to `normal` is not -reported as in force. A client that offers Goal disables `set` and `resume` while `shell` is in -force (the `effective` value) and shows the named refusal otherwise. +request prepared after it, and the row shows the effective mode, so a mode that fell back to `normal` is not +reported as in force. `goal_update` is a dialogue tool, so a goal can be completed or blocked in every mode. ## 9. Compatibility - Stored records: an absent `toolMode` is `normal`; `normal` is omitted when serialized, so the - native store's text form does not change for existing Sessions. The applied input record gains - an optional `toolMode`; a record without it reads as `normal`, the only mode before this feature. + native store's text form does not change for existing Sessions. - A fork copies its source's current configuration and therefore its mode. - The v3 Code Mode gate stays. `excluded_tools` keeps `codemode` out of that Session's callable set, the fallback rule makes the Session `normal`, and a v3 client can neither select nor receive Code @@ -415,12 +343,11 @@ force (the `effective` value) and shows the named refusal otherwise. instead of every adopted tool), the admission split (a child only inside `delegated`), and the outer result rebuilding content blocks instead of serializing the program value as JSON. Its child-event contract is unchanged. -- [Goal](plugins/Goal.md) gains the shell lifecycle in §2, and - [PromptSources](plugins/PromptSources.md) gains the mode-aware environment block. +- [PromptSources](plugins/PromptSources.md) gains the mode-aware environment block. - The remaining contracts gain the mode with the implementation, each by its owner: `SessionConfig.toolMode` in [session access](contracts/session-access.md), the live mode plus projection in [ToolRegistry](../architecture/rust-agent/plugins/ToolRegistry.md), and the turn's - mode pin in [Loop](../architecture/rust-agent/plugins/Loop.md). + mode read in [Loop](../architecture/rust-agent/plugins/Loop.md). - A Session restored from a record that predates this field becomes `normal`, except in the minimal-execution profile, whose host sets `shell` on create and restore (§6). A Session that used the `codemode` tool therefore loses it on upgrade until the operator selects `codemode`. That is @@ -430,7 +357,7 @@ force (the `effective` value) and shows the named refusal otherwise. - Flow: create a Session in each mode (request field; absent = `normal`) and assert the request's declarations: `normal` declares every tool except `codemode` and `execute`; `codemode` declares - `codemode` and `skill`; `shell` declares `execute`, `ask_user` and `recall`. + `codemode` and `skill`; `shell` declares `execute`, `ask_user`, `goal_update` and `recall`. - Flow: in `codemode` mode a top-level call naming `read`, `ask_user` or `execute` is refused as an unknown tool even though the request pinned it for children, and a child call to `codemode` is refused as outside `delegated`. In `shell` mode a top-level call naming `read` is refused. @@ -443,37 +370,19 @@ force (the `effective` value) and shows the named refusal otherwise. `session.question.respond`; its result drives the program and is not duplicated into the model context unless the program returns it. - Flow: switch a running Session in each direction; an input applied after the switch declares the - new visible set, a request after a tool result in the same turn keeps the turn's pin, an - in-process budget recovery keeps its pin, a process restart settles the in-flight request without + new visible set, a request after a tool result reads the live mode again, an in-process budget + recovery keeps the mode it read, a process restart settles the in-flight request without reissuing it, and a call already admitted finishes. -- Flow: a turn whose input is applied but which is deferred for compaction, or recovered after a - restart, uses the mode recorded at application; a switch after the application does not change it. - A turn that pins `shell` waits for the committed pause text to be adopted before its first - request, and the Dispatcher keeps running while it waits. +- Flow: a request deferred for a compaction step, or one built after a restart, reads the live + effective mode when it is prepared. - Flow: fallback — a mode whose entry tool is absent stays chosen in `get` and is reported as not in force; the Session declares the `normal` surface. - Flow: a member created under `codemode` records it; switching the creator leaves the member unchanged. - Flow: restore a record without the field, and fork a Session; both keep `normal` and the source mode respectively, except that the minimal-execution host restores its Sessions as `shell`. -- Flow: a `resume` arriving after the update's settle and before the live publish waits on the mode - gate and is refused because `shell` is effective; one that commits before the settle is paused by - the settle, which withdraws its unapplied trigger and continuation. -- Flow: a registration that makes `shell` effective calls `settle(shell, registration)` before it - publishes; a `resume` that commits before that call is paused and withdrawn, and one that waits on - the gate is refused after the publish. A settle failure keeps the projection at `normal`. -- Flow: a goal with a queued continuation, switched to an effective `shell` before it is applied: - the continuation is withdrawn, the goal pauses (`mode`) with its pause text, and no turn carrying - the `goal_update` instruction starts in `shell`. An input applied before the switch keeps its pin; - one applied after the switch pins `shell` and waits for the pause text before its first request. - A turn that already started finishes under its pin. The same settle runs when `execute` registers - and makes `shell` effective without an update: the registry holds the gate from before the settle - through the publish; a pending application does not block the withdrawal or the pause, and after - the switch it pins `shell` with the pause in its history. The pause is committed before the record - write and the live mode, so a turn that pins `shell` has the pause text in history; a cancelled - update after the pause and before the record write leaves the goal paused and the mode unchanged. - `set`/`resume` are refused while `shell` is in force; a chosen `shell` that runs `normal` (no - `execute`) neither pauses nor refuses; after leaving, the operator resumes the goal. +- Flow: `goal_update` is a dialogue tool like `ask_user` and `recall`: it stays visible in + `shell`, so a goal can be completed or blocked there and a mode switch does not touch Goal state. - Flow: stop a shell task with `session.exec.stop` after switching the Session to `normal`; the route resolves the live `ExecStop` before `BackgroundExec`, and neither answers for a live task from history. The minimal-execution profile's Session runs `shell` and keeps `execute`. @@ -495,61 +404,40 @@ force (the `effective` value) and shows the named refusal otherwise. registry that applies them, not to core infrastructure. - §4 rule 5: no batches. - §4 rule 6: the visible set is exactly what the request declares; no new context path. -- §4 rule 7: parts coordinate through the Session configuration, the registry's read, the Session's - mode gate (a synchronization primitive, not business state), and the internal tool-mode - transition service, where Goal registers its settle handler (§2). The service is in-process and - carries no public face; neither the App Server nor the registry depends on Goal. +- §4 rule 7: parts coordinate through the Session configuration and the registry's read; the + update gate serializes the record write and the live value. - §4 rule 8: no infrastructure change; the product profile's tool wiring changes (§6), while Timeline, Dispatcher, the event envelope, rutis assembly and the Session facades are untouched. - §4 rule 9: the mode is Session configuration, not a Timeline fact, and follows `session.language`: the current value lives in the registry, the durable copy in the stored record. - §7.1 for the live mode: the resource is the value; lifecycle is the Session's; the operations are - `get` and `update`. A cancellation before the record write leaves the mode pair unchanged; a Goal - pause already committed stays. After the record write, the new value stays stored and in force. - Both report the effective mode rather than refusing one. + `get` and `update`. A cancellation before the record write leaves the mode pair unchanged; after + the record write, the new value stays stored and in force. Both report the effective mode rather + than refusing one. - §7.2: no object or resource handle crosses an owner; no new public service, and the mode methods - join the existing Session method face; the parameters are data. The mode gate is a - synchronization primitive, not a service or a value; the tool-mode transition service is an - internal in-process Session service, not a public face. -- [ADR 002](../adr/002-plugin-scope.md) D1: the mode is Session configuration and the pinned mode is - branch state. D2: no wiring module. D3: ToolRegistry keeps no hard dependency on Code Mode; an + join the existing Session method face; the parameters are data. The update gate is a + synchronization primitive, not a service or a value; no new service crosses an owner. +- [ADR 002](../adr/002-plugin-scope.md) D1: the mode is Session configuration, read live when a + request is prepared. D2: no wiring module. D3: ToolRegistry keeps no hard dependency on Code Mode; an absent or excluded `codemode` falls back to `normal`. D4: business configuration, read at creation and changed by its owner's operation. D5: the mode methods take data. ## 12. Requirements raised to mechanism owners Requirements go to other owners: -- **Goal.** Register the settle handler with the internal `ToolModeTransition` service. The - handler receives `(mode, cause)` as data — `update` with the pending mode, `registration` with - `shell` — and settles on every transition to an effective `shell`, before the record write for an - update and before the registry publishes for a registration. It never reads the published value. - Fan out from the Goal Session part to every branch with an active goal: write `paused` (`mode`), a - pause text with a `mode` phrase as an `Append` input, and withdraw the `set`/`resume` trigger and - any continuation the InputQueue has not applied. For the general lifecycle, read the mode in - force, the value `session.tool_mode.get` reports in `effective`, never the chosen mode, and take - the Session's mode gate around `set` and `resume` to re-check the effective mode at their commit - boundary. While `shell` is in force, pause new continuations and refuse `session.goal.set` and - `resume`; leave resumption to the operator after `shell` leaves. The pause text is an `Append` - input committed before the publish, so a turn that pins `shell` has it before its first request's - history cutoff. Its owner carries this into [Goal](plugins/Goal.md). -- **ToolRegistry.** Provide the `ToolModeTransition` service and the Session's mode gate; on a - registration, hold the gate from before `settle(shell, registration)` through the publish, and - keep the projection at `normal` on a failure. While the switch runs, a pending application does - not block the withdrawal or the pause; it is ordered after the switch, so the first new `shell` - request includes the pause. +- **Goal.** No change: `goal_update` is one of the dialogue tools §2 keeps visible in `shell`, so a + goal can be completed or blocked in every mode and a mode switch does not touch Goal state. - **PromptSources.** The environment block follows the surface: while `shell` is in force (the `effective` value) it drops the Windows file-encoding guidance about `read`/`edit`/`write`. Its owner carries this into [PromptSources](plugins/PromptSources.md). -- **Loop.** Record the effective mode when the input is applied, at its serial position, and - recover it from the applied record on a rebuild; hold it for the turn. Adopt a committed pause - text before starting a turn that pins `shell`, and keep the Dispatcher running while the turn - waits. - Its page gains the turn's mode pin. Its owner carries this into +- **Loop.** Read the live effective mode when a request is prepared; a switch applies to the next + request prepared after it. Its page gains that live read. Its owner carries this into [Loop](../architecture/rust-agent/plugins/Loop.md). Everything else stays within the owners that already exist: ToolRegistry projects its own set and -holds the live mode, the Loop holds the turn's mode pin, ToolBinding pins the callable set, -ToolExecution refuses a call outside the turn's sets, ContextUsage counts `visible`, the App Server +holds the live mode, the Loop reads it at preparation, ToolBinding pins the request's callable set, +ToolExecution refuses a call outside the request's sets, ContextUsage counts the request's +declarations, the App Server owns the stored record and the Session methods, and each client owns its control and its remembered choice. diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index ed0dcc1c8e..49b5a60e54 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -970,6 +970,22 @@ A daemon that does not serve `runtime.list` answers `unknown_method`; the panel daemon does not serve runtimes and prints the version, rather than an empty list that reads as "no runtimes". +## Tool mode settings + +`/settings` exposes the `Tool mode` row under Tools. It reads the shown +Session's mode with `session.tool_mode.get` each time the panel opens and +cycles `normal` → `codemode` → `shell` with Enter, writing with +`session.tool_mode.update`. The row shows the chosen mode, and the mode in +force when it falls back, e.g. `Code Mode → Normal`; a mode the daemon does not +advertise is marked `(unavailable)` and keeps the choice while running +`normal` (design +[agent-tool-modes §5](agent-tool-modes.md#5-configuration-creation-and-switching)). + +```text +Tools +Tool mode Code Mode > +``` + ## Process isolation settings `/settings` exposes the `Process isolation` control under Permissions. `/permissions` 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. diff --git a/docs/design/plugins/CodeMode.md b/docs/design/plugins/CodeMode.md index fd6ad89a50..3f59d29c5c 100644 --- a/docs/design/plugins/CodeMode.md +++ b/docs/design/plugins/CodeMode.md @@ -486,3 +486,11 @@ parts required for a Session that must publish only after the tool is registered profile may install the plugin by default once the v4 protocol, TUI/web grouping and the `AgentLoop` rebuild filter in [child tool batches](../appserver/child-tool-batches.md) land. The Session gate keeps `codemode` out of v3 connections even when the plugin is installed. + +## Admission by origin + +A request declares only the mode's visible set. The outer `codemode` call is a +top-level call and must be visible; its program's calls are child calls and may +use only the delegated set. The request's `tools` and the gate's +`tools.list` are the two allowlists; a name outside its own list is refused +before it creates call state. diff --git a/docs/design/plugins/ContextUsage.md b/docs/design/plugins/ContextUsage.md index c18c0bb55d..d5e253c308 100644 --- a/docs/design/plugins/ContextUsage.md +++ b/docs/design/plugins/ContextUsage.md @@ -58,7 +58,7 @@ current.at 是这份累计值对应的来源位置;source_through 是本份结 六类是恢复源。model-start 不是持久进度源;打开输出的标记由请求控制事实按需取得。context/prepare、model/call、context/budget 用于有限实时关联,不读取它们的历史消息数组,不因为这些回调保存统计。 -固定 tools 已在配置中时直接采用它。否则使用原 ToolRegistry 当前声明及 source key/version。集合身份不变直接复用 fixed 数字,不重新序列化工具。读取注册表当前声明的复制成本仍按工具数量计,不冒充零成本;不调用 bind/bind_current。动态集合不产生额外 Timeline 事件。只在内存缓存 configuration ID、source key/version 摘要、实际控制内容身份和固定贡献;source 版本变化但内容相同则复用数字。当前读采用这份固定贡献,并仅采用身份匹配的 provider 基准;重载重新取得当前集合。数字已就绪时,显式 context/configured 变化按原规则保存;尚未就绪时等待实际请求。 +固定 tools 取 boundary 前最近一次 model request 实际声明的集合;还没有请求时回落到原 ToolRegistry 的当前声明。集合身份不变直接复用 fixed 数字,不重新序列化工具。读取注册表当前声明的复制成本仍按工具数量计,不冒充零成本;不调用 bind/bind_current。动态集合不产生额外 Timeline 事件。只在内存缓存 configuration ID、source key/version 摘要、实际控制内容身份和固定贡献;source 版本变化但内容相同则复用数字。当前读采用这份固定贡献,并仅采用身份匹配的 provider 基准;重载重新取得当前集合。数字已就绪时,显式 context/configured 变化按原规则保存;尚未就绪时等待实际请求。 ## 4. 复用已经计算出的数值 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/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() 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..3679ba1fcd 100644 --- a/web/src/features/chat/ChatPage.vue +++ b/web/src/features/chat/ChatPage.vue @@ -1,5 +1,5 @@ + + + + diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index 85587e8207..9dc8518d41 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -76,6 +76,16 @@ const en = { "composer.command.new": "New session", "composer.command.scheduled": "Manage scheduled tasks on the CLI host", "composer.commandKeys": "↑↓ select · Enter confirm · Esc close", + "composer.command.toolMode": "Show or change the session tool mode", + "composer.toolMode.label": "Tool mode", + "composer.toolMode.name.normal": "Normal", + "composer.toolMode.name.codemode": "Code Mode", + "composer.toolMode.name.shell": "Shell", + "composer.toolMode.description.normal": "One tool call per step, with the full tool surface.", + "composer.toolMode.description.codemode": "One program per step; it calls the other tools through code.", + "composer.toolMode.description.shell": "One command per step, run in a persistent shell.", + "composer.toolMode.unavailable": "Not available in this daemon; normal is in force.", + "composer.toolMode.fallback": "The mode's entry tool is not available; normal is in force.", "composer.command.permissions": "Show or change the session permissions", "composer.permission.label": "Permissions", "composer.permission.preset.read-only": "Read only", diff --git a/web/src/i18n/zh-CN.ts b/web/src/i18n/zh-CN.ts index ceadfa06ba..40d214f6fe 100644 --- a/web/src/i18n/zh-CN.ts +++ b/web/src/i18n/zh-CN.ts @@ -81,6 +81,16 @@ const zhCN: Messages = { "composer.command.scheduled": "管理 CLI 主机上的定时任务", "composer.commandKeys": "↑↓ 选择 · Enter 确认 · Esc 关闭", "composer.command.permissions": "查看或修改会话权限", + "composer.command.toolMode": "查看或切换会话工具模式", + "composer.toolMode.label": "工具模式", + "composer.toolMode.name.normal": "普通", + "composer.toolMode.name.codemode": "代码模式", + "composer.toolMode.name.shell": "Shell", + "composer.toolMode.description.normal": "每一步调用一个工具,使用全部工具面。", + "composer.toolMode.description.codemode": "每一步运行一个程序,通过代码调用其他工具。", + "composer.toolMode.description.shell": "每一步执行一条命令,运行在持久 shell 中。", + "composer.toolMode.unavailable": "当前 daemon 不可用;普通模式生效。", + "composer.toolMode.fallback": "该模式的入口工具不可用,普通模式生效。", "composer.permission.label": "权限", "composer.permission.preset.read-only": "只读", "composer.permission.preset.workspace-write": "工作区读写", diff --git a/web/src/rpc/read.ts b/web/src/rpc/read.ts index 746a65bf3e..38e249ff1f 100644 --- a/web/src/rpc/read.ts +++ b/web/src/rpc/read.ts @@ -34,6 +34,8 @@ import type { SessionEvent, SessionSummary, SessionTitle, + ToolMode, + ToolModeState, ToolResult, UserInput, WithdrawResult, @@ -349,6 +351,19 @@ export function readPermissionState(value: unknown): PermissionState { return { version: num(source, "version", at), policy: readPermissionPolicy(source.policy, `${at}.policy`) } } +/** A tool mode as the server names it; anything else is a protocol error. */ +function readMode(value: unknown, at: string): ToolMode { + if (value === "normal" || value === "codemode" || value === "shell") return value + return fail(at, "a tool mode") +} + +/** `session.tool_mode.get` and `.update`: the chosen mode and the mode in force. */ +export function readToolModeState(value: unknown): ToolModeState { + const at = "session.tool_mode" + const source = obj(value, at) + return { mode: readMode(source.mode, `${at}.mode`), effective: readMode(source.effective, `${at}.effective`) } +} + /** `session.permission.update`: the version the new policy is stored under. */ export function readPermissionVersion(value: unknown): number { return num(obj(value, "session.permission.update"), "version", "session.permission.update") diff --git a/web/src/stores/chat.ts b/web/src/stores/chat.ts index 75d0ce194c..5fd0f2476f 100644 --- a/web/src/stores/chat.ts +++ b/web/src/stores/chat.ts @@ -8,9 +8,9 @@ import { ConnectionLost, RpcError } from "../rpc/client" import type { Goal, GoalCall } from "../goal" import { readLoops as readLoopsReply, readStartedLoop, type Loop } from "../loop" import { readUploadedImage } from "../rpc/read" -import { ROOT_BRANCH_ID, type ApprovalDecision, type ApprovalRequest, type DraftAttachments, type FileCandidate, type ModelId, type ModelProgress, type Notification, type PendingQuestion, type PermissionPreset, type ModelRetryProgress, type PermissionPolicy, type PermissionState, type QueuedInput, type QuestionAnswer, type SessionEvent, type SubmitMode, type UserInput, type WithdrawResult } from "../rpc/protocol" +import { ROOT_BRANCH_ID, type ApprovalDecision, type ApprovalRequest, type DraftAttachments, type FileCandidate, type ModelId, type ModelProgress, type Notification, type PendingQuestion, type PermissionPreset, type ModelRetryProgress, type PermissionPolicy, type PermissionState, type QueuedInput, type QuestionAnswer, type SessionEvent, type SubmitMode, type ToolMode, type ToolModeState, type UserInput, type WithdrawResult } from "../rpc/protocol" import { readRevision, readRules } from "../rpc/general-settings" -import { ProtocolError, readAdoptedConfiguration, type AdoptedConfiguration, readAttached, readBranches, readBranchDetail, readDefaultBranch, readPendingInputs, readPendingQuestions, readTurn, readGoal, readTool, readAck, readAttachmentPath, readBranchCreate, readCompactResult, readConfigurationOutcome, readContextUsage, readFileCandidates, readForkedSessionId, readHistory, readDisplayHistory, readModelUpdate, readMemberApproval, readPermissionState, readPermissionVersion, readSessionMethods, readSessionSkills, readWithdrawResult } from "../rpc/read" +import { ProtocolError, readAdoptedConfiguration, type AdoptedConfiguration, readAttached, readBranches, readBranchDetail, readDefaultBranch, readPendingInputs, readPendingQuestions, readTurn, readGoal, readTool, readAck, readAttachmentPath, readBranchCreate, readCompactResult, readConfigurationOutcome, readContextUsage, readFileCandidates, readForkedSessionId, readHistory, readDisplayHistory, readModelUpdate, readMemberApproval, readPermissionState, readPermissionVersion, readSessionMethods, readToolModeState, readSessionSkills, readWithdrawResult } from "../rpc/read" import { useConnectionStore } from "./connection" import { useSessionsStore } from "./sessions" import { useUiStore } from "./ui" @@ -60,6 +60,8 @@ export type SessionView = { permission: PermissionPolicy | undefined /** The version `permission` was published at: the line's last `permission/changed`, so a read that left earlier is stale. */ permissionVersion: number | undefined + /** This Session's tool mode: the chosen one and the one in force. */ + toolMode: ToolModeState | undefined /** The default branch's current goal from its owner. */ goal: Goal | undefined /** Messages queued on the default branch while it runs, oldest first. */ @@ -183,6 +185,7 @@ export const useChatStore = defineStore("chat", () => { methods: [], permission: undefined, permissionVersion: undefined, + toolMode: undefined, goal: undefined, queued: [], model: stored?.model, @@ -1269,6 +1272,22 @@ export const useChatStore = defineStore("chat", () => { return client().call("session.input.withdraw", { sessionId, branchId, inputId, ...(steer === undefined ? {} : { steer }) }, readWithdrawResult) } + /** Reads the Session's tool mode, or leaves it unset when the daemon serves no mode methods. */ + async function loadToolMode(sessionId: string): Promise { + if (!useConnectionStore().supports("session.tool_mode")) return + const state = await client().call("session.tool_mode.get", { sessionId }, readToolModeState).catch(() => undefined) + const view = views[sessionId] + if (state !== undefined && view !== undefined) view.toolMode = state + } + + /** Changes the Session's tool mode and shows the mode that comes into force. */ + async function setToolMode(sessionId: string, mode: ToolMode): Promise { + const state = await client().call("session.tool_mode.update", { sessionId, mode }, readToolModeState) + const view = views[sessionId] + if (view !== undefined) view.toolMode = state + return state + } + /** The named line's policy and version, or undefined when the Session serves no permission method or the read fails. */ async function sessionPermission(sessionId: string, branchId = defaultBranch(sessionId)): Promise { if (!useConnectionStore().supports("session.permission.get")) return undefined @@ -1347,5 +1366,5 @@ export const useChatStore = defineStore("chat", () => { publish(channel) } - return { views, open, resync, receive, ensureLine, loadEarlier, retryLine, retryCentre, submit, stop, createLine, endLine, setDefaultBranch, respond, allowAlways, allowForSession, answerQuestion, compact, usage, fork, writeGoal, startLoop, readLoops, stopLoop, setEffort, setPermission, withdrawInput, searchFiles, sessionSkills, memberApproval, setModel } + return { views, open, resync, receive, ensureLine, loadEarlier, retryLine, retryCentre, submit, stop, createLine, endLine, setDefaultBranch, respond, allowAlways, allowForSession, answerQuestion, compact, usage, fork, writeGoal, startLoop, readLoops, stopLoop, setEffort, setPermission, loadToolMode, setToolMode, withdrawInput, searchFiles, sessionSkills, memberApproval, setModel } }) diff --git a/web/src/stores/sessions.ts b/web/src/stores/sessions.ts index 376073bca7..a9e1564022 100644 --- a/web/src/stores/sessions.ts +++ b/web/src/stores/sessions.ts @@ -49,6 +49,8 @@ export const useSessionsStore = defineStore("sessions", () => { async function create(cwd: string, model: ModelId | undefined): Promise { const params: Record = { cwd } if (model !== undefined) params.model = { provider: model.providerId, modelId: model.modelId } + const mode = localStorage.getItem("dim.toolMode") + if ((mode === "normal" || mode === "codemode" || mode === "shell") && useConnectionStore().supports("session.create.toolMode")) params.toolMode = mode const created = await useConnectionStore().client.call("session.create", params, readCreate) void refresh() return created.sessionId diff --git a/web/tests/chat-input.mjs b/web/tests/chat-input.mjs index 87bda43a7a..e14d6052dd 100644 --- a/web/tests/chat-input.mjs +++ b/web/tests/chat-input.mjs @@ -106,6 +106,8 @@ function mount(t, branchId, questions = [], component, stores = {}, props = {}, views: { session: view }, open() {}, ensureLine() {}, async submit(sessionId, branch, value, attachments, mode) { submissions.push({ sessionId, branch, value, attachments, mode }) }, async stop(sessionId, branch) { globalThis.chatInputStops.push({ sessionId, branch }) }, + async loadToolMode() {}, + async setToolMode() {}, async withdrawInput(sessionId, branch, inputId) { globalThis.chatInputWithdrawals.push({ sessionId, branch, inputId }) return { status: "deleted" } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 20add81bfb..a3583cf85a 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -493,6 +493,8 @@ const PLUGIN_TOOL: &str = "plugin"; /// served a keyed stub adapter and declare it, while the service is cleared /// before the run's own Sessions, which mount the name but do not declare or /// call it, so their judged Timeline carries no source adoption. +/// Tools `RUN_TOOLS` mounts that a default (normal) probe never declares. +const NORMAL_HIDDEN: [&str; 2] = ["codemode", "execute"]; const RUN_TOOLS: &[&str] = &[ "read", "write", @@ -501,6 +503,7 @@ const RUN_TOOLS: &[&str] = &[ "grep", "exec", "exec_stop", + "execute", "agent", "ask_user", "branch", @@ -3699,7 +3702,10 @@ async fn child_drive( Some("the preflight phase is faulted by the test hook".to_owned()), ) } else { - let expected = session_tools(scenario); + let expected: Vec = session_tools(scenario) + .into_iter() + .filter(|name| !NORMAL_HIDDEN.contains(&name.as_str())) + .collect(); match preflight_session( &mut client, params, @@ -17290,7 +17296,7 @@ mod tests { let expected: Vec<&str> = RUN_TOOLS .iter() .copied() - .filter(|name| *name != "web_search") + .filter(|name| *name != "web_search" && !NORMAL_HIDDEN.contains(name)) .collect(); assert_eq!( offered, expected, @@ -20505,8 +20511,13 @@ mod tests { .await .unwrap(); println!("native probe: {} ms", started.elapsed().as_millis()); + let expected: Vec<&str> = RUN_TOOLS + .iter() + .copied() + .filter(|name| !NORMAL_HIDDEN.contains(name)) + .collect(); let names: Vec<&str> = native.iter().map(|(name, _)| name.as_str()).collect(); - for tool in RUN_TOOLS { + for tool in &expected { assert!( names.contains(tool), "the native set declares {tool}: {names:?}" @@ -20514,8 +20525,8 @@ mod tests { } assert_eq!( names.len(), - RUN_TOOLS.len(), - "the native set is the run list: {names:?}" + expected.len(), + "the native set is the run list's normal declarations: {names:?}" ); assert!( !names.contains(&PLUGIN_TOOL),