1use std::borrow::Cow;
16use std::path::Path;
17
18use serde_json::Value;
19
20use crate::formatting::{collapse_whitespace, truncate_middle, truncate_path_middle};
21use crate::tool_types::tool_names;
22
23#[must_use]
25pub fn lookup_string(args: &Value, key: &str) -> Option<String> {
26 lookup_first_string(args, &[key])
27}
28
29#[must_use]
35pub fn lookup_first_string(args: &Value, keys: &[&str]) -> Option<String> {
36 keys.iter()
37 .filter_map(|key| args.get(key).and_then(Value::as_str))
38 .find_map(|text| {
39 let trimmed = text.trim();
40 (!trimmed.is_empty()).then(|| trimmed.to_string())
41 })
42}
43
44#[must_use]
50pub fn relativize_to_workspace<'a>(path: &'a str, workspace_root: Option<&Path>) -> Cow<'a, str> {
51 let Some(root) = workspace_root else {
52 return Cow::Borrowed(path);
53 };
54 let candidate = Path::new(path);
55 if candidate.is_absolute() {
56 if let Ok(rel) = candidate.strip_prefix(root) {
57 if !rel.as_os_str().is_empty() {
58 return Cow::Owned(rel.to_string_lossy().into_owned());
59 }
60 }
61 }
62 Cow::Borrowed(path)
63}
64
65#[must_use]
67pub fn is_path_key(key: &str) -> bool {
68 matches!(key, "path" | "file_path" | "filename" | "destination" | "source")
69}
70
71#[must_use]
77pub fn humanize_key(key: &str) -> String {
78 let replaced = key.replace('_', " ");
79 if replaced.is_empty() {
80 return replaced;
81 }
82 let mut chars = replaced.chars();
83 let first = chars.next().unwrap_or_default();
84 let mut result = first.to_uppercase().collect::<String>();
85 result.push_str(&chars.collect::<String>());
86 result
87}
88
89#[must_use]
97pub fn humanize_tool_name(tool_name: &str) -> String {
98 let bare = strip_mcp_prefix(tool_name);
99 let mut words: Vec<String> = Vec::new();
100 let mut current = String::new();
101 let mut previous: Option<char> = None;
102 for c in bare.chars() {
106 if c == '_' {
107 if !current.is_empty() {
108 words.push(std::mem::take(&mut current));
109 }
110 } else {
111 let boundary = previous.is_some_and(|prev| c.is_uppercase() && (prev.is_lowercase() || prev.is_numeric()));
112 if boundary && !current.is_empty() {
113 words.push(std::mem::take(&mut current));
114 }
115 current.push(c);
116 }
117 previous = Some(c);
118 }
119 if !current.is_empty() {
120 words.push(current);
121 }
122 if words.is_empty() {
123 return tool_name.to_string();
124 }
125 for word in &mut words {
126 let mut chars = word.chars();
129 if let Some(first) = chars.next() {
130 let mut pretty = first.to_uppercase().collect::<String>();
131 pretty.push_str(chars.as_str());
132 *word = pretty;
133 }
134 }
135 words.join(" ")
136}
137
138#[must_use]
146pub fn mcp_tool_display_name(tool_name: &str) -> Option<&str> {
147 if tool_name.starts_with("mcp__") {
148 return Some(tool_name.split("__").last().unwrap_or(tool_name));
149 }
150 if tool_name.starts_with("mcp::") {
151 return Some(tool_name.split("::").last().unwrap_or(tool_name));
152 }
153 if let Some(rest) = tool_name.strip_prefix("mcp_") {
154 return Some(rest);
155 }
156 None
157}
158
159#[must_use]
165pub fn strip_mcp_prefix(tool_name: &str) -> &str {
166 mcp_tool_display_name(tool_name).unwrap_or(tool_name)
167}
168
169#[must_use]
171pub fn is_verbose_key(key: &str) -> bool {
172 matches!(
173 key,
174 "command"
175 | "raw_command"
176 | "bash_command"
177 | "cmd"
178 | "old_str"
179 | "new_str"
180 | "content"
181 | "new_content"
182 | "text"
183 | "patch"
184 | "code"
185 )
186}
187
188fn text_is_search_query(tool_name: &str, key: &str) -> bool {
194 key == "text" && strip_mcp_prefix(tool_name) == tool_names::CODE_SEARCH
195}
196
197#[must_use]
203pub fn is_noise_param(key: &str) -> bool {
204 matches!(
205 key,
206 "timeout_secs"
208 | "timeout"
209 | "max_bytes"
210 | "max_matches"
211 | "debug_query"
213 | "strictness"
214 | "case_sensitive"
215 | "literal"
216 | "context_lines"
217 | "shell"
219 | "login"
220 | "tty"
221 | "sandbox_permissions"
222 | "additional_permissions"
223 | "justification"
224 | "prefix_rule"
225 | "workdir"
226 | "cwd"
227 | "language"
228 | "spool_path"
229 | "type"
231 | "tool_call_id"
232 | "call_type"
233 | "action"
235 | "max_output_tokens"
237 | "max_tokens"
238 )
239}
240
241#[must_use]
251pub fn collect_param_details(
252 tool_name: &str,
253 args: &Value,
254 skipped: &[&str],
255 workspace_root: Option<&Path>,
256) -> Vec<String> {
257 let mut details = Vec::new();
258 let Some(map) = args.as_object() else {
259 return details;
260 };
261 for (key, value) in map {
262 let verbose_hidden = is_verbose_key(key) && !text_is_search_query(tool_name, key);
263 if is_noise_param(key) || verbose_hidden || skipped.contains(&key.as_str()) {
264 continue;
265 }
266 match value {
267 Value::String(s) if !s.is_empty() => {
268 let display: Cow<'_, str> = if is_path_key(key) {
270 relativize_to_workspace(s, workspace_root)
271 } else {
272 Cow::Borrowed(s.as_str())
273 };
274 details.push(format!("{}: {}", humanize_key(key), truncate_middle(&display, 60)))
275 }
276 Value::Bool(true) => {
277 details.push(humanize_key(key));
278 }
279 Value::Array(items) => {
280 let strings: Vec<String> =
281 items.iter().filter_map(|item| item.as_str().map(|s| s.to_string())).collect();
282 if !strings.is_empty() {
283 details.push(format!("{}: {}", humanize_key(key), summarize_list(&strings)));
284 }
285 }
286 Value::Number(num) => {
287 if num.as_f64().is_some_and(|n| n == 0.0) {
289 continue;
290 }
291 details.push(format!("{}: {}", humanize_key(key), num));
292 }
293 _ => {}
294 }
295 }
296 details
297}
298
299#[must_use]
307pub fn exec_session_param_detail(args: &Value) -> Option<String> {
308 let session = lookup_string(args, "session_id").map(|id| format!("Session {id}"));
309 let wait = ["wait_timeout_seconds", "timeout_seconds"]
310 .iter()
311 .find_map(|key| args.get(key).and_then(Value::as_u64))
312 .filter(|secs| *secs > 0)
313 .map(|secs| format!("wait up to {secs}s"));
314
315 let parts = [session, wait].into_iter().flatten().collect::<Vec<_>>();
316 (!parts.is_empty()).then(|| parts.join(" · "))
317}
318
319mod descriptors;
320pub use descriptors::{
321 COMPUTER_USE_RUNNING_STATUS_PREFIX, describe_code_search, describe_computer_use, describe_fetch_action,
322 describe_grep_file, describe_list_files, status_is_computer_use_running, summarize_list,
323};
324
325const SCRIPT_RUNNER_FLAGS: &[&str] = &["-c", "-e", "--code"];
328
329#[must_use]
341pub fn preview_command(command: &str, max_len: usize) -> String {
342 if max_len == 0 {
343 return String::new();
344 }
345 let lines: Vec<&str> = command.lines().map(str::trim).filter(|line| !line.is_empty()).collect();
346 let Some((first, rest)) = lines.split_first() else {
347 return String::new();
348 };
349 let mut first_line = collapse_whitespace(first);
350 if is_script_prefix_only(&first_line) && !rest.is_empty() {
351 let need = max_len.saturating_sub(first_line.chars().count()).saturating_add(16);
354 let mut rest_parts = Vec::new();
355 let mut rest_len = 0usize;
356 for line in rest {
357 let collapsed = collapse_whitespace(line);
358 if collapsed.is_empty() {
359 continue;
360 }
361 rest_len += collapsed.chars().count() + 1;
362 rest_parts.push(collapsed);
363 if rest_len >= need {
364 break;
365 }
366 }
367 if !rest_parts.is_empty() {
368 let rest = rest_parts.join(" ");
369 if first_line.ends_with('"') || first_line.ends_with('\'') {
370 first_line.push_str(&rest);
375 } else {
376 first_line.push(' ');
377 first_line.push_str(&rest);
378 }
379 }
380 }
381 if first_line.chars().count() <= max_len {
382 return first_line;
383 }
384
385 let budget = max_len.saturating_sub(1);
386 let mut head: String = first_line.chars().take(budget).collect();
387 if let Some(last_space) = head.rfind(char::is_whitespace) {
388 if last_space >= budget / 2 {
391 head.truncate(last_space);
392 }
393 }
394 format!("{}…", head.trim_end())
395}
396
397#[must_use]
404pub fn preview_full_command(command: &str) -> String {
405 preview_command(command, usize::MAX)
406}
407
408fn is_script_runner_program(program: &str) -> bool {
413 let base = program.rsplit(['/', '\\']).next().unwrap_or(program).to_ascii_lowercase();
414 base.starts_with("python")
415 || matches!(
416 base.as_str(),
417 "bash" | "sh" | "zsh" | "node" | "ruby" | "perl" | "php" | "deno" | "bun" | "pwsh" | "powershell"
418 )
419}
420
421fn is_script_prefix_only(first_line: &str) -> bool {
430 let mut tokens = first_line.split_whitespace();
431 let Some(program) = tokens.next() else {
432 return false;
433 };
434 if !is_script_runner_program(program) {
435 return false;
436 }
437 if !tokens.clone().any(|token| SCRIPT_RUNNER_FLAGS.contains(&token)) {
438 return false;
439 }
440 let token_count = 1 + tokens.clone().count();
442 if token_count == 2 {
443 return true;
444 }
445 shell_words::split(first_line).is_err()
448}
449
450pub const WAIT_FOR_COMMAND_SESSION: &str = "Wait for command session";
456pub const READ_COMMAND_SESSION: &str = "Read command session";
457
458#[must_use]
466pub fn unified_exec_action_label(args: &Value) -> &'static str {
467 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
468 if action.eq_ignore_ascii_case("run") {
469 "Run command"
470 } else if action.eq_ignore_ascii_case("write") {
471 "Send command input"
472 } else if action.eq_ignore_ascii_case("poll") {
473 READ_COMMAND_SESSION
474 } else if action.eq_ignore_ascii_case("wait") {
475 WAIT_FOR_COMMAND_SESSION
476 } else if action.eq_ignore_ascii_case("continue") {
477 "Continue command session"
478 } else if action.eq_ignore_ascii_case("inspect") {
479 "Inspect command output"
480 } else if action.eq_ignore_ascii_case("list") {
481 "List command sessions"
482 } else if action.eq_ignore_ascii_case("close") {
483 "Close command session"
484 } else if action.eq_ignore_ascii_case("code") {
485 "Run code"
486 } else {
487 "Exec action"
488 }
489}
490
491#[must_use]
501pub fn verb_callout_headline(tool_name: &str, args: &Value, workspace_root: Option<&Path>) -> String {
502 let name = strip_mcp_prefix(tool_name);
503 if let Some(label) = session_followup_title(name, args) {
506 return label;
507 }
508 if name == tool_names::LIST_FILES {
509 if let Some((title, _)) = describe_list_files(args, workspace_root) {
510 return title;
511 }
512 } else if name == tool_names::GREP_FILE {
513 if let Some((title, _)) = describe_grep_file(args, workspace_root) {
514 return title;
515 }
516 } else if name == tool_names::COMPUTER_USE {
517 let (title, _) = describe_computer_use(args);
518 return title;
519 }
520 match name {
521 tool_names::READ_FILE
522 | tool_names::READ_PTY_SESSION
523 | tool_names::WEB_FETCH
524 | tool_names::FETCH_URL
525 | tool_names::FETCH
526 | tool_names::GET_ERRORS
527 | tool_names::LIST_FILES => {
528 if let Some(base) = headline_basename(args) {
529 return format!("Read {base}");
530 }
531 if lookup_first_string(args, &["url"]).is_some() {
532 let (title, _) = describe_fetch_action(args);
533 return title;
534 }
535 }
536 tool_names::EDIT_FILE
537 | tool_names::WRITE_FILE
538 | tool_names::CREATE_FILE
539 | tool_names::DELETE_FILE
540 | tool_names::APPLY_PATCH
541 | tool_names::SEARCH_REPLACE => {
542 if let Some(base) = headline_basename(args) {
543 return format!("Edited {base}");
544 }
545 }
546 tool_names::EXEC_COMMAND
547 | tool_names::RUN_PTY_CMD
548 | tool_names::CREATE_PTY_SESSION
549 | tool_names::SHELL
550 | tool_names::BASH_ALIAS => {
551 if let Some(command) = command_text(args) {
552 return format!("Ran {}", compact_command_headline(&command));
553 }
554 }
555 tool_names::CODE_SEARCH | tool_names::GREP | tool_names::GREP_FILE => {
556 if let Some((title, _)) = search_headline(name, args) {
557 return title;
558 }
559 }
560 tool_names::UNIFIED_EXEC => {
561 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
562 if !action.eq_ignore_ascii_case("run") {
563 return unified_exec_action_label(args).to_string();
564 }
565 if let Some(command) = command_text(args) {
566 return format!("Ran {}", compact_command_headline(&command));
567 }
568 }
569 tool_names::UNIFIED_FILE => {
570 let action = args.get("action").and_then(Value::as_str).unwrap_or("read");
571 if action.eq_ignore_ascii_case("read") {
572 if let Some(base) = headline_basename(args) {
573 return format!("Read {base}");
574 }
575 } else if ["write", "edit", "patch", "delete", "move", "copy"]
576 .iter()
577 .any(|known| action.eq_ignore_ascii_case(known))
578 && let Some(base) = headline_basename(args)
579 {
580 return format!("Edited {base}");
581 }
582 }
583 _ => {}
584 }
585 humanize_tool_name(tool_name)
586}
587
588#[must_use]
591pub fn session_followup_title(name: &str, args: &Value) -> Option<String> {
592 match name {
593 tool_names::SEND_PTY_INPUT => Some("Send command input".to_string()),
594 tool_names::READ_PTY_SESSION => Some(READ_COMMAND_SESSION.to_string()),
595 tool_names::WRITE_STDIN => Some(write_stdin_action_label(args).to_string()),
596 tool_names::UNIFIED_EXEC => {
597 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
598 (!action.eq_ignore_ascii_case("run")).then(|| unified_exec_action_label(args).to_string())
599 }
600 _ => None,
601 }
602}
603
604#[must_use]
607pub fn search_headline(name: &str, args: &Value) -> Option<(String, &'static [&'static str])> {
608 if name == tool_names::CODE_SEARCH {
609 return describe_code_search(args);
610 }
611 for key in ["pattern", "query"] {
612 if let Some(pattern) = lookup_string(args, key) {
613 let keys: &'static [&'static str] = if key == "pattern" { &["pattern"] } else { &["query"] };
614 return Some((format!("Search files for {}", truncate_middle(&pattern, 40)), keys));
615 }
616 }
617 None
618}
619
620fn headline_basename(args: &Value) -> Option<String> {
622 lookup_first_string(args, &["path", "file_path", "filepath", "target_path"])
623 .as_deref()
624 .and_then(|path| path.split(['/', '\\']).rfind(|segment| !segment.is_empty()))
625 .map(str::to_string)
626}
627
628#[must_use]
630pub fn command_text(args: &Value) -> Option<String> {
631 let text = if let Some(text) = ["command", "cmd", "raw_command", "bash_command"]
632 .iter()
633 .filter_map(|key| args.get(key).and_then(Value::as_str))
634 .find(|text| !text.trim().is_empty())
635 {
636 text.to_owned()
637 } else {
638 let parts: Vec<&str> = args.get("command")?.as_array()?.iter().filter_map(Value::as_str).collect();
639 if parts.iter().all(|part| part.trim().is_empty()) {
640 return None;
641 }
642 let joined = shell_words::join(parts);
643 (!joined.trim().is_empty()).then_some(joined)?
644 };
645 Some(text)
646}
647
648#[must_use]
650pub fn compact_command_headline(command: &str) -> String {
651 let line = command.lines().next().unwrap_or_default().trim();
652 let words = shell_words::split(line).unwrap_or_default();
653 let program = words
654 .first()
655 .map(String::as_str)
656 .or_else(|| line.split_whitespace().next())
657 .unwrap_or("command");
658 let first_word = program;
659 let first_program = first_word.split(['|', '&', ';', '<', '>']).next().unwrap_or("command");
660 let program = first_program
661 .rsplit(['/', '\\'])
662 .next()
663 .filter(|part| !part.is_empty())
664 .unwrap_or("command");
665 if first_word.len() != first_program.len() {
666 return program.to_string();
667 }
668 let target = words
669 .iter()
670 .skip(1)
671 .take_while(|word| !word.contains(['|', '&', ';', '<', '>']))
672 .filter(|word| !word.starts_with('-'))
673 .find_map(|word| {
674 let base = word.rsplit(['/', '\\']).next()?;
675 (base.contains('.')
676 && !base.starts_with('.')
677 && !base.ends_with('.')
678 && base.chars().all(|ch| ch.is_alphanumeric() || matches!(ch, '.' | '_' | '-')))
679 .then_some(base)
680 });
681 target.map_or_else(|| program.to_string(), |target| format!("{program} {target}"))
682}
683#[must_use]
686pub fn write_stdin_action_label(args: &Value) -> &'static str {
687 if let Some(action) = args.get("action").and_then(Value::as_str) {
688 if action.eq_ignore_ascii_case("wait") {
689 return WAIT_FOR_COMMAND_SESSION;
690 }
691 if action.eq_ignore_ascii_case("poll") {
692 return READ_COMMAND_SESSION;
693 }
694 if action.eq_ignore_ascii_case("inspect") {
695 return "Inspect command output";
696 }
697 if action.eq_ignore_ascii_case("close") {
698 return "Close command session";
699 }
700 if action.eq_ignore_ascii_case("terminate") {
701 return "Terminate command session";
702 }
703 if action.eq_ignore_ascii_case("write") {
704 return if has_session_input(args) {
707 "Send command input"
708 } else {
709 READ_COMMAND_SESSION
710 };
711 }
712 }
713 if has_session_input(args) {
714 "Send command input"
715 } else {
716 READ_COMMAND_SESSION
719 }
720}
721
722#[must_use]
724pub fn has_session_input(args: &Value) -> bool {
725 ["chars", "input", "text"]
726 .iter()
727 .any(|key| args.get(key).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))
728}
729
730#[must_use]
746pub fn harness_is_user_visible(kind: &vtcode_exec_events::HarnessEventKind) -> bool {
747 use vtcode_exec_events::HarnessEventKind::*;
748 match kind {
749 ToolLatencyRecorded
750 | PlanningStarted
751 | PlanningCompleted
752 | ContinuationStarted
753 | ContinuationSkipped
754 | EvaluationStarted
755 | EvaluationPassed
756 | RevisionStarted
757 | VerificationStarted
758 | VerificationPassed
759 | SnapshotCreated
760 | DelegatedAgentStatus
761 | SessionMessageSent
762 | SessionMessageReceived => false,
763 SessionMessageExpired
764 | TurnBlocked
765 | BlockedRecoveryStarted
766 | BlockedRecoveryFinished
767 | BlockedHandoffWritten
768 | BlockedHandoffResolved
769 | EvaluationFailed
770 | EscalationTriggered
771 | EscalationBypassed
772 | VerificationFailed
773 | ErrorRecovered
774 | ToolRetryAttempted
775 | SnapshotRestored
776 | SessionToolLimitIncreased
777 | ToolLoopLimitIncreased
778 | BackgroundSubprocessCompleted => true,
779 }
780}
781
782mod session_poll;
783
784pub use session_poll::{SessionPollKey, poll_run_tick, session_poll_key};
785
786#[cfg(test)]
787mod tests;