|
| 1 | +// tmux-bridge — exposes a Unix socket so other tmux panes can push |
| 2 | +// user messages into this running pi session. |
| 3 | +// |
| 4 | +// Socket path: $TMPDIR/pi-tmux-<sanitized-session-id>.sock |
| 5 | +// Companion CLI: dotfiles/tmux/pi-send (writes one JSON line per message). |
| 6 | +// |
| 7 | +// Wire format: one JSON object per line, e.g. |
| 8 | +// {"text": "hello"} |
| 9 | +// {"text": "...", "mode": "steer" | "followUp"} // mode used while streaming |
| 10 | +import type { |
| 11 | + ExtensionAPI, |
| 12 | + ExtensionContext, |
| 13 | +} from "@earendil-works/pi-coding-agent"; |
| 14 | +import { execSync } from "node:child_process"; |
| 15 | +import * as fs from "node:fs"; |
| 16 | +import * as net from "node:net"; |
| 17 | +import * as os from "node:os"; |
| 18 | +import * as path from "node:path"; |
| 19 | + |
| 20 | +function getTmuxSessionId(): string | null { |
| 21 | + if (!process.env.TMUX) return null; |
| 22 | + try { |
| 23 | + const id = execSync("tmux display-message -p '#{session_id}'", { |
| 24 | + encoding: "utf8", |
| 25 | + stdio: ["ignore", "pipe", "ignore"], |
| 26 | + }).trim(); |
| 27 | + return id || null; |
| 28 | + } catch { |
| 29 | + return null; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +function socketPathFor(sessionId: string): string { |
| 34 | + const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"); |
| 35 | + return path.join(os.tmpdir(), `pi-tmux-${safe}.sock`); |
| 36 | +} |
| 37 | + |
| 38 | +export default function (pi: ExtensionAPI) { |
| 39 | + const sessionId = getTmuxSessionId(); |
| 40 | + if (!sessionId) return; // not in tmux — nothing to do |
| 41 | + const sockPath = socketPathFor(sessionId); |
| 42 | + |
| 43 | + let server: net.Server | undefined; |
| 44 | + let currentCtx: ExtensionContext | undefined; |
| 45 | + |
| 46 | + const handleLine = (line: string) => { |
| 47 | + const trimmed = line.trim(); |
| 48 | + if (!trimmed) return; |
| 49 | + let payload: { text?: string; mode?: "steer" | "followUp" }; |
| 50 | + try { |
| 51 | + payload = JSON.parse(trimmed); |
| 52 | + } catch { |
| 53 | + currentCtx?.ui?.notify?.( |
| 54 | + "tmux-bridge: dropped malformed JSON line", |
| 55 | + "warning", |
| 56 | + ); |
| 57 | + return; |
| 58 | + } |
| 59 | + const text = payload.text; |
| 60 | + if (!text || typeof text !== "string") return; |
| 61 | + |
| 62 | + const idle = currentCtx?.isIdle?.() ?? true; |
| 63 | + // When idle, sendUserMessage triggers a turn immediately. |
| 64 | + // When streaming, deliverAs is required. |
| 65 | + const opts = idle ? undefined : { deliverAs: payload.mode ?? "steer" }; |
| 66 | + |
| 67 | + try { |
| 68 | + pi.sendUserMessage(text, opts as never); |
| 69 | + } catch (e) { |
| 70 | + const msg = e instanceof Error ? e.message : String(e); |
| 71 | + currentCtx?.ui?.notify?.(`tmux-bridge: ${msg}`, "error"); |
| 72 | + } |
| 73 | + }; |
| 74 | + |
| 75 | + const probeExistingListener = (): Promise<boolean> => |
| 76 | + new Promise((resolve) => { |
| 77 | + if (!fs.existsSync(sockPath)) return resolve(false); |
| 78 | + const probe = net.createConnection(sockPath); |
| 79 | + let decided = false; |
| 80 | + const done = (alive: boolean) => { |
| 81 | + if (decided) return; |
| 82 | + decided = true; |
| 83 | + probe.destroy(); |
| 84 | + resolve(alive); |
| 85 | + }; |
| 86 | + probe.once("connect", () => done(true)); |
| 87 | + probe.once("error", () => done(false)); |
| 88 | + setTimeout(() => done(false), 200); |
| 89 | + }); |
| 90 | + |
| 91 | + const start = async (ctx: ExtensionContext) => { |
| 92 | + currentCtx = ctx; |
| 93 | + if (server) return; |
| 94 | + if (await probeExistingListener()) { |
| 95 | + ctx.ui?.notify?.( |
| 96 | + `tmux-bridge: another pi is already listening on ${sockPath}; ` + |
| 97 | + "this instance will not receive sends from pi-send / neovim.", |
| 98 | + "warning", |
| 99 | + ); |
| 100 | + return; |
| 101 | + } |
| 102 | + try { |
| 103 | + fs.unlinkSync(sockPath); // stale file from a crashed pi |
| 104 | + } catch { |
| 105 | + /* not present */ |
| 106 | + } |
| 107 | + server = net.createServer((socket) => { |
| 108 | + let buf = ""; |
| 109 | + socket.setEncoding("utf8"); |
| 110 | + socket.on("data", (chunk) => { |
| 111 | + buf += chunk; |
| 112 | + let idx = buf.indexOf("\n"); |
| 113 | + while (idx !== -1) { |
| 114 | + const line = buf.slice(0, idx); |
| 115 | + buf = buf.slice(idx + 1); |
| 116 | + handleLine(line); |
| 117 | + idx = buf.indexOf("\n"); |
| 118 | + } |
| 119 | + }); |
| 120 | + socket.on("error", () => { |
| 121 | + /* ignore peer disconnects */ |
| 122 | + }); |
| 123 | + }); |
| 124 | + server.on("error", (err) => { |
| 125 | + ctx.ui?.notify?.(`tmux-bridge: ${err.message}`, "error"); |
| 126 | + }); |
| 127 | + server.listen(sockPath, () => { |
| 128 | + try { |
| 129 | + fs.chmodSync(sockPath, 0o600); |
| 130 | + } catch { |
| 131 | + /* best effort */ |
| 132 | + } |
| 133 | + }); |
| 134 | + }; |
| 135 | + |
| 136 | + const stop = () => { |
| 137 | + if (!server) return; // we never owned the socket; don't unlink another pi's file |
| 138 | + server.close(); |
| 139 | + server = undefined; |
| 140 | + try { |
| 141 | + fs.unlinkSync(sockPath); |
| 142 | + } catch { |
| 143 | + /* ignore */ |
| 144 | + } |
| 145 | + }; |
| 146 | + |
| 147 | + pi.on("session_start", async (_event, ctx) => { |
| 148 | + start(ctx); |
| 149 | + }); |
| 150 | + pi.on("session_shutdown", async () => { |
| 151 | + stop(); |
| 152 | + }); |
| 153 | +} |
0 commit comments