| 1 | //! Local narrowing for the existing Engine. It grants no authority. |
| 2 | use super::*; |
| 3 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 4 | pub enum EngineHostProfile { |
| 5 | #[default] |
| 6 | Normal, |
| 7 | Acp, |
| 8 | Headless, |
| 9 | Rlm, |
| 10 | Child, |
| 11 | } |
| 12 | impl EngineHostProfile { |
| 13 | pub fn is_acp(self) -> bool { |
| 14 | self == Self::Acp |
| 15 | } |
| 16 | |
| 17 | pub fn is_headless(self) -> bool { |
| 18 | self == Self::Headless |
| 19 | } |
| 20 | } |
| 21 | /// Additional local narrowing on one exact admitted control. Neither request |
| 22 | /// JSON nor persistent configuration can choose it. Inherit preserves the base |
| 23 | /// host's ceiling (including Child); Acp never replaces that base authority. |
| 24 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 25 | pub enum TurnNarrowing { |
| 26 | #[default] |
| 27 | Inherit, |
| 28 | Acp, |
| 29 | } |
| 30 | impl TurnNarrowing { |
| 31 | pub fn is_acp(self) -> bool { |
| 32 | self == Self::Acp |
| 33 | } |
| 34 | pub fn request_fingerprint(self, ordinary: String) -> String { |
| 35 | match self { |
| 36 | Self::Inherit => ordinary, |
| 37 | Self::Acp => codewhale_runtime::hashing::sha256_hex(format!( |
| 38 | "runtime-turn-narrowing\u{1f}acp\u{1f}{ordinary}" |
| 39 | )), |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | impl Engine { |
| 44 | pub(super) fn is_acp_turn(&self) -> bool { |
| 45 | self.host_profile.is_acp() || self.turn_narrowing.is_acp() |
| 46 | } |
| 47 | |
| 48 | pub(super) async fn acp_turn_tool_build( |
| 49 | &mut self, |
| 50 | authority: &TurnAuthority, |
| 51 | route: &TurnRouteContext, |
| 52 | allowed: Option<Vec<String>>, |
| 53 | mcp_access: McpAccess, |
| 54 | ) -> TurnToolBuild { |
| 55 | let ext_enabled = self.config.features.enabled(Feature::ExtensionHost); |
| 56 | let creator_eligible = self.creator_eligible(); |
| 57 | let is_creator = |
| 58 | crate::conversation_modes::is_creator(self.session.agent_preset.as_deref()); |
| 59 | if let Some(attachment) = self |
| 60 | .extension_host |
| 61 | .as_ref() |
| 62 | .filter(|_| ext_enabled || creator_eligible) |
| 63 | { |
| 64 | if ext_enabled { |
| 65 | if attachment.selection_settled() |
| 66 | && (!creator_eligible || !is_creator || attachment.creator_ready()) |
| 67 | { |
| 68 | attachment.sync_in_background(); |
| 69 | } else { |
| 70 | attachment.sync_within(EXTENSION_FIRST_SYNC_WAIT).await; |
| 71 | } |
| 72 | } else if creator_eligible { |
| 73 | if is_creator && !attachment.creator_ready() { |
| 74 | attachment |
| 75 | .sync_creator_within(EXTENSION_FIRST_SYNC_WAIT) |
| 76 | .await; |
| 77 | } else { |
| 78 | attachment.sync_creator_in_background(); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | let mcp = if self.config.features.enabled(Feature::Mcp) { |
| 83 | if mcp_access.may_connect() { |
| 84 | self.wait_for_mcp_boot().await; |
| 85 | let tools = self.mcp_tools().await; |
| 86 | let server_count = match self.mcp_pool.as_ref() { |
| 87 | Some(pool) => pool.lock().await.connected_servers().len(), |
| 88 | None => 0, |
| 89 | }; |
| 90 | McpToolState::Live { |
| 91 | tools, |
| 92 | server_count, |
| 93 | } |
| 94 | } else { |
| 95 | self.passive_mcp_snapshot().await |
| 96 | } |
| 97 | } else { |
| 98 | McpToolState::Disabled |
| 99 | }; |
| 100 | self.acp_tool_build_with_mcp(authority, route, allowed, mcp) |
| 101 | } |
| 102 | |
| 103 | #[cfg(test)] |
| 104 | pub(super) fn acp_tool_build( |
| 105 | &self, |
| 106 | authority: &TurnAuthority, |
| 107 | route: &TurnRouteContext, |
| 108 | allowed: Option<Vec<String>>, |
| 109 | ) -> TurnToolBuild { |
| 110 | self.acp_tool_build_with_mcp(authority, route, allowed, McpToolState::Disabled) |
| 111 | } |
| 112 | |
| 113 | pub(super) fn acp_tool_build_with_mcp( |
| 114 | &self, |
| 115 | authority: &TurnAuthority, |
| 116 | route: &TurnRouteContext, |
| 117 | allowed: Option<Vec<String>>, |
| 118 | mcp: McpToolState, |
| 119 | ) -> TurnToolBuild { |
| 120 | let mut context = self.build_tool_context_for_turn(authority, route); |
| 121 | let requested = self |
| 122 | .api_config |
| 123 | .sandbox_backend |
| 124 | .as_deref() |
| 125 | .is_some_and(|kind| !kind.trim().is_empty() && !kind.eq_ignore_ascii_case("none")); |
| 126 | let backend = codewhale_sandbox::backend::create_backend(&self.api_config) |
| 127 | .ok() |
| 128 | .flatten() |
| 129 | .filter(|backend| { |
| 130 | backend.kind() != codewhale_sandbox::backend::SandboxKind::Unsupported |
| 131 | }) |
| 132 | .map(Arc::from); |
| 133 | let shell = authority.allow_shell |
| 134 | && self.turn_acp_shell_ceiling.unwrap_or(authority.allow_shell) |
| 135 | && authority.mode != AppMode::Plan |
| 136 | && self.api_config.allow_shell() |
| 137 | && self.config.features.enabled(Feature::ShellTool) |
| 138 | && (!requested || backend.is_some()); |
| 139 | context = context.with_shell_policy(if shell { |
| 140 | codewhale_agent_contract::worker_profile::ShellPolicy::Full |
| 141 | } else { |
| 142 | codewhale_agent_contract::worker_profile::ShellPolicy::None |
| 143 | }); |
| 144 | if let Some(backend) = backend { |
| 145 | context = context.with_sandbox_backend(backend); |
| 146 | } |
| 147 | let mut builder = ToolRegistryBuilder::new() |
| 148 | .with_file_tools() |
| 149 | .with_search_tools() |
| 150 | .with_git_tools() |
| 151 | .with_compaction_archive_tools(); |
| 152 | if self.config.features.enabled(Feature::ApplyPatch) { |
| 153 | builder = builder.with_patch_tools(); |
| 154 | } |
| 155 | if shell { |
| 156 | builder = builder.with_foreground_shell_tools(); |
| 157 | } |
| 158 | let mut registry = builder.build(context); |
| 159 | let ext_enabled = self.config.features.enabled(Feature::ExtensionHost); |
| 160 | let creator_eligible = self.creator_eligible(); |
| 161 | let extension_host = self.extension_host.as_ref().filter(|_| ext_enabled); |
| 162 | if let Some(attachment) = self |
| 163 | .extension_host |
| 164 | .as_ref() |
| 165 | .filter(|_| ext_enabled || creator_eligible) |
| 166 | { |
| 167 | attachment.manager().note_native_names(registry.names()); |
| 168 | } |
| 169 | let creator_tools = |
| 170 | if creator_eligible && let Some(attachment) = self.extension_host.as_ref() { |
| 171 | attachment.install_creator_tools(&mut registry) |
| 172 | } else { |
| 173 | Vec::new() |
| 174 | }; |
| 175 | if let Some(overrides) = self |
| 176 | .api_config |
| 177 | .tools |
| 178 | .as_ref() |
| 179 | .and_then(|tools| tools.overrides.as_ref()) |
| 180 | { |
| 181 | for (name, override_cfg) in overrides { |
| 182 | let is_disabled = matches!( |
| 183 | override_cfg, |
| 184 | codewhale_runtime::config::ToolOverride::Disabled |
| 185 | ); |
| 186 | let is_protected_creator = creator_tools |
| 187 | .iter() |
| 188 | .any(|tool| tool.eq_ignore_ascii_case(name)) |
| 189 | || crate::conversation_modes::CREATOR_TOOL_NAMES |
| 190 | .iter() |
| 191 | .any(|tool| tool.eq_ignore_ascii_case(name)) |
| 192 | || name.eq_ignore_ascii_case(crate::extension_host::dsh_broker::ACT_TOOL); |
| 193 | if is_disabled || !is_protected_creator { |
| 194 | let target = creator_tools |
| 195 | .iter() |
| 196 | .map(String::as_str) |
| 197 | .find(|tool| tool.eq_ignore_ascii_case(name)) |
| 198 | .unwrap_or(name); |
| 199 | remove_acp_overridden_builtin(&mut registry, target); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | let plugin_tool_names: HashSet<String> = extension_host |
| 204 | .map(|attachment| attachment.install_tools(&mut registry)) |
| 205 | .unwrap_or_default() |
| 206 | .into_iter() |
| 207 | .collect(); |
| 208 | let extension_tool_names = plugin_tool_names.clone(); |
| 209 | if let Some(overrides) = self |
| 210 | .api_config |
| 211 | .tools |
| 212 | .as_ref() |
| 213 | .and_then(|tools| tools.overrides.as_ref()) |
| 214 | { |
| 215 | for (name, override_cfg) in overrides { |
| 216 | if matches!( |
| 217 | override_cfg, |
| 218 | codewhale_runtime::config::ToolOverride::Disabled |
| 219 | ) && name.eq_ignore_ascii_case(crate::extension_host::dsh_broker::ACT_TOOL) |
| 220 | { |
| 221 | remove_acp_overridden_builtin(&mut registry, name); |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | let mut mcp_tools = if self.child_host.is_none() { |
| 226 | mcp.tools().to_vec() |
| 227 | } else { |
| 228 | Vec::new() |
| 229 | }; |
| 230 | mcp_tools.sort_by(|a, b| a.name.cmp(&b.name)); |
| 231 | let mcp_tool_names: Vec<String> = mcp_tools.iter().map(|tool| tool.name.clone()).collect(); |
| 232 | let allowed = Some( |
| 233 | registry |
| 234 | .names() |
| 235 | .into_iter() |
| 236 | .map(str::to_string) |
| 237 | .chain(mcp_tool_names.iter().cloned()) |
| 238 | .filter(|name| tool_catalog::tool_allowed(allowed.as_deref(), name)) |
| 239 | .collect(), |
| 240 | ); |
| 241 | let mut catalog = self.child_host.as_ref().map_or_else( |
| 242 | || registry.to_api_tools_with_cache(true), |
| 243 | |child| { |
| 244 | child |
| 245 | .authority |
| 246 | .tools_for_model(®istry, &child.authority.agent_type) |
| 247 | }, |
| 248 | ); |
| 249 | for tool in &mut catalog { |
| 250 | if plugin_tool_names.contains(&tool.name) { |
| 251 | tool.defer_loading = Some(false); |
| 252 | } |
| 253 | } |
| 254 | catalog.extend(mcp_tools.into_iter().map(|mut tool| { |
| 255 | tool.defer_loading = Some(false); |
| 256 | tool |
| 257 | })); |
| 258 | let always_load = catalog.iter().map(|tool| tool.name.clone()).collect(); |
| 259 | TurnToolBuild { |
| 260 | surface: ToolSurfacePolicy::new( |
| 261 | registry, |
| 262 | Some(catalog), |
| 263 | authority.mode, |
| 264 | &always_load, |
| 265 | false, |
| 266 | allowed, |
| 267 | self.config.disallowed_tools.clone(), |
| 268 | self.config.max_tool_calls, |
| 269 | tool_catalog::ToolMode::Direct, |
| 270 | ) |
| 271 | .with_extension_tool_names(extension_tool_names), |
| 272 | mcp_tool_names, |
| 273 | mcp, |
| 274 | #[cfg(test)] |
| 275 | subagent_runtime_model: None, |
| 276 | mailbox: None, |
| 277 | plugin_tool_names, |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | fn remove_acp_overridden_builtin(registry: &mut crate::tools::ToolRegistry, tool_name: &str) { |
| 282 | let aliases: &[&str] = match tool_name { |
| 283 | "bash" | "Bash" | "exec_shell" => &["bash", "exec_shell"], |
| 284 | "read" | "write" | "edit" | "File" | "read_file" | "write_file" | "edit_file" => &[ |
| 285 | "read", |
| 286 | "write", |
| 287 | "edit", |
| 288 | "read_file", |
| 289 | "write_file", |
| 290 | "edit_file", |
| 291 | ], |
| 292 | "apply_patch" => &["apply_patch"], |
| 293 | other => { |
| 294 | if let Some(canonical) = crate::conversation_modes::CREATOR_TOOL_NAMES |
| 295 | .iter() |
| 296 | .copied() |
| 297 | .find(|name| name.eq_ignore_ascii_case(other)) |
| 298 | { |
| 299 | registry.remove_tool(canonical); |
| 300 | } else if other.eq_ignore_ascii_case(crate::extension_host::dsh_broker::ACT_TOOL) { |
| 301 | registry.remove_tool(crate::extension_host::dsh_broker::ACT_TOOL); |
| 302 | } |
| 303 | std::slice::from_ref(&tool_name) |
| 304 | } |
| 305 | }; |
| 306 | for alias in aliases { |
| 307 | registry.remove_tool(alias); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | fn fixture(workspace: &std::path::Path) -> (Engine, EngineHandle, TurnRouteContext) { |
| 315 | let api = { |
| 316 | let __cw_config_init_0_0 = Some(true); |
| 317 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 318 | __cw_config_init_0_value.allow_shell = __cw_config_init_0_0; |
| 319 | __cw_config_init_0_value |
| 320 | } |
| 321 | .with_legacy_root(Some("local-acp-profile-fixture".into()), None); |
| 322 | let (mut engine, handle) = Engine::new( |
| 323 | EngineConfig { |
| 324 | workspace: workspace.to_path_buf(), |
| 325 | snapshots_enabled: false, |
| 326 | memory_enabled: false, |
| 327 | subagents_enabled: false, |
| 328 | ..Default::default() |
| 329 | }, |
| 330 | &api, |
| 331 | ); |
| 332 | engine.config.features.disable(Feature::Mcp); |
| 333 | engine.host_profile = EngineHostProfile::Acp; |
| 334 | let route = TurnRouteContext { |
| 335 | provider: codewhale_config::ProviderKind::Deepseek, |
| 336 | model: DEFAULT_TEXT_MODEL.into(), |
| 337 | capabilities: Default::default(), |
| 338 | limits: None, |
| 339 | client: engine.codewhale_client.clone(), |
| 340 | api_config: Box::new(api), |
| 341 | locale_tag: engine.config.locale_tag.clone(), |
| 342 | role_models: HashMap::new(), |
| 343 | auto_model: false, |
| 344 | reasoning_effort: None, |
| 345 | reasoning_effort_auto: false, |
| 346 | }; |
| 347 | (engine, handle, route) |
| 348 | } |
| 349 | fn authority(mode: AppMode, shell: bool) -> TurnAuthority { |
| 350 | TurnAuthority::from_effective_fields(mode, shell, false, false, ApprovalMode::Suggest) |
| 351 | } |
| 352 | #[tokio::test(flavor = "current_thread")] |
| 353 | async fn acp_catalog_and_final_authority_exclude_hidden_runtime_lifecycles() { |
| 354 | let dir = tempfile::tempdir().unwrap(); |
| 355 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 356 | let (engine, _handle, route) = fixture(dir.path()); |
| 357 | let build = engine.acp_tool_build(&authority(AppMode::Agent, false), &route, None); |
| 358 | assert!(build.surface.registry.get("read").is_some()); |
| 359 | for name in [ |
| 360 | "bash", |
| 361 | "Bash", |
| 362 | "exec_shell", |
| 363 | "exec_shell_interact", |
| 364 | "code_execution", |
| 365 | "execute_tools", |
| 366 | "tool_search", |
| 367 | "Task", |
| 368 | "request_user_input", |
| 369 | "rlm", |
| 370 | ] { |
| 371 | assert!(build.surface.registry.get(name).is_none(), "{name}"); |
| 372 | assert!( |
| 373 | !build.surface.catalog.iter().any(|tool| tool.name == name), |
| 374 | "{name}" |
| 375 | ); |
| 376 | } |
| 377 | let unrelated = crate::tools::ToolRegistryBuilder::new() |
| 378 | .with_foreground_shell_tools() |
| 379 | .build(build.surface.registry.context().clone()); |
| 380 | let err = unrelated |
| 381 | .execute_full("bash", serde_json::json!({"command":"printf forbidden"})) |
| 382 | .await |
| 383 | .unwrap_err(); |
| 384 | assert!(matches!(err, ToolError::PermissionDenied { .. })); |
| 385 | } |
| 386 | #[tokio::test(flavor = "current_thread")] |
| 387 | async fn acp_final_cap_rejects_stateful_aliases_and_plan_writes() { |
| 388 | let dir = tempfile::tempdir().unwrap(); |
| 389 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 390 | let (engine, _handle, route) = fixture(dir.path()); |
| 391 | let build = engine.acp_tool_build(&authority(AppMode::Agent, true), &route, None); |
| 392 | for input in [ |
| 393 | serde_json::json!({"command":"sleep 5 &"}), |
| 394 | serde_json::json!({"command":"nohup true"}), |
| 395 | serde_json::json!({"command":"printf x","persist":true}), |
| 396 | serde_json::json!({"command":"printf x","interactive":true}), |
| 397 | serde_json::json!({"action":"start","command":"printf x"}), |
| 398 | ] { |
| 399 | assert!( |
| 400 | build |
| 401 | .surface |
| 402 | .registry |
| 403 | .execute_full("bash", input) |
| 404 | .await |
| 405 | .is_err() |
| 406 | ); |
| 407 | } |
| 408 | let plan = engine.acp_tool_build(&authority(AppMode::Plan, true), &route, None); |
| 409 | assert!( |
| 410 | plan.surface |
| 411 | .registry |
| 412 | .execute_full("write", serde_json::json!({"path":"no.txt","content":"x"})) |
| 413 | .await |
| 414 | .is_err() |
| 415 | ); |
| 416 | assert!(!dir.path().join("no.txt").exists()); |
| 417 | for command in [ |
| 418 | "printf 'a&b'", |
| 419 | "printf a\\&b", |
| 420 | "true && true", |
| 421 | "printf x >&2", |
| 422 | ] { |
| 423 | assert!( |
| 424 | !crate::tools::shell::foreground_command_requests_detach(command), |
| 425 | "{command}" |
| 426 | ); |
| 427 | } |
| 428 | } |
| 429 | #[tokio::test(flavor = "current_thread")] |
| 430 | async fn acp_override_removes_all_file_and_shell_compatibility_aliases() { |
| 431 | let dir = tempfile::tempdir().unwrap(); |
| 432 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 433 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 434 | engine.api_config.tools = Some(codewhale_runtime::config::ToolsConfig { |
| 435 | overrides: Some(HashMap::from([ |
| 436 | ( |
| 437 | "write".into(), |
| 438 | codewhale_runtime::config::ToolOverride::Disabled, |
| 439 | ), |
| 440 | ( |
| 441 | "exec_shell".into(), |
| 442 | codewhale_runtime::config::ToolOverride::Command { |
| 443 | command: "must-never-launch".into(), |
| 444 | args: None, |
| 445 | }, |
| 446 | ), |
| 447 | ])), |
| 448 | ..Default::default() |
| 449 | }); |
| 450 | let build = engine.acp_tool_build(&authority(AppMode::Agent, true), &route, None); |
| 451 | for name in [ |
| 452 | "read", |
| 453 | "write", |
| 454 | "edit", |
| 455 | "read_file", |
| 456 | "write_file", |
| 457 | "edit_file", |
| 458 | "bash", |
| 459 | "Bash", |
| 460 | "exec_shell", |
| 461 | ] { |
| 462 | assert!(build.surface.registry.get(name).is_none(), "{name}"); |
| 463 | } |
| 464 | } |
| 465 | #[tokio::test(flavor = "current_thread")] |
| 466 | async fn ordinary_engine_context_does_not_inherit_acp_narrowing_or_observations() { |
| 467 | let dir = tempfile::tempdir().unwrap(); |
| 468 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 469 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 470 | engine.host_profile = EngineHostProfile::Normal; |
| 471 | assert_eq!( |
| 472 | engine |
| 473 | .build_tool_context_for_turn(&authority(AppMode::Agent, true), &route) |
| 474 | .acp_host, |
| 475 | None |
| 476 | ); |
| 477 | engine.host_profile = EngineHostProfile::Acp; |
| 478 | assert_eq!( |
| 479 | engine |
| 480 | .build_tool_context_for_turn(&authority(AppMode::Plan, true), &route) |
| 481 | .acp_host, |
| 482 | Some(AppMode::Plan) |
| 483 | ); |
| 484 | assert!(matches!( |
| 485 | engine.goal_continuation_if_active(), |
| 486 | GoalContinuationAction::Inactive |
| 487 | )); |
| 488 | } |
| 489 | #[tokio::test(flavor = "current_thread")] |
| 490 | async fn acp_catalogs_keep_concurrent_workspaces_and_foreground_execution_independent() { |
| 491 | let dir = tempfile::tempdir().unwrap(); |
| 492 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 493 | let a = dir.path().join("a"); |
| 494 | let b = dir.path().join("b"); |
| 495 | std::fs::create_dir(&a).unwrap(); |
| 496 | std::fs::create_dir(&b).unwrap(); |
| 497 | std::fs::write(a.join("f.txt"), "workspace-a").unwrap(); |
| 498 | std::fs::write(b.join("f.txt"), "workspace-b").unwrap(); |
| 499 | let (ea, _ha, ra) = fixture(&a); |
| 500 | let (eb, _hb, rb) = fixture(&b); |
| 501 | let ba = ea.acp_tool_build(&authority(AppMode::Agent, true), &ra, None); |
| 502 | let bb = eb.acp_tool_build(&authority(AppMode::Agent, false), &rb, None); |
| 503 | let (oa, ob) = tokio::join!( |
| 504 | ba.surface |
| 505 | .registry |
| 506 | .execute_full("read", serde_json::json!({"path":"f.txt"})), |
| 507 | bb.surface |
| 508 | .registry |
| 509 | .execute_full("read", serde_json::json!({"path":"f.txt"})) |
| 510 | ); |
| 511 | assert!(oa.unwrap().content.contains("workspace-a")); |
| 512 | assert!(ob.unwrap().content.contains("workspace-b")); |
| 513 | assert!(ba.surface.registry.get("bash").is_some()); |
| 514 | assert!(bb.surface.registry.get("bash").is_none()); |
| 515 | let output = ba |
| 516 | .surface |
| 517 | .registry |
| 518 | .execute_full( |
| 519 | "bash", |
| 520 | serde_json::json!({"command":"echo acp-foreground-marker"}), |
| 521 | ) |
| 522 | .await |
| 523 | .unwrap(); |
| 524 | assert!(output.content.contains("acp-foreground-marker")); |
| 525 | } |
| 526 | #[tokio::test(flavor = "current_thread")] |
| 527 | async fn requested_unavailable_external_sandbox_removes_acp_shell_without_fallback() { |
| 528 | let dir = tempfile::tempdir().unwrap(); |
| 529 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 530 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 531 | engine.api_config.sandbox_backend = Some("unsupported-fixture-backend".into()); |
| 532 | let build = engine.acp_tool_build(&authority(AppMode::Agent, true), &route, None); |
| 533 | assert!(build.surface.registry.get("bash").is_none()); |
| 534 | assert!(build.surface.registry.get("Bash").is_none()); |
| 535 | assert_eq!( |
| 536 | build.surface.registry.context().shell_policy, |
| 537 | codewhale_agent_contract::worker_profile::ShellPolicy::None |
| 538 | ); |
| 539 | } |
| 540 | #[test] |
| 541 | fn narrowed_request_fingerprint_keeps_ordinary_historical_bytes_and_separates_acp() { |
| 542 | let historical = codewhale_runtime::hashing::sha256_hex("ordinary canonical payload"); |
| 543 | assert_eq!( |
| 544 | TurnNarrowing::Inherit.request_fingerprint(historical.clone()), |
| 545 | historical |
| 546 | ); |
| 547 | let narrowed = TurnNarrowing::Acp.request_fingerprint(historical.clone()); |
| 548 | assert_ne!(narrowed, historical); |
| 549 | assert_eq!(narrowed, TurnNarrowing::Acp.request_fingerprint(historical)); |
| 550 | } |
| 551 | #[tokio::test(flavor = "current_thread")] |
| 552 | async fn effective_acp_catalog_keeps_normal_base_and_initial_shell_ceiling() { |
| 553 | let dir = tempfile::tempdir().unwrap(); |
| 554 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 555 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 556 | engine.host_profile = EngineHostProfile::Normal; |
| 557 | engine.config.max_steps = 97; |
| 558 | engine.config.goal_max_steps = Some(211); |
| 559 | engine.config.subagents_enabled = true; |
| 560 | engine.turn_narrowing = TurnNarrowing::Acp; |
| 561 | engine.turn_acp_shell_ceiling = Some(false); |
| 562 | let build = engine.acp_tool_build(&authority(AppMode::Agent, true), &route, None); |
| 563 | assert!( |
| 564 | build.surface.registry.get("bash").is_none(), |
| 565 | "later ordinary authority cannot raise the ACP client's initial terminal ceiling" |
| 566 | ); |
| 567 | assert_eq!(engine.host_profile, EngineHostProfile::Normal); |
| 568 | assert_eq!(engine.config.max_steps, 97); |
| 569 | assert_eq!(engine.config.goal_max_steps, Some(211)); |
| 570 | assert!(engine.config.subagents_enabled); |
| 571 | assert_eq!( |
| 572 | engine |
| 573 | .build_tool_context_for_turn(&authority(AppMode::Agent, true), &route) |
| 574 | .acp_host, |
| 575 | Some(AppMode::Agent) |
| 576 | ); |
| 577 | engine.turn_narrowing = TurnNarrowing::Inherit; |
| 578 | engine.turn_acp_shell_ceiling = None; |
| 579 | assert_eq!( |
| 580 | engine |
| 581 | .build_tool_context_for_turn(&authority(AppMode::Agent, true), &route) |
| 582 | .acp_host, |
| 583 | None |
| 584 | ); |
| 585 | } |
| 586 | #[tokio::test(flavor = "current_thread")] |
| 587 | async fn acp_defers_normal_boot_queue_without_losing_its_generation() { |
| 588 | let dir = tempfile::tempdir().unwrap(); |
| 589 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 590 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 591 | engine.host_profile = EngineHostProfile::Normal; |
| 592 | engine.turn_narrowing = TurnNarrowing::Acp; |
| 593 | engine.mcp_boot_generation = Some(1); |
| 594 | engine.mcp_boot_in_flight = true; |
| 595 | engine.session.pending_prefix_change_reason = None; |
| 596 | let (tx, rx) = tokio::sync::mpsc::channel(1); |
| 597 | engine.mcp_boot_rx = Some(rx); |
| 598 | tx.try_send(McpBootUpdate::Progress { |
| 599 | generation: 1, |
| 600 | authority_errors: Arc::new(HashMap::new()), |
| 601 | connection_errors: HashMap::new(), |
| 602 | connecting: vec!["ordinary-pending".into()], |
| 603 | }) |
| 604 | .unwrap(); |
| 605 | let build = engine.acp_tool_build(&authority(AppMode::Agent, false), &route, None); |
| 606 | let mut catalog = build.surface.catalog.clone(); |
| 607 | let mut names = catalog.iter().map(|tool| tool.name.clone()).collect(); |
| 608 | engine |
| 609 | .refresh_boot_mcp_catalog(&build.surface, &mut catalog, &mut names) |
| 610 | .await; |
| 611 | assert_eq!(engine.mcp_boot_rx.as_ref().unwrap().len(), 1); |
| 612 | assert!(engine.session.pending_prefix_change_reason.is_none()); |
| 613 | engine.turn_narrowing = TurnNarrowing::Inherit; |
| 614 | engine |
| 615 | .refresh_boot_mcp_catalog(&build.surface, &mut catalog, &mut names) |
| 616 | .await; |
| 617 | assert_eq!(engine.mcp_boot_rx.as_ref().unwrap().len(), 0); |
| 618 | assert_eq!( |
| 619 | engine.session.pending_prefix_change_reason.as_deref(), |
| 620 | Some("mcp-session-boot") |
| 621 | ); |
| 622 | } |
| 623 | #[tokio::test(flavor = "current_thread")] |
| 624 | async fn real_engine_queued_normal_acp_normal_controls_keep_exact_fifo_profile() { |
| 625 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 626 | let dir = tempfile::tempdir().unwrap(); |
| 627 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 628 | let api = Config::default().with_legacy_root(Some("local-acp-queue-fixture".into()), None); |
| 629 | let model = Arc::new(MockLlmClient::new(vec![ |
| 630 | canned::simple_text_turn("ordinary first"), |
| 631 | canned::simple_text_turn("ACP middle"), |
| 632 | canned::simple_text_turn("ordinary successor"), |
| 633 | ])); |
| 634 | let (mut engine, handle) = Engine::new_with_model_client( |
| 635 | EngineConfig { |
| 636 | workspace: dir.path().to_path_buf(), |
| 637 | snapshots_enabled: false, |
| 638 | memory_enabled: false, |
| 639 | max_steps: 97, |
| 640 | goal_max_steps: Some(211), |
| 641 | subagents_enabled: true, |
| 642 | ..Default::default() |
| 643 | }, |
| 644 | &api, |
| 645 | model.clone(), |
| 646 | ); |
| 647 | engine.config.features.disable(Feature::Mcp); |
| 648 | let message = |content: &str| { |
| 649 | Op::SendMessage(TurnSpec { |
| 650 | profile_constitution: None, |
| 651 | max_output_tokens: None, |
| 652 | content: content.into(), |
| 653 | images: Vec::new(), |
| 654 | mode: AppMode::Agent, |
| 655 | route: Box::new( |
| 656 | resolve_runtime_route_for_identity( |
| 657 | &api, |
| 658 | &api.active_provider_identity().unwrap(), |
| 659 | Some(DEFAULT_TEXT_MODEL), |
| 660 | ) |
| 661 | .unwrap(), |
| 662 | ), |
| 663 | compaction: Box::new(CompactionConfig::default()), |
| 664 | initial_routed_usage: Box::default(), |
| 665 | goal_objective: None, |
| 666 | goal_token_budget: None, |
| 667 | goal_status: GoalStatus::Paused, |
| 668 | reasoning_effort: None, |
| 669 | reasoning_effort_auto: false, |
| 670 | auto_model: false, |
| 671 | allow_shell: false, |
| 672 | trust_mode: false, |
| 673 | auto_approve: false, |
| 674 | approval_mode: ApprovalMode::Suggest, |
| 675 | translation_enabled: false, |
| 676 | allowed_tools: None, |
| 677 | dynamic_tools: Vec::new(), |
| 678 | hook_executor: None, |
| 679 | verbosity: None, |
| 680 | provenance: UserInputProvenance::ExternalUser, |
| 681 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 682 | submission_id: None, |
| 683 | }) |
| 684 | }; |
| 685 | handle.send(message("ordinary first")).await.unwrap(); |
| 686 | handle.send_reserved_acp_op( |
| 687 | handle.tx_op.clone().try_reserve_owned().unwrap(), |
| 688 | message("ACP middle"), |
| 689 | ); |
| 690 | handle.send(message("ordinary successor")).await.unwrap(); |
| 691 | assert_eq!(engine.host_profile, EngineHostProfile::Normal); |
| 692 | assert!( |
| 693 | !engine.is_acp_turn(), |
| 694 | "a queued ACP operation must not narrow the current owner" |
| 695 | ); |
| 696 | let worker = tokio::spawn(Box::pin(engine.run())); |
| 697 | let mut declared_tool_changes = Vec::new(); |
| 698 | tokio::time::timeout(Duration::from_secs(30), async { |
| 699 | let mut completed = 0; |
| 700 | while completed != 3 { |
| 701 | let event = handle |
| 702 | .rx_event |
| 703 | .write() |
| 704 | .await |
| 705 | .recv() |
| 706 | .await |
| 707 | .expect("Engine event"); |
| 708 | match event { |
| 709 | Event::PrefixCacheChange { |
| 710 | changed: true, |
| 711 | tools_changed: true, |
| 712 | pin_reason, |
| 713 | .. |
| 714 | } => declared_tool_changes.push(pin_reason), |
| 715 | Event::TurnComplete { .. } => completed += 1, |
| 716 | _ => {} |
| 717 | } |
| 718 | } |
| 719 | }) |
| 720 | .await |
| 721 | .expect("three actual queued turns"); |
| 722 | assert_eq!( |
| 723 | declared_tool_changes, |
| 724 | ["change:tool_surface", "change:tool_surface"], |
| 725 | "both admitted profile transitions must have attributed prefix changes" |
| 726 | ); |
| 727 | let requests = model.captured_requests(); |
| 728 | assert_eq!(requests.len(), 3); |
| 729 | assert_ne!(requests[0].tools, requests[1].tools); |
| 730 | assert_eq!( |
| 731 | requests[0].tools, requests[2].tools, |
| 732 | "the exact queued ACP control must not narrow either ordinary neighbour" |
| 733 | ); |
| 734 | handle.send(Op::Shutdown).await.unwrap(); |
| 735 | tokio::time::timeout(Duration::from_secs(5), worker) |
| 736 | .await |
| 737 | .unwrap() |
| 738 | .unwrap(); |
| 739 | } |
| 740 | #[tokio::test(flavor = "current_thread")] |
| 741 | async fn acp_override_disables_but_non_disable_keeps_creator_tools() { |
| 742 | let dir = tempfile::tempdir().unwrap(); |
| 743 | let _home = crate::test_support::SealedHome::at(dir.path()); |
| 744 | let (mut engine, _handle, route) = fixture(dir.path()); |
| 745 | let manager = Arc::new(crate::extension_host::ExtensionHostManager::new( |
| 746 | crate::extension_host::ExtensionHostOptions { |
| 747 | root: Some(dir.path().to_path_buf()), |
| 748 | ..Default::default() |
| 749 | }, |
| 750 | )); |
| 751 | manager.register_test_creator_tool("plugin_manager"); |
| 752 | let attachment = manager.attach(Arc::new(codewhale_plugins::PluginRegistry::empty( |
| 753 | dir.path(), |
| 754 | ))); |
| 755 | assert!(attachment.set_creator_demand(true)); |
| 756 | engine.extension_host = Some(attachment); |
| 757 | engine.creator_available = true; |
| 758 | engine.config.features.enable(Feature::PluginCreator); |
| 759 | |
| 760 | let assert_creator_tools_active = |build: &TurnToolBuild, label: &str| { |
| 761 | let act_tool = crate::extension_host::dsh_broker::ACT_TOOL; |
| 762 | assert!( |
| 763 | build.surface.registry.get("plugin_manager").is_some(), |
| 764 | "{label}: plugin_manager missing from registry" |
| 765 | ); |
| 766 | assert!( |
| 767 | build |
| 768 | .surface |
| 769 | .catalog |
| 770 | .iter() |
| 771 | .any(|tool| tool.name == "plugin_manager"), |
| 772 | "{label}: plugin_manager missing from catalog" |
| 773 | ); |
| 774 | assert!( |
| 775 | build.surface.registry.get(act_tool).is_some(), |
| 776 | "{label}: {act_tool} missing from registry" |
| 777 | ); |
| 778 | assert!( |
| 779 | !build |
| 780 | .surface |
| 781 | .catalog |
| 782 | .iter() |
| 783 | .any(|tool| tool.name == act_tool), |
| 784 | "{label}: hidden {act_tool} must stay out of catalog" |
| 785 | ); |
| 786 | }; |
| 787 | |
| 788 | let default_build = engine.acp_tool_build(&authority(AppMode::Agent, false), &route, None); |
| 789 | assert_creator_tools_active(&default_build, "default"); |
| 790 | |
| 791 | engine.api_config.tools = Some(codewhale_runtime::config::ToolsConfig { |
| 792 | overrides: Some(HashMap::from([ |
| 793 | ( |
| 794 | "plugin_manager".into(), |
| 795 | codewhale_runtime::config::ToolOverride::Script { |
| 796 | path: "never.sh".into(), |
| 797 | args: None, |
| 798 | }, |
| 799 | ), |
| 800 | ( |
| 801 | crate::extension_host::dsh_broker::ACT_TOOL.into(), |
| 802 | codewhale_runtime::config::ToolOverride::Command { |
| 803 | command: "never".into(), |
| 804 | args: None, |
| 805 | }, |
| 806 | ), |
| 807 | ])), |
| 808 | ..Default::default() |
| 809 | }); |
| 810 | let protected_build = |
| 811 | engine.acp_tool_build(&authority(AppMode::Agent, false), &route, None); |
| 812 | assert_creator_tools_active(&protected_build, "protected"); |
| 813 | |
| 814 | for overrides in [ |
| 815 | HashMap::from([ |
| 816 | ( |
| 817 | "plugin_manager".into(), |
| 818 | codewhale_runtime::config::ToolOverride::Disabled, |
| 819 | ), |
| 820 | ( |
| 821 | crate::extension_host::dsh_broker::ACT_TOOL.into(), |
| 822 | codewhale_runtime::config::ToolOverride::Disabled, |
| 823 | ), |
| 824 | ]), |
| 825 | HashMap::from([ |
| 826 | ( |
| 827 | "PLUGIN_MANAGER".into(), |
| 828 | codewhale_runtime::config::ToolOverride::Disabled, |
| 829 | ), |
| 830 | ( |
| 831 | "DSH_BROKER_ACT".into(), |
| 832 | codewhale_runtime::config::ToolOverride::Disabled, |
| 833 | ), |
| 834 | ]), |
| 835 | ] { |
| 836 | engine.api_config.tools = Some(codewhale_runtime::config::ToolsConfig { |
| 837 | overrides: Some(overrides), |
| 838 | ..Default::default() |
| 839 | }); |
| 840 | let disabled_build = |
| 841 | engine.acp_tool_build(&authority(AppMode::Agent, false), &route, None); |
| 842 | for name in [ |
| 843 | "plugin_manager", |
| 844 | crate::extension_host::dsh_broker::ACT_TOOL, |
| 845 | ] { |
| 846 | assert!( |
| 847 | disabled_build.surface.registry.get(name).is_none(), |
| 848 | "{name}" |
| 849 | ); |
| 850 | assert!( |
| 851 | !disabled_build |
| 852 | .surface |
| 853 | .catalog |
| 854 | .iter() |
| 855 | .any(|tool| tool.name == name), |
| 856 | "{name}" |
| 857 | ); |
| 858 | } |
| 859 | } |
| 860 | } |
| 861 | } |
| 862 |