@phren/cli 0.3.12 → 0.3.13

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.
Files changed (52) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hooks.d.ts +3 -0
  4. package/dist/bridge/agent-hooks.js +20 -1
  5. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  6. package/dist/bridge/codex-hook-trust.js +237 -0
  7. package/dist/bridge/command.js +3 -0
  8. package/dist/bridge/dispatch-command.js +9 -3
  9. package/dist/bridge/dispatch-returns.d.ts +5 -0
  10. package/dist/bridge/dispatch-returns.js +16 -6
  11. package/dist/bridge/dispatch.d.ts +25 -1
  12. package/dist/bridge/dispatch.js +35 -6
  13. package/dist/bridge/hand-off-queue.d.ts +74 -0
  14. package/dist/bridge/hand-off-queue.js +235 -0
  15. package/dist/bridge/hand-off.d.ts +12 -4
  16. package/dist/bridge/hand-off.js +27 -7
  17. package/dist/bridge/install.js +16 -2
  18. package/dist/bridge/pane-status.d.ts +12 -0
  19. package/dist/bridge/pane-status.js +50 -1
  20. package/dist/bridge/push.d.ts +6 -0
  21. package/dist/bridge/push.js +21 -0
  22. package/dist/bridge/schedule-launch.d.ts +1 -1
  23. package/dist/bridge/schedule-launch.js +5 -1
  24. package/dist/bridge/schedule-watch.d.ts +15 -1
  25. package/dist/bridge/schedule-watch.js +45 -10
  26. package/dist/bridge/server-launch.js +14 -4
  27. package/dist/bridge/server-overview.d.ts +8 -1
  28. package/dist/bridge/server-overview.js +12 -3
  29. package/dist/bridge/server-pane-routes.d.ts +1 -0
  30. package/dist/bridge/server-pane-routes.js +9 -7
  31. package/dist/bridge/server-routes.d.ts +4 -0
  32. package/dist/bridge/server-routes.js +57 -7
  33. package/dist/bridge/server.js +15 -2
  34. package/dist/bridge/session-activity.d.ts +24 -12
  35. package/dist/bridge/session-activity.js +36 -14
  36. package/dist/bridge/stalls.d.ts +22 -0
  37. package/dist/bridge/stalls.js +57 -0
  38. package/dist/bridge/sudo.d.ts +209 -0
  39. package/dist/bridge/sudo.js +501 -0
  40. package/dist/bridge/terminal-tmux.d.ts +12 -0
  41. package/dist/bridge/terminal-tmux.js +79 -4
  42. package/dist/bridge/transcript-claude.d.ts +4 -0
  43. package/dist/bridge/transcript-claude.js +131 -6
  44. package/dist/bridge/usage.d.ts +17 -0
  45. package/dist/bridge/usage.js +37 -3
  46. package/dist/bridge-hook.mjs +19448 -18102
  47. package/dist/cli-registry.js +7 -1
  48. package/dist/modules/registry.js +8 -8
  49. package/dist/tools/dispatch.js +17 -2
  50. package/package.json +1 -1
  51. package/starter/global/AGENTS.md +4 -0
  52. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -0,0 +1,501 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { EventEmitter } from "node:events";
