| 1 | //! Tool approval system for `DeepSeek` CLI. |
| 2 | //! |
| 3 | //! Hosts the [`ApprovalRequest`] / [`ApprovalView`] pair the engine asks |
| 4 | //! the TUI to present whenever a tool needs human approval, plus the |
| 5 | //! sandbox elevation flow ([`ElevationRequest`] / [`ElevationView`]) that |
| 6 | //! follows a sandbox denial. |
| 7 | //! |
| 8 | //! ## v0.6.7: Codex-style takeover with stakes-based variants (#129) |
| 9 | //! |
| 10 | //! The modal renders as a compact bottom-anchored approval card that preserves |
| 11 | //! transcript context and routes each request to one of two |
| 12 | //! stakes-based variants: |
| 13 | //! |
| 14 | //! - **Benign** (`RiskLevel::Benign`) — read-only ops, MCP discovery, |
| 15 | //! query-only network. A single `Enter` / `1` / `y` approves once; |
| 16 | //! `2` / `a` approves for the session. |
| 17 | //! - **Destructive** (`RiskLevel::Destructive`) — file writes, shell |
| 18 | //! commands that are not proven read-only, patches, MCP actions, |
| 19 | //! unclassified tools, and any "fetch arbitrary content" surface. |
| 20 | //! The approval card keeps the destructive badge and |
| 21 | //! impact summary visible, then lets `Enter` commit the highlighted |
| 22 | //! option or `y` / `a` / `d` commit directly. |
| 23 | //! |
| 24 | //! The decision events emitted upstream are unchanged |
| 25 | //! (`ViewEvent::ApprovalDecision`), so `ui.rs` and the engine handle |
| 26 | //! both variants without modification. Auto-approve / YOLO bypasses |
| 27 | //! happen *before* the view is constructed (see `tui/ui.rs`); this |
| 28 | //! module always assumes the user is being asked. |
| 29 | |
| 30 | use codewhale_config::ToolAskRule; |
| 31 | use codewhale_engine::tools::approval_summary::{ |
| 32 | delegated_authority_fields, param_preview, truncate_string_value, |
| 33 | }; |
| 34 | use codewhale_execpolicy::canonical_action::canonical_action_alias; |
| 35 | use codewhale_localization::{Locale, MessageId, tr}; |
| 36 | #[cfg(test)] |
| 37 | use codewhale_runtime::config::ApprovalDefaultSelection; |
| 38 | use serde_json::Value; |
| 39 | use std::borrow::Cow; |
| 40 | use std::path::Path; |
| 41 | use std::path::PathBuf; |
| 42 | |
| 43 | #[cfg(test)] |
| 44 | use crate::tui::views::{ModalView, ViewAction, ViewEvent}; |
| 45 | #[cfg(test)] |
| 46 | use codewhale_sandbox::SandboxPolicy; |
| 47 | #[cfg(test)] |
| 48 | use crossterm::event::KeyEvent; |
| 49 | |
| 50 | mod ask_rules; |
| 51 | mod elevation; |
| 52 | pub mod policy; |
| 53 | mod previews; |
| 54 | mod view; |
| 55 | |
| 56 | pub use ask_rules::PermissionRuleSavePreview; |
| 57 | #[cfg(test)] |
| 58 | use ask_rules::build_save_preview as build_permission_rule_save_preview; |
| 59 | pub(crate) use ask_rules::format_allow_rules_pattern; |
| 60 | use ask_rules::{SAVE_PREVIEW_MAX_ENTRIES, build_save_preview}; |
| 61 | pub use elevation::{ElevationOption, ElevationRequest, ElevationView}; |
| 62 | #[cfg(test)] |
| 63 | use previews::apply_patch_preview_lines; |
| 64 | pub(crate) use previews::format_shell_command_for_approval; |
| 65 | use previews::{ |
| 66 | docked_prompt_parts, file_write_preview_lines, localize_detail_label, |
| 67 | localize_preview_shell_line, param_text, receipt_subject, |
| 68 | }; |
| 69 | // Keep the existing module path even though production callers only construct |
| 70 | // `ApprovalView`; approval characterization tests inspect its typed options. |
| 71 | #[allow(unused_imports)] |
| 72 | pub use view::ApprovalOption; |
| 73 | pub use view::ApprovalView; |
| 74 | pub(crate) use view::{ENTER_ARMING_DELAY, ENTER_QUIET_GAP}; |
| 75 | |
| 76 | pub use policy::{ApprovalStakes, ToolCategory, classify_stakes, get_tool_category_for_call}; |
| 77 | |
| 78 | use codewhale_engine::core::authority::{RiskLevel, classify_risk}; |
| 79 | |
| 80 | /// User's decision for a pending approval |
| 81 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 82 | pub enum ReviewDecision { |
| 83 | /// Execute this tool once |
| 84 | Approved, |
| 85 | /// Approve and don't ask again for this tool type this session |
| 86 | ApprovedForSession, |
| 87 | /// Reject the tool execution |
| 88 | Denied, |
| 89 | /// Abort the entire turn |
| 90 | Abort, |
| 91 | } |
| 92 | |
| 93 | /// The agent a child approval card belongs to (approvals C1). `None` on the |
| 94 | /// parent's own cards. |
| 95 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 96 | pub struct ApprovalOwner { |
| 97 | pub agent_id: String, |
| 98 | /// Stable user-facing agent label (`App::ensure_agent_label`). |
| 99 | pub label: String, |
| 100 | /// Fleet role label, when the roster knows the agent yet. |
| 101 | pub role: Option<String>, |
| 102 | } |
| 103 | |
| 104 | /// Request for user approval of a tool execution |
| 105 | #[derive(Debug, Clone)] |
| 106 | pub struct ApprovalRequest { |
| 107 | /// Unique ID for this tool use |
| 108 | pub id: String, |
| 109 | /// Tool being executed |
| 110 | pub tool_name: String, |
| 111 | /// Human-readable tool description from the engine |
| 112 | pub description: String, |
| 113 | /// One plain sentence naming what the call does ("Search the web for |
| 114 | /// 'espresso'", "Write notes/espresso.md"), built from the tool name and |
| 115 | /// its arguments only (E6). The card leads with it. |
| 116 | pub summary: String, |
| 117 | /// Workspace the call runs in; card paths are shown relative to it. |
| 118 | pub workspace: PathBuf, |
| 119 | /// Tool category |
| 120 | pub category: ToolCategory, |
| 121 | /// Stakes-based routing for the compact approval card |
| 122 | pub risk: RiskLevel, |
| 123 | /// Derived impact summary for the approval prompt |
| 124 | pub impacts: Vec<String>, |
| 125 | /// Tool parameters (for display) |
| 126 | pub params: Value, |
| 127 | /// Exact-argument fingerprint, used to scope *denials* (#1617). |
| 128 | pub approval_key: String, |
| 129 | /// Lossy / arity-aware fingerprint, used to scope *approvals* so an |
| 130 | /// "approve for session" covers later flag variants (v0.8.37). |
| 131 | pub approval_grouping_key: String, |
| 132 | /// The model's explanation of intent before invoking write tools (#2381). |
| 133 | /// Displayed in the approval view so users understand *why* the change |
| 134 | /// is being made before reviewing *what* will change. |
| 135 | pub intent_summary: Option<String>, |
| 136 | /// Ask-only persistent rules that can be saved with the approval. |
| 137 | pub persistent_ask_rules: Vec<ToolAskRule>, |
| 138 | /// Exact repo-scoped allow rules available for safe approval requests. |
| 139 | pub persistent_allow_rules: Vec<ToolAskRule>, |
| 140 | /// The agent that raised this request, when it is a child's card. |
| 141 | pub owner: Option<ApprovalOwner>, |
| 142 | /// This file write asks only because the folder has no git repository; |
| 143 | /// in one it would run without a card. The card says so in one line. |
| 144 | pub asks_without_git: bool, |
| 145 | stakes: ApprovalStakes, |
| 146 | } |
| 147 | |
| 148 | /// Key approval details rendered prominently in the approval card. |
| 149 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 150 | pub struct ApprovalDetail { |
| 151 | pub label: String, |
| 152 | pub value: String, |
| 153 | /// Preformatted shell lines for commands that benefit from safe wrapping |
| 154 | /// or a compact write-file preview. `value` remains the original command. |
| 155 | pub shell_lines: Option<Vec<String>>, |
| 156 | pub is_preview: bool, |
| 157 | } |
| 158 | |
| 159 | impl ApprovalRequest { |
| 160 | /// Mechanical repo-law asks are a distinct authority boundary, not an |
| 161 | /// ordinary risk prompt. The engine stamps this stable prefix when a |
| 162 | /// `.codewhale/constitution.json` ask rule forces review. |
| 163 | #[must_use] |
| 164 | pub fn is_repo_law_prompt(&self) -> bool { |
| 165 | codewhale_engine::core::authority::persistent_rules::is_repo_law_prompt(&self.description) |
| 166 | } |
| 167 | |
| 168 | /// Presentation stakes for this request (see [`ApprovalStakes`]). |
| 169 | #[must_use] |
| 170 | pub fn stakes(&self) -> ApprovalStakes { |
| 171 | self.stakes |
| 172 | } |
| 173 | |
| 174 | #[cfg(test)] |
| 175 | pub fn new( |
| 176 | id: &str, |
| 177 | tool_name: &str, |
| 178 | description: &str, |
| 179 | params: &Value, |
| 180 | approval_key: &str, |
| 181 | ) -> Self { |
| 182 | Self::new_with_intent( |
| 183 | id, |
| 184 | tool_name, |
| 185 | description, |
| 186 | params, |
| 187 | approval_key, |
| 188 | None, |
| 189 | Path::new("/workspace"), |
| 190 | ) |
| 191 | } |
| 192 | |
| 193 | pub fn new_with_intent( |
| 194 | id: &str, |
| 195 | tool_name: &str, |
| 196 | description: &str, |
| 197 | params: &Value, |
| 198 | approval_key: &str, |
| 199 | intent_summary: Option<&str>, |
| 200 | workspace: &Path, |
| 201 | ) -> Self { |
| 202 | let semantic_tool_name = canonical_action_alias(tool_name, params); |
| 203 | let category = get_tool_category_for_call(tool_name, params); |
| 204 | let risk = classify_risk(tool_name, category, params); |
| 205 | let approval_grouping_key = |
| 206 | codewhale_engine::tools::approval_cache::build_approval_grouping_key(tool_name, params) |
| 207 | .0; |
| 208 | let stakes = classify_stakes(tool_name, category, risk, params); |
| 209 | let codewhale_engine::core::authority::persistent_rules::PersistentRuleCandidates { |
| 210 | ask: persistent_ask_rules, |
| 211 | allow: persistent_allow_rules, |
| 212 | } = codewhale_engine::core::authority::persistent_rules::persistent_rule_candidates( |
| 213 | tool_name, |
| 214 | params, |
| 215 | description, |
| 216 | workspace, |
| 217 | ); |
| 218 | |
| 219 | Self { |
| 220 | id: id.to_string(), |
| 221 | tool_name: tool_name.to_string(), |
| 222 | description: description.to_string(), |
| 223 | summary: codewhale_engine::tools::approval_summary::approval_summary( |
| 224 | tool_name, |
| 225 | params, |
| 226 | Some(workspace), |
| 227 | ), |
| 228 | workspace: workspace.to_path_buf(), |
| 229 | category, |
| 230 | risk, |
| 231 | impacts: build_impact_summary(Locale::En, semantic_tool_name, category, params), |
| 232 | params: params.clone(), |
| 233 | approval_key: approval_key.to_string(), |
| 234 | approval_grouping_key, |
| 235 | intent_summary: intent_summary.and_then(|summary| { |
| 236 | let summary = summary.trim(); |
| 237 | if summary.is_empty() { |
| 238 | None |
| 239 | } else { |
| 240 | Some(summary.to_string()) |
| 241 | } |
| 242 | }), |
| 243 | persistent_ask_rules, |
| 244 | persistent_allow_rules, |
| 245 | owner: None, |
| 246 | asks_without_git: false, |
| 247 | stakes, |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /// Format parameters for display (truncated) |
| 252 | pub fn params_display(&self) -> String { |
| 253 | let truncated = truncate_params_value(&self.params, 200); |
| 254 | serde_json::to_string(&truncated).unwrap_or_else(|_| truncated.to_string()) |
| 255 | } |
| 256 | |
| 257 | /// The plain summary in `locale` (E6, experience mark 4): the same |
| 258 | /// sentence the English card leads with, translated around the verbatim |
| 259 | /// command, path or query. |
| 260 | #[must_use] |
| 261 | pub fn summary_for_locale(&self, locale: Locale) -> String { |
| 262 | if locale == Locale::En { |
| 263 | return self.summary.clone(); |
| 264 | } |
| 265 | codewhale_engine::tools::approval_summary::approval_summary_in( |
| 266 | locale, |
| 267 | &self.tool_name, |
| 268 | &self.params, |
| 269 | Some(&self.workspace), |
| 270 | ) |
| 271 | } |
| 272 | |
| 273 | pub(crate) fn review_failure(&self) -> Option<(&str, &str)> { |
| 274 | self.description |
| 275 | .strip_prefix("Auto-Review could not finish (")? |
| 276 | .split_once("); please decide.") |
| 277 | } |
| 278 | |
| 279 | fn localized_review_failure(locale: Locale, reason: &str) -> Cow<'_, str> { |
| 280 | let id = match reason { |
| 281 | "timed out" => MessageId::BackgroundOutcomeTimedOut, |
| 282 | "transport error" => MessageId::ApprovalReviewTransport, |
| 283 | "unparseable answer" => MessageId::ApprovalReviewUnparseable, |
| 284 | "incomplete answer" => MessageId::ApprovalReviewIncomplete, |
| 285 | "review context over budget" => MessageId::ApprovalReviewOverBudget, |
| 286 | _ => return Cow::Borrowed(reason), |
| 287 | }; |
| 288 | tr(locale, id) |
| 289 | } |
| 290 | |
| 291 | pub fn description_for_locale(&self, locale: Locale) -> String { |
| 292 | if let Some((reason, detail)) = self.review_failure() { |
| 293 | let reason = Self::localized_review_failure(locale, reason); |
| 294 | let mut description = |
| 295 | tr(locale, MessageId::ApprovalReviewFallback).replace("{reason}", &reason); |
| 296 | description.push_str(detail); |
| 297 | return description; |
| 298 | } |
| 299 | match locale { |
| 300 | Locale::En if self.category == ToolCategory::Shell => { |
| 301 | "Review the command before it runs.".to_string() |
| 302 | } |
| 303 | Locale::En => self.description.clone(), |
| 304 | _ => localized_description(self.category, locale), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | pub fn impacts_for_locale(&self, locale: Locale) -> Vec<String> { |
| 309 | if locale == Locale::En { |
| 310 | return self.impacts.clone(); |
| 311 | } |
| 312 | let semantic_tool_name = canonical_action_alias(&self.tool_name, &self.params); |
| 313 | build_impact_summary(locale, semantic_tool_name, self.category, &self.params) |
| 314 | } |
| 315 | |
| 316 | #[must_use] |
| 317 | pub fn can_save_ask_rule(&self) -> bool { |
| 318 | !self.persistent_ask_rules.is_empty() |
| 319 | } |
| 320 | |
| 321 | #[must_use] |
| 322 | pub fn can_save_allow_rule(&self) -> bool { |
| 323 | !self.persistent_allow_rules.is_empty() |
| 324 | && self.stakes() != ApprovalStakes::Critical |
| 325 | && !self.is_repo_law_prompt() |
| 326 | } |
| 327 | |
| 328 | #[must_use] |
| 329 | pub fn ask_rule_save_preview(&self) -> Option<PermissionRuleSavePreview> { |
| 330 | build_save_preview(&self.persistent_ask_rules, SAVE_PREVIEW_MAX_ENTRIES) |
| 331 | } |
| 332 | |
| 333 | #[must_use] |
| 334 | pub fn allow_rule_save_preview(&self) -> Option<PermissionRuleSavePreview> { |
| 335 | self.can_save_allow_rule().then(|| { |
| 336 | build_save_preview(&self.persistent_allow_rules, SAVE_PREVIEW_MAX_ENTRIES) |
| 337 | .expect("eligible allow rules are non-empty") |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | pub(crate) fn docked_parts(&self, locale: Locale) -> (String, String, bool) { |
| 342 | let parts = docked_prompt_parts( |
| 343 | &self.tool_name, |
| 344 | &self.params, |
| 345 | &self.workspace, |
| 346 | &self.summary, |
| 347 | ); |
| 348 | let verb = match self.review_failure() { |
| 349 | Some((reason, _)) => format!( |
| 350 | "{} ({}) · {}", |
| 351 | tr(locale, MessageId::ConfigChoiceAutoReview), |
| 352 | Self::localized_review_failure(locale, reason), |
| 353 | parts.verb |
| 354 | ), |
| 355 | None => parts.verb, |
| 356 | }; |
| 357 | (verb, parts.subject, parts.outside_workspace) |
| 358 | } |
| 359 | |
| 360 | #[must_use] |
| 361 | pub(crate) fn receipt_subject(&self) -> String { |
| 362 | receipt_subject( |
| 363 | &self.tool_name, |
| 364 | &self.params, |
| 365 | &self.workspace, |
| 366 | &self.summary, |
| 367 | ) |
| 368 | } |
| 369 | |
| 370 | #[must_use] |
| 371 | #[cfg(test)] |
| 372 | pub fn ask_rule_preview(&self) -> Option<String> { |
| 373 | if self.persistent_ask_rules.is_empty() { |
| 374 | return None; |
| 375 | } |
| 376 | let permissions = codewhale_config::PermissionsToml { |
| 377 | rules: self.persistent_ask_rules.clone(), |
| 378 | }; |
| 379 | toml::to_string_pretty(&permissions).ok() |
| 380 | } |
| 381 | |
| 382 | /// Extract the most important params for the approval card. |
| 383 | #[must_use] |
| 384 | pub fn prominent_detail_items(&self, locale: Locale) -> Vec<ApprovalDetail> { |
| 385 | let semantic_tool_name = canonical_action_alias(&self.tool_name, &self.params); |
| 386 | build_prominent_details(semantic_tool_name, self.category, &self.params) |
| 387 | .into_iter() |
| 388 | .map(|mut detail| { |
| 389 | if matches!(detail.label.as_str(), "File" | "Path" | "Dir") { |
| 390 | detail.value = |
| 391 | codewhale_util::utils::workspace_relative(&detail.value, &self.workspace); |
| 392 | } |
| 393 | detail.label = localize_detail_label(&detail.label, locale).to_string(); |
| 394 | if detail.is_preview |
| 395 | && let Some(lines) = detail.shell_lines.as_mut() |
| 396 | { |
| 397 | for line in lines.iter_mut() { |
| 398 | *line = localize_preview_shell_line(semantic_tool_name, line, locale) |
| 399 | .to_string(); |
| 400 | } |
| 401 | detail.value = lines.join("\n"); |
| 402 | } |
| 403 | detail |
| 404 | }) |
| 405 | .collect() |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | pub use codewhale_engine::mcp::connected_app_server; |
| 410 | |
| 411 | fn mcp_target_hint(tool_name: &str) -> Option<String> { |
| 412 | let remainder = tool_name.strip_prefix("mcp_")?; |
| 413 | if remainder.is_empty() { |
| 414 | None |
| 415 | } else { |
| 416 | Some(remainder.to_string()) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | fn impact_line(locale: Locale, id: MessageId, value: String) -> String { |
| 421 | tr(locale, id).replace("{value}", &value) |
| 422 | } |
| 423 | |
| 424 | fn build_impact_summary( |
| 425 | locale: Locale, |
| 426 | tool_name: &str, |
| 427 | category: ToolCategory, |
| 428 | params: &Value, |
| 429 | ) -> Vec<String> { |
| 430 | let mut impacts = match category { |
| 431 | ToolCategory::Safe => { |
| 432 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactSafe).into_owned()]; |
| 433 | if let Some(path) = param_preview(params, &["path", "ref_id", "uri"], 72) { |
| 434 | impacts.push(impact_line(locale, MessageId::ApprovalImpactReads, path)); |
| 435 | } |
| 436 | impacts |
| 437 | } |
| 438 | ToolCategory::FileWrite => { |
| 439 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactFileWrite).into_owned()]; |
| 440 | if let Some(path) = param_preview(params, &["path", "target", "destination"], 72) { |
| 441 | impacts.push(impact_line(locale, MessageId::ApprovalImpactWrites, path)); |
| 442 | } |
| 443 | impacts |
| 444 | } |
| 445 | ToolCategory::Shell => { |
| 446 | vec![tr(locale, MessageId::ApprovalImpactShell).into_owned()] |
| 447 | } |
| 448 | ToolCategory::Network => { |
| 449 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactNetwork).into_owned()]; |
| 450 | if let Some(target) = |
| 451 | param_preview(params, &["url", "q", "query", "location", "repo"], 96) |
| 452 | { |
| 453 | impacts.push(impact_line(locale, MessageId::ApprovalImpactTarget, target)); |
| 454 | } |
| 455 | impacts |
| 456 | } |
| 457 | ToolCategory::McpRead => { |
| 458 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactMcpRead).into_owned()]; |
| 459 | if let Some(target) = mcp_target_hint(tool_name) { |
| 460 | impacts.push(impact_line( |
| 461 | locale, |
| 462 | MessageId::ApprovalImpactConnectedApp, |
| 463 | target, |
| 464 | )); |
| 465 | } |
| 466 | impacts |
| 467 | } |
| 468 | ToolCategory::McpAction => { |
| 469 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactMcpAction).into_owned()]; |
| 470 | if let Some(target) = mcp_target_hint(tool_name) { |
| 471 | impacts.push(impact_line( |
| 472 | locale, |
| 473 | MessageId::ApprovalImpactConnectedApp, |
| 474 | target, |
| 475 | )); |
| 476 | } |
| 477 | impacts |
| 478 | } |
| 479 | ToolCategory::Agent if tool_name == "workflow" && locale == Locale::En => { |
| 480 | // #4126: elevated Workflow plan card — goal, children, capability flags, budget. |
| 481 | codewhale_engine::tools::workflow_plan_approval::analyze_workflow_plan_approval(params) |
| 482 | .approval_impacts() |
| 483 | } |
| 484 | ToolCategory::Agent => { |
| 485 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactAgent).into_owned()]; |
| 486 | if let Some(kind) = param_preview(params, &["type"], 40) { |
| 487 | impacts.push(impact_line( |
| 488 | locale, |
| 489 | MessageId::ApprovalImpactAgentType, |
| 490 | kind, |
| 491 | )); |
| 492 | } |
| 493 | impacts |
| 494 | } |
| 495 | ToolCategory::Unknown => { |
| 496 | let mut impacts = vec![tr(locale, MessageId::ApprovalImpactUnknown).into_owned()]; |
| 497 | if let Some(target) = param_preview( |
| 498 | params, |
| 499 | &["path", "cmd", "command", "url", "q", "query", "ref_id"], |
| 500 | 96, |
| 501 | ) { |
| 502 | impacts.push(impact_line( |
| 503 | locale, |
| 504 | MessageId::ApprovalImpactPrimaryInput, |
| 505 | target, |
| 506 | )); |
| 507 | } |
| 508 | impacts |
| 509 | } |
| 510 | }; |
| 511 | impacts.extend(delegated_authority_impacts( |
| 512 | tool_name, |
| 513 | params, |
| 514 | locale == Locale::ZhHans, |
| 515 | )); |
| 516 | impacts |
| 517 | } |
| 518 | |
| 519 | fn localized_description(category: ToolCategory, locale: Locale) -> String { |
| 520 | match category { |
| 521 | ToolCategory::Safe => tr(locale, MessageId::ApprovalDescSafe).to_string(), |
| 522 | ToolCategory::FileWrite => tr(locale, MessageId::ApprovalDescFileWrite).to_string(), |
| 523 | ToolCategory::Shell => tr(locale, MessageId::ApprovalDescShell).to_string(), |
| 524 | ToolCategory::Network => tr(locale, MessageId::ApprovalDescNetwork).to_string(), |
| 525 | ToolCategory::McpRead => tr(locale, MessageId::ApprovalDescMcpRead).to_string(), |
| 526 | ToolCategory::McpAction => tr(locale, MessageId::ApprovalDescMcpAction).to_string(), |
| 527 | ToolCategory::Agent => tr(locale, MessageId::ApprovalDescAgent).to_string(), |
| 528 | ToolCategory::Unknown => tr(locale, MessageId::ApprovalDescUnknown).to_string(), |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | /// Tools that hand work to a later, unattended run (a durable task or a |
| 533 | /// scheduled automation) and can ask for authority of their own. |
| 534 | fn delegated_authority_impacts(tool_name: &str, params: &Value, zh: bool) -> Vec<String> { |
| 535 | let separator = if zh { ":" } else { ": " }; |
| 536 | delegated_authority_fields(tool_name, params, zh) |
| 537 | .into_iter() |
| 538 | .map(|(label, value)| format!("{label}{separator}{value}")) |
| 539 | .collect() |
| 540 | } |
| 541 | |
| 542 | fn build_prominent_details( |
| 543 | tool_name: &str, |
| 544 | category: ToolCategory, |
| 545 | params: &Value, |
| 546 | ) -> Vec<ApprovalDetail> { |
| 547 | let mut details: Vec<ApprovalDetail> = delegated_authority_fields(tool_name, params, false) |
| 548 | .into_iter() |
| 549 | .map(|(label, value)| ApprovalDetail { |
| 550 | label, |
| 551 | value, |
| 552 | shell_lines: None, |
| 553 | is_preview: false, |
| 554 | }) |
| 555 | .collect(); |
| 556 | match category { |
| 557 | ToolCategory::Shell => { |
| 558 | if let Some(command) = param_text(params, &["command", "cmd"]) { |
| 559 | details.push(ApprovalDetail { |
| 560 | label: "Command".to_string(), |
| 561 | shell_lines: Some(format_shell_command_for_approval(&command)), |
| 562 | value: command, |
| 563 | is_preview: false, |
| 564 | }); |
| 565 | } |
| 566 | if let Some(workdir) = param_preview(params, &["workdir", "cwd"], 96) { |
| 567 | details.push(ApprovalDetail { |
| 568 | label: "Dir".to_string(), |
| 569 | value: workdir, |
| 570 | shell_lines: None, |
| 571 | is_preview: false, |
| 572 | }); |
| 573 | } |
| 574 | } |
| 575 | ToolCategory::FileWrite => { |
| 576 | if let Some(path) = param_preview(params, &["path", "target", "destination"], 200) { |
| 577 | details.push(ApprovalDetail { |
| 578 | label: "File".to_string(), |
| 579 | value: path, |
| 580 | shell_lines: None, |
| 581 | is_preview: false, |
| 582 | }); |
| 583 | } |
| 584 | if let Some(preview_lines) = file_write_preview_lines(tool_name, params) { |
| 585 | details.push(ApprovalDetail { |
| 586 | label: "Preview".to_string(), |
| 587 | value: preview_lines.join("\n"), |
| 588 | shell_lines: Some(preview_lines), |
| 589 | is_preview: true, |
| 590 | }); |
| 591 | } |
| 592 | } |
| 593 | ToolCategory::Safe => { |
| 594 | if let Some(path) = param_preview(params, &["path", "ref_id", "uri"], 200) { |
| 595 | details.push(ApprovalDetail { |
| 596 | label: "Path".to_string(), |
| 597 | value: path, |
| 598 | shell_lines: None, |
| 599 | is_preview: false, |
| 600 | }); |
| 601 | } |
| 602 | } |
| 603 | ToolCategory::Network => { |
| 604 | if let Some(target) = |
| 605 | param_preview(params, &["url", "q", "query", "location", "repo"], 200) |
| 606 | { |
| 607 | details.push(ApprovalDetail { |
| 608 | label: "Target".to_string(), |
| 609 | value: target, |
| 610 | shell_lines: None, |
| 611 | is_preview: false, |
| 612 | }); |
| 613 | } |
| 614 | } |
| 615 | ToolCategory::Agent if tool_name == "workflow" => { |
| 616 | // #4126: elevated Workflow plan card fields. |
| 617 | let summary = |
| 618 | codewhale_engine::tools::workflow_plan_approval::analyze_workflow_plan_approval( |
| 619 | params, |
| 620 | ); |
| 621 | for (label, value) in summary.card_fields() { |
| 622 | details.push(ApprovalDetail { |
| 623 | label: label.to_string(), |
| 624 | value, |
| 625 | shell_lines: None, |
| 626 | is_preview: false, |
| 627 | }); |
| 628 | } |
| 629 | } |
| 630 | ToolCategory::Agent => { |
| 631 | if let Some(action) = param_preview(params, &["action"], 40) { |
| 632 | details.push(ApprovalDetail { |
| 633 | label: "Action".to_string(), |
| 634 | value: action, |
| 635 | shell_lines: None, |
| 636 | is_preview: false, |
| 637 | }); |
| 638 | } |
| 639 | if let Some(kind) = param_preview(params, &["type"], 40) { |
| 640 | details.push(ApprovalDetail { |
| 641 | label: "Type".to_string(), |
| 642 | value: kind, |
| 643 | shell_lines: None, |
| 644 | is_preview: false, |
| 645 | }); |
| 646 | } |
| 647 | if let Some(prompt) = param_preview(params, &["prompt", "task", "message"], 200) { |
| 648 | details.push(ApprovalDetail { |
| 649 | label: "Prompt".to_string(), |
| 650 | value: prompt, |
| 651 | shell_lines: None, |
| 652 | is_preview: false, |
| 653 | }); |
| 654 | } |
| 655 | } |
| 656 | ToolCategory::McpRead | ToolCategory::McpAction | ToolCategory::Unknown => { |
| 657 | if let Some(input) = param_preview( |
| 658 | params, |
| 659 | &["command", "cmd", "path", "url", "q", "query", "ref_id"], |
| 660 | 200, |
| 661 | ) { |
| 662 | details.push(ApprovalDetail { |
| 663 | label: "Input".to_string(), |
| 664 | value: input, |
| 665 | shell_lines: None, |
| 666 | is_preview: false, |
| 667 | }); |
| 668 | } |
| 669 | } |
| 670 | } |
| 671 | details |
| 672 | } |
| 673 | |
| 674 | fn truncate_params_value(value: &Value, max_len: usize) -> Value { |
| 675 | match value { |
| 676 | Value::Object(map) => { |
| 677 | let truncated = map |
| 678 | .iter() |
| 679 | .map(|(key, val)| (key.clone(), truncate_params_value(val, max_len))) |
| 680 | .collect(); |
| 681 | Value::Object(truncated) |
| 682 | } |
| 683 | Value::Array(items) => { |
| 684 | let truncated_items = items |
| 685 | .iter() |
| 686 | .map(|val| truncate_params_value(val, max_len)) |
| 687 | .collect(); |
| 688 | Value::Array(truncated_items) |
| 689 | } |
| 690 | Value::String(text) => Value::String(truncate_string_value(text, max_len)), |
| 691 | other => { |
| 692 | let rendered = other.to_string(); |
| 693 | if rendered.chars().count() > max_len { |
| 694 | Value::String(truncate_string_value(&rendered, max_len)) |
| 695 | } else { |
| 696 | other.clone() |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | // ============================================================================ |
| 703 | // Tests |
| 704 | // ============================================================================ |
| 705 | |
| 706 | #[cfg(test)] |
| 707 | mod tests; |
| 708 |