summaryrefslogtreecommitdiff
path: root/bin/pi-reload-agents
diff options
context:
space:
mode:
Diffstat (limited to 'bin/pi-reload-agents')
-rwxr-xr-xbin/pi-reload-agents172
1 files changed, 172 insertions, 0 deletions
diff --git a/bin/pi-reload-agents b/bin/pi-reload-agents
new file mode 100755
index 0000000..2bad1b2
--- /dev/null
+++ b/bin/pi-reload-agents
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+// Reload (pi's /reload) every pi agent in this tmux server that is not busy,
+// for instance after changing ~/.pi/agent/settings.json or mcp.json.
+//
+// pi-reload-agents reload each idle agent that is off screen
+// pi-reload-agents --visible also the ones on screen
+// pi-reload-agents -n only list what it would ask, and why not
+//
+// It sends no keystrokes. It asks each agent through the control socket of
+// dingger's pi extension (~/src/dingger, `dingger install pi`), which the
+// dingger daemon records in the pane option @dingger_control. The extension
+// checks at that moment and refuses while the agent is busy (a turn, a
+// dialog, queued messages) or has a draft in its input box, so nothing typed
+// is lost or sent. Agents without the extension are listed, to /reload by
+// hand.
+//
+// It skips its own pane, and by default panes on screen (the active window
+// of an attached session), where you may be about to type: the same rule as
+// `dingger reload-agents`, which does this only for agents on an old dingger
+// extension. A reload also resets pi's other extensions: MCP servers
+// reconnect.
+"use strict";
+
+const { execFileSync } = require("node:child_process");
+const net = require("node:net");
+
+const USAGE = `usage: pi-reload-agents [--visible] [-n|--dry-run]`;
+
+const args = process.argv.slice(2);
+let visible = false;
+let dryRun = false;
+for (const arg of args) {
+ if (arg === "--visible") visible = true;
+ else if (arg === "-n" || arg === "--dry-run") dryRun = true;
+ else if (arg === "-h" || arg === "--help") {
+ console.log(USAGE);
+ process.exit(0);
+ } else {
+ console.error(USAGE);
+ process.exit(2);
+ }
+}
+
+const FIELDS = [
+ "#{pane_id}",
+ "#{session_name}:#{window_index}.#{pane_index}",
+ "#{window_active}",
+ "#{session_attached}",
+ "#{pane_current_command}",
+ "#{@agent}",
+ "#{@agent_state}",
+ "#{@dingger_control}",
+ "#{@agent_name}",
+];
+
+function listPanes() {
+ let out;
+ try {
+ out = execFileSync("tmux", ["list-panes", "-a", "-F", FIELDS.join("\t")], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ } catch (err) {
+ console.error(`pi-reload-agents: cannot list tmux panes: ${(err.stderr || err.message).trim()}`);
+ process.exit(1);
+ }
+ // A window linked into several sessions is listed once per session: keep
+ // the first listing, and count it on screen if it is in any of them.
+ const panes = new Map();
+ for (const line of out.split("\n")) {
+ if (!line) continue;
+ const [id, where, windowActive, attached, command, agent, state, control, name] = line.split("\t");
+ const onScreen = windowActive === "1" && attached !== "0";
+ const known = panes.get(id);
+ if (known) {
+ known.onScreen ||= onScreen;
+ continue;
+ }
+ panes.set(id, { id, where, onScreen, command, agent, state, control, name });
+ }
+ return [...panes.values()];
+}
+
+// Ask the extension behind `control` to reload: resolves to undefined when it
+// does, else the reason it does not.
+function requestReload(control) {
+ return new Promise((resolve) => {
+ let answer = "";
+ let settled = false;
+ const done = (reason) => {
+ if (settled) return;
+ settled = true;
+ socket.destroy();
+ resolve(reason);
+ };
+ const socket = net.createConnection(control);
+ socket.setTimeout(2000, () => done("no answer"));
+ socket.on("error", (err) => done(`cannot connect: ${err.code || err.message}`));
+ socket.on("connect", () => socket.write('{"method":"reload"}\n'));
+ socket.on("data", (data) => {
+ answer += data.toString();
+ const newline = answer.indexOf("\n");
+ if (newline < 0) return;
+ try {
+ const parsed = JSON.parse(answer.slice(0, newline));
+ done(parsed.ok ? undefined : parsed.reason || "refused");
+ } catch {
+ done(`unexpected answer: ${answer.trim()}`);
+ }
+ });
+ socket.on("end", () => done(answer ? `unexpected answer: ${answer.trim()}` : "no answer"));
+ });
+}
+
+async function main() {
+ const self = process.env.TMUX_PANE;
+ const isPi = (pane) => pane.agent === "pi" || (!pane.agent && pane.command === "pi");
+ const agents = listPanes().filter(isPi);
+ if (agents.length === 0) {
+ console.log("no pi agents in this tmux server");
+ return;
+ }
+
+ const width = Math.max(...agents.map((pane) => pane.where.length));
+ const counts = { reloaded: 0, skipped: 0, refused: 0, byHand: 0 };
+ const report = (pane, outcome) => {
+ const name = pane.name ? ` ${pane.name}` : "";
+ console.log(`${pane.where.padEnd(width)} ${outcome.padEnd(22)}${name}`);
+ };
+
+ const asks = [];
+ for (const pane of agents) {
+ if (pane.id === self) {
+ report(pane, "skipped: this pane");
+ counts.skipped++;
+ } else if (!pane.control) {
+ report(pane, "by hand: no extension");
+ counts.byHand++;
+ } else if (pane.onScreen && !visible) {
+ report(pane, "skipped: on screen");
+ counts.skipped++;
+ } else if (pane.state === "working" || pane.state === "blocked") {
+ // The extension would refuse too; this saves asking.
+ report(pane, `refused: ${pane.state}`);
+ counts.refused++;
+ } else if (dryRun) {
+ report(pane, `would ask (${pane.state || "?"})`);
+ } else {
+ asks.push(
+ requestReload(pane.control).then((reason) => ({ pane, reason })),
+ );
+ }
+ }
+
+ for (const { pane, reason } of await Promise.all(asks)) {
+ if (reason === undefined) {
+ report(pane, "reloaded");
+ counts.reloaded++;
+ } else {
+ report(pane, `refused: ${reason}`);
+ counts.refused++;
+ }
+ }
+
+ if (!dryRun) {
+ const parts = [`${counts.reloaded} reloaded`, `${counts.refused} refused`, `${counts.skipped} skipped`];
+ if (counts.byHand) parts.push(`${counts.byHand} to /reload by hand`);
+ console.log(`\n${parts.join(", ")}`);
+ }
+}
+
+main();