4
+ import { existsSync } from "node:fs";
5
+ import { open, readdir, readFile, readlink, unlink } from "node:fs/promises";
6
+ import { request } from "node:http";
7
+ import path from "node:path";
8
+ import { promisify } from "node:util";
9
+ import { userInfo } from "node:os";
10
+ import { atomic, bridgeRoot, object } from "./protocol.js";
11
+ import { localSocket } from "./agent-hook-stores.js";
12
+ import { intervalFromEnv } from "./limits.js";
13
+ import { terminalPaneFromEnv } from "./terminal.js";
14
+ import { briefId } from "./launch-brief.js";
15
+ /**
16
+ * sudo with no terminal, answered from the phone.
17
+ *
18
+ * `sudo -A` runs `SUDO_ASKPASS` (`<bridge>/askpass`, a two-line script the
19
+ * Hook installs) with its prompt as the argument and reads the password from
20
+ * its stdout. The script runs the bundle's `askpass`, which asks the Hook over
21
+ * agent.sock and holds the connection. The password must reach sudo and no
22
+ * one else, so before asking the phone the Hook checks the whole chain
23
+ * (`verifyAsker`): the asker is this Hook's node running its bundle with no
24
+ * flags, its parent is the installed script, that script's parent is a sudo
25
+ * running as root (euid 0, which no process of the owner's can fake), and the
26
+ * asker's stdout is a pipe no other process of the owner's reads. The
27
+ * connection is bound to that process too: on macOS its other end must be
28
+ * held by the asker alone; on Linux the Hook writes the password straight into
29
+ * the asker's stdout (`/proc/<pid>/fd/1`), so a connection that names another
30
+ * process's pid gets nothing. It reads
31
+ * that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
32
+ * list it. `POST /v1/sudo/answer` writes the password into the held
33
+ * connection and forgets the request: the password is never logged, stored,
34
+ * or kept past that write. Deny, a timeout, no reachable phone, or the asker
35
+ * going away ends the request, and askpass exits non-zero, so sudo fails.
36
+ */
37
+ export const SUDO_HOLD_MS = intervalFromEnv("PHREN_SUDO_TIMEOUT_MS", 120_000, 1_000, 600_000);
38
+ /** Held askpass requests at once; more are refused. */
39
+ export const MAX_SUDO_PENDING = 8;
40
+ /** How long after a password is handed over the Hook waits to see whether
41
+ * sudo asks again, before calling it accepted. */
42
+ export const SUDO_OUTCOME_MS = intervalFromEnv("PHREN_SUDO_OUTCOME_MS", 6_000, 100, 30_000);
43
+ /** sudo's default `passwd_tries`: after the last one it gives up instead of asking again. */
44
+ const SUDO_TRIES = 3;
45
+ export const ASKPASS_FILE = "askpass";
46
+ export const askpassPath = () => path.join(bridgeRoot(), ASKPASS_FILE);
47
+ export const askpassInstalled = () => existsSync(askpassPath());
48
+ /** SUDO_ASKPASS for a launch, when this computer's Hook installed its helper. */
49
+ export const askpassEnv = () => askpassInstalled() ? { SUDO_ASKPASS: askpassPath() } : {};
50
+ const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
51
+ /** sudo runs SUDO_ASKPASS with no arguments of its own, so the helper is a
52
+ * script: the node that installed the Hook, the current bundle, `askpass`.
53
+ * It stays node's parent (no exec) so the Hook can see it in the chain, and
54
+ * drops what would load other code into node. */
55
+ export function askpassScript(node, bundle) {
56
+ return `#!/bin/sh\n# Installed by Phren Hook: sudo -A asks the phone for the password.\n`
57
+ + `unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH DYLD_INSERT_LIBRARIES DYLD_LIBRARY_PATH\n${quote(node)} ${quote(bundle)} askpass "$@"\n`;
58
+ }
59
+ export async function installAskpass(node, bundle) {
60
+ await atomic(askpassPath(), askpassScript(node, bundle), 0o700);
61
+ }
62
+ export async function removeAskpass() { await unlink(askpassPath()).catch(() => { }); }
63
+ /** sudo's options that take a value, short and long. */
64
+ const VALUE_FLAGS = new Set(["-u", "-g", "-p", "-C", "-D", "-h", "-r", "-t", "-T", "-U", "-c", "-R",
65
+ "--user", "--group", "--prompt", "--close-from", "--chdir", "--host", "--role", "--type", "--command-timeout", "--other-user", "--login-class", "--chroot"]);
66
+ const SHORT_VALUE = new Set([..."ugpCDhrtTUcR"]);
67
+ /** The command a sudo process will run, without sudo's own options, and the
68
+ * user it runs as. Falls back to the whole line when there is no command
69
+ * (`sudo -v`, `sudo -s`). */
70
+ export function sudoCommand(argv) {
71
+ let user, index = 1;
72
+ while (index < argv.length) {
73
+ const arg = argv[index];
74
+ if (arg === "--") {
75
+ index++;
76
+ break;
77
+ }
78
+ if (!arg.startsWith("-") || arg === "-")
79
+ break;
80
+ if (arg.startsWith("--")) {
81
+ const [name, inline] = arg.split("=", 2);
82
+ const value = inline ?? (VALUE_FLAGS.has(name) ? argv[++index] : undefined);
83
+ if (name === "--user" && value)
84
+ user = value;
85
+ index++;
86
+ continue;
87
+ }
88
+ // Clustered short flags: -Au root, -uroot, -nA.
89
+ for (let at = 1; at < arg.length; at++) {
90
+ const flag = arg[at];
91
+ if (!SHORT_VALUE.has(flag))
92
+ continue;
93
+ const value = at + 1 < arg.length ? arg.slice(at + 1) : argv[++index];
94
+ if (flag === "u" && value)
95
+ user = value;
96
+ break;
97
+ }
98
+ index++;
99
+ }
100
+ const rest = argv.slice(index).join(" ").trim();
101
+ const command = (rest || argv.join(" ")).slice(0, 2_000);
102
+ return { command, ...(user ? { user: user.slice(0, 64) } : {}) };
103
+ }
104
+ const exec = promisify(execFile);
105
+ /** One process's parent, effective uid, name and arguments. */
106
+ export async function readProcess(pid) {
107
+ if (!Number.isInteger(pid) || pid <= 1)
108
+ return undefined;
109
+ try {
110
+ const { stdout } = await exec("ps", ["-ww", "-o", "ppid=", "-o", "uid=", "-o", "comm=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
111
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(stdout.trim().split("\n")[0] ?? "");
112
+ if (!match)
113
+ return undefined;
114
+ const args = await exec("ps", ["-ww", "-o", "args=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
115
+ const line = args.stdout.trim();
116
+ const started = (await exec("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 4_096 }).catch(() => ({ stdout: "" }))).stdout.trim();
117
+ let argv = line.split(/\s+/).filter(Boolean), env;
118
+ if (process.platform === "linux") {
119
+ argv = await readFile(`/proc/${pid}/cmdline`, "utf8").then(text => text.split("\0").filter(Boolean)).catch(() => argv);
120
+ env = await readFile(`/proc/${pid}/environ`, "utf8").then(text => text.split("\0").filter(Boolean).map(item => item.split("=", 1)[0])).catch(() => undefined);
121
+ }
122
+ return { ppid: Number(match[1]), euid: Number(match[2]), name: path.basename(match[3]), argv, line, ...(env ? { env } : {}), ...(started ? { started } : {}) };
123
+ }
124
+ catch {
125
+ return undefined;
126
+ }
127
+ }
128
+ /** Whether `pid`'s stdout is a pipe that no process of the owner's other than
129
+ * `allowed` holds. sudo, running as root, is never visible here. */
130
+ export async function stdoutReaders(pid, allowed) {
131
+ try {
132
+ if (process.platform === "linux") {
133
+ const target = await readlink(`/proc/${pid}/fd/1`);
134
+ if (!/^pipe:\[\d+\]$/.test(target))
135
+ return "other";
136
+ for (const entry of await readdir("/proc")) {
137
+ const holder = Number(entry);
138
+ if (!Number.isInteger(holder) || holder === pid || allowed.includes(holder))
139
+ continue;
140
+ const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
141
+ for (const fd of fds)
142
+ if (await readlink(`/proc/${holder}/fd/${fd}`).catch(() => "") === target)
143
+ return "other";
144
+ }
145
+ return "sudo";
146
+ }
147
+ // macOS: each pipe end has its own address, and `n->` names the other end.
148
+ const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });
149
+ const type = /^t(.+)$/m.exec(own.stdout)?.[1], peer = /^n->(0x[0-9a-f]+)$/m.exec(own.stdout)?.[1];
150
+ if (type !== "PIPE" || !peer)
151
+ return "other";
152
+ const all = await exec("lsof", ["-nP", "-u", String(process.getuid?.() ?? ""), "-F", "pd"], { timeout: 10_000, maxBuffer: 64 * 1_048_576 }).catch(error => error);
153
+ let holder = 0;
154
+ for (const row of String(all.stdout ?? "").split("\n")) {
155
+ if (row.startsWith("p"))
156
+ holder = Number(row.slice(1));
157
+ else if (row === `d${peer}` && holder !== pid && !allowed.includes(holder))
158
+ return "other";
159
+ }
160
+ return all.stdout ? "sudo" : "unknown";
161
+ }
162
+ catch {
163
+ return "unknown";
164
+ }
165
+ }
166
+ /** macOS: whether the other end of the Hook's connection `hookFd` is held by
167
+ * `pid` and no other process of the owner's. */
168
+ export async function connectionHolders(pid, hookFd) {
169
+ if (hookFd === undefined)
170
+ return "unknown";
171
+ try {
172
+ const own = await exec("lsof", ["-nP", "-a", "-p", String(process.pid), "-d", String(hookFd), "-F", "d"], { timeout: 5_000, maxBuffer: 65_536 });
173
+ const end = /^d(0x[0-9a-f]+)$/m.exec(own.stdout)?.[1];
174
+ if (!end)
175
+ return "unknown";
176
+ const all = await exec("lsof", ["-nP", "-a", "-U", "-u", String(process.getuid?.() ?? ""), "-F", "pn"], { timeout: 10_000, maxBuffer: 64 * 1_048_576 }).catch(error => error);
177
+ const holders = new Set();
178
+ let holder = 0;
179
+ for (const row of String(all.stdout ?? "").split("\n")) {
180
+ if (row.startsWith("p"))
181
+ holder = Number(row.slice(1));
182
+ else if (row === `n->${end}`)
183
+ holders.add(holder);
184
+ }
185
+ return holders.size === 1 && holders.has(pid) ? "asker" : holders.size ? "other" : "unknown";
186
+ }
187
+ catch {
188
+ return "unknown";
189
+ }
190
+ }
191
+ /** Linux: a process's start time, to tell it from a later one with its pid. */
192
+ export async function processStart(pid) {
193
+ const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch(() => undefined);
194
+ return stat?.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
195
+ }
196
+ /** Linux: the password written into the asker's stdout, the pipe verified to
197
+ * reach sudo alone, if the asker is still the process that was verified. */
198
+ async function writeToAsker(pid, start, password) {
199
+ if (await processStart(pid) !== start)
200
+ return { status: 410, error: "askpass went away." };
201
+ try {
202
+ const out = await open(`/proc/${pid}/fd/1`, "w");
203
+ try {
204
+ await out.write(`${password}\n`);
205
+ }
206
+ finally {
207
+ await out.close();
208
+ }
209
+ return { delivered: true };
210
+ }
211
+ catch {
212
+ return { status: 410, error: "askpass went away." };
213
+ }
214
+ }
215
+ /** What would run other code in the shell script (which drops the rest) or in node. */
216
+ const PRELOADS = ["LD_PRELOAD", "DYLD_INSERT_LIBRARIES"], NODE_LOADERS = [...PRELOADS, "NODE_OPTIONS"];
217
+ /** The chain from askpass up to sudo, or why it is refused. */
218
+ export async function verifyAsker(pid, check) {
219
+ const asker = await check.processes(pid);
220
+ if (!asker)
221
+ return { refused: "phren askpass only answers sudo -A." };
222
+ const script = await check.processes(asker.ppid);
223
+ const sudo = script ? await check.processes(script.ppid) : undefined;
224
+ if (!script || !sudo || sudo.name !== "sudo" || (sudo.euid !== 0 && !check.unprivilegedSudo))
225
+ return { refused: "phren askpass only answers sudo -A." };
226
+ // node <bundle> askpass [prompt]: no flags that could load other code.
227
+ const runs = check.bundles.some(bundle => asker.line === `${check.node} ${bundle} askpass` || asker.line.startsWith(`${check.node} ${bundle} askpass `));
228
+ const scripted = script.line === `/bin/sh ${check.script}` || script.line.startsWith(`/bin/sh ${check.script} `);
229
+ if (!runs || !scripted)
230
+ return { refused: `Only ${check.script} may ask for sudo's password.` };
231
+ if (asker.env?.some(name => NODE_LOADERS.includes(name)) || script.env?.some(name => PRELOADS.includes(name))) {
232
+ return { refused: "askpass refused an environment that loads other code." };
233
+ }
234
+ const readers = await check.stdout(pid, [asker.ppid, script.ppid]);
235
+ if (readers !== "sudo")
236
+ return { refused: readers === "other" ? "askpass's output must go to sudo alone." : "Phren Hook could not check where askpass's output goes." };
237
+ const connection = await check.connection(pid);
238
+ if (connection !== "asker")
239
+ return { refused: connection === "other" ? "Only askpass itself may ask for its password." : "Phren Hook could not check who asked." };
240
+ return { sudo, sudoPid: script.ppid };
241
+ }
242
+ const placeName = /^[A-Za-z0-9_.:%@-]{1,128}$/;
243
+ function placeFrom(value) {
244
+ const item = object(value);
245
+ const fields = ["server", "workspace", "tab", "pane"];
246
+ if (!fields.every(key => typeof item[key] === "string" && placeName.test(item[key])))
247
+ return undefined;
248
+ return Object.fromEntries(fields.map(key => [key, item[key]]));
249
+ }
250
+ /** The chain check against this Hook's own node, bundle and script. */
251
+ async function defaultVerify(pid, hookFd) {
252
+ const linux = process.platform === "linux";
253
+ const running = process.argv[1] ? [path.resolve(process.argv[1])] : [];
254
+ const start = linux ? await processStart(pid) : undefined;
255
+ const result = await verifyAsker(pid, { processes: readProcess, stdout: stdoutReaders, node: process.execPath, script: askpassPath(),
256
+ bundles: [...new Set([path.join(bridgeRoot(), "current/bridge-hook.mjs"), ...running])],
257
+ // On Linux the password goes to the asker's stdout, not this connection.
258
+ connection: linux ? async () => start ? "asker" : "unknown" : asker => connectionHolders(asker, hookFd),
259
+ // The real-Hook tests stand a copy of bash named sudo in for sudo, which cannot run as root.
260
+ unprivilegedSudo: process.env.NODE_ENV === "test" && process.env.PHREN_SUDO_TEST_PARENT === "1" });
261
+ if ("refused" in result)
262
+ return result;
263
+ return { sudo: result.sudo, sudoPid: result.sudoPid, deliver: linux ? password => writeToAsker(pid, start, password) : async (password) => ({ password }) };
264
+ }
265
+ export class SudoBroker {
266
+ options;
267
+ pending = new Map();
268
+ events = new EventEmitter();
269
+ watchers = 0;
270
+ tries = new Map();
271
+ constructor(options) {
272
+ this.options = options;
273
+ this.events.setMaxListeners(64);
274
+ }
275
+ get now() { return this.options.now ?? Date.now; }
276
+ list() { return [...this.pending.values()].map(entry => entry.view); }
277
+ /** Overview sockets that asked for sudo frames. Each counts as a phone
278
+ * that can answer while it is open. */
279
+ subscribe(listener) {
280
+ this.watchers++;
281
+ const handler = () => listener(this.list());
282
+ this.events.on("change", handler);
283
+ let open = true;
284
+ return () => { if (!open)
285
+ return; open = false; this.watchers--; this.events.off("change", handler); };
286
+ }
287
+ changed() { this.events.emit("change"); }
288
+ /** An askpass call: checks the caller, builds the request, holds it until
289
+ * an answer, a timeout, or `cancel` (the caller went away). */
290
+ async ask(body, respond, hookFd) {
291
+ const none = { cancel: () => { } };
292
+ const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd);
293
+ if ("refused" in verified) {
294
+ respond({ status: 400, error: verified.refused });
295
+ return none;
296
+ }
297
+ const sudo = verified.sudo, pushable = this.options.push?.available === true;
298
+ // A second ask from the same sudo means it refused the last password,
299
+ // whether or not this ask can reach the phone.
300
+ const key = `${verified.sudoPid}\n${sudo.started ?? ""}`;
301
+ const tries = this.tries.get(key) ?? { attempts: 0 };
302
+ tries.waiting?.("rejected");
303
+ tries.waiting = undefined;
304
+ tries.attempts++;
305
+ this.tries.delete(key);
306
+ this.tries.set(key, tries);
307
+ while (this.tries.size > 64)
308
+ this.tries.delete(this.tries.keys().next().value);
309
+ if (this.pending.size >= MAX_SUDO_PENDING) {
310
+ respond({ status: 429, error: "Too many sudo requests are waiting for the phone." });
311
+ return none;
312
+ }
313
+ if (this.watchers === 0 && !pushable) {
314
+ respond({ status: 503, error: "No phone can answer sudo right now. Open Phren on your phone, or set up approval push (phren bridge doctor)." });
315
+ return none;
316
+ }
317
+ const place = placeFrom(body.place);
318
+ const dispatch = briefId.safeParse(body.dispatchId).success ? String(body.dispatchId) : undefined;
319
+ const described = place && this.options.describe ? await this.options.describe(place).catch(() => undefined) : undefined;
320
+ const dispatchLabel = dispatch && this.options.label ? await this.options.label(dispatch).catch(() => undefined) : undefined;
321
+ const label = dispatchLabel ?? described?.label;
322
+ const session = place || described || label
323
+ ? { ...(described?.source ? { source: described.source } : {}), ...(label ? { label: label.slice(0, 120) } : {}), ...place } : undefined;
324
+ const cwd = typeof body.cwd === "string" && path.isAbsolute(body.cwd) && body.cwd.length <= 1_024 ? body.cwd : undefined;
325
+ const at = this.now(), hold = this.options.holdMs ?? SUDO_HOLD_MS;
326
+ const account = this.options.account ?? userName();
327
+ const view = { id: randomUUID(), computer: this.options.computer(), ...sudoCommand(sudo.argv), ...(account ? { account } : {}),
328
+ ...(cwd ? { cwd } : {}), ...(session ? { session } : {}),
329
+ askedAt: new Date(at).toISOString(), expiresAt: new Date(at + hold).toISOString() };
330
+ const finish = (reply) => {
331
+ const entry = this.pending.get(view.id);
332
+ if (!entry)
333
+ return;
334
+ clearTimeout(entry.timer);
335
+ this.pending.delete(view.id);
336
+ this.changed();
337
+ void Promise.resolve(reply).catch(() => ({ status: 410, error: "askpass went away." })).then(respond);
338
+ };
339
+ const timer = setTimeout(() => finish({ status: 408, error: "No answer from the phone in time." }), hold);
340
+ this.pending.set(view.id, { view, respond: finish, deliver: verified.deliver, timer,
341
+ sudo: { key, pid: verified.sudoPid, ...(sudo.started ? { started: sudo.started } : {}), attempt: tries.attempts } });
342
+ this.changed();
343
+ if (pushable) {
344
+ void this.options.push.notifySudo(view).catch(() => false).then(delivered => {
345
+ if (!delivered && this.watchers === 0)
346
+ finish({ status: 503, error: "The phone could not be reached for sudo." });
347
+ });
348
+ }
349
+ return { cancel: () => { const entry = this.pending.get(view.id); if (!entry)
350
+ return; clearTimeout(entry.timer); this.pending.delete(view.id); this.changed(); } };
351
+ }
352
+ /** The phone's answer. Single use: the request is gone once answered.
353
+ * `outcome` resolves to whether sudo took the password: rejected when the
354
+ * same sudo asks again, accepted when it has not within `outcomeMs` (or
355
+ * is still running then), unknown when it gave up or the Hook cannot tell. */
356
+ answer(id, answer) {
357
+ const entry = this.pending.get(id);
358
+ if (!entry)
359
+ return false;
360
+ if (!("password" in answer)) {
361
+ entry.respond({ status: 403, error: "Denied on the phone." });
362
+ return { outcome: Promise.resolve(undefined) };
363
+ }
364
+ const delivered = entry.deliver(answer.password);
365
+ entry.respond(delivered);
366
+ return { outcome: delivered.then(reply => "status" in reply ? "unknown" : this.watchOutcome(entry.sudo), () => "unknown") };
367
+ }
368
+ watchOutcome(sudo) {
369
+ const tries = this.tries.get(sudo.key);
370
+ if (!tries)
371
+ return Promise.resolve("unknown");
372
+ return new Promise(resolve => {
373
+ const timer = setTimeout(() => {
374
+ if (tries.waiting !== settle)
375
+ return;
376
+ tries.waiting = undefined;
377
+ void (this.options.processes ?? readProcess)(sudo.pid).then(now => {
378
+ const running = now !== undefined && (sudo.started ? now.started === sudo.started : now.name === "sudo");
379
+ resolve(running || sudo.attempt < SUDO_TRIES ? "accepted" : "unknown");
380
+ }, () => resolve("unknown"));
381
+ }, this.options.outcomeMs ?? SUDO_OUTCOME_MS);
382
+ const settle = (outcome) => { clearTimeout(timer); resolve(outcome); };
383
+ tries.waiting = settle;
384
+ });
385
+ }
386
+ close() {
387
+ for (const entry of [...this.pending.values()])
388
+ entry.respond({ status: 503, error: "Phren Hook stopped." });
389
+ }
390
+ /** The agent.sock `/sudo` route. */
391
+ async handle(req, res) {
392
+ let size = 0;
393
+ const chunks = [];
394
+ for await (const bytes of req) {
395
+ size += bytes.length;
396
+ if (size > 16_384)
397
+ throw new Error("Oversized sudo request");
398
+ chunks.push(bytes);
399
+ }
400
+ const body = object(JSON.parse(Buffer.concat(chunks).toString()));
401
+ let done = false, gone = false, held;
402
+ res.on("close", () => { gone = true; if (!done) {
403
+ done = true;
404
+ held?.cancel();
405
+ } });
406
+ held = await this.ask(body, reply => {
407
+ if (done)
408
+ return;
409
+ done = true;
410
+ if ("status" in reply) {
411
+ res.statusCode = reply.status;
412
+ res.end(JSON.stringify({ error: reply.error }));
413
+ }
414
+ else {
415
+ res.statusCode = 200;
416
+ res.end(JSON.stringify(reply));
417
+ }
418
+ }, req.socket._handle?.fd);
419
+ // The asker left while the request was being built.
420
+ if (gone)
421
+ held.cancel();
422
+ }
423
+ }
424
+ function userName() { try {
425
+ return userInfo().username || undefined;
426
+ }
427
+ catch {
428
+ return undefined;
429
+ } }
430
+ /** A password as sudo reads it from askpass: one line, nothing it would cut. */
431
+ export function sudoAnswer(data) {
432
+ const id = typeof data.id === "string" && /^[0-9a-f-]{36}$/i.test(data.id) ? data.id : undefined;
433
+ if (!id)
434
+ throw new SudoAnswerError();
435
+ if (data.deny !== undefined) {
436
+ if (data.deny === true && data.password === undefined && data.outcome === undefined)
437
+ return { id, answer: { deny: true }, outcome: false };
438
+ throw new SudoAnswerError();
439
+ }
440
+ const password = data.password;
441
+ // Checked by hand: a schema error could echo the value it refused.
442
+ if (typeof password !== "string" || password.length < 1 || password.length > 1_024 || /[\x00\n\r]/.test(password))
443
+ throw new SudoAnswerError();
444
+ if (data.outcome !== undefined && typeof data.outcome !== "boolean")
445
+ throw new SudoAnswerError();
446
+ return { id, answer: { password }, outcome: data.outcome === true };
447
+ }
448
+ export class SudoAnswerError extends Error {
449
+ constructor() { super("Send an id and a password, or deny."); }
450
+ }
451
+ /** The bundle's `askpass` command, run by sudo through `<bridge>/askpass`.
452
+ * Prints the password and exits 0, or explains on stderr and exits 1. */
453
+ export async function askpass(prompt, env = process.env) {
454
+ const place = await terminalPaneFromEnv(env).catch(() => undefined);
455
+ const dispatchId = env.PHREN_DISPATCH_ID && briefId.safeParse(env.PHREN_DISPATCH_ID).success ? env.PHREN_DISPATCH_ID : undefined;
456
+ const data = JSON.stringify({ pid: process.pid, cwd: process.cwd(), ...(prompt ? { prompt: prompt.slice(0, 200) } : {}),
457
+ ...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}) });
458
+ const reply = await new Promise(resolve => {
459
+ const req = request({ socketPath: localSocket(), path: "/sudo", method: "POST", timeout: SUDO_HOLD_MS + 15_000,
460
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
461
+ let text = "";
462
+ res.on("data", chunk => { text += chunk.toString(); if (text.length > 16_384)
463
+ req.destroy(); });
464
+ res.on("end", () => { try {
465
+ resolve({ status: res.statusCode ?? 0, body: object(JSON.parse(text)) });
466
+ }
467
+ catch {
468
+ resolve({ status: 0, body: {} });
469
+ } });
470
+ });
471
+ req.on("timeout", () => req.destroy());
472
+ req.on("error", () => resolve({ status: 0, body: { error: "Phren Hook is not running on this computer (phren bridge status)." } }));
473
+ req.end(data);
474
+ });
475
+ if (reply.status === 200 && typeof reply.body.password === "string") {
476
+ process.stdout.write(`${reply.body.password}\n`);
477
+ return 0;
478
+ }
479
+ // Linux: the Hook already wrote it into this process's stdout.
480
+ if (reply.status === 200 && reply.body.delivered === true)
481
+ return 0;
482
+ process.stderr.write(`phren askpass: ${typeof reply.body.error === "string" ? reply.body.error : "sudo was not approved."}\n`);
483
+ return 1;
484
+ }
485
+ /** `phren sudo <command...>`: `sudo -A` with this Hook's askpass, so the
486
+ * password comes from the phone even with no terminal (a `!` command, an
487
+ * agent's shell). Exits with sudo's status. */
488
+ export async function runSudo(args) {
489
+ if (!args.length || args[0] === "--help" || args[0] === "-h") {
490
+ console.log("Usage: phren sudo <command...>\nRuns sudo -A <command>; Phren asks your phone for the password.");
491
+ return args.length ? 0 : 1;
492
+ }
493
+ if (!askpassInstalled())
494
+ throw new Error("Phren Hook's askpass helper is missing. Run phren bridge install.");
495
+ const { spawn } = await import("node:child_process");
496
+ return new Promise(resolve => {
497
+ const child = spawn("sudo", ["-A", ...args], { stdio: "inherit", env: { ...process.env, SUDO_ASKPASS: askpassPath() } });
498
+ child.on("error", error => { process.stderr.write(`phren sudo: ${error.message}\n`); resolve(127); });
499
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 128 + ({ SIGINT: 2, SIGTERM: 15, SIGKILL: 9, SIGHUP: 1 }[signal] ?? 1) : 1)));
500
+ });
501
+ }
@@ -103,6 +103,18 @@ export declare function tmuxPaneFromEnv(env?: NodeJS.ProcessEnv): Promise<{
103
103
  tab: string;
104
104
  pane: string;
105
105
  } | undefined>;
