1use agent_client_protocol::schema::v1::{
4 SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdateFields, ToolKind,
5};
6use mj_core::acp::RuntimeEvent;
7pub use mj_core::transcript::*;
8use serde::Deserialize;
9use serde_json::Value;
10use tree_sitter::{Node, Parser};
11const TOOL_SUMMARY_SOURCE_BYTES: usize = 64 * 1024;
12pub const TOOL_SUMMARY_VERSION: u8 = 5;
14
15pub fn compact_tool_call_for_retention(body: &mut TranscriptBody) -> bool {
26 let TranscriptBody::Tool {
27 call,
28 terminal_outputs,
29 terminal_refs,
30 ..
31 } = body
32 else {
33 return false;
34 };
35 let Some(object) = call.as_object_mut() else {
36 return false;
37 };
38 let mut changed = !terminal_outputs.is_empty() || !terminal_refs.is_empty();
39 terminal_outputs.clear();
40 terminal_refs.clear();
41 for field in ["rawInput", "rawOutput", "_meta"] {
42 changed |= object.remove(field).is_some();
43 }
44 let Some(content) = object
45 .get_mut("content")
46 .and_then(|value| value.as_array_mut())
47 else {
48 return changed;
49 };
50 let before = content.len();
51 content.retain(|item| item.get("type").and_then(|kind| kind.as_str()) == Some("diff"));
56 changed |= content.len() != before;
57 for item in content.iter_mut() {
58 changed |= drop_diff_body(item);
59 }
60 changed
61}
62
63fn drop_diff_body(item: &mut serde_json::Value) -> bool {
64 use agent_client_protocol::schema::v1::ToolCallContent;
65
66 let mut content = match serde_json::from_value::<ToolCallContent>(item.clone()) {
70 Ok(content) => content,
71 Err(error) => {
73 tracing::warn!(%error, "skipping unreadable tool content during retention");
74 return false;
75 }
76 };
77 let ToolCallContent::Diff(diff) = &mut content else {
78 return false;
79 };
80 if !mj_core::diff::drop_patch_text(diff) {
81 return false;
82 }
83 match serde_json::to_value(&content) {
84 Ok(value) => {
85 *item = value;
86 true
87 }
88 Err(error) => {
89 tracing::warn!(%error, "could not rewrite a diff during retention");
90 false
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96enum ToolSummarySource {
97 Shell(String),
98 Argv {
99 executable: String,
100 arguments: Vec<String>,
101 },
102}
103
104pub fn tool_call_update_changes_presentation(
106 call: &ToolCall,
107 fields: &ToolCallUpdateFields,
108) -> bool {
109 fields
110 .title
111 .as_ref()
112 .is_some_and(|title| title != &call.title)
113 || fields.kind.is_some_and(|kind| kind != call.kind)
114 || fields
115 .raw_input
116 .as_ref()
117 .is_some_and(|input| Some(input) != call.raw_input.as_ref())
118 || (call.kind == ToolKind::Execute
119 && fields
120 .raw_output
121 .as_ref()
122 .is_some_and(|output| Some(output) != call.raw_output.as_ref())
123 && command_source(call.raw_input.as_ref()).is_none())
124}
125
126pub fn tool_call_presentation(call: &ToolCall) -> ToolCallPresentation {
128 let kind = call.kind;
129 if kind == ToolKind::Execute {
130 if let Some(source) = command_source(call.raw_input.as_ref()) {
131 return presentation_from_source(
132 source,
133 ToolSummarySourceKind::RawInput,
134 kind,
135 &call.title,
136 );
137 }
138 if let Some(source) = command_source(call.raw_output.as_ref()) {
139 return presentation_from_source(
140 source,
141 ToolSummarySourceKind::RawOutput,
142 kind,
143 &call.title,
144 );
145 }
146 }
147 presentation_from_title(&call.title, kind)
148}
149
150pub fn materialized_tool_call_presentation(
154 stored: Option<&ToolCallPresentation>,
155 call: &ToolCall,
156) -> ToolCallPresentation {
157 stored
158 .filter(|presentation| presentation.summary_version >= TOOL_SUMMARY_VERSION)
159 .cloned()
160 .unwrap_or_else(|| tool_call_presentation(call))
161}
162
163pub fn update_tool_call_presentation(
167 previous: Option<&ToolCallPresentation>,
168 title: &str,
169 kind: Option<ToolKind>,
170 raw_input: Option<&Value>,
171 raw_output: Option<&Value>,
172) -> ToolCallPresentation {
173 let next_kind = kind.unwrap_or_else(|| {
174 previous
175 .map(|presentation| presentation.tool_kind)
176 .unwrap_or_default()
177 });
178
179 if next_kind == ToolKind::Execute {
180 if let Some(source) = raw_input.and_then(|value| command_source(Some(value))) {
181 return presentation_from_source(
182 source,
183 ToolSummarySourceKind::RawInput,
184 next_kind,
185 title,
186 );
187 }
188 if let Some(source) = raw_output.and_then(|value| command_source(Some(value)))
189 && (raw_input.is_some()
190 || !previous.is_some_and(|previous| {
191 previous.source_kind == ToolSummarySourceKind::RawInput
192 }))
193 {
194 return presentation_from_source(
195 source,
196 ToolSummarySourceKind::RawOutput,
197 next_kind,
198 title,
199 );
200 }
201 if let Some(previous) = previous
202 && previous.tool_kind == ToolKind::Execute
203 && ((raw_input.is_none() && previous.source_kind == ToolSummarySourceKind::RawInput)
204 || (raw_input.is_none()
205 && raw_output.is_none()
206 && previous.source_kind == ToolSummarySourceKind::RawOutput))
207 {
208 return ToolCallPresentation {
209 tool_kind: next_kind,
210 ..previous.clone()
211 };
212 }
213 }
214
215 presentation_from_title(title, next_kind)
216}
217
218fn command_source(raw: Option<&Value>) -> Option<ToolSummarySource> {
219 let command = raw?.get("command")?;
220 match command {
221 Value::String(command) if !command.trim().is_empty() => {
222 Some(ToolSummarySource::Shell(command.clone()))
223 }
224 Value::Array(argv) => {
225 let argv = argv.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
226 let first = argv.first()?.trim();
227 if first.is_empty() {
228 return None;
229 }
230 if is_shell_interpreter(first)
231 && let Some(script) = shell_script_argument(&argv[1..])
232 {
233 return Some(ToolSummarySource::Shell(script.to_owned()));
234 }
235 Some(ToolSummarySource::Argv {
236 executable: first.to_owned(),
237 arguments: argv[1..]
238 .iter()
239 .map(|argument| (*argument).to_owned())
240 .collect(),
241 })
242 }
243 _ => None,
244 }
245}
246
247fn is_shell_interpreter(value: &str) -> bool {
248 let executable = value.rsplit('/').next().unwrap_or(value);
249 matches!(executable, "sh" | "bash" | "dash" | "zsh")
250}
251
252fn shell_script_argument<'a>(arguments: &'a [&'a str]) -> Option<&'a str> {
253 let mut index = 0;
254 while index < arguments.len() {
255 let argument = arguments[index];
256 if argument == "--" {
257 return None;
258 }
259 if argument == "-c" || argument == "--command" {
260 return arguments.get(index + 1).copied();
261 }
262 if argument.starts_with('-') && !argument.starts_with("--") && argument[1..].contains('c') {
263 return arguments.get(index + 1).copied();
264 }
265 index += 1;
266 }
267 None
268}
269
270fn presentation_from_source(
271 source: ToolSummarySource,
272 source_kind: ToolSummarySourceKind,
273 tool_kind: ToolKind,
274 title: &str,
275) -> ToolCallPresentation {
276 let (source, summary) = match source {
277 ToolSummarySource::Shell(source) => {
278 let bounded = bound_summary_source(&source);
279 let summary = summarize_shell(&bounded)
280 .or_else(|| first_meaningful_token(title))
281 .unwrap_or_else(|| "tool".to_owned());
282 (bounded, summary)
283 }
284 ToolSummarySource::Argv {
285 executable,
286 arguments,
287 } => {
288 let source = std::iter::once(executable.as_str())
289 .chain(arguments.iter().map(String::as_str))
290 .collect::<Vec<_>>()
291 .join(" ");
292 let bounded = bound_summary_source(&source);
293 let summary = summarize_invocation(&executable, &arguments)
294 .or_else(|| first_meaningful_token(title))
295 .unwrap_or_else(|| "tool".to_owned());
296 (bounded, summary)
297 }
298 };
299 ToolCallPresentation {
300 summary,
301 source,
302 source_kind,
303 tool_kind,
304 summary_version: TOOL_SUMMARY_VERSION,
305 }
306}
307
308fn presentation_from_title(title: &str, tool_kind: ToolKind) -> ToolCallPresentation {
309 let source = title_source(title);
310 let bounded = bound_summary_source(&source);
311 let summary = if tool_kind == ToolKind::Execute {
312 summarize_shell(&bounded)
313 .or_else(|| first_meaningful_token(&bounded))
314 .unwrap_or_else(|| "tool".to_owned())
315 } else if bounded.trim_end().ends_with('?') {
316 bounded.trim().to_owned()
319 } else {
320 first_meaningful_token(&bounded).unwrap_or_else(|| "tool".to_owned())
321 };
322 ToolCallPresentation {
323 summary,
324 source: bounded,
325 source_kind: ToolSummarySourceKind::Title,
326 tool_kind,
327 summary_version: TOOL_SUMMARY_VERSION,
328 }
329}
330
331fn title_source(title: &str) -> String {
332 let title = title.trim();
333 let title = title
334 .strip_prefix("Running:")
335 .or_else(|| title.strip_prefix("Starting background:"))
336 .map(str::trim)
337 .unwrap_or(title);
338 if let Some(inner) = title
339 .strip_prefix("Execute `")
340 .and_then(|value| value.strip_suffix('`'))
341 {
342 return inner.to_owned();
343 }
344 title.to_owned()
345}
346
347fn first_meaningful_token(value: &str) -> Option<String> {
348 let token = value
349 .split_whitespace()
350 .next()?
351 .trim_matches(|character: char| {
352 !character.is_alphanumeric() && character != '/' && character != '.' && character != '_'
353 });
354 if token.is_empty() {
355 None
356 } else {
357 Some(token.trim_matches(['\'', '"', '`']).to_owned())
358 }
359}
360
361fn bound_summary_source(source: &str) -> String {
362 if source.len() <= TOOL_SUMMARY_SOURCE_BYTES {
363 return source.to_owned();
364 }
365 let mut end = TOOL_SUMMARY_SOURCE_BYTES;
366 while !source.is_char_boundary(end) {
367 end -= 1;
368 }
369 source[..end].to_owned()
370}
371
372fn summarize_shell(source: &str) -> Option<String> {
373 let mut parser = Parser::new();
374 parser
375 .set_language(&tree_sitter_bash::LANGUAGE.into())
376 .ok()?;
377 let tree = parser.parse(source, None)?;
378 let root = tree.root_node();
379 if root.has_error() {
380 return None;
381 }
382
383 let mut commands = Vec::new();
384 let mut operators = Vec::new();
385 let mut subshells = Vec::new();
386 if !collect_shell_tokens(root, source, &mut commands, &mut operators, &mut subshells) {
387 return None;
388 }
389 if commands.is_empty() {
390 return None;
391 }
392 commands.sort_by_key(|command| command.start);
393 operators.sort_by_key(|operator| operator.start);
394 subshells.sort_by_key(|subshell| subshell.start);
395
396 let mut tokens = Vec::new();
397 for (index, command) in commands.iter().enumerate() {
398 if index > 0 {
399 let previous = &commands[index - 1];
400 let separator = shell_separator_between(previous, command, &operators);
401 tokens.push(ShellToken {
402 start: separator.start,
403 text: separator.kind,
404 order: 1,
405 });
406 }
407 tokens.push(ShellToken {
408 start: command.start,
409 text: command.summary.clone(),
410 order: 2,
411 });
412 }
413
414 for subshell in subshells {
418 if !commands
419 .iter()
420 .any(|command| command.start >= subshell.start && command.end <= subshell.end)
421 {
422 continue;
423 }
424 let close = subshell.end.saturating_sub(1);
425 tokens.push(ShellToken {
426 start: subshell.start,
427 text: "(".to_owned(),
428 order: 0,
429 });
430 tokens.push(ShellToken {
431 start: close,
432 text: ")".to_owned(),
433 order: 3,
434 });
435 }
436
437 tokens.sort_by_key(|token| (token.start, token.order));
438 Some(join_shell_tokens(
439 tokens.into_iter().map(|token| token.text).collect(),
440 ))
441}
442
443#[derive(Debug, Clone)]
444struct ShellCommandToken {
445 start: usize,
446 end: usize,
447 summary: String,
448}
449
450#[derive(Debug, Clone)]
451struct ShellOperatorToken {
452 start: usize,
453 kind: String,
454}
455
456#[derive(Debug, Clone)]
457struct ShellSubshell {
458 start: usize,
459 end: usize,
460}
461
462#[derive(Debug, Clone)]
463struct ShellToken {
464 start: usize,
465 text: String,
466 order: u8,
467}
468
469fn collect_shell_tokens(
470 node: Node<'_>,
471 source: &str,
472 commands: &mut Vec<ShellCommandToken>,
473 operators: &mut Vec<ShellOperatorToken>,
474 subshells: &mut Vec<ShellSubshell>,
475) -> bool {
476 let kind = node.kind();
477 if matches!(kind, "command_substitution" | "process_substitution") {
478 return true;
479 }
480 if kind == "command" {
481 if let Some(summary) = summarize_command_node(node, source) {
482 commands.push(ShellCommandToken {
483 start: node.start_byte(),
484 end: node.end_byte(),
485 summary,
486 });
487 return true;
488 }
489 return false;
490 }
491 if is_shell_operator(node) {
492 operators.push(ShellOperatorToken {
493 start: node.start_byte(),
494 kind: kind.to_owned(),
495 });
496 return true;
497 }
498
499 if kind == "subshell" {
500 subshells.push(ShellSubshell {
501 start: node.start_byte(),
502 end: node.end_byte(),
503 });
504 }
505
506 let mut cursor = node.walk();
507 node.children(&mut cursor)
508 .all(|child| collect_shell_tokens(child, source, commands, operators, subshells))
509}
510
511fn shell_separator_between(
512 previous: &ShellCommandToken,
513 next: &ShellCommandToken,
514 operators: &[ShellOperatorToken],
515) -> ShellOperatorToken {
516 let mut candidates = operators
517 .iter()
518 .filter(|operator| operator.start >= previous.end && operator.start < next.start);
519 let structural = candidates.clone().find(|operator| operator.kind != ";");
520 if let Some(operator) = structural {
521 return operator.clone();
522 }
523 if let Some(operator) = candidates.find(|operator| operator.kind == ";") {
524 return operator.clone();
525 }
526 ShellOperatorToken {
527 start: previous.end,
528 kind: ";".to_owned(),
529 }
530}
531
532#[derive(Debug, Clone)]
536struct InvocationArgument {
537 value: String,
538 literal: bool,
539}
540
541fn summarize_command_node(node: Node<'_>, source: &str) -> Option<String> {
542 let name = node.child_by_field_name("name")?;
543 let executable = shell_command_name(name, source)?;
544 let mut cursor = node.walk();
545 let arguments = node
546 .children_by_field_name("argument", &mut cursor)
547 .map(|argument| match shell_argument_value(argument, source) {
548 Some(value) => InvocationArgument {
549 value,
550 literal: true,
551 },
552 None => InvocationArgument {
553 value: strip_matching_quotes(source[argument.byte_range()].trim()).to_owned(),
554 literal: false,
555 },
556 })
557 .collect::<Vec<_>>();
558 summarize_invocation_with_literals(&executable, &arguments)
559}
560
561fn shell_command_name(node: Node<'_>, source: &str) -> Option<String> {
562 if contains_dynamic_shell_node(node) {
563 return None;
564 }
565 normalize_command_name(&source[node.byte_range()])
566}
567
568fn shell_argument_value(node: Node<'_>, source: &str) -> Option<String> {
569 if contains_dynamic_shell_node(node) {
570 return None;
571 }
572 let text = source[node.byte_range()].trim();
573 if text.is_empty() {
574 return None;
575 }
576 Some(strip_matching_quotes(text).to_owned())
577}
578
579fn contains_dynamic_shell_node(node: Node<'_>) -> bool {
580 if matches!(
581 node.kind(),
582 "expansion"
583 | "simple_expansion"
584 | "command_substitution"
585 | "process_substitution"
586 | "arithmetic_expansion"
587 ) {
588 return true;
589 }
590 let mut cursor = node.walk();
591 node.children(&mut cursor).any(contains_dynamic_shell_node)
592}
593
594fn summarize_invocation(executable: &str, arguments: &[String]) -> Option<String> {
595 summarize_invocation_with_literals(
596 executable,
597 &arguments
598 .iter()
599 .map(|value| InvocationArgument {
600 value: strip_matching_quotes(value).to_owned(),
601 literal: true,
602 })
603 .collect::<Vec<_>>(),
604 )
605}
606
607fn summarize_invocation_with_literals(
608 executable: &str,
609 arguments: &[InvocationArgument],
610) -> Option<String> {
611 let mut executable = normalize_command_name(executable)?;
612 let mut arguments = arguments;
613 let mut words = Vec::new();
614 'invocations: loop {
617 let basename = executable
618 .rsplit(['/', '\\'])
619 .next()
620 .unwrap_or(&executable)
621 .to_owned();
622 if is_shell_interpreter(&basename) {
623 words.push(summarize_shell_invocation(&basename, arguments));
624 break;
625 }
626 words.push(executable);
627 if !is_summary_executable(&basename) {
628 break;
629 }
630 let mut index = 0;
631
632 if matches!(basename.as_str(), "cargo" | "mbx")
633 && arguments.first().is_some_and(|argument| {
634 argument.literal && argument.value.starts_with('+') && argument.value.len() > 1
635 })
636 {
637 index += 1;
638 }
639
640 let mut first_verb = loop {
641 let Some(argument) = arguments.get(index) else {
642 break 'invocations;
643 };
644 if !argument.literal {
645 break 'invocations;
646 }
647 if argument.value == "--" || argument.value.starts_with('-') {
648 if let Some(consumed) = known_leading_option_arguments(&basename, arguments, index)
649 {
650 index += consumed;
651 continue;
652 }
653 break 'invocations;
654 }
655 break argument.value.as_str();
656 };
657
658 if basename == "timeout" {
659 let duration = first_verb
660 .strip_suffix(['s', 'm', 'h', 'd'])
661 .unwrap_or(first_verb);
662 if duration.parse::<f64>().is_ok() {
663 index += 1;
664 let Some(argument) = arguments.get(index).filter(|argument| argument.literal)
665 else {
666 break;
667 };
668 first_verb = &argument.value;
669 }
670 }
671
672 if matches!(basename.as_str(), "nice" | "timeout") {
673 let Some(inner) = normalize_command_name(first_verb) else {
674 break;
675 };
676 executable = inner;
677 arguments = &arguments[index + 1..];
678 continue;
679 }
680 words.push(first_verb.to_owned());
681
682 if allows_second_verb(&basename, first_verb)
683 && let Some(argument) = arguments.get(index + 1)
684 && argument.literal
685 && !argument.value.starts_with('-')
686 && argument.value != "--"
687 {
688 if basename == "uv" && first_verb == "run" {
690 let name = argument.value.rsplit('/').next().unwrap_or(&argument.value);
691 let Some(inner) = normalize_command_name(name) else {
692 break;
693 };
694 executable = inner;
695 arguments = &arguments[index + 2..];
696 continue;
697 }
698 words.push(argument.value.clone());
699 }
700 break;
701 }
702 Some(words.join(" "))
703}
704
705fn summarize_shell_invocation(shell: &str, arguments: &[InvocationArgument]) -> String {
710 let values = arguments
711 .iter()
712 .map(|argument| argument.value.as_str())
713 .collect::<Vec<_>>();
714 let Some(script) = shell_script_argument(&values) else {
715 return shell.to_owned();
716 };
717 match summarize_shell(script) {
718 Some(inner) => format!("{shell} -c {inner}"),
719 None => format!("{shell} -c"),
720 }
721}
722
723fn is_summary_executable(basename: &str) -> bool {
724 matches!(
725 basename,
726 "git"
727 | "gh"
728 | "cargo"
729 | "rustup"
730 | "npm"
731 | "pnpm"
732 | "yarn"
733 | "bun"
734 | "uv"
735 | "pip"
736 | "pip3"
737 | "docker"
738 | "podman"
739 | "nice"
740 | "timeout"
741 | "mbx"
742 | "mj"
743 | "tmux"
744 )
745}
746
747fn allows_second_verb(basename: &str, first_verb: &str) -> bool {
748 match basename {
749 "git" => matches!(
752 first_verb,
753 "bisect"
754 | "bundle"
755 | "hook"
756 | "lfs"
757 | "maintenance"
758 | "notes"
759 | "remote"
760 | "sparse-checkout"
761 | "stash"
762 | "submodule"
763 | "worktree"
764 ),
765 "gh" => matches!(
766 first_verb,
767 "alias"
768 | "auth"
769 | "cache"
770 | "codespace"
771 | "config"
772 | "extension"
773 | "gist"
774 | "gpg-key"
775 | "issue"
776 | "label"
777 | "org"
778 | "pr"
779 | "project"
780 | "release"
781 | "repo"
782 | "ruleset"
783 | "run"
784 | "search"
785 | "secret"
786 | "ssh-key"
787 | "variable"
788 | "workflow"
789 ),
790 "docker" => matches!(
791 first_verb,
792 "buildx"
793 | "compose"
794 | "config"
795 | "context"
796 | "container"
797 | "image"
798 | "manifest"
799 | "network"
800 | "node"
801 | "plugin"
802 | "secret"
803 | "service"
804 | "stack"
805 | "swarm"
806 | "system"
807 | "trust"
808 | "volume"
809 ),
810 "podman" => matches!(
811 first_verb,
812 "artifact"
813 | "container"
814 | "farm"
815 | "generate"
816 | "image"
817 | "machine"
818 | "manifest"
819 | "network"
820 | "play"
821 | "pod"
822 | "secret"
823 | "system"
824 | "volume"
825 ),
826 "uv" => matches!(first_verb, "cache" | "pip" | "python" | "run" | "tool"),
827 "npm" => matches!(first_verb, "run" | "run-script"),
828 "pnpm" | "yarn" | "bun" => first_verb == "run",
829 "mbx" => matches!(first_verb, "cache" | "explain" | "settings"),
830 "mj" => matches!(
831 first_verb,
832 "daemon" | "import" | "recover" | "review" | "setup" | "workspaces"
833 ),
834 "rustup" => matches!(
835 first_verb,
836 "component" | "override" | "target" | "toolchain"
837 ),
838 _ => false,
839 }
840}
841
842fn known_leading_option_arguments(
843 basename: &str,
844 arguments: &[InvocationArgument],
845 index: usize,
846) -> Option<usize> {
847 let option = arguments.get(index)?.value.as_str();
848 if option == "--" {
849 if matches!(basename, "nice" | "timeout") {
850 return Some(1);
851 }
852 return None;
853 }
854 let (option_name, attached_value) = option
855 .split_once('=')
856 .map_or((option, false), |(name, _)| (name, true));
857 if basename == "nice"
858 && option.starts_with('-')
859 && option.len() > 1
860 && option[1..].parse::<i32>().is_ok()
861 {
862 return Some(1);
863 }
864 if basename == "nice"
865 && option
866 .strip_prefix("-n")
867 .is_some_and(|value| !value.is_empty() && value.parse::<i32>().is_ok())
868 {
869 return Some(1);
870 }
871 let attached_short_value = match basename {
872 "git" => option.starts_with("-C") || option.starts_with("-c"),
873 "gh" => option.starts_with("-R"),
874 "docker" | "podman" => option.starts_with("-H"),
875 "mj" => option.starts_with("-i"),
876 "timeout" => option.starts_with("-s") || option.starts_with("-k"),
877 "tmux" => ["-L", "-S", "-f", "-c", "-T"]
878 .iter()
879 .any(|prefix| option.starts_with(prefix)),
880 _ => false,
881 } && option.len() > 2;
882 let takes_value = match basename {
883 "git" => matches!(
884 option_name,
885 "-C" | "-c"
886 | "--config-env"
887 | "--exec-path"
888 | "--git-dir"
889 | "--namespace"
890 | "--super-prefix"
891 | "--work-tree"
892 ),
893 "gh" => matches!(
894 option_name,
895 "-R" | "--hostname" | "--repo" | "--jq" | "--template"
896 ),
897 "cargo" => matches!(
898 option_name,
899 "--manifest-path" | "--target-dir" | "--config" | "--color"
900 ),
901 "npm" | "pnpm" | "yarn" | "bun" => {
902 matches!(
903 option_name,
904 "--cwd" | "--dir" | "--prefix" | "--registry" | "--userconfig"
905 )
906 }
907 "uv" => matches!(option_name, "--directory" | "--project" | "--python"),
908 "rustup" => matches!(option_name, "--toolchain"),
909 "mj" => matches!(option_name, "-i" | "--instance" | "--workspace"),
910 "tmux" => matches!(option_name, "-L" | "-S" | "-f" | "-c" | "-T"),
911 "nice" => {
912 matches!(option_name, "-n" | "--adjustment")
913 }
914 "timeout" => matches!(option_name, "-s" | "--signal" | "-k" | "--kill-after"),
915 "docker" | "podman" => matches!(
916 option_name,
917 "-H" | "--config" | "--connection" | "--context" | "--host" | "--log-level"
918 ),
919 _ => false,
920 };
921 if attached_short_value {
922 return Some(1);
923 }
924 if attached_value {
925 return takes_value.then_some(1);
926 }
927 if takes_value {
928 return arguments
929 .get(index + 1)
930 .filter(|argument| argument.literal)
931 .map(|_| 2);
932 }
933 let known_flag = match basename {
934 "git" => matches!(
935 option_name,
936 "-p" | "--paginate"
937 | "-P"
938 | "--no-pager"
939 | "--bare"
940 | "--literal-pathspecs"
941 | "--glob-pathspecs"
942 | "--noglob-pathspecs"
943 | "--icase-pathspecs"
944 | "--no-optional-locks"
945 | "--no-advice"
946 ),
947 "gh" => false,
948 "cargo" => matches!(
949 option_name,
950 "-q" | "--quiet" | "-v" | "--verbose" | "--locked" | "--offline" | "--frozen"
951 ),
952 "npm" | "pnpm" | "yarn" | "bun" => {
953 matches!(option_name, "-g" | "--global" | "--silent")
954 }
955 "uv" => matches!(
956 option_name,
957 "-q" | "--quiet" | "-v" | "--verbose" | "--offline"
958 ),
959 "rustup" => matches!(option_name, "-q" | "--quiet" | "-v" | "--verbose"),
960 "docker" | "podman" => matches!(option_name, "-D" | "--debug" | "--tls"),
961 "tmux" => matches!(
962 option_name,
963 "-2" | "-C" | "-CC" | "-D" | "-l" | "-N" | "-u" | "-v"
964 ),
965 "nice" => false,
966 "timeout" => matches!(
967 option_name,
968 "-f" | "--foreground" | "-p" | "--preserve-status" | "-v" | "--verbose"
969 ),
970 _ => false,
971 };
972 known_flag.then_some(1)
973}
974
975fn strip_matching_quotes(value: &str) -> &str {
976 value
977 .strip_prefix('"')
978 .and_then(|value| value.strip_suffix('"'))
979 .or_else(|| {
980 value
981 .strip_prefix('\'')
982 .and_then(|value| value.strip_suffix('\''))
983 })
984 .unwrap_or(value)
985}
986
987fn is_shell_operator(node: Node<'_>) -> bool {
988 match node.kind() {
989 ";" => true,
990 "&&" | "||" => node.parent().is_some_and(|parent| parent.kind() == "list"),
991 "|" | "|&" => node
992 .parent()
993 .is_some_and(|parent| parent.kind() == "pipeline"),
994 "&" => node.parent().is_none_or(|parent| {
995 !matches!(
996 parent.kind(),
997 "binary_expression" | "unary_expression" | "postfix_expression"
998 )
999 }),
1000 _ => false,
1001 }
1002}
1003
1004fn normalize_command_name(text: &str) -> Option<String> {
1005 let text = text.trim();
1006 if text.contains('$') || text.contains('`') {
1007 return None;
1008 }
1009 let text = text
1010 .strip_prefix('"')
1011 .and_then(|value| value.strip_suffix('"'))
1012 .or_else(|| {
1013 text.strip_prefix('\'')
1014 .and_then(|value| value.strip_suffix('\''))
1015 })
1016 .unwrap_or(text);
1017 (!text.is_empty()).then(|| text.to_owned())
1018}
1019
1020fn join_shell_tokens(tokens: Vec<String>) -> String {
1021 let mut output = String::new();
1022 for token in tokens {
1023 match token.as_str() {
1024 "(" => {
1025 if !output.is_empty() && !output.ends_with(' ') {
1026 output.push(' ');
1027 }
1028 output.push('(');
1029 }
1030 ")" => {
1031 output = output.trim_end().to_owned();
1032 output.push(')');
1033 }
1034 _ => {
1035 if !output.is_empty() && !output.ends_with(' ') && !output.ends_with('(') {
1036 output.push(' ');
1037 }
1038 output.push_str(&token);
1039 }
1040 }
1041 }
1042 output
1043}
1044
1045pub fn tool_input_text(input: &Value) -> String {
1048 fn value_text(value: &Value) -> String {
1049 match value {
1050 Value::String(text) => text.clone(),
1051 _ => serde_json::to_string_pretty(value)
1052 .expect("tool arguments are serializable JSON values"),
1053 }
1054 }
1055
1056 let text = match input {
1057 Value::Object(fields) if !fields.is_empty() => fields
1058 .iter()
1059 .map(|(name, value)| format!("{name}:\n{}", value_text(value)))
1060 .collect::<Vec<_>>()
1061 .join("\n\n"),
1062 _ => value_text(input),
1063 };
1064 sanitize_terminal_text(&text)
1065}
1066
1067pub fn tool_content_details(
1068 content: &[ToolCallContent],
1069 terminal_outputs: &[TerminalOutputRecord],
1070 raw_output: Option<&serde_json::Value>,
1071) -> Vec<String> {
1072 let mut details = Vec::new();
1073 let mut referenced: Vec<&str> = Vec::new();
1074 for item in content {
1075 let detail = match item {
1076 ToolCallContent::Content(content) => content_block_text(&content.content),
1077 ToolCallContent::Diff(_) => None,
1078 ToolCallContent::Terminal(terminal) => {
1082 let terminal_id = terminal.terminal_id.0.as_ref();
1083 referenced.push(terminal_id);
1084 Some(
1085 terminal_outputs
1086 .iter()
1087 .find(|record| record.terminal_id.as_str() == terminal_id)
1088 .map(terminal_output_detail)
1089 .or_else(|| raw_output.and_then(raw_output_terminal_detail))
1090 .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
1091 )
1092 }
1093 _ => None,
1094 };
1095 if let Some(detail) = detail {
1096 details.push(sanitize_terminal_text(&detail));
1097 }
1098 }
1099 for record in terminal_outputs {
1103 if referenced.contains(&record.terminal_id.as_str()) {
1104 continue;
1105 }
1106 let output = sanitize_terminal_text(&record.output);
1107 if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1108 details.push(terminal_exit_summary(record));
1112 } else {
1113 details.push(sanitize_terminal_text(&terminal_output_detail(record)));
1114 }
1115 }
1116 details
1117}
1118
1119fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1124 let output = raw_output.get("formatted_output")?.as_str()?;
1125 let Some(exit_code) = raw_output
1126 .get("exit_code")
1127 .and_then(serde_json::Value::as_i64)
1128 else {
1129 return Some(output.to_owned());
1130 };
1131 let summary = format!("exited {exit_code}");
1132 if output.is_empty() {
1133 return Some(summary);
1134 }
1135 Some(format!("{output}\n{summary}"))
1136}
1137
1138pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1140 let summary = terminal_exit_summary(record);
1141 if record.output.is_empty() {
1142 return summary;
1143 }
1144 format!("{}\n{summary}", record.output)
1145}
1146
1147fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1149 let mut summary = match (record.exit_code, &record.signal) {
1150 (_, Some(signal)) => format!("killed by {signal}"),
1151 (Some(code), None) => format!("exited {code}"),
1152 (None, None) => "released before exit".to_owned(),
1153 };
1154 if record.truncated {
1155 summary.push_str(" · output truncated");
1156 }
1157 summary
1158}
1159
1160pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1161 content
1162 .iter()
1163 .filter_map(|item| match item {
1164 ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1165 _ => None,
1166 })
1167 .collect()
1168}
1169
1170pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1171 locations
1172 .iter()
1173 .map(|location| match location.line {
1174 Some(line) => format!("{}:{line}", location.path.display()),
1175 None => location.path.display().to_string(),
1176 })
1177 .collect()
1178}
1179
1180pub(crate) fn push_streamed_entry(
1184 entries: &mut Vec<ChatEntry>,
1185 seq: u64,
1186 recorded_at_ms: Option<i64>,
1187 role: ChatRole,
1188 message_id: Option<String>,
1189 text: &str,
1190) {
1191 let text = sanitize_terminal_text(text);
1192 if let Some(last) = entries.last_mut()
1193 && last.role == role
1194 && (role == ChatRole::Thought || last.message_id == message_id)
1195 {
1196 last.touch(seq);
1197 if role == ChatRole::Thought
1198 && last.message_id != message_id
1199 && !last.text.is_empty()
1200 && !text.is_empty()
1201 {
1202 while last.text.ends_with('\n') {
1203 last.text.pop();
1204 }
1205 last.text.push('\n');
1206 last.text.push_str(text.trim_start_matches('\n'));
1207 } else {
1208 last.text.push_str(&text);
1209 }
1210 return;
1211 }
1212 let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1213 entry.message_id = message_id;
1214 entries.push(entry);
1215}
1216
1217pub fn apply_session_update_to_entries(
1221 entries: &mut Vec<ChatEntry>,
1222 seq: u64,
1223 recorded_at_ms: Option<i64>,
1224 update: SessionUpdate,
1225) -> Option<SessionUpdate> {
1226 match update {
1227 SessionUpdate::AgentMessageChunk(chunk) => {
1228 let message_id = chunk.message_id.map(|id| id.to_string());
1229 if let Some(text) = content_block_text(&chunk.content) {
1230 push_streamed_entry(
1231 entries,
1232 seq,
1233 recorded_at_ms,
1234 ChatRole::Agent,
1235 message_id,
1236 &text,
1237 );
1238 }
1239 }
1240 SessionUpdate::AgentThoughtChunk(chunk) => {
1241 let message_id = chunk.message_id.map(|id| id.to_string());
1242 if let Some(text) = content_block_text(&chunk.content) {
1243 push_streamed_entry(
1244 entries,
1245 seq,
1246 recorded_at_ms,
1247 ChatRole::Thought,
1248 message_id,
1249 &text,
1250 );
1251 }
1252 }
1253 SessionUpdate::UserMessageChunk(_) => {}
1256 SessionUpdate::ToolCall(call) => {
1257 let presentation = tool_call_presentation(&call);
1258 let mut entry = ChatEntry::tool(
1259 seq,
1260 call.title,
1261 Some(call.tool_call_id.to_string()),
1262 tool_status(&call.status),
1263 );
1264 entry.tool_summary = Some(presentation.summary.clone());
1265 entry.tool_presentation = Some(presentation);
1266 entry.tool_input = call.raw_input;
1267 entry.tool_content = tool_content_details(&call.content, &[], call.raw_output.as_ref());
1268 entry.tool_diffstats = tool_diff_paths(&call.content);
1269 entry.tool_locations = tool_location_details(&call.locations);
1270 entries.push(entry);
1271 }
1272 SessionUpdate::ToolCallUpdate(update) => {
1273 let tool_call_id = update.tool_call_id.to_string();
1274 let entry = entries.iter_mut().rev().find(|entry| {
1275 entry.role == ChatRole::Tool
1276 && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1277 })?;
1278 entry.touch(seq);
1279 let kind = update.fields.kind;
1280 let raw_input = update.fields.raw_input.clone();
1281 let raw_output = update.fields.raw_output.clone();
1282 if let Some(input) = &raw_input {
1283 entry.tool_input = Some(input.clone());
1284 }
1285 if let Some(title) = update.fields.title {
1286 entry.text = sanitize_terminal_text(&title);
1287 }
1288 if let Some(status) = update.fields.status {
1289 entry.tool_status = Some(tool_status(&status));
1290 }
1291 if let Some(content) = update.fields.content {
1292 entry.tool_content =
1293 tool_content_details(&content, &[], update.fields.raw_output.as_ref());
1294 entry.tool_diffstats = tool_diff_paths(&content);
1295 }
1296 if let Some(locations) = update.fields.locations {
1297 entry.tool_locations = tool_location_details(&locations);
1298 }
1299 let presentation = update_tool_call_presentation(
1300 entry.tool_presentation.as_ref(),
1301 &entry.text,
1302 kind,
1303 raw_input.as_ref(),
1304 raw_output.as_ref(),
1305 );
1306 entry.tool_summary = Some(presentation.summary.clone());
1307 entry.tool_presentation = Some(presentation);
1308 }
1309 SessionUpdate::Plan(plan) => {
1310 let lines = plan
1311 .entries
1312 .into_iter()
1313 .map(|entry| PlanLine {
1314 text: sanitize_terminal_text(&entry.content),
1315 status: plan_status(&entry.status),
1316 })
1317 .collect();
1318 let latest_user_seq = entries
1319 .iter()
1320 .rev()
1321 .find(|entry| entry.role == ChatRole::User)
1322 .map_or(0, |entry| entry.seq);
1323 if let Some(entry) = entries
1324 .iter_mut()
1325 .rev()
1326 .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1327 {
1328 entry.touch(seq);
1329 entry.plan = lines;
1330 } else {
1331 entries.push(ChatEntry::plan(seq, lines));
1332 }
1333 }
1334 other => return Some(other),
1335 }
1336 None
1337}
1338
1339pub fn apply_runtime_event_to_entries(
1343 entries: &mut Vec<ChatEntry>,
1344 seq: u64,
1345 recorded_at_ms: Option<i64>,
1346 runtime: RuntimeEvent,
1347) -> Option<RuntimeEvent> {
1348 match runtime {
1349 RuntimeEvent::SessionUpdate { update } => {
1350 let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1351 Ok(parsed) => parsed,
1352 Err(error) => {
1353 tracing::debug!(%error, "ignoring invalid ACP session update");
1354 return None;
1355 }
1356 };
1357 apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1358 .map(|_| RuntimeEvent::SessionUpdate { update })
1359 }
1360 RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1361 entries.push(ChatEntry::plain(
1362 seq,
1363 ChatRole::System,
1364 format!("warning: {message}"),
1365 ));
1366 None
1367 }
1368 RuntimeEvent::ConfigApplied { key, value, .. } => {
1369 entries.push(ChatEntry::plain(
1370 seq,
1371 ChatRole::System,
1372 format!("{key} set to {value}"),
1373 ));
1374 None
1375 }
1376 RuntimeEvent::SessionStarted { resumed: false, .. } => {
1377 entries.push(ChatEntry::plain(
1378 seq,
1379 ChatRole::System,
1380 "harness session started",
1381 ));
1382 None
1383 }
1384 RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1385 RuntimeEvent::ElicitationResolved {
1386 reply: Some(reply), ..
1387 } => {
1388 let mut entry =
1389 ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1390 entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1391 entries.push(entry);
1392 None
1393 }
1394 other => Some(other),
1395 }
1396}
1397
1398pub fn transcript_item_text(item: &TranscriptItem) -> String {
1404 match &item.body {
1405 TranscriptBody::User { content } => materialized_content_text(content),
1406 TranscriptBody::Message { event } => format!(
1407 "{}\n\n{}",
1408 event.message_label(),
1409 mj_core::transcript::sanitize_terminal_text(
1410 event.message_text().expect("message entry metadata")
1411 )
1412 ),
1413 TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1414 materialized_chunks_text(chunks)
1415 }
1416 TranscriptBody::Tool {
1417 call,
1418 terminal_outputs,
1419 presentation,
1420 ..
1421 } => {
1422 let Ok(call) = ToolCall::deserialize(call) else {
1423 return "[invalid tool call]".to_owned();
1424 };
1425 let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1426 .summary
1427 .clone();
1428 if text.trim().is_empty() {
1429 text = call.title.clone();
1430 }
1431 for record in terminal_outputs {
1432 text.push('\n');
1433 text.push_str(&terminal_output_detail(record));
1434 }
1435 sanitize_terminal_text(&text)
1436 }
1437 TranscriptBody::TerminalOutput { record } => {
1438 sanitize_terminal_text(&terminal_output_detail(record))
1439 }
1440 TranscriptBody::Plan { plan } => {
1441 let Ok(plan) = agent_client_protocol::schema::v1::Plan::deserialize(plan) else {
1442 return String::new();
1443 };
1444 plan.entries
1445 .iter()
1446 .map(|entry| {
1447 let status = match plan_status(&entry.status) {
1448 PlanStatus::Pending => "pending",
1449 PlanStatus::Running => "running",
1450 PlanStatus::Completed => "completed",
1451 };
1452 format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1453 })
1454 .collect::<Vec<_>>()
1455 .join("\n")
1456 }
1457 TranscriptBody::PlanProposal { plan, .. } => plan.clone(),
1458 TranscriptBody::System { text } => text.clone(),
1459 }
1460}
1461
1462pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1463 content
1464 .iter()
1465 .filter_map(|item| match item {
1466 ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1467 _ => None,
1468 })
1469 .collect()
1470}
1471
1472pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1473 let TranscriptBody::Tool { call, .. } = &item.body else {
1474 return None;
1475 };
1476 let call = match ToolCall::deserialize(call) {
1477 Ok(call) => call,
1478 Err(error) => {
1479 tracing::warn!(
1480 stable_id = %item.stable_id,
1481 %error,
1482 "could not decode a stored tool call while reading diff summary"
1483 );
1484 return None;
1485 }
1486 };
1487 if !matches!(
1488 tool_status(&call.status),
1489 ToolStatus::Completed | ToolStatus::Failed
1490 ) {
1491 return None;
1492 }
1493 let diffstats = compute_tool_diffstats(&call.content);
1494 (!diffstats.is_empty()).then_some(diffstats)
1495}
1496
1497fn format_diffstat(diff: &agent_client_protocol::schema::v1::Diff) -> String {
1498 let patch = mj_core::diff::patch_of(diff);
1502 format!(
1503 "{} +{} −{}",
1504 diff.path.display(),
1505 patch.insertions,
1506 patch.deletions
1507 )
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512 use super::*;
1513 use agent_client_protocol::schema::v1::{ToolCall, ToolCallStatus};
1514 use serde_json::json;
1515
1516 #[test]
1520 fn a_question_tool_is_summarized_by_its_whole_question() {
1521 let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1522 .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1523 assert_eq!(
1524 tool_call_presentation(&call).summary,
1525 "Which file name should I use for the new file?"
1526 );
1527 let read = ToolCall::new("read", "Read src/lib.rs");
1528 assert_eq!(tool_call_presentation(&read).summary, "Read");
1529 let stale = ToolCallPresentation {
1530 summary: "Which".into(),
1531 source: call.title.clone(),
1532 source_kind: ToolSummarySourceKind::Title,
1533 tool_kind: ToolKind::Other,
1534 summary_version: 1,
1535 };
1536 assert_eq!(
1537 materialized_tool_call_presentation(Some(&stale), &call).summary,
1538 "Which file name should I use for the new file?",
1539 "stored rows written by the old rules are repaired"
1540 );
1541 }
1542
1543 fn execute_summary(command: serde_json::Value) -> String {
1544 let call = ToolCall::new("argv", "Bash")
1545 .kind(ToolKind::Execute)
1546 .raw_input(command);
1547 tool_call_presentation(&call).summary
1548 }
1549
1550 #[test]
1551 fn unknown_leading_options_make_verb_position_ambiguous() {
1552 assert_eq!(
1553 execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1554 "git"
1555 );
1556 assert_eq!(
1557 execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1558 "cargo"
1559 );
1560 }
1561
1562 #[test]
1563 fn git_commands_with_nested_subcommands_show_both_verbs() {
1564 let cases = [
1565 ("git worktree add ../x mj/session", "git worktree add"),
1566 ("git -C repo worktree list", "git worktree list"),
1567 ("git stash push -u -m tag", "git stash push"),
1568 ("git stash", "git stash"),
1569 ("git remote -v", "git remote"),
1570 ("git bisect good abc123", "git bisect good"),
1571 ("git stash -- src", "git stash"),
1572 ("git log origin/master", "git log"),
1573 ("git config user.name", "git config"),
1574 ];
1575 for (command, summary) in cases {
1576 assert_eq!(
1577 execute_summary(json!({"command": command})),
1578 summary,
1579 "{command}"
1580 );
1581 }
1582 }
1583
1584 #[test]
1585 fn project_tools_and_script_runners_show_their_subcommands() {
1586 let cases = [
1587 ("mbx nextest run -p brokk-mj-tui", "mbx nextest"),
1588 ("mbx +1.91 build bifrost", "mbx build"),
1589 ("mbx cache stats --json", "mbx cache stats"),
1590 ("mj daemon restart", "mj daemon restart"),
1591 (
1592 "mj -i test --workspace hel daemon status",
1593 "mj daemon status",
1594 ),
1595 ("mj transcript abc123", "mj transcript"),
1596 ("tmux -L mjv-e send-keys -t 0 q", "tmux send-keys"),
1597 ("tmux -Lmjv capture-pane -p", "tmux capture-pane"),
1598 ("tmux -S /tmp/sock -2 new-session -d", "tmux new-session"),
1599 ("uv run pytest -q", "uv run pytest"),
1600 ("uv run ./scripts/check.py", "uv run check.py"),
1601 ("uv run --with x pytest", "uv run"),
1602 ("npm run build", "npm run build"),
1603 ("npm run-script test:e2e", "npm run-script test:e2e"),
1604 ("pnpm run lint", "pnpm run lint"),
1605 ("npm test", "npm test"),
1606 ];
1607 for (command, summary) in cases {
1608 assert_eq!(
1609 execute_summary(json!({"command": command})),
1610 summary,
1611 "{command}"
1612 );
1613 }
1614 }
1615
1616 #[test]
1617 fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1618 let cases = [
1619 ("bash -c 'python x.py'", "bash -c python"),
1620 ("/bin/bash -c \"python x.py\"", "bash -c python"),
1621 (
1622 "/usr/bin/zsh -lc 'git status && cargo test'",
1623 "zsh -c git status && cargo test",
1624 ),
1625 ("bash -c \"cd $dir && make\"", "bash -c cd && make"),
1626 ("bash -c \"$script\"", "bash -c"),
1627 ("/bin/bash script.sh", "bash"),
1628 (
1629 "bash -c 'bash -c \"uv run pytest\"'",
1630 "bash -c bash -c uv run pytest",
1631 ),
1632 ];
1633 for (command, summary) in cases {
1634 assert_eq!(
1635 execute_summary(json!({"command": command})),
1636 summary,
1637 "{command}"
1638 );
1639 }
1640 assert_eq!(
1642 execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1643 "python"
1644 );
1645 assert_eq!(
1646 execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1647 "zsh"
1648 );
1649 }
1650
1651 #[test]
1652 fn quoted_and_dynamic_shell_verbs_are_distinguished() {
1653 let quoted = ToolCall::new("quoted", "Bash")
1654 .kind(ToolKind::Execute)
1655 .raw_input(json!({"command": "git \"status\""}));
1656 assert_eq!(tool_call_presentation("ed).summary, "git status");
1657
1658 let dynamic = ToolCall::new("dynamic", "Bash")
1659 .kind(ToolKind::Execute)
1660 .raw_input(json!({"command": "git \"$verb\""}));
1661 assert_eq!(tool_call_presentation(&dynamic).summary, "git");
1662
1663 let dynamic_name = ToolCall::new("dynamic-name", "Bash")
1664 .kind(ToolKind::Execute)
1665 .raw_input(json!({"command": "$command status"}));
1666 assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
1667 }
1668
1669 #[test]
1670 fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
1671 let call = ToolCall::new("call", "Bash")
1672 .kind(ToolKind::Execute)
1673 .raw_input(json!({
1674 "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
1675 }));
1676 assert_eq!(tool_call_presentation(&call).summary, "env");
1677
1678 let subshell = ToolCall::new("subshell", "Bash")
1679 .kind(ToolKind::Execute)
1680 .raw_input(json!({
1681 "command": "(cd dir && python x.py) | cat"
1682 }));
1683 assert_eq!(
1684 tool_call_presentation(&subshell).summary,
1685 "(cd && python) | cat"
1686 );
1687 }
1688
1689 #[test]
1690 fn shell_summary_keeps_list_pipeline_and_background_operators() {
1691 let simple = ToolCall::new("call-1", "Bash")
1692 .kind(ToolKind::Execute)
1693 .raw_input(json!({
1694 "command": "cd dir && python x.py | cat | wc ; print ok"
1695 }));
1696 let presentation = tool_call_presentation(&simple);
1697 assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
1698 assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
1699
1700 let call = ToolCall::new("operators", "Bash")
1701 .kind(ToolKind::Execute)
1702 .raw_input(json!({
1703 "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
1704 }));
1705
1706 assert_eq!(
1707 tool_call_presentation(&call).summary,
1708 "printf |& sed || echo & wait ; cat"
1709 );
1710 }
1711
1712 #[test]
1713 fn shell_summary_removes_structural_loop_and_group_separators() {
1714 let call = ToolCall::new("compound", "Bash")
1715 .kind(ToolKind::Execute)
1716 .raw_input(json!({
1717 "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
1718 }));
1719
1720 assert_eq!(
1721 tool_call_presentation(&call).summary,
1722 "rm ; mkdir ; nice python3"
1723 );
1724
1725 let conditional = ToolCall::new("conditional", "Bash")
1726 .kind(ToolKind::Execute)
1727 .raw_input(json!({
1728 "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
1729 }));
1730 assert_eq!(
1731 tool_call_presentation(&conditional).summary,
1732 "test ; rm ; mkdir ; echo"
1733 );
1734
1735 let case_statement = ToolCall::new("case", "Bash")
1736 .kind(ToolKind::Execute)
1737 .raw_input(json!({
1738 "command": "echo start; case x in a|b) echo branch;; esac; echo done"
1739 }));
1740 assert_eq!(
1741 tool_call_presentation(&case_statement).summary,
1742 "echo ; echo ; echo"
1743 );
1744 }
1745
1746 #[test]
1747 fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
1748 let call = ToolCall::new("live-loop-shape", "Bash")
1749 .kind(ToolKind::Execute)
1750 .raw_input(json!({
1751 "command": "cd /tmp && for spec in a b; do set -- $spec; rm \"$spec\"; mkdir -p \"$spec\"; nice -n 10 ./bin/bifrost \"$spec\"; echo \"$spec\"; done; python3 script.py"
1752 }));
1753
1754 assert_eq!(
1755 tool_call_presentation(&call).summary,
1756 "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
1757 );
1758 }
1759
1760 #[test]
1761 fn shell_summary_inserts_a_separator_after_a_heredoc() {
1762 let call = ToolCall::new("heredoc", "Bash")
1763 .kind(ToolKind::Execute)
1764 .raw_input(json!({
1765 "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
1766 }));
1767
1768 assert_eq!(
1769 tool_call_presentation(&call).summary,
1770 "python3 ; grep | head"
1771 );
1772 }
1773
1774 #[test]
1775 fn materialized_summary_from_an_older_parser_is_repaired() {
1776 let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
1777 let call = ToolCall::new("heredoc", "Bash")
1778 .kind(ToolKind::Execute)
1779 .raw_input(json!({ "command": source }));
1780 let stale = ToolCallPresentation {
1781 summary: "python3 grep | head".into(),
1782 source: source.into(),
1783 source_kind: ToolSummarySourceKind::RawInput,
1784 tool_kind: ToolKind::Execute,
1785 summary_version: 0,
1786 };
1787
1788 let repaired = materialized_tool_call_presentation(Some(&stale), &call);
1789 assert_eq!(repaired.summary, "python3 ; grep | head");
1790 assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
1791
1792 let mut current = repaired;
1793 current.summary = "stored current summary".into();
1794 assert_eq!(
1795 materialized_tool_call_presentation(Some(¤t), &call).summary,
1796 "stored current summary"
1797 );
1798 }
1799
1800 #[test]
1801 fn execute_summary_bounds_the_retained_source_before_parsing() {
1802 let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
1803 let call = ToolCall::new("bounded", "Bash")
1804 .kind(ToolKind::Execute)
1805 .raw_input(json!({ "command": command }));
1806
1807 let presentation = tool_call_presentation(&call);
1808 assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
1809 assert_eq!(presentation.summary, "echo");
1810 }
1811
1812 #[test]
1813 fn title_wrappers_and_malformed_shell_fall_back_safely() {
1814 let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
1815 assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
1816
1817 let malformed = ToolCall::new("bad", "Bash")
1818 .kind(ToolKind::Execute)
1819 .raw_input(json!({"command": "cd && ("}));
1820 assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
1821 }
1822
1823 #[test]
1824 fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
1825 let initial = ToolCall::new("call", "Bash")
1826 .kind(ToolKind::Execute)
1827 .raw_input(json!({"command": "python script.py"}));
1828 let previous = tool_call_presentation(&initial);
1829 let empty_input = json!({"command": null});
1830 let updated = update_tool_call_presentation(
1831 Some(&previous),
1832 "Running: ls -la",
1833 None,
1834 Some(&empty_input),
1835 None,
1836 );
1837 assert_eq!(updated.summary, "ls");
1838 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1839
1840 let output = json!({"command": "cat result.txt"});
1841 let updated = update_tool_call_presentation(
1842 Some(&previous),
1843 "Running: ls -la",
1844 None,
1845 Some(&empty_input),
1846 Some(&output),
1847 );
1848 assert_eq!(updated.summary, "cat");
1849 assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
1850
1851 let output_initial = ToolCall::new("output", "Bash")
1852 .kind(ToolKind::Execute)
1853 .raw_output(json!({"command": "python result.py"}));
1854 let output_previous = tool_call_presentation(&output_initial);
1855 let empty_output = json!({"command": null});
1856 let updated = update_tool_call_presentation(
1857 Some(&output_previous),
1858 "Running: ls -la",
1859 None,
1860 None,
1861 Some(&empty_output),
1862 );
1863 assert_eq!(updated.summary, "ls");
1864 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
1865 }
1866
1867 fn rendered_tool_row(call: &ToolCall) -> String {
1868 let presentation = tool_call_presentation(call);
1869 let item = TranscriptItem {
1870 stable_id: "tool:golden".into(),
1871 position: 1,
1872 latest_content_event_ordinal: None,
1873 created_at_ms: 1,
1874 last_changed_at_ms: 1,
1875 body: TranscriptBody::Tool {
1876 call: serde_json::to_value(call).expect("serialize tool call"),
1877 terminal_outputs: Vec::new(),
1878 terminal_refs: Vec::new(),
1879 presentation: Some(Box::new(presentation)),
1880 },
1881 };
1882 transcript_item_text(&item)
1883 }
1884
1885 fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
1886 use std::fmt::Write as _;
1887 if !output.is_empty() {
1888 output.push('\n');
1889 }
1890 writeln!(output, "=== {label} (transcript row) ===").unwrap();
1891 output.push_str(&rendered_tool_row(call));
1892 output.push('\n');
1893 }
1894
1895 #[test]
1896 fn golden_transcript_tool_row_summary() {
1897 use std::fmt::Write as _;
1898
1899 let mut output = String::new();
1900 let diff = agent_client_protocol::schema::v1::Diff::new("/workspace/new.txt", "one\ntwo\n");
1901 writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
1902 writeln!(output, "{}", format_diffstat(&diff)).unwrap();
1903
1904 let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
1905 let record = TerminalOutputRecord {
1906 terminal_id: "term-1".into(),
1907 output: text.into(),
1908 truncated,
1909 exit_code,
1910 signal: signal.map(str::to_owned),
1911 };
1912 let item = TranscriptItem {
1913 stable_id: "terminal:golden".into(),
1914 position: 1,
1915 latest_content_event_ordinal: None,
1916 created_at_ms: 1,
1917 last_changed_at_ms: 1,
1918 body: TranscriptBody::TerminalOutput { record },
1919 };
1920 transcript_item_text(&item)
1921 };
1922 for (label, row) in [
1923 ("successful terminal", terminal(Some(0), None, false, "out")),
1924 ("truncated terminal", terminal(Some(1), None, true, "out")),
1925 (
1926 "signal termination",
1927 terminal(None, Some("SIGKILL"), false, "out"),
1928 ),
1929 ("released terminal", terminal(None, None, false, "out")),
1930 (
1931 "silent signal termination",
1932 terminal(None, Some("SIGTERM"), false, ""),
1933 ),
1934 ] {
1935 writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
1936 }
1937
1938 append_tool_row(
1939 &mut output,
1940 "shell command",
1941 &ToolCall::new("shell", "Terminal")
1942 .kind(ToolKind::Execute)
1943 .raw_input(json!({
1944 "command": ["bash", "-lc", "cd dir && python x.py | cat"]
1945 })),
1946 );
1947 append_tool_row(
1948 &mut output,
1949 "ordinary argv command",
1950 &ToolCall::new("argv", "Execute")
1951 .kind(ToolKind::Execute)
1952 .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
1953 );
1954
1955 let update_call = ToolCall::new("shell", "Bash")
1956 .kind(ToolKind::Execute)
1957 .raw_input(json!({"command": "cargo test"}));
1958 let original = tool_call_presentation(&update_call);
1959 let mut output_update = ToolCallUpdateFields::default();
1960 output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
1961 writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
1962 writeln!(
1963 output,
1964 "presentation changed: {}",
1965 tool_call_update_changes_presentation(&update_call, &output_update)
1966 )
1967 .unwrap();
1968 writeln!(output, "{}", original.summary).unwrap();
1969 let mut status_update = ToolCallUpdateFields::default();
1970 status_update.status = Some(ToolCallStatus::Completed);
1971 writeln!(
1972 output,
1973 "status-only update changes presentation: {}",
1974 tool_call_update_changes_presentation(&update_call, &status_update)
1975 )
1976 .unwrap();
1977 let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
1978 writeln!(
1979 output,
1980 "output-only call changes presentation: {}",
1981 tool_call_update_changes_presentation(&output_call, &output_update)
1982 )
1983 .unwrap();
1984 let changed_input = json!({"command": "cargo check"});
1985 let mut input_update = ToolCallUpdateFields::default();
1986 input_update.raw_input = Some(changed_input.clone());
1987 writeln!(
1988 output,
1989 "changed command presentation: {}",
1990 tool_call_update_changes_presentation(&update_call, &input_update)
1991 )
1992 .unwrap();
1993 writeln!(
1994 output,
1995 "updated row: {}",
1996 update_tool_call_presentation(
1997 Some(&original),
1998 "Bash",
1999 Some(ToolKind::Execute),
2000 Some(&changed_input),
2001 None,
2002 )
2003 .summary
2004 )
2005 .unwrap();
2006
2007 for (label, command) in [
2008 (
2009 "git registered verb",
2010 json!({"command": ["git", "--no-pager", "status", "--short"]}),
2011 ),
2012 (
2013 "cargo registered verb",
2014 json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
2015 ),
2016 (
2017 "gh registered namespace",
2018 json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
2019 ),
2020 (
2021 "docker registered namespace",
2022 json!({"command": ["docker", "--context", "work", "compose", "up"]}),
2023 ),
2024 (
2025 "podman registered namespace",
2026 json!({"command": ["podman", "machine", "list"]}),
2027 ),
2028 (
2029 "uv registered namespace",
2030 json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
2031 ),
2032 (
2033 "rustup registered namespace",
2034 json!({"command": ["rustup", "toolchain", "list"]}),
2035 ),
2036 (
2037 "npm registered namespace",
2038 json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
2039 ),
2040 ] {
2041 append_tool_row(
2042 &mut output,
2043 label,
2044 &ToolCall::new("argv", "Bash")
2045 .kind(ToolKind::Execute)
2046 .raw_input(command),
2047 );
2048 }
2049
2050 let shell = ToolCall::new("string", "Bash")
2051 .kind(ToolKind::Execute)
2052 .raw_input(json!({"command": "git --no-pager status --short"}));
2053 let argv = ToolCall::new("argv", "Bash")
2054 .kind(ToolKind::Execute)
2055 .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
2056 writeln!(
2057 output,
2058 "\n=== shell and argv invocation depth (transcript rows) ==="
2059 )
2060 .unwrap();
2061 writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
2062 writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
2063
2064 for (label, command) in [
2065 ("sudo wrapper", "sudo -n git status"),
2066 ("env wrapper", "env FOO=bar git status"),
2067 ("command wrapper", "command git status"),
2068 ] {
2069 append_tool_row(
2070 &mut output,
2071 label,
2072 &ToolCall::new("wrapper", "Bash")
2073 .kind(ToolKind::Execute)
2074 .raw_input(json!({"command": command})),
2075 );
2076 }
2077
2078 for (label, command) in [
2079 (
2080 "unlisted build tool",
2081 json!({"command": ["mytool", "build", "src"]}),
2082 ),
2083 (
2084 "unlisted script",
2085 json!({"command": ["mytool", "./script.sh"]}),
2086 ),
2087 ("python script", json!({"command": ["python", "script.py"]})),
2088 (
2089 "gh API namespace",
2090 json!({"command": ["gh", "api", "graphql"]}),
2091 ),
2092 (
2093 "docker run namespace",
2094 json!({"command": ["docker", "run", "ubuntu"]}),
2095 ),
2096 (
2097 "registered future git verb",
2098 json!({"command": ["git", "future-verb"]}),
2099 ),
2100 (
2101 "absolute git with attached directory",
2102 json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
2103 ),
2104 (
2105 "git short global option",
2106 json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
2107 ),
2108 (
2109 "gh attached repository option",
2110 json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
2111 ),
2112 (
2113 "cargo color option",
2114 json!({"command": ["cargo", "--color=always", "test"]}),
2115 ),
2116 (
2117 "cargo config option",
2118 json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
2119 ),
2120 ] {
2121 append_tool_row(
2122 &mut output,
2123 label,
2124 &ToolCall::new("argv", "Bash")
2125 .kind(ToolKind::Execute)
2126 .raw_input(command),
2127 );
2128 }
2129
2130 for command in [
2131 vec!["nice", "-n", "10", "python3", "script.py"],
2132 vec!["nice", "--adjustment", "10", "python3", "script.py"],
2133 vec!["nice", "--adjustment=10", "python3", "script.py"],
2134 vec!["nice", "-10", "python3", "script.py"],
2135 vec!["nice", "-n10", "python3", "script.py"],
2136 vec!["nice", "--", "python3", "script.py"],
2137 ] {
2138 append_tool_row(
2139 &mut output,
2140 "nice command options",
2141 &ToolCall::new("nice", "Bash")
2142 .kind(ToolKind::Execute)
2143 .raw_input(json!({"command": command})),
2144 );
2145 }
2146 append_tool_row(
2147 &mut output,
2148 "nice shell command",
2149 &ToolCall::new("nice-shell", "Bash")
2150 .kind(ToolKind::Execute)
2151 .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
2152 );
2153 for (label, command) in [
2154 ("timeout shell command", json!("timeout git status")),
2155 (
2156 "timeout argv command",
2157 json!(["timeout", "30s", "git", "-C", "repo", "worktree", "list"]),
2158 ),
2159 (
2160 "timeout command options",
2161 json!([
2162 "timeout",
2163 "--foreground",
2164 "--preserve-status",
2165 "--verbose",
2166 "--signal",
2167 "TERM",
2168 "--kill-after=5s",
2169 "1.5m",
2170 "git",
2171 "status"
2172 ]),
2173 ),
2174 (
2175 "timeout attached short options",
2176 json!("timeout -sTERM -k5s -- 30 git status"),
2177 ),
2178 (
2179 "nested command wrappers",
2180 json!("nice -n 10 timeout 5m nice -- cargo +nightly test -q"),
2181 ),
2182 (
2183 "recursive script runner",
2184 json!("uv run /usr/bin/timeout 5m git status"),
2185 ),
2186 (
2187 "wrapped shell command",
2188 json!("timeout 1h /bin/bash -lc 'git status && cargo test'"),
2189 ),
2190 (
2191 "timeout in a pipeline",
2192 json!("timeout 10 git status | cat && timeout 2m gh pr list"),
2193 ),
2194 (
2195 "timeout unknown option",
2196 json!("nice timeout --mystery 10 git status"),
2197 ),
2198 (
2199 "timeout dynamic duration",
2200 json!("timeout \"$duration\" git status"),
2201 ),
2202 (
2203 "timeout dynamic command",
2204 json!("timeout 30 \"$command\" status"),
2205 ),
2206 ("wrapped dynamic verb", json!("timeout 30 git \"$verb\"")),
2207 ("timeout without command", json!(["timeout", "30"])),
2208 (
2209 "script name is not an invocation",
2210 json!("timeout 30 npm run git status"),
2211 ),
2212 (
2213 "ordinary command arguments are not invocations",
2214 json!("timeout 30 python git status"),
2215 ),
2216 ] {
2217 append_tool_row(
2218 &mut output,
2219 label,
2220 &ToolCall::new("recursive", "Bash")
2221 .kind(ToolKind::Execute)
2222 .raw_input(json!({"command": command})),
2223 );
2224 }
2225 let cached = ToolCall::new("cached-wrapper", "Bash")
2226 .kind(ToolKind::Execute)
2227 .raw_input(json!({"command": "nice -n 10 timeout 30 git status"}));
2228 let item = TranscriptItem {
2229 stable_id: "tool:cached-wrapper".into(),
2230 position: 1,
2231 latest_content_event_ordinal: None,
2232 created_at_ms: 1,
2233 last_changed_at_ms: 1,
2234 body: TranscriptBody::Tool {
2235 call: serde_json::to_value(&cached).expect("serialize tool call"),
2236 terminal_outputs: Vec::new(),
2237 terminal_refs: Vec::new(),
2238 presentation: Some(Box::new(ToolCallPresentation {
2239 summary: "nice timeout".into(),
2240 summary_version: 4,
2241 ..tool_call_presentation(&cached)
2242 })),
2243 },
2244 };
2245 writeln!(
2246 output,
2247 "\n=== cached wrapper summary (transcript row) ===\n{}",
2248 transcript_item_text(&item)
2249 )
2250 .unwrap();
2251 append_tool_row(
2252 &mut output,
2253 "non-execute tool title",
2254 &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
2255 );
2256
2257 mj_core::golden::assert_golden(
2258 env!("CARGO_MANIFEST_DIR"),
2259 "transcript-tool-row-summary",
2260 &output,
2261 );
2262 }
2263}