From 1a78a228e0d023d844d250e5155f964c4614b9f3 Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Mon, 7 Sep 2026 20:33:24 -0400 Subject: [PATCH 1/7] feat(adapter): add pi coding agent event support - new PiAdapter parses session-start/end, user-prompt-submit, stop, and activity-log events bridged from pi's extension API, normalizing pi's lowercase tool names/keys into the existing canonical vocabulary - wire PI_AGENT/AgentType::Pi through resolve_adapter, tmux types, and the sidebar's agent color theme (@sidebar_color_agent_pi) - treat pi like Codex/OpenCode for stale-pane cleanup, since pi's session_shutdown extension event isn't guaranteed to fire on a hard kill or pane close --- src/adapter/mod.rs | 1 + src/adapter/pi.rs | 298 +++++++++++++++++++++++++++++++++++++++++++ src/event/adapter.rs | 21 ++- src/tmux.rs | 26 ++-- src/tmux/options.rs | 1 + src/tmux/query.rs | 33 +++-- src/tmux/types.rs | 7 + src/ui/colors.rs | 5 + 8 files changed, 366 insertions(+), 26 deletions(-) create mode 100644 src/adapter/pi.rs diff --git a/src/adapter/mod.rs b/src/adapter/mod.rs index c9ec1385..45f5a5e0 100644 --- a/src/adapter/mod.rs +++ b/src/adapter/mod.rs @@ -1,6 +1,7 @@ pub mod claude; pub mod codex; pub mod opencode; +pub mod pi; use crate::event::AgentEventKind; diff --git a/src/adapter/pi.rs b/src/adapter/pi.rs new file mode 100644 index 00000000..0b1e9b5e --- /dev/null +++ b/src/adapter/pi.rs @@ -0,0 +1,298 @@ +use serde_json::{Map, Value}; + +use crate::event::{AgentEvent, EventAdapter}; +use crate::tmux::PI_AGENT; +use crate::tool_name::CanonicalTool; + +use super::{json_str, json_value_or_null, optional_str}; + +/// Adapter for the pi coding agent (`@earendil-works/pi-coding-agent`). +/// +/// Unlike Claude Code and Codex, pi has no native hooks-JSON config — +/// events are bridged from a pi extension (`.pi/extensions/tmux-agent-sidebar.ts`) +/// that listens on pi's extension event bus and shells out to `hook.sh`, +/// the same fire-and-forget pattern OpenCode's plugin bridge uses. See +/// `adapter/opencode.rs` for the sibling implementation. +/// +/// pi has no native permission-mode or tool-approval concept exposed to +/// extensions, so (like OpenCode) `permission_mode` is always empty and +/// there is no `PermissionDenied`/worktree support. +pub struct PiAdapter; + +/// pi's built-in tools are lowercase (`bash`, `read`, `write`, `edit`, ...) +/// and file tools key their target path as `path` rather than the +/// Claude-style `file_path` the label extractor in `src/cli/label.rs` +/// expects. Normalise here so the activity log and its strategy table +/// share one vocabulary across agents. +/// +/// Only tools whose input schema is verified against pi's documented +/// extension API (`docs/extensions.md`) are mapped; anything else passes +/// through unmapped and simply won't get a label — the same trade-off +/// Codex's Bash-only `PostToolUse` makes. +fn normalize_tool_name(raw: &str) -> String { + let canonical = match raw { + "bash" => CanonicalTool::Bash, + "read" => CanonicalTool::Read, + "write" => CanonicalTool::Write, + "edit" => CanonicalTool::Edit, + "powershell" => CanonicalTool::PowerShell, + other => return other.to_string(), + }; + canonical.as_str().to_string() +} + +/// Translate pi's `path` tool argument into the `file_path` key the label +/// extractor expects for Read/Write/Edit. Keys are added alongside the +/// originals rather than replacing them so downstream consumers that want +/// the raw payload still see it. +fn normalize_tool_input(tool_name: &str, input: Value) -> Value { + let Value::Object(mut map) = input else { + return input; + }; + let rewrites: &[(&str, &str)] = match tool_name { + "Read" | "Write" | "Edit" => &[("path", "file_path")], + _ => &[], + }; + copy_keys(&mut map, rewrites); + Value::Object(map) +} + +fn copy_keys(map: &mut Map, pairs: &[(&str, &str)]) { + for (src, dst) in pairs { + if map.contains_key(*dst) { + continue; + } + if let Some(value) = map.get(*src).cloned() { + map.insert((*dst).to_string(), value); + } + } +} + +impl EventAdapter for PiAdapter { + fn parse(&self, event_name: &str, input: &Value) -> Option { + match event_name { + "session-start" => Some(AgentEvent::SessionStart { + agent: PI_AGENT.into(), + cwd: json_str(input, "cwd").into(), + permission_mode: String::new(), + source: json_str(input, "source").into(), + worktree: None, + agent_id: None, + session_id: optional_str(input, "session_id"), + }), + "session-end" => Some(AgentEvent::SessionEnd { + end_reason: json_str(input, "end_reason").into(), + }), + "user-prompt-submit" => Some(AgentEvent::UserPromptSubmit { + agent: PI_AGENT.into(), + cwd: json_str(input, "cwd").into(), + permission_mode: String::new(), + prompt: json_str(input, "prompt").into(), + worktree: None, + agent_id: None, + session_id: optional_str(input, "session_id"), + }), + "stop" => Some(AgentEvent::Stop { + agent: PI_AGENT.into(), + cwd: json_str(input, "cwd").into(), + permission_mode: String::new(), + last_message: json_str(input, "last_message").into(), + response: None, + worktree: None, + agent_id: None, + session_id: optional_str(input, "session_id"), + }), + "activity-log" => { + let raw_name = json_str(input, "tool_name"); + if raw_name.is_empty() { + return None; + } + let tool_name = normalize_tool_name(raw_name); + let tool_input = + normalize_tool_input(&tool_name, json_value_or_null(input, "tool_input")); + Some(AgentEvent::ActivityLog { + tool_name, + tool_input, + tool_response: json_value_or_null(input, "tool_response"), + }) + } + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn session_start() { + let adapter = PiAdapter; + let event = adapter + .parse( + "session-start", + &json!({"cwd": "/tmp", "session_id": "ses-1", "source": "resume"}), + ) + .unwrap(); + assert_eq!( + event, + AgentEvent::SessionStart { + agent: PI_AGENT.into(), + cwd: "/tmp".into(), + permission_mode: "".into(), + source: "resume".into(), + worktree: None, + agent_id: None, + session_id: Some("ses-1".into()), + } + ); + } + + #[test] + fn session_end() { + let adapter = PiAdapter; + let event = adapter + .parse("session-end", &json!({"end_reason": "quit"})) + .unwrap(); + assert_eq!( + event, + AgentEvent::SessionEnd { + end_reason: "quit".into() + } + ); + } + + #[test] + fn user_prompt_submit() { + let adapter = PiAdapter; + let event = adapter + .parse( + "user-prompt-submit", + &json!({"cwd": "/tmp", "prompt": "hello"}), + ) + .unwrap(); + assert_eq!( + event, + AgentEvent::UserPromptSubmit { + agent: PI_AGENT.into(), + cwd: "/tmp".into(), + permission_mode: "".into(), + prompt: "hello".into(), + worktree: None, + agent_id: None, + session_id: None, + } + ); + } + + #[test] + fn stop_has_no_response() { + let adapter = PiAdapter; + let event = adapter + .parse("stop", &json!({"last_message": "done"})) + .unwrap(); + match event { + AgentEvent::Stop { + last_message, + response, + .. + } => { + assert_eq!(last_message, "done"); + assert!(response.is_none()); + } + other => panic!("expected Stop, got {:?}", other), + } + } + + #[test] + fn activity_log_normalizes_lowercase_bash() { + let adapter = PiAdapter; + let event = adapter + .parse( + "activity-log", + &json!({ + "tool_name": "bash", + "tool_input": {"command": "ls"}, + "tool_response": {"content": [], "isError": false} + }), + ) + .unwrap(); + match event { + AgentEvent::ActivityLog { + tool_name, + tool_input, + .. + } => { + assert_eq!(tool_name, "Bash"); + assert_eq!( + tool_input.get("command").and_then(|v| v.as_str()), + Some("ls") + ); + } + other => panic!("expected ActivityLog, got {:?}", other), + } + } + + #[test] + fn activity_log_rewrites_path_to_file_path_for_read() { + let adapter = PiAdapter; + let event = adapter + .parse( + "activity-log", + &json!({ + "tool_name": "read", + "tool_input": {"path": "/tmp/foo.rs"}, + "tool_response": {} + }), + ) + .unwrap(); + match event { + AgentEvent::ActivityLog { + tool_name, + tool_input, + .. + } => { + assert_eq!(tool_name, "Read"); + assert_eq!( + tool_input.get("file_path").and_then(|v| v.as_str()), + Some("/tmp/foo.rs") + ); + // Original key is preserved alongside the rewritten one. + assert_eq!( + tool_input.get("path").and_then(|v| v.as_str()), + Some("/tmp/foo.rs") + ); + } + other => panic!("expected ActivityLog, got {:?}", other), + } + } + + #[test] + fn activity_log_missing_tool_name_returns_none() { + let adapter = PiAdapter; + assert!(adapter.parse("activity-log", &json!({})).is_none()); + } + + #[test] + fn activity_log_passes_through_unmapped_tool_names() { + let adapter = PiAdapter; + let event = adapter + .parse( + "activity-log", + &json!({"tool_name": "grep", "tool_input": {"pattern": "fn main"}}), + ) + .unwrap(); + match event { + AgentEvent::ActivityLog { tool_name, .. } => assert_eq!(tool_name, "grep"), + other => panic!("expected ActivityLog, got {:?}", other), + } + } + + #[test] + fn unknown_event_returns_none() { + let adapter = PiAdapter; + assert!(adapter.parse("permission-denied", &json!({})).is_none()); + assert!(adapter.parse("cwd-changed", &json!({})).is_none()); + } +} diff --git a/src/event/adapter.rs b/src/event/adapter.rs index 6c06f25f..09b755bd 100644 --- a/src/event/adapter.rs +++ b/src/event/adapter.rs @@ -2,7 +2,7 @@ use serde_json::Value; use super::AgentEvent; use crate::adapter; -use crate::tmux::{CLAUDE_AGENT, CODEX_AGENT, OPENCODE_AGENT}; +use crate::tmux::{CLAUDE_AGENT, CODEX_AGENT, OPENCODE_AGENT, PI_AGENT}; /// Adapter that converts external agent events into internal `AgentEvent`. pub trait EventAdapter { @@ -14,6 +14,7 @@ pub fn resolve_adapter(agent_name: &str) -> Option> { CLAUDE_AGENT => Some(Box::new(adapter::claude::ClaudeAdapter)), CODEX_AGENT => Some(Box::new(adapter::codex::CodexAdapter)), OPENCODE_AGENT => Some(Box::new(adapter::opencode::OpenCodeAdapter)), + PI_AGENT => Some(Box::new(adapter::pi::PiAdapter)), _ => None, } } @@ -48,6 +49,12 @@ mod tests { assert!(adapter.is_some()); } + #[test] + fn resolve_pi() { + let adapter = resolve_adapter("pi"); + assert!(adapter.is_some()); + } + #[test] fn resolve_unknown_returns_none() { assert!(resolve_adapter("gemini").is_none()); @@ -92,6 +99,18 @@ mod tests { } } + #[test] + fn pi_adapter_sets_agent_pi() { + let adapter = resolve_adapter("pi").unwrap(); + let event = adapter + .parse("user-prompt-submit", &json!({"prompt": "hi"})) + .unwrap(); + match event { + AgentEvent::UserPromptSubmit { agent, .. } => assert_eq!(agent, "pi"), + other => panic!("expected UserPromptSubmit, got {:?}", other), + } + } + #[test] fn claude_stop_has_no_response() { let adapter = resolve_adapter("claude").unwrap(); diff --git a/src/tmux.rs b/src/tmux.rs index 28f0040d..6c5e0341 100644 --- a/src/tmux.rs +++ b/src/tmux.rs @@ -16,17 +16,17 @@ pub use options::{ PANE_STARTED_AT, PANE_STATUS, PANE_SUBAGENTS, PANE_WAIT_REASON, PANE_WORKTREE_BRANCH, PANE_WORKTREE_NAME, SIDEBAR_BOTTOM_HEIGHT, SIDEBAR_COLOR_ACCENT, SIDEBAR_COLOR_ACTIVITY_TIMESTAMP, SIDEBAR_COLOR_AGENT_CLAUDE, SIDEBAR_COLOR_AGENT_CODEX, - SIDEBAR_COLOR_AGENT_OPENCODE, SIDEBAR_COLOR_ALL, SIDEBAR_COLOR_BORDER, SIDEBAR_COLOR_BRANCH, - SIDEBAR_COLOR_COMMIT_HASH, SIDEBAR_COLOR_DIFF_ADDED, SIDEBAR_COLOR_DIFF_DELETED, - SIDEBAR_COLOR_ERROR, SIDEBAR_COLOR_FILE_CHANGE, SIDEBAR_COLOR_FILTER_INACTIVE, - SIDEBAR_COLOR_IDLE, SIDEBAR_COLOR_PET_BODY, SIDEBAR_COLOR_PET_EYE, SIDEBAR_COLOR_PORT, - SIDEBAR_COLOR_PR_LINK, SIDEBAR_COLOR_RESPONSE_ARROW, SIDEBAR_COLOR_RUNNING, - SIDEBAR_COLOR_SECTION_TITLE, SIDEBAR_COLOR_SELECTION, SIDEBAR_COLOR_SESSION, - SIDEBAR_COLOR_SUBAGENT, SIDEBAR_COLOR_TASK_PROGRESS, SIDEBAR_COLOR_TEXT_ACTIVE, - SIDEBAR_COLOR_TEXT_INACTIVE, SIDEBAR_COLOR_TEXT_MUTED, SIDEBAR_COLOR_WAIT_REASON, - SIDEBAR_COLOR_WAITING, SIDEBAR_CURSOR, SIDEBAR_FILTER, SIDEBAR_ICON_ALL, - SIDEBAR_ICON_BACKGROUND, SIDEBAR_ICON_ERROR, SIDEBAR_ICON_IDLE, SIDEBAR_ICON_RUNNING, - SIDEBAR_ICON_UNKNOWN, SIDEBAR_ICON_WAITING, SIDEBAR_NOTIFICATIONS, + SIDEBAR_COLOR_AGENT_OPENCODE, SIDEBAR_COLOR_AGENT_PI, SIDEBAR_COLOR_ALL, SIDEBAR_COLOR_BORDER, + SIDEBAR_COLOR_BRANCH, SIDEBAR_COLOR_COMMIT_HASH, SIDEBAR_COLOR_DIFF_ADDED, + SIDEBAR_COLOR_DIFF_DELETED, SIDEBAR_COLOR_ERROR, SIDEBAR_COLOR_FILE_CHANGE, + SIDEBAR_COLOR_FILTER_INACTIVE, SIDEBAR_COLOR_IDLE, SIDEBAR_COLOR_PET_BODY, + SIDEBAR_COLOR_PET_EYE, SIDEBAR_COLOR_PORT, SIDEBAR_COLOR_PR_LINK, SIDEBAR_COLOR_RESPONSE_ARROW, + SIDEBAR_COLOR_RUNNING, SIDEBAR_COLOR_SECTION_TITLE, SIDEBAR_COLOR_SELECTION, + SIDEBAR_COLOR_SESSION, SIDEBAR_COLOR_SUBAGENT, SIDEBAR_COLOR_TASK_PROGRESS, + SIDEBAR_COLOR_TEXT_ACTIVE, SIDEBAR_COLOR_TEXT_INACTIVE, SIDEBAR_COLOR_TEXT_MUTED, + SIDEBAR_COLOR_WAIT_REASON, SIDEBAR_COLOR_WAITING, SIDEBAR_CURSOR, SIDEBAR_FILTER, + SIDEBAR_ICON_ALL, SIDEBAR_ICON_BACKGROUND, SIDEBAR_ICON_ERROR, SIDEBAR_ICON_IDLE, + SIDEBAR_ICON_RUNNING, SIDEBAR_ICON_UNKNOWN, SIDEBAR_ICON_WAITING, SIDEBAR_NOTIFICATIONS, SIDEBAR_NOTIFICATIONS_EVENTS, SIDEBAR_PET, SIDEBAR_PID, SIDEBAR_POSITION, SIDEBAR_REPO_FILTER, SIDEBAR_WIDTH, get_all_global_options, get_option, get_pane_option_value, set_pane_option, unset_pane_option, @@ -38,8 +38,8 @@ pub use panes::{ pub use query::query_sessions; pub(crate) use query::query_sessions_with_process_snapshot; pub use types::{ - AgentType, CLAUDE_AGENT, CODEX_AGENT, OPENCODE_AGENT, PaneInfo, PaneStatus, PermissionMode, - SessionInfo, WindowInfo, WorktreeMetadata, + AgentType, CLAUDE_AGENT, CODEX_AGENT, OPENCODE_AGENT, PI_AGENT, PaneInfo, PaneStatus, + PermissionMode, SessionInfo, WindowInfo, WorktreeMetadata, }; #[cfg(test)] diff --git a/src/tmux/options.rs b/src/tmux/options.rs index 617fb295..6b5dc2c0 100644 --- a/src/tmux/options.rs +++ b/src/tmux/options.rs @@ -104,6 +104,7 @@ pub const SIDEBAR_COLOR_FILTER_INACTIVE: &str = "@sidebar_color_filter_inactive" pub const SIDEBAR_COLOR_AGENT_CLAUDE: &str = "@sidebar_color_agent_claude"; pub const SIDEBAR_COLOR_AGENT_CODEX: &str = "@sidebar_color_agent_codex"; pub const SIDEBAR_COLOR_AGENT_OPENCODE: &str = "@sidebar_color_agent_opencode"; +pub const SIDEBAR_COLOR_AGENT_PI: &str = "@sidebar_color_agent_pi"; pub const SIDEBAR_COLOR_PET_BODY: &str = "@sidebar_color_pet_body"; pub const SIDEBAR_COLOR_PET_EYE: &str = "@sidebar_color_pet_eye"; pub const SIDEBAR_COLOR_TEXT_ACTIVE: &str = "@sidebar_color_text_active"; diff --git a/src/tmux/query.rs b/src/tmux/query.rs index ab27d3c5..ef9d6364 100644 --- a/src/tmux/query.rs +++ b/src/tmux/query.rs @@ -267,16 +267,21 @@ fn parse_pane_fields_with_processes( let current_command = parts[pane_line_field::PANE_CURRENT_COMMAND].as_str(); let pane_pid: Option = parts[pane_line_field::PANE_PID].parse().ok(); - // Codex / OpenCode panes can leave stale tmux metadata behind after the - // agent exits and the pane falls back to the user's shell. Neither - // agent exposes a reliable "process exit" hook (Codex has no such - // hook, OpenCode runs under Bun where `process.on("exit")` does not - // fire our handlers), so the Rust polling side must own teardown: - // wipe pane options + activity log the first poll after the agent - // is gone. Subsequent polls short-circuit at the `AgentType::from_label` - // check above once `@pane_agent` has been cleared. Claude is excluded - // because its SessionEnd hook drives cleanup instead. - if matches!(agent, AgentType::Codex | AgentType::OpenCode) && is_shell_command(current_command) + // Codex / OpenCode / pi panes can leave stale tmux metadata behind + // after the agent exits and the pane falls back to the user's shell. + // None of the three expose a reliable "process exit" hook (Codex has + // no such hook, OpenCode runs under Bun where `process.on("exit")` + // does not fire our handlers, and pi's `session_shutdown` extension + // event is not guaranteed to fire on a hard kill/pane close), so the + // Rust polling side must own teardown: wipe pane options + activity + // log the first poll after the agent is gone. Subsequent polls + // short-circuit at the `AgentType::from_label` check above once + // `@pane_agent` has been cleared. Claude is excluded because its + // SessionEnd hook drives cleanup instead. + if matches!( + agent, + AgentType::Codex | AgentType::OpenCode | AgentType::Pi + ) && is_shell_command(current_command) { let agent_still_alive = pane_pid .and_then(|pid| { @@ -444,8 +449,12 @@ fn pane_output_needs_process_snapshot(all_panes_output: &str) -> bool { return false; } let pane_fields = &parts[session_line_field::PANE_LINE_OFFSET..]; - AgentType::from_label(&pane_fields[pane_line_field::AGENT]) - .is_some_and(|agent| matches!(agent, AgentType::Codex | AgentType::OpenCode)) + AgentType::from_label(&pane_fields[pane_line_field::AGENT]).is_some_and(|agent| { + matches!( + agent, + AgentType::Codex | AgentType::OpenCode | AgentType::Pi + ) + }) }) } diff --git a/src/tmux/types.rs b/src/tmux/types.rs index d515c49a..c76c6097 100644 --- a/src/tmux/types.rs +++ b/src/tmux/types.rs @@ -1,6 +1,7 @@ pub const CLAUDE_AGENT: &str = "claude"; pub const CODEX_AGENT: &str = "codex"; pub const OPENCODE_AGENT: &str = "opencode"; +pub const PI_AGENT: &str = "pi"; #[derive(Debug, Clone)] pub struct PaneInfo { @@ -92,6 +93,7 @@ pub enum AgentType { Claude, Codex, OpenCode, + Pi, #[allow(dead_code)] Unknown, } @@ -119,6 +121,7 @@ impl AgentType { CLAUDE_AGENT => Some(Self::Claude), CODEX_AGENT => Some(Self::Codex), OPENCODE_AGENT => Some(Self::OpenCode), + PI_AGENT => Some(Self::Pi), _ => None, } } @@ -128,6 +131,7 @@ impl AgentType { Self::Claude => CLAUDE_AGENT, Self::Codex => CODEX_AGENT, Self::OpenCode => OPENCODE_AGENT, + Self::Pi => PI_AGENT, Self::Unknown => "unknown", } } @@ -200,6 +204,7 @@ mod tests { assert_eq!(AgentType::from_label("claude"), Some(AgentType::Claude)); assert_eq!(AgentType::from_label("codex"), Some(AgentType::Codex)); assert_eq!(AgentType::from_label("opencode"), Some(AgentType::OpenCode)); + assert_eq!(AgentType::from_label("pi"), Some(AgentType::Pi)); assert_eq!(AgentType::from_label("unknown"), None); assert_eq!(AgentType::from_label(""), None); } @@ -209,6 +214,7 @@ mod tests { assert_eq!(AgentType::Claude.label(), "claude"); assert_eq!(AgentType::Codex.label(), "codex"); assert_eq!(AgentType::OpenCode.label(), "opencode"); + assert_eq!(AgentType::Pi.label(), "pi"); assert_eq!(AgentType::Unknown.label(), "unknown"); } @@ -217,6 +223,7 @@ mod tests { assert_eq!(AgentType::Claude.as_str(), CLAUDE_AGENT); assert_eq!(AgentType::Codex.as_str(), CODEX_AGENT); assert_eq!(AgentType::OpenCode.as_str(), OPENCODE_AGENT); + assert_eq!(AgentType::Pi.as_str(), PI_AGENT); } #[test] diff --git a/src/ui/colors.rs b/src/ui/colors.rs index 956990c5..c41a3fa9 100644 --- a/src/ui/colors.rs +++ b/src/ui/colors.rs @@ -23,6 +23,7 @@ pub struct ColorTheme { pub agent_claude: Color, pub agent_codex: Color, pub agent_opencode: Color, + pub agent_pi: Color, pub pet_body: Color, pub pet_eye: Color, pub text_active: Color, @@ -63,6 +64,7 @@ impl Default for ColorTheme { agent_claude: Color::Indexed(174), agent_codex: Color::Indexed(141), agent_opencode: Color::Indexed(117), + agent_pi: Color::Indexed(215), pet_body: Color::Indexed(208), pet_eye: Color::Indexed(114), text_active: Color::Indexed(255), @@ -119,6 +121,7 @@ impl ColorTheme { theme.agent_claude = read(tmux::SIDEBAR_COLOR_AGENT_CLAUDE, theme.agent_claude); theme.agent_codex = read(tmux::SIDEBAR_COLOR_AGENT_CODEX, theme.agent_codex); theme.agent_opencode = read(tmux::SIDEBAR_COLOR_AGENT_OPENCODE, theme.agent_opencode); + theme.agent_pi = read(tmux::SIDEBAR_COLOR_AGENT_PI, theme.agent_pi); theme.pet_body = read(tmux::SIDEBAR_COLOR_PET_BODY, theme.pet_body); theme.pet_eye = read(tmux::SIDEBAR_COLOR_PET_EYE, theme.pet_eye); theme.text_active = read(tmux::SIDEBAR_COLOR_TEXT_ACTIVE, theme.text_active); @@ -165,6 +168,7 @@ impl ColorTheme { AgentType::Claude => self.agent_claude, AgentType::Codex => self.agent_codex, AgentType::OpenCode => self.agent_opencode, + AgentType::Pi => self.agent_pi, AgentType::Unknown => self.status_unknown, } } @@ -243,6 +247,7 @@ mod tests { assert_eq!(theme.agent_color(&AgentType::Claude), Color::Indexed(174)); assert_eq!(theme.agent_color(&AgentType::Codex), Color::Indexed(141)); assert_eq!(theme.agent_color(&AgentType::OpenCode), Color::Indexed(117)); + assert_eq!(theme.agent_color(&AgentType::Pi), Color::Indexed(215)); assert_eq!(theme.agent_color(&AgentType::Unknown), theme.status_unknown); } From 2de3405b986d4180e9fabdcac0faff3279631c27 Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Mon, 7 Sep 2026 20:33:29 -0400 Subject: [PATCH 2/7] feat(worktree): add pi to the agent spawn list - add "pi" to worktree::AGENTS with a single default mode (PI_MODES), same as OpenCode, since pi has no permission-mode concept - lets the spawn modal (n) launch a fresh pi pane + worktree --- src/worktree.rs | 4 ++-- src/worktree/config.rs | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/worktree.rs b/src/worktree.rs index fa037d38..2418df66 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -10,8 +10,8 @@ mod slug; pub use config::{ AGENT_OPTION, AGENTS, BRANCH_PREFIX_OPTION, CLAUDE_MODES, CODEX_MODES, DEFAULT_AGENT, - DEFAULT_BRANCH_PREFIX, DEFAULT_MODE, DEFAULT_WORKTREE_DIR, OPENCODE_MODES, RemoveMode, - WORKTREE_DIR_OPTION, agent_command, modes_for, + DEFAULT_BRANCH_PREFIX, DEFAULT_MODE, DEFAULT_WORKTREE_DIR, OPENCODE_MODES, PI_MODES, + RemoveMode, WORKTREE_DIR_OPTION, agent_command, modes_for, }; pub use flow::{SpawnRequest, remove, spawn}; pub use markers::{ diff --git a/src/worktree/config.rs b/src/worktree/config.rs index 4779ac32..0750cca7 100644 --- a/src/worktree/config.rs +++ b/src/worktree/config.rs @@ -7,7 +7,7 @@ pub const AGENT_OPTION: &str = "@agent-sidebar-default-agent"; pub const BRANCH_PREFIX_OPTION: &str = "@agent-sidebar-branch-prefix"; pub const WORKTREE_DIR_OPTION: &str = "@agent-sidebar-worktree-dir"; -pub const AGENTS: &[&str] = &["claude", "codex", "opencode"]; +pub const AGENTS: &[&str] = &["claude", "codex", "opencode", "pi"]; pub const CLAUDE_MODES: &[&str] = &[ "default", "plan", @@ -17,11 +17,13 @@ pub const CLAUDE_MODES: &[&str] = &[ ]; pub const CODEX_MODES: &[&str] = &["default", "auto", "bypassPermissions"]; pub const OPENCODE_MODES: &[&str] = &["default"]; +pub const PI_MODES: &[&str] = &["default"]; pub fn modes_for(agent: &str) -> &'static [&'static str] { match agent { "codex" => CODEX_MODES, "opencode" => OPENCODE_MODES, + "pi" => PI_MODES, _ => CLAUDE_MODES, } } @@ -44,6 +46,7 @@ pub fn agent_command(agent: &str, mode: &str) -> String { ("codex", "bypassPermissions") => "codex --dangerously-bypass-approvals-and-sandbox".into(), ("codex", _) => "codex".into(), ("opencode", _) => "opencode".into(), + ("pi", _) => "pi".into(), (a, _) => a.to_string(), } } @@ -116,6 +119,20 @@ mod tests { assert_eq!(agent_command("opencode", ""), "opencode"); } + #[test] + fn modes_for_pi_returns_pi_modes() { + assert_eq!(modes_for("pi"), PI_MODES); + } + + #[test] + fn agent_command_pi_ignores_mode() { + // pi has no permission-mode concept; every variant collapses to + // the bare binary, same as OpenCode. + assert_eq!(agent_command("pi", "default"), "pi"); + assert_eq!(agent_command("pi", "plan"), "pi"); + assert_eq!(agent_command("pi", ""), "pi"); + } + #[test] fn agent_command_unknown_agent_passes_through() { assert_eq!(agent_command("gemini", "default"), "gemini"); From 4b942a8cc5fbe4238a2202dfcba3642b401fffb8 Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Mon, 7 Sep 2026 20:33:35 -0400 Subject: [PATCH 3/7] feat(pi): ship extension bridge for hook events - .pi/extensions/tmux-agent-sidebar.ts listens on pi's extension event bus (session_start/session_shutdown/before_agent_start/agent_end+ agent_settled/tool_result) and fire-and-forget spawns hook.sh pi , mirroring the OpenCode plugin bridge - ships as .ts (not .js) because pi only auto-discovers *.ts under ~/.pi/agent/extensions/ and .pi/extensions/ --- .pi/extensions/tmux-agent-sidebar.ts | 152 +++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 .pi/extensions/tmux-agent-sidebar.ts diff --git a/.pi/extensions/tmux-agent-sidebar.ts b/.pi/extensions/tmux-agent-sidebar.ts new file mode 100644 index 00000000..7e1383f8 --- /dev/null +++ b/.pi/extensions/tmux-agent-sidebar.ts @@ -0,0 +1,152 @@ +// tmux-agent-sidebar bridge for the pi coding agent. +// +// pi has no native hooks-JSON config like Claude Code / Codex, so this +// extension listens on pi's own extension event bus +// (https://github.com/earendil-works/pi-coding-agent — see docs/extensions.md) +// and shells out to hook.sh, the same fire-and-forget pattern used by +// OpenCode's plugin bridge (.opencode/plugins/tmux-agent-sidebar.js). +// +// Install: symlink this file (not the directory) into pi's global +// extensions directory so it auto-loads for every project without +// needing per-project trust: +// +// mkdir -p ~/.pi/agent/extensions +// ln -sf ~/.tmux/plugins/tmux-agent-sidebar/.pi/extensions/tmux-agent-sidebar.ts \ +// ~/.pi/agent/extensions/tmux-agent-sidebar.ts +// +// Extensions are plain untyped JS/TS run through jiti, so this file makes +// no use of pi's ExtensionAPI types — it only needs `.ts` naming to match +// pi's auto-discovery glob (`~/.pi/agent/extensions/*.ts`, `.pi/extensions/*.ts`). +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const resolveHookScript = () => { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let i = 0; i < 4; i += 1) { + const candidate = resolve(dir, "hook.sh"); + if (existsSync(candidate)) { + return candidate; + } + const parent = dirname(dir); + if (parent === dir) { + break; + } + dir = parent; + } + return null; +}; + +const HOOK_COMMAND = (() => { + const hookScript = resolveHookScript(); + return hookScript + ? { cmd: "bash", prefix: [hookScript, "pi"] } + : { cmd: "tmux-agent-sidebar", prefix: ["hook", "pi"] }; +})(); + +// Fire-and-forget: pi does not await extension event handlers before +// continuing its own event loop, so serializing subprocess exits would +// only add latency without backpressure. +const hook = (eventName, payload) => { + try { + const child = spawn(HOOK_COMMAND.cmd, [...HOOK_COMMAND.prefix, eventName], { + stdio: ["pipe", "ignore", "ignore"], + }); + child.on("error", () => {}); + child.stdin.on("error", () => {}); + child.stdin.end(JSON.stringify(payload)); + } catch { + // pi should keep running even if the bridge is missing or the + // sidebar binary is unavailable. + } +}; + +const getSessionId = (ctx) => { + try { + return ctx?.sessionManager?.getSessionId?.() ?? ""; + } catch { + return ""; + } +}; + +// "resume" and "fork" both continue a prior conversation from the user's +// point of view; every other session_start reason ("startup", "reload", +// "new") is treated as a fresh session. +const mapSource = (reason) => (reason === "resume" || reason === "fork" ? "resume" : ""); + +const extractAssistantText = (messages) => { + if (!Array.isArray(messages)) return ""; + for (let i = messages.length - 1; i >= 0; i -= 1) { + const message = messages[i]; + if (!message || message.role !== "assistant") continue; + const content = Array.isArray(message.content) ? message.content : []; + const chunks = content + .filter((part) => part && part.type === "text" && typeof part.text === "string") + .map((part) => part.text); + if (chunks.length > 0) return chunks.join("\n"); + } + return ""; +}; + +export default function (pi) { + // Last assistant reply seen this run, flushed into the `stop` hook once + // pi truly settles. `agent_end` can still be followed by an automatic + // retry/compaction retry/queued follow-up, so the actual "done" signal + // is `agent_settled`, not `agent_end`. + let lastAssistantText = ""; + + pi.on("session_start", async (event, ctx) => { + hook("session-start", { + cwd: ctx.cwd, + session_id: getSessionId(ctx), + source: mapSource(event.reason), + }); + }); + + pi.on("session_shutdown", async (event, ctx) => { + hook("session-end", { end_reason: event.reason ?? "" }); + }); + + pi.on("before_agent_start", async (event, ctx) => { + hook("user-prompt-submit", { + cwd: ctx.cwd, + session_id: getSessionId(ctx), + prompt: event.prompt ?? "", + }); + }); + + pi.on("agent_end", async (event) => { + const text = extractAssistantText(event.messages); + if (text) { + lastAssistantText = text; + } + }); + + pi.on("agent_settled", async (_event, ctx) => { + hook("stop", { + cwd: ctx.cwd, + session_id: getSessionId(ctx), + last_message: lastAssistantText, + }); + lastAssistantText = ""; + }); + + // `tool_result` (rather than `tool_execution_end`) is the one lifecycle + // event that carries both the tool's input args and its finalized + // result in the same payload. + pi.on("tool_result", async (event, ctx) => { + if (!event?.toolName) return; + hook("activity-log", { + cwd: ctx.cwd, + session_id: getSessionId(ctx), + tool_name: event.toolName, + tool_input: event.input ?? {}, + tool_response: { + content: event.content ?? [], + details: event.details ?? {}, + isError: Boolean(event.isError), + }, + }); + }); +} From f5447886f38f3d3a791b52f149025b15da06f86e Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Mon, 7 Sep 2026 20:33:41 -0400 Subject: [PATCH 4/7] docs: document pi agent support - README/AGENTS.md/state-management.md: mention pi (and fix stale OpenCode wording) alongside the other supported agents - website: new agents/pi.md + getting-started/pi.md pages, sidebar nav entries, and pi rows/notes added to the agent comparison matrix, activity-log, notifications, worktree, tmux-options, and scripting docs - add the pi brand icon (website/public/brands/pi.svg) and wire it into the homepage hero tagline alongside Claude Code/Codex/OpenCode --- AGENTS.md | 4 +- README.md | 16 +++++-- docs/state-management.md | 4 +- website/astro.config.mjs | 2 + website/public/brands/pi.svg | 20 +++++++++ website/src/content/docs/agents/index.md | 36 ++++++++-------- website/src/content/docs/agents/pi.md | 42 +++++++++++++++++++ .../content/docs/features/activity-log.mdx | 1 + .../content/docs/features/notifications.mdx | 2 +- .../src/content/docs/features/worktree.mdx | 2 +- .../docs/getting-started/installation.md | 1 + .../src/content/docs/getting-started/pi.md | 36 ++++++++++++++++ website/src/content/docs/index.mdx | 10 ++--- .../src/content/docs/reference/scripting.md | 4 +- .../content/docs/reference/tmux-options.md | 3 +- 15 files changed, 147 insertions(+), 36 deletions(-) create mode 100644 website/public/brands/pi.svg create mode 100644 website/src/content/docs/agents/pi.md create mode 100644 website/src/content/docs/getting-started/pi.md diff --git a/AGENTS.md b/AGENTS.md index d3f0ac73..ef858953 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ ## Project Overview -A tmux sidebar TUI (built with Ratatui + Crossterm) that monitors AI coding agents (Claude Code, Codex) across all tmux sessions/windows/panes in real-time. Distributed as a single binary via tmux plugin managers. +A tmux sidebar TUI (built with Ratatui + Crossterm) that monitors AI coding agents (Claude Code, Codex, OpenCode, pi) across all tmux sessions/windows/panes in real-time. Distributed as a single binary via tmux plugin managers. ## Build & Development Commands @@ -53,7 +53,7 @@ TUI event loop (app::run) → AppState::sync_global_state() - **`state.rs` + `state/`** — `AppState` central struct plus topical submodules (`activity`, `session`, `focus`, `scroll`, `pane_runtime`, `layout`, `popup`, `notices`, `timers`, `filter`, `global`, `refresh`, `tab`). All UI is computed from this state. - **`app.rs` + `app/`** — TUI orchestration: `setup` (prime `AppState`), `workers` (background git/session/version threads), `input` (keyboard/mouse handling), `render` (per-frame render entry). Split out from `main.rs` so the binary entry point only handles CLI dispatch, signal wiring, and TUI session setup. - **`tmux.rs`** — Tmux integration: queries all panes via single `list-panes -a` call, defines `PaneInfo`/`PaneStatus`/`AgentType`/`PermissionMode`/`WorktreeMetadata`. -- **`adapter/`** — Per-agent hook adapters (`claude`, `codex`, `opencode`). Each exposes a `HOOK_REGISTRATIONS` table binding upstream hook triggers to an internal `AgentEventKind`, plus a `parse()` that maps raw JSON payloads into `AgentEvent`. Single source of truth consumed by the setup wizard, README snippets, and tests. +- **`adapter/`** — Per-agent hook adapters (`claude`, `codex`, `opencode`, `pi`). Each exposes a `parse()` that maps raw JSON payloads into `AgentEvent`. Claude and Codex additionally expose a `HOOK_REGISTRATIONS` table binding upstream hook triggers to an internal `AgentEventKind` — the single source of truth consumed by the `setup` wizard, README snippets, and drift tests, since both have native hooks-JSON config. OpenCode and pi have no such config; they're driven by a bundled plugin/extension bridge (`.opencode/plugins/`, `.pi/extensions/`) instead, so their adapters only implement `parse()`. - **`event.rs` + `event/`** — Internal event layer: `AgentEvent` (pre-extracted fields; handlers never touch raw JSON or agent names), `AgentEventKind` (compile-time enum for hook kinds), `EventAdapter` trait + `resolve_adapter`. - **`cli/hook.rs` + `cli/hook/`** — Receives real-time status updates from agent hooks; dispatch in `hook.rs`, with submodules `context` (shared helpers + `AgentContext`), `handlers` (per-event `on_*` handlers), `activity` (activity log writing), `notifications` (desktop notification helpers). - **`git.rs`** — Git operations (branch, ahead/behind, PR numbers via `gh` CLI, diff stats). Runs in a background polling thread. diff --git a/README.md b/README.md index d549b19b..0d23ba48 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

tmux-agent-sidebar

-

One tmux sidebar that tracks every Claude Code, Codex, and OpenCode pane across every session and window. See status, background shells, prompts, Git state, activity, and worktrees without switching windows.

+

One tmux sidebar that tracks every Claude Code, Codex, OpenCode, and pi pane across every session and window. See status, background shells, prompts, Git state, activity, and worktrees without switching windows.

tmux-agent-sidebar hero

@@ -13,7 +13,7 @@ ## Features - **Every pane, one view** - — tracks Claude Code, Codex, and OpenCode panes across all tmux sessions and windows + — tracks Claude Code, Codex, OpenCode, and pi panes across all tmux sessions and windows - **Live metadata** — prompts, tool calls, response previews, background shell state, wait reasons, task progress, and subagent trees refresh as the agents work - **Worktrees, included** @@ -21,7 +21,7 @@ - **Desktop notifications** — native alerts when an agent finishes, needs permission, or errors out -OpenCode uses a small local plugin bridge instead of per-event hook config. The plugin lives at `.opencode/plugins/tmux-agent-sidebar.js` and can be symlinked as a single file into `~/.config/opencode/plugins/` so it coexists with any existing plugins. +OpenCode and pi both use a small local plugin/extension bridge instead of per-event hook config, since neither exposes a hooks-JSON config the way Claude Code and Codex do. The OpenCode plugin lives at `.opencode/plugins/tmux-agent-sidebar.js` (symlink as a single file into `~/.config/opencode/plugins/`); the pi extension lives at `.pi/extensions/tmux-agent-sidebar.ts` (symlink as a single file into `~/.pi/agent/extensions/`). ## Requirements @@ -59,7 +59,15 @@ Reload tmux (`tmux source ~/.tmux.conf`), then press `prefix + I`. The install w ~/.config/opencode/plugins/tmux-agent-sidebar.js ``` -Full walkthroughs: [Claude Code setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/claude-code/) · [Codex setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/codex/) · [OpenCode setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/opencode/) +- **pi** — symlink the extension into pi's global extensions directory so it loads for every project without a per-project trust prompt: + + ```sh + mkdir -p ~/.pi/agent/extensions + ln -sf ~/.tmux/plugins/tmux-agent-sidebar/.pi/extensions/tmux-agent-sidebar.ts \ + ~/.pi/agent/extensions/tmux-agent-sidebar.ts + ``` + +Full walkthroughs: [Claude Code setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/claude-code/) · [Codex setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/codex/) · [OpenCode setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/opencode/) · [pi setup](https://hiroppy.github.io/tmux-agent-sidebar/getting-started/pi/) ### 3. Toggle the sidebar diff --git a/docs/state-management.md b/docs/state-management.md index c9f273d4..51b5316a 100644 --- a/docs/state-management.md +++ b/docs/state-management.md @@ -33,7 +33,7 @@ Pane options written to tmux: | Tmux Option | Update Trigger | Description | |-------------|----------------|-------------| -| `@pane_agent` | SessionStart | Agent type ("claude" / "codex" / "opencode") | +| `@pane_agent` | SessionStart | Agent type ("claude" / "codex" / "opencode" / "pi") | | `@pane_status` | Every event | Status ("running" / "background" / "waiting" / "idle" / "error") | | `@pane_cwd` | SessionStart, CwdChanged | Working directory | | `@pane_permission_mode` | SessionStart, hook event | Permission mode | @@ -192,7 +192,7 @@ enum StatusFilter { All, Running, Background, Waiting, Idle, Error } enum RepoFilter { All, Repo(String) } enum BottomTab { Activity, GitStatus } enum PaneStatus { Running, Background, Waiting, Idle, Error, Unknown } -enum AgentType { Claude, Codex, OpenCode, Unknown } +enum AgentType { Claude, Codex, OpenCode, Pi, Unknown } enum PermissionMode { Default, Plan, AcceptEdits, Auto, DontAsk, BypassPermissions, Defer } /// At-most-one popup state. The enum encodes both which popup is open diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 33b79ff3..95eb57ca 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -100,6 +100,7 @@ export default defineConfig({ { slug: 'getting-started/claude-code' }, { slug: 'getting-started/codex' }, { slug: 'getting-started/opencode' }, + { slug: 'getting-started/pi' }, ], }, { @@ -120,6 +121,7 @@ export default defineConfig({ { slug: 'agents/claude-code' }, { slug: 'agents/codex' }, { slug: 'agents/opencode' }, + { slug: 'agents/pi' }, ], }, { diff --git a/website/public/brands/pi.svg b/website/public/brands/pi.svg new file mode 100644 index 00000000..df44f948 --- /dev/null +++ b/website/public/brands/pi.svg @@ -0,0 +1,20 @@ + + + + + diff --git a/website/src/content/docs/agents/index.md b/website/src/content/docs/agents/index.md index 36c40fd2..9de85e6c 100644 --- a/website/src/content/docs/agents/index.md +++ b/website/src/content/docs/agents/index.md @@ -1,25 +1,25 @@ --- title: Agent support overview -description: What the sidebar shows for Claude Code, Codex, and OpenCode, side by side. +description: What the sidebar shows for Claude Code, Codex, OpenCode, and pi, side by side. --- -Claude Code, Codex, and OpenCode work with the sidebar, but they expose different sets of hooks — so the sidebar's surface area is narrower for Codex and OpenCode than it is for Claude Code. +Claude Code, Codex, OpenCode, and pi work with the sidebar, but they expose different sets of hooks — so the sidebar's surface area is narrower for Codex, OpenCode, and pi than it is for Claude Code. ## Feature support by agent -| Feature | Claude Code | Codex | OpenCode | Notes | -| ---------------------------------------- | ----------- | ------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | -| Base status tracking | ✓ | ✓ | ✓ | Covers `running`, `idle`, and `error`; `waiting` and `background` depend on agent-specific hooks | -| Prompt text display | ✓ | ✓ | ✓ | Saved from `UserPromptSubmit` | -| Response text display (`▷ ...`) | ✓ | ✓ | ✓ | Populated from the `Stop` payload | -| Background shell state | ✓ | — | — | Claude Bash tools can report `run_in_background`; Codex and OpenCode do not currently document a background Bash flag | -| Waiting status + wait reason | ✓ | — | ✓ | OpenCode maps permission prompts to waiting notifications; Claude also has `Notification`, `PermissionDenied`, and `TeammateIdle` | -| API failure reason display | ✓ | — | ✓ | `StopFailure` is wired only for Claude and OpenCode | -| Permission badge | ✓ (`plan` / `edit` / `auto` / `!`) | ✓ (`auto` / `!` only) | — | Codex badges are inferred from process arguments; OpenCode does not expose permission modes | -| Git branch display | ✓ | ✓ | ✓ | Uses the pane `cwd`; Claude updates dynamically via `CwdChanged` | -| Elapsed time | ✓ | ✓ | ✓ | Since the last prompt | -| Task progress | ✓ | — | — | Requires `PostToolUse`; Codex fires `PostToolUse` only for `Bash`, and OpenCode does not surface task progress | -| Task lifecycle notifications | ✓ | ✓ (`Stop` only) | ✓ | `Stop` desktop notifications fire for all three. `Notification`, `TaskCompleted`, `StopFailure`, and `PermissionDenied` vary. | -| Sub-agent display | ✓ | — | — | Requires `SubagentStart` / `SubagentStop` | -| Activity log | ✓ | ✓ (Bash only) | ✓ | Codex's `PostToolUse` fires only for `Bash`; OpenCode records the tool events the plugin bridge receives | -| Worktree lifecycle tracking | ✓ | — | — | Requires `WorktreeCreate` / `WorktreeRemove` | +| Feature | Claude Code | Codex | OpenCode | pi | Notes | +| ----------------------------------------- | ----------- | ------------ | ------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | +| Base status tracking | ✓ | ✓ | ✓ | ✓ | Covers `running`, `idle`, and `error`; `waiting` and `background` depend on agent-specific hooks | +| Prompt text display | ✓ | ✓ | ✓ | ✓ | Saved from `UserPromptSubmit` (pi: `before_agent_start`) | +| Response text display (`▷ ...`) | ✓ | ✓ | ✓ | ✓ | Populated from the `Stop` payload (pi: `agent_settled`) | +| Background shell state | ✓ | — | — | — | Claude Bash tools can report `run_in_background`; Codex, OpenCode, and pi do not currently document a background Bash flag | +| Waiting status + wait reason | ✓ | — | ✓ | — | OpenCode maps permission prompts to waiting notifications; Claude also has `Notification`, `PermissionDenied`, and `TeammateIdle`; pi exposes no permission-approval event to extensions | +| API failure reason display | ✓ | — | ✓ | — | `StopFailure` is wired only for Claude and OpenCode; pi has no dedicated "agent errored" event | +| Permission badge | ✓ (`plan` / `edit` / `auto` / `!`) | ✓ (`auto` / `!` only) | — | — | Codex badges are inferred from process arguments; OpenCode and pi do not expose permission modes | +| Git branch display | ✓ | ✓ | ✓ | ✓ | Uses the pane `cwd`; Claude updates dynamically via `CwdChanged` | +| Elapsed time | ✓ | ✓ | ✓ | ✓ | Since the last prompt | +| Task progress | ✓ | — | — | — | Requires `PostToolUse`; Codex fires `PostToolUse` only for `Bash`, and OpenCode/pi do not surface task progress | +| Task lifecycle notifications | ✓ | ✓ (`Stop` only) | ✓ | ✓ (`Stop` only) | `Stop` desktop notifications fire for all four. `Notification`, `TaskCompleted`, `StopFailure`, and `PermissionDenied` vary. | +| Sub-agent display | ✓ | — | — | — | Requires `SubagentStart` / `SubagentStop` | +| Activity log | ✓ | ✓ (Bash only) | ✓ | ✓ | Codex's `PostToolUse` fires only for `Bash`; OpenCode and pi record the tool events their bridge receives (pi normalizes `bash`/`read`/`write`/`edit`/`powershell`; other tools log unlabeled) | +| Worktree lifecycle tracking | ✓ | — | — | — | Requires `WorktreeCreate` / `WorktreeRemove` | diff --git a/website/src/content/docs/agents/pi.md b/website/src/content/docs/agents/pi.md new file mode 100644 index 00000000..4a03a81b --- /dev/null +++ b/website/src/content/docs/agents/pi.md @@ -0,0 +1,42 @@ +--- +title: pi +description: What the sidebar shows for pi panes, and how the extension bridge maps its events. +--- + +pi works with the sidebar through a local extension bridge, so the visible +surface is similar to OpenCode but with a different event source. + +## What you get + +### Status and prompts + +- Live status from `session_start` / `before_agent_start` / `agent_settled` +- Prompt text from `before_agent_start` +- Response preview (`▷ ...`) from the last assistant message, flushed on `agent_settled` +- Elapsed time since the last prompt + +### Activity log + +- Tool calls recorded from `tool_result` — `bash`, `read`, `write`, `edit`, and + `powershell` are normalized into the same vocabulary Claude Code uses; + other tools are still logged but without a derived label + +### Git + +- Branch display from the pane's `cwd` + +## What is not available + +| Feature | Why | +| ---------------------------- | ---------------------------------------------------------------------------------------- | +| Permission badge | pi does not expose Claude-style permission modes to extensions | +| Waiting status + wait reason | pi has no native permission-approval event exposed to extensions | +| Background shell state | pi's bash tool result does not currently document a background flag | +| API failure reason | pi's extension API has no dedicated "agent errored" lifecycle event distinct from `stop` | +| Task progress counter | The bridge does not map a task-progress event | +| Sub-agent tree | pi does not emit Claude-style sub-agent lifecycle events to extensions | +| Worktree lifecycle tracking | pi does not emit `WorktreeCreate` / `WorktreeRemove` | + +## Setup + +Wire the extension bridge from [pi setup](/tmux-agent-sidebar/getting-started/pi/). diff --git a/website/src/content/docs/features/activity-log.mdx b/website/src/content/docs/features/activity-log.mdx index 7a3d6faf..82068ef5 100644 --- a/website/src/content/docs/features/activity-log.mdx +++ b/website/src/content/docs/features/activity-log.mdx @@ -46,6 +46,7 @@ Tool names map to a stable color so `Read` / `Edit` / `Bash` etc. stay distingui | Claude Code | Every tool the hook payload exposes | | Codex | `Bash` only — Codex's `PostToolUse` fires for Bash alone (its `tool_input` is typed `{ command: string }`), so `Read` / `Edit` / `Write` / `Grep` / `Glob` and other tool calls are **not** reported | | OpenCode | Every tool event the plugin bridge emits | +| pi | Every tool event the extension bridge emits; `bash` / `read` / `write` / `edit` / `powershell` get normalized labels, other tools log unlabeled | ## Switching tabs diff --git a/website/src/content/docs/features/notifications.mdx b/website/src/content/docs/features/notifications.mdx index 88485acf..e36302e4 100644 --- a/website/src/content/docs/features/notifications.mdx +++ b/website/src/content/docs/features/notifications.mdx @@ -16,7 +16,7 @@ The **Default** column shows which events fire when `@sidebar_notifications_even | Event | Fired when | Agent | Default | | ------------------- | --------------------------------------------------------- | ---------------- | ------- | -| `stop` | Assistant finished responding (`Stop` hook) | Claude, Codex, OpenCode | ✓ | +| `stop` | Assistant finished responding (`Stop` hook) | Claude, Codex, OpenCode, pi | ✓ | | `notification` | Permission prompt or other attention request | Claude, OpenCode | ✓ | | `stop_failure` | Assistant ended with an error (`StopFailure` hook) | Claude, OpenCode | ✓ | | `permission_denied` | Permission explicitly denied (`PermissionDenied` hook) | Claude only | ✓ | diff --git a/website/src/content/docs/features/worktree.mdx b/website/src/content/docs/features/worktree.mdx index 5e6822ad..d7ce24ca 100644 --- a/website/src/content/docs/features/worktree.mdx +++ b/website/src/content/docs/features/worktree.mdx @@ -28,7 +28,7 @@ The modal's `NAME` field is slugified (lowercase, non-alphanumeric → `-`) and - **Branch** — ``, where `` defaults to `agent/` (e.g. `add login form` → `agent/add-login-form`). Colliding slugs get an incrementing suffix (`-2`, `-3`, …). - **Worktree path** — `/.worktrees/` by default. Change the repo-relative directory with `@agent-sidebar-worktree-dir`; absolute paths and `..` are rejected. -- **tmux window** — the slug is used as the window name; the agent you picked in the modal (`claude` / `codex` / `opencode`) launches inside it with the selected permission `MODE`. +- **tmux window** — the slug is used as the window name; the agent you picked in the modal (`claude` / `codex` / `opencode` / `pi`) launches inside it with the selected permission `MODE`. Defaults for the agent, branch prefix, and worktree directory live in tmux options — see [tmux options](/tmux-agent-sidebar/reference/tmux-options/) for the full list. diff --git a/website/src/content/docs/getting-started/installation.md b/website/src/content/docs/getting-started/installation.md index 69b1e0dc..fbc61402 100644 --- a/website/src/content/docs/getting-started/installation.md +++ b/website/src/content/docs/getting-started/installation.md @@ -70,3 +70,4 @@ The sidebar receives status updates through agent hooks — continue with the ag - [Claude Code setup](/tmux-agent-sidebar/getting-started/claude-code/) - [Codex setup](/tmux-agent-sidebar/getting-started/codex/) - [OpenCode setup](/tmux-agent-sidebar/getting-started/opencode/) +- [pi setup](/tmux-agent-sidebar/getting-started/pi/) diff --git a/website/src/content/docs/getting-started/pi.md b/website/src/content/docs/getting-started/pi.md new file mode 100644 index 00000000..6193264a --- /dev/null +++ b/website/src/content/docs/getting-started/pi.md @@ -0,0 +1,36 @@ +--- +title: pi setup +description: Wire up the pi extension bridge from the bundled extension directory. +--- + +pi uses the bundled extension bridge. Once you make the extension visible to +pi, the sidebar can receive its events automatically. + +## Extension bridge + +### Link the extension file + +Create pi's global extensions directory if it does not already exist, then +symlink the extension **file** (not the directory) into it. Linking the +single file lets the bridge coexist with any other extensions you have +installed, and installing into the global directory means it loads for +every project without needing a per-project trust decision: + +```sh +mkdir -p ~/.pi/agent/extensions +ln -sf ~/.tmux/plugins/tmux-agent-sidebar/.pi/extensions/tmux-agent-sidebar.ts \ + ~/.pi/agent/extensions/tmux-agent-sidebar.ts +``` + +If you keep `tmux-agent-sidebar` in a different path, point the symlink at +that copy instead. + +> Prefer a project-local install instead? pi also auto-discovers +> `.pi/extensions/*.ts` inside a trusted project, but the extension will not +> load until that project has been trusted — the global install above avoids +> that gate entirely. + +### Restart pi + +Restart pi after adding the extension so it discovers the new bridge. You can +also run `/reload` inside an existing pi session instead of restarting. diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index 418b56b2..9ed1e8e0 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -1,9 +1,9 @@ --- title: tmux-agent-sidebar -description: tmux-agent-sidebar — one tmux sidebar that tracks every Claude Code, Codex, and OpenCode pane across every session and window. See status, background shells, prompts, Git state, activity, and worktrees without switching windows. +description: tmux-agent-sidebar — one tmux sidebar that tracks every Claude Code, Codex, OpenCode, and pi pane across every session and window. See status, background shells, prompts, Git state, activity, and worktrees without switching windows. template: splash hero: - tagline: 'Every Claude Code, Codex, and OpenCode pane across every tmux session and window — status, background shells, prompts, Git, and activity in one sidebar.' + tagline: 'Every Claude Code, Codex, OpenCode, and pi pane across every tmux session and window — status, background shells, prompts, Git, and activity in one sidebar.' image: alt: tmux-agent-sidebar screenshot file: ../../assets/captures/hero.png @@ -24,7 +24,7 @@ import { Card, CardGrid } from '@astrojs/starlight/components'; - Tracks Claude Code, Codex, and OpenCode panes across every tmux session and window at + Tracks Claude Code, Codex, OpenCode, and pi panes across every tmux session and window at once, so context switching stops meaning window switching. @@ -54,5 +54,5 @@ install wizard downloads a pre-built binary or builds from source. Next, wire up your agent hooks — [Claude Code](/tmux-agent-sidebar/getting-started/claude-code/) installs as a plugin, [Codex](/tmux-agent-sidebar/getting-started/codex/) is a -one-paste setup inside its own pane, and [OpenCode](/tmux-agent-sidebar/getting-started/opencode/) -uses the bundled plugin bridge. +one-paste setup inside its own pane, and [OpenCode](/tmux-agent-sidebar/getting-started/opencode/) and +[pi](/tmux-agent-sidebar/getting-started/pi/) both use a bundled plugin/extension bridge. diff --git a/website/src/content/docs/reference/scripting.md b/website/src/content/docs/reference/scripting.md index f123f32a..29a27fd2 100644 --- a/website/src/content/docs/reference/scripting.md +++ b/website/src/content/docs/reference/scripting.md @@ -14,7 +14,7 @@ tmux show -t "$pane_id" -pv @pane_status # Get agent type tmux show -t "$pane_id" -pv @pane_agent -# → claude / codex / opencode / (empty) +# → claude / codex / opencode / pi / (empty) ``` ## Available pane options @@ -23,7 +23,7 @@ tmux show -t "$pane_id" -pv @pane_agent | -------------------------- | ------------------------------------------------------------------ | | `@pane_status` | `running` / `background` / `waiting` / `idle` / `error` / empty | | `@pane_attention` | `1` while the pane is flagged for attention, otherwise empty | -| `@pane_agent` | `claude` / `codex` / `opencode` / empty | +| `@pane_agent` | `claude` / `codex` / `opencode` / `pi` / empty | | `@pane_name` | Friendly agent/session name (from `/rename` on Claude) | | `@pane_role` | `sidebar` for the sidebar pane itself; empty for agent panes | | `@pane_prompt` | Latest user prompt text or response preview | diff --git a/website/src/content/docs/reference/tmux-options.md b/website/src/content/docs/reference/tmux-options.md index b079a2ae..7ec4abf9 100644 --- a/website/src/content/docs/reference/tmux-options.md +++ b/website/src/content/docs/reference/tmux-options.md @@ -24,7 +24,7 @@ Most options must be set **before** loading the plugin in your `tmux.conf`. Colo | Option | Default | Description | | --------------------------------- | ----------- | --------------------------------------------------------- | -| `@agent-sidebar-default-agent` | `claude` | Agent launched by `n` (also accepts `codex`) | +| `@agent-sidebar-default-agent` | `claude` | Agent launched by `n` (also accepts `codex`, `opencode`, `pi`) | | `@agent-sidebar-branch-prefix` | `agent/` | Branch prefix for new worktrees | | `@agent-sidebar-worktree-dir` | `.worktrees` | Repo-relative directory for sidebar-spawned worktrees; absolute paths and `..` are rejected | @@ -55,6 +55,7 @@ Most options must be set **before** loading the plugin in your `tmux.conf`. Colo | `@sidebar_color_agent_claude` | `174` (terracotta) | Claude brand color | | `@sidebar_color_agent_codex` | `141` (purple) | Codex brand color | | `@sidebar_color_agent_opencode` | `117` (light blue) | OpenCode brand color | +| `@sidebar_color_agent_pi` | `215` (orange) | pi brand color | ## Text colors From 88017bc910b952111a4426143b87a8aeb7a478da Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Tue, 8 Sep 2026 01:55:31 -0400 Subject: [PATCH 5/7] fix(pi): add grep to tool name normalization --- src/adapter/pi.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/adapter/pi.rs b/src/adapter/pi.rs index 0b1e9b5e..5333de0e 100644 --- a/src/adapter/pi.rs +++ b/src/adapter/pi.rs @@ -36,6 +36,7 @@ fn normalize_tool_name(raw: &str) -> String { "write" => CanonicalTool::Write, "edit" => CanonicalTool::Edit, "powershell" => CanonicalTool::PowerShell, + "grep" => CanonicalTool::Grep, other => return other.to_string(), }; canonical.as_str().to_string() From 0e8f43d49f66884dbf5cdccf2b68a494e67952df Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Tue, 8 Sep 2026 03:00:31 -0400 Subject: [PATCH 6/7] test(adapter): fix grep normalization test left stale by 0688687 - 0688687 mapped pi's "grep" tool to CanonicalTool::Grep but left the test asserting it stays unmapped, so it now correctly expects "Grep" - add a fresh unmapped-tool-name regression test using "find" instead, so pass-through coverage for genuinely unmapped tools isn't lost --- src/adapter/pi.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/adapter/pi.rs b/src/adapter/pi.rs index 5333de0e..c4624d20 100644 --- a/src/adapter/pi.rs +++ b/src/adapter/pi.rs @@ -276,7 +276,7 @@ mod tests { } #[test] - fn activity_log_passes_through_unmapped_tool_names() { + fn activity_log_normalizes_lowercase_grep() { let adapter = PiAdapter; let event = adapter .parse( @@ -285,7 +285,22 @@ mod tests { ) .unwrap(); match event { - AgentEvent::ActivityLog { tool_name, .. } => assert_eq!(tool_name, "grep"), + AgentEvent::ActivityLog { tool_name, .. } => assert_eq!(tool_name, "Grep"), + other => panic!("expected ActivityLog, got {:?}", other), + } + } + + #[test] + fn activity_log_passes_through_unmapped_tool_names() { + let adapter = PiAdapter; + let event = adapter + .parse( + "activity-log", + &json!({"tool_name": "find", "tool_input": {"pattern": "*.rs"}}), + ) + .unwrap(); + match event { + AgentEvent::ActivityLog { tool_name, .. } => assert_eq!(tool_name, "find"), other => panic!("expected ActivityLog, got {:?}", other), } } From d11adcb561e32ae5770fa37a75ddf2e7c288807a Mon Sep 17 00:00:00 2001 From: Chen Yi Le Date: Tue, 8 Sep 2026 03:00:41 -0400 Subject: [PATCH 7/7] fix(pi): resolve hook.sh through the global extension symlink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - resolveHookScript() previously walked up from dirname(fileURLToPath(import.meta.url)), but pi's extension loader (jiti) does a dynamic import() that preserves the discovered path verbatim — for the documented global install that path is the ~/.pi/agent/extensions/tmux-agent-sidebar.ts symlink itself, not the real file. The walk-up therefore searched the wrong directory tree and never found hook.sh, silently falling back to a bare "tmux-agent-sidebar" command that is not on PATH, so every hook event (session-start, user-prompt-submit, stop, activity-log) was dropped for every project except the one the extension physically lives in - realpath the resolved module path first so the walk-up starts from the real plugin/repo directory regardless of how the extension was discovered - root-caused live via debug instrumentation across a real tmux + pi session in an untrusted project (VoCat); confirmed the fix restores full status/prompt/response tracking for pi sessions outside the tmux-agent-sidebar repo itself --- .pi/extensions/tmux-agent-sidebar.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/.pi/extensions/tmux-agent-sidebar.ts b/.pi/extensions/tmux-agent-sidebar.ts index 7e1383f8..4e8506c3 100644 --- a/.pi/extensions/tmux-agent-sidebar.ts +++ b/.pi/extensions/tmux-agent-sidebar.ts @@ -18,12 +18,31 @@ // no use of pi's ExtensionAPI types — it only needs `.ts` naming to match // pi's auto-discovery glob (`~/.pi/agent/extensions/*.ts`, `.pi/extensions/*.ts`). import { spawn } from "node:child_process"; -import { existsSync } from "node:fs"; +import { existsSync, realpathSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +// pi loads extensions (via jiti) through a dynamic `import()` of whatever +// path discovery found — for the documented global install that path is +// the `~/.pi/agent/extensions/tmux-agent-sidebar.ts` symlink itself, and +// `import.meta.url` reflects that symlink path verbatim rather than the +// real file it points at (unlike a plain `node ` CLI invocation, +// which does resolve symlinks for its entry module). Without realpath-ing +// first, the walk-up below starts from the wrong directory tree entirely +// (`~/.pi/agent/extensions/` instead of the plugin/repo root) and can +// never find `hook.sh`, silently falling back to a bare `tmux-agent-sidebar` +// command that usually isn't on PATH. +const resolveSelfPath = () => { + const raw = fileURLToPath(import.meta.url); + try { + return realpathSync(raw); + } catch { + return raw; + } +}; + const resolveHookScript = () => { - let dir = dirname(fileURLToPath(import.meta.url)); + let dir = dirname(resolveSelfPath()); for (let i = 0; i < 4; i += 1) { const candidate = resolve(dir, "hook.sh"); if (existsSync(candidate)) {