1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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();
|