1use std::borrow::Cow;
16use std::path::Path;
17
18use serde_json::Value;
19
20use crate::formatting::{collapse_whitespace, truncate_middle, truncate_path_middle};
21
22#[must_use]
24pub fn lookup_string(args: &Value, key: &str) -> Option<String> {
25 lookup_first_string(args, &[key])
26}
27
28#[must_use]
34pub fn lookup_first_string(args: &Value, keys: &[&str]) -> Option<String> {
35 keys.iter()
36 .filter_map(|key| args.get(key).and_then(Value::as_str))
37 .find_map(|text| {
38 let trimmed = text.trim();
39 (!trimmed.is_empty()).then(|| trimmed.to_string())
40 })
41}
42
43#[must_use]
49pub fn relativize_to_workspace<'a>(path: &'a str, workspace_root: Option<&Path>) -> Cow<'a, str> {
50 let Some(root) = workspace_root else {
51 return Cow::Borrowed(path);
52 };
53 let candidate = Path::new(path);
54 if candidate.is_absolute() {
55 if let Ok(rel) = candidate.strip_prefix(root) {
56 if !rel.as_os_str().is_empty() {
57 return Cow::Owned(rel.to_string_lossy().into_owned());
58 }
59 }
60 }
61 Cow::Borrowed(path)
62}
63
64#[must_use]
66pub fn is_path_key(key: &str) -> bool {
67 matches!(key, "path" | "file_path" | "filename" | "destination" | "source")
68}
69
70#[must_use]
76pub fn humanize_key(key: &str) -> String {
77 let replaced = key.replace('_', " ");
78 if replaced.is_empty() {
79 return replaced;
80 }
81 let mut chars = replaced.chars();
82 let first = chars.next().unwrap_or_default();
83 let mut result = first.to_uppercase().collect::<String>();
84 result.push_str(&chars.collect::<String>());
85 result
86}
87
88#[must_use]
96pub fn humanize_tool_name(tool_name: &str) -> String {
97 let bare = strip_mcp_prefix(tool_name);
98 let mut words: Vec<String> = Vec::new();
99 let mut current = String::new();
100 let mut previous: Option<char> = None;
101 for c in bare.chars() {
105 if c == '_' {
106 if !current.is_empty() {
107 words.push(std::mem::take(&mut current));
108 }
109 } else {
110 let boundary = previous.is_some_and(|prev| c.is_uppercase() && (prev.is_lowercase() || prev.is_numeric()));
111 if boundary && !current.is_empty() {
112 words.push(std::mem::take(&mut current));
113 }
114 current.push(c);
115 }
116 previous = Some(c);
117 }
118 if !current.is_empty() {
119 words.push(current);
120 }
121 if words.is_empty() {
122 return tool_name.to_string();
123 }
124 for word in &mut words {
125 let mut chars = word.chars();
128 if let Some(first) = chars.next() {
129 let mut pretty = first.to_uppercase().collect::<String>();
130 pretty.push_str(chars.as_str());
131 *word = pretty;
132 }
133 }
134 words.join(" ")
135}
136
137#[must_use]
145pub fn mcp_tool_display_name(tool_name: &str) -> Option<&str> {
146 if tool_name.starts_with("mcp__") {
147 return Some(tool_name.split("__").last().unwrap_or(tool_name));
148 }
149 if tool_name.starts_with("mcp::") {
150 return Some(tool_name.split("::").last().unwrap_or(tool_name));
151 }
152 if let Some(rest) = tool_name.strip_prefix("mcp_") {
153 return Some(rest);
154 }
155 None
156}
157
158#[must_use]
164pub fn strip_mcp_prefix(tool_name: &str) -> &str {
165 mcp_tool_display_name(tool_name).unwrap_or(tool_name)
166}
167
168#[must_use]
170pub fn summarize_list(items: &[String]) -> String {
171 if items.is_empty() {
172 return String::new();
173 }
174 let shown: Vec<String> = items.iter().take(2).map(|s| truncate_middle(s, 60)).collect();
175 if items.len() > 2 {
176 format!("{} +{} more", shown.join(", "), items.len() - 2)
177 } else {
178 shown.join(", ")
179 }
180}
181
182#[must_use]
184pub fn is_verbose_key(key: &str) -> bool {
185 matches!(
186 key,
187 "command"
188 | "raw_command"
189 | "bash_command"
190 | "cmd"
191 | "old_str"
192 | "new_str"
193 | "content"
194 | "new_content"
195 | "text"
196 | "patch"
197 | "code"
198 )
199}
200
201fn text_is_search_query(tool_name: &str, key: &str) -> bool {
207 key == "text" && strip_mcp_prefix(tool_name) == "code_search"
208}
209
210#[must_use]
216pub fn is_noise_param(key: &str) -> bool {
217 matches!(
218 key,
219 "timeout_secs"
221 | "timeout"
222 | "max_bytes"
223 | "max_matches"
224 | "debug_query"
226 | "strictness"
227 | "case_sensitive"
228 | "literal"
229 | "context_lines"
230 | "shell"
232 | "login"
233 | "tty"
234 | "sandbox_permissions"
235 | "additional_permissions"
236 | "justification"
237 | "prefix_rule"
238 | "workdir"
239 | "cwd"
240 | "language"
241 | "spool_path"
242 | "type"
244 | "tool_call_id"
245 | "call_type"
246 | "action"
248 | "max_output_tokens"
250 | "max_tokens"
251 )
252}
253
254#[must_use]
264pub fn collect_param_details(
265 tool_name: &str,
266 args: &Value,
267 skipped: &[&str],
268 workspace_root: Option<&Path>,
269) -> Vec<String> {
270 let mut details = Vec::new();
271 let Some(map) = args.as_object() else {
272 return details;
273 };
274 for (key, value) in map {
275 let verbose_hidden = is_verbose_key(key) && !text_is_search_query(tool_name, key);
276 if is_noise_param(key) || verbose_hidden || skipped.contains(&key.as_str()) {
277 continue;
278 }
279 match value {
280 Value::String(s) if !s.is_empty() => {
281 let display: Cow<'_, str> = if is_path_key(key) {
283 relativize_to_workspace(s, workspace_root)
284 } else {
285 Cow::Borrowed(s.as_str())
286 };
287 details.push(format!("{}: {}", humanize_key(key), truncate_middle(&display, 60)))
288 }
289 Value::Bool(true) => {
290 details.push(humanize_key(key));
291 }
292 Value::Array(items) => {
293 let strings: Vec<String> =
294 items.iter().filter_map(|item| item.as_str().map(|s| s.to_string())).collect();
295 if !strings.is_empty() {
296 details.push(format!("{}: {}", humanize_key(key), summarize_list(&strings)));
297 }
298 }
299 Value::Number(num) => {
300 if num.as_f64().is_some_and(|n| n == 0.0) {
302 continue;
303 }
304 details.push(format!("{}: {}", humanize_key(key), num));
305 }
306 _ => {}
307 }
308 }
309 details
310}
311
312#[must_use]
320pub fn exec_session_param_detail(args: &Value) -> Option<String> {
321 let session = lookup_string(args, "session_id").map(|id| format!("Session {id}"));
322 let wait = ["wait_timeout_seconds", "timeout_seconds"]
323 .iter()
324 .find_map(|key| args.get(key).and_then(Value::as_u64))
325 .filter(|secs| *secs > 0)
326 .map(|secs| format!("wait up to {secs}s"));
327
328 let parts = [session, wait].into_iter().flatten().collect::<Vec<_>>();
329 (!parts.is_empty()).then(|| parts.join(" · "))
330}
331
332mod descriptors;
333pub use descriptors::{describe_code_search, describe_fetch_action, describe_grep_file, describe_list_files};
334
335const SCRIPT_RUNNER_FLAGS: &[&str] = &["-c", "-e", "--code"];
338
339#[must_use]
351pub fn preview_command(command: &str, max_len: usize) -> String {
352 if max_len == 0 {
353 return String::new();
354 }
355 let lines: Vec<&str> = command.lines().map(str::trim).filter(|line| !line.is_empty()).collect();
356 let Some((first, rest)) = lines.split_first() else {
357 return String::new();
358 };
359 let mut first_line = collapse_whitespace(first);
360 if is_script_prefix_only(&first_line) && !rest.is_empty() {
361 let need = max_len.saturating_sub(first_line.chars().count()).saturating_add(16);
364 let mut rest_parts = Vec::new();
365 let mut rest_len = 0usize;
366 for line in rest {
367 let collapsed = collapse_whitespace(line);
368 if collapsed.is_empty() {
369 continue;
370 }
371 rest_len += collapsed.chars().count() + 1;
372 rest_parts.push(collapsed);
373 if rest_len >= need {
374 break;
375 }
376 }
377 if !rest_parts.is_empty() {
378 let rest = rest_parts.join(" ");
379 if first_line.ends_with('"') || first_line.ends_with('\'') {
380 first_line.push_str(&rest);
385 } else {
386 first_line.push(' ');
387 first_line.push_str(&rest);
388 }
389 }
390 }
391 if first_line.chars().count() <= max_len {
392 return first_line;
393 }
394
395 let budget = max_len.saturating_sub(1);
396 let mut head: String = first_line.chars().take(budget).collect();
397 if let Some(last_space) = head.rfind(char::is_whitespace) {
398 if last_space >= budget / 2 {
401 head.truncate(last_space);
402 }
403 }
404 format!("{}…", head.trim_end())
405}
406
407#[must_use]
414pub fn preview_full_command(command: &str) -> String {
415 preview_command(command, usize::MAX)
416}
417
418fn is_script_runner_program(program: &str) -> bool {
423 let base = program.rsplit(['/', '\\']).next().unwrap_or(program).to_ascii_lowercase();
424 base.starts_with("python")
425 || matches!(
426 base.as_str(),
427 "bash" | "sh" | "zsh" | "node" | "ruby" | "perl" | "php" | "deno" | "bun" | "pwsh" | "powershell"
428 )
429}
430
431fn is_script_prefix_only(first_line: &str) -> bool {
440 let mut tokens = first_line.split_whitespace();
441 let Some(program) = tokens.next() else {
442 return false;
443 };
444 if !is_script_runner_program(program) {
445 return false;
446 }
447 if !tokens.clone().any(|token| SCRIPT_RUNNER_FLAGS.contains(&token)) {
448 return false;
449 }
450 let token_count = 1 + tokens.clone().count();
452 if token_count == 2 {
453 return true;
454 }
455 shell_words::split(first_line).is_err()
458}
459
460pub const WAIT_FOR_COMMAND_SESSION: &str = "Wait for command session";
466pub const READ_COMMAND_SESSION: &str = "Read command session";
467
468#[must_use]
476pub fn unified_exec_action_label(args: &Value) -> &'static str {
477 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
478 if action.eq_ignore_ascii_case("run") {
479 "Run command"
480 } else if action.eq_ignore_ascii_case("write") {
481 "Send command input"
482 } else if action.eq_ignore_ascii_case("poll") {
483 READ_COMMAND_SESSION
484 } else if action.eq_ignore_ascii_case("wait") {
485 WAIT_FOR_COMMAND_SESSION
486 } else if action.eq_ignore_ascii_case("continue") {
487 "Continue command session"
488 } else if action.eq_ignore_ascii_case("inspect") {
489 "Inspect command output"
490 } else if action.eq_ignore_ascii_case("list") {
491 "List command sessions"
492 } else if action.eq_ignore_ascii_case("close") {
493 "Close command session"
494 } else if action.eq_ignore_ascii_case("code") {
495 "Run code"
496 } else {
497 "Exec action"
498 }
499}
500
501#[must_use]
511pub fn verb_callout_headline(tool_name: &str, args: &Value, workspace_root: Option<&Path>) -> String {
512 let name = strip_mcp_prefix(tool_name);
513 if let Some(label) = session_followup_title(name, args) {
516 return label;
517 }
518 if name == "list_files" {
519 if let Some((title, _)) = describe_list_files(args, workspace_root) {
520 return title;
521 }
522 } else if name == "grep_file" {
523 if let Some((title, _)) = describe_grep_file(args, workspace_root) {
524 return title;
525 }
526 }
527 match name {
528 "read_file" | "read_pty_session" | "web_fetch" | "fetch_url" | "fetch" | "get_errors" | "list_files" => {
529 if let Some(base) = headline_basename(args) {
530 return format!("Read {base}");
531 }
532 if lookup_first_string(args, &["url"]).is_some() {
533 let (title, _) = describe_fetch_action(args);
534 return title;
535 }
536 }
537 "edit_file" | "write_file" | "create_file" | "delete_file" | "apply_patch" | "search_replace" => {
538 if let Some(base) = headline_basename(args) {
539 return format!("Edited {base}");
540 }
541 }
542 "exec_command" | "run_pty_cmd" | "create_pty_session" | "shell" | "bash" => {
543 if let Some(command) = command_text(args) {
544 return format!("Ran {}", compact_command_headline(&command));
545 }
546 }
547 "code_search" | "grep" | "grep_file" => {
548 if let Some((title, _)) = search_headline(name, args) {
549 return title;
550 }
551 }
552 "command_session_internal" => {
553 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
554 if !action.eq_ignore_ascii_case("run") {
555 return unified_exec_action_label(args).to_string();
556 }
557 if let Some(command) = command_text(args) {
558 return format!("Ran {}", compact_command_headline(&command));
559 }
560 }
561 "file_operation_internal" => {
562 let action = args.get("action").and_then(Value::as_str).unwrap_or("read");
563 if action.eq_ignore_ascii_case("read") {
564 if let Some(base) = headline_basename(args) {
565 return format!("Read {base}");
566 }
567 } else if ["write", "edit", "patch", "delete", "move", "copy"]
568 .iter()
569 .any(|known| action.eq_ignore_ascii_case(known))
570 && let Some(base) = headline_basename(args)
571 {
572 return format!("Edited {base}");
573 }
574 }
575 _ => {}
576 }
577 humanize_tool_name(tool_name)
578}
579
580#[must_use]
583pub fn session_followup_title(name: &str, args: &Value) -> Option<String> {
584 match name {
585 "send_pty_input" => Some("Send command input".to_string()),
586 "read_pty_session" => Some(READ_COMMAND_SESSION.to_string()),
587 "write_stdin" => Some(write_stdin_action_label(args).to_string()),
588 "command_session_internal" => {
589 let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
590 (!action.eq_ignore_ascii_case("run")).then(|| unified_exec_action_label(args).to_string())
591 }
592 _ => None,
593 }
594}
595
596#[must_use]
599pub fn search_headline(name: &str, args: &Value) -> Option<(String, &'static [&'static str])> {
600 if name == "code_search" {
601 return describe_code_search(args);
602 }
603 for key in ["pattern", "query"] {
604 if let Some(pattern) = lookup_string(args, key) {
605 let keys: &'static [&'static str] = if key == "pattern" { &["pattern"] } else { &["query"] };
606 return Some((format!("Search files for {}", truncate_middle(&pattern, 40)), keys));
607 }
608 }
609 None
610}
611
612fn headline_basename(args: &Value) -> Option<String> {
614 lookup_first_string(args, &["path", "file_path", "filepath", "target_path"])
615 .as_deref()
616 .and_then(|path| path.split(['/', '\\']).rfind(|segment| !segment.is_empty()))
617 .map(str::to_string)
618}
619
620#[must_use]
622pub fn command_text(args: &Value) -> Option<String> {
623 let text = if let Some(text) = ["command", "cmd", "raw_command", "bash_command"]
624 .iter()
625 .filter_map(|key| args.get(key).and_then(Value::as_str))
626 .find(|text| !text.trim().is_empty())
627 {
628 text.to_owned()
629 } else {
630 let parts: Vec<&str> = args.get("command")?.as_array()?.iter().filter_map(Value::as_str).collect();
631 if parts.iter().all(|part| part.trim().is_empty()) {
632 return None;
633 }
634 let joined = shell_words::join(parts);
635 (!joined.trim().is_empty()).then_some(joined)?
636 };
637 Some(text)
638}
639
640#[must_use]
642pub fn compact_command_headline(command: &str) -> String {
643 let line = command.lines().next().unwrap_or_default().trim();
644 let words = shell_words::split(line).unwrap_or_default();
645 let program = words
646 .first()
647 .map(String::as_str)
648 .or_else(|| line.split_whitespace().next())
649 .unwrap_or("command");
650 let first_word = program;
651 let first_program = first_word.split(['|', '&', ';', '<', '>']).next().unwrap_or("command");
652 let program = first_program
653 .rsplit(['/', '\\'])
654 .next()
655 .filter(|part| !part.is_empty())
656 .unwrap_or("command");
657 if first_word.len() != first_program.len() {
658 return program.to_string();
659 }
660 let target = words
661 .iter()
662 .skip(1)
663 .take_while(|word| !word.contains(['|', '&', ';', '<', '>']))
664 .filter(|word| !word.starts_with('-'))
665 .find_map(|word| {
666 let base = word.rsplit(['/', '\\']).next()?;
667 (base.contains('.')
668 && !base.starts_with('.')
669 && !base.ends_with('.')
670 && base.chars().all(|ch| ch.is_alphanumeric() || matches!(ch, '.' | '_' | '-')))
671 .then_some(base)
672 });
673 target.map_or_else(|| program.to_string(), |target| format!("{program} {target}"))
674}
675#[must_use]
678pub fn write_stdin_action_label(args: &Value) -> &'static str {
679 if let Some(action) = args.get("action").and_then(Value::as_str) {
680 if action.eq_ignore_ascii_case("wait") {
681 return WAIT_FOR_COMMAND_SESSION;
682 }
683 if action.eq_ignore_ascii_case("poll") {
684 return READ_COMMAND_SESSION;
685 }
686 if action.eq_ignore_ascii_case("inspect") {
687 return "Inspect command output";
688 }
689 if action.eq_ignore_ascii_case("close") {
690 return "Close command session";
691 }
692 if action.eq_ignore_ascii_case("terminate") {
693 return "Terminate command session";
694 }
695 if action.eq_ignore_ascii_case("write") {
696 return if has_session_input(args) {
699 "Send command input"
700 } else {
701 READ_COMMAND_SESSION
702 };
703 }
704 }
705 if has_session_input(args) {
706 "Send command input"
707 } else {
708 READ_COMMAND_SESSION
711 }
712}
713
714#[must_use]
716pub fn has_session_input(args: &Value) -> bool {
717 ["chars", "input", "text"]
718 .iter()
719 .any(|key| args.get(key).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))
720}
721
722#[must_use]
738pub fn harness_is_user_visible(kind: &vtcode_exec_events::HarnessEventKind) -> bool {
739 use vtcode_exec_events::HarnessEventKind::*;
740 match kind {
741 ToolLatencyRecorded
742 | PlanningStarted
743 | PlanningCompleted
744 | ContinuationStarted
745 | ContinuationSkipped
746 | EvaluationStarted
747 | EvaluationPassed
748 | RevisionStarted
749 | VerificationStarted
750 | VerificationPassed
751 | SnapshotCreated
752 | DelegatedAgentStatus
753 | SessionMessageSent
754 | SessionMessageReceived => false,
755 SessionMessageExpired
756 | TurnBlocked
757 | BlockedRecoveryStarted
758 | BlockedRecoveryFinished
759 | BlockedHandoffWritten
760 | BlockedHandoffResolved
761 | EvaluationFailed
762 | EscalationTriggered
763 | EscalationBypassed
764 | VerificationFailed
765 | ErrorRecovered
766 | ToolRetryAttempted
767 | SnapshotRestored
768 | SessionToolLimitIncreased
769 | ToolLoopLimitIncreased
770 | BackgroundSubprocessCompleted => true,
771 }
772}
773
774mod session_poll;
775
776pub use session_poll::{SessionPollKey, poll_run_tick, session_poll_key};
777
778#[cfg(test)]
779mod tests;