Skip to main content

vtcode_commons/
tool_headlines.rs

1//! Shared tool-call headlines and transcript detail lines.
2//!
3//! Single home for the display phrases both transcript surfaces render — the
4//! CLI (`src/agent/runloop/unified/tool_summary*`) and the desktop app
5//! (`vtcode-desktop/src/desktop/transcript/`) — so a headline or skip list can
6//! never drift between them. String-based by design (same contract as
7//! [`crate::tracker_title`]): callers walk their own payload shapes and
8//! converge here for the humanization, truncation, and fallback rules.
9//!
10//! Surface composition stays local: the CLI keeps its `(headline, used)`
11//! dispatcher, `MCP ` prefix policy, and TUI renderers; the desktop keeps its
12//! verb categories, single-line collapse, and GPUI renderers. Only the pure
13//! phrase builders live here.
14
15use 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/// First non-blank string under a single key, trimmed.
24#[must_use]
25pub fn lookup_string(args: &Value, key: &str) -> Option<String> {
26    lookup_first_string(args, &[key])
27}
28
29/// First non-blank string under the given keys, trimmed.
30///
31/// Blank and mistyped values are skipped so a headline never phrases
32/// whitespace: trimming here (not at each caller) keeps every describer
33/// total over messy agent payloads.
34#[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/// Display a path relative to the workspace root when it lies within it.
45///
46/// Returns the path unchanged when `workspace_root` is `None`, the path is
47/// not absolute, or it does not lie within the root (including the
48/// degenerate path-equals-root case, kept in its original form).
49#[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/// Keys whose values are file-system paths, shown relative to the workspace.
66#[must_use]
67pub fn is_path_key(key: &str) -> bool {
68    matches!(key, "path" | "file_path" | "filename" | "destination" | "source")
69}
70
71/// Humanize a parameter key (`timeout_secs` → `Timeout secs`).
72///
73/// Only the first letter is capitalized: detail lines read as labels, not
74/// titles. Tool *names* take [`humanize_tool_name`] instead, which splits
75/// word boundaries per word.
76#[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/// Human fallback for tool names the headline readers cannot phrase.
90///
91/// Strips MCP prefixes, then splits `snake_case` and `PascalCase`/`camelCase`
92/// boundaries into capitalized words (`DiagramCommand` → `Diagram Command`,
93/// `diagram_render` → `Diagram Render`). Only the first letter of each word
94/// is touched, so acronyms (`MCP`) and versions (`v2`) survive. Never
95/// returns blank: a name with no word characters falls back to itself.
96#[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    // Single char walk, no slicing: `_` always breaks, and a new word starts
103    // before an uppercase letter that follows a lowercase letter or digit.
104    // Acronym runs (`MCPTool`) stay whole rather than guessing.
105    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        // Only the first letter is touched, so acronyms (`MCP`) and versions
127        // (`v2`) survive; the rest keeps its original casing.
128        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/// Bare tool name from an MCP-qualified one (`None` for non-MCP names).
139///
140/// Accepts the `mcp__server__tool`, `mcp::provider::tool`, and legacy
141/// `mcp_tool` spellings. Canonical MCP name parser — do not fork the
142/// prefix/segment handling per call site, so every surface labels the same
143/// tool identically. Surfaces that drop the prefix unconditionally take
144/// [`strip_mcp_prefix`] instead.
145#[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/// MCP prefixes stripped, or the name itself when it carries none.
160///
161/// Total form of [`mcp_tool_display_name`] for surfaces that never show the
162/// prefix. The legacy single-underscore arm runs last, so it cannot misfire
163/// on the qualified `mcp__` form.
164#[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/// Raw content keys too verbose for a summary row (commands, file bodies).
170#[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
188/// Whether `text` is an accepted query alias for this tool rather than a body.
189///
190/// `code_search` phrases `text` as a last-resort query alias, so an
191/// unconsumed `text` value shows instead of hiding as verbose content;
192/// everywhere else (edits, unknown tools) `text` stays a hidden body.
193fn 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/// Parameter keys that are infrastructure/plumbing noise, omitted from the
198/// human-facing summary. Session plumbing (`session_id`, `chars`, wait
199/// deadlines) is not noise: [`exec_session_param_detail`] folds it into one
200/// identity row instead. Search strings (`query`) are content, never
201/// plumbing: they hide only when the headline consumed them.
202#[must_use]
203pub fn is_noise_param(key: &str) -> bool {
204    matches!(
205        key,
206        // Timeouts and size limits
207        "timeout_secs"
208            | "timeout"
209            | "max_bytes"
210            | "max_matches"
211            // Search plumbing
212            | "debug_query"
213            | "strictness"
214            | "case_sensitive"
215            | "literal"
216            | "context_lines"
217            // Execution plumbing
218            | "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            // Tool identity / routing
230            | "type"
231            | "tool_call_id"
232            | "call_type"
233            // Redundant with summary headline (e.g., "Read file" already implies action=read)
234            | "action"
235            // Output caps, same plumbing class as the size limits above.
236            | "max_output_tokens"
237            | "max_tokens"
238    )
239}
240
241/// Human `Key: value` lines for the arguments a headline does not consume.
242///
243/// Verbose content keys, plumbing noise, and the caller-supplied `skipped`
244/// keys (headline-consumed) stay out; strings truncate to 60 columns, paths
245/// relativize against the workspace, lists summarize to two items, and only
246/// `true` flags and non-zero numbers render. Key order follows
247/// `serde_json::Map` iteration. An empty `skipped` slice shows every
248/// displayable key — no separate include-all flag needed. `tool_name` (MCP
249/// prefixes accepted) decides the `text` exemption below.
250#[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                // Render file-system path values relative to the workspace root.
269                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                // Skip zero-valued numbers — they are defaults and add no information.
288                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/// One row for an exec-session follow-up: session identity plus an explicit
300/// wait deadline.
301///
302/// Output-token caps, yield windows, and the raw stdin payload are
303/// deliberately dropped: the model receives the arguments unchanged, and the
304/// reader only needs the session at a glance. Returns `None` when the call
305/// carries neither, so non-session tools keep their normal detail rows.
306#[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
325/// Exact flag tokens that introduce an inline script for a runner.
326/// Token-exact (not substring) so `grep -c` / `--code-review` never match.
327const SCRIPT_RUNNER_FLAGS: &[&str] = &["-c", "-e", "--code"];
328
329/// Program-only label for callers that intentionally hide arguments.
330///
331/// User-visible `Ran …` surfaces use [`command_headline_with_args`] instead so
332/// the transcript identifies what was actually executed.
333///
334/// Multi-line commands preview their first non-empty line; long commands
335/// are head-truncated at a word boundary with a trailing ellipsis. The
336/// mid-string ellipsis of `truncate_middle` is avoided on purpose: cutting
337/// `checkpoints/turn_1032` into `tur…ool_calls` reads as a rendering bug.
338///
339/// When the first line is only a script-runner prefix (`python3 -c "`,
340/// bare `python3 -c`, or an unclosed quote on a `-c`/`-e`/`--code` runner),
341/// the following lines are folded in so the header shows real script content
342/// (`python3 -c "import json …`) instead of a dangling `python3 -c "`.
343#[must_use]
344pub fn preview_command(command: &str, max_len: usize) -> String {
345    if max_len == 0 {
346        return String::new();
347    }
348    let lines: Vec<&str> = command.lines().map(str::trim).filter(|line| !line.is_empty()).collect();
349    let Some((first, rest)) = lines.split_first() else {
350        return String::new();
351    };
352    let mut first_line = collapse_whitespace(first);
353    if is_script_prefix_only(&first_line) && !rest.is_empty() {
354        // Bounded: only fold enough continuation lines to fill the preview
355        // budget instead of materializing a 100-line script into one String.
356        let need = max_len.saturating_sub(first_line.chars().count()).saturating_add(16);
357        let mut rest_parts = Vec::new();
358        let mut rest_len = 0usize;
359        for line in rest {
360            let collapsed = collapse_whitespace(line);
361            if collapsed.is_empty() {
362                continue;
363            }
364            rest_len += collapsed.chars().count() + 1;
365            rest_parts.push(collapsed);
366            if rest_len >= need {
367                break;
368            }
369        }
370        if !rest_parts.is_empty() {
371            let rest = rest_parts.join(" ");
372            if first_line.ends_with('"') || first_line.ends_with('\'') {
373                // `python3 -c "` + `import json` -> `python3 -c "import json`
374                // (no extra space: the newline after the opening quote is
375                // insignificant, and `collapse_whitespace` would leave a
376                // distracting `" import` gap).
377                first_line.push_str(&rest);
378            } else {
379                first_line.push(' ');
380                first_line.push_str(&rest);
381            }
382        }
383    }
384    if first_line.chars().count() <= max_len {
385        return first_line;
386    }
387
388    let budget = max_len.saturating_sub(1);
389    let mut head: String = first_line.chars().take(budget).collect();
390    if let Some(last_space) = head.rfind(char::is_whitespace) {
391        // Only honor the word boundary when it keeps at least half the budget,
392        // so a late first space does not collapse the preview to almost nothing.
393        if last_space >= budget / 2 {
394            head.truncate(last_space);
395        }
396    }
397    format!("{}…", head.trim_end())
398}
399
400/// Full-length variant of [`preview_command`] for transcript surfaces.
401///
402/// Keeps the first-line selection and script-runner prefix folding (so
403/// `python3 -c "` still pulls in script content) but applies no length cap:
404/// the selected line shows in full, with viewport-aware wrapping owning the
405/// overflow instead of a `…` truncation.
406#[must_use]
407pub fn preview_full_command(command: &str) -> String {
408    preview_command(command, usize::MAX)
409}
410
411/// Command text for user-visible `Ran …` rows, arguments included.
412///
413/// Reuses [`preview_full_command`] so script-runner prefixes (for example
414/// `python3 -c "`) still fold into readable content. Unlike
415/// [`compact_command_headline`], this keeps every argument of the first
416/// command: users must be able to tell what was actually executed from the
417/// transcript, not only which program was launched.
418#[must_use]
419pub fn command_headline_with_args(command: &str) -> String {
420    let full = preview_full_command(command);
421    let collapsed = collapse_whitespace(&full);
422    if collapsed.is_empty() {
423        "command".to_string()
424    } else {
425        collapsed
426    }
427}
428
429/// Single-line variant of [`command_headline_with_args`] for one-row slots
430/// (desktop titles and compact activity rows). Both ends survive truncation
431/// so a long command still exposes its distinguishing arguments.
432#[must_use]
433pub fn command_headline_single_line(command: &str, max_len: usize) -> String {
434    truncate_middle(&command_headline_with_args(command), max_len)
435}
436
437/// Whether `program` names a known inline-script runner (`python3`, `bash`,
438/// `node`, …). Compared against the path basename so `/usr/bin/python3` and
439/// Windows-style `C:\Python\python.exe` both match, keeping the check
440/// token-exact instead of substring-based.
441fn is_script_runner_program(program: &str) -> bool {
442    let base = program.rsplit(['/', '\\']).next().unwrap_or(program).to_ascii_lowercase();
443    base.starts_with("python")
444        || matches!(
445            base.as_str(),
446            "bash" | "sh" | "zsh" | "node" | "ruby" | "perl" | "php" | "deno" | "bun" | "pwsh" | "powershell"
447        )
448}
449
450/// Whether the first preview line is just a script-runner prefix with no
451/// usable script content (e.g. `python3 -c "` or bare `python3 -c`).
452///
453/// Rendering such a prefix alone reads as broken (`• Ran python3 -c "`).
454/// Token-exact on both program and flag so `grep -c`, `grep -e`, and
455/// `--code-review` never match. Unclosed quoting is detected with the
456/// canonical `shell_words` parser (not raw `'` counting) so contractions
457/// inside a balanced script (`python3 -c "don't …"`) do not misfire.
458fn is_script_prefix_only(first_line: &str) -> bool {
459    let mut tokens = first_line.split_whitespace();
460    let Some(program) = tokens.next() else {
461        return false;
462    };
463    if !is_script_runner_program(program) {
464        return false;
465    }
466    if !tokens.clone().any(|token| SCRIPT_RUNNER_FLAGS.contains(&token)) {
467        return false;
468    }
469    // Bare flag with no script yet: `python3 -c`.
470    let token_count = 1 + tokens.clone().count();
471    if token_count == 2 {
472        return true;
473    }
474    // Unclosed quoting means the script continues on later lines, e.g.
475    // `python3 -c "` or `python3 -c "import json`.
476    shell_words::split(first_line).is_err()
477}
478
479/// Session follow-up labels that coalesce into one transcript row per run.
480///
481/// Both surfaces (CLI renderer, desktop app) collapse consecutive polls and
482/// waits for one session; matching on these consts (never retyped literals)
483/// keeps the run predicate and the row titles in agreement by construction.
484pub const WAIT_FOR_COMMAND_SESSION: &str = "Wait for command session";
485pub const READ_COMMAND_SESSION: &str = "Read command session";
486
487/// Action-aware label for `command_session_internal` follow-up calls.
488///
489/// Canonical home of the session labels: `vtcode-core` re-exports this, and
490/// transcript surfaces call it directly. Launches take `Run command` /
491/// `Run code`; callers that phrase launches from the command itself (rather
492/// than a generic label) resolve [`crate::tool_intent::command_session_action`]
493/// first and skip the `run` action.
494#[must_use]
495pub fn unified_exec_action_label(args: &Value) -> &'static str {
496    let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
497    if action.eq_ignore_ascii_case("run") {
498        "Run command"
499    } else if action.eq_ignore_ascii_case("write") {
500        "Send command input"
501    } else if action.eq_ignore_ascii_case("poll") {
502        READ_COMMAND_SESSION
503    } else if action.eq_ignore_ascii_case("wait") {
504        WAIT_FOR_COMMAND_SESSION
505    } else if action.eq_ignore_ascii_case("continue") {
506        "Continue command session"
507    } else if action.eq_ignore_ascii_case("inspect") {
508        "Inspect command output"
509    } else if action.eq_ignore_ascii_case("list") {
510        "List command sessions"
511    } else if action.eq_ignore_ascii_case("close") {
512        "Close command session"
513    } else if action.eq_ignore_ascii_case("code") {
514        "Run code"
515    } else {
516        "Exec action"
517    }
518}
519
520/// Verb-led running callout for any tool call (`Read main.rs`, `Ran cargo
521/// check`): the surface-neutral form of the headline an already-running
522/// call shows so the live status agrees with the completed summary row.
523///
524/// Falls back to the prettified tool name ([`humanize_tool_name`]) when the
525/// call has no ownable headline — never a raw identifier. `command` preview:
526/// compact executable and file target, matching the completed-row preview.
527/// `workspace_root` relativizes `list_files` and
528/// `grep_file` path headlines exactly as those describers do.
529#[must_use]
530pub fn verb_callout_headline(tool_name: &str, args: &Value, workspace_root: Option<&Path>) -> String {
531    let name = strip_mcp_prefix(tool_name);
532    // Session follow-ups take the action-aware label first; a `run` launch
533    // falls through to the argument gist (the command itself).
534    if let Some(label) = session_followup_title(name, args) {
535        return label;
536    }
537    if name == tool_names::LIST_FILES {
538        if let Some((title, _)) = describe_list_files(args, workspace_root) {
539            return title;
540        }
541    } else if name == tool_names::GREP_FILE {
542        if let Some((title, _)) = describe_grep_file(args, workspace_root) {
543            return title;
544        }
545    } else if name == tool_names::COMPUTER_USE {
546        let (title, _) = describe_computer_use(args);
547        return title;
548    }
549    match name {
550        tool_names::READ_FILE
551        | tool_names::READ_PTY_SESSION
552        | tool_names::WEB_FETCH
553        | tool_names::FETCH_URL
554        | tool_names::FETCH
555        | tool_names::GET_ERRORS
556        | tool_names::LIST_FILES => {
557            if let Some(base) = headline_basename(args) {
558                return format!("Read {base}");
559            }
560            if lookup_first_string(args, &["url"]).is_some() {
561                let (title, _) = describe_fetch_action(args);
562                return title;
563            }
564        }
565        tool_names::EDIT_FILE
566        | tool_names::WRITE_FILE
567        | tool_names::CREATE_FILE
568        | tool_names::DELETE_FILE
569        | tool_names::APPLY_PATCH
570        | tool_names::SEARCH_REPLACE => {
571            if let Some(base) = headline_basename(args) {
572                return format!("Edited {base}");
573            }
574        }
575        tool_names::EXEC_COMMAND
576        | tool_names::RUN_PTY_CMD
577        | tool_names::CREATE_PTY_SESSION
578        | tool_names::SHELL
579        | tool_names::BASH_ALIAS => {
580            if let Some(command) = command_text(args) {
581                return format!("Ran {}", command_headline_with_args(&command));
582            }
583        }
584        tool_names::CODE_SEARCH | tool_names::GREP | tool_names::GREP_FILE => {
585            if let Some((title, _)) = search_headline(name, args) {
586                return title;
587            }
588        }
589        tool_names::UNIFIED_EXEC => {
590            let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
591            if !action.eq_ignore_ascii_case("run") {
592                return unified_exec_action_label(args).to_string();
593            }
594            if let Some(command) = command_text(args) {
595                return format!("Ran {}", command_headline_with_args(&command));
596            }
597        }
598        tool_names::UNIFIED_FILE => {
599            let action = args.get("action").and_then(Value::as_str).unwrap_or("read");
600            if action.eq_ignore_ascii_case("read") {
601                if let Some(base) = headline_basename(args) {
602                    return format!("Read {base}");
603                }
604            } else if ["write", "edit", "patch", "delete", "move", "copy"]
605                .iter()
606                .any(|known| action.eq_ignore_ascii_case(known))
607                && let Some(base) = headline_basename(args)
608            {
609                return format!("Edited {base}");
610            }
611        }
612        _ => {}
613    }
614    humanize_tool_name(tool_name)
615}
616
617/// Action-aware title for session follow-up calls; `None` falls through to the
618/// argument gist (`run` launches show the command text instead).
619#[must_use]
620pub fn session_followup_title(name: &str, args: &Value) -> Option<String> {
621    match name {
622        tool_names::SEND_PTY_INPUT => Some("Send command input".to_string()),
623        tool_names::READ_PTY_SESSION => Some(READ_COMMAND_SESSION.to_string()),
624        tool_names::WRITE_STDIN => Some(write_stdin_action_label(args).to_string()),
625        tool_names::UNIFIED_EXEC => {
626            let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
627            (!action.eq_ignore_ascii_case("run")).then(|| unified_exec_action_label(args).to_string())
628        }
629        _ => None,
630    }
631}
632
633/// Search headline per tool: `code_search` takes the shared describer;
634/// anything else phrases a file search over the first of pattern/query.
635#[must_use]
636pub fn search_headline(name: &str, args: &Value) -> Option<(String, &'static [&'static str])> {
637    if name == tool_names::CODE_SEARCH {
638        return describe_code_search(args);
639    }
640    for key in ["pattern", "query"] {
641        if let Some(pattern) = lookup_string(args, key) {
642            let keys: &'static [&'static str] = if key == "pattern" { &["pattern"] } else { &["query"] };
643            return Some((format!("Search files for {}", truncate_middle(&pattern, 40)), keys));
644        }
645    }
646    None
647}
648
649/// Basename of the path argument, in service display order.
650fn headline_basename(args: &Value) -> Option<String> {
651    lookup_first_string(args, &["path", "file_path", "filepath", "target_path"])
652        .as_deref()
653        .and_then(|path| path.split(['/', '\\']).rfind(|segment| !segment.is_empty()))
654        .map(str::to_string)
655}
656
657/// Full command text from a launch's string or argument-array form.
658#[must_use]
659pub fn command_text(args: &Value) -> Option<String> {
660    let text = if let Some(text) = ["command", "cmd", "raw_command", "bash_command"]
661        .iter()
662        .filter_map(|key| args.get(key).and_then(Value::as_str))
663        .find(|text| !text.trim().is_empty())
664    {
665        text.to_owned()
666    } else {
667        let parts: Vec<&str> = args.get("command")?.as_array()?.iter().filter_map(Value::as_str).collect();
668        if parts.iter().all(|part| part.trim().is_empty()) {
669            return None;
670        }
671        let joined = shell_words::join(parts);
672        (!joined.trim().is_empty()).then_some(joined)?
673    };
674    Some(text)
675}
676
677/// A quiet command headline that never exposes the full shell expression.
678#[must_use]
679pub fn compact_command_headline(command: &str) -> String {
680    let line = command.lines().next().unwrap_or_default().trim();
681    let words = shell_words::split(line).unwrap_or_default();
682    let program = words
683        .first()
684        .map(String::as_str)
685        .or_else(|| line.split_whitespace().next())
686        .unwrap_or("command");
687    let first_word = program;
688    let first_program = first_word.split(['|', '&', ';', '<', '>']).next().unwrap_or("command");
689    let program = first_program
690        .rsplit(['/', '\\'])
691        .next()
692        .filter(|part| !part.is_empty())
693        .unwrap_or("command");
694    if first_word.len() != first_program.len() {
695        return program.to_string();
696    }
697    let target = words
698        .iter()
699        .skip(1)
700        .take_while(|word| !word.contains(['|', '&', ';', '<', '>']))
701        .filter(|word| !word.starts_with('-'))
702        .find_map(|word| {
703            let base = word.rsplit(['/', '\\']).next()?;
704            (base.contains('.')
705                && !base.starts_with('.')
706                && !base.ends_with('.')
707                && base.chars().all(|ch| ch.is_alphanumeric() || matches!(ch, '.' | '_' | '-')))
708            .then_some(base)
709        });
710    target.map_or_else(|| program.to_string(), |target| format!("{program} {target}"))
711}
712/// otherwise input sniffing decides send vs read so pure waits never
713/// misrender as sends.
714#[must_use]
715pub fn write_stdin_action_label(args: &Value) -> &'static str {
716    if let Some(action) = args.get("action").and_then(Value::as_str) {
717        if action.eq_ignore_ascii_case("wait") {
718            return WAIT_FOR_COMMAND_SESSION;
719        }
720        if action.eq_ignore_ascii_case("poll") {
721            return READ_COMMAND_SESSION;
722        }
723        if action.eq_ignore_ascii_case("inspect") {
724            return "Inspect command output";
725        }
726        if action.eq_ignore_ascii_case("close") {
727            return "Close command session";
728        }
729        if action.eq_ignore_ascii_case("terminate") {
730            return "Terminate command session";
731        }
732        if action.eq_ignore_ascii_case("write") {
733            // Match `write_stdin_dispatch`: explicit write with empty/missing
734            // input polls instead of sending, so label it as a read.
735            return if has_session_input(args) {
736                "Send command input"
737            } else {
738                READ_COMMAND_SESSION
739            };
740        }
741    }
742    if has_session_input(args) {
743        "Send command input"
744    } else {
745        // A session_id-only follow-up polls output; calling it "Send" misleads
746        // (screenshot 2026-10-02: pure waits rendered as sends).
747        READ_COMMAND_SESSION
748    }
749}
750
751/// Whether the call carries a non-empty stdin payload under the input keys.
752#[must_use]
753pub fn has_session_input(args: &Value) -> bool {
754    ["chars", "input", "text"]
755        .iter()
756        .any(|key| args.get(key).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))
757}
758
759/// Whether a harness event belongs in the user-visible transcript.
760///
761/// Routine telemetry — latency records, lifecycle starts and passes,
762/// per-turn snapshots, delegation observations, mailbox plumbing — stays out:
763/// the transcript is a conversation surface, and the canonical event still
764/// carries the complete evidence for forensics. Failures, blocks, losses
765/// (including an expired undelivered mailbox message), recoveries, rewinds,
766/// background completions, and limit grants stay: the user can act on them.
767/// Exhaustive on purpose — a new `HarnessEventKind` must make a conscious
768/// display choice here at compile time instead of silently inheriting
769/// visibility.
770///
771/// Conversational surfaces (CLI transcript, desktop transcript) filter
772/// through this; forensic surfaces (log viewers, event exports) keep the
773/// complete stream.
774pub use vtcode_exec_events::harness_is_user_visible;
775
776mod session_poll;
777
778pub use session_poll::{SessionPollKey, poll_run_tick, session_poll_key};
779
780#[cfg(test)]
781mod tests;