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