106
+ /**
107
+ * Scrolls one pane for a phone whose terminal gets no wheel events of its
108
+ * own: a server with `mouse off` (tmux's default) never turns on the phone's
109
+ * mouse reporting, and tmux draws on the alternate screen, so the phone has
110
+ * no local history either. Does what tmux's default WheelUpPane binding does:
111
+ * an app tracking the mouse (Claude, Codex) gets wheel events, and anything
112
+ * else scrolls in `copy-mode -e`, which ends by itself at the bottom.
113
+ * `lines` > 0 is older output; 0 leaves copy mode so typing reaches the pane.
114
+ */
115
+ export declare function tmuxScroll(server: string, pane: string | undefined, lines: number): Promise<{
116
+ history: boolean;
117
+ }>;
106
118
  /** The command that attaches the phone's SSH terminal to a tmux server. */
107
119
  export declare function tmuxAttach(server: string): {
108
120
  file: string;
@@ -18,7 +18,8 @@ import { hostname, userInfo } from "node:os";
18
18
  import path from "node:path";
19
19
  import { BridgeError, objects, serverName } from "./protocol.js";
20
20
  import { harnessStatus } from "./harness-status.js";
21
- import { dialogStatus, notePaneStatus, paneStatus } from "./pane-status.js";
21
+ import { dialogStatus, notePaneStatus, paneStatus, startupStatus } from "./pane-status.js";
22
+ import { plainTitle } from "./session-activity.js";
22
23
  import { herdrPanes } from "./terminal-herdr.js";
23
24
  /** The owner's own tmux server (the default socket). */
24
25
  export const TMUX_DEFAULT = "tmux";
@@ -123,7 +124,9 @@ const defaultDeps = {
123
124
  reject(new BridgeError(503, "tmux is not installed on this computer."));
124
125
  return;
125
126
  }
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
+ // -u: without a UTF-8 locale (launchd and systemd services often have
128
+ // none) tmux 3.7 prints a format's tabs as "_" and no pane parses.
129
+ const child = execFile(binary, ["-u", ...socketFlags(socket), ...args], { timeout: options.timeoutMs ?? 5_000, maxBuffer: 4_194_304, env: tmuxEnvironment(), signal: options.signal }, (error, stdout, stderr) => { if (error)
127
130
  reject(tmuxError(String(stderr), error));
128
131
  else
129
132
  resolve(String(stdout)); });
@@ -251,7 +254,9 @@ async function agentStatus(server, pane, terminal, agent, pids) {
251
254
  }
252
255
  else
253
256
  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 }));
