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};
21
22/// First non-blank string under a single key, trimmed.
23#[must_use]
24pub fn lookup_string(args: &Value, key: &str) -> Option<String> {
25    lookup_first_string(args, &[key])
26}
27
28/// First non-blank string under the given keys, trimmed.
29///
30/// Blank and mistyped values are skipped so a headline never phrases
31/// whitespace: trimming here (not at each caller) keeps every describer
32/// total over messy agent payloads.
33#[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/// Display a path relative to the workspace root when it lies within it.
44///
45/// Returns the path unchanged when `workspace_root` is `None`, the path is
46/// not absolute, or it does not lie within the root (including the
47/// degenerate path-equals-root case, kept in its original form).
48#[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/// Keys whose values are file-system paths, shown relative to the workspace.
65#[must_use]
66pub fn is_path_key(key: &str) -> bool {
67    matches!(key, "path" | "file_path" | "filename" | "destination" | "source")
68}
69
70/// Humanize a parameter key (`timeout_secs` → `Timeout secs`).
71///
72/// Only the first letter is capitalized: detail lines read as labels, not
73/// titles. Tool *names* take [`humanize_tool_name`] instead, which splits
74/// word boundaries per word.
75#[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/// Human fallback for tool names the headline readers cannot phrase.
89///
90/// Strips MCP prefixes, then splits `snake_case` and `PascalCase`/`camelCase`
91/// boundaries into capitalized words (`DiagramCommand` → `Diagram Command`,
92/// `diagram_render` → `Diagram Render`). Only the first letter of each word
93/// is touched, so acronyms (`MCP`) and versions (`v2`) survive. Never
94/// returns blank: a name with no word characters falls back to itself.
95#[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    // Single char walk, no slicing: `_` always breaks, and a new word starts
102    // before an uppercase letter that follows a lowercase letter or digit.
103    // Acronym runs (`MCPTool`) stay whole rather than guessing.
104    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        // Only the first letter is touched, so acronyms (`MCP`) and versions
126        // (`v2`) survive; the rest keeps its original casing.
127        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/// Bare tool name from an MCP-qualified one (`None` for non-MCP names).
138///
139/// Accepts the `mcp__server__tool`, `mcp::provider::tool`, and legacy
140/// `mcp_tool` spellings. Canonical MCP name parser — do not fork the
141/// prefix/segment handling per call site, so every surface labels the same
142/// tool identically. Surfaces that drop the prefix unconditionally take
143/// [`strip_mcp_prefix`] instead.
144#[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/// MCP prefixes stripped, or the name itself when it carries none.
159///
160/// Total form of [`mcp_tool_display_name`] for surfaces that never show the
161/// prefix. The legacy single-underscore arm runs last, so it cannot misfire
162/// on the qualified `mcp__` form.
163#[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/// Summarize a string list to two items plus an overflow count.
169#[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/// Raw content keys too verbose for a summary row (commands, file bodies).
183#[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
201/// Whether `text` is an accepted query alias for this tool rather than a body.
202///
203/// `code_search` phrases `text` as a last-resort query alias, so an
204/// unconsumed `text` value shows instead of hiding as verbose content;
205/// everywhere else (edits, unknown tools) `text` stays a hidden body.
206fn text_is_search_query(tool_name: &str, key: &str) -> bool {
207    key == "text" && strip_mcp_prefix(tool_name) == "code_search"
208}
209
210/// Parameter keys that are infrastructure/plumbing noise, omitted from the
211/// human-facing summary. Session plumbing (`session_id`, `chars`, wait
212/// deadlines) is not noise: [`exec_session_param_detail`] folds it into one
213/// identity row instead. Search strings (`query`) are content, never
214/// plumbing: they hide only when the headline consumed them.
215#[must_use]
216pub fn is_noise_param(key: &str) -> bool {
217    matches!(
218        key,
219        // Timeouts and size limits
220        "timeout_secs"
221            | "timeout"
222            | "max_bytes"
223            | "max_matches"
224            // Search plumbing
225            | "debug_query"
226            | "strictness"
227            | "case_sensitive"
228            | "literal"
229            | "context_lines"
230            // Execution plumbing
231            | "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            // Tool identity / routing
243            | "type"
244            | "tool_call_id"
245            | "call_type"
246            // Redundant with summary headline (e.g., "Read file" already implies action=read)
247            | "action"
248            // Output caps, same plumbing class as the size limits above.
249            | "max_output_tokens"
250            | "max_tokens"
251    )
252}
253
254/// Human `Key: value` lines for the arguments a headline does not consume.
255///
256/// Verbose content keys, plumbing noise, and the caller-supplied `skipped`
257/// keys (headline-consumed) stay out; strings truncate to 60 columns, paths
258/// relativize against the workspace, lists summarize to two items, and only
259/// `true` flags and non-zero numbers render. Key order follows
260/// `serde_json::Map` iteration. An empty `skipped` slice shows every
261/// displayable key — no separate include-all flag needed. `tool_name` (MCP
262/// prefixes accepted) decides the `text` exemption below.
263#[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                // Render file-system path values relative to the workspace root.
282                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                // Skip zero-valued numbers — they are defaults and add no information.
301                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/// One row for an exec-session follow-up: session identity plus an explicit
313/// wait deadline.
314///
315/// Output-token caps, yield windows, and the raw stdin payload are
316/// deliberately dropped: the model receives the arguments unchanged, and the
317/// reader only needs the session at a glance. Returns `None` when the call
318/// carries neither, so non-session tools keep their normal detail rows.
319#[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
335/// Exact flag tokens that introduce an inline script for a runner.
336/// Token-exact (not substring) so `grep -c` / `--code-review` never match.
337const SCRIPT_RUNNER_FLAGS: &[&str] = &["-c", "-e", "--code"];
338
339/// Compact single-line preview of a command for `• Ran …` headers.
340///
341/// Multi-line commands preview their first non-empty line; long commands
342/// are head-truncated at a word boundary with a trailing ellipsis. The
343/// mid-string ellipsis of `truncate_middle` is avoided on purpose: cutting
344/// `checkpoints/turn_1032` into `tur…ool_calls` reads as a rendering bug.
345///
346/// When the first line is only a script-runner prefix (`python3 -c "`,
347/// bare `python3 -c`, or an unclosed quote on a `-c`/`-e`/`--code` runner),
348/// the following lines are folded in so the header shows real script content
349/// (`python3 -c "import json …`) instead of a dangling `python3 -c "`.
350#[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        // Bounded: only fold enough continuation lines to fill the preview
362        // budget instead of materializing a 100-line script into one String.
363        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                // `python3 -c "` + `import json` -> `python3 -c "import json`
381                // (no extra space: the newline after the opening quote is
382                // insignificant, and `collapse_whitespace` would leave a
383                // distracting `" import` gap).
384                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        // Only honor the word boundary when it keeps at least half the budget,
399        // so a late first space does not collapse the preview to almost nothing.
400        if last_space >= budget / 2 {
401            head.truncate(last_space);
402        }
403    }
404    format!("{}…", head.trim_end())
405}
406
407/// Full-length variant of [`preview_command`] for transcript surfaces.
408///
409/// Keeps the first-line selection and script-runner prefix folding (so
410/// `python3 -c "` still pulls in script content) but applies no length cap:
411/// the selected line shows in full, with viewport-aware wrapping owning the
412/// overflow instead of a `…` truncation.
413#[must_use]
414pub fn preview_full_command(command: &str) -> String {
415    preview_command(command, usize::MAX)
416}
417
418/// Whether `program` names a known inline-script runner (`python3`, `bash`,
419/// `node`, …). Compared against the path basename so `/usr/bin/python3` and
420/// Windows-style `C:\Python\python.exe` both match, keeping the check
421/// token-exact instead of substring-based.
422fn 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
431/// Whether the first preview line is just a script-runner prefix with no
432/// usable script content (e.g. `python3 -c "` or bare `python3 -c`).
433///
434/// Rendering such a prefix alone reads as broken (`• Ran python3 -c "`).
435/// Token-exact on both program and flag so `grep -c`, `grep -e`, and
436/// `--code-review` never match. Unclosed quoting is detected with the
437/// canonical `shell_words` parser (not raw `'` counting) so contractions
438/// inside a balanced script (`python3 -c "don't …"`) do not misfire.
439fn 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    // Bare flag with no script yet: `python3 -c`.
451    let token_count = 1 + tokens.clone().count();
452    if token_count == 2 {
453        return true;
454    }
455    // Unclosed quoting means the script continues on later lines, e.g.
456    // `python3 -c "` or `python3 -c "import json`.
457    shell_words::split(first_line).is_err()
458}
459
460/// Session follow-up labels that coalesce into one transcript row per run.
461///
462/// Both surfaces (CLI renderer, desktop app) collapse consecutive polls and
463/// waits for one session; matching on these consts (never retyped literals)
464/// keeps the run predicate and the row titles in agreement by construction.
465pub const WAIT_FOR_COMMAND_SESSION: &str = "Wait for command session";
466pub const READ_COMMAND_SESSION: &str = "Read command session";
467
468/// Action-aware label for `command_session_internal` follow-up calls.
469///
470/// Canonical home of the session labels: `vtcode-core` re-exports this, and
471/// transcript surfaces call it directly. Launches take `Run command` /
472/// `Run code`; callers that phrase launches from the command itself (rather
473/// than a generic label) resolve [`crate::tool_intent::command_session_action`]
474/// first and skip the `run` action.
475#[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/// Verb-led running callout for any tool call (`Read main.rs`, `Ran cargo
502/// check`): the surface-neutral form of the headline an already-running
503/// call shows so the live status agrees with the completed summary row.
504///
505/// Falls back to the prettified tool name ([`humanize_tool_name`]) when the
506/// call has no ownable headline — never a raw identifier. `command` preview:
507/// compact executable and file target, matching the completed-row preview.
508/// `workspace_root` relativizes `list_files` and
509/// `grep_file` path headlines exactly as those describers do.
510#[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    // Session follow-ups take the action-aware label first; a `run` launch
514    // falls through to the argument gist (the command itself).
515    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/// Action-aware title for session follow-up calls; `None` falls through to the
581/// argument gist (`run` launches show the command text instead).
582#[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/// Search headline per tool: `code_search` takes the shared describer;
597/// anything else phrases a file search over the first of pattern/query.
598#[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
612/// Basename of the path argument, in service display order.
613fn 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/// Full command text from a launch's string or argument-array form.
621#[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/// A quiet command headline that never exposes the full shell expression.
641#[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/// otherwise input sniffing decides send vs read so pure waits never
676/// misrender as sends.
677#[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            // Match `write_stdin_dispatch`: explicit write with empty/missing
697            // input polls instead of sending, so label it as a read.
698            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        // A session_id-only follow-up polls output; calling it "Send" misleads
709        // (screenshot 2026-10-02: pure waits rendered as sends).
710        READ_COMMAND_SESSION
711    }
712}
713
714/// Whether the call carries a non-empty stdin payload under the input keys.
715#[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/// Whether a harness event belongs in the user-visible transcript.
723///
724/// Routine telemetry — latency records, lifecycle starts and passes,
725/// per-turn snapshots, delegation observations, mailbox plumbing — stays out:
726/// the transcript is a conversation surface, and the canonical event still
727/// carries the complete evidence for forensics. Failures, blocks, losses
728/// (including an expired undelivered mailbox message), recoveries, rewinds,
729/// background completions, and limit grants stay: the user can act on them.
730/// Exhaustive on purpose — a new `HarnessEventKind` must make a conscious
731/// display choice here at compile time instead of silently inheriting
732/// visibility.
733///
734/// Conversational surfaces (CLI transcript, desktop transcript) filter
735/// through this; forensic surfaces (log viewers, event exports) keep the
736/// complete stream.
737#[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;