@phren/cli 0.3.11 → 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 (182) 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-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -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
+ }
@@ -2,7 +2,7 @@
2
2
  // socket API. It calls herdr.ts's exported `rpc`, the seam the bridge tests
3
3
  // fake, so a test that records Herdr requests sees exactly what it did before
4
4
  // the provider existed.
5
- import { rpc, snapshot } from "./herdr.js";
5
+ import { herdrSocketPath, rpc, snapshot } from "./herdr.js";
6
6
  import { object, objects } from "./protocol.js";
7
7
  const text = (value) => typeof value === "string" && value ? value : undefined;
8
8
  /** A Herdr snapshot's panes in the provider's shape; Herdr's agent report becomes hints. */
@@ -43,14 +43,20 @@ export const herdrTerminal = {
43
43
  else
44
44
  await rpc(server, "agent.prompt", { target: pane, text });
45
45
  },
46
- async create(server, { workspace, label, cwd }) {
47
- await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
46
+ async create(server, { workspace, label, cwd, env }) {
47
+ await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: env ?? {} });
48
48
  },
49
+ // `agent.start` takes no environment; the pane's shell got it at `create`.
49
50
  async startAgent(server, pane, { name, kind, args, timeoutMs }) {
50
51
  // Herdr waits up to `timeout_ms` for the agent to become ready; the socket waits a little longer.
51
52
  await rpc(server, "agent.start", { name, kind, pane_id: pane, timeout_ms: timeoutMs, ...(args.length ? { args } : {}) }, undefined, timeoutMs + 5_000);
52
53
  },
54
+ // What Herdr sets in its own panes (herdrPaneFromEnv reads them back).
55
+ paneEnv(server, { workspace, tab, pane }) {
56
+ return { HERDR_ENV: "1", HERDR_SOCKET_PATH: herdrSocketPath(server), HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane };
57
+ },
53
58
  async focusPane(server, pane) { await rpc(server, "pane.focus", { pane_id: pane }); },
59
+ async renamePane(server, pane, label) { await rpc(server, "pane.rename", { pane_id: pane, label }); },
54
60
  async groupAction(server, operation, { workspace, tab }, label) {
55
61
  await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
56
62
  },
@@ -60,7 +60,7 @@ interface Proc {
60
60
  args: string;
61
61
  }
62
62
  export declare function parseProcesses(text: string): Proc[];
63
- declare const FIELDS: readonly ["session_id", "session_name", "session_attached", "session_activity", "window_id", "window_name", "window_active", "pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title"];
63
+ declare const FIELDS: readonly ["session_id", "session_name", "session_attached", "session_activity", "window_id", "window_name", "window_active", "pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title", "@phren_label"];
64
64
  type Row = Record<(typeof FIELDS)[number], string>;
65
65
  export declare function parsePanes(text: string): Row[];
66
66
  /** One tmux server in the shape of the Hook's pane snapshot (the shape
@@ -74,8 +74,8 @@ export declare function sendKeysCalls(pane: string, keys: string[]): string[][];
74
74
  export declare const tmuxTerminal: TerminalProvider;
75
75
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
76
76
  * servers that answer, and (unless `hidden: false`) the hidden server whenever
77
- * tmux is installed (a launch starts it). `kind` stays "herdr", the phone's name for the Hook's
78
- * session protocol; `terminal` names the multiplexer. */
77
+ * tmux is installed (a launch starts it). An already running hidden server
78
+ * remains discoverable beside Herdr too. `kind` names the actual multiplexer. */
79
79
  export declare function tmuxServers(options?: {
80
80
  hidden?: boolean;
81
81
  }): Promise<Json[]>;
@@ -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;