257
+ const read = () => tmuxTerminal.readScreen(server, pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 });
258
+ // Codex runs SessionStart only with its first turn; until then its screen says.
259
+ return await dialogStatus(server, pane, terminal, agent, status, read) ?? startupStatus(server, pane, terminal, agent, read);
255
260
  }
256
261
  const STATUS_RANK = ["blocked", "waiting", "working", "done", "idle"];
257
262
  /** One tmux server in the shape of the Hook's pane snapshot (the shape
@@ -280,7 +285,8 @@ export async function tmuxSnapshot(server) {
280
285
  // others count as idle until their own records say otherwise.
281
286
  const hooked = agent === "claude" || agent === "codex";
282
287
  const name = row["@phren_agent"] || undefined;
283
- const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? row.pane_title : undefined;
288
+ // A harness spins a glyph in front of its title while it works.
289
+ const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? plainTitle(row.pane_title) : undefined;
284
290
  panes.push({ pane_id: pane, tab_id: tab, workspace_id: workspace, terminal_id: terminal, cwd: row.pane_current_path || undefined,
285
291
  foreground_cwd: row.pane_current_path || undefined, title, ...(row["@phren_label"] ? { label: row["@phren_label"] } : {}),
286
292
  ...(agent ? { agent, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
@@ -554,6 +560,75 @@ export async function tmuxPaneFromEnv(env = process.env) {
554
560
  return undefined;
555
561
  }
556
562
  }
563
+ /** The pane of the client that last did anything on `server`: the phone's
564
+ * attach, when it names no pane. */
565
+ async function activeClientPane(server) {
566
+ const rows = (await tmux(server, ["list-clients", "-F", "#{client_activity}\t#{pane_id}"])).split("\n").filter(Boolean).map(row => row.split("\t"));
567
+ const newest = rows.sort((a, b) => Number(b[0]) - Number(a[0]))[0]?.[1];
568
+ if (!newest || !fromTmuxId(newest))
569
+ throw new BridgeError(409, "No terminal is attached to this tmux server.");
570
+ return newest;
571
+ }
572
+ /**
573
+ * Scrolls one pane for a phone whose terminal gets no wheel events of its
574
+ * own: a server with `mouse off` (tmux's default) never turns on the phone's
575
+ * mouse reporting, and tmux draws on the alternate screen, so the phone has
576
+ * no local history either. Does what tmux's default WheelUpPane binding does:
577
+ * an app tracking the mouse (Claude, Codex) gets wheel events, and anything
578
+ * else scrolls in `copy-mode -e`, which ends by itself at the bottom.
579
+ * `lines` > 0 is older output; 0 leaves copy mode so typing reaches the pane.
580
+ */
581
+ export async function tmuxScroll(server, pane, lines) {
582
+ const target = pane ? toTmuxId(pane, "p") : await activeClientPane(server);
583
+ // One scroll per pane at a time: two overlapping swipes could otherwise
584
+ // enter and cancel copy mode out of order and leave the pane in it, where
585
+ // it would swallow the next typed prompt.
586
+ const key = `${server}\0${target}`;
587
+ const run = (scrollQueues.get(key) ?? Promise.resolve()).then(() => scrollPane(server, target, lines), () => scrollPane(server, target, lines));
588
+ const settled = run.catch(() => undefined);
589
+ scrollQueues.set(key, settled);
590
+ void settled.then(() => { if (scrollQueues.get(key) === settled)
591
+ scrollQueues.delete(key); });
592
+ return run;
593
+ }
594
+ const scrollQueues = new Map();
595
+ async function scrollPane(server, target, lines) {
596
+ const state = async () => {
597
+ const [mode, mouse, sgr, width, height] = (await tmux(server, ["display-message", "-p", "-t", target,
598
+ "#{pane_mode}\t#{mouse_any_flag}\t#{mouse_sgr_flag}\t#{pane_width}\t#{pane_height}"])).replace(/\n$/, "").split("\t");
599
+ return { mode, mouse: mouse === "1", sgr: sgr === "1", width: Number(width) || 80, height: Number(height) || 24 };
600
+ };
601
+ const before = await state();
602
+ const copy = before.mode === "copy-mode";
603
+ if (lines === 0) {
604
+ if (copy)
605
+ await tmux(server, ["send-keys", "-t", target, "-X", "cancel"]);
606
+ return { history: false };
607
+ }
608
+ // Another mode (the tree chooser, the clock) is the owner's; leave it.
609
+ if (before.mode && !copy)
610
+ return { history: false };
611
+ if (!copy && before.mouse) {
612
+ // tmux's `send -M`, as raw bytes: a paste without brackets reaches the
613
+ // app as typed input. The pane's middle keeps X10 coordinates ASCII.
614
+ const button = lines > 0 ? 64 : 65;
615
+ const x = Math.min(95, Math.ceil(before.width / 2)), y = Math.min(95, Math.ceil(before.height / 2));
616
+ const event = before.sgr ? `\x1b[<${button};${x};${y}M` : `\x1b[M${String.fromCharCode(32 + button, 32 + x, 32 + y)}`;
617
+ const buffer = `phren-scroll-${process.pid}-${Date.now().toString(36)}`;
618
+ await tmux(server, ["load-buffer", "-b", buffer, "-"], { input: event.repeat(Math.abs(lines)) });
619
+ // Newer tmux shows a paste's control characters as text (ESC as "^[")
620
+ // unless -S, a flag older tmux, which pastes them as they are, refuses.
621
+ const paste = (flags) => tmux(server, ["paste-buffer", ...flags, "-d", "-r", "-b", buffer, "-t", target]);
622
+ await paste(["-S"]).catch(error => /unknown flag|invalid option/i.test(String(error?.message)) ? paste([]) : Promise.reject(error));
623
+ return { history: false };
624
+ }
625
+ if (lines < 0 && !copy)
626
+ return { history: false };
627
+ if (!copy)
628
+ await tmux(server, ["copy-mode", "-e", "-t", target]);
629
+ await tmux(server, ["send-keys", "-t", target, "-X", "-N", String(Math.abs(lines)), lines > 0 ? "scroll-up" : "scroll-down"]);
630
+ return { history: (await state()).mode === "copy-mode" };
631
+ }
557
632
  /** The command that attaches the phone's SSH terminal to a tmux server. */
558
633
  export function tmuxAttach(server) {
559
634
  const binary = deps.binary();
@@ -7,6 +7,10 @@ import type { ChildAgentRelation } from "./transcripts.js";
7
7
  * and a worktree already removed is not offered. */
8
8
  export declare function claudeChildCheckout(file: string): Promise<Pick<ChildAgentRelation, "cwd" | "worktreeName" | "branch">>;
9
9
  export declare function claudeChildAgents(file: string, session: string): Promise<ChildAgentRelation[]>;
10
+ /** How long a background skill's transcript may sit unchanged before it is
11
+ * taken as finished: the parent records no end for it, and a session that
12
+ * exited mid-skill leaves it without a final reply. */
13
+ export declare const CLAUDE_SKILL_QUIET_MS: number;
10
14
  export declare const harnessPreamble: (text: string) => boolean;
11
15
  export declare function unwrapPastedContent(text: string): string;
12
16
  /** A thinking block Claude marks as narration for the person watching: its