@phren/cli 0.3.3 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.d.ts +6 -0
- package/dist/bridge/agent-hooks.js +66 -25
- package/dist/bridge/canary.d.ts +4 -0
- package/dist/bridge/canary.js +17 -4
- package/dist/bridge/changes.d.ts +7 -0
- package/dist/bridge/changes.js +6 -1
- package/dist/bridge/client.js +2 -1
- package/dist/bridge/command.js +7 -5
- package/dist/bridge/conductor-group.d.ts +1 -0
- package/dist/bridge/conductor-group.js +4 -3
- package/dist/bridge/dispatch-command.js +2 -2
- package/dist/bridge/fanouts.js +6 -2
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +3 -2
- package/dist/bridge/harness-status.d.ts +12 -0
- package/dist/bridge/harness-status.js +153 -0
- package/dist/bridge/health.d.ts +18 -0
- package/dist/bridge/health.js +30 -4
- package/dist/bridge/herdr.d.ts +6 -0
- package/dist/bridge/herdr.js +62 -8
- package/dist/bridge/install.js +4 -0
- package/dist/bridge/model-switch.d.ts +4 -1
- package/dist/bridge/model-switch.js +12 -7
- package/dist/bridge/models.js +3 -2
- package/dist/bridge/pane-status.d.ts +37 -0
- package/dist/bridge/pane-status.js +139 -0
- package/dist/bridge/pane-text.d.ts +3 -11
- package/dist/bridge/pane-text.js +9 -16
- package/dist/bridge/peers.js +9 -6
- package/dist/bridge/prompt-once.d.ts +26 -0
- package/dist/bridge/prompt-once.js +69 -0
- package/dist/bridge/protocol.d.ts +10 -0
- package/dist/bridge/protocol.js +10 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-launch.d.ts +10 -1
- package/dist/bridge/schedule-launch.js +29 -3
- package/dist/bridge/schedule-watch.js +1 -1
- package/dist/bridge/schedules.d.ts +10 -0
- package/dist/bridge/schedules.js +40 -0
- package/dist/bridge/server-launch.js +12 -10
- package/dist/bridge/server-pane-routes.js +23 -9
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/session-servers.js +5 -6
- package/dist/bridge/side-questions.js +6 -5
- package/dist/bridge/terminal-choice.d.ts +12 -5
- package/dist/bridge/terminal-choice.js +66 -0
- package/dist/bridge/terminal-herdr.d.ts +5 -0
- package/dist/bridge/terminal-herdr.js +57 -0
- package/dist/bridge/terminal-tmux.d.ts +111 -0
- package/dist/bridge/terminal-tmux.js +549 -0
- package/dist/bridge/terminal.d.ts +119 -0
- package/dist/bridge/terminal.js +66 -0
- package/dist/bridge/transcript-claude.d.ts +6 -0
- package/dist/bridge/transcript-claude.js +20 -0
- package/dist/bridge/transcript-opencode.js +1 -1
- package/dist/bridge/transcript-preview.d.ts +5 -0
- package/dist/bridge/transcript-preview.js +52 -2
- package/dist/bridge/transport.js +10 -4
- package/dist/bridge-hook.mjs +4852 -3391
- package/dist/cli-registry.js +7 -0
- package/dist/entrypoint.js +2 -1
- package/dist/init/init.js +4 -0
- package/dist/link/doctor.js +33 -30
- package/dist/modules/agent-package.d.ts +35 -0
- package/dist/modules/agent-package.js +133 -0
- package/dist/modules/registry.js +2 -2
- package/dist/session/utils.js +1 -1
- package/dist/tools/dispatch.js +2 -2
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +97 -6
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
// tmux as the Hook's terminal provider, for computers without Herdr.
|
|
2
|
+
//
|
|
3
|
+
// Two tmux servers are Hook servers: the owner's own (the default socket,
|
|
4
|
+
// server name "tmux"), where the Hook finds agents the owner started, and a
|
|
5
|
+
// hidden one on its own socket (`tmux -L phren`, server name "tmux-phren"),
|
|
6
|
+
// where agents started from the phone run. Nobody has to know tmux for the
|
|
7
|
+
// second: it starts on the first launch, and `tmux -L phren attach` shows it.
|
|
8
|
+
//
|
|
9
|
+
// tmux knows processes, not agents. The agent in a pane comes from its
|
|
10
|
+
// foreground processes' command lines, and its status from the harness's own
|
|
11
|
+
// lifecycle hooks (pane-status.ts). Everything runs through execFile with an
|
|
12
|
+
// argument array: text from the phone reaches tmux as an argument or on
|
|
13
|
+
// stdin, never through a shell.
|
|
14
|
+
import { execFile } from "node:child_process";
|
|
15
|
+
import { accessSync, constants, existsSync, statSync } from "node:fs";
|
|
16
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
17
|
+
import { hostname, userInfo } from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { BridgeError, objects, serverName } from "./protocol.js";
|
|
20
|
+
import { harnessStatus } from "./harness-status.js";
|
|
21
|
+
import { dialogStatus, notePaneStatus, paneStatus } from "./pane-status.js";
|
|
22
|
+
import { herdrPanes } from "./terminal-herdr.js";
|
|
23
|
+
/** The owner's own tmux server (the default socket). */
|
|
24
|
+
export const TMUX_DEFAULT = "tmux";
|
|
25
|
+
/** The hidden server phone-started agents run in: `tmux -L phren`. */
|
|
26
|
+
export const TMUX_HIDDEN = "tmux-phren";
|
|
27
|
+
/** The tmux socket name (`-L`) a Hook server name stands for: "tmux" is the
|
|
28
|
+
* default socket and "tmux-<name>" the socket `<name>`. */
|
|
29
|
+
export function tmuxSocketName(server) {
|
|
30
|
+
const match = /^tmux(?:-([A-Za-z0-9_][A-Za-z0-9_.-]{0,63}))?$/.exec(server);
|
|
31
|
+
return match ? match[1] ?? "default" : undefined;
|
|
32
|
+
}
|
|
33
|
+
/** The Hook server name for a tmux socket name. */
|
|
34
|
+
export function tmuxServerName(socket) {
|
|
35
|
+
const name = socket === "default" ? TMUX_DEFAULT : `tmux-${socket}`;
|
|
36
|
+
return tmuxSocketName(name) === socket && serverName.safeParse(name).success ? name : undefined;
|
|
37
|
+
}
|
|
38
|
+
let cachedBinary;
|
|
39
|
+
/** The tmux on PATH or in the usual install folders; the Hook's service
|
|
40
|
+
* PATH can be shorter than a login shell's. Rechecked every minute. */
|
|
41
|
+
export function tmuxBinary() {
|
|
42
|
+
// PHREN_TMUX=off keeps the Hook on Herdr alone.
|
|
43
|
+
if (process.env.PHREN_TMUX === "off")
|
|
44
|
+
return undefined;
|
|
45
|
+
if (cachedBinary && Date.now() - cachedBinary.at < 60_000)
|
|
46
|
+
return cachedBinary.value;
|
|
47
|
+
const folders = [...(process.env.PATH ?? "").split(path.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
|
|
48
|
+
let value;
|
|
49
|
+
for (const folder of folders) {
|
|
50
|
+
if (!folder || !path.isAbsolute(folder))
|
|
51
|
+
continue;
|
|
52
|
+
const candidate = path.join(folder, "tmux");
|
|
53
|
+
try {
|
|
54
|
+
if (statSync(candidate).isFile()) {
|
|
55
|
+
accessSync(candidate, constants.X_OK);
|
|
56
|
+
value = candidate;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch { /* next folder */ }
|
|
61
|
+
}
|
|
62
|
+
cachedBinary = { at: Date.now(), value };
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
/** The environment tmux and the panes it starts get: the Hook's, without
|
|
66
|
+
* another multiplexer's variables. */
|
|
67
|
+
function tmuxEnvironment() {
|
|
68
|
+
return Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("HERDR_") && name !== "TMUX" && name !== "TMUX_PANE"));
|
|
69
|
+
}
|
|
70
|
+
function tmuxError(stderr, error) {
|
|
71
|
+
const said = stderr.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
|
|
72
|
+
if (error.name === "AbortError")
|
|
73
|
+
return new BridgeError(499, "Request cancelled.");
|
|
74
|
+
if (error.killed || error.signal === "SIGTERM")
|
|
75
|
+
return new BridgeError(504, "tmux did not answer. Refresh before trying again.");
|
|
76
|
+
if (error.code === "ENOENT")
|
|
77
|
+
return new BridgeError(503, "tmux is not installed on this computer.");
|
|
78
|
+
if (/no server running|error connecting to|No such file or directory/i.test(said))
|
|
79
|
+
return new BridgeError(503, "tmux is not running on this computer.", { code: "not_running" });
|
|
80
|
+
return new BridgeError(409, said ? `tmux: ${said}` : "tmux could not perform this action. Refresh the session before trying again.");
|
|
81
|
+
}
|
|
82
|
+
/** The folders this user's tmux sockets live in: `$TMUX_TMPDIR/tmux-<uid>`,
|
|
83
|
+
* where `-L` looks, then `/tmp/tmux-<uid>` when TMUX_TMPDIR points elsewhere
|
|
84
|
+
* (a server started from a shell with another TMUX_TMPDIR than the Hook's). */
|
|
85
|
+
export function tmuxSocketFolders(env = process.env) {
|
|
86
|
+
const uid = process.getuid?.();
|
|
87
|
+
if (uid === undefined)
|
|
88
|
+
return [];
|
|
89
|
+
const base = env.TMUX_TMPDIR && path.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
|
|
90
|
+
return [...new Set([path.join(base, `tmux-${uid}`), path.join("/tmp", `tmux-${uid}`)])];
|
|
91
|
+
}
|
|
92
|
+
/** Sockets outside `-L`'s folder, by name: tmux reaches them with `-S`. */
|
|
93
|
+
const socketPaths = new Map();
|
|
94
|
+
function socketFlags(socket) {
|
|
95
|
+
const file = socketPaths.get(socket);
|
|
96
|
+
return file ? ["-S", file] : ["-L", socket];
|
|
97
|
+
}
|
|
98
|
+
/** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
|
|
99
|
+
* outside the first folder of `tmuxSocketFolders` is remembered by path. */
|
|
100
|
+
export async function tmuxSocketsIn(folder) {
|
|
101
|
+
const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
|
|
102
|
+
const names = (await readdir(folder).catch(() => [])).slice(0, 256);
|
|
103
|
+
const found = [];
|
|
104
|
+
for (const name of names) {
|
|
105
|
+
if (found.length >= 32)
|
|
106
|
+
break;
|
|
107
|
+
if (!tmuxServerName(name))
|
|
108
|
+
continue;
|
|
109
|
+
const info = await lstat(path.join(folder, name)).catch(() => undefined);
|
|
110
|
+
if (!info?.isSocket() || (uid !== undefined && info.uid !== uid))
|
|
111
|
+
continue;
|
|
112
|
+
found.push(name);
|
|
113
|
+
if (folder !== primary && !socketPaths.has(name) && !existsSync(path.join(primary ?? folder, name)))
|
|
114
|
+
socketPaths.set(name, path.join(folder, name));
|
|
115
|
+
}
|
|
116
|
+
return found;
|
|
117
|
+
}
|
|
118
|
+
const defaultDeps = {
|
|
119
|
+
binary: tmuxBinary,
|
|
120
|
+
run: (socket, args, options = {}) => new Promise((resolve, reject) => {
|
|
121
|
+
const binary = tmuxBinary();
|
|
122
|
+
if (!binary) {
|
|
123
|
+
reject(new BridgeError(503, "tmux is not installed on this computer."));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const child = execFile(binary, [...socketFlags(socket), ...args], { timeout: options.timeoutMs ?? 5_000, maxBuffer: 4_194_304, env: tmuxEnvironment(), signal: options.signal }, (error, stdout, stderr) => { if (error)
|
|
127
|
+
reject(tmuxError(String(stderr), error));
|
|
128
|
+
else
|
|
129
|
+
resolve(String(stdout)); });
|
|
130
|
+
if (options.input !== undefined)
|
|
131
|
+
child.stdin?.end(options.input);
|
|
132
|
+
else
|
|
133
|
+
child.stdin?.end();
|
|
134
|
+
}),
|
|
135
|
+
processes: () => new Promise(resolve => {
|
|
136
|
+
execFile("ps", ["-A", "-o", "pid=,pgid=,tpgid=,tty=,args="], { timeout: 3_000, maxBuffer: 8_388_608, env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => resolve(error ? "" : String(stdout)));
|
|
137
|
+
}),
|
|
138
|
+
version: () => new Promise(resolve => {
|
|
139
|
+
const binary = tmuxBinary();
|
|
140
|
+
if (!binary) {
|
|
141
|
+
resolve("");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
execFile(binary, ["-V"], { timeout: 3_000 }, (error, stdout) => resolve(error ? "" : String(stdout)));
|
|
145
|
+
}),
|
|
146
|
+
sockets: async () => (await Promise.all(tmuxSocketFolders().map(tmuxSocketsIn))).flat(),
|
|
147
|
+
sleep: (ms, signal) => new Promise((resolve, reject) => {
|
|
148
|
+
if (signal?.aborted) {
|
|
149
|
+
reject(new BridgeError(499, "Request cancelled."));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const timer = setTimeout(() => { signal?.removeEventListener("abort", abort); resolve(); }, ms);
|
|
153
|
+
const abort = () => { clearTimeout(timer); reject(new BridgeError(499, "Request cancelled.")); };
|
|
154
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
155
|
+
}),
|
|
156
|
+
};
|
|
157
|
+
let deps = defaultDeps;
|
|
158
|
+
/** For tests: replace how tmux and ps run; the returned function restores them. */
|
|
159
|
+
export function setTmuxDeps(replacement) {
|
|
160
|
+
const previous = deps;
|
|
161
|
+
deps = { ...deps, ...replacement };
|
|
162
|
+
return () => { deps = previous; };
|
|
163
|
+
}
|
|
164
|
+
function socketOf(server) {
|
|
165
|
+
const socket = tmuxSocketName(serverName.parse(server));
|
|
166
|
+
if (!socket)
|
|
167
|
+
throw new BridgeError(400, "This is not a tmux server.");
|
|
168
|
+
return socket;
|
|
169
|
+
}
|
|
170
|
+
const tmux = (server, args, options) => deps.run(socketOf(server), args, options);
|
|
171
|
+
// tmux ids carry sigils the Hook's ids do not allow: session $3, window @5,
|
|
172
|
+
// pane %12 become s3, w5 and p12, and back.
|
|
173
|
+
const SIGILS = { s: "$", w: "@", p: "%" };
|
|
174
|
+
export function fromTmuxId(value) {
|
|
175
|
+
const match = /^([$@%])(\d{1,9})$/.exec(value);
|
|
176
|
+
return match ? `${match[1] === "$" ? "s" : match[1] === "@" ? "w" : "p"}${match[2]}` : undefined;
|
|
177
|
+
}
|
|
178
|
+
export function toTmuxId(value, kind) {
|
|
179
|
+
const match = /^([swp])(\d{1,9})$/.exec(value);
|
|
180
|
+
if (!match || match[1] !== kind)
|
|
181
|
+
throw new BridgeError(409, "This tmux pane changed. Refresh the computer.");
|
|
182
|
+
return SIGILS[kind] + match[2];
|
|
183
|
+
}
|
|
184
|
+
/** The agent a command line runs, by the harness's executable or package. */
|
|
185
|
+
export function agentFromCommand(command) {
|
|
186
|
+
const words = command.trim().split(/\s+/).filter(Boolean).slice(0, 4);
|
|
187
|
+
const [first, second] = words, base = (word) => word ? path.basename(word) : "";
|
|
188
|
+
// A Node, Bun or Deno launcher runs the harness as its script.
|
|
189
|
+
const program = /^(node|nodejs|bun|deno)$/.test(base(first)) && second ? second : first;
|
|
190
|
+
if (!program)
|
|
191
|
+
return undefined;
|
|
192
|
+
const name = base(program);
|
|
193
|
+
if (name === "claude" || program.includes("/claude/versions/") || program.includes("@anthropic-ai/claude-code"))
|
|
194
|
+
return "claude";
|
|
195
|
+
if (name === "codex" || program.includes("@openai/codex"))
|
|
196
|
+
return "codex";
|
|
197
|
+
if (name === "opencode" || name === ".opencode" || program.includes("opencode-ai"))
|
|
198
|
+
return "opencode";
|
|
199
|
+
if (name === "copilot" || program.includes("@github/copilot"))
|
|
200
|
+
return "copilot";
|
|
201
|
+
if (name === "phren-agent" || program.includes("@phren/agent/") || /\/packages\/agent\/dist\/bin\.js$/.test(program))
|
|
202
|
+
return "phren";
|
|
203
|
+
// `phren agent` runs the same agent through the CLI.
|
|
204
|
+
const next = words[words.indexOf(program) + 1];
|
|
205
|
+
if ((name === "phren" || program.includes("@phren/cli/")) && next === "agent")
|
|
206
|
+
return "phren";
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
export function parseProcesses(text) {
|
|
210
|
+
return text.split("\n").flatMap(line => {
|
|
211
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
212
|
+
return match ? [{ pid: Number(match[1]), pgid: Number(match[2]), tpgid: Number(match[3]), tty: match[4], args: match[5] }] : [];
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/** The pane terminal's foreground process group, oldest process first. */
|
|
216
|
+
function foreground(processes, paneTty) {
|
|
217
|
+
const tty = paneTty.replace(/^\/dev\//, "");
|
|
218
|
+
return processes.filter(p => (p.tty === tty || `tty${p.tty}` === tty) && p.tpgid > 0 && p.pgid === p.tpgid).sort((a, b) => a.pid - b.pid);
|
|
219
|
+
}
|
|
220
|
+
const FIELDS = ["session_id", "session_name", "session_attached", "session_activity", "window_id", "window_name", "window_active",
|
|
221
|
+
"pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title"];
|
|
222
|
+
const FORMAT = FIELDS.map(field => `#{${field}}`).join("\t");
|
|
223
|
+
export function parsePanes(text) {
|
|
224
|
+
return text.split("\n").flatMap(line => {
|
|
225
|
+
const values = line.split("\t");
|
|
226
|
+
if (values.length !== FIELDS.length)
|
|
227
|
+
return [];
|
|
228
|
+
const row = Object.fromEntries(FIELDS.map((field, index) => [field, values[index]]));
|
|
229
|
+
return fromTmuxId(row.session_id) && fromTmuxId(row.window_id) && fromTmuxId(row.pane_id) && /^\d+$/.test(row.pane_pid) ? [row] : [];
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
async function listRows(server) {
|
|
233
|
+
try {
|
|
234
|
+
return parsePanes(await tmux(server, ["list-panes", "-a", "-F", FORMAT]));
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
// The hidden server starts with the first launch; until then it has no panes.
|
|
238
|
+
if (server === TMUX_HIDDEN && error instanceof BridgeError && error.details?.code === "not_running")
|
|
239
|
+
return [];
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** The agent's status in a pane: its lifecycle events (Claude, Codex,
|
|
244
|
+
* phren-agent) or its own records (OpenCode, Copilot), then blocked while a
|
|
245
|
+
* working agent draws a dialog on the screen. */
|
|
246
|
+
async function agentStatus(server, pane, terminal, agent, pids) {
|
|
247
|
+
let status;
|
|
248
|
+
if (agent === "opencode" || agent === "copilot") {
|
|
249
|
+
const recorded = await harnessStatus(agent, pids).catch(() => undefined);
|
|
250
|
+
status = recorded ? notePaneStatus(server, pane, terminal, recorded) : undefined;
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
status = await paneStatus(server, pane, terminal);
|
|
254
|
+
return dialogStatus(server, pane, terminal, agent, status, () => tmuxTerminal.readScreen(server, pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }));
|
|
255
|
+
}
|
|
256
|
+
const STATUS_RANK = ["blocked", "waiting", "working", "done", "idle"];
|
|
257
|
+
/** One tmux server in the shape of the Hook's pane snapshot (the shape
|
|
258
|
+
* Herdr's `session.snapshot` answers): workspaces are tmux sessions, tabs
|
|
259
|
+
* windows, panes panes. */
|
|
260
|
+
export async function tmuxSnapshot(server) {
|
|
261
|
+
const rows = await listRows(server);
|
|
262
|
+
const processes = rows.length ? parseProcesses(await deps.processes()) : [];
|
|
263
|
+
const host = hostname(), short = host.split(".")[0];
|
|
264
|
+
const workspaces = new Map(), tabs = new Map();
|
|
265
|
+
const panes = [], agents = [];
|
|
266
|
+
let focused;
|
|
267
|
+
for (const row of rows) {
|
|
268
|
+
const workspace = fromTmuxId(row.session_id), tab = fromTmuxId(row.window_id), pane = fromTmuxId(row.pane_id);
|
|
269
|
+
if (!workspaces.has(workspace))
|
|
270
|
+
workspaces.set(workspace, { workspace_id: workspace, label: row.session_name });
|
|
271
|
+
const tabKey = `${workspace}\0${tab}`;
|
|
272
|
+
if (!tabs.has(tabKey))
|
|
273
|
+
tabs.set(tabKey, { tab_id: tab, workspace_id: workspace, label: row.window_name });
|
|
274
|
+
const running = foreground(processes, row.pane_tty);
|
|
275
|
+
const agent = [row.pane_current_command, ...running.map(p => p.args)].map(agentFromCommand).find(Boolean);
|
|
276
|
+
const terminal = `${pane}:${row.pane_pid}`;
|
|
277
|
+
const status = agent ? await agentStatus(server, pane, terminal, agent, running.map(p => p.pid)) : undefined;
|
|
278
|
+
// Claude and Codex report every turn through their lifecycle hooks; until
|
|
279
|
+
// the first event the status is unknown (a folder-trust screen, say). The
|
|
280
|
+
// others count as idle until their own records say otherwise.
|
|
281
|
+
const hooked = agent === "claude" || agent === "codex";
|
|
282
|
+
const name = row["@phren_agent"] || undefined;
|
|
283
|
+
const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? row.pane_title : undefined;
|
|
284
|
+
panes.push({ pane_id: pane, tab_id: tab, workspace_id: workspace, terminal_id: terminal, cwd: row.pane_current_path || undefined,
|
|
285
|
+
foreground_cwd: row.pane_current_path || undefined, title,
|
|
286
|
+
...(agent ? { agent, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
|
|
287
|
+
...(agent && name ? { agent_name: name } : {}) });
|
|
288
|
+
if (agent && name)
|
|
289
|
+
agents.push({ name, pane_id: pane });
|
|
290
|
+
if (Number(row.session_attached) > 0 && row.window_active === "1" && row.pane_active === "1"
|
|
291
|
+
&& (!focused || Number(row.session_activity) > Number(focused.session_activity)))
|
|
292
|
+
focused = row;
|
|
293
|
+
}
|
|
294
|
+
// A window's status is its most pressing pane's.
|
|
295
|
+
for (const tab of tabs.values()) {
|
|
296
|
+
const statuses = panes.filter(p => p.tab_id === tab.tab_id && p.workspace_id === tab.workspace_id && typeof p.agent_status === "string").map(p => String(p.agent_status));
|
|
297
|
+
const status = STATUS_RANK.find(value => statuses.includes(value)) ?? statuses[0];
|
|
298
|
+
if (status)
|
|
299
|
+
tab.agent_status = status;
|
|
300
|
+
}
|
|
301
|
+
return { workspaces: [...workspaces.values()], tabs: [...tabs.values()], panes, agents,
|
|
302
|
+
...(focused ? { focused_workspace_id: fromTmuxId(focused.session_id), focused_tab_id: fromTmuxId(focused.window_id), focused_pane_id: fromTmuxId(focused.pane_id) } : {}) };
|
|
303
|
+
}
|
|
304
|
+
/** The Hook's key names as tmux key names; undefined for a literal character. */
|
|
305
|
+
export function tmuxKey(key) {
|
|
306
|
+
const named = { enter: "Enter", esc: "Escape", escape: "Escape", up: "Up", down: "Down", left: "Left", right: "Right",
|
|
307
|
+
tab: "Tab", space: "Space", backspace: "BSpace", home: "Home", end: "End", pageup: "PPage", pagedown: "NPage" };
|
|
308
|
+
if ([...key].length === 1)
|
|
309
|
+
return undefined;
|
|
310
|
+
const lower = key.toLowerCase();
|
|
311
|
+
if (named[lower])
|
|
312
|
+
return named[lower];
|
|
313
|
+
const modified = /^(alt|ctrl|shift)\+(.+)$/i.exec(key);
|
|
314
|
+
if (modified) {
|
|
315
|
+
const rest = modified[2], inner = [...rest].length === 1 ? rest : tmuxKey(rest);
|
|
316
|
+
if (inner)
|
|
317
|
+
return `${{ alt: "M-", ctrl: "C-", shift: "S-" }[modified[1].toLowerCase()]}${inner}`;
|
|
318
|
+
}
|
|
319
|
+
throw new BridgeError(400, `The key ${key.slice(0, 20)} is not supported in tmux.`);
|
|
320
|
+
}
|
|
321
|
+
/** send-keys calls for `keys`, in order: named keys together, literal characters with -l. */
|
|
322
|
+
export function sendKeysCalls(pane, keys) {
|
|
323
|
+
const calls = [];
|
|
324
|
+
let named = [], literal = "";
|
|
325
|
+
const flush = () => {
|
|
326
|
+
if (named.length)
|
|
327
|
+
calls.push(["send-keys", "-t", pane, ...named]);
|
|
328
|
+
if (literal)
|
|
329
|
+
calls.push(["send-keys", "-t", pane, "-l", "--", literal]);
|
|
330
|
+
named = [];
|
|
331
|
+
literal = "";
|
|
332
|
+
};
|
|
333
|
+
for (const key of keys) {
|
|
334
|
+
const name = tmuxKey(key);
|
|
335
|
+
if (name === undefined) {
|
|
336
|
+
if (named.length)
|
|
337
|
+
flush();
|
|
338
|
+
literal += key;
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
if (literal)
|
|
342
|
+
flush();
|
|
343
|
+
named.push(name);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
flush();
|
|
347
|
+
return calls;
|
|
348
|
+
}
|
|
349
|
+
/** tmux 3.0 and later run a multi-argument command directly, without a shell. */
|
|
350
|
+
async function requireDirectExec() {
|
|
351
|
+
if (!deps.binary())
|
|
352
|
+
throw new BridgeError(503, "tmux is not installed on this computer.");
|
|
353
|
+
const match = /(\d+)\.(\d+)/.exec(await deps.version());
|
|
354
|
+
if (!match || Number(match[1]) < 3)
|
|
355
|
+
throw new BridgeError(409, "Phren needs tmux 3.0 or later to start agents. Update tmux on the computer.");
|
|
356
|
+
}
|
|
357
|
+
/** The login shell a started agent runs under, and falls back to when it exits. */
|
|
358
|
+
function loginShell() {
|
|
359
|
+
const shell = process.env.SHELL && path.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => { try {
|
|
360
|
+
return userInfo().shell ?? "";
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
return "";
|
|
364
|
+
} })();
|
|
365
|
+
// Only a POSIX shell takes the launcher script below.
|
|
366
|
+
return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path.basename(shell)) && existsSync(shell) ? shell : "/bin/sh";
|
|
367
|
+
}
|
|
368
|
+
/** A session name tmux accepts: no "." or ":" and nothing unprintable. */
|
|
369
|
+
function sessionName(label, taken) {
|
|
370
|
+
const base = (label ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
|
|
371
|
+
let name = base;
|
|
372
|
+
for (let n = 2; taken.has(name) && n < 1000; n++)
|
|
373
|
+
name = `${base}-${n}`;
|
|
374
|
+
return name;
|
|
375
|
+
}
|
|
376
|
+
async function paneRow(server, pane) {
|
|
377
|
+
return parsePanes(await tmux(server, ["list-panes", "-a", "-F", FORMAT])).find(row => row.pane_id === pane);
|
|
378
|
+
}
|
|
379
|
+
export const tmuxTerminal = {
|
|
380
|
+
kind: "tmux",
|
|
381
|
+
async ping(server) {
|
|
382
|
+
if (!deps.binary())
|
|
383
|
+
throw new BridgeError(503, "tmux is not installed on this computer.");
|
|
384
|
+
// The hidden server answers even before it has started: a launch starts it.
|
|
385
|
+
if (server !== TMUX_HIDDEN)
|
|
386
|
+
await tmux(server, ["list-sessions", "-F", "#{session_id}"], { timeoutMs: 3_000 });
|
|
387
|
+
},
|
|
388
|
+
snapshot: tmuxSnapshot,
|
|
389
|
+
async listPanes(server) { return herdrPanes(server, await tmuxSnapshot(server)); },
|
|
390
|
+
async processes(server, pane) {
|
|
391
|
+
const row = await paneRow(server, toTmuxId(pane, "p"));
|
|
392
|
+
if (!row)
|
|
393
|
+
throw new BridgeError(409, "This tmux pane changed. Refresh the computer.");
|
|
394
|
+
return { shellPid: Number(row.pane_pid), foregroundPids: foreground(parseProcesses(await deps.processes()), row.pane_tty).map(p => p.pid) };
|
|
395
|
+
},
|
|
396
|
+
async readScreen(server, pane, read) {
|
|
397
|
+
const lines = Math.max(1, Math.min(10_000, Math.floor(read.lines)));
|
|
398
|
+
const args = ["capture-pane", "-p", "-t", toTmuxId(pane, "p"), ...(read.stripAnsi === false || read.format === "ansi" ? ["-e"] : []),
|
|
399
|
+
...(read.source === "recent" ? ["-S", `-${lines}`] : [])];
|
|
400
|
+
const text = (await tmux(server, args, { timeoutMs: read.timeoutMs })).replace(/\n$/, "").split("\n");
|
|
401
|
+
// A screen's unused rows come back blank; the readers want its last drawn lines.
|
|
402
|
+
while (text.length && !text.at(-1).replace(/\x1b\[[0-9;]*m/g, "").trim())
|
|
403
|
+
text.pop();
|
|
404
|
+
return text.slice(-lines).join("\n");
|
|
405
|
+
},
|
|
406
|
+
async sendKeys(server, pane, keys) {
|
|
407
|
+
const target = toTmuxId(pane, "p");
|
|
408
|
+
for (const call of sendKeysCalls(target, keys))
|
|
409
|
+
await tmux(server, call);
|
|
410
|
+
},
|
|
411
|
+
async prompt(server, pane, text, signal) {
|
|
412
|
+
const target = toTmuxId(pane, "p"), buffer = `phren-${process.pid}-${Date.now().toString(36)}`;
|
|
413
|
+
// The text reaches tmux on stdin and the pane as one bracketed paste
|
|
414
|
+
// (-p), newlines kept (-r), then Enter submits it.
|
|
415
|
+
await tmux(server, ["load-buffer", "-b", buffer, "-"], { input: text, signal });
|
|
416
|
+
await tmux(server, ["paste-buffer", "-d", "-p", "-r", "-b", buffer, "-t", target], { signal });
|
|
417
|
+
await deps.sleep(150, signal);
|
|
418
|
+
await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
|
|
419
|
+
},
|
|
420
|
+
async create(server, { workspace, label, cwd }) {
|
|
421
|
+
const directory = cwd && path.isAbsolute(cwd) ? ["-c", cwd] : [];
|
|
422
|
+
const name = label ? ["-n", label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
|
|
423
|
+
if (workspace) {
|
|
424
|
+
await tmux(server, ["new-window", "-d", "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
|
|
428
|
+
await tmux(server, ["new-session", "-d", "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]);
|
|
429
|
+
},
|
|
430
|
+
async startAgent(server, pane, { name, kind, args, timeoutMs }) {
|
|
431
|
+
if (!["claude", "codex", "copilot", "opencode"].includes(kind))
|
|
432
|
+
throw new BridgeError(400, "This agent cannot be started in tmux.");
|
|
433
|
+
await requireDirectExec();
|
|
434
|
+
const target = toTmuxId(pane, "p"), row = await paneRow(server, target);
|
|
435
|
+
if (!row)
|
|
436
|
+
throw new BridgeError(409, "This tmux pane changed. Refresh the computer.");
|
|
437
|
+
// The name marks the pane for the phone (a conductor, a scheduled run).
|
|
438
|
+
await tmux(server, ["set-option", "-p", "-t", target, "@phren_agent", name]).catch(() => undefined);
|
|
439
|
+
// The harness runs under a login shell, so it gets the owner's PATH, and
|
|
440
|
+
// the pane falls back to that shell when it exits. The harness and its
|
|
441
|
+
// arguments are the script's positional parameters, never script text.
|
|
442
|
+
const shell = loginShell();
|
|
443
|
+
await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []),
|
|
444
|
+
"--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
|
|
445
|
+
// Started once the harness is the pane's foreground program.
|
|
446
|
+
const deadline = Date.now() + Math.min(timeoutMs, 30_000);
|
|
447
|
+
for (;;) {
|
|
448
|
+
const snapshot = await tmuxSnapshot(server);
|
|
449
|
+
const current = objects(snapshot.panes).find(p => p.pane_id === pane);
|
|
450
|
+
if (!current)
|
|
451
|
+
throw new BridgeError(409, `tmux closed the pane before ${kind} started.`);
|
|
452
|
+
if (current.agent === kind)
|
|
453
|
+
return;
|
|
454
|
+
if (Date.now() >= deadline)
|
|
455
|
+
throw new BridgeError(504, `${kind} did not start in the tmux pane. Check that it is installed and on the login shell's PATH.`);
|
|
456
|
+
await deps.sleep(250);
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
async focusPane(server, pane) {
|
|
460
|
+
const target = toTmuxId(pane, "p");
|
|
461
|
+
await tmux(server, ["select-window", "-t", target]);
|
|
462
|
+
await tmux(server, ["select-pane", "-t", target]);
|
|
463
|
+
},
|
|
464
|
+
async groupAction(server, operation, { workspace, tab }, label) {
|
|
465
|
+
if (tab) {
|
|
466
|
+
const target = toTmuxId(tab, "w");
|
|
467
|
+
if (operation === "focus")
|
|
468
|
+
await tmux(server, ["select-window", "-t", target]);
|
|
469
|
+
else if (operation === "rename")
|
|
470
|
+
await tmux(server, ["rename-window", "-t", target, (label ?? "").replace(/[\x00-\x1f\x7f]/g, " ")]);
|
|
471
|
+
else
|
|
472
|
+
await tmux(server, ["kill-window", "-t", target]);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (!workspace)
|
|
476
|
+
throw new BridgeError(400, "Choose a tmux session.");
|
|
477
|
+
const target = toTmuxId(workspace, "s");
|
|
478
|
+
// A session has no focus of its own without an attached client.
|
|
479
|
+
if (operation === "focus")
|
|
480
|
+
return;
|
|
481
|
+
if (operation === "rename")
|
|
482
|
+
await tmux(server, ["rename-session", "-t", target, sessionName(label, new Set())]);
|
|
483
|
+
else
|
|
484
|
+
await tmux(server, ["kill-session", "-t", target]);
|
|
485
|
+
},
|
|
486
|
+
};
|
|
487
|
+
/** The owner's tmux servers that answer, by Hook server name: the default
|
|
488
|
+
* socket and every other socket in the user's tmux folders (`tmux -L work`
|
|
489
|
+
* is "tmux-work"), at most 16. The hidden server is not among them. */
|
|
490
|
+
async function ownerServers() {
|
|
491
|
+
const sockets = [...new Set(["default", ...await deps.sockets().catch(() => [])])].filter(socket => socket !== "phren");
|
|
492
|
+
const names = sockets.flatMap(socket => tmuxServerName(socket) ?? []).slice(0, 16);
|
|
493
|
+
const running = await Promise.all(names.map(name => tmuxTerminal.ping(name).then(() => true, () => false)));
|
|
494
|
+
return names.filter((_, index) => running[index]);
|
|
495
|
+
}
|
|
496
|
+
/** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
|
|
497
|
+
* servers that answer, and the hidden server whenever tmux is installed (a
|
|
498
|
+
* launch starts it). `kind` stays "herdr", the phone's name for the Hook's
|
|
499
|
+
* session protocol; `terminal` names the multiplexer. */
|
|
500
|
+
export async function tmuxServers() {
|
|
501
|
+
if (!deps.binary())
|
|
502
|
+
return [];
|
|
503
|
+
return [...await ownerServers(), TMUX_HIDDEN].map(name => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
|
|
504
|
+
}
|
|
505
|
+
export async function tmuxHealth() {
|
|
506
|
+
if (process.env.PHREN_TMUX === "off")
|
|
507
|
+
return { state: "off" };
|
|
508
|
+
if (!deps.binary())
|
|
509
|
+
return { state: "missing" };
|
|
510
|
+
const [version, servers, hidden] = await Promise.all([
|
|
511
|
+
deps.version().then(text => /(\d+\.\d+[a-z]?)/.exec(text)?.[1]),
|
|
512
|
+
ownerServers(),
|
|
513
|
+
tmux(TMUX_HIDDEN, ["list-sessions", "-F", "#{session_id}"], { timeoutMs: 3_000 })
|
|
514
|
+
.then(text => ({ running: true, sessions: text.split("\n").filter(Boolean).length }), () => ({ running: false })),
|
|
515
|
+
]);
|
|
516
|
+
const major = Number(/^(\d+)/.exec(version ?? "")?.[1]);
|
|
517
|
+
return { state: "ok", ...(version ? { version, launches: major >= 3 } : {}), servers, hidden };
|
|
518
|
+
}
|
|
519
|
+
/** The tmux pane this process runs in, from the variables tmux sets in every
|
|
520
|
+
* pane, with its session and window asked of that server. */
|
|
521
|
+
export async function tmuxPaneFromEnv(env = process.env) {
|
|
522
|
+
const socket = env.TMUX?.split(",")[0], pane = env.TMUX_PANE;
|
|
523
|
+
if (!socket || !path.isAbsolute(socket) || !pane || !fromTmuxId(pane))
|
|
524
|
+
return undefined;
|
|
525
|
+
const server = tmuxServerName(path.basename(socket));
|
|
526
|
+
if (!server)
|
|
527
|
+
return undefined;
|
|
528
|
+
// A socket outside `-L`'s folder (another TMUX_TMPDIR) is reached by path.
|
|
529
|
+
const primary = tmuxSocketFolders(env)[0];
|
|
530
|
+
if (primary && path.dirname(socket) !== primary && !socketPaths.has(path.basename(socket)))
|
|
531
|
+
socketPaths.set(path.basename(socket), socket);
|
|
532
|
+
try {
|
|
533
|
+
const [session, window] = (await deps.run(path.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id}\t#{window_id}"], { timeoutMs: 1_500 })).trim().split("\t");
|
|
534
|
+
const workspace = fromTmuxId(session ?? ""), tab = fromTmuxId(window ?? "");
|
|
535
|
+
return workspace && tab ? { server, workspace, tab, pane: fromTmuxId(pane) } : undefined;
|
|
536
|
+
}
|
|
537
|
+
catch {
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** The command that attaches the phone's SSH terminal to a tmux server. */
|
|
542
|
+
export function tmuxAttach(server) {
|
|
543
|
+
const binary = deps.binary();
|
|
544
|
+
if (!binary)
|
|
545
|
+
throw new BridgeError(503, "tmux is not installed on this computer.");
|
|
546
|
+
return { file: binary, args: [...socketFlags(socketOf(server)), "attach-session"] };
|
|
547
|
+
}
|
|
548
|
+
/** For tests: forget the tmux executable lookup and the sockets found by path. */
|
|
549
|
+
export function resetTmuxBinary() { cachedBinary = undefined; socketPaths.clear(); }
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
/** The pane this process runs in, from the variables its multiplexer sets:
|
|
3
|
+
* inside Herdr only Herdr's pane counts, elsewhere a tmux pane does. */
|
|
4
|
+
export declare function terminalPaneFromEnv(env?: NodeJS.ProcessEnv): Promise<{
|
|
5
|
+
server: string;
|
|
6
|
+
workspace: string;
|
|
7
|
+
tab: string;
|
|
8
|
+
pane: string;
|
|
9
|
+
} | undefined>;
|
|
10
|
+
/** A pane as the multiplexer lists it. `server` names the multiplexer instance
|
|
11
|
+
* (a Herdr session, a tmux socket), `workspace` and `tab` its place in it
|
|
12
|
+
* (a Herdr workspace and tab, a tmux session and window). */
|
|
13
|
+
export interface TerminalPane {
|
|
14
|
+
server: string;
|
|
15
|
+
workspace: string;
|
|
16
|
+
tab: string;
|
|
17
|
+
pane: string;
|
|
18
|
+
/** The foreground process's directory, else the pane's own. */
|
|
19
|
+
cwd?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
label?: string;
|
|
22
|
+
/** What the multiplexer itself knows about the agent in the pane. Optional:
|
|
23
|
+
* a provider without agent awareness returns none. */
|
|
24
|
+
hints?: {
|
|
25
|
+
/** Which agent runs there ("claude", "codex", …). */
|
|
26
|
+
agent?: string;
|
|
27
|
+
/** "working", "idle", "blocked", "waiting", "done" or "unknown". */
|
|
28
|
+
status?: string;
|
|
29
|
+
/** The conversation id the multiplexer reports for the agent. */
|
|
30
|
+
session?: string;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The processes a pane runs. */
|
|
34
|
+
export interface PaneProcesses {
|
|
35
|
+
shellPid?: number;
|
|
36
|
+
/** The pane's foreground process group, in the multiplexer's order. */
|
|
37
|
+
foregroundPids: number[];
|
|
38
|
+
}
|
|
39
|
+
/** One read of what a pane draws. */
|
|
40
|
+
export interface ScreenRead {
|
|
41
|
+
/** "agent" reads through the pane's agent (refused while none runs there);
|
|
42
|
+
* "pane" reads any pane, including one whose agent is still starting. */
|
|
43
|
+
scope: "agent" | "pane";
|
|
44
|
+
/** The visible screen, or the recent scrollback. */
|
|
45
|
+
source: "visible" | "recent";
|
|
46
|
+
lines: number;
|
|
47
|
+
/** Plain text unless false. */
|
|
48
|
+
stripAnsi?: boolean;
|
|
49
|
+
/** "ansi" keeps the styles even where the multiplexer strips by default. */
|
|
50
|
+
format?: "ansi";
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
}
|
|
53
|
+
/** A new pane: a tab in `workspace`, or a new workspace when it is absent. */
|
|
54
|
+
export interface PanePlacement {
|
|
55
|
+
workspace?: string;
|
|
56
|
+
label?: string;
|
|
57
|
+
cwd?: string;
|
|
58
|
+
}
|
|
59
|
+
/** Starts an agent in an existing, empty pane. */
|
|
60
|
+
export interface AgentStart {
|
|
61
|
+
name: string;
|
|
62
|
+
kind: string;
|
|
63
|
+
args: string[];
|
|
64
|
+
timeoutMs: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Key names are the Hook's vocabulary: "enter", "esc", "up", "down", "tab",
|
|
68
|
+
* "space", "alt+Up" and single characters. A provider maps them to its own.
|
|
69
|
+
*
|
|
70
|
+
* Every method rejects with a BridgeError when the multiplexer refuses or is
|
|
71
|
+
* unreachable; the message is shown to the phone.
|
|
72
|
+
*/
|
|
73
|
+
export interface TerminalProvider {
|
|
74
|
+
readonly kind: string;
|
|
75
|
+
/** Resolves when `server` is running and answering. */
|
|
76
|
+
ping(server: string): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* The server's panes in the Hook's snapshot shape, the one Herdr's
|
|
79
|
+
* `session.snapshot` answers: `workspaces` (`workspace_id`, `label`), `tabs`
|
|
80
|
+
* (`tab_id`, `workspace_id`, `label`, `agent_status`) and `panes`
|
|
81
|
+
* (`pane_id`, `tab_id`, `workspace_id`, `terminal_id`, `cwd`,
|
|
82
|
+
* `foreground_cwd`, `title`, `label`, `agent`, `agent_status`,
|
|
83
|
+
* `agent_name`, `state_change_seq`), plus `focused_workspace_id` /
|
|
84
|
+
* `focused_tab_id` / `focused_pane_id`. `terminal_id` names the terminal
|
|
85
|
+
* instance, so a pane reused by a new shell is a different terminal.
|
|
86
|
+
*/
|
|
87
|
+
snapshot(server: string): Promise<Json>;
|
|
88
|
+
listPanes(server: string): Promise<TerminalPane[]>;
|
|
89
|
+
processes(server: string, pane: string): Promise<PaneProcesses>;
|
|
90
|
+
readScreen(server: string, pane: string, read: ScreenRead): Promise<string>;
|
|
91
|
+
sendKeys(server: string, pane: string, keys: string[]): Promise<void>;
|
|
92
|
+
/** Types `text` into the pane's agent and submits it. */
|
|
93
|
+
prompt(server: string, pane: string, text: string, signal?: AbortSignal): Promise<void>;
|
|
94
|
+
/** Opens a pane; the caller finds it in the next `listPanes`. */
|
|
95
|
+
create(server: string, placement: PanePlacement): Promise<void>;
|
|
96
|
+
startAgent(server: string, pane: string, agent: AgentStart): Promise<void>;
|
|
97
|
+
focusPane(server: string, pane: string): Promise<void>;
|
|
98
|
+
/** Focuses, renames or closes a whole tab (when `tab` is set) or workspace. */
|
|
99
|
+
groupAction(server: string, operation: "focus" | "rename" | "close", group: {
|
|
100
|
+
workspace?: string;
|
|
101
|
+
tab?: string;
|
|
102
|
+
}, label?: string): Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
/** Which multiplexer a Hook server name belongs to: "tmux" and "tmux-<socket>"
|
|
105
|
+
* are tmux servers unless Herdr has a session of that name; every other name
|
|
106
|
+
* is a Herdr server, exactly as before tmux support. */
|
|
107
|
+
export declare function terminalKind(server: string): "herdr" | "tmux";
|
|
108
|
+
/** The multiplexer's name as the phone shows it in messages. */
|
|
109
|
+
export declare function terminalName(server: string): string;
|
|
110
|
+
/** The provider for each server by its name: Herdr's or tmux's. */
|
|
111
|
+
export declare const routedTerminal: TerminalProvider;
|
|
112
|
+
/** True when a start or prompt was refused because the agent is still
|
|
113
|
+
* starting (a folder-trust or login screen holds it). Herdr says so with its
|
|
114
|
+
* own error code; another provider with `code`. */
|
|
115
|
+
export declare function agentNotReady(error: unknown): boolean;
|
|
116
|
+
/** The multiplexer the Hook drives: each call goes to its server's provider. */
|
|
117
|
+
export declare function terminalProvider(): TerminalProvider;
|
|
118
|
+
/** For tests: drive the Hook through `provider`; the returned function restores the previous one. */
|
|
119
|
+
export declare function setTerminalProvider(provider: TerminalProvider): () => void;
|