1use agent_client_protocol::v1::schema::{
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;
12const TOOL_SUMMARY_MAX_NESTING: usize = 16;
13const UNNAMED_COMMAND_SUMMARY: &str = "…";
15pub const TOOL_SUMMARY_VERSION: u8 = 8;
17
18pub fn compact_tool_call_for_retention(body: &mut TranscriptBody) -> bool {
29 let TranscriptBody::Tool {
30 call,
31 terminal_outputs,
32 terminal_refs,
33 ..
34 } = body
35 else {
36 return false;
37 };
38 let Some(object) = call.as_object_mut() else {
39 return false;
40 };
41 let mut changed = !terminal_outputs.is_empty() || !terminal_refs.is_empty();
42 terminal_outputs.clear();
43 terminal_refs.clear();
44 for field in ["rawInput", "rawOutput", "_meta"] {
45 changed |= object.remove(field).is_some();
46 }
47 let Some(content) = object
48 .get_mut("content")
49 .and_then(|value| value.as_array_mut())
50 else {
51 return changed;
52 };
53 let before = content.len();
54 content.retain(|item| item.get("type").and_then(|kind| kind.as_str()) == Some("diff"));
59 changed |= content.len() != before;
60 for item in content.iter_mut() {
61 changed |= drop_diff_body(item);
62 }
63 changed
64}
65
66fn drop_diff_body(item: &mut serde_json::Value) -> bool {
67 use agent_client_protocol::v1::schema::ToolCallContent;
68
69 let mut content = match serde_json::from_value::<ToolCallContent>(item.clone()) {
73 Ok(content) => content,
74 Err(error) => {
76 tracing::warn!(%error, "skipping unreadable tool content during retention");
77 return false;
78 }
79 };
80 let ToolCallContent::Diff(diff) = &mut content else {
81 return false;
82 };
83 if !mj_core::diff::drop_patch_text(diff) {
84 return false;
85 }
86 match serde_json::to_value(&content) {
87 Ok(value) => {
88 *item = value;
89 true
90 }
91 Err(error) => {
92 tracing::warn!(%error, "could not rewrite a diff during retention");
93 false
94 }
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99enum ToolSummarySource {
100 Shell(String),
101 Argv {
102 executable: String,
103 arguments: Vec<String>,
104 },
105}
106
107pub fn tool_call_update_changes_presentation(
109 call: &ToolCall,
110 fields: &ToolCallUpdateFields,
111) -> bool {
112 fields
113 .title
114 .as_ref()
115 .is_some_and(|title| title != &call.title)
116 || fields.kind.is_some_and(|kind| kind != call.kind)
117 || fields
118 .raw_input
119 .as_ref()
120 .is_some_and(|input| Some(input) != call.raw_input.as_ref())
121 || (call.kind == ToolKind::Execute
122 && fields
123 .raw_output
124 .as_ref()
125 .is_some_and(|output| Some(output) != call.raw_output.as_ref())
126 && command_source(call.raw_input.as_ref()).is_none())
127}
128
129pub fn tool_call_presentation(call: &ToolCall) -> ToolCallPresentation {
131 let kind = call.kind;
132 if kind == ToolKind::Execute {
133 if let Some(source) = command_source(call.raw_input.as_ref()) {
134 return presentation_from_source(
135 source,
136 ToolSummarySourceKind::RawInput,
137 kind,
138 &call.title,
139 );
140 }
141 if let Some(source) = command_source(call.raw_output.as_ref()) {
142 return presentation_from_source(
143 source,
144 ToolSummarySourceKind::RawOutput,
145 kind,
146 &call.title,
147 );
148 }
149 }
150 presentation_from_title(&call.title, kind)
151}
152
153pub fn materialized_tool_call_presentation(
160 stored: Option<&ToolCallPresentation>,
161 call: &ToolCall,
162) -> ToolCallPresentation {
163 stored
164 .filter(|presentation| {
165 presentation.summary_version >= TOOL_SUMMARY_VERSION
166 || match presentation.source_kind {
167 ToolSummarySourceKind::RawInput => call.raw_input.is_none(),
168 ToolSummarySourceKind::RawOutput => call.raw_output.is_none(),
169 ToolSummarySourceKind::Title => false,
170 }
171 })
172 .cloned()
173 .unwrap_or_else(|| tool_call_presentation(call))
174}
175
176pub fn update_tool_call_presentation(
180 previous: Option<&ToolCallPresentation>,
181 title: &str,
182 kind: Option<ToolKind>,
183 raw_input: Option<&Value>,
184 raw_output: Option<&Value>,
185) -> ToolCallPresentation {
186 let next_kind = kind.unwrap_or_else(|| {
187 previous
188 .map(|presentation| presentation.tool_kind)
189 .unwrap_or_default()
190 });
191
192 if next_kind == ToolKind::Execute {
193 if let Some(source) = raw_input.and_then(|value| command_source(Some(value))) {
194 return presentation_from_source(
195 source,
196 ToolSummarySourceKind::RawInput,
197 next_kind,
198 title,
199 );
200 }
201 if let Some(source) = raw_output.and_then(|value| command_source(Some(value)))
202 && (raw_input.is_some()
203 || !previous.is_some_and(|previous| {
204 previous.source_kind == ToolSummarySourceKind::RawInput
205 }))
206 {
207 return presentation_from_source(
208 source,
209 ToolSummarySourceKind::RawOutput,
210 next_kind,
211 title,
212 );
213 }
214 if let Some(previous) = previous
215 && previous.tool_kind == ToolKind::Execute
216 && ((raw_input.is_none() && previous.source_kind == ToolSummarySourceKind::RawInput)
217 || (raw_input.is_none()
218 && raw_output.is_none()
219 && previous.source_kind == ToolSummarySourceKind::RawOutput))
220 {
221 return ToolCallPresentation {
222 tool_kind: next_kind,
223 ..previous.clone()
224 };
225 }
226 }
227
228 presentation_from_title(title, next_kind)
229}
230
231fn command_source(raw: Option<&Value>) -> Option<ToolSummarySource> {
232 let command = raw?.get("command")?;
233 match command {
234 Value::String(command) if !command.trim().is_empty() => {
235 Some(ToolSummarySource::Shell(command.clone()))
236 }
237 Value::Array(argv) => {
238 let argv = argv.iter().map(Value::as_str).collect::<Option<Vec<_>>>()?;
239 let first = argv.first()?.trim();
240 if first.is_empty() {
241 return None;
242 }
243 if is_shell_interpreter(first)
244 && let Some(script) = shell_script_argument(&argv[1..])
245 {
246 return Some(ToolSummarySource::Shell(script.to_owned()));
247 }
248 Some(ToolSummarySource::Argv {
249 executable: first.to_owned(),
250 arguments: argv[1..]
251 .iter()
252 .map(|argument| (*argument).to_owned())
253 .collect(),
254 })
255 }
256 _ => None,
257 }
258}
259
260fn is_shell_interpreter(value: &str) -> bool {
261 let executable = value.rsplit('/').next().unwrap_or(value);
262 matches!(executable, "sh" | "bash" | "dash" | "zsh")
263}
264
265fn shell_script_argument<'a>(arguments: &'a [&'a str]) -> Option<&'a str> {
266 arguments.get(shell_script_index(arguments)?).copied()
267}
268
269fn shell_script_index(arguments: &[&str]) -> Option<usize> {
271 for (index, argument) in arguments.iter().enumerate() {
272 if *argument == "--" {
273 return None;
274 }
275 if *argument == "-c"
276 || *argument == "--command"
277 || (argument.starts_with('-')
278 && !argument.starts_with("--")
279 && argument[1..].contains('c'))
280 {
281 return (index + 1 < arguments.len()).then_some(index + 1);
282 }
283 }
284 None
285}
286
287fn wrapped_shell_script(command: &str) -> Option<String> {
292 let mut parser = Parser::new();
293 parser
294 .set_language(&tree_sitter_bash::LANGUAGE.into())
295 .ok()?;
296 let tree = parser.parse(command, None)?;
297 let root = tree.root_node();
298 if root.has_error() || root.named_child_count() != 1 {
299 return None;
300 }
301 let node = root.named_child(0)?;
302 if node.kind() != "command" {
303 return None;
304 }
305 let name = shell_command_name(node.child_by_field_name("name")?, command)?;
306 let mut cursor = node.walk();
307 let arguments = node
308 .children_by_field_name("argument", &mut cursor)
309 .collect::<Vec<_>>();
310 if !is_shell_interpreter(&name) || node.named_child_count() != arguments.len() + 1 {
313 return None;
314 }
315 let words = arguments
316 .iter()
317 .map(|argument| &command[argument.byte_range()])
318 .collect::<Vec<_>>();
319 shell_literal_text(arguments[shell_script_index(&words)?], command)
320}
321
322fn shell_literal_text(node: Node<'_>, source: &str) -> Option<String> {
326 let text = &source[node.byte_range()];
327 match node.kind() {
328 "raw_string" => Some(text.strip_prefix('\'')?.strip_suffix('\'')?.to_owned()),
329 "string" => Some(unescape_double_quoted(
330 text.strip_prefix('"')?.strip_suffix('"')?,
331 )),
332 "word" => Some(unescape_word(text)),
333 "concatenation" => {
334 let mut cursor = node.walk();
335 let mut end = node.start_byte();
336 let mut joined = String::new();
337 for piece in node.children(&mut cursor) {
338 if piece.start_byte() != end {
340 return None;
341 }
342 end = piece.end_byte();
343 joined.push_str(&shell_literal_text(piece, source)?);
344 }
345 (end == node.end_byte()).then_some(joined)
346 }
347 _ => None,
348 }
349}
350
351fn unescape_word(text: &str) -> String {
354 let mut unescaped = String::with_capacity(text.len());
355 let mut characters = text.chars();
356 while let Some(character) = characters.next() {
357 match character {
358 '\\' => match characters.next() {
359 Some('\n') | None => {}
360 Some(escaped) => unescaped.push(escaped),
361 },
362 character => unescaped.push(character),
363 }
364 }
365 unescaped
366}
367
368fn unescape_double_quoted(text: &str) -> String {
371 let mut unescaped = String::with_capacity(text.len());
372 let mut characters = text.chars().peekable();
373 while let Some(character) = characters.next() {
374 if character == '\\' {
375 match characters.peek() {
376 Some('$' | '`' | '"' | '\\') => {
377 unescaped.extend(characters.next());
378 continue;
379 }
380 Some('\n') => {
381 characters.next();
382 continue;
383 }
384 _ => {}
385 }
386 }
387 unescaped.push(character);
388 }
389 unescaped
390}
391
392fn presentation_from_source(
393 source: ToolSummarySource,
394 source_kind: ToolSummarySourceKind,
395 tool_kind: ToolKind,
396 title: &str,
397) -> ToolCallPresentation {
398 let (source, summary) = match source {
399 ToolSummarySource::Shell(source) => {
400 let bounded = bound_summary_source(&source);
401 if let Some(script) = wrapped_shell_script(&bounded)
402 && let Some(summary) = summarize_shell(&script, 1)
403 {
404 (script, summary)
405 } else {
406 let summary = summarize_shell(&bounded, 0)
407 .or_else(|| first_meaningful_token(title))
408 .unwrap_or_else(|| "tool".to_owned());
409 (bounded, summary)
410 }
411 }
412 ToolSummarySource::Argv {
413 executable,
414 arguments,
415 } => {
416 let source = std::iter::once(executable.as_str())
417 .chain(arguments.iter().map(String::as_str))
418 .collect::<Vec<_>>()
419 .join(" ");
420 let bounded = bound_summary_source(&source);
421 let summary = summarize_invocation(&executable, &arguments)
422 .or_else(|| first_meaningful_token(title))
423 .unwrap_or_else(|| "tool".to_owned());
424 (bounded, summary)
425 }
426 };
427 ToolCallPresentation {
428 summary,
429 source,
430 source_kind,
431 tool_kind,
432 summary_version: TOOL_SUMMARY_VERSION,
433 }
434}
435
436fn presentation_from_title(title: &str, tool_kind: ToolKind) -> ToolCallPresentation {
437 let source = title_source(title);
438 let bounded = bound_summary_source(&source);
439 let summary = if tool_kind == ToolKind::Execute {
440 summarize_shell(&bounded, 0)
441 .or_else(|| first_meaningful_token(&bounded))
442 .unwrap_or_else(|| "tool".to_owned())
443 } else if bounded.trim_end().ends_with('?') {
444 bounded.trim().to_owned()
447 } else {
448 first_meaningful_token(&bounded).unwrap_or_else(|| "tool".to_owned())
449 };
450 ToolCallPresentation {
451 summary,
452 source: bounded,
453 source_kind: ToolSummarySourceKind::Title,
454 tool_kind,
455 summary_version: TOOL_SUMMARY_VERSION,
456 }
457}
458
459fn title_source(title: &str) -> String {
460 let title = title.trim();
461 let title = title
462 .strip_prefix("Running:")
463 .or_else(|| title.strip_prefix("Starting background:"))
464 .map(str::trim)
465 .unwrap_or(title);
466 if let Some(inner) = title
467 .strip_prefix("Execute `")
468 .and_then(|value| value.strip_suffix('`'))
469 {
470 return inner.to_owned();
471 }
472 title.to_owned()
473}
474
475fn first_meaningful_token(value: &str) -> Option<String> {
476 let token = value
477 .split_whitespace()
478 .next()?
479 .trim_matches(|character: char| {
480 !character.is_alphanumeric() && character != '/' && character != '.' && character != '_'
481 });
482 if token.is_empty() {
483 None
484 } else {
485 Some(token.trim_matches(['\'', '"', '`']).to_owned())
486 }
487}
488
489fn bound_summary_source(source: &str) -> String {
490 if source.len() <= TOOL_SUMMARY_SOURCE_BYTES {
491 return source.to_owned();
492 }
493 let mut end = TOOL_SUMMARY_SOURCE_BYTES;
494 while !source.is_char_boundary(end) {
495 end -= 1;
496 }
497 source[..end].to_owned()
498}
499
500fn summarize_shell(source: &str, nesting: usize) -> Option<String> {
501 if nesting >= TOOL_SUMMARY_MAX_NESTING {
504 return Some("…".to_owned());
505 }
506 let mut parser = Parser::new();
507 parser
508 .set_language(&tree_sitter_bash::LANGUAGE.into())
509 .ok()?;
510 let tree = parser.parse(source, None)?;
511 let root = tree.root_node();
512 if root.has_error() {
513 return None;
514 }
515
516 let mut commands = Vec::new();
517 let mut operators = Vec::new();
518 let mut subshells = Vec::new();
519 if !collect_shell_tokens(
520 root,
521 source,
522 nesting,
523 &mut commands,
524 &mut operators,
525 &mut subshells,
526 ) {
527 return None;
528 }
529 if commands
532 .iter()
533 .all(|command| command.summary == UNNAMED_COMMAND_SUMMARY)
534 {
535 return None;
536 }
537 commands.sort_by_key(|command| command.start);
538 operators.sort_by_key(|operator| operator.start);
539 subshells.sort_by_key(|subshell| subshell.start);
540
541 let mut tokens = Vec::new();
542 for (index, command) in commands.iter().enumerate() {
543 if index > 0 {
544 let previous = &commands[index - 1];
545 let separator = shell_separator_between(previous, command, &operators);
546 tokens.push(ShellToken {
547 start: separator.start,
548 text: separator.kind,
549 order: 1,
550 });
551 }
552 tokens.push(ShellToken {
553 start: command.start,
554 text: command.summary.clone(),
555 order: 2,
556 });
557 }
558
559 for subshell in subshells {
563 if !commands
564 .iter()
565 .any(|command| command.start >= subshell.start && command.end <= subshell.end)
566 {
567 continue;
568 }
569 let close = subshell.end.saturating_sub(1);
570 tokens.push(ShellToken {
571 start: subshell.start,
572 text: "(".to_owned(),
573 order: 0,
574 });
575 tokens.push(ShellToken {
576 start: close,
577 text: ")".to_owned(),
578 order: 3,
579 });
580 }
581
582 tokens.sort_by_key(|token| (token.start, token.order));
583 Some(join_shell_tokens(
584 tokens.into_iter().map(|token| token.text).collect(),
585 ))
586}
587
588#[derive(Debug, Clone)]
589struct ShellCommandToken {
590 start: usize,
591 end: usize,
592 summary: String,
593}
594
595#[derive(Debug, Clone)]
596struct ShellOperatorToken {
597 start: usize,
598 kind: String,
599}
600
601#[derive(Debug, Clone)]
602struct ShellSubshell {
603 start: usize,
604 end: usize,
605}
606
607#[derive(Debug, Clone)]
608struct ShellToken {
609 start: usize,
610 text: String,
611 order: u8,
612}
613
614fn collect_shell_tokens(
615 node: Node<'_>,
616 source: &str,
617 nesting: usize,
618 commands: &mut Vec<ShellCommandToken>,
619 operators: &mut Vec<ShellOperatorToken>,
620 subshells: &mut Vec<ShellSubshell>,
621) -> bool {
622 let kind = node.kind();
623 if matches!(kind, "command_substitution" | "process_substitution") {
624 return true;
625 }
626 if kind == "command" {
627 commands.push(ShellCommandToken {
628 start: node.start_byte(),
629 end: node.end_byte(),
630 summary: summarize_command_node(node, source, nesting)
631 .unwrap_or_else(|| UNNAMED_COMMAND_SUMMARY.to_owned()),
632 });
633 return true;
634 }
635 if kind == "variable_assignment" {
636 return collect_assignment_substitutions(
637 node, source, nesting, commands, operators, subshells,
638 );
639 }
640 if is_shell_operator(node) {
641 operators.push(ShellOperatorToken {
642 start: node.start_byte(),
643 kind: kind.to_owned(),
644 });
645 return true;
646 }
647
648 if kind == "subshell" {
649 subshells.push(ShellSubshell {
650 start: node.start_byte(),
651 end: node.end_byte(),
652 });
653 }
654
655 let mut cursor = node.walk();
656 node.children(&mut cursor)
657 .all(|child| collect_shell_tokens(child, source, nesting, commands, operators, subshells))
658}
659
660fn collect_assignment_substitutions(
664 node: Node<'_>,
665 source: &str,
666 nesting: usize,
667 commands: &mut Vec<ShellCommandToken>,
668 operators: &mut Vec<ShellOperatorToken>,
669 subshells: &mut Vec<ShellSubshell>,
670) -> bool {
671 let mut cursor = node.walk();
672 node.children(&mut cursor).all(|child| {
673 if child.kind() == "command_substitution" {
674 let mut cursor = child.walk();
675 child.children(&mut cursor).all(|grandchild| {
676 collect_shell_tokens(grandchild, source, nesting, commands, operators, subshells)
677 })
678 } else {
679 collect_assignment_substitutions(child, source, nesting, commands, operators, subshells)
680 }
681 })
682}
683
684fn shell_separator_between(
685 previous: &ShellCommandToken,
686 next: &ShellCommandToken,
687 operators: &[ShellOperatorToken],
688) -> ShellOperatorToken {
689 let mut candidates = operators
690 .iter()
691 .filter(|operator| operator.start >= previous.end && operator.start < next.start);
692 let structural = candidates.clone().find(|operator| operator.kind != ";");
693 if let Some(operator) = structural {
694 return operator.clone();
695 }
696 if let Some(operator) = candidates.find(|operator| operator.kind == ";") {
697 return operator.clone();
698 }
699 ShellOperatorToken {
700 start: previous.end,
701 kind: ";".to_owned(),
702 }
703}
704
705#[derive(Debug, Clone)]
709struct InvocationArgument {
710 value: String,
711 literal: bool,
712}
713
714fn summarize_command_node(node: Node<'_>, source: &str, nesting: usize) -> Option<String> {
715 let name = node.child_by_field_name("name")?;
716 let executable = shell_command_name(name, source)?;
717 let mut cursor = node.walk();
718 let arguments = node
719 .children_by_field_name("argument", &mut cursor)
720 .map(|argument| match shell_argument_value(argument, source) {
721 Some(value) => InvocationArgument {
722 value,
723 literal: true,
724 },
725 None => InvocationArgument {
726 value: strip_matching_quotes(source[argument.byte_range()].trim()).to_owned(),
727 literal: false,
728 },
729 })
730 .collect::<Vec<_>>();
731 summarize_invocation_with_literals(&executable, &arguments, nesting)
732}
733
734fn shell_command_name(node: Node<'_>, source: &str) -> Option<String> {
735 if contains_dynamic_shell_node(node) {
736 return None;
737 }
738 normalize_command_name(&source[node.byte_range()])
739}
740
741fn shell_argument_value(node: Node<'_>, source: &str) -> Option<String> {
742 if contains_dynamic_shell_node(node) {
743 return None;
744 }
745 let text = source[node.byte_range()].trim();
746 if text.is_empty() {
747 return None;
748 }
749 Some(strip_matching_quotes(text).to_owned())
750}
751
752fn contains_dynamic_shell_node(node: Node<'_>) -> bool {
753 if matches!(
754 node.kind(),
755 "expansion"
756 | "simple_expansion"
757 | "command_substitution"
758 | "process_substitution"
759 | "arithmetic_expansion"
760 ) {
761 return true;
762 }
763 let mut cursor = node.walk();
764 node.children(&mut cursor).any(contains_dynamic_shell_node)
765}
766
767fn summarize_invocation(executable: &str, arguments: &[String]) -> Option<String> {
768 summarize_invocation_with_literals(
769 executable,
770 &arguments
771 .iter()
772 .map(|value| InvocationArgument {
773 value: strip_matching_quotes(value).to_owned(),
774 literal: true,
775 })
776 .collect::<Vec<_>>(),
777 0,
778 )
779}
780
781fn summarize_invocation_with_literals(
782 executable: &str,
783 arguments: &[InvocationArgument],
784 nesting: usize,
785) -> Option<String> {
786 let mut executable = normalize_command_name(executable)?;
787 let mut arguments = arguments;
788 let mut words = Vec::new();
789 'invocations: loop {
792 let basename = executable
793 .rsplit(['/', '\\'])
794 .next()
795 .unwrap_or(&executable)
796 .to_owned();
797 if is_shell_interpreter(&basename) {
798 words.push(summarize_shell_invocation(&basename, arguments, nesting));
799 break;
800 }
801 words.push(executable);
802 if !is_summary_executable(&basename) {
803 break;
804 }
805 let mut index = 0;
806
807 if matches!(basename.as_str(), "cargo" | "mbx")
808 && arguments.first().is_some_and(|argument| {
809 argument.literal && argument.value.starts_with('+') && argument.value.len() > 1
810 })
811 {
812 index += 1;
813 }
814
815 let mut first_verb = loop {
816 let Some(argument) = arguments.get(index) else {
817 break 'invocations;
818 };
819 if !argument.literal {
820 break 'invocations;
821 }
822 if argument.value == "--" || argument.value.starts_with('-') {
823 if let Some(consumed) = known_leading_option_arguments(&basename, arguments, index)
824 {
825 index += consumed;
826 continue;
827 }
828 break 'invocations;
829 }
830 break argument.value.as_str();
831 };
832
833 if basename == "ssh" {
834 words.push(first_verb.to_owned());
835 index += 1;
836 while let Some(argument) = arguments.get(index) {
839 if !argument.literal || !argument.value.starts_with('-') {
840 break;
841 }
842 let Some(consumed) = known_leading_option_arguments("ssh", arguments, index) else {
843 break 'invocations;
844 };
845 index += consumed;
846 if argument.value == "--" {
847 break;
848 }
849 }
850 let script = arguments[index..]
851 .iter()
852 .map(|argument| argument.value.as_str())
853 .collect::<Vec<_>>()
854 .join(" ");
855 if !script.is_empty()
856 && let Some(inner) = summarize_shell(&script, nesting + 1)
857 {
858 words.push(inner);
859 }
860 break;
861 }
862
863 if basename == "timeout" {
864 let duration = first_verb
865 .strip_suffix(['s', 'm', 'h', 'd'])
866 .unwrap_or(first_verb);
867 if duration.parse::<f64>().is_ok() {
868 index += 1;
869 let Some(argument) = arguments.get(index).filter(|argument| argument.literal)
870 else {
871 break;
872 };
873 first_verb = &argument.value;
874 }
875 }
876
877 if matches!(basename.as_str(), "nice" | "timeout") {
878 let Some(inner) = normalize_command_name(first_verb) else {
879 break;
880 };
881 executable = inner;
882 arguments = &arguments[index + 1..];
883 continue;
884 }
885 words.push(first_verb.to_owned());
886
887 if allows_second_verb(&basename, first_verb)
888 && let Some(argument) = arguments.get(index + 1)
889 && argument.literal
890 && !argument.value.starts_with('-')
891 && argument.value != "--"
892 {
893 if basename == "uv" && first_verb == "run" {
895 let name = argument.value.rsplit('/').next().unwrap_or(&argument.value);
896 let Some(inner) = normalize_command_name(name) else {
897 break;
898 };
899 executable = inner;
900 arguments = &arguments[index + 2..];
901 continue;
902 }
903 words.push(argument.value.clone());
904 }
905 break;
906 }
907 Some(words.join(" "))
908}
909
910fn summarize_shell_invocation(
915 shell: &str,
916 arguments: &[InvocationArgument],
917 nesting: usize,
918) -> String {
919 let values = arguments
920 .iter()
921 .map(|argument| argument.value.as_str())
922 .collect::<Vec<_>>();
923 let Some(script) = shell_script_argument(&values) else {
924 return shell.to_owned();
925 };
926 match summarize_shell(script, nesting + 1) {
927 Some(inner) => format!("{shell} -c {inner}"),
928 None => format!("{shell} -c"),
929 }
930}
931
932fn is_summary_executable(basename: &str) -> bool {
933 matches!(
934 basename,
935 "git"
936 | "gh"
937 | "cargo"
938 | "rustup"
939 | "npm"
940 | "pnpm"
941 | "yarn"
942 | "bun"
943 | "uv"
944 | "pip"
945 | "pip3"
946 | "docker"
947 | "podman"
948 | "nice"
949 | "timeout"
950 | "ssh"
951 | "mbx"
952 | "mj"
953 | "tmux"
954 )
955}
956
957fn allows_second_verb(basename: &str, first_verb: &str) -> bool {
958 match basename {
959 "git" => matches!(
962 first_verb,
963 "bisect"
964 | "bundle"
965 | "hook"
966 | "lfs"
967 | "maintenance"
968 | "notes"
969 | "remote"
970 | "sparse-checkout"
971 | "stash"
972 | "submodule"
973 | "worktree"
974 ),
975 "gh" => matches!(
976 first_verb,
977 "alias"
978 | "auth"
979 | "cache"
980 | "codespace"
981 | "config"
982 | "extension"
983 | "gist"
984 | "gpg-key"
985 | "issue"
986 | "label"
987 | "org"
988 | "pr"
989 | "project"
990 | "release"
991 | "repo"
992 | "ruleset"
993 | "run"
994 | "search"
995 | "secret"
996 | "ssh-key"
997 | "variable"
998 | "workflow"
999 ),
1000 "docker" => matches!(
1001 first_verb,
1002 "buildx"
1003 | "compose"
1004 | "config"
1005 | "context"
1006 | "container"
1007 | "image"
1008 | "manifest"
1009 | "network"
1010 | "node"
1011 | "plugin"
1012 | "secret"
1013 | "service"
1014 | "stack"
1015 | "swarm"
1016 | "system"
1017 | "trust"
1018 | "volume"
1019 ),
1020 "podman" => matches!(
1021 first_verb,
1022 "artifact"
1023 | "container"
1024 | "farm"
1025 | "generate"
1026 | "image"
1027 | "machine"
1028 | "manifest"
1029 | "network"
1030 | "play"
1031 | "pod"
1032 | "secret"
1033 | "system"
1034 | "volume"
1035 ),
1036 "uv" => matches!(first_verb, "cache" | "pip" | "python" | "run" | "tool"),
1037 "npm" => matches!(first_verb, "run" | "run-script"),
1038 "pnpm" | "yarn" | "bun" => first_verb == "run",
1039 "mbx" => matches!(first_verb, "cache" | "explain" | "settings"),
1040 "mj" => matches!(
1041 first_verb,
1042 "daemon" | "import" | "recover" | "review" | "setup" | "workspaces"
1043 ),
1044 "rustup" => matches!(
1045 first_verb,
1046 "component" | "override" | "target" | "toolchain"
1047 ),
1048 _ => false,
1049 }
1050}
1051
1052fn known_leading_option_arguments(
1053 basename: &str,
1054 arguments: &[InvocationArgument],
1055 index: usize,
1056) -> Option<usize> {
1057 let option = arguments.get(index)?.value.as_str();
1058 if option == "--" {
1059 if matches!(basename, "nice" | "timeout" | "ssh") {
1060 return Some(1);
1061 }
1062 return None;
1063 }
1064 if basename == "ssh" {
1065 let flags = option.strip_prefix('-')?;
1068 for (offset, flag) in flags.char_indices() {
1069 if "BbcDEeFIiJLlmOoPpQRSWw".contains(flag) {
1070 return if offset + flag.len_utf8() < flags.len() {
1071 Some(1)
1072 } else {
1073 arguments
1074 .get(index + 1)
1075 .filter(|argument| argument.literal)
1076 .map(|_| 2)
1077 };
1078 }
1079 if !"46AaCfGgKkMNnqsTtVvXxYy".contains(flag) {
1080 return None;
1081 }
1082 }
1083 return (!flags.is_empty()).then_some(1);
1084 }
1085 let (option_name, attached_value) = option
1086 .split_once('=')
1087 .map_or((option, false), |(name, _)| (name, true));
1088 if basename == "nice"
1089 && option.starts_with('-')
1090 && option.len() > 1
1091 && option[1..].parse::<i32>().is_ok()
1092 {
1093 return Some(1);
1094 }
1095 if basename == "nice"
1096 && option
1097 .strip_prefix("-n")
1098 .is_some_and(|value| !value.is_empty() && value.parse::<i32>().is_ok())
1099 {
1100 return Some(1);
1101 }
1102 let attached_short_value = match basename {
1103 "git" => option.starts_with("-C") || option.starts_with("-c"),
1104 "gh" => option.starts_with("-R"),
1105 "docker" | "podman" => option.starts_with("-H"),
1106 "mj" => option.starts_with("-i"),
1107 "timeout" => option.starts_with("-s") || option.starts_with("-k"),
1108 "tmux" => ["-L", "-S", "-f", "-c", "-T"]
1109 .iter()
1110 .any(|prefix| option.starts_with(prefix)),
1111 _ => false,
1112 } && option.len() > 2;
1113 let takes_value = match basename {
1114 "git" => matches!(
1115 option_name,
1116 "-C" | "-c"
1117 | "--config-env"
1118 | "--exec-path"
1119 | "--git-dir"
1120 | "--namespace"
1121 | "--super-prefix"
1122 | "--work-tree"
1123 ),
1124 "gh" => matches!(
1125 option_name,
1126 "-R" | "--hostname" | "--repo" | "--jq" | "--template"
1127 ),
1128 "cargo" => matches!(
1129 option_name,
1130 "--manifest-path" | "--target-dir" | "--config" | "--color"
1131 ),
1132 "npm" | "pnpm" | "yarn" | "bun" => {
1133 matches!(
1134 option_name,
1135 "--cwd" | "--dir" | "--prefix" | "--registry" | "--userconfig"
1136 )
1137 }
1138 "uv" => matches!(option_name, "--directory" | "--project" | "--python"),
1139 "rustup" => matches!(option_name, "--toolchain"),
1140 "mj" => matches!(option_name, "-i" | "--instance" | "--workspace"),
1141 "tmux" => matches!(option_name, "-L" | "-S" | "-f" | "-c" | "-T"),
1142 "nice" => {
1143 matches!(option_name, "-n" | "--adjustment")
1144 }
1145 "timeout" => matches!(option_name, "-s" | "--signal" | "-k" | "--kill-after"),
1146 "docker" | "podman" => matches!(
1147 option_name,
1148 "-H" | "--config" | "--connection" | "--context" | "--host" | "--log-level"
1149 ),
1150 _ => false,
1151 };
1152 if attached_short_value {
1153 return Some(1);
1154 }
1155 if attached_value {
1156 return takes_value.then_some(1);
1157 }
1158 if takes_value {
1159 return arguments
1160 .get(index + 1)
1161 .filter(|argument| argument.literal)
1162 .map(|_| 2);
1163 }
1164 let known_flag = match basename {
1165 "git" => matches!(
1166 option_name,
1167 "-p" | "--paginate"
1168 | "-P"
1169 | "--no-pager"
1170 | "--bare"
1171 | "--literal-pathspecs"
1172 | "--glob-pathspecs"
1173 | "--noglob-pathspecs"
1174 | "--icase-pathspecs"
1175 | "--no-optional-locks"
1176 | "--no-advice"
1177 ),
1178 "gh" => false,
1179 "cargo" => matches!(
1180 option_name,
1181 "-q" | "--quiet" | "-v" | "--verbose" | "--locked" | "--offline" | "--frozen"
1182 ),
1183 "npm" | "pnpm" | "yarn" | "bun" => {
1184 matches!(option_name, "-g" | "--global" | "--silent")
1185 }
1186 "uv" => matches!(
1187 option_name,
1188 "-q" | "--quiet" | "-v" | "--verbose" | "--offline"
1189 ),
1190 "rustup" => matches!(option_name, "-q" | "--quiet" | "-v" | "--verbose"),
1191 "docker" | "podman" => matches!(option_name, "-D" | "--debug" | "--tls"),
1192 "tmux" => matches!(
1193 option_name,
1194 "-2" | "-C" | "-CC" | "-D" | "-l" | "-N" | "-u" | "-v"
1195 ),
1196 "nice" => false,
1197 "timeout" => matches!(
1198 option_name,
1199 "-f" | "--foreground" | "-p" | "--preserve-status" | "-v" | "--verbose"
1200 ),
1201 _ => false,
1202 };
1203 known_flag.then_some(1)
1204}
1205
1206fn strip_matching_quotes(value: &str) -> &str {
1207 value
1208 .strip_prefix('"')
1209 .and_then(|value| value.strip_suffix('"'))
1210 .or_else(|| {
1211 value
1212 .strip_prefix('\'')
1213 .and_then(|value| value.strip_suffix('\''))
1214 })
1215 .unwrap_or(value)
1216}
1217
1218fn is_shell_operator(node: Node<'_>) -> bool {
1219 match node.kind() {
1220 ";" => true,
1221 "&&" | "||" => node.parent().is_some_and(|parent| parent.kind() == "list"),
1222 "|" | "|&" => node
1223 .parent()
1224 .is_some_and(|parent| parent.kind() == "pipeline"),
1225 "&" => node.parent().is_none_or(|parent| {
1226 !matches!(
1227 parent.kind(),
1228 "binary_expression" | "unary_expression" | "postfix_expression"
1229 )
1230 }),
1231 _ => false,
1232 }
1233}
1234
1235fn normalize_command_name(text: &str) -> Option<String> {
1236 let text = text.trim();
1237 if text.contains('$') || text.contains('`') {
1238 return None;
1239 }
1240 let text = text
1241 .strip_prefix('"')
1242 .and_then(|value| value.strip_suffix('"'))
1243 .or_else(|| {
1244 text.strip_prefix('\'')
1245 .and_then(|value| value.strip_suffix('\''))
1246 })
1247 .unwrap_or(text);
1248 (!text.is_empty()).then(|| text.to_owned())
1249}
1250
1251fn join_shell_tokens(tokens: Vec<String>) -> String {
1252 let mut output = String::new();
1253 for token in tokens {
1254 match token.as_str() {
1255 "(" => {
1256 if !output.is_empty() && !output.ends_with(' ') {
1257 output.push(' ');
1258 }
1259 output.push('(');
1260 }
1261 ")" => {
1262 output = output.trim_end().to_owned();
1263 output.push(')');
1264 }
1265 _ => {
1266 if !output.is_empty() && !output.ends_with(' ') && !output.ends_with('(') {
1267 output.push(' ');
1268 }
1269 output.push_str(&token);
1270 }
1271 }
1272 }
1273 output
1274}
1275
1276pub fn tool_input_text(input: &Value) -> String {
1279 fn value_text(value: &Value) -> String {
1280 match value {
1281 Value::String(text) => text.clone(),
1282 _ => serde_json::to_string_pretty(value)
1283 .expect("tool arguments are serializable JSON values"),
1284 }
1285 }
1286
1287 let text = match input {
1288 Value::Object(fields) if !fields.is_empty() => fields
1289 .iter()
1290 .map(|(name, value)| format!("{name}:\n{}", value_text(value)))
1291 .collect::<Vec<_>>()
1292 .join("\n\n"),
1293 _ => value_text(input),
1294 };
1295 sanitize_terminal_text(&text)
1296}
1297
1298pub fn tool_content_details(
1299 content: &[ToolCallContent],
1300 terminal_outputs: &[TerminalOutputRecord],
1301 raw_output: Option<&serde_json::Value>,
1302 status: ToolStatus,
1303) -> Vec<String> {
1304 let terminal_finished = |record: &TerminalOutputRecord| {
1305 !matches!(status, ToolStatus::Pending | ToolStatus::Running)
1306 || record.exit_code.is_some()
1307 || record.signal.is_some()
1308 };
1309 let terminal_detail = |record: &TerminalOutputRecord| {
1310 if !terminal_finished(record) {
1311 if record.truncated {
1312 format!("{}\noutput truncated", record.output)
1313 } else {
1314 record.output.clone()
1315 }
1316 } else {
1317 terminal_output_detail(record)
1318 }
1319 };
1320 let mut details = Vec::new();
1321 let mut referenced: Vec<&str> = Vec::new();
1322 for item in content {
1323 let detail = match item {
1324 ToolCallContent::Content(content) => content_block_text(&content.content),
1325 ToolCallContent::Diff(_) => None,
1326 ToolCallContent::Terminal(terminal) => {
1330 let terminal_id = terminal.terminal_id.0.as_ref();
1331 referenced.push(terminal_id);
1332 Some(
1333 terminal_outputs
1334 .iter()
1335 .find(|record| record.terminal_id.as_str() == terminal_id)
1336 .map(terminal_detail)
1337 .or_else(|| raw_output.and_then(raw_output_terminal_detail))
1338 .unwrap_or_else(|| format!("terminal {}", terminal.terminal_id)),
1339 )
1340 }
1341 _ => None,
1342 };
1343 if let Some(detail) = detail {
1344 details.push(sanitize_terminal_text(&detail));
1345 }
1346 }
1347 for record in terminal_outputs {
1351 if referenced.contains(&record.terminal_id.as_str()) {
1352 continue;
1353 }
1354 let output = sanitize_terminal_text(&record.output);
1355 if !output.is_empty() && details.iter().any(|detail| detail == &output) {
1356 if terminal_finished(record) {
1360 details.push(terminal_exit_summary(record));
1361 }
1362 } else {
1363 details.push(sanitize_terminal_text(&terminal_detail(record)));
1364 }
1365 }
1366 details
1367}
1368
1369pub fn tool_error_detail(raw_output: Option<&Value>) -> Option<String> {
1373 let error = raw_output?.get("error")?;
1374 if error.is_null() {
1375 return None;
1376 }
1377 let text = match error {
1378 Value::String(text) => text.clone(),
1379 _ => serde_json::to_string_pretty(error)
1380 .expect("tool diagnostics are serializable JSON values"),
1381 };
1382 (!text.is_empty()).then(|| sanitize_terminal_text(&text))
1383}
1384
1385fn raw_output_terminal_detail(raw_output: &serde_json::Value) -> Option<String> {
1390 let output = raw_output.get("formatted_output")?.as_str()?;
1391 let Some(exit_code) = raw_output
1392 .get("exit_code")
1393 .and_then(serde_json::Value::as_i64)
1394 else {
1395 return Some(output.to_owned());
1396 };
1397 let summary = format!("exited {exit_code}");
1398 if output.is_empty() {
1399 return Some(summary);
1400 }
1401 Some(format!("{output}\n{summary}"))
1402}
1403
1404pub fn terminal_output_detail(record: &TerminalOutputRecord) -> String {
1406 let summary = terminal_exit_summary(record);
1407 if record.output.is_empty() {
1408 return summary;
1409 }
1410 format!("{}\n{summary}", record.output)
1411}
1412
1413fn terminal_exit_summary(record: &TerminalOutputRecord) -> String {
1415 let mut summary = match (record.exit_code, &record.signal) {
1416 (_, Some(signal)) => format!("killed by {signal}"),
1417 (Some(code), None) => format!("exited {code}"),
1418 (None, None) => "exit status unavailable".to_owned(),
1419 };
1420 if record.truncated {
1421 summary.push_str(" · output truncated");
1422 }
1423 summary
1424}
1425
1426pub fn tool_diff_paths(content: &[ToolCallContent]) -> Vec<String> {
1427 content
1428 .iter()
1429 .filter_map(|item| match item {
1430 ToolCallContent::Diff(diff) => Some(diff.path.display().to_string()),
1431 _ => None,
1432 })
1433 .collect()
1434}
1435
1436pub fn tool_location_details(locations: &[ToolCallLocation]) -> Vec<String> {
1437 locations
1438 .iter()
1439 .map(|location| match location.line {
1440 Some(line) => format!("{}:{line}", location.path.display()),
1441 None => location.path.display().to_string(),
1442 })
1443 .collect()
1444}
1445
1446pub(crate) fn push_streamed_entry(
1450 entries: &mut Vec<ChatEntry>,
1451 seq: u64,
1452 recorded_at_ms: Option<i64>,
1453 role: ChatRole,
1454 message_id: Option<String>,
1455 text: &str,
1456) {
1457 let text = sanitize_terminal_text(text);
1458 if let Some(last) = entries.last_mut()
1459 && last.role == role
1460 && (role == ChatRole::Thought || last.message_id == message_id)
1461 {
1462 last.touch(seq);
1463 if role == ChatRole::Thought
1464 && last.message_id != message_id
1465 && !last.text.is_empty()
1466 && !text.is_empty()
1467 {
1468 while last.text.ends_with('\n') {
1469 last.text.pop();
1470 }
1471 last.text.push('\n');
1472 last.text.push_str(text.trim_start_matches('\n'));
1473 } else {
1474 last.text.push_str(&text);
1475 }
1476 return;
1477 }
1478 let mut entry = ChatEntry::plain(seq, role, text).with_recorded_at(recorded_at_ms);
1479 entry.message_id = message_id;
1480 entries.push(entry);
1481}
1482
1483pub fn apply_session_update_to_entries(
1487 entries: &mut Vec<ChatEntry>,
1488 seq: u64,
1489 recorded_at_ms: Option<i64>,
1490 update: SessionUpdate,
1491) -> Option<SessionUpdate> {
1492 match update {
1493 SessionUpdate::AgentMessageChunk(chunk) => {
1494 let message_id = chunk.message_id.map(|id| id.to_string());
1495 if let Some(text) = content_block_text(&chunk.content) {
1496 push_streamed_entry(
1497 entries,
1498 seq,
1499 recorded_at_ms,
1500 ChatRole::Agent,
1501 message_id,
1502 &text,
1503 );
1504 }
1505 }
1506 SessionUpdate::AgentThoughtChunk(chunk) => {
1507 let message_id = chunk.message_id.map(|id| id.to_string());
1508 if let Some(text) = content_block_text(&chunk.content) {
1509 push_streamed_entry(
1510 entries,
1511 seq,
1512 recorded_at_ms,
1513 ChatRole::Thought,
1514 message_id,
1515 &text,
1516 );
1517 }
1518 }
1519 SessionUpdate::UserMessageChunk(_) => {}
1522 SessionUpdate::ToolCall(call) => {
1523 let presentation = tool_call_presentation(&call);
1524 let mut entry = ChatEntry::tool(
1525 seq,
1526 call.title,
1527 Some(call.tool_call_id.to_string()),
1528 tool_status(&call.status),
1529 )
1530 .with_recorded_at(recorded_at_ms);
1531 mark_tool_end(&mut entry, recorded_at_ms);
1532 entry.tool_summary = Some(presentation.summary.clone());
1533 entry.tool_presentation = Some(presentation);
1534 entry.tool_input = call.raw_input;
1535 entry.tool_error = tool_error_detail(call.raw_output.as_ref());
1536 entry.tool_content = tool_content_details(
1537 &call.content,
1538 &[],
1539 call.raw_output.as_ref(),
1540 tool_status(&call.status),
1541 );
1542 entry.tool_diffstats = tool_diff_paths(&call.content);
1543 entry.tool_locations = tool_location_details(&call.locations);
1544 entries.push(entry);
1545 }
1546 SessionUpdate::ToolCallUpdate(update) => {
1547 let tool_call_id = update.tool_call_id.to_string();
1548 let entry = entries.iter_mut().rev().find(|entry| {
1549 entry.role == ChatRole::Tool
1550 && entry.tool_call_id.as_deref() == Some(tool_call_id.as_str())
1551 })?;
1552 entry.touch(seq);
1553 let kind = update.fields.kind;
1554 let raw_input = update.fields.raw_input.clone();
1555 let raw_output = update.fields.raw_output.clone();
1556 if let Some(input) = &raw_input {
1557 entry.tool_input = Some(input.clone());
1558 }
1559 if let Some(raw_output) = &raw_output {
1560 entry.tool_error = tool_error_detail(Some(raw_output));
1561 }
1562 if let Some(title) = update.fields.title {
1563 entry.text = sanitize_terminal_text(&title);
1564 }
1565 if let Some(status) = update.fields.status {
1566 entry.tool_status = Some(tool_status(&status));
1567 mark_tool_end(entry, recorded_at_ms);
1568 }
1569 if let Some(content) = update.fields.content {
1570 entry.tool_content = tool_content_details(
1571 &content,
1572 &[],
1573 raw_output.as_ref(),
1574 entry.tool_status.unwrap_or(ToolStatus::Pending),
1575 );
1576 entry.tool_diffstats = tool_diff_paths(&content);
1577 }
1578 if let Some(locations) = update.fields.locations {
1579 entry.tool_locations = tool_location_details(&locations);
1580 }
1581 let presentation = update_tool_call_presentation(
1582 entry.tool_presentation.as_ref(),
1583 &entry.text,
1584 kind,
1585 raw_input.as_ref(),
1586 raw_output.as_ref(),
1587 );
1588 entry.tool_summary = Some(presentation.summary.clone());
1589 entry.tool_presentation = Some(presentation);
1590 }
1591 SessionUpdate::Plan(plan) => {
1592 let lines = plan
1593 .entries
1594 .into_iter()
1595 .map(|entry| PlanLine {
1596 text: sanitize_terminal_text(&entry.content),
1597 status: plan_status(&entry.status),
1598 })
1599 .collect();
1600 let latest_user_seq = entries
1603 .iter()
1604 .rev()
1605 .find(|entry| entry.role == ChatRole::User)
1606 .map_or(0, |entry| entry.seq);
1607 if let Some(entry) = entries
1608 .iter_mut()
1609 .rev()
1610 .find(|entry| entry.role == ChatRole::Plan && entry.seq > latest_user_seq)
1611 {
1612 entry.touch(seq);
1613 entry.plan = lines;
1614 } else {
1615 entries.push(ChatEntry::plan(seq, lines));
1616 }
1617 }
1618 other => return Some(other),
1619 }
1620 None
1621}
1622
1623fn mark_tool_end(entry: &mut ChatEntry, recorded_at_ms: Option<i64>) {
1625 entry.tool_ended_at_ms = match entry.tool_status {
1626 Some(ToolStatus::Completed | ToolStatus::Failed) => recorded_at_ms,
1627 _ => None,
1628 };
1629}
1630
1631pub fn apply_runtime_event_to_entries(
1635 entries: &mut Vec<ChatEntry>,
1636 seq: u64,
1637 recorded_at_ms: Option<i64>,
1638 runtime: RuntimeEvent,
1639) -> Option<RuntimeEvent> {
1640 match runtime {
1641 RuntimeEvent::SessionUpdate { update } => {
1642 let parsed = match serde_json::from_value::<SessionUpdate>(update.clone()) {
1643 Ok(parsed) => parsed,
1644 Err(error) => {
1645 tracing::debug!(%error, "ignoring invalid ACP session update");
1646 return None;
1647 }
1648 };
1649 apply_session_update_to_entries(entries, seq, recorded_at_ms, parsed)
1650 .map(|_| RuntimeEvent::SessionUpdate { update })
1651 }
1652 RuntimeEvent::Warning { message } | RuntimeEvent::SessionFault { message } => {
1653 entries.push(ChatEntry::plain(
1654 seq,
1655 ChatRole::System,
1656 format!("warning: {message}"),
1657 ));
1658 None
1659 }
1660 RuntimeEvent::ConfigApplied { key, value, .. } => {
1661 entries.push(ChatEntry::plain(
1662 seq,
1663 ChatRole::System,
1664 format!("{key} set to {value}"),
1665 ));
1666 None
1667 }
1668 RuntimeEvent::SessionStarted { resumed: false, .. } => {
1669 entries.push(ChatEntry::plain(
1670 seq,
1671 ChatRole::System,
1672 "harness session started",
1673 ));
1674 None
1675 }
1676 RuntimeEvent::SessionStarted { resumed: true, .. } => None,
1677 RuntimeEvent::ElicitationResolved { action, .. }
1678 if action == mj_core::elicitation::OPERATOR_AWAY_ACTION =>
1679 {
1680 None
1681 }
1682 RuntimeEvent::ElicitationResolved {
1683 reply: Some(reply), ..
1684 } => {
1685 let mut entry =
1686 ChatEntry::plain(seq, ChatRole::User, reply).with_recorded_at(recorded_at_ms);
1687 entry.message_id = Some(format!("{ELICITATION_REPLY_ITEM_PREFIX}{seq}"));
1688 entries.push(entry);
1689 None
1690 }
1691 other => Some(other),
1692 }
1693}
1694
1695pub fn transcript_item_text(item: &TranscriptItem) -> String {
1701 match &item.body {
1702 TranscriptBody::User { content } => {
1703 sanitize_terminal_text(&materialized_content_text(content))
1704 }
1705 TranscriptBody::Message { event } => format!(
1706 "{}\n\n{}",
1707 event.message_label(),
1708 mj_core::transcript::sanitize_terminal_text(
1709 event.message_text().expect("message entry metadata")
1710 )
1711 ),
1712 TranscriptBody::Agent { chunks, .. } | TranscriptBody::Thought { chunks, .. } => {
1713 materialized_chunks_text(chunks)
1714 }
1715 TranscriptBody::Tool {
1716 call,
1717 terminal_outputs,
1718 presentation,
1719 ..
1720 } => {
1721 let Ok(call) = ToolCall::deserialize(call) else {
1722 return "[invalid tool call]".to_owned();
1723 };
1724 let mut text = materialized_tool_call_presentation(presentation.as_deref(), &call)
1725 .summary
1726 .clone();
1727 if text.trim().is_empty() {
1728 text = call.title.clone();
1729 }
1730 for record in terminal_outputs {
1731 text.push('\n');
1732 text.push_str(&terminal_output_detail(record));
1733 }
1734 sanitize_terminal_text(&text)
1735 }
1736 TranscriptBody::TerminalOutput { record } => {
1737 sanitize_terminal_text(&terminal_output_detail(record))
1738 }
1739 TranscriptBody::Plan { plan } => {
1740 let Ok(plan) = agent_client_protocol::v1::schema::Plan::deserialize(plan) else {
1741 return String::new();
1742 };
1743 plan.entries
1744 .iter()
1745 .map(|entry| {
1746 let status = match plan_status(&entry.status) {
1747 PlanStatus::Pending => "pending",
1748 PlanStatus::Running => "running",
1749 PlanStatus::Completed => "completed",
1750 };
1751 format!("[{status}] {}", sanitize_terminal_text(&entry.content))
1752 })
1753 .collect::<Vec<_>>()
1754 .join("\n")
1755 }
1756 TranscriptBody::PlanProposal { plan, .. } => sanitize_terminal_text(plan),
1757 TranscriptBody::System { text } => sanitize_terminal_text(text),
1758 }
1759}
1760
1761pub(crate) fn compute_tool_diffstats(content: &[ToolCallContent]) -> Vec<String> {
1762 content
1763 .iter()
1764 .filter_map(|item| match item {
1765 ToolCallContent::Diff(diff) => Some(format_diffstat(diff)),
1766 _ => None,
1767 })
1768 .collect()
1769}
1770
1771pub fn materialized_tool_diffstats(item: &TranscriptItem) -> Option<Vec<String>> {
1772 let TranscriptBody::Tool { call, .. } = &item.body else {
1773 return None;
1774 };
1775 let call = match ToolCall::deserialize(call) {
1776 Ok(call) => call,
1777 Err(error) => {
1778 tracing::warn!(
1779 stable_id = %item.stable_id,
1780 %error,
1781 "could not decode a stored tool call while reading diff summary"
1782 );
1783 return None;
1784 }
1785 };
1786 if !matches!(
1787 tool_status(&call.status),
1788 ToolStatus::Completed | ToolStatus::Failed
1789 ) {
1790 return None;
1791 }
1792 let diffstats = compute_tool_diffstats(&call.content);
1793 (!diffstats.is_empty()).then_some(diffstats)
1794}
1795
1796fn format_diffstat(diff: &agent_client_protocol::v1::schema::Diff) -> String {
1797 let patch = mj_core::diff::patch_of(diff);
1801 format!(
1802 "{} +{} −{}",
1803 diff.path.display(),
1804 patch.insertions,
1805 patch.deletions
1806 )
1807}
1808
1809#[cfg(test)]
1810mod tests {
1811 use super::*;
1812 use agent_client_protocol::v1::schema::{ToolCall, ToolCallStatus, ToolCallUpdate};
1813 use serde_json::json;
1814
1815 #[test]
1816 fn a_live_tool_call_records_when_it_started_and_ended() {
1817 let mut entries = Vec::new();
1818 let call = ToolCall::new("tool-1", "cargo test").status(ToolCallStatus::InProgress);
1819 apply_session_update_to_entries(
1820 &mut entries,
1821 1,
1822 Some(1_000),
1823 SessionUpdate::ToolCall(call),
1824 );
1825 assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1826 assert_eq!(entries[0].tool_ended_at_ms, None);
1827
1828 let finish = SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
1829 "tool-1",
1830 ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
1831 ));
1832 apply_session_update_to_entries(&mut entries, 2, Some(91_000), finish);
1833 assert_eq!(entries[0].recorded_at_ms, Some(1_000));
1834 assert_eq!(entries[0].tool_ended_at_ms, Some(91_000));
1835 }
1836
1837 #[test]
1841 fn a_question_tool_is_summarized_by_its_whole_question() {
1842 let call = ToolCall::new("ask", "Which file name should I use for the new file?")
1843 .raw_input(json!({"questions": [{"question": "Which file name should I use for the new file?", "header": "File name"}]}));
1844 assert_eq!(
1845 tool_call_presentation(&call).summary,
1846 "Which file name should I use for the new file?"
1847 );
1848 let read = ToolCall::new("read", "Read src/lib.rs");
1849 assert_eq!(tool_call_presentation(&read).summary, "Read");
1850 let stale = ToolCallPresentation {
1851 summary: "Which".into(),
1852 source: call.title.clone(),
1853 source_kind: ToolSummarySourceKind::Title,
1854 tool_kind: ToolKind::Other,
1855 summary_version: 1,
1856 };
1857 assert_eq!(
1858 materialized_tool_call_presentation(Some(&stale), &call).summary,
1859 "Which file name should I use for the new file?",
1860 "stored rows written by the old rules are repaired"
1861 );
1862 }
1863
1864 fn execute_summary(command: serde_json::Value) -> String {
1865 let call = ToolCall::new("argv", "Bash")
1866 .kind(ToolKind::Execute)
1867 .raw_input(command);
1868 tool_call_presentation(&call).summary
1869 }
1870
1871 #[test]
1872 fn unknown_leading_options_make_verb_position_ambiguous() {
1873 assert_eq!(
1874 execute_summary(json!({"command": ["git", "--mystery", "status"]})),
1875 "git"
1876 );
1877 assert_eq!(
1878 execute_summary(json!({"command": ["cargo", "--mystery", "test"]})),
1879 "cargo"
1880 );
1881 }
1882
1883 #[test]
1884 fn git_commands_with_nested_subcommands_show_both_verbs() {
1885 let cases = [
1886 ("git worktree add ../x mj/session", "git worktree add"),
1887 ("git -C repo worktree list", "git worktree list"),
1888 ("git stash push -u -m tag", "git stash push"),
1889 ("git stash", "git stash"),
1890 ("git remote -v", "git remote"),
1891 ("git bisect good abc123", "git bisect good"),
1892 ("git stash -- src", "git stash"),
1893 ("git log origin/master", "git log"),
1894 ("git config user.name", "git config"),
1895 ];
1896 for (command, summary) in cases {
1897 assert_eq!(
1898 execute_summary(json!({"command": command})),
1899 summary,
1900 "{command}"
1901 );
1902 }
1903 }
1904
1905 #[test]
1906 fn project_tools_and_script_runners_show_their_subcommands() {
1907 let cases = [
1908 ("mbx nextest run -p brokk-mj-tui", "mbx nextest"),
1909 ("mbx +1.91 build bifrost", "mbx build"),
1910 ("mbx cache stats --json", "mbx cache stats"),
1911 ("mj daemon restart", "mj daemon restart"),
1912 (
1913 "mj -i test --workspace hel daemon status",
1914 "mj daemon status",
1915 ),
1916 ("mj transcript abc123", "mj transcript"),
1917 ("tmux -L mjv-e send-keys -t 0 q", "tmux send-keys"),
1918 ("tmux -Lmjv capture-pane -p", "tmux capture-pane"),
1919 ("tmux -S /tmp/sock -2 new-session -d", "tmux new-session"),
1920 ("uv run pytest -q", "uv run pytest"),
1921 ("uv run ./scripts/check.py", "uv run check.py"),
1922 ("uv run --with x pytest", "uv run"),
1923 ("npm run build", "npm run build"),
1924 ("npm run-script test:e2e", "npm run-script test:e2e"),
1925 ("pnpm run lint", "pnpm run lint"),
1926 ("npm test", "npm test"),
1927 ];
1928 for (command, summary) in cases {
1929 assert_eq!(
1930 execute_summary(json!({"command": command})),
1931 summary,
1932 "{command}"
1933 );
1934 }
1935 }
1936
1937 #[test]
1938 fn a_nested_shell_is_named_without_its_path_and_shows_its_script() {
1939 let cases = [
1940 ("cd dir && bash -c 'python x.py'", "cd && bash -c python"),
1941 (
1942 "/bin/bash -c \"python x.py\" | tee log",
1943 "bash -c python | tee",
1944 ),
1945 (
1946 "true; /usr/bin/zsh -lc 'git status && cargo test'",
1947 "true ; zsh -c git status && cargo test",
1948 ),
1949 ("bash -c \"$script\"", "bash -c"),
1950 ("/bin/bash script.sh", "bash"),
1951 (
1952 "bash -c 'bash -c \"uv run pytest\"'",
1953 "bash -c uv run pytest",
1954 ),
1955 ];
1956 for (command, summary) in cases {
1957 assert_eq!(
1958 execute_summary(json!({"command": command})),
1959 summary,
1960 "{command}"
1961 );
1962 }
1963 assert_eq!(
1965 execute_summary(json!({"command": ["/bin/bash", "-lc", "python x.py"]})),
1966 "python"
1967 );
1968 assert_eq!(
1969 execute_summary(json!({"command": ["/bin/zsh", "script.sh"]})),
1970 "zsh"
1971 );
1972 }
1973
1974 #[test]
1978 fn a_command_that_is_only_a_shell_wrapper_stands_for_its_script() {
1979 let script = "python3 - <<'PY'\nprint(\"x\")\nPY";
1980 let wrapped = format!(
1981 "/bin/bash -lc \"{}\"",
1982 script.replace('\\', "\\\\").replace('"', "\\\"")
1983 );
1984 let presentation = |command: &str| {
1985 tool_call_presentation(
1986 &ToolCall::new("call", "Bash")
1987 .kind(ToolKind::Execute)
1988 .raw_input(json!({ "command": command })),
1989 )
1990 };
1991 assert_eq!(presentation(script).summary, "python3");
1992 assert_eq!(presentation(&wrapped).summary, "python3");
1993 assert_eq!(presentation(&wrapped).source, script);
1994
1995 let cases = [
1996 ("bash -c 'python x.py'", "python"),
1997 (
1998 "/usr/bin/zsh -lc 'git status && cargo test'",
1999 "git status && cargo test",
2000 ),
2001 ("bash -c \"cd $dir && make\"", "cd && make"),
2002 ("bash -c 'cargo test' arg0", "cargo test"),
2003 (
2005 "/bin/bash -lc \"rg -n '\"'^fn'\"' src | head\"",
2006 "rg | head",
2007 ),
2008 ("FOO=1 bash -c 'cargo test'", "bash -c cargo test"),
2010 ];
2011 for (command, summary) in cases {
2012 assert_eq!(presentation(command).summary, summary, "{command}");
2013 }
2014 }
2015
2016 #[test]
2019 fn a_summary_whose_input_retention_dropped_is_kept() {
2020 let compacted = ToolCall::new("call", "Bash").kind(ToolKind::Execute);
2021 let stale = ToolCallPresentation {
2022 summary: "cargo test".into(),
2023 source: "cargo test --workspace".into(),
2024 source_kind: ToolSummarySourceKind::RawInput,
2025 tool_kind: ToolKind::Execute,
2026 summary_version: 0,
2027 };
2028 assert_eq!(
2029 materialized_tool_call_presentation(Some(&stale), &compacted),
2030 stale
2031 );
2032 let titled = ToolCallPresentation {
2033 source_kind: ToolSummarySourceKind::Title,
2034 ..stale
2035 };
2036 assert_eq!(
2037 materialized_tool_call_presentation(Some(&titled), &compacted).summary,
2038 "Bash"
2039 );
2040 }
2041
2042 #[test]
2043 fn quoted_and_dynamic_shell_verbs_are_distinguished() {
2044 let quoted = ToolCall::new("quoted", "Bash")
2045 .kind(ToolKind::Execute)
2046 .raw_input(json!({"command": "git \"status\""}));
2047 assert_eq!(tool_call_presentation("ed).summary, "git status");
2048
2049 let dynamic = ToolCall::new("dynamic", "Bash")
2050 .kind(ToolKind::Execute)
2051 .raw_input(json!({"command": "git \"$verb\""}));
2052 assert_eq!(tool_call_presentation(&dynamic).summary, "git");
2053
2054 let dynamic_name = ToolCall::new("dynamic-name", "Bash")
2055 .kind(ToolKind::Execute)
2056 .raw_input(json!({"command": "$command status"}));
2057 assert_eq!(tool_call_presentation(&dynamic_name).summary, "Bash");
2058 }
2059
2060 #[test]
2063 fn shell_summary_keeps_the_commands_around_an_unnamed_one() {
2064 let presentation = |command: &str| {
2065 tool_call_presentation(
2066 &ToolCall::new("call", "Bash")
2067 .kind(ToolKind::Execute)
2068 .raw_input(json!({ "command": command })),
2069 )
2070 .summary
2071 };
2072 let cases = [
2073 (
2074 "T=$(git grep -l 'facts' -- tests | head -1); echo \"file: $T\"; \
2075 S=$(echo $T | cut -d/ -f2); E=\"env -u CARGO\"; \
2076 $E X=1 cargo nextest run --test $S 2>&1 | grep -E 'FAIL'; \
2077 $E cargo clippy 2>&1 | grep -E '^error' | head -3",
2078 "git grep | head ; echo ; echo | cut ; … | grep ; … | grep | head",
2079 ),
2080 ("export T=\"$(git rev-parse HEAD)\"", "git rev-parse"),
2081 ("A=1 B=$(date)", "date"),
2082 ("cd dir && $runner test", "cd && …"),
2083 ("FOO=bar env -i echo $(printf hi)", "env"),
2084 ("E=x", "Bash"),
2085 ];
2086 for (command, summary) in cases {
2087 assert_eq!(presentation(command), summary, "{command}");
2088 }
2089 }
2090
2091 #[test]
2092 fn shell_summary_skips_assignments_arguments_and_nested_substitutions() {
2093 let call = ToolCall::new("call", "Bash")
2094 .kind(ToolKind::Execute)
2095 .raw_input(json!({
2096 "command": "FOO=bar env -i bash -c \"echo $(printf hi)\""
2097 }));
2098 assert_eq!(tool_call_presentation(&call).summary, "env");
2099
2100 let subshell = ToolCall::new("subshell", "Bash")
2101 .kind(ToolKind::Execute)
2102 .raw_input(json!({
2103 "command": "(cd dir && python x.py) | cat"
2104 }));
2105 assert_eq!(
2106 tool_call_presentation(&subshell).summary,
2107 "(cd && python) | cat"
2108 );
2109 }
2110
2111 #[test]
2112 fn shell_summary_keeps_list_pipeline_and_background_operators() {
2113 let simple = ToolCall::new("call-1", "Bash")
2114 .kind(ToolKind::Execute)
2115 .raw_input(json!({
2116 "command": "cd dir && python x.py | cat | wc ; print ok"
2117 }));
2118 let presentation = tool_call_presentation(&simple);
2119 assert_eq!(presentation.summary, "cd && python | cat | wc ; print");
2120 assert_eq!(presentation.source_kind, ToolSummarySourceKind::RawInput);
2121
2122 let call = ToolCall::new("operators", "Bash")
2123 .kind(ToolKind::Execute)
2124 .raw_input(json!({
2125 "command": "'printf' '%s' hi >out |& sed s/hi/bye/ || echo failed & wait; cat <in"
2126 }));
2127
2128 assert_eq!(
2129 tool_call_presentation(&call).summary,
2130 "printf |& sed || echo & wait ; cat"
2131 );
2132 }
2133
2134 #[test]
2135 fn shell_summary_removes_structural_loop_and_group_separators() {
2136 let call = ToolCall::new("compound", "Bash")
2137 .kind(ToolKind::Execute)
2138 .raw_input(json!({
2139 "command": "for file in a b; do rm \"$file\"; done; mkdir -p out; nice -n 10 python3 script.py"
2140 }));
2141
2142 assert_eq!(
2143 tool_call_presentation(&call).summary,
2144 "rm ; mkdir ; nice python3"
2145 );
2146
2147 let conditional = ToolCall::new("conditional", "Bash")
2148 .kind(ToolKind::Execute)
2149 .raw_input(json!({
2150 "command": "if test -f foo; then rm foo; fi; { mkdir bar; echo done; }"
2151 }));
2152 assert_eq!(
2153 tool_call_presentation(&conditional).summary,
2154 "test ; rm ; mkdir ; echo"
2155 );
2156
2157 let case_statement = ToolCall::new("case", "Bash")
2158 .kind(ToolKind::Execute)
2159 .raw_input(json!({
2160 "command": "echo start; case x in a|b) echo branch;; esac; echo done"
2161 }));
2162 assert_eq!(
2163 tool_call_presentation(&case_statement).summary,
2164 "echo ; echo ; echo"
2165 );
2166 }
2167
2168 #[test]
2169 fn shell_summary_handles_a_loop_with_a_leading_pipeline_and_nice() {
2170 let call = ToolCall::new("live-loop-shape", "Bash")
2171 .kind(ToolKind::Execute)
2172 .raw_input(json!({
2173 "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"
2174 }));
2175
2176 assert_eq!(
2177 tool_call_presentation(&call).summary,
2178 "cd && set ; rm ; mkdir ; nice ./bin/bifrost ; echo ; python3"
2179 );
2180 }
2181
2182 #[test]
2183 fn shell_summary_inserts_a_separator_after_a_heredoc() {
2184 let call = ToolCall::new("heredoc", "Bash")
2185 .kind(ToolKind::Execute)
2186 .raw_input(json!({
2187 "command": "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head"
2188 }));
2189
2190 assert_eq!(
2191 tool_call_presentation(&call).summary,
2192 "python3 ; grep | head"
2193 );
2194 }
2195
2196 #[test]
2197 fn materialized_summary_from_an_older_parser_is_repaired() {
2198 let source = "python3 <<'PYEOF'\nprint(\"x\")\nPYEOF\ngrep -n x file | head";
2199 let call = ToolCall::new("heredoc", "Bash")
2200 .kind(ToolKind::Execute)
2201 .raw_input(json!({ "command": source }));
2202 let stale = ToolCallPresentation {
2203 summary: "python3 grep | head".into(),
2204 source: source.into(),
2205 source_kind: ToolSummarySourceKind::RawInput,
2206 tool_kind: ToolKind::Execute,
2207 summary_version: 0,
2208 };
2209
2210 let repaired = materialized_tool_call_presentation(Some(&stale), &call);
2211 assert_eq!(repaired.summary, "python3 ; grep | head");
2212 assert_eq!(repaired.summary_version, TOOL_SUMMARY_VERSION);
2213
2214 let mut current = repaired;
2215 current.summary = "stored current summary".into();
2216 assert_eq!(
2217 materialized_tool_call_presentation(Some(¤t), &call).summary,
2218 "stored current summary"
2219 );
2220 }
2221
2222 #[test]
2223 fn execute_summary_bounds_the_retained_source_before_parsing() {
2224 let command = format!("echo {}", "argument".repeat(TOOL_SUMMARY_SOURCE_BYTES));
2225 let call = ToolCall::new("bounded", "Bash")
2226 .kind(ToolKind::Execute)
2227 .raw_input(json!({ "command": command }));
2228
2229 let presentation = tool_call_presentation(&call);
2230 assert_eq!(presentation.source.len(), TOOL_SUMMARY_SOURCE_BYTES);
2231 assert_eq!(presentation.summary, "echo");
2232 }
2233
2234 #[test]
2235 fn title_wrappers_and_malformed_shell_fall_back_safely() {
2236 let wrapped = ToolCall::new("wrapped", "Running: ls -la").kind(ToolKind::Execute);
2237 assert_eq!(tool_call_presentation(&wrapped).summary, "ls");
2238
2239 let malformed = ToolCall::new("bad", "Bash")
2240 .kind(ToolKind::Execute)
2241 .raw_input(json!({"command": "cd && ("}));
2242 assert_eq!(tool_call_presentation(&malformed).summary, "Bash");
2243 }
2244
2245 #[test]
2246 fn explicit_empty_raw_input_drops_a_stale_raw_summary() {
2247 let initial = ToolCall::new("call", "Bash")
2248 .kind(ToolKind::Execute)
2249 .raw_input(json!({"command": "python script.py"}));
2250 let previous = tool_call_presentation(&initial);
2251 let empty_input = json!({"command": null});
2252 let updated = update_tool_call_presentation(
2253 Some(&previous),
2254 "Running: ls -la",
2255 None,
2256 Some(&empty_input),
2257 None,
2258 );
2259 assert_eq!(updated.summary, "ls");
2260 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
2261
2262 let output = json!({"command": "cat result.txt"});
2263 let updated = update_tool_call_presentation(
2264 Some(&previous),
2265 "Running: ls -la",
2266 None,
2267 Some(&empty_input),
2268 Some(&output),
2269 );
2270 assert_eq!(updated.summary, "cat");
2271 assert_eq!(updated.source_kind, ToolSummarySourceKind::RawOutput);
2272
2273 let output_initial = ToolCall::new("output", "Bash")
2274 .kind(ToolKind::Execute)
2275 .raw_output(json!({"command": "python result.py"}));
2276 let output_previous = tool_call_presentation(&output_initial);
2277 let empty_output = json!({"command": null});
2278 let updated = update_tool_call_presentation(
2279 Some(&output_previous),
2280 "Running: ls -la",
2281 None,
2282 None,
2283 Some(&empty_output),
2284 );
2285 assert_eq!(updated.summary, "ls");
2286 assert_eq!(updated.source_kind, ToolSummarySourceKind::Title);
2287 }
2288
2289 fn rendered_tool_row(call: &ToolCall) -> String {
2290 let presentation = tool_call_presentation(call);
2291 let item = TranscriptItem {
2292 stable_id: "tool:golden".into(),
2293 position: 1,
2294 latest_content_event_ordinal: None,
2295 created_at_ms: 1,
2296 last_changed_at_ms: 1,
2297 body: TranscriptBody::Tool {
2298 call: serde_json::to_value(call).expect("serialize tool call"),
2299 terminal_outputs: Vec::new(),
2300 terminal_refs: Vec::new(),
2301 presentation: Some(Box::new(presentation)),
2302 },
2303 };
2304 transcript_item_text(&item)
2305 }
2306
2307 fn append_tool_row(output: &mut String, label: &str, call: &ToolCall) {
2308 use std::fmt::Write as _;
2309 if !output.is_empty() {
2310 output.push('\n');
2311 }
2312 writeln!(output, "=== {label} (transcript row) ===").unwrap();
2313 output.push_str(&rendered_tool_row(call));
2314 output.push('\n');
2315 }
2316
2317 #[test]
2318 fn golden_transcript_tool_row_summary() {
2319 use std::fmt::Write as _;
2320
2321 let mut output = String::new();
2322 let hostile = "safe\x1b]52;c;Y2xpcGJvYXJk\x07\x1b[31mred\x1b[0m";
2324 for (label, body) in [
2325 (
2326 "user message",
2327 TranscriptBody::User {
2328 content: vec![json!({"type":"text","text":hostile})],
2329 },
2330 ),
2331 (
2332 "plan proposal",
2333 TranscriptBody::PlanProposal {
2334 proposal_id: "golden".into(),
2335 plan: hostile.into(),
2336 },
2337 ),
2338 (
2339 "system message",
2340 TranscriptBody::System {
2341 text: hostile.into(),
2342 },
2343 ),
2344 ] {
2345 let item = TranscriptItem {
2346 stable_id: format!("{label}:golden"),
2347 position: 1,
2348 latest_content_event_ordinal: None,
2349 created_at_ms: 1,
2350 last_changed_at_ms: 1,
2351 body,
2352 };
2353 writeln!(output, "=== {label} (transcript row) ===").unwrap();
2354 writeln!(output, "{}", transcript_item_text(&item)).unwrap();
2355 }
2356 let diff = agent_client_protocol::v1::schema::Diff::new("/workspace/new.txt", "one\ntwo\n");
2357 writeln!(output, "=== new file diff detail (transcript row) ===").unwrap();
2358 writeln!(output, "{}", format_diffstat(&diff)).unwrap();
2359
2360 let terminal = |exit_code, signal: Option<&str>, truncated, text: &str| {
2361 let record = TerminalOutputRecord {
2362 terminal_id: "term-1".into(),
2363 output: text.into(),
2364 truncated,
2365 exit_code,
2366 signal: signal.map(str::to_owned),
2367 };
2368 let item = TranscriptItem {
2369 stable_id: "terminal:golden".into(),
2370 position: 1,
2371 latest_content_event_ordinal: None,
2372 created_at_ms: 1,
2373 last_changed_at_ms: 1,
2374 body: TranscriptBody::TerminalOutput { record },
2375 };
2376 transcript_item_text(&item)
2377 };
2378 for (label, row) in [
2379 ("successful terminal", terminal(Some(0), None, false, "out")),
2380 ("truncated terminal", terminal(Some(1), None, true, "out")),
2381 (
2382 "signal termination",
2383 terminal(None, Some("SIGKILL"), false, "out"),
2384 ),
2385 ("released terminal", terminal(None, None, false, "out")),
2386 (
2387 "silent signal termination",
2388 terminal(None, Some("SIGTERM"), false, ""),
2389 ),
2390 ] {
2391 writeln!(output, "\n=== {label} (transcript row) ===\n{row}").unwrap();
2392 }
2393
2394 append_tool_row(
2395 &mut output,
2396 "shell command",
2397 &ToolCall::new("shell", "Terminal")
2398 .kind(ToolKind::Execute)
2399 .raw_input(json!({
2400 "command": ["bash", "-lc", "cd dir && python x.py | cat"]
2401 })),
2402 );
2403 append_tool_row(
2404 &mut output,
2405 "ordinary argv command",
2406 &ToolCall::new("argv", "Execute")
2407 .kind(ToolKind::Execute)
2408 .raw_input(json!({"command": ["python", "-c", "print(1)"]})),
2409 );
2410
2411 let update_call = ToolCall::new("shell", "Bash")
2412 .kind(ToolKind::Execute)
2413 .raw_input(json!({"command": "cargo test"}));
2414 let original = tool_call_presentation(&update_call);
2415 let mut output_update = ToolCallUpdateFields::default();
2416 output_update.raw_output = Some(json!({"output": "x".repeat(128 * 1024)}));
2417 writeln!(output, "\n=== output-only update (transcript row) ===").unwrap();
2418 writeln!(
2419 output,
2420 "presentation changed: {}",
2421 tool_call_update_changes_presentation(&update_call, &output_update)
2422 )
2423 .unwrap();
2424 writeln!(output, "{}", original.summary).unwrap();
2425 let mut status_update = ToolCallUpdateFields::default();
2426 status_update.status = Some(ToolCallStatus::Completed);
2427 writeln!(
2428 output,
2429 "status-only update changes presentation: {}",
2430 tool_call_update_changes_presentation(&update_call, &status_update)
2431 )
2432 .unwrap();
2433 let output_call = ToolCall::new("output", "Bash").kind(ToolKind::Execute);
2434 writeln!(
2435 output,
2436 "output-only call changes presentation: {}",
2437 tool_call_update_changes_presentation(&output_call, &output_update)
2438 )
2439 .unwrap();
2440 let changed_input = json!({"command": "cargo check"});
2441 let mut input_update = ToolCallUpdateFields::default();
2442 input_update.raw_input = Some(changed_input.clone());
2443 writeln!(
2444 output,
2445 "changed command presentation: {}",
2446 tool_call_update_changes_presentation(&update_call, &input_update)
2447 )
2448 .unwrap();
2449 writeln!(
2450 output,
2451 "updated row: {}",
2452 update_tool_call_presentation(
2453 Some(&original),
2454 "Bash",
2455 Some(ToolKind::Execute),
2456 Some(&changed_input),
2457 None,
2458 )
2459 .summary
2460 )
2461 .unwrap();
2462
2463 for (label, command) in [
2464 (
2465 "git registered verb",
2466 json!({"command": ["git", "--no-pager", "status", "--short"]}),
2467 ),
2468 (
2469 "cargo registered verb",
2470 json!({"command": ["cargo", "+nightly", "test", "--package", "hel"]}),
2471 ),
2472 (
2473 "gh registered namespace",
2474 json!({"command": ["gh", "--hostname", "github.example", "pr", "list"]}),
2475 ),
2476 (
2477 "docker registered namespace",
2478 json!({"command": ["docker", "--context", "work", "compose", "up"]}),
2479 ),
2480 (
2481 "podman registered namespace",
2482 json!({"command": ["podman", "machine", "list"]}),
2483 ),
2484 (
2485 "uv registered namespace",
2486 json!({"command": ["uv", "--project", "app", "pip", "install", "ruff"]}),
2487 ),
2488 (
2489 "rustup registered namespace",
2490 json!({"command": ["rustup", "toolchain", "list"]}),
2491 ),
2492 (
2493 "npm registered namespace",
2494 json!({"command": ["npm", "--prefix", "web", "run", "build"]}),
2495 ),
2496 ] {
2497 append_tool_row(
2498 &mut output,
2499 label,
2500 &ToolCall::new("argv", "Bash")
2501 .kind(ToolKind::Execute)
2502 .raw_input(command),
2503 );
2504 }
2505
2506 let shell = ToolCall::new("string", "Bash")
2507 .kind(ToolKind::Execute)
2508 .raw_input(json!({"command": "git --no-pager status --short"}));
2509 let argv = ToolCall::new("argv", "Bash")
2510 .kind(ToolKind::Execute)
2511 .raw_input(json!({"command": ["git", "--no-pager", "status", "--short"]}));
2512 writeln!(
2513 output,
2514 "\n=== shell and argv invocation depth (transcript rows) ==="
2515 )
2516 .unwrap();
2517 writeln!(output, "shell: {}", rendered_tool_row(&shell)).unwrap();
2518 writeln!(output, "argv: {}", rendered_tool_row(&argv)).unwrap();
2519
2520 for (label, command) in [
2521 ("sudo wrapper", "sudo -n git status"),
2522 ("env wrapper", "env FOO=bar git status"),
2523 ("command wrapper", "command git status"),
2524 ] {
2525 append_tool_row(
2526 &mut output,
2527 label,
2528 &ToolCall::new("wrapper", "Bash")
2529 .kind(ToolKind::Execute)
2530 .raw_input(json!({"command": command})),
2531 );
2532 }
2533
2534 for (label, command) in [
2535 (
2536 "unlisted build tool",
2537 json!({"command": ["mytool", "build", "src"]}),
2538 ),
2539 (
2540 "unlisted script",
2541 json!({"command": ["mytool", "./script.sh"]}),
2542 ),
2543 ("python script", json!({"command": ["python", "script.py"]})),
2544 (
2545 "gh API namespace",
2546 json!({"command": ["gh", "api", "graphql"]}),
2547 ),
2548 (
2549 "docker run namespace",
2550 json!({"command": ["docker", "run", "ubuntu"]}),
2551 ),
2552 (
2553 "registered future git verb",
2554 json!({"command": ["git", "future-verb"]}),
2555 ),
2556 (
2557 "absolute git with attached directory",
2558 json!({"command": ["/usr/bin/git", "-Crepo", "status"]}),
2559 ),
2560 (
2561 "git short global option",
2562 json!({"command": ["git", "-c", "core.pager=cat", "status"]}),
2563 ),
2564 (
2565 "gh attached repository option",
2566 json!({"command": ["gh", "-Rorg/repo", "pr", "list"]}),
2567 ),
2568 (
2569 "cargo color option",
2570 json!({"command": ["cargo", "--color=always", "test"]}),
2571 ),
2572 (
2573 "cargo config option",
2574 json!({"command": ["cargo", "--config", "build.jobs=2", "test"]}),
2575 ),
2576 ] {
2577 append_tool_row(
2578 &mut output,
2579 label,
2580 &ToolCall::new("argv", "Bash")
2581 .kind(ToolKind::Execute)
2582 .raw_input(command),
2583 );
2584 }
2585
2586 for command in [
2587 vec!["nice", "-n", "10", "python3", "script.py"],
2588 vec!["nice", "--adjustment", "10", "python3", "script.py"],
2589 vec!["nice", "--adjustment=10", "python3", "script.py"],
2590 vec!["nice", "-10", "python3", "script.py"],
2591 vec!["nice", "-n10", "python3", "script.py"],
2592 vec!["nice", "--", "python3", "script.py"],
2593 ] {
2594 append_tool_row(
2595 &mut output,
2596 "nice command options",
2597 &ToolCall::new("nice", "Bash")
2598 .kind(ToolKind::Execute)
2599 .raw_input(json!({"command": command})),
2600 );
2601 }
2602 append_tool_row(
2603 &mut output,
2604 "nice shell command",
2605 &ToolCall::new("nice-shell", "Bash")
2606 .kind(ToolKind::Execute)
2607 .raw_input(json!({"command": "nice -n 10 python3 script.py"})),
2608 );
2609 for (label, command) in [
2610 ("timeout shell command", json!("timeout git status")),
2611 (
2612 "timeout argv command",
2613 json!(["timeout", "30s", "git", "-C", "repo", "worktree", "list"]),
2614 ),
2615 (
2616 "timeout command options",
2617 json!([
2618 "timeout",
2619 "--foreground",
2620 "--preserve-status",
2621 "--verbose",
2622 "--signal",
2623 "TERM",
2624 "--kill-after=5s",
2625 "1.5m",
2626 "git",
2627 "status"
2628 ]),
2629 ),
2630 (
2631 "timeout attached short options",
2632 json!("timeout -sTERM -k5s -- 30 git status"),
2633 ),
2634 (
2635 "nested command wrappers",
2636 json!("nice -n 10 timeout 5m nice -- cargo +nightly test -q"),
2637 ),
2638 (
2639 "recursive script runner",
2640 json!("uv run /usr/bin/timeout 5m git status"),
2641 ),
2642 (
2643 "wrapped shell command",
2644 json!("timeout 1h /bin/bash -lc 'git status && cargo test'"),
2645 ),
2646 (
2647 "timeout in a pipeline",
2648 json!("timeout 10 git status | cat && timeout 2m gh pr list"),
2649 ),
2650 (
2651 "timeout unknown option",
2652 json!("nice timeout --mystery 10 git status"),
2653 ),
2654 (
2655 "timeout dynamic duration",
2656 json!("timeout \"$duration\" git status"),
2657 ),
2658 (
2659 "timeout dynamic command",
2660 json!("timeout 30 \"$command\" status"),
2661 ),
2662 ("wrapped dynamic verb", json!("timeout 30 git \"$verb\"")),
2663 ("timeout without command", json!(["timeout", "30"])),
2664 (
2665 "script name is not an invocation",
2666 json!("timeout 30 npm run git status"),
2667 ),
2668 (
2669 "ordinary command arguments are not invocations",
2670 json!("timeout 30 python git status"),
2671 ),
2672 (
2673 "ssh remote command",
2674 json!("ssh builder git status --short"),
2675 ),
2676 (
2677 "ssh remote argv",
2678 json!(["ssh", "builder", "git", "-C", "repo", "worktree", "list"]),
2679 ),
2680 (
2681 "ssh quoted remote script",
2682 json!("ssh builder 'cd repo && git status | cat'"),
2683 ),
2684 (
2685 "ssh quoted remote argv script",
2686 json!(["ssh", "builder", "git status && cargo test -q"]),
2687 ),
2688 (
2689 "ssh connection options",
2690 json!(
2691 "/usr/bin/ssh -vvT -p 2222 -o BatchMode=yes -i /keys/build builder git status"
2692 ),
2693 ),
2694 (
2695 "ssh attached options after destination",
2696 json!("ssh builder -Tp2222 -oBatchMode=yes -- uv run pytest -q"),
2697 ),
2698 (
2699 "ssh wrapped remote shell",
2700 json!("timeout 30 ssh -- builder 'bash -lc \"git status && cargo test\"'"),
2701 ),
2702 ("ssh without remote command", json!("ssh builder")),
2703 ("ssh dynamic destination", json!("ssh \"$host\" git status")),
2704 (
2705 "ssh dynamic remote script",
2706 json!("ssh builder \"cd $dir && git status\""),
2707 ),
2708 (
2709 "ssh dynamic remote command",
2710 json!("ssh builder \"$script\""),
2711 ),
2712 (
2713 "ssh unknown connection option",
2714 json!("ssh --mystery value builder git status"),
2715 ),
2716 (
2717 "ssh unknown option after destination",
2718 json!("ssh builder --mystery value git status"),
2719 ),
2720 ("ssh without destination", json!(["ssh", "-p", "2222"])),
2721 (
2722 "ssh nesting budget",
2723 json!(format!("{}git status", "ssh builder ".repeat(2_000))),
2724 ),
2725 ] {
2726 append_tool_row(
2727 &mut output,
2728 label,
2729 &ToolCall::new("recursive", "Bash")
2730 .kind(ToolKind::Execute)
2731 .raw_input(json!({"command": command})),
2732 );
2733 }
2734 for (label, command, summary, summary_version) in [
2735 (
2736 "cached wrapper summary",
2737 "nice -n 10 timeout 30 git status",
2738 "nice timeout",
2739 4,
2740 ),
2741 ("cached ssh summary", "ssh builder 'git status'", "ssh", 5),
2742 ] {
2743 let cached = ToolCall::new("cached-wrapper", "Bash")
2744 .kind(ToolKind::Execute)
2745 .raw_input(json!({"command": command}));
2746 let item = TranscriptItem {
2747 stable_id: "tool:cached-wrapper".into(),
2748 position: 1,
2749 latest_content_event_ordinal: None,
2750 created_at_ms: 1,
2751 last_changed_at_ms: 1,
2752 body: TranscriptBody::Tool {
2753 call: serde_json::to_value(&cached).expect("serialize tool call"),
2754 terminal_outputs: Vec::new(),
2755 terminal_refs: Vec::new(),
2756 presentation: Some(Box::new(ToolCallPresentation {
2757 summary: summary.into(),
2758 summary_version,
2759 ..tool_call_presentation(&cached)
2760 })),
2761 },
2762 };
2763 writeln!(
2764 output,
2765 "\n=== {label} (transcript row) ===\n{}",
2766 transcript_item_text(&item)
2767 )
2768 .unwrap();
2769 }
2770 append_tool_row(
2771 &mut output,
2772 "non-execute tool title",
2773 &ToolCall::new("read", "Read src/lib.rs").kind(ToolKind::Read),
2774 );
2775
2776 mj_core::golden::assert_golden(
2777 env!("CARGO_MANIFEST_DIR"),
2778 "transcript-tool-row-summary",
2779 &output,
2780 );
2781 }
2782}