Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions .pi/extensions/tmux-agent-sidebar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// 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, 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 <path>` 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(resolveSelfPath());
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),
},
});
});
}
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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.
Expand Down
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<h1 align="center">tmux-agent-sidebar</h1>

<p align="center">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.</p>
<p align="center">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.</p>

<p align="center"><img src="website/src/assets/captures/hero.png" alt="tmux-agent-sidebar hero" /></p>

Expand All @@ -13,15 +13,15 @@
## 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**
— spawn a fresh worktree + agent from the sidebar and tear it down — window, worktree, and branch — in one keystroke
- **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

Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions docs/state-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/adapter/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod claude;
pub mod codex;
pub mod opencode;
pub mod pi;

use crate::event::AgentEventKind;

Expand Down
Loading