Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

show shell-heavy ipython cells as bash in the collapsed card (#3307)

Sebastian Müllerd38bcb56e3b8
diff --git a/.changes/ipython-bash-dominated-cells.md b/.changes/ipython-bash-dominated-cells.md
new file mode 100644
index 0000000000..8ad9ad5203
--- /dev/null
+++ b/.changes/ipython-bash-dominated-cells.md
@@ -0,0 +1 @@
+- An ipython cell that mostly runs shell commands now shows as `bash` in its collapsed card, with its first `bash()` command and how many more it ran, including commands run through helper functions.
diff --git a/crates/pa-cli/src/interactive_mode/telemetry.rs b/crates/pa-cli/src/interactive_mode/telemetry.rs
index cf92e74cc9..87a1fe546a 100644
--- a/crates/pa-cli/src/interactive_mode/telemetry.rs
+++ b/crates/pa-cli/src/interactive_mode/telemetry.rs
@@ -157,6 +157,25 @@ impl pa_tui::interactive::InteractionTelemetry for CliInteractionTelemetry {
})
}
+ fn ipython_bash_rendered(
+ &self,
+ bash_lines: usize,
+ cell_lines: usize,
+ count: usize,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ Box::pin(async move {
+ let Some(client) = self.client() else {
+ return;
+ };
+ let mut properties = pa_telemetry::base_properties("interactive");
+ properties.set("bash_lines", serde_json::Value::from(bash_lines));
+ properties.set("cell_lines", serde_json::Value::from(cell_lines));
+ properties.set("count", serde_json::Value::from(count));
+ client.track("tui ipython bash rendered", properties);
+ let _ = client.shutdown().await;
+ })
+ }
+
fn scroll_used(
&self,
action: &'static str,
diff --git a/crates/pa-core/src/kernel/manager/events.rs b/crates/pa-core/src/kernel/manager/events.rs
index a232e341bf..c911ac4307 100644
--- a/crates/pa-core/src/kernel/manager/events.rs
+++ b/crates/pa-core/src/kernel/manager/events.rs
@@ -3,9 +3,10 @@
use super::{
append_truncated, lock, parse_attachment_display, parse_diff_display, parse_sent_agent_message,
- Arc, Event, ExecBuffers, ExecuteStatus, Guarded, Inner, KernelError, StreamName, Value,
- AGENT_MESSAGE_DISPLAY_MIME, ATTACHMENT_DISPLAY_MIME, BASH_ACTIVITY_DISPLAY_MIME,
- DIFF_DISPLAY_MIME, MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS,
+ Arc, Event, ExecBuffers, ExecuteStatus, Guarded, Inner, KernelBashCommands, KernelError,
+ StreamName, Value, AGENT_MESSAGE_DISPLAY_MIME, ATTACHMENT_DISPLAY_MIME,
+ BASH_ACTIVITY_DISPLAY_MIME, BASH_COMMAND_DISPLAY_MIME, DIFF_DISPLAY_MIME,
+ MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS,
};
use std::fmt::Write as _;
@@ -228,6 +229,26 @@ impl Inner {
buffers.sent_agent_messages.push(message);
}
}
+ if let Some(payload) = data.get(BASH_COMMAND_DISPLAY_MIME) {
+ if let (Some(command), Some(lines)) = (
+ payload.get("command").and_then(Value::as_str),
+ payload
+ .get("lines")
+ .and_then(Value::as_u64)
+ .and_then(|lines| usize::try_from(lines).ok()),
+ ) {
+ if let Some(bash) = buffers.bash_commands.as_mut() {
+ bash.count += 1;
+ bash.lines += lines;
+ } else {
+ buffers.bash_commands = Some(KernelBashCommands {
+ first: command.to_string(),
+ count: 1,
+ lines,
+ });
+ }
+ }
+ }
}
/// Unattributed stream text: attached to the active cell's background
diff --git a/crates/pa-core/src/kernel/manager/execution.rs b/crates/pa-core/src/kernel/manager/execution.rs
index b2e40686cc..654b335691 100644
--- a/crates/pa-core/src/kernel/manager/execution.rs
+++ b/crates/pa-core/src/kernel/manager/execution.rs
@@ -233,6 +233,7 @@ impl Inner {
.then(|| std::mem::take(&mut buffers.attachments)),
sent_agent_messages: (!buffers.sent_agent_messages.is_empty())
.then(|| std::mem::take(&mut buffers.sent_agent_messages)),
+ bash_commands: buffers.bash_commands.take(),
background_output: (!background_output.is_empty()).then_some(background_output),
status,
error: buffers.error.take(),
diff --git a/crates/pa-core/src/kernel/manager/mod.rs b/crates/pa-core/src/kernel/manager/mod.rs
index c303c8f285..b430fe00ff 100644
--- a/crates/pa-core/src/kernel/manager/mod.rs
+++ b/crates/pa-core/src/kernel/manager/mod.rs
@@ -23,15 +23,15 @@ use crate::kernel::orphan_journal;
use crate::kernel::protocol::{parse_event, Event, Request, REPL_PROTOCOL_VERSION};
use crate::kernel::shared::{
parse_attachment_display, parse_diff_display, parse_sent_agent_message, ExecuteOptions,
- ExecuteResult, ExecuteStatus, HostRequestPayload, KernelAttachment, KernelDiffDisplay,
- KernelError, KernelManagerOptions, KernelSentAgentMessage, KernelShutdownOptions,
- LateSentAgentMessageCallback, StreamName, AGENT_MESSAGE_DISPLAY_MIME, ATTACHMENT_DISPLAY_MIME,
- BASH_ACTIVITY_DISPLAY_MIME, DEFAULT_MAX_OUTPUT_CHARS, DEFAULT_SNAPSHOT_DEBOUNCE_MS,
- DIFF_DISPLAY_MIME, HOST_REQUEST_SHUTDOWN_TIMEOUT_MS, KERNEL_ABORT_GRACE_MS,
- KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE, KERNEL_BUSY_INTERRUPT_INTERVAL_MS,
- KERNEL_BUSY_REUSE_WAIT_MS, KERNEL_SHUTDOWN_TIMEOUT_MS, KERNEL_STDERR_LOG_BUDGET_MARKER,
- MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS, MAX_KERNEL_STDERR_CHARS,
- MAX_KERNEL_STDERR_LOG_BYTES, MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS,
+ ExecuteResult, ExecuteStatus, HostRequestPayload, KernelAttachment, KernelBashCommands,
+ KernelDiffDisplay, KernelError, KernelManagerOptions, KernelSentAgentMessage,
+ KernelShutdownOptions, LateSentAgentMessageCallback, StreamName, AGENT_MESSAGE_DISPLAY_MIME,
+ ATTACHMENT_DISPLAY_MIME, BASH_ACTIVITY_DISPLAY_MIME, BASH_COMMAND_DISPLAY_MIME,
+ DEFAULT_MAX_OUTPUT_CHARS, DEFAULT_SNAPSHOT_DEBOUNCE_MS, DIFF_DISPLAY_MIME,
+ HOST_REQUEST_SHUTDOWN_TIMEOUT_MS, KERNEL_ABORT_GRACE_MS, KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE,
+ KERNEL_BUSY_INTERRUPT_INTERVAL_MS, KERNEL_BUSY_REUSE_WAIT_MS, KERNEL_SHUTDOWN_TIMEOUT_MS,
+ KERNEL_STDERR_LOG_BUDGET_MARKER, MAX_ATTACHMENT_DATA_CHARS, MAX_BACKGROUND_OUTPUT_CHARS,
+ MAX_KERNEL_STDERR_CHARS, MAX_KERNEL_STDERR_LOG_BYTES, MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS,
RESTORE_EXECUTION_TIMEOUT_MS, SNAPSHOT_EXECUTION_TIMEOUT_MS,
};
use crate::kernel::state_snapshot::{
@@ -95,6 +95,7 @@ struct ExecBuffers {
attachments: Vec<KernelAttachment>,
attachment_oversized: bool,
sent_agent_messages: Vec<KernelSentAgentMessage>,
+ bash_commands: Option<KernelBashCommands>,
background_output: String,
background_output_chars: usize,
background_output_truncated: bool,
@@ -136,6 +137,7 @@ impl InternalExecuteResult {
diffs: None,
attachments: None,
sent_agent_messages: None,
+ bash_commands: None,
background_output: None,
status: ExecuteStatus::Aborted,
error: None,
diff --git a/crates/pa-core/src/kernel/shared.rs b/crates/pa-core/src/kernel/shared.rs
index 5ccb93dabd..d0f61debbb 100644
--- a/crates/pa-core/src/kernel/shared.rs
+++ b/crates/pa-core/src/kernel/shared.rs
@@ -45,6 +45,8 @@ pub const ATTACHMENT_DISPLAY_MIME: &str = "application/vnd.prime-agent.attachmen
pub const AGENT_MESSAGE_DISPLAY_MIME: &str = "application/vnd.prime-agent.agent-message+json";
/// Internal lifetime notices, consumed before user display rendering.
pub const BASH_ACTIVITY_DISPLAY_MIME: &str = "application/vnd.prime-agent.bash-activity+json";
+/// One `bash()` call's command text (capped) and non-blank line count.
+pub const BASH_COMMAND_DISPLAY_MIME: &str = "application/vnd.prime-agent.bash-command+json";
pub const EXECUTE_STATUS_OK: &str = "ok";
pub const EXECUTE_STATUS_ERROR: &str = "error";
@@ -149,6 +151,14 @@ pub struct SentAgentMessageTarget {
pub session_name: Option<String>,
}
+/// The `bash()` commands one cell started, summarized for display.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct KernelBashCommands {
+ pub first: String,
+ pub count: usize,
+ pub lines: usize,
+}
+
/// A kernel error reported by a failed cell.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelError {
@@ -170,6 +180,8 @@ pub struct ExecuteResult {
pub attachments: Option<Vec<KernelAttachment>>,
/// Agent messages sent from this cell, in order.
pub sent_agent_messages: Option<Vec<KernelSentAgentMessage>>,
+ /// The `bash()` commands this cell started, summarized for display.
+ pub bash_commands: Option<KernelBashCommands>,
/// Output that arrived without this cell's id (user threads, other cells' leftovers, raw fd writes).
pub background_output: Option<String>,
pub status: ExecuteStatus,
diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rs
index 5fa9cef25d..3cb6319ddb 100644
--- a/crates/pa-core/src/session_engine/runtime_wiring.rs
+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs
@@ -364,6 +364,7 @@ fn convert_execute_result(
})
.collect(),
sent_agent_messages: result.sent_agent_messages.unwrap_or_default(),
+ bash_commands: result.bash_commands,
}
}
diff --git a/crates/pa-core/src/tools/ipython.rs b/crates/pa-core/src/tools/ipython.rs
index 855e4f84b3..02b2a32a02 100644
--- a/crates/pa-core/src/tools/ipython.rs
+++ b/crates/pa-core/src/tools/ipython.rs
@@ -65,6 +65,9 @@ pub struct ExecuteResult {
/// Agent messages sent from this cell, in order (TS
/// `sentAgentMessages` on the tool-result details).
pub sent_agent_messages: Vec<crate::kernel::shared::KernelSentAgentMessage>,
+ /// The `bash()` commands this cell started, summarized for display
+ /// (`bashCommands` on the tool-result details).
+ pub bash_commands: Option<crate::kernel::shared::KernelBashCommands>,
}
/// The wire form of one sent agent message (TS `KernelSentAgentMessage`):
@@ -458,6 +461,13 @@ pub async fn execute_ipython(
if let Some(result_text) = &r.result {
details["result"] = json!(result_text);
}
+ if let Some(bash) = &r.bash_commands {
+ details["bashCommands"] = json!({
+ "first": bash.first,
+ "count": bash.count,
+ "lines": bash.lines,
+ });
+ }
if let Some(background) = &r.background_output {
details["backgroundOutput"] = json!(background);
}
diff --git a/crates/pa-core/tests/kernel_lifecycle.rs b/crates/pa-core/tests/kernel_lifecycle.rs
index b1fd27eb5f..eed3b14ed8 100644
--- a/crates/pa-core/tests/kernel_lifecycle.rs
+++ b/crates/pa-core/tests/kernel_lifecycle.rs
@@ -30,7 +30,7 @@ use std::time::Duration;
use pa_core::kernel::bootstrap::build_rlm_bootstrap_code;
use pa_core::kernel::manager::{KernelStartOptions, ReplKernelManager};
use pa_core::kernel::shared::{
- ExecuteOptions, ExecuteStatus, HostRequestHandlers, KernelManagerOptions,
+ ExecuteOptions, ExecuteStatus, HostRequestHandlers, KernelBashCommands, KernelManagerOptions,
KernelShutdownOptions, KernelSnapshotConfig,
};
use pa_core::kernel::state_snapshot::{manifest_path_in, snapshot_path_in};
@@ -480,6 +480,39 @@ async fn kernel_teardown_with_live_handles_settles_the_callback_once() {
assert_eq!(settled.load(std::sync::atomic::Ordering::SeqCst), 1);
}
+/// Each `bash()` call a cell starts reports its command text and line
+/// count through the bash-command display MIME, aggregated into the cell's
+/// execute result — including calls routed through a helper function,
+/// which a static scan of the cell source cannot see.
+#[tokio::test]
+async fn cell_result_summarizes_the_bash_commands_it_ran() {
+ let Some(options) = test_options(None) else {
+ return;
+ };
+ let manager = started_manager(options).await;
+ execute(&manager, "from rlm import bash").await;
+
+ let result = execute(
+ &manager,
+ "async def sh(cmd):\n return await bash(cmd)\nawait sh(\"echo one\\necho two\")\nawait bash(\"true\")",
+ )
+ .await;
+
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ result.bash_commands,
+ Some(KernelBashCommands {
+ first: "echo one\necho two".to_string(),
+ count: 2,
+ lines: 3,
+ })
+ );
+ manager
+ .shutdown(KernelShutdownOptions::default())
+ .await
+ .expect("shutdown");
+}
+
#[tokio::test]
async fn graceful_shutdown_flushes_the_final_snapshot() {
let dir = tempfile::tempdir().expect("tempdir");
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index dcf78ba504..b02e0084fd 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -1553,6 +1553,17 @@ const TUI_EVENTS: &[EventRule] = &[
),
],
},
+ // A settled ipython cell that rendered as bash: its executed bash()
+ // line share and command count, never command text.
+ EventRule {
+ name: "tui ipython bash rendered",
+ since: 2,
+ properties: &[
+ ("bash_lines", required(count())),
+ ("cell_lines", required(count())),
+ ("count", required(count())),
+ ],
+ },
];
/// The update-flow events (v1): `update completed` plus the per-phase
diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs
index 9e688185b6..6f90e78a7c 100644
--- a/crates/pa-tui/src/interactive.rs
+++ b/crates/pa-tui/src/interactive.rs
@@ -305,6 +305,16 @@ pub trait InteractionTelemetry: Send + Sync {
&self,
action: &'static str,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
+ /// One live ipython result whose collapsed card renders as bash
+ /// (event `tui ipython bash rendered`): the executed `bash()` line share
+ /// of the cell and the command count — primitives only, never command
+ /// text.
+ fn ipython_bash_rendered(
+ &self,
+ bash_lines: usize,
+ cell_lines: usize,
+ count: usize,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}
/// Options for one interactive run. `Debug` skips the telemetry handle (the
diff --git a/crates/pa-tui/src/session_ui/apply.rs b/crates/pa-tui/src/session_ui/apply.rs
index ad66d82e82..bac65ff11b 100644
--- a/crates/pa-tui/src/session_ui/apply.rs
+++ b/crates/pa-tui/src/session_ui/apply.rs
@@ -1053,6 +1053,7 @@ impl SessionUi {
if !partial {
card.ended_at = Some(std::time::Instant::now());
self.pending_tools.remove(tool_call_id);
+ self.track_ipython_bash_rendered(card);
}
view.mark_entry_stale(index);
return true;
@@ -1061,6 +1062,25 @@ impl SessionUi {
false
}
+ /// `tui ipython bash rendered`: the settled ipython card that renders
+ /// as bash reports its bash share, primitives only.
+ fn track_ipython_bash_rendered(&self, card: &crate::tool_card::ToolCallCard) {
+ if card.name != "ipython" {
+ return;
+ }
+ let Some(stats) = crate::tool_card::ipython::bash_dominated_stats(card) else {
+ return;
+ };
+ let Some(telemetry) = self.telemetry.clone() else {
+ return;
+ };
+ tokio::spawn(async move {
+ telemetry
+ .ipython_bash_rendered(stats.bash_lines, stats.cell_lines, stats.count)
+ .await;
+ });
+ }
+
/// Update the loader activity label (agent-activity tracker subset).
fn set_working_activity(activity: &'static str, download: bool, view: &mut AgentView) {
if let Some(working) = &mut view.working {
diff --git a/crates/pa-tui/src/tool_card/ipython.rs b/crates/pa-tui/src/tool_card/ipython.rs
index 30f67af403..50b6555ff4 100644
--- a/crates/pa-tui/src/tool_card/ipython.rs
+++ b/crates/pa-tui/src/tool_card/ipython.rs
@@ -11,13 +11,14 @@ use serde_json::Value;
use super::ipython_details::{
format_duration, is_agent_message_receipt, is_edit_confirmation, parse_sent_agent_message,
- read_background_shell, BackgroundShell, IpythonDetails, IpythonError,
+ read_background_shell, BackgroundShell, BashCommands, IpythonDetails, IpythonError,
};
use super::layout::RowOutput;
use super::{highlight, ToolCallCard};
use crate::chat::Detail;
use crate::code_preview::{
- parse_ipython_bash_cell, preview_ipython_code, python_statement_lines, CodePreviewLanguage,
+ parse_ipython_bash_cell, preview_bash_command, preview_ipython_code, python_statement_lines,
+ CodePreviewLanguage,
};
use crate::custom_message::AgentMessageDirection;
use crate::error_summary::{normalize_error_details, summarize_error_details};
@@ -194,12 +195,17 @@ fn collapsed_line(
let success = theme.fg_style(ThemeColor::Success);
let bash_mode = theme.fg_style(ThemeColor::BashMode);
+ let dominant = dominant_bash(details, code);
let preview = preview_ipython_code(code);
let is_bash_cell = parse_ipython_bash_cell(code).is_some();
- let language_label = match (is_bash_cell, &preview.language) {
- (true, CodePreviewLanguage::Python) => "bash \u{00b7} python".to_string(),
- (true | false, CodePreviewLanguage::Bash) => "bash".to_string(),
- (false, CodePreviewLanguage::Python) => "python".to_string(),
+ let language_label = if dominant.is_some() {
+ "bash".to_string()
+ } else {
+ match (is_bash_cell, &preview.language) {
+ (true, CodePreviewLanguage::Python) => "bash \u{00b7} python".to_string(),
+ (true | false, CodePreviewLanguage::Bash) => "bash".to_string(),
+ (false, CodePreviewLanguage::Python) => "python".to_string(),
+ }
};
let marker: Line = match CardStatus::of(card, details) {
@@ -218,7 +224,15 @@ fn collapsed_line(
marker.push(Span::raw(" "));
marker.push(Span::styled(language_label, muted));
parts.push(marker);
- if !preview.text.is_empty() {
+ if let Some(bash) = dominant {
+ let preview = preview_bash_command(&bash.first);
+ if !preview.text.is_empty() {
+ parts.push(vec![Span::styled(preview.text, dim)]);
+ }
+ if bash.count > 1 {
+ parts.push(vec![Span::styled(format!("+{} more", bash.count - 1), dim)]);
+ }
+ } else if !preview.text.is_empty() {
parts.push(vec![Span::styled(preview.text, dim)]);
} else if !card.started {
parts.push(vec![Span::styled("waiting for code".to_string(), dim)]);
@@ -260,12 +274,49 @@ fn collapsed_line(
truncate_line(&row, width, "")
}
+/// A cell renders as bash when its executed `bash()` lines are at least
+/// `1/BASH_DOMINANCE_DIVISOR` of the cell's non-blank lines. 2 means the bash
+/// lines are at least as many as the remaining Python lines (B >= P - B):
+/// literal commands also appear in the cell source, so P - B estimates
+/// the non-bash Python.
+const BASH_DOMINANCE_DIVISOR: usize = 2;
+
+fn input_line_count(code: &str) -> usize {
+ let body = parse_ipython_bash_cell(code).map_or_else(|| code.to_string(), |cell| cell.body);
+ body.lines().filter(|line| !line.trim().is_empty()).count()
+}
+
+fn dominant_bash<'a>(details: &'a IpythonDetails, code: &str) -> Option<&'a BashCommands> {
+ details
+ .bash_commands
+ .as_ref()
+ .filter(|bash| bash.lines * BASH_DOMINANCE_DIVISOR >= input_line_count(code))
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) struct BashCellStats {
+ pub(crate) bash_lines: usize,
+ pub(crate) cell_lines: usize,
+ pub(crate) count: usize,
+}
+
+/// The bash stats of a settled ipython card that renders as bash.
+pub(crate) fn bash_dominated_stats(card: &ToolCallCard) -> Option<BashCellStats> {
+ let code = cell_code(card).trim_end();
+ let details = IpythonDetails::parse(&card.result.as_ref()?.details);
+ let bash = dominant_bash(&details, code)?;
+ Some(BashCellStats {
+ bash_lines: bash.lines,
+ cell_lines: input_line_count(code),
+ count: bash.count,
+ })
+}
+
/// `\u{2191}in \u{2193}out lines` (TS `lineCounts`): non-empty input
/// lines, output lines from the structured fields (edits show the diff, so
/// their output counts zero).
fn line_counts(card: &ToolCallCard, details: &IpythonDetails, code: &str) -> Option<String> {
- let body = parse_ipython_bash_cell(code).map_or_else(|| code.to_string(), |cell| cell.body);
- let input = body.lines().filter(|line| !line.trim().is_empty()).count();
+ let input = input_line_count(code);
let has_diffs = !details.diffs.is_empty();
let result =
diff --git a/crates/pa-tui/src/tool_card/ipython/tests.rs b/crates/pa-tui/src/tool_card/ipython/tests.rs
index 04380f1b68..4807beec27 100644
--- a/crates/pa-tui/src/tool_card/ipython/tests.rs
+++ b/crates/pa-tui/src/tool_card/ipython/tests.rs
@@ -352,3 +352,61 @@ fn no_output_placeholder() {
"got: {flat:?}"
);
}
+
+#[test]
+fn bash_dominated_cell_renders_as_bash() {
+ let code =
+ "r = await sh(\"\"\"\ncd crates/pa-tui\ncargo test -p pa-tui\n\"\"\")\nprint(r.output)";
+ let card = cell_card(
+ code,
+ json!({
+ "status": "ok",
+ "durationMs": 2,
+ "stdout": "ok\n",
+ "bashCommands": {
+ "first": "\ncd crates/pa-tui\ncargo test -p pa-tui\n",
+ "count": 3,
+ "lines": 4,
+ },
+ }),
+ false,
+ false,
+ );
+ let lines = render(&card, 0, Detail::Overview, &theme(), 100, true);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(
+ text_of(&lines[0]),
+ " \u{2713} bash \u{00b7} cargo test -p pa-tui \u{00b7} +2 more \u{00b7} \u{2191} 5 \u{2193} 1 lines \u{00b7} 2ms"
+ );
+ assert_eq!(
+ bash_dominated_stats(&card),
+ Some(BashCellStats {
+ bash_lines: 4,
+ cell_lines: 5,
+ count: 3,
+ })
+ );
+}
+
+#[test]
+fn bash_minority_cell_stays_python() {
+ let code = "async def sh(cmd):\n return await bash(cmd)\nr = await sh(\"ls\")\nprint(r.pid)";
+ let card = cell_card(
+ code,
+ json!({
+ "status": "ok",
+ "durationMs": 5,
+ "stdout": "0\n",
+ "bashCommands": { "first": "ls", "count": 1, "lines": 1 },
+ }),
+ false,
+ false,
+ );
+ let lines = render(&card, 0, Detail::Overview, &theme(), 100, true);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(
+ text_of(&lines[0]),
+ " \u{2713} python \u{00b7} r = await sh(\"ls\") \u{00b7} \u{2191} 4 \u{2193} 1 lines \u{00b7} 5ms"
+ );
+ assert_eq!(bash_dominated_stats(&card), None);
+}
diff --git a/crates/pa-tui/src/tool_card/ipython_details.rs b/crates/pa-tui/src/tool_card/ipython_details.rs
index e542daca74..30f1b9d867 100644
--- a/crates/pa-tui/src/tool_card/ipython_details.rs
+++ b/crates/pa-tui/src/tool_card/ipython_details.rs
@@ -19,6 +19,7 @@ pub(crate) struct IpythonDetails {
pub(crate) error: Option<IpythonError>,
pub(crate) diffs: Vec<Value>,
pub(crate) sent_agent_messages: Vec<Value>,
+ pub(crate) bash_commands: Option<BashCommands>,
}
pub(crate) struct IpythonError {
@@ -27,6 +28,29 @@ pub(crate) struct IpythonError {
pub(crate) traceback: Vec<String>,
}
+/// The `bashCommands` details field: the first executed `bash()` command,
+/// how many ran, and their summed non-blank line count.
+pub(crate) struct BashCommands {
+ pub(crate) first: String,
+ pub(crate) count: usize,
+ pub(crate) lines: usize,
+}
+
+fn read_bash_commands(value: &Value) -> Option<BashCommands> {
+ let record = value.as_object()?;
+ Some(BashCommands {
+ first: record.get("first")?.as_str()?.to_string(),
+ count: record
+ .get("count")?
+ .as_u64()
+ .and_then(|count| usize::try_from(count).ok())?,
+ lines: record
+ .get("lines")?
+ .as_u64()
+ .and_then(|lines| usize::try_from(lines).ok())?,
+ })
+}
+
pub(crate) fn read_error_details(value: &Value) -> Option<IpythonError> {
let record = value.as_object()?;
let ename = record.get("ename")?.as_str()?.to_string();
@@ -63,6 +87,7 @@ impl IpythonDetails {
error: None,
diffs: Vec::new(),
sent_agent_messages: Vec::new(),
+ bash_commands: None,
};
let Some(record) = details.as_object() else {
return empty;
@@ -107,6 +132,7 @@ impl IpythonDetails {
.and_then(Value::as_array)
.cloned()
.unwrap_or_default(),
+ bash_commands: record.get("bashCommands").and_then(read_bash_commands),
}
}
}
diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.py
index 440dbbc21b..5e17b1ae32 100644
--- a/prime-agent-runtime/src/rlm/bash.py
+++ b/prime-agent-runtime/src/rlm/bash.py
@@ -46,6 +46,9 @@ _COMPLETION_SUFFIX = b"\x1f"
_CANCEL_TERM_GRACE = 0.5
_CANCEL_KILL_WAIT = 2.0
_COMPLETION_NOTICE_COMMAND_CAP = 1000
+# Display MIME the host aggregates into a per-cell summary of the bash()
+# commands the cell ran (first capped command, count, line total).
+_BASH_COMMAND_MIME = "application/vnd.prime-agent.bash-command+json"
_ASYNCIO_WRAPPER_CALLBACKS = {
("asyncio.tasks", "gather.<locals>._done_callback"),
("asyncio.tasks", "shield.<locals>._inner_done_callback"),
@@ -82,6 +85,12 @@ def _consume_notice_task(task: asyncio.Task[None]) -> None:
task.exception()
+def _capped(command: str) -> str:
+ if len(command) > _COMPLETION_NOTICE_COMMAND_CAP:
+ return command[:_COMPLETION_NOTICE_COMMAND_CAP] + "\n... [command truncated]"
+ return command
+
+
def _completion_reaches(
start: asyncio.Future[Any], targets: tuple[asyncio.Future[Any], ...]
) -> bool:
@@ -717,9 +726,7 @@ class BashHandle:
await cell_finished.wait()
if self._awaited_by_creating_cell or self._result_consumed or not repl.is_active():
return
- command = self.command
- if len(command) > _COMPLETION_NOTICE_COMMAND_CAP:
- command = command[:_COMPLETION_NOTICE_COMMAND_CAP] + "\n... [command truncated]"
+ command = _capped(self.command)
reply = await repl.host_request(
{
"type": "bash.completed",
@@ -969,7 +976,18 @@ def bash(command: str) -> BashHandle:
if not isinstance(command, str) or not command:
raise TypeError("command must be a non-empty str")
_install_shutdown_hook()
- return BashHandle(command)
+ handle = BashHandle(command)
+ from . import repl
+
+ repl.emit(
+ {
+ _BASH_COMMAND_MIME: {
+ "command": _capped(command),
+ "lines": sum(1 for line in command.splitlines() if line.strip()),
+ }
+ }
+ )
+ return handle
def _shell() -> str: