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/// Summarize a string list to two items plus an overflow count.
170#[must_use]
171pub fn summarize_list(items: &[String]) -> String {
172    if items.is_empty() {
173        return String::new();
174    }
175    let shown: Vec<String> = items.iter().take(2).map(|s| truncate_middle(s, 60)).collect();
176    if items.len() > 2 {
177        format!("{} +{} more", shown.join(", "), items.len() - 2)
178    } else {
179        shown.join(", ")
180    }
181}
182
183/// Raw content keys too verbose for a summary row (commands, file bodies).
184#[must_use]
185pub fn is_verbose_key(key: &str) -> bool {
186    matches!(
187        key,
188        "command"
189            | "raw_command"
190            | "bash_command"
191            | "cmd"
192            | "old_str"
193            | "new_str"
194            | "content"
195            | "new_content"
196            | "text"
197            | "patch"
198            | "code"
199    )
200}
201
202/// Whether `text` is an accepted query alias for this tool rather than a body.
203///
204/// `code_search` phrases `text` as a last-resort query alias, so an
205/// unconsumed `text` value shows instead of hiding as verbose content;
206/// everywhere else (edits, unknown tools) `text` stays a hidden body.
207fn text_is_search_query(tool_name: &str, key: &str) -> bool {
208    key == "text" && strip_mcp_prefix(tool_name) == tool_names::CODE_SEARCH
209}
210
211/// Parameter keys that are infrastructure/plumbing noise, omitted from the
212/// human-facing summary. Session plumbing (`session_id`, `chars`, wait
213/// deadlines) is not noise: [`exec_session_param_detail`] folds it into one
214/// identity row instead. Search strings (`query`) are content, never
215/// plumbing: they hide only when the headline consumed them.
216#[must_use]
217pub fn is_noise_param(key: &str) -> bool {
218    matches!(
219        key,
220        // Timeouts and size limits
221        "timeout_secs"
222            | "timeout"
223            | "max_bytes"
224            | "max_matches"
225            // Search plumbing
226            | "debug_query"
227            | "strictness"
228            | "case_sensitive"
229            | "literal"
230            | "context_lines"
231            // Execution plumbing
232            | "shell"
233            | "login"
234            | "tty"
235            | "sandbox_permissions"
236            | "additional_permissions"
237            | "justification"
238            | "prefix_rule"
239            | "workdir"
240            | "cwd"
241            | "language"
242            | "spool_path"
243            // Tool identity / routing
244            | "type"
245            | "tool_call_id"
246            | "call_type"
247            // Redundant with summary headline (e.g., "Read file" already implies action=read)
248            | "action"
249            // Output caps, same plumbing class as the size limits above.
250            | "max_output_tokens"
251            | "max_tokens"
252    )
253}
254
255/// Human `Key: value` lines for the arguments a headline does not consume.
256///
257/// Verbose content keys, plumbing noise, and the caller-supplied `skipped`
258/// keys (headline-consumed) stay out; strings truncate to 60 columns, paths
259/// relativize against the workspace, lists summarize to two items, and only
260/// `true` flags and non-zero numbers render. Key order follows
261/// `serde_json::Map` iteration. An empty `skipped` slice shows every
262/// displayable key — no separate include-all flag needed. `tool_name` (MCP
263/// prefixes accepted) decides the `text` exemption below.
264#[must_use]
265pub fn collect_param_details(
266    tool_name: &str,
267    args: &Value,
268    skipped: &[&str],
269    workspace_root: Option<&Path>,
270) -> Vec<String> {
271    let mut details = Vec::new();
272    let Some(map) = args.as_object() else {
273        return details;
274    };
275    for (key, value) in map {
276        let verbose_hidden = is_verbose_key(key) && !text_is_search_query(tool_name, key);
277        if is_noise_param(key) || verbose_hidden || skipped.contains(&key.as_str()) {
278            continue;
279        }
280        match value {
281            Value::String(s) if !s.is_empty() => {
282                // Render file-system path values relative to the workspace root.
283                let display: Cow<'_, str> = if is_path_key(key) {
284                    relativize_to_workspace(s, workspace_root)
285                } else {
286                    Cow::Borrowed(s.as_str())
287                };
288                details.push(format!("{}: {}", humanize_key(key), truncate_middle(&display, 60)))
289            }
290            Value::Bool(true) => {
291                details.push(humanize_key(key));
292            }
293            Value::Array(items) => {
294                let strings: Vec<String> =
295                    items.iter().filter_map(|item| item.as_str().map(|s| s.to_string())).collect();
296                if !strings.is_empty() {
297                    details.push(format!("{}: {}", humanize_key(key), summarize_list(&strings)));
298                }
299            }
300            Value::Number(num) => {
301                // Skip zero-valued numbers — they are defaults and add no information.
302                if num.as_f64().is_some_and(|n| n == 0.0) {
303                    continue;
304                }
305                details.push(format!("{}: {}", humanize_key(key), num));
306            }
307            _ => {}
308        }
309    }
310    details
311}
312
313/// One row for an exec-session follow-up: session identity plus an explicit
314/// wait deadline.
315///
316/// Output-token caps, yield windows, and the raw stdin payload are
317/// deliberately dropped: the model receives the arguments unchanged, and the
318/// reader only needs the session at a glance. Returns `None` when the call
319/// carries neither, so non-session tools keep their normal detail rows.
320#[must_use]
321pub fn exec_session_param_detail(args: &Value) -> Option<String> {
322    let session = lookup_string(args, "session_id").map(|id| format!("Session {id}"));
323    let wait = ["wait_timeout_seconds", "timeout_seconds"]
324        .iter()
325        .find_map(|key| args.get(key).and_then(Value::as_u64))
326        .filter(|secs| *secs > 0)
327        .map(|secs| format!("wait up to {secs}s"));
328
329    let parts = [session, wait].into_iter().flatten().collect::<Vec<_>>();
330    (!parts.is_empty()).then(|| parts.join(" · "))
331}
332
333mod descriptors;
334pub use descriptors::{
335    describe_code_search, describe_computer_use, describe_fetch_action, describe_grep_file, describe_list_files,
336};
337
338/// Exact flag tokens that introduce an inline script for a runner.
339/// Token-exact (not substring) so `grep -c` / `--code-review` never match.
340const SCRIPT_RUNNER_FLAGS: &[&str] = &["-c", "-e", "--code"];
341
342/// Compact single-line preview of a command for `• Ran …` headers.
343///
344/// Multi-line commands preview their first non-empty line; long commands
345/// are head-truncated at a word boundary with a trailing ellipsis. The
346/// mid-string ellipsis of `truncate_middle` is avoided on purpose: cutting
347/// `checkpoints/turn_1032` into `tur…ool_calls` reads as a rendering bug.
348///
349/// When the first line is only a script-runner prefix (`python3 -c "`,
350/// bare `python3 -c`, or an unclosed quote on a `-c`/`-e`/`--code` runner),
351/// the following lines are folded in so the header shows real script content
352/// (`python3 -c "import json …`) instead of a dangling `python3 -c "`.
353#[must_use]
354pub fn preview_command(command: &str, max_len: usize) -> String {
355    if max_len == 0 {
356        return String::new();
357    }
358    let lines: Vec<&str> = command.lines().map(str::trim).filter(|line| !line.is_empty()).collect();
359    let Some((first, rest)) = lines.split_first() else {
360        return String::new();
361    };
362    let mut first_line = collapse_whitespace(first);
363    if is_script_prefix_only(&first_line) && !rest.is_empty() {
364        // Bounded: only fold enough continuation lines to fill the preview
365        // budget instead of materializing a 100-line script into one String.
366        let need = max_len.saturating_sub(first_line.chars().count()).saturating_add(16);
367        let mut rest_parts = Vec::new();
368        let mut rest_len = 0usize;
369        for line in rest {
370            let collapsed = collapse_whitespace(line);
371            if collapsed.is_empty() {
372                continue;
373            }
374            rest_len += collapsed.chars().count() + 1;
375            rest_parts.push(collapsed);
376            if rest_len >= need {
377                break;
378            }
379        }
380        if !rest_parts.is_empty() {
381            let rest = rest_parts.join(" ");
382            if first_line.ends_with('"') || first_line.ends_with('\'') {
383                // `python3 -c "` + `import json` -> `python3 -c "import json`
384                // (no extra space: the newline after the opening quote is
385                // insignificant, and `collapse_whitespace` would leave a
386                // distracting `" import` gap).
387                first_line.push_str(&rest);
388            } else {
389                first_line.push(' ');
390                first_line.push_str(&rest);
391            }
392        }
393    }
394    if first_line.chars().count() <= max_len {
395        return first_line;
396    }
397
398    let budget = max_len.saturating_sub(1);
399    let mut head: String = first_line.chars().take(budget).collect();
400    if let Some(last_space) = head.rfind(char::is_whitespace) {
401        // Only honor the word boundary when it keeps at least half the budget,
402        // so a late first space does not collapse the preview to almost nothing.
403        if last_space >= budget / 2 {
404            head.truncate(last_space);
405        }
406    }
407    format!("{}…", head.trim_end())
408}
409
410/// Full-length variant of [`preview_command`] for transcript surfaces.
411///
412/// Keeps the first-line selection and script-runner prefix folding (so
413/// `python3 -c "` still pulls in script content) but applies no length cap:
414/// the selected line shows in full, with viewport-aware wrapping owning the
415/// overflow instead of a `…` truncation.
416#[must_use]
417pub fn preview_full_command(command: &str) -> String {
418    preview_command(command, usize::MAX)
419}
420
421/// Whether `program` names a known inline-script runner (`python3`, `bash`,
422/// `node`, …). Compared against the path basename so `/usr/bin/python3` and
423/// Windows-style `C:\Python\python.exe` both match, keeping the check
424/// token-exact instead of substring-based.
425fn is_script_runner_program(program: &str) -> bool {
426    let base = program.rsplit(['/', '\\']).next().unwrap_or(program).to_ascii_lowercase();
427    base.starts_with("python")
428        || matches!(
429            base.as_str(),
430            "bash" | "sh" | "zsh" | "node" | "ruby" | "perl" | "php" | "deno" | "bun" | "pwsh" | "powershell"
431        )
432}
433
434/// Whether the first preview line is just a script-runner prefix with no
435/// usable script content (e.g. `python3 -c "` or bare `python3 -c`).
436///
437/// Rendering such a prefix alone reads as broken (`• Ran python3 -c "`).
438/// Token-exact on both program and flag so `grep -c`, `grep -e`, and
439/// `--code-review` never match. Unclosed quoting is detected with the
440/// canonical `shell_words` parser (not raw `'` counting) so contractions
441/// inside a balanced script (`python3 -c "don't …"`) do not misfire.
442fn is_script_prefix_only(first_line: &str) -> bool {
443    let mut tokens = first_line.split_whitespace();
444    let Some(program) = tokens.next() else {
445        return false;
446    };
447    if !is_script_runner_program(program) {
448        return false;
449    }
450    if !tokens.clone().any(|token| SCRIPT_RUNNER_FLAGS.contains(&token)) {
451        return false;
452    }
453    // Bare flag with no script yet: `python3 -c`.
454    let token_count = 1 + tokens.clone().count();
455    if token_count == 2 {
456        return true;
457    }
458    // Unclosed quoting means the script continues on later lines, e.g.
459    // `python3 -c "` or `python3 -c "import json`.
460    shell_words::split(first_line).is_err()
461}
462
463/// Session follow-up labels that coalesce into one transcript row per run.
464///
465/// Both surfaces (CLI renderer, desktop app) collapse consecutive polls and
466/// waits for one session; matching on these consts (never retyped literals)
467/// keeps the run predicate and the row titles in agreement by construction.
468pub const WAIT_FOR_COMMAND_SESSION: &str = "Wait for command session";
469pub const READ_COMMAND_SESSION: &str = "Read command session";
470
471/// Action-aware label for `command_session_internal` follow-up calls.
472///
473/// Canonical home of the session labels: `vtcode-core` re-exports this, and
474/// transcript surfaces call it directly. Launches take `Run command` /
475/// `Run code`; callers that phrase launches from the command itself (rather
476/// than a generic label) resolve [`crate::tool_intent::command_session_action`]
477/// first and skip the `run` action.
478#[must_use]
479pub fn unified_exec_action_label(args: &Value) -> &'static str {
480    let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
481    if action.eq_ignore_ascii_case("run") {
482        "Run command"
483    } else if action.eq_ignore_ascii_case("write") {
484        "Send command input"
485    } else if action.eq_ignore_ascii_case("poll") {
486        READ_COMMAND_SESSION
487    } else if action.eq_ignore_ascii_case("wait") {
488        WAIT_FOR_COMMAND_SESSION
489    } else if action.eq_ignore_ascii_case("continue") {
490        "Continue command session"
491    } else if action.eq_ignore_ascii_case("inspect") {
492        "Inspect command output"
493    } else if action.eq_ignore_ascii_case("list") {
494        "List command sessions"
495    } else if action.eq_ignore_ascii_case("close") {
496        "Close command session"
497    } else if action.eq_ignore_ascii_case("code") {
498        "Run code"
499    } else {
500        "Exec action"
501    }
502}
503
504/// Verb-led running callout for any tool call (`Read main.rs`, `Ran cargo
505/// check`): the surface-neutral form of the headline an already-running
506/// call shows so the live status agrees with the completed summary row.
507///
508/// Falls back to the prettified tool name ([`humanize_tool_name`]) when the
509/// call has no ownable headline — never a raw identifier. `command` preview:
510/// compact executable and file target, matching the completed-row preview.
511/// `workspace_root` relativizes `list_files` and
512/// `grep_file` path headlines exactly as those describers do.
513#[must_use]
514pub fn verb_callout_headline(tool_name: &str, args: &Value, workspace_root: Option<&Path>) -> String {
515    let name = strip_mcp_prefix(tool_name);
516    // Session follow-ups take the action-aware label first; a `run` launch
517    // falls through to the argument gist (the command itself).
518    if let Some(label) = session_followup_title(name, args) {
519        return label;
520    }
521    if name == tool_names::LIST_FILES {
522        if let Some((title, _)) = describe_list_files(args, workspace_root) {
523            return title;
524        }
525    } else if name == tool_names::GREP_FILE {
526        if let Some((title, _)) = describe_grep_file(args, workspace_root) {
527            return title;
528        }
529    } else if name == tool_names::COMPUTER_USE {
530        let (title, _) = describe_computer_use(args);
531        return title;
532    }
533    match name {
534        tool_names::READ_FILE
535        | tool_names::READ_PTY_SESSION
536        | tool_names::WEB_FETCH
537        | tool_names::FETCH_URL
538        | tool_names::FETCH
539        | tool_names::GET_ERRORS
540        | tool_names::LIST_FILES => {
541            if let Some(base) = headline_basename(args) {
542                return format!("Read {base}");
543            }
544            if lookup_first_string(args, &["url"]).is_some() {
545                let (title, _) = describe_fetch_action(args);
546                return title;
547            }
548        }
549        tool_names::EDIT_FILE
550        | tool_names::WRITE_FILE
551        | tool_names::CREATE_FILE
552        | tool_names::DELETE_FILE
553        | tool_names::APPLY_PATCH
554        | tool_names::SEARCH_REPLACE => {
555            if let Some(base) = headline_basename(args) {
556                return format!("Edited {base}");
557            }
558        }
559        tool_names::EXEC_COMMAND
560        | tool_names::RUN_PTY_CMD
561        | tool_names::CREATE_PTY_SESSION
562        | tool_names::SHELL
563        | tool_names::BASH_ALIAS => {
564            if let Some(command) = command_text(args) {
565                return format!("Ran {}", compact_command_headline(&command));
566            }
567        }
568        tool_names::CODE_SEARCH | tool_names::GREP | tool_names::GREP_FILE => {
569            if let Some((title, _)) = search_headline(name, args) {
570                return title;
571            }
572        }
573        tool_names::UNIFIED_EXEC => {
574            let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
575            if !action.eq_ignore_ascii_case("run") {
576                return unified_exec_action_label(args).to_string();
577            }
578            if let Some(command) = command_text(args) {
579                return format!("Ran {}", compact_command_headline(&command));
580            }
581        }
582        tool_names::UNIFIED_FILE => {
583            let action = args.get("action").and_then(Value::as_str).unwrap_or("read");
584            if action.eq_ignore_ascii_case("read") {
585                if let Some(base) = headline_basename(args) {
586                    return format!("Read {base}");
587                }
588            } else if ["write", "edit", "patch", "delete", "move", "copy"]
589                .iter()
590                .any(|known| action.eq_ignore_ascii_case(known))
591                && let Some(base) = headline_basename(args)
592            {
593                return format!("Edited {base}");
594            }
595        }
596        _ => {}
597    }
598    humanize_tool_name(tool_name)
599}
600
601/// Action-aware title for session follow-up calls; `None` falls through to the
602/// argument gist (`run` launches show the command text instead).
603#[must_use]
604pub fn session_followup_title(name: &str, args: &Value) -> Option<String> {
605    match name {
606        tool_names::SEND_PTY_INPUT => Some("Send command input".to_string()),
607        tool_names::READ_PTY_SESSION => Some(READ_COMMAND_SESSION.to_string()),
608        tool_names::WRITE_STDIN => Some(write_stdin_action_label(args).to_string()),
609        tool_names::UNIFIED_EXEC => {
610            let action = crate::tool_intent::command_session_action(args).unwrap_or("run");
611            (!action.eq_ignore_ascii_case("run")).then(|| unified_exec_action_label(args).to_string())
612        }
613        _ => None,
614    }
615}
616
617/// Search headline per tool: `code_search` takes the shared describer;
618/// anything else phrases a file search over the first of pattern/query.
619#[must_use]
620pub fn search_headline(name: &str, args: &Value) -> Option<(String, &'static [&'static str])> {
621    if name == tool_names::CODE_SEARCH {
622        return describe_code_search(args);
623    }
624    for key in ["pattern", "query"] {
625        if let Some(pattern) = lookup_string(args, key) {
626            let keys: &'static [&'static str] = if key == "pattern" { &["pattern"] } else { &["query"] };
627            return Some((format!("Search files for {}", truncate_middle(&pattern, 40)), keys));
628        }
629    }
630    None
631}
632
633/// Basename of the path argument, in service display order.
634fn headline_basename(args: &Value) -> Option<String> {
635    lookup_first_string(args, &["path", "file_path", "filepath", "target_path"])
636        .as_deref()
637        .and_then(|path| path.split(['/', '\\']).rfind(|segment| !segment.is_empty()))
638        .map(str::to_string)
639}
640
641/// Full command text from a launch's string or argument-array form.
642#[must_use]
643pub fn command_text(args: &Value) -> Option<String> {
644    let text = if let Some(text) = ["command", "cmd", "raw_command", "bash_command"]
645        .iter()
646        .filter_map(|key| args.get(key).and_then(Value::as_str))
647        .find(|text| !text.trim().is_empty())
648    {
649        text.to_owned()
650    } else {
651        let parts: Vec<&str> = args.get("command")?.as_array()?.iter().filter_map(Value::as_str).collect();
652        if parts.iter().all(|part| part.trim().is_empty()) {
653            return None;
654        }
655        let joined = shell_words::join(parts);
656        (!joined.trim().is_empty()).then_some(joined)?
657    };
658    Some(text)
659}
660
661/// A quiet command headline that never exposes the full shell expression.
662#[must_use]
663pub fn compact_command_headline(command: &str) -> String {
664    let line = command.lines().next().unwrap_or_default().trim();
665    let words = shell_words::split(line).unwrap_or_default();
666    let program = words
667        .first()
668        .map(String::as_str)
669        .or_else(|| line.split_whitespace().next())
670        .unwrap_or("command");
671    let first_word = program;
672    let first_program = first_word.split(['|', '&', ';', '<', '>']).next().unwrap_or("command");
673    let program = first_program
674        .rsplit(['/', '\\'])
675        .next()
676        .filter(|part| !part.is_empty())
677        .unwrap_or("command");
678    if first_word.len() != first_program.len() {
679        return program.to_string();
680    }
681    let target = words
682        .iter()
683        .skip(1)
684        .take_while(|word| !word.contains(['|', '&', ';', '<', '>']))
685        .filter(|word| !word.starts_with('-'))
686        .find_map(|word| {
687            let base = word.rsplit(['/', '\\']).next()?;
688            (base.contains('.')
689                && !base.starts_with('.')
690                && !base.ends_with('.')
691                && base.chars().all(|ch| ch.is_alphanumeric() || matches!(ch, '.' | '_' | '-')))
692            .then_some(base)
693        });
694    target.map_or_else(|| program.to_string(), |target| format!("{program} {target}"))
695}
696/// otherwise input sniffing decides send vs read so pure waits never
697/// misrender as sends.
698#[must_use]
699pub fn write_stdin_action_label(args: &Value) -> &'static str {
700    if let Some(action) = args.get("action").and_then(Value::as_str) {
701        if action.eq_ignore_ascii_case("wait") {
702            return WAIT_FOR_COMMAND_SESSION;
703        }
704        if action.eq_ignore_ascii_case("poll") {
705            return READ_COMMAND_SESSION;
706        }
707        if action.eq_ignore_ascii_case("inspect") {
708            return "Inspect command output";
709        }
710        if action.eq_ignore_ascii_case("close") {
711            return "Close command session";
712        }
713        if action.eq_ignore_ascii_case("terminate") {
714            return "Terminate command session";
715        }
716        if action.eq_ignore_ascii_case("write") {
717            // Match `write_stdin_dispatch`: explicit write with empty/missing
718            // input polls instead of sending, so label it as a read.
719            return if has_session_input(args) {
720                "Send command input"
721            } else {
722                READ_COMMAND_SESSION
723            };
724        }
725    }
726    if has_session_input(args) {
727        "Send command input"
728    } else {
729        // A session_id-only follow-up polls output; calling it "Send" misleads
730        // (screenshot 2026-10-02: pure waits rendered as sends).
731        READ_COMMAND_SESSION
732    }
733}
734
735/// Whether the call carries a non-empty stdin payload under the input keys.
736#[must_use]
737pub fn has_session_input(args: &Value) -> bool {
738    ["chars", "input", "text"]
739        .iter()
740        .any(|key| args.get(key).and_then(Value::as_str).is_some_and(|s| !s.is_empty()))
741}
742
743/// Whether a harness event belongs in the user-visible transcript.
744///
745/// Routine telemetry — latency records, lifecycle starts and passes,
746/// per-turn snapshots, delegation observations, mailbox plumbing — stays out:
747/// the transcript is a conversation surface, and the canonical event still
748/// carries the complete evidence for forensics. Failures, blocks, losses
749/// (including an expired undelivered mailbox message), recoveries, rewinds,
750/// background completions, and limit grants stay: the user can act on them.
751/// Exhaustive on purpose — a new `HarnessEventKind` must make a conscious
752/// display choice here at compile time instead of silently inheriting
753/// visibility.
754///
755/// Conversational surfaces (CLI transcript, desktop transcript) filter
756/// through this; forensic surfaces (log viewers, event exports) keep the
757/// complete stream.
758#[must_use]
759pub fn harness_is_user_visible(kind: &vtcode_exec_events::HarnessEventKind) -> bool {
760    use vtcode_exec_events::HarnessEventKind::*;
761    match kind {
762        ToolLatencyRecorded
763        | PlanningStarted
764        | PlanningCompleted
765        | ContinuationStarted
766        | ContinuationSkipped
767        | EvaluationStarted
768        | EvaluationPassed
769        | RevisionStarted
770        | VerificationStarted
771        | VerificationPassed
772        | SnapshotCreated
773        | DelegatedAgentStatus
774        | SessionMessageSent
775        | SessionMessageReceived => false,
776        SessionMessageExpired
777        | TurnBlocked
778        | BlockedRecoveryStarted
779        | BlockedRecoveryFinished
780        | BlockedHandoffWritten
781        | BlockedHandoffResolved
782        | EvaluationFailed
783        | EscalationTriggered
784        | EscalationBypassed
785        | VerificationFailed
786        | ErrorRecovered
787        | ToolRetryAttempted
788        | SnapshotRestored
789        | SessionToolLimitIncreased
790        | ToolLoopLimitIncreased
791        | BackgroundSubprocessCompleted => true,
792    }
793}
794
795mod session_poll;
796
797pub use session_poll::{SessionPollKey, poll_run_tick, session_poll_key};
798
799#[cfg(test)]
800mod